@brainbox-labs/sdk 0.0.0-stage → 0.22.1
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 +56 -0
- package/dist/chunk-43LDD7YT.js +139 -0
- package/dist/chunk-AJR44IFE.js +47 -0
- package/dist/chunk-ANGBZHCB.js +120 -0
- package/dist/chunk-MLKGABMK.js +9 -0
- package/dist/chunk-OOHPBQXX.js +152 -0
- package/dist/chunk-VEXUCOXR.js +387 -0
- package/dist/chunk-YRH35U57.js +178 -0
- package/dist/chunk-YWH6IOQG.js +650 -0
- package/dist/column-profiler-FJCAQQAS.js +23 -0
- package/dist/docs-loader-VMBVV44Y.js +9 -0
- package/dist/index-qV0gq2eJ.d.ts +148 -0
- package/dist/index.d.ts +387 -0
- package/dist/index.js +507 -0
- package/dist/ingest/public.d.ts +182 -0
- package/dist/ingest/public.js +63 -0
- package/dist/ingest-OA6KWJNR.js +9 -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 +7 -0
- package/dist/sql-parser-TB26PFXS.js +198 -0
- package/dist/trino-TUQ7CIRM.js +13 -0
- package/package.json +79 -4
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// src/ingest/docs-loader.ts
|
|
2
|
+
import * as fs2 from "fs/promises";
|
|
3
|
+
import * as nodePath2 from "path";
|
|
4
|
+
import { glob } from "glob";
|
|
5
|
+
|
|
6
|
+
// src/ingest/doc-converter.ts
|
|
7
|
+
import * as fs from "fs/promises";
|
|
8
|
+
import * as nodePath from "path";
|
|
9
|
+
function needsConversion(filePath) {
|
|
10
|
+
const ext = nodePath.extname(filePath).toLowerCase();
|
|
11
|
+
return ext === ".pdf" || ext === ".docx" || ext === ".html" || ext === ".htm";
|
|
12
|
+
}
|
|
13
|
+
async function htmlToMarkdown(html) {
|
|
14
|
+
const TurndownService = (await import("turndown")).default;
|
|
15
|
+
const td = new TurndownService({ headingStyle: "atx", codeBlockStyle: "fenced" });
|
|
16
|
+
return td.turndown(html);
|
|
17
|
+
}
|
|
18
|
+
async function convertToMarkdown(filePath) {
|
|
19
|
+
const ext = nodePath.extname(filePath).toLowerCase();
|
|
20
|
+
if (ext === ".docx") {
|
|
21
|
+
const mammoth = await import("mammoth");
|
|
22
|
+
const result = await mammoth.convertToHtml({ path: filePath });
|
|
23
|
+
const warnings = result.messages.filter((m) => m.type === "warning").map((m) => m.message);
|
|
24
|
+
if (warnings.length > 0) {
|
|
25
|
+
process.stderr.write(`mammoth warnings for ${nodePath.basename(filePath)}:
|
|
26
|
+
${warnings.join("\n")}
|
|
27
|
+
`);
|
|
28
|
+
}
|
|
29
|
+
return htmlToMarkdown(result.value);
|
|
30
|
+
}
|
|
31
|
+
if (ext === ".html" || ext === ".htm") {
|
|
32
|
+
const html = await fs.readFile(filePath, "utf-8");
|
|
33
|
+
return htmlToMarkdown(html);
|
|
34
|
+
}
|
|
35
|
+
if (ext === ".pdf") {
|
|
36
|
+
const { PDFParse } = await import("pdf-parse");
|
|
37
|
+
const buffer = await fs.readFile(filePath);
|
|
38
|
+
const parser = new PDFParse({ data: buffer });
|
|
39
|
+
try {
|
|
40
|
+
const result = await parser.getText();
|
|
41
|
+
return result.text;
|
|
42
|
+
} finally {
|
|
43
|
+
await parser.destroy();
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
throw new Error(`No converter available for extension "${ext}"`);
|
|
47
|
+
}
|
|
48
|
+
function convertedName(filePath) {
|
|
49
|
+
return nodePath.basename(filePath) + ".md";
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// src/ingest/docs-loader.ts
|
|
53
|
+
var BINARY_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
54
|
+
".png",
|
|
55
|
+
".jpg",
|
|
56
|
+
".jpeg",
|
|
57
|
+
".gif",
|
|
58
|
+
".bmp",
|
|
59
|
+
".zip",
|
|
60
|
+
".tar",
|
|
61
|
+
".gz",
|
|
62
|
+
".bz2",
|
|
63
|
+
".7z",
|
|
64
|
+
".exe",
|
|
65
|
+
".dll",
|
|
66
|
+
".so",
|
|
67
|
+
".bin"
|
|
68
|
+
]);
|
|
69
|
+
var CONVERT_EXTENSIONS = /* @__PURE__ */ new Set([".pdf", ".docx"]);
|
|
70
|
+
function inferType(filePath) {
|
|
71
|
+
const ext = nodePath2.extname(filePath).toLowerCase();
|
|
72
|
+
if (ext === ".md" || ext === ".markdown") return "markdown";
|
|
73
|
+
if (ext === ".html" || ext === ".htm") return "html";
|
|
74
|
+
return "text";
|
|
75
|
+
}
|
|
76
|
+
async function expandDocPatterns(patterns, outputDir, analysisDepth) {
|
|
77
|
+
if (outputDir) {
|
|
78
|
+
await fs2.mkdir(outputDir, { recursive: true });
|
|
79
|
+
}
|
|
80
|
+
const sources = [];
|
|
81
|
+
const seen = /* @__PURE__ */ new Set();
|
|
82
|
+
for (const pattern of patterns) {
|
|
83
|
+
const matches = await glob(pattern, { nodir: true, absolute: true });
|
|
84
|
+
for (const file of matches) {
|
|
85
|
+
if (seen.has(file)) continue;
|
|
86
|
+
seen.add(file);
|
|
87
|
+
const ext = nodePath2.extname(file).toLowerCase();
|
|
88
|
+
if (BINARY_EXTENSIONS.has(ext)) {
|
|
89
|
+
throw new Error(
|
|
90
|
+
`Unsupported file type "${ext}" for "${file}". Convert to markdown/text before passing to brain.ingest.`
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
if (CONVERT_EXTENSIONS.has(ext)) {
|
|
94
|
+
const content = await convertToMarkdown(file);
|
|
95
|
+
const name = convertedName(file);
|
|
96
|
+
if (outputDir) {
|
|
97
|
+
await fs2.writeFile(nodePath2.join(outputDir, name), content, "utf-8");
|
|
98
|
+
}
|
|
99
|
+
sources.push({ id: name, name, content, type: "markdown", ...analysisDepth && { analysisDepth } });
|
|
100
|
+
} else {
|
|
101
|
+
const content = await fs2.readFile(file, "utf-8");
|
|
102
|
+
const name = nodePath2.basename(file);
|
|
103
|
+
sources.push({ id: name, name, content, type: inferType(file), ...analysisDepth && { analysisDepth } });
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return sources;
|
|
108
|
+
}
|
|
109
|
+
function inlineText(text, analysisDepth) {
|
|
110
|
+
return { id: "inline.txt", name: "inline.txt", content: text, type: "text", ...analysisDepth && { analysisDepth } };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export {
|
|
114
|
+
needsConversion,
|
|
115
|
+
htmlToMarkdown,
|
|
116
|
+
convertToMarkdown,
|
|
117
|
+
convertedName,
|
|
118
|
+
expandDocPatterns,
|
|
119
|
+
inlineText
|
|
120
|
+
};
|
|
@@ -0,0 +1,152 @@
|
|
|
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 performIngest(ctx, opts) {
|
|
54
|
+
if (!opts.postgres && !opts.trino && !opts.athena && !opts.sql && !opts.docs && !opts.text && !opts.skill) {
|
|
55
|
+
throw new Error(
|
|
56
|
+
"[BrainBox] brain.ingest requires at least one source: postgres, trino, athena, sql, docs, text, or skill."
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
if ([opts.postgres, opts.trino, opts.athena].filter((s) => s !== void 0).length > 1) {
|
|
60
|
+
throw new Error(
|
|
61
|
+
"[BrainBox] brain.ingest accepts only one of `postgres`, `trino`, or `athena` \u2014 run separate ingests per database."
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
if (opts.sql && opts.sql.length > 0 && !opts.postgres && !opts.trino && !opts.athena) {
|
|
65
|
+
throw new Error(
|
|
66
|
+
"[BrainBox] brain.ingest `sql` requires `postgres`, `trino`, or `athena` \u2014 SQL files are submitted alongside a schema."
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
const [{ introspectDatabaseSchema }, { parseSqlInputs }, { expandDocPatterns, inlineText }, { connectAndProfile }] = await Promise.all([
|
|
70
|
+
import("./introspect-KQOOQEZM.js"),
|
|
71
|
+
import("./sql-parser-TB26PFXS.js"),
|
|
72
|
+
import("./docs-loader-VMBVV44Y.js"),
|
|
73
|
+
import("./column-profiler-FJCAQQAS.js")
|
|
74
|
+
]);
|
|
75
|
+
const api = new BrainBoxApiClient(ctx.apiUrl, ctx.apiKey, noopLogger);
|
|
76
|
+
const { orgId, projectId } = await resolveIds(api, ctx);
|
|
77
|
+
const timeoutMs = opts.timeoutMs ?? 3e5;
|
|
78
|
+
const reviewOnly = opts.reviewOnly ?? false;
|
|
79
|
+
const force = opts.force ?? false;
|
|
80
|
+
const dryRun = opts.dryRun ?? false;
|
|
81
|
+
const stages = [];
|
|
82
|
+
const runOrFail = async (kind, fn) => {
|
|
83
|
+
try {
|
|
84
|
+
stages.push(await fn());
|
|
85
|
+
} catch (err) {
|
|
86
|
+
if (stages.length > 0) throw new IngestPartialFailureError(kind, stages, err);
|
|
87
|
+
throw err;
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
const dbKind = opts.postgres ? "postgres" : opts.trino ? "trino" : opts.athena ? "athena" : void 0;
|
|
91
|
+
const db = opts.postgres ?? opts.trino ?? opts.athena;
|
|
92
|
+
if (db !== void 0 || opts.sql) {
|
|
93
|
+
await runOrFail("sql", async () => {
|
|
94
|
+
let schema;
|
|
95
|
+
if (db !== void 0) {
|
|
96
|
+
schema = await introspectDatabaseSchema(db.connectionString, dbKind);
|
|
97
|
+
if (db.tables !== void 0) {
|
|
98
|
+
const allowed = new Set(db.tables);
|
|
99
|
+
schema.tables = schema.tables.filter((t) => allowed.has(t.name));
|
|
100
|
+
}
|
|
101
|
+
if (opts.profile) {
|
|
102
|
+
const skipColumns = new Set((opts.profile.skipColumns ?? []).map((s) => s.trim()));
|
|
103
|
+
const sampleRows = opts.profile.sampleRows ?? 1e4;
|
|
104
|
+
schema = await connectAndProfile(db.connectionString, schema, {
|
|
105
|
+
mode: opts.profile.mode,
|
|
106
|
+
sampleRows,
|
|
107
|
+
skipColumns
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
const stageWarnings = [];
|
|
112
|
+
let queries = [];
|
|
113
|
+
if (opts.sql && opts.sql.length > 0) {
|
|
114
|
+
queries = await parseSqlInputs(opts.sql, stageWarnings);
|
|
115
|
+
}
|
|
116
|
+
if (!schema) {
|
|
117
|
+
throw new Error("[BrainBox] brain.ingest: missing schema for SQL stage.");
|
|
118
|
+
}
|
|
119
|
+
const dialect = db?.dialect ?? dbKind ?? "postgres";
|
|
120
|
+
const connector = await api.createSqlConnector(orgId, projectId, schema, queries, dialect);
|
|
121
|
+
if (dryRun) return { kind: "sql", connectorDraftId: connector.id, ...stageWarnings.length > 0 && { warnings: stageWarnings } };
|
|
122
|
+
return runStage(api, orgId, projectId, "sql", connector.id, timeoutMs, reviewOnly, stageWarnings, force);
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
const docSources = [];
|
|
126
|
+
if (opts.docs && opts.docs.length > 0) {
|
|
127
|
+
docSources.push(...await expandDocPatterns(opts.docs, opts.convertedOutputDir, opts.analysisDepth));
|
|
128
|
+
}
|
|
129
|
+
if (opts.text !== void 0) {
|
|
130
|
+
docSources.push(inlineText(opts.text, opts.analysisDepth));
|
|
131
|
+
}
|
|
132
|
+
if (docSources.length > 0) {
|
|
133
|
+
await runOrFail("docs", async () => {
|
|
134
|
+
const connector = await api.createDocsConnector(orgId, projectId, docSources, void 0, opts.analysisDepth);
|
|
135
|
+
if (dryRun) return { kind: "docs", connectorDraftId: connector.id };
|
|
136
|
+
return runStage(api, orgId, projectId, "docs", connector.id, timeoutMs, reviewOnly, [], force);
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
if (opts.skill) {
|
|
140
|
+
await runOrFail("skill", async () => {
|
|
141
|
+
const sources = await expandDocPatterns(opts.skill.sources);
|
|
142
|
+
const connector = await api.createSkillConnector(orgId, projectId, opts.skill.name, opts.skill.description, sources);
|
|
143
|
+
return { kind: "skill", connectorDraftId: connector.connectorDraftId };
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
return { stages };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export {
|
|
150
|
+
IngestPartialFailureError,
|
|
151
|
+
performIngest
|
|
152
|
+
};
|
|
@@ -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
|
+
};
|