@brainbox-labs/sdk 0.0.0-stage → 0.23.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.
@@ -0,0 +1,178 @@
1
+ import { RawSchema, ColumnProfile, JsonKeyEntry } from '@brainbox-labs/types';
2
+ export { e as expandDocPatterns, i as inlineText } from '../docs-loader-B2l0cO36.js';
3
+
4
+ type Dialect = 'postgres' | 'mysql' | 'sqlite' | 'duckdb' | 'trino' | 'athena';
5
+ type ProfileMode = 'cardinality' | 'full';
6
+ interface ProfileOptions {
7
+ mode: ProfileMode;
8
+ sampleRows: number;
9
+ /** "tablename.columnname" entries — columns whose profiles are excluded from output. */
10
+ skipColumns: Set<string>;
11
+ }
12
+ /** Minimal database abstraction used by ColumnProfiler. Injectable for testing. */
13
+ interface DbConnection {
14
+ queryRows<T = Record<string, unknown>>(sql: string, params?: unknown[]): Promise<T[]>;
15
+ close(): Promise<void>;
16
+ }
17
+ declare function detectDialect(url: string): Dialect;
18
+ declare function quoteIdentifier(name: string, dialect: Dialect): string;
19
+ /**
20
+ * Detects a structural format hint from a sample of string values.
21
+ * Returns 'free-text' when fewer than 80% of values match any known pattern.
22
+ * Returns undefined only when the sample is empty.
23
+ */
24
+ declare function detectFormatHint(values: string[]): ColumnProfile['formatHint'];
25
+ /**
26
+ * Extracts a flattened key-path summary from sampled JSON values.
27
+ * `occurrence` is expressed as a fraction of `totalDocs` (rowsScanned for the column),
28
+ * matching the RFC definition: "documents-with-this-path / rowsScanned".
29
+ */
30
+ declare function extractJsonShape(jsonValues: unknown[], totalDocs: number): JsonKeyEntry[];
31
+ declare class ColumnProfiler {
32
+ private readonly conn;
33
+ private readonly dialect;
34
+ /** Injected timestamp for determinism in tests. Defaults to new Date(). */
35
+ private readonly now;
36
+ constructor(conn: DbConnection, dialect: Dialect,
37
+ /** Injected timestamp for determinism in tests. Defaults to new Date(). */
38
+ now?: () => string);
39
+ private q;
40
+ /** Returns the qualified table reference (schema-qualified except for SQLite). */
41
+ private tableRef;
42
+ /**
43
+ * Profiles each column in every table of `schema` and returns a new RawSchema
44
+ * with `profile` populated on each non-skipped column.
45
+ */
46
+ profileSchema(schema: RawSchema, opts: ProfileOptions): Promise<RawSchema>;
47
+ private profileTable;
48
+ /**
49
+ * Fetches up to `limit` rows in a deterministic order.
50
+ *
51
+ * When a PK is available, ORDER BY the PK column(s) — fully deterministic.
52
+ * Without a PK, fall back to a dialect-specific physical row identifier:
53
+ * postgres → ctid, sqlite → rowid, duckdb → rowid (system column)
54
+ * mysql → ORDER BY 1 (sort by first projected column, deterministic
55
+ * for stable data but NOT guaranteed across InnoDB page splits;
56
+ * best-effort until a schema-introspection PK is available).
57
+ * trino → ORDER BY 1 (no physical row id; Trino never reports PKs, so
58
+ * this is always the path taken — same best-effort caveat).
59
+ * athena → ORDER BY 1 (same rationale as trino; Athena's engine is
60
+ * Trino-based and reports no physical row id either).
61
+ */
62
+ private fetchSample;
63
+ private profileColumn;
64
+ }
65
+ /** Main entry point: connect, profile, close. */
66
+ declare function connectAndProfile(connectionUrl: string, schema: RawSchema, opts: ProfileOptions): Promise<RawSchema>;
67
+ /** Parses a `--profile-data [mode]` Commander option value into ProfileMode or null. */
68
+ declare function parseProfileMode(value: boolean | string | undefined): ProfileMode | null;
69
+ /** Parses a `--skip-profile-columns table.col,...` string into a Set. */
70
+ declare function parseSkipColumns(raw: string | undefined): Set<string>;
71
+
72
+ type IntrospectionDialect = 'postgres' | 'trino' | 'athena';
73
+ declare const SUPPORTED_INTROSPECTION_DIALECTS: readonly IntrospectionDialect[];
74
+ /**
75
+ * Strict URL-scheme detection — unlike the profiler's detectDialect(), this
76
+ * never falls back to postgres, because misrouting introspection produces a
77
+ * confusing driver error instead of a clear "unsupported" one.
78
+ */
79
+ declare function detectIntrospectionDialect(url: string): IntrospectionDialect | undefined;
80
+ /**
81
+ * Introspects a database schema, routing to the engine's introspector.
82
+ *
83
+ * `dialect` wins when given (callers that already know the engine — e.g.
84
+ * brain.ingest's `postgres` / `trino` / `athena` option keys — must pass it, which also
85
+ * keeps keyword/value Postgres connection strings working). Otherwise the
86
+ * engine is detected from the URL scheme.
87
+ */
88
+ declare function introspectDatabaseSchema(connectionString: string, dialect?: IntrospectionDialect): Promise<RawSchema>;
89
+
90
+ interface TrinoTarget {
91
+ /** http(s) endpoint of the Trino coordinator, e.g. "https://trino.acme.io:443". */
92
+ server: string;
93
+ catalog: string;
94
+ /** When present, introspection is restricted to this schema. */
95
+ schema?: string;
96
+ user: string;
97
+ password?: string;
98
+ }
99
+ /**
100
+ * Parses a Trino connection URL of the form
101
+ *
102
+ * trino://user[:password]@host[:port]/catalog[/schema][?ssl=true|false]
103
+ *
104
+ * TLS is used when the scheme is `trino+https://`, when `?ssl=true` is set, or
105
+ * whenever a password is present (Trino rejects password auth over plain HTTP).
106
+ * `?ssl=false` or a `trino+http://` scheme forces plain HTTP for dev setups.
107
+ * Default port: 443 with TLS, 8080 without.
108
+ *
109
+ * The URL contains credentials — like the Postgres connection string, it must
110
+ * never be logged or sent to BrainBox. Errors thrown here deliberately omit it.
111
+ */
112
+ declare function parseTrinoUrl(url: string): TrinoTarget;
113
+ declare function openTrinoConnection(url: string): Promise<DbConnection>;
114
+ /**
115
+ * Introspects the catalog's information_schema over an open connection.
116
+ * Exported separately so tests can inject a fake DbConnection.
117
+ */
118
+ declare function introspectTrinoSchemaWithConnection(conn: DbConnection, schemaFilter?: string): Promise<RawSchema>;
119
+ declare function introspectTrinoSchema(connectionString: string): Promise<RawSchema>;
120
+
121
+ interface AthenaTarget {
122
+ region: string;
123
+ /** Glue Data Catalog name. Defaults to "AwsDataCatalog". */
124
+ catalog: string;
125
+ /** Athena database — the "schema" level in Trino terms. */
126
+ database: string;
127
+ /** Workgroup to run queries under. Defaults to "primary". */
128
+ workgroup: string;
129
+ /** s3:// location for query results. Omitted when the workgroup enforces its own. */
130
+ outputLocation?: string;
131
+ /** Max time to wait for a query to reach a terminal state, in ms. Defaults to 300 000 (5 min). */
132
+ pollTimeoutMs: number;
133
+ }
134
+ /**
135
+ * Parses an Athena connection URL of the form
136
+ *
137
+ * athena://region/database[?catalog=AwsDataCatalog&workgroup=primary&output=s3://bucket/prefix&pollTimeoutMs=300000]
138
+ *
139
+ * AWS credentials are never part of the URL — they come from the standard AWS
140
+ * SDK credential chain (env vars, shared config/profile, or an IAM role), the
141
+ * same way any other AWS SDK client in this environment would resolve them.
142
+ * `jdbc:awsathena://...` connection strings are a different, unsupported
143
+ * format; convert to the `athena://` form above.
144
+ */
145
+ declare function parseAthenaUrl(url: string): AthenaTarget;
146
+ declare function openAthenaConnection(url: string): Promise<DbConnection>;
147
+ /**
148
+ * Introspects the database's information_schema over an open connection.
149
+ * Exported separately so tests can inject a fake DbConnection.
150
+ */
151
+ declare function introspectAthenaSchemaWithConnection(conn: DbConnection, database: string): Promise<RawSchema>;
152
+ declare function introspectAthenaSchema(connectionString: string): Promise<RawSchema>;
153
+
154
+ /**
155
+ * Returns true for file extensions that require conversion to markdown
156
+ * before staging (PDF, DOCX, HTML).
157
+ */
158
+ declare function needsConversion(filePath: string): boolean;
159
+ /**
160
+ * Converts an HTML string (not a file) to markdown. Exported so callers that
161
+ * already hold HTML in memory — e.g. the `collect web` crawler — reuse the exact
162
+ * same turndown configuration as file conversion instead of adding a converter.
163
+ */
164
+ declare function htmlToMarkdown(html: string): Promise<string>;
165
+ /**
166
+ * Converts a PDF, DOCX, or HTML file to a markdown string.
167
+ * DOCX: mammoth converts to HTML, then turndown converts to markdown.
168
+ * HTML: turndown converts directly to markdown.
169
+ * PDF: pdf-parse extracts plain text (valid markdown).
170
+ */
171
+ declare function convertToMarkdown(filePath: string): Promise<string>;
172
+ /**
173
+ * Returns the staging filename for a converted document.
174
+ * e.g. "report.pdf" → "report.pdf.md", "spec.docx" → "spec.docx.md"
175
+ */
176
+ declare function convertedName(filePath: string): string;
177
+
178
+ export { type AthenaTarget, ColumnProfiler, type DbConnection, type Dialect, type IntrospectionDialect, type ProfileMode, type ProfileOptions, SUPPORTED_INTROSPECTION_DIALECTS, type TrinoTarget, connectAndProfile, convertToMarkdown, convertedName, detectDialect, detectFormatHint, detectIntrospectionDialect, extractJsonShape, htmlToMarkdown, introspectAthenaSchema, introspectAthenaSchemaWithConnection, introspectDatabaseSchema, introspectTrinoSchema, introspectTrinoSchemaWithConnection, needsConversion, openAthenaConnection, openTrinoConnection, parseAthenaUrl, parseProfileMode, parseSkipColumns, parseTrinoUrl, quoteIdentifier };
@@ -0,0 +1,63 @@
1
+ import {
2
+ ColumnProfiler,
3
+ connectAndProfile,
4
+ detectDialect,
5
+ detectFormatHint,
6
+ extractJsonShape,
7
+ parseProfileMode,
8
+ parseSkipColumns,
9
+ quoteIdentifier
10
+ } from "../chunk-VEXUCOXR.js";
11
+ import {
12
+ convertToMarkdown,
13
+ convertedName,
14
+ expandDocPatterns,
15
+ htmlToMarkdown,
16
+ inlineText,
17
+ needsConversion
18
+ } from "../chunk-4J77FNJJ.js";
19
+ import {
20
+ introspectTrinoSchema,
21
+ introspectTrinoSchemaWithConnection,
22
+ openTrinoConnection,
23
+ parseTrinoUrl
24
+ } from "../chunk-43LDD7YT.js";
25
+ import {
26
+ introspectAthenaSchema,
27
+ introspectAthenaSchemaWithConnection,
28
+ openAthenaConnection,
29
+ parseAthenaUrl
30
+ } from "../chunk-YRH35U57.js";
31
+ import {
32
+ SUPPORTED_INTROSPECTION_DIALECTS,
33
+ detectIntrospectionDialect,
34
+ introspectDatabaseSchema
35
+ } from "../chunk-AJR44IFE.js";
36
+ import "../chunk-MLKGABMK.js";
37
+ export {
38
+ ColumnProfiler,
39
+ SUPPORTED_INTROSPECTION_DIALECTS,
40
+ connectAndProfile,
41
+ convertToMarkdown,
42
+ convertedName,
43
+ detectDialect,
44
+ detectFormatHint,
45
+ detectIntrospectionDialect,
46
+ expandDocPatterns,
47
+ extractJsonShape,
48
+ htmlToMarkdown,
49
+ inlineText,
50
+ introspectAthenaSchema,
51
+ introspectAthenaSchemaWithConnection,
52
+ introspectDatabaseSchema,
53
+ introspectTrinoSchema,
54
+ introspectTrinoSchemaWithConnection,
55
+ needsConversion,
56
+ openAthenaConnection,
57
+ openTrinoConnection,
58
+ parseAthenaUrl,
59
+ parseProfileMode,
60
+ parseSkipColumns,
61
+ parseTrinoUrl,
62
+ quoteIdentifier
63
+ };
@@ -0,0 +1,13 @@
1
+ import {
2
+ IngestPartialFailureError,
3
+ lookupIds,
4
+ performIngest,
5
+ resolveIds
6
+ } from "./chunk-XFLBPF4A.js";
7
+ import "./chunk-MLKGABMK.js";
8
+ export {
9
+ IngestPartialFailureError,
10
+ lookupIds,
11
+ performIngest,
12
+ resolveIds
13
+ };
@@ -0,0 +1,11 @@
1
+ import {
2
+ SUPPORTED_INTROSPECTION_DIALECTS,
3
+ detectIntrospectionDialect,
4
+ introspectDatabaseSchema
5
+ } from "./chunk-AJR44IFE.js";
6
+ import "./chunk-MLKGABMK.js";
7
+ export {
8
+ SUPPORTED_INTROSPECTION_DIALECTS,
9
+ detectIntrospectionDialect,
10
+ introspectDatabaseSchema
11
+ };
@@ -0,0 +1,150 @@
1
+ import "./chunk-MLKGABMK.js";
2
+
3
+ // src/ingest/schema-reader.ts
4
+ import pg from "pg";
5
+ var { Client } = pg;
6
+ async function introspectSchema(connectionString) {
7
+ const client = new Client({ connectionString });
8
+ await client.connect();
9
+ try {
10
+ const tablesResult = await client.query(`
11
+ SELECT table_name, table_schema
12
+ FROM information_schema.tables
13
+ WHERE table_schema NOT IN ('pg_catalog', 'information_schema')
14
+ AND table_type = 'BASE TABLE'
15
+ ORDER BY table_name
16
+ `);
17
+ const tables = [];
18
+ for (const tableRow of tablesResult.rows) {
19
+ const tableName = tableRow.table_name;
20
+ const tableSchema = tableRow.table_schema;
21
+ const columnsResult = await client.query(
22
+ `SELECT column_name, data_type, is_nullable, column_default
23
+ FROM information_schema.columns
24
+ WHERE table_schema = $1 AND table_name = $2
25
+ ORDER BY ordinal_position`,
26
+ [tableSchema, tableName]
27
+ );
28
+ const pkResult = await client.query(
29
+ `SELECT kcu.column_name
30
+ FROM information_schema.table_constraints tc
31
+ JOIN information_schema.key_column_usage kcu
32
+ ON tc.constraint_name = kcu.constraint_name
33
+ WHERE tc.constraint_type = 'PRIMARY KEY'
34
+ AND tc.table_schema = $1
35
+ AND tc.table_name = $2`,
36
+ [tableSchema, tableName]
37
+ );
38
+ const primaryKeyColumns = new Set(pkResult.rows.map((r) => r.column_name));
39
+ const fkResult = await client.query(
40
+ `SELECT kcu.column_name, ccu.table_name AS foreign_table_name, ccu.column_name AS foreign_column_name
41
+ FROM information_schema.table_constraints tc
42
+ JOIN information_schema.key_column_usage kcu
43
+ ON tc.constraint_name = kcu.constraint_name
44
+ JOIN information_schema.constraint_column_usage ccu
45
+ ON tc.constraint_name = ccu.constraint_name
46
+ WHERE tc.constraint_type = 'FOREIGN KEY'
47
+ AND tc.table_schema = $1
48
+ AND tc.table_name = $2`,
49
+ [tableSchema, tableName]
50
+ );
51
+ const fkMap = /* @__PURE__ */ new Map();
52
+ for (const fk of fkResult.rows) {
53
+ fkMap.set(fk.column_name, {
54
+ table: fk.foreign_table_name,
55
+ column: fk.foreign_column_name
56
+ });
57
+ }
58
+ const columns = columnsResult.rows.map((col) => {
59
+ const fkRef = fkMap.get(col.column_name);
60
+ const column = {
61
+ name: col.column_name,
62
+ type: col.data_type,
63
+ nullable: col.is_nullable === "YES",
64
+ isPrimaryKey: primaryKeyColumns.has(col.column_name),
65
+ isForeignKey: fkMap.has(col.column_name)
66
+ };
67
+ if (fkRef !== void 0) column.references = fkRef;
68
+ if (col.column_default !== null) column.defaultValue = col.column_default;
69
+ return column;
70
+ });
71
+ const indexResult = await client.query(
72
+ `SELECT i.relname AS index_name, a.attname AS column_name, ix.indisunique AS is_unique
73
+ FROM pg_class t
74
+ JOIN pg_index ix ON t.oid = ix.indrelid
75
+ JOIN pg_class i ON i.oid = ix.indexrelid
76
+ JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey)
77
+ WHERE t.relkind = 'r' AND t.relname = $1
78
+ ORDER BY i.relname`,
79
+ [tableName]
80
+ );
81
+ const indexMap = /* @__PURE__ */ new Map();
82
+ for (const idxRow of indexResult.rows) {
83
+ const existing = indexMap.get(idxRow.index_name);
84
+ if (existing !== void 0) {
85
+ existing.columns.push(idxRow.column_name);
86
+ } else {
87
+ indexMap.set(idxRow.index_name, {
88
+ columns: [idxRow.column_name],
89
+ isUnique: idxRow.is_unique
90
+ });
91
+ }
92
+ }
93
+ const indexes = Array.from(indexMap.entries()).map(([name, val]) => ({
94
+ name,
95
+ columns: val.columns,
96
+ isUnique: val.isUnique
97
+ }));
98
+ const constraintResult = await client.query(
99
+ `SELECT tc.constraint_name, tc.constraint_type, kcu.column_name
100
+ FROM information_schema.table_constraints tc
101
+ JOIN information_schema.key_column_usage kcu
102
+ ON tc.constraint_name = kcu.constraint_name
103
+ WHERE tc.table_schema = $1 AND tc.table_name = $2`,
104
+ [tableSchema, tableName]
105
+ );
106
+ const constraintMap = /* @__PURE__ */ new Map();
107
+ for (const cRow of constraintResult.rows) {
108
+ const existing = constraintMap.get(cRow.constraint_name);
109
+ if (existing !== void 0) {
110
+ existing.columns.push(cRow.column_name);
111
+ } else {
112
+ constraintMap.set(cRow.constraint_name, {
113
+ type: cRow.constraint_type,
114
+ columns: [cRow.column_name]
115
+ });
116
+ }
117
+ }
118
+ const constraints = Array.from(constraintMap.entries()).map(([name, val]) => {
119
+ const type = val.type;
120
+ const constraint = { name, type, columns: val.columns };
121
+ if (type === "FOREIGN KEY") {
122
+ const firstCol = val.columns[0];
123
+ if (firstCol !== void 0) {
124
+ const fkRef = fkMap.get(firstCol);
125
+ if (fkRef !== void 0) {
126
+ constraint.referencedTable = fkRef.table;
127
+ constraint.referencedColumns = [fkRef.column];
128
+ }
129
+ }
130
+ }
131
+ return constraint;
132
+ }).filter(
133
+ (c) => c.type === "PRIMARY KEY" || c.type === "FOREIGN KEY" || c.type === "UNIQUE" || c.type === "CHECK"
134
+ );
135
+ tables.push({
136
+ name: tableName,
137
+ schema: tableSchema,
138
+ columns,
139
+ indexes,
140
+ constraints
141
+ });
142
+ }
143
+ return { tables, extractedAt: (/* @__PURE__ */ new Date()).toISOString() };
144
+ } finally {
145
+ await client.end();
146
+ }
147
+ }
148
+ export {
149
+ introspectSchema
150
+ };
@@ -0,0 +1,2 @@
1
+ export { C as ContextTool, b as CustomExecutor, a as MCP, M as MCPOptions, c as MiddlewareFn, S as SqlClient, d as StartOptions, T as ToolContext, e as ToolHandlerFn } from '../index-qV0gq2eJ.js';
2
+ export { ContextToolExecution, ContextToolInputSchema } from '@brainbox-labs/types';
@@ -0,0 +1,8 @@
1
+ import {
2
+ MCP
3
+ } from "../chunk-MF3BADT7.js";
4
+ import "../chunk-GVWDS5TG.js";
5
+ import "../chunk-MLKGABMK.js";
6
+ export {
7
+ MCP
8
+ };
@@ -0,0 +1,198 @@
1
+ import "./chunk-MLKGABMK.js";
2
+
3
+ // src/ingest/sql-parser.ts
4
+ import { parse } from "pgsql-ast-parser";
5
+ import * as fs from "fs/promises";
6
+ import * as path from "path";
7
+ function extractQueryName(filename, sql) {
8
+ const lines = sql.split("\n");
9
+ for (const line of lines) {
10
+ const trimmed = line.trim();
11
+ if (!trimmed.startsWith("--")) break;
12
+ const nameMatch = trimmed.match(/^--\s*name:\s*(\S+)/i);
13
+ if (nameMatch !== null && nameMatch[1] !== void 0) return nameMatch[1];
14
+ const singleWordMatch = trimmed.match(/^--\s+([A-Za-z][A-Za-z0-9_]+)\s*$/);
15
+ if (singleWordMatch !== null && singleWordMatch[1] !== void 0) return singleWordMatch[1];
16
+ }
17
+ return path.basename(filename, path.extname(filename));
18
+ }
19
+ function extractComments(sql) {
20
+ const comments = [];
21
+ for (const line of sql.split("\n")) {
22
+ const trimmed = line.trim();
23
+ if (trimmed.startsWith("--")) comments.push(trimmed);
24
+ }
25
+ return comments;
26
+ }
27
+ function inferParameterName(sql, position) {
28
+ const paramToken = `$${position}`;
29
+ const pattern = /(\w+)\s*(?:=|>|<|>=|<=|LIKE|ILIKE|!=|<>)\s*\$(\d+)/gi;
30
+ let match;
31
+ while ((match = pattern.exec(sql)) !== null) {
32
+ if (match[2] === String(position)) return match[1] ?? paramToken;
33
+ }
34
+ return paramToken;
35
+ }
36
+ function extractParameters(sql) {
37
+ const paramRegex = /\$(\d+)/g;
38
+ const seen = /* @__PURE__ */ new Set();
39
+ const params = [];
40
+ let match;
41
+ while ((match = paramRegex.exec(sql)) !== null) {
42
+ const pos = parseInt(match[1] ?? "0", 10);
43
+ if (!seen.has(pos)) {
44
+ seen.add(pos);
45
+ params.push({ position: pos, inferredName: inferParameterName(sql, pos) });
46
+ }
47
+ }
48
+ params.sort((a, b) => a.position - b.position);
49
+ return params;
50
+ }
51
+ function collectTablesFromFrom(froms, tables) {
52
+ if (!froms) return;
53
+ for (const from of froms) {
54
+ if (from.type === "table") {
55
+ const ft = from;
56
+ tables.add(ft.name.name.toLowerCase());
57
+ } else if (from.type === "statement") {
58
+ walkStatementForTables(from.statement, tables);
59
+ }
60
+ }
61
+ }
62
+ function walkStatementForTables(stmt, tables) {
63
+ if (stmt.type === "select") {
64
+ const sel = stmt;
65
+ collectTablesFromFrom(sel.from ?? null, tables);
66
+ } else if (stmt.type === "with" || stmt.type === "with recursive") {
67
+ if ("bind" in stmt && Array.isArray(stmt.bind)) {
68
+ for (const binding of stmt.bind) {
69
+ if ("statement" in binding) walkStatementForTables(binding.statement, tables);
70
+ }
71
+ }
72
+ if ("in" in stmt) walkStatementForTables(stmt.in, tables);
73
+ } else if (stmt.type === "union" || stmt.type === "union all") {
74
+ walkStatementForTables(stmt.left, tables);
75
+ walkStatementForTables(stmt.right, tables);
76
+ }
77
+ }
78
+ function collectColumnsFromSelect(columns, selected) {
79
+ if (!columns) return;
80
+ for (const col of columns) {
81
+ const expr = col.expr;
82
+ if (expr && "type" in expr && expr.type === "ref") {
83
+ const ref = expr;
84
+ if (ref.name !== "*") selected.push(ref.name.toLowerCase());
85
+ }
86
+ }
87
+ }
88
+ function collectColumnsFromWhere(where, filtered) {
89
+ if (!where) return;
90
+ if ("type" in where && where.type === "binary") {
91
+ const bin = where;
92
+ if ("type" in bin.left && bin.left.type === "ref") {
93
+ const ref = bin.left;
94
+ if (ref.name !== "*") filtered.push(ref.name.toLowerCase());
95
+ }
96
+ collectColumnsFromWhere(bin.left, filtered);
97
+ collectColumnsFromWhere(bin.right, filtered);
98
+ }
99
+ }
100
+ function formatExprRef(expr) {
101
+ if (!expr || !("type" in expr)) return null;
102
+ if (expr.type === "ref") {
103
+ const ref = expr;
104
+ if (ref.table) return `${ref.table.name}.${ref.name}`;
105
+ return ref.name;
106
+ }
107
+ return null;
108
+ }
109
+ function buildJoinPatterns(froms) {
110
+ if (!froms) return [];
111
+ const patterns = [];
112
+ for (const from of froms) {
113
+ if (from.type === "table") {
114
+ const ft = from;
115
+ if (ft.join) {
116
+ const joinType = ft.join.type;
117
+ const tableName = ft.name.name;
118
+ let onClause = "";
119
+ if (ft.join.on && "type" in ft.join.on && ft.join.on.type === "binary") {
120
+ const bin = ft.join.on;
121
+ const left = formatExprRef(bin.left);
122
+ const right = formatExprRef(bin.right);
123
+ if (left && right) onClause = ` ON ${left} = ${right}`;
124
+ }
125
+ patterns.push(`${joinType} ${tableName}${onClause}`);
126
+ }
127
+ }
128
+ }
129
+ return patterns;
130
+ }
131
+ function parseSqlFile(filename, sql, warnings) {
132
+ const name = extractQueryName(filename, sql);
133
+ const comments = extractComments(sql);
134
+ const parameters = extractParameters(sql);
135
+ const tablesReferenced = [];
136
+ const columnsSelected = [];
137
+ const columnsFiltered = [];
138
+ const joinPatterns = [];
139
+ try {
140
+ const statements = parse(sql);
141
+ for (const stmt of statements) {
142
+ const tableSet = /* @__PURE__ */ new Set();
143
+ walkStatementForTables(stmt, tableSet);
144
+ for (const t of tableSet) {
145
+ if (!tablesReferenced.includes(t)) tablesReferenced.push(t);
146
+ }
147
+ if (stmt.type === "select") {
148
+ const sel = stmt;
149
+ collectColumnsFromSelect(sel.columns ?? null, columnsSelected);
150
+ collectColumnsFromWhere(sel.where ?? null, columnsFiltered);
151
+ joinPatterns.push(...buildJoinPatterns(sel.from ?? null));
152
+ }
153
+ }
154
+ } catch (err) {
155
+ const msg = err instanceof Error ? err.message : String(err);
156
+ warnings?.push(`SQL parse failed for ${filename}: ${msg}`);
157
+ }
158
+ return {
159
+ name,
160
+ filename,
161
+ sql,
162
+ tablesReferenced,
163
+ columnsSelected: [...new Set(columnsSelected)],
164
+ columnsFiltered: [...new Set(columnsFiltered)],
165
+ joinPatterns,
166
+ parameters,
167
+ comments
168
+ };
169
+ }
170
+ async function parseSqlDirectory(dirPath, warnings) {
171
+ const entries = await fs.readdir(dirPath);
172
+ const sqlFiles = entries.filter((f) => f.endsWith(".sql"));
173
+ const results = [];
174
+ for (const file of sqlFiles) {
175
+ const filePath = path.join(dirPath, file);
176
+ const content = await fs.readFile(filePath, "utf-8");
177
+ results.push(parseSqlFile(file, content, warnings));
178
+ }
179
+ return results;
180
+ }
181
+ async function parseSqlInputs(inputs, warnings) {
182
+ const results = [];
183
+ for (const input of inputs) {
184
+ const stat2 = await fs.stat(input);
185
+ if (stat2.isDirectory()) {
186
+ results.push(...await parseSqlDirectory(input, warnings));
187
+ } else {
188
+ const content = await fs.readFile(input, "utf-8");
189
+ results.push(parseSqlFile(input, content, warnings));
190
+ }
191
+ }
192
+ return results;
193
+ }
194
+ export {
195
+ parseSqlDirectory,
196
+ parseSqlFile,
197
+ parseSqlInputs
198
+ };