@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.
- package/README.md +346 -2
- package/dist/athena-R67AV2DO.js +13 -0
- package/dist/bin.d.ts +1 -0
- package/dist/bin.js +57 -0
- package/dist/chunk-43LDD7YT.js +139 -0
- package/dist/chunk-4J77FNJJ.js +192 -0
- package/dist/chunk-AJR44IFE.js +47 -0
- package/dist/chunk-GVWDS5TG.js +112 -0
- package/dist/chunk-MF3BADT7.js +544 -0
- package/dist/chunk-MLKGABMK.js +9 -0
- package/dist/chunk-VEXUCOXR.js +387 -0
- package/dist/chunk-XFLBPF4A.js +169 -0
- package/dist/chunk-YRH35U57.js +178 -0
- package/dist/column-profiler-FJCAQQAS.js +23 -0
- package/dist/docs-loader-B2l0cO36.d.ts +25 -0
- package/dist/docs-loader-VA4KBG6Y.js +11 -0
- package/dist/index-qV0gq2eJ.d.ts +148 -0
- package/dist/index.d.ts +476 -0
- package/dist/index.js +523 -0
- package/dist/ingest/public.d.ts +178 -0
- package/dist/ingest/public.js +63 -0
- package/dist/ingest-DICRS7WW.js +13 -0
- package/dist/introspect-KQOOQEZM.js +11 -0
- package/dist/schema-reader-4ZVTUZIX.js +150 -0
- package/dist/serve/index.d.ts +2 -0
- package/dist/serve/index.js +8 -0
- package/dist/sql-parser-TB26PFXS.js +198 -0
- package/dist/sync-MXG4WALD.js +260 -0
- package/dist/trino-TUQ7CIRM.js +13 -0
- package/package.json +79 -4
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
// src/ingest/column-profiler.ts
|
|
2
|
+
import { ENUM_THRESHOLD } from "@brainbox-labs/types";
|
|
3
|
+
function detectDialect(url) {
|
|
4
|
+
const lower = url.toLowerCase();
|
|
5
|
+
if (lower.startsWith("postgres://") || lower.startsWith("postgresql://")) return "postgres";
|
|
6
|
+
if (lower.startsWith("mysql://") || lower.startsWith("mysql2://")) return "mysql";
|
|
7
|
+
if (lower.startsWith("sqlite:") || lower.endsWith(".db") || lower.endsWith(".sqlite")) return "sqlite";
|
|
8
|
+
if (lower.startsWith("duckdb:") || lower.startsWith("md:") || lower.endsWith(".duckdb")) return "duckdb";
|
|
9
|
+
if (lower.startsWith("trino://") || lower.startsWith("trino+http")) return "trino";
|
|
10
|
+
if (lower.startsWith("athena://") || lower.startsWith("awsathena://")) return "athena";
|
|
11
|
+
return "postgres";
|
|
12
|
+
}
|
|
13
|
+
function quoteIdentifier(name, dialect) {
|
|
14
|
+
if (dialect === "mysql") return `\`${name.replace(/`/g, "``")}\``;
|
|
15
|
+
return `"${name.replace(/"/g, '""')}"`;
|
|
16
|
+
}
|
|
17
|
+
function isNumericOrDate(type) {
|
|
18
|
+
const t = type.toLowerCase();
|
|
19
|
+
return /\b(int|integer|bigint|smallint|tinyint|float|double|real|numeric|decimal|number)\b/.test(t) || /\b(date|time|timestamp|datetime)\b/.test(t);
|
|
20
|
+
}
|
|
21
|
+
function isStringType(type) {
|
|
22
|
+
const t = type.toLowerCase();
|
|
23
|
+
return /\b(char|varchar|text|string|nchar|nvarchar|clob|mediumtext|longtext|tinytext)\b/.test(t);
|
|
24
|
+
}
|
|
25
|
+
function isJsonType(type) {
|
|
26
|
+
const t = type.toLowerCase();
|
|
27
|
+
return t === "json" || t === "jsonb";
|
|
28
|
+
}
|
|
29
|
+
function sortedPercentile(sortedNums, p) {
|
|
30
|
+
if (sortedNums.length === 0) return void 0;
|
|
31
|
+
const idx = Math.min(Math.floor(sortedNums.length * p), sortedNums.length - 1);
|
|
32
|
+
return sortedNums[idx];
|
|
33
|
+
}
|
|
34
|
+
function detectFormatHint(values) {
|
|
35
|
+
const sample = values.filter((v) => v.length > 0).slice(0, 200);
|
|
36
|
+
if (sample.length === 0) return void 0;
|
|
37
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
38
|
+
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
|
|
39
|
+
const URL_RE = /^https?:\/\//i;
|
|
40
|
+
const ISO_DT_RE = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/;
|
|
41
|
+
const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
42
|
+
const PHONE_RE = /^\+?[\d\s\-().]{7,15}$/;
|
|
43
|
+
const IPV4_RE = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
|
|
44
|
+
const threshold = sample.length * 0.8;
|
|
45
|
+
const checks = [
|
|
46
|
+
[UUID_RE, "uuid"],
|
|
47
|
+
[EMAIL_RE, "email"],
|
|
48
|
+
[URL_RE, "url"],
|
|
49
|
+
[ISO_DT_RE, "iso-datetime"],
|
|
50
|
+
[ISO_DATE_RE, "iso-date"],
|
|
51
|
+
[PHONE_RE, "phone"],
|
|
52
|
+
[IPV4_RE, "ipv4"]
|
|
53
|
+
];
|
|
54
|
+
for (const [re, hint] of checks) {
|
|
55
|
+
if (sample.filter((v) => re.test(v)).length >= threshold) return hint;
|
|
56
|
+
}
|
|
57
|
+
return "free-text";
|
|
58
|
+
}
|
|
59
|
+
function jsonTypeOf(v) {
|
|
60
|
+
if (v === null) return "null";
|
|
61
|
+
if (Array.isArray(v)) return "array";
|
|
62
|
+
switch (typeof v) {
|
|
63
|
+
case "string":
|
|
64
|
+
return "string";
|
|
65
|
+
case "number":
|
|
66
|
+
return "number";
|
|
67
|
+
case "boolean":
|
|
68
|
+
return "boolean";
|
|
69
|
+
case "object":
|
|
70
|
+
return "object";
|
|
71
|
+
default:
|
|
72
|
+
return "string";
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
function collectPaths(value, prefix, acc) {
|
|
76
|
+
if (Array.isArray(value)) {
|
|
77
|
+
const key = prefix ? `${prefix}[]` : "[]";
|
|
78
|
+
const entry = acc.get(key) ?? { types: /* @__PURE__ */ new Set(), count: 0 };
|
|
79
|
+
entry.types.add("array");
|
|
80
|
+
entry.count++;
|
|
81
|
+
acc.set(key, entry);
|
|
82
|
+
for (const item of value.slice(0, 5)) {
|
|
83
|
+
collectPaths(item, key, acc);
|
|
84
|
+
}
|
|
85
|
+
} else if (value !== null && typeof value === "object") {
|
|
86
|
+
for (const [k, v] of Object.entries(value)) {
|
|
87
|
+
const key = prefix ? `${prefix}.${k}` : k;
|
|
88
|
+
const entry = acc.get(key) ?? { types: /* @__PURE__ */ new Set(), count: 0 };
|
|
89
|
+
entry.types.add(jsonTypeOf(v));
|
|
90
|
+
entry.count++;
|
|
91
|
+
acc.set(key, entry);
|
|
92
|
+
if (v !== null && typeof v === "object") {
|
|
93
|
+
collectPaths(v, key, acc);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
function extractJsonShape(jsonValues, totalDocs) {
|
|
99
|
+
if (totalDocs === 0) return [];
|
|
100
|
+
const acc = /* @__PURE__ */ new Map();
|
|
101
|
+
for (const raw of jsonValues) {
|
|
102
|
+
let obj;
|
|
103
|
+
if (typeof raw === "string") {
|
|
104
|
+
try {
|
|
105
|
+
obj = JSON.parse(raw);
|
|
106
|
+
} catch {
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
} else {
|
|
110
|
+
obj = raw;
|
|
111
|
+
}
|
|
112
|
+
if (obj !== null && typeof obj === "object") {
|
|
113
|
+
collectPaths(obj, "", acc);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
if (acc.size === 0) return [];
|
|
117
|
+
return Array.from(acc.entries()).map(([path, { types, count }]) => ({
|
|
118
|
+
path,
|
|
119
|
+
types: Array.from(types),
|
|
120
|
+
occurrence: count / totalDocs
|
|
121
|
+
})).sort((a, b) => b.occurrence - a.occurrence).slice(0, 50);
|
|
122
|
+
}
|
|
123
|
+
var ColumnProfiler = class {
|
|
124
|
+
constructor(conn, dialect, now = () => (/* @__PURE__ */ new Date()).toISOString()) {
|
|
125
|
+
this.conn = conn;
|
|
126
|
+
this.dialect = dialect;
|
|
127
|
+
this.now = now;
|
|
128
|
+
}
|
|
129
|
+
conn;
|
|
130
|
+
dialect;
|
|
131
|
+
now;
|
|
132
|
+
q(name) {
|
|
133
|
+
return quoteIdentifier(name, this.dialect);
|
|
134
|
+
}
|
|
135
|
+
/** Returns the qualified table reference (schema-qualified except for SQLite). */
|
|
136
|
+
tableRef(schema, table) {
|
|
137
|
+
if (this.dialect === "sqlite") return this.q(table);
|
|
138
|
+
return `${this.q(schema)}.${this.q(table)}`;
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Profiles each column in every table of `schema` and returns a new RawSchema
|
|
142
|
+
* with `profile` populated on each non-skipped column.
|
|
143
|
+
*/
|
|
144
|
+
async profileSchema(schema, opts) {
|
|
145
|
+
const tables = [];
|
|
146
|
+
for (const table of schema.tables) {
|
|
147
|
+
tables.push(await this.profileTable(table, opts));
|
|
148
|
+
}
|
|
149
|
+
return { ...schema, tables };
|
|
150
|
+
}
|
|
151
|
+
async profileTable(table, opts) {
|
|
152
|
+
const pkCols = table.columns.filter((c) => c.isPrimaryKey).map((c) => c.name);
|
|
153
|
+
const sampleRows = await this.fetchSample(table.name, table.schema, pkCols, opts.sampleRows);
|
|
154
|
+
const columns = [];
|
|
155
|
+
for (const col of table.columns) {
|
|
156
|
+
columns.push(await this.profileColumn(table, col, sampleRows, opts));
|
|
157
|
+
}
|
|
158
|
+
return { ...table, columns };
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Fetches up to `limit` rows in a deterministic order.
|
|
162
|
+
*
|
|
163
|
+
* When a PK is available, ORDER BY the PK column(s) — fully deterministic.
|
|
164
|
+
* Without a PK, fall back to a dialect-specific physical row identifier:
|
|
165
|
+
* postgres → ctid, sqlite → rowid, duckdb → rowid (system column)
|
|
166
|
+
* mysql → ORDER BY 1 (sort by first projected column, deterministic
|
|
167
|
+
* for stable data but NOT guaranteed across InnoDB page splits;
|
|
168
|
+
* best-effort until a schema-introspection PK is available).
|
|
169
|
+
* trino → ORDER BY 1 (no physical row id; Trino never reports PKs, so
|
|
170
|
+
* this is always the path taken — same best-effort caveat).
|
|
171
|
+
* athena → ORDER BY 1 (same rationale as trino; Athena's engine is
|
|
172
|
+
* Trino-based and reports no physical row id either).
|
|
173
|
+
*/
|
|
174
|
+
async fetchSample(tableName, tableSchema, pkCols, limit) {
|
|
175
|
+
const ref = this.tableRef(tableSchema, tableName);
|
|
176
|
+
let orderBy;
|
|
177
|
+
if (pkCols.length > 0) {
|
|
178
|
+
orderBy = `ORDER BY ${pkCols.map((c) => this.q(c)).join(", ")}`;
|
|
179
|
+
} else {
|
|
180
|
+
switch (this.dialect) {
|
|
181
|
+
case "postgres":
|
|
182
|
+
orderBy = "ORDER BY ctid";
|
|
183
|
+
break;
|
|
184
|
+
case "sqlite":
|
|
185
|
+
orderBy = "ORDER BY rowid";
|
|
186
|
+
break;
|
|
187
|
+
case "duckdb":
|
|
188
|
+
orderBy = "ORDER BY rowid";
|
|
189
|
+
break;
|
|
190
|
+
case "mysql":
|
|
191
|
+
orderBy = "ORDER BY 1";
|
|
192
|
+
break;
|
|
193
|
+
case "trino":
|
|
194
|
+
orderBy = "ORDER BY 1";
|
|
195
|
+
break;
|
|
196
|
+
case "athena":
|
|
197
|
+
orderBy = "ORDER BY 1";
|
|
198
|
+
break;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
const sql = `SELECT * FROM ${ref} ${orderBy} LIMIT ${limit}`;
|
|
202
|
+
try {
|
|
203
|
+
return await this.conn.queryRows(sql);
|
|
204
|
+
} catch {
|
|
205
|
+
return [];
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
async profileColumn(table, column, sampleRows, opts) {
|
|
209
|
+
const skipKey = `${table.name}.${column.name}`;
|
|
210
|
+
if (opts.skipColumns.has(skipKey)) {
|
|
211
|
+
const { profile: _drop, ...rest } = column;
|
|
212
|
+
return rest;
|
|
213
|
+
}
|
|
214
|
+
const ref = this.tableRef(table.schema, table.name);
|
|
215
|
+
const colQ = this.q(column.name);
|
|
216
|
+
let rowsScanned = sampleRows.length;
|
|
217
|
+
let distinctCount;
|
|
218
|
+
let nullRate;
|
|
219
|
+
try {
|
|
220
|
+
const sql = `SELECT COUNT(*) AS total_rows, COUNT(DISTINCT ${colQ}) AS distinct_count, SUM(CASE WHEN ${colQ} IS NULL THEN 1 ELSE 0 END) AS null_count FROM ${ref}`;
|
|
221
|
+
const rows = await this.conn.queryRows(sql);
|
|
222
|
+
const r = rows[0];
|
|
223
|
+
if (r !== void 0) {
|
|
224
|
+
const total = Number(r.total_rows);
|
|
225
|
+
rowsScanned = total;
|
|
226
|
+
distinctCount = Number(r.distinct_count);
|
|
227
|
+
nullRate = total > 0 ? Number(r.null_count) / total : 0;
|
|
228
|
+
}
|
|
229
|
+
} catch {
|
|
230
|
+
}
|
|
231
|
+
const profile = {
|
|
232
|
+
rowsScanned,
|
|
233
|
+
profiledAt: this.now(),
|
|
234
|
+
...distinctCount !== void 0 ? { distinctCount } : {},
|
|
235
|
+
...nullRate !== void 0 ? { nullRate } : {}
|
|
236
|
+
};
|
|
237
|
+
if (isNumericOrDate(column.type)) {
|
|
238
|
+
try {
|
|
239
|
+
const rows = await this.conn.queryRows(
|
|
240
|
+
`SELECT MIN(${colQ}) AS min_val, MAX(${colQ}) AS max_val FROM ${ref}`
|
|
241
|
+
);
|
|
242
|
+
const r = rows[0];
|
|
243
|
+
if (r !== void 0) {
|
|
244
|
+
if (r.min_val !== null && r.min_val !== void 0) profile.min = String(r.min_val);
|
|
245
|
+
if (r.max_val !== null && r.max_val !== void 0) profile.max = String(r.max_val);
|
|
246
|
+
}
|
|
247
|
+
} catch {
|
|
248
|
+
}
|
|
249
|
+
const nums = sampleRows.map((r) => r[column.name]).filter((v) => v !== null && v !== void 0).map((v) => Number(v)).filter((v) => !isNaN(v)).sort((a, b) => a - b);
|
|
250
|
+
if (nums.length > 0) {
|
|
251
|
+
const p50 = sortedPercentile(nums, 0.5);
|
|
252
|
+
const p95 = sortedPercentile(nums, 0.95);
|
|
253
|
+
if (p50 !== void 0) profile.p50 = String(p50);
|
|
254
|
+
if (p95 !== void 0) profile.p95 = String(p95);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
if (isStringType(column.type)) {
|
|
258
|
+
const strs = sampleRows.map((r) => r[column.name]).filter((v) => typeof v === "string");
|
|
259
|
+
if (strs.length > 0) {
|
|
260
|
+
profile.avgLength = strs.reduce((sum, s) => sum + s.length, 0) / strs.length;
|
|
261
|
+
const hint = detectFormatHint(strs);
|
|
262
|
+
if (hint !== void 0) profile.formatHint = hint;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
if (opts.mode === "full" && distinctCount !== void 0 && distinctCount <= ENUM_THRESHOLD) {
|
|
266
|
+
try {
|
|
267
|
+
const rows = await this.conn.queryRows(
|
|
268
|
+
`SELECT DISTINCT ${colQ} AS val FROM ${ref} WHERE ${colQ} IS NOT NULL ORDER BY ${colQ} LIMIT ${ENUM_THRESHOLD + 1}`
|
|
269
|
+
);
|
|
270
|
+
if (rows.length <= ENUM_THRESHOLD) {
|
|
271
|
+
profile.enumValues = rows.map((r) => String(r.val));
|
|
272
|
+
}
|
|
273
|
+
} catch {
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
if (opts.mode === "full" && isJsonType(column.type)) {
|
|
277
|
+
const jsonVals = sampleRows.map((r) => r[column.name]).filter((v) => v !== null && v !== void 0);
|
|
278
|
+
if (jsonVals.length > 0) {
|
|
279
|
+
const shape = extractJsonShape(jsonVals, rowsScanned);
|
|
280
|
+
if (shape.length > 0) profile.jsonShape = shape;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
return { ...column, profile };
|
|
284
|
+
}
|
|
285
|
+
};
|
|
286
|
+
async function openPostgresConnection(url) {
|
|
287
|
+
const pg = await import("pg");
|
|
288
|
+
const PgClient = pg.default.Client;
|
|
289
|
+
const client = new PgClient({ connectionString: url });
|
|
290
|
+
await client.connect();
|
|
291
|
+
return {
|
|
292
|
+
queryRows: async (sql) => {
|
|
293
|
+
const result = await client.query(sql);
|
|
294
|
+
return result.rows;
|
|
295
|
+
},
|
|
296
|
+
close: () => client.end()
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
async function openMysqlConnection(url) {
|
|
300
|
+
const mysql = await import("mysql2/promise");
|
|
301
|
+
const conn = await mysql.createConnection(url);
|
|
302
|
+
return {
|
|
303
|
+
queryRows: async (sql) => {
|
|
304
|
+
const [rows] = await conn.execute(sql);
|
|
305
|
+
return rows;
|
|
306
|
+
},
|
|
307
|
+
close: () => conn.end()
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
async function openSqliteConnection(url) {
|
|
311
|
+
const mod = await import("better-sqlite3");
|
|
312
|
+
const Database = mod.default;
|
|
313
|
+
const dbPath = url.replace(/^sqlite:\/\/\//, "/").replace(/^sqlite:/, "");
|
|
314
|
+
const db = new Database(dbPath, { readonly: true });
|
|
315
|
+
return {
|
|
316
|
+
queryRows: async (sql) => db.prepare(sql).all(),
|
|
317
|
+
close: async () => {
|
|
318
|
+
db.close();
|
|
319
|
+
}
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
async function openDuckDBConnection(url) {
|
|
323
|
+
const duckdb = await import("@duckdb/node-api");
|
|
324
|
+
const dbPath = url.startsWith("md:") ? url : url.replace(/^duckdb:\/\/\//, "/").replace(/^duckdb:/, "");
|
|
325
|
+
const instance = await duckdb.DuckDBInstance.create(dbPath);
|
|
326
|
+
const connection = await instance.connect();
|
|
327
|
+
return {
|
|
328
|
+
queryRows: async (sql) => {
|
|
329
|
+
const reader = await connection.runAndReadAll(sql);
|
|
330
|
+
return reader.getRowObjectsJson();
|
|
331
|
+
},
|
|
332
|
+
close: async () => {
|
|
333
|
+
connection.closeSync();
|
|
334
|
+
}
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
async function openConnection(url, dialect) {
|
|
338
|
+
switch (dialect) {
|
|
339
|
+
case "postgres":
|
|
340
|
+
return openPostgresConnection(url);
|
|
341
|
+
case "mysql":
|
|
342
|
+
return openMysqlConnection(url);
|
|
343
|
+
case "sqlite":
|
|
344
|
+
return openSqliteConnection(url);
|
|
345
|
+
case "duckdb":
|
|
346
|
+
return openDuckDBConnection(url);
|
|
347
|
+
case "trino": {
|
|
348
|
+
const { openTrinoConnection } = await import("./trino-TUQ7CIRM.js");
|
|
349
|
+
return openTrinoConnection(url);
|
|
350
|
+
}
|
|
351
|
+
case "athena": {
|
|
352
|
+
const { openAthenaConnection } = await import("./athena-R67AV2DO.js");
|
|
353
|
+
return openAthenaConnection(url);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
async function connectAndProfile(connectionUrl, schema, opts) {
|
|
358
|
+
const dialect = detectDialect(connectionUrl);
|
|
359
|
+
const conn = await openConnection(connectionUrl, dialect);
|
|
360
|
+
try {
|
|
361
|
+
const profiler = new ColumnProfiler(conn, dialect);
|
|
362
|
+
return await profiler.profileSchema(schema, opts);
|
|
363
|
+
} finally {
|
|
364
|
+
await conn.close();
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
function parseProfileMode(value) {
|
|
368
|
+
if (!value) return null;
|
|
369
|
+
if (value === "full") return "full";
|
|
370
|
+
return "cardinality";
|
|
371
|
+
}
|
|
372
|
+
function parseSkipColumns(raw) {
|
|
373
|
+
if (!raw) return /* @__PURE__ */ new Set();
|
|
374
|
+
return new Set(raw.split(",").map((s) => s.trim()).filter(Boolean));
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
export {
|
|
378
|
+
detectDialect,
|
|
379
|
+
quoteIdentifier,
|
|
380
|
+
detectFormatHint,
|
|
381
|
+
extractJsonShape,
|
|
382
|
+
ColumnProfiler,
|
|
383
|
+
openConnection,
|
|
384
|
+
connectAndProfile,
|
|
385
|
+
parseProfileMode,
|
|
386
|
+
parseSkipColumns
|
|
387
|
+
};
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
// src/ingest/index.ts
|
|
2
|
+
import { BrainBoxApiClient } from "@brainbox-labs/api";
|
|
3
|
+
var IngestPartialFailureError = class extends Error {
|
|
4
|
+
completed;
|
|
5
|
+
failedKind;
|
|
6
|
+
cause;
|
|
7
|
+
constructor(failedKind, completed, cause) {
|
|
8
|
+
const summary = completed.length === 0 ? "no stages completed" : `${completed.length} stage(s) already activated: ${completed.map((s) => s.kind).join(", ")}`;
|
|
9
|
+
const causeMsg = cause instanceof Error ? cause.message : String(cause);
|
|
10
|
+
super(`[BrainBox] brain.ingest ${failedKind} stage failed (${summary}): ${causeMsg}`);
|
|
11
|
+
this.name = "IngestPartialFailureError";
|
|
12
|
+
this.completed = completed;
|
|
13
|
+
this.failedKind = failedKind;
|
|
14
|
+
this.cause = cause;
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
var noopLogger = {
|
|
18
|
+
isVerbose: false,
|
|
19
|
+
debug: () => {
|
|
20
|
+
},
|
|
21
|
+
info: () => {
|
|
22
|
+
},
|
|
23
|
+
warn: () => {
|
|
24
|
+
},
|
|
25
|
+
error: () => {
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
var CUID2_RE = /^[a-z][a-z0-9]{23}$/;
|
|
29
|
+
async function runStage(api, orgId, projectId, kind, connectorDraftId, timeoutMs, reviewOnly, warnings, force) {
|
|
30
|
+
const ctx = await api.createContext(orgId, projectId, { connectorDraftId, modelVersion: "v2", ...force && { force } });
|
|
31
|
+
const contextId = ctx.contextId;
|
|
32
|
+
const ready = await api.pollContextUntilReady(orgId, projectId, contextId, 3e3, timeoutMs);
|
|
33
|
+
const baseResult = { kind, connectorDraftId, contextId };
|
|
34
|
+
if (warnings.length > 0) baseResult.warnings = warnings;
|
|
35
|
+
if (reviewOnly || ready.status === "active") {
|
|
36
|
+
if (ready.status === "active") {
|
|
37
|
+
const v = ready.version;
|
|
38
|
+
if (v !== void 0) baseResult.version = v;
|
|
39
|
+
}
|
|
40
|
+
return baseResult;
|
|
41
|
+
}
|
|
42
|
+
const activated = await api.activateContext(orgId, projectId, contextId);
|
|
43
|
+
return { ...baseResult, version: activated.version, layerId: activated.id };
|
|
44
|
+
}
|
|
45
|
+
async function resolveIds(api, ctx) {
|
|
46
|
+
const org = await api.getOrCreateOrg(ctx.org);
|
|
47
|
+
if (CUID2_RE.test(ctx.project)) {
|
|
48
|
+
return { orgId: org.id, projectId: ctx.project };
|
|
49
|
+
}
|
|
50
|
+
const project = await api.getOrCreateProject(org.id, ctx.project);
|
|
51
|
+
return { orgId: org.id, projectId: project.id };
|
|
52
|
+
}
|
|
53
|
+
async function lookupIds(api, ctx) {
|
|
54
|
+
const org = await api.getOrg(ctx.org);
|
|
55
|
+
if (CUID2_RE.test(ctx.project)) return { orgId: org.id, projectId: ctx.project };
|
|
56
|
+
const project = (await api.listProjects(org.id)).find((p) => p.name === ctx.project);
|
|
57
|
+
return { orgId: org.id, projectId: project?.id };
|
|
58
|
+
}
|
|
59
|
+
async function performIngest(ctx, opts, ids) {
|
|
60
|
+
if (!opts.postgres && !opts.trino && !opts.athena && !opts.sql && !opts.docs && !opts.text && !opts.skill) {
|
|
61
|
+
throw new Error(
|
|
62
|
+
"[BrainBox] brain.ingest requires at least one source: postgres, trino, athena, sql, docs, text, or skill."
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
if ([opts.postgres, opts.trino, opts.athena].filter((s) => s !== void 0).length > 1) {
|
|
66
|
+
throw new Error(
|
|
67
|
+
"[BrainBox] brain.ingest accepts only one of `postgres`, `trino`, or `athena` \u2014 run separate ingests per database."
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
if (opts.sql && opts.sql.length > 0 && !opts.postgres && !opts.trino && !opts.athena) {
|
|
71
|
+
throw new Error(
|
|
72
|
+
"[BrainBox] brain.ingest `sql` requires `postgres`, `trino`, or `athena` \u2014 SQL files are submitted alongside a schema."
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
const [{ introspectDatabaseSchema }, { parseSqlInputs }, { expandDocPatterns, inlineText }, { connectAndProfile }] = await Promise.all([
|
|
76
|
+
import("./introspect-KQOOQEZM.js"),
|
|
77
|
+
import("./sql-parser-TB26PFXS.js"),
|
|
78
|
+
import("./docs-loader-VA4KBG6Y.js"),
|
|
79
|
+
import("./column-profiler-FJCAQQAS.js")
|
|
80
|
+
]);
|
|
81
|
+
const api = new BrainBoxApiClient(ctx.apiUrl, ctx.apiKey, noopLogger);
|
|
82
|
+
const { orgId, projectId } = ids ?? await resolveIds(api, ctx);
|
|
83
|
+
const timeoutMs = opts.timeoutMs ?? 3e5;
|
|
84
|
+
const reviewOnly = opts.reviewOnly ?? false;
|
|
85
|
+
const force = opts.force ?? false;
|
|
86
|
+
const dryRun = opts.dryRun ?? false;
|
|
87
|
+
const stages = [];
|
|
88
|
+
const runOrFail = async (kind, fn) => {
|
|
89
|
+
try {
|
|
90
|
+
stages.push(await fn());
|
|
91
|
+
} catch (err) {
|
|
92
|
+
if (stages.length > 0) throw new IngestPartialFailureError(kind, stages, err);
|
|
93
|
+
throw err;
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
const dbKind = opts.postgres ? "postgres" : opts.trino ? "trino" : opts.athena ? "athena" : void 0;
|
|
97
|
+
const db = opts.postgres ?? opts.trino ?? opts.athena;
|
|
98
|
+
if (db !== void 0 || opts.sql) {
|
|
99
|
+
await runOrFail("sql", async () => {
|
|
100
|
+
let schema;
|
|
101
|
+
if (db !== void 0) {
|
|
102
|
+
schema = await introspectDatabaseSchema(db.connectionString, dbKind);
|
|
103
|
+
if (db.tables !== void 0) {
|
|
104
|
+
const allowed = new Set(db.tables);
|
|
105
|
+
schema.tables = schema.tables.filter((t) => allowed.has(t.name));
|
|
106
|
+
}
|
|
107
|
+
if (opts.profile) {
|
|
108
|
+
const skipColumns = new Set((opts.profile.skipColumns ?? []).map((s) => s.trim()));
|
|
109
|
+
const sampleRows = opts.profile.sampleRows ?? 1e4;
|
|
110
|
+
schema = await connectAndProfile(db.connectionString, schema, {
|
|
111
|
+
mode: opts.profile.mode,
|
|
112
|
+
sampleRows,
|
|
113
|
+
skipColumns
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
const stageWarnings = [];
|
|
118
|
+
let queries = [];
|
|
119
|
+
if (opts.sql && opts.sql.length > 0) {
|
|
120
|
+
queries = await parseSqlInputs(opts.sql, stageWarnings);
|
|
121
|
+
}
|
|
122
|
+
if (!schema) {
|
|
123
|
+
throw new Error("[BrainBox] brain.ingest: missing schema for SQL stage.");
|
|
124
|
+
}
|
|
125
|
+
const dialect = db?.dialect ?? dbKind ?? "postgres";
|
|
126
|
+
const connector = await api.createSqlConnector(orgId, projectId, schema, queries, dialect);
|
|
127
|
+
if (dryRun) return { kind: "sql", connectorDraftId: connector.id, ...stageWarnings.length > 0 && { warnings: stageWarnings } };
|
|
128
|
+
return runStage(api, orgId, projectId, "sql", connector.id, timeoutMs, reviewOnly, stageWarnings, force);
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
const docSources = [];
|
|
132
|
+
if (opts.docs && opts.docs.length > 0) {
|
|
133
|
+
docSources.push(...await expandDocPatterns(opts.docs, opts.convertedOutputDir, opts.analysisDepth));
|
|
134
|
+
}
|
|
135
|
+
if (opts.text !== void 0) {
|
|
136
|
+
docSources.push(inlineText(opts.text, opts.analysisDepth));
|
|
137
|
+
}
|
|
138
|
+
if (docSources.length > 0) {
|
|
139
|
+
await runOrFail("docs", async () => {
|
|
140
|
+
const connector = await api.createDocsConnector(
|
|
141
|
+
orgId,
|
|
142
|
+
projectId,
|
|
143
|
+
docSources,
|
|
144
|
+
void 0,
|
|
145
|
+
opts.analysisDepth,
|
|
146
|
+
opts.forceDocs ? { force: true } : void 0
|
|
147
|
+
);
|
|
148
|
+
const unchanged = connector.unchanged && connector.unchanged.length > 0 ? { unchanged: connector.unchanged } : {};
|
|
149
|
+
if (!connector.id) return { kind: "docs", ...unchanged };
|
|
150
|
+
if (dryRun) return { kind: "docs", connectorDraftId: connector.id, ...unchanged };
|
|
151
|
+
return { ...await runStage(api, orgId, projectId, "docs", connector.id, timeoutMs, reviewOnly, [], force), ...unchanged };
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
if (opts.skill) {
|
|
155
|
+
await runOrFail("skill", async () => {
|
|
156
|
+
const sources = await expandDocPatterns(opts.skill.sources);
|
|
157
|
+
const connector = await api.createSkillConnector(orgId, projectId, opts.skill.name, opts.skill.description, sources);
|
|
158
|
+
return { kind: "skill", connectorDraftId: connector.connectorDraftId };
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
return { stages };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export {
|
|
165
|
+
IngestPartialFailureError,
|
|
166
|
+
resolveIds,
|
|
167
|
+
lookupIds,
|
|
168
|
+
performIngest
|
|
169
|
+
};
|