@bytebase/dbhub
Version:
Token-efficient database MCP server for PostgreSQL, MySQL, MariaDB, SQL Server, Oracle, ClickHouse, SQLite
226 lines (223 loc) • 7.39 kB
JavaScript
import {
splitSQLStatements
} from "./chunk-HJNFFBF4.js";
// src/utils/postgres-sql.ts
var parser;
var parserLoadError;
try {
const loaded = await import("libpg-query");
await loaded.loadModule();
parser = loaded;
} catch (error) {
parserLoadError = error;
}
function loadedParser() {
if (!parser) {
const reason = parserLoadError instanceof Error ? parserLoadError.message : String(parserLoadError);
throw new Error(`The PostgreSQL SQL parser (libpg-query) failed to load: ${reason}`, {
cause: parserLoadError
});
}
return parser;
}
function assertPostgresParserLoaded() {
loadedParser();
}
var severity = { read: 0, dml: 1, ddl: 2, admin: 3, unknown: 4 };
var restrictedFunctions = /* @__PURE__ */ new Set([
"pg_read_file",
"pg_read_binary_file",
"pg_ls_dir",
"set_config"
]);
var ddlNodes = /* @__PURE__ */ new Set([
"CreateStmt",
"CreateTableAsStmt",
"CreateSchemaStmt",
"CreateFunctionStmt",
"CreateSeqStmt",
"CreateExtensionStmt",
"CreateTrigStmt",
"CreateDomainStmt",
"CreateEnumStmt",
"CreateRangeStmt",
"CompositeTypeStmt",
"IndexStmt",
"ViewStmt",
"AlterTableStmt",
"AlterObjectSchemaStmt",
"AlterOwnerStmt",
"AlterFunctionStmt",
"AlterSeqStmt",
"AlterEnumStmt",
"AlterDomainStmt",
"AlterExtensionStmt",
"DropStmt",
"TruncateStmt",
"RenameStmt",
"CommentStmt"
]);
var postgresExplainOptions = /* @__PURE__ */ new Set([
"verbose",
"costs",
"settings",
"generic_plan",
"buffers",
"serialize",
"wal",
"timing",
"summary",
"memory",
"format"
]);
function strictest(a, b) {
return severity[a] >= severity[b] ? a : b;
}
function parseOrError(sql) {
const pg = loadedParser();
try {
return { parsed: pg.parseSync(sql) };
} catch (error) {
if (error instanceof pg.SqlError) return { error };
throw error;
}
}
function parsePostgresSQL(sql) {
if (!sql.trim()) return null;
const outcome = parseOrError(sql);
return "parsed" in outcome ? outcome.parsed : null;
}
function postgresSyntaxError(sql) {
if (!sql.trim()) return null;
const whole = parseOrError(sql);
if ("error" in whole) {
const position = whole.error.sqlDetails?.cursorPosition ?? 0;
return position > 0 ? `${whole.error.message} (position ${position + 1})` : whole.error.message;
}
for (const piece of splitSQLStatements(sql, "postgres")) {
const outcome = parseOrError(piece);
if ("error" in outcome) return outcome.error.message;
}
return null;
}
function explainExecutes(stmt) {
let analyze = false;
for (const option of stmt.options ?? []) {
const def = "DefElem" in option ? option.DefElem : void 0;
if (!def) return true;
if (def.defname === "analyze") {
const value = def.arg;
analyze = value && "String" in value ? !["false", "off", "0"].includes(value.String.sval?.toLowerCase() ?? "") : value && "Integer" in value ? value.Integer.ival !== 0 : value && "Boolean" in value ? value.Boolean.boolval === true : true;
} else if (!postgresExplainOptions.has(def.defname ?? "")) {
return true;
}
}
return analyze;
}
function isRestrictedName(name) {
return !!name && "String" in name && restrictedFunctions.has(name.String.sval ?? "");
}
function callsRestrictedFunction(node) {
if ("FuncCall" in node) return isRestrictedName(node.FuncCall.funcname?.slice(-1)[0]);
if ("A_Indirection" in node) return !!node.A_Indirection.indirection?.some(isRestrictedName);
return false;
}
function classifyChildren(value, restrictFunctions) {
if (!value || typeof value !== "object") return "read";
if (Array.isArray(value))
return value.reduce(
(result, child) => strictest(result, classifyChildren(child, restrictFunctions)),
"read"
);
const object = value;
const node = value;
if (restrictFunctions && callsRestrictedFunction(node)) return "admin";
if (Object.keys(object).some((key) => key.endsWith("Stmt") && key[0] === key[0].toUpperCase()))
return classifyNode(node, restrictFunctions);
return Object.values(object).reduce(
(result, child) => strictest(result, classifyChildren(child, restrictFunctions)),
"read"
);
}
function classifyNode(node, restrictFunctions = true) {
if ("ExplainStmt" in node) {
return explainExecutes(node.ExplainStmt) ? node.ExplainStmt.query ? classifyNode(node.ExplainStmt.query, restrictFunctions) : "unknown" : "read";
}
if ("SelectStmt" in node) {
const { larg, rarg, ...select } = node.SelectStmt;
let result = strictest(
select.intoClause ? "ddl" : "read",
classifyChildren(select, restrictFunctions)
);
for (const branch of [larg, rarg]) {
if (branch) result = strictest(result, classifyNode({ SelectStmt: branch }, restrictFunctions));
}
return result;
}
if ("VariableShowStmt" in node) return "read";
if ("InsertStmt" in node || "UpdateStmt" in node || "DeleteStmt" in node || "MergeStmt" in node) {
return strictest("dml", classifyChildren(Object.values(node), restrictFunctions));
}
if ("GrantStmt" in node || "GrantRoleStmt" in node) return "admin";
if (Object.keys(node).some((key) => ddlNodes.has(key))) return "ddl";
return "unknown";
}
function classifyText(sql) {
const parsed = parsePostgresSQL(sql);
if (!parsed) return "unknown";
if (!parsed.stmts?.length) return null;
return parsed.stmts.reduce(
(result, raw) => strictest(result, raw.stmt ? classifyNode(raw.stmt) : "unknown"),
"read"
);
}
function classifyPostgresSQL(sql) {
const whole = classifyText(sql);
if (whole === null) return "unknown";
return splitSQLStatements(sql, "postgres").reduce(
(result, piece) => strictest(result, classifyText(piece) ?? "read"),
whole
);
}
function isPostgresSelect(sql) {
if (!sql.trim()) return false;
const outcome = parseOrError(sql);
if ("error" in outcome) return null;
const { stmts } = outcome.parsed;
const node = stmts?.length === 1 ? stmts[0].stmt : void 0;
return !!node && "SelectStmt" in node && classifyNode(node, false) === "read";
}
function validatePostgresExplain(sql) {
const input = parsePostgresSQL(sql);
if (input?.stmts?.some((raw) => raw.stmt && "ExplainStmt" in raw.stmt)) {
return "explain_sql input must not itself start with EXPLAIN";
}
const explain = `EXPLAIN ${sql}`;
const outcome = parseOrError(explain);
if ("error" in outcome) {
return `explain_sql requires valid PostgreSQL EXPLAIN syntax: ${outcome.error.message}`;
}
const { parsed } = outcome;
if (parsed.stmts?.length !== 1 || splitSQLStatements(explain, "postgres").length !== 1) {
return "explain_sql only supports a single SQL statement";
}
const node = parsed.stmts[0].stmt;
if (!node || !("ExplainStmt" in node)) return "explain_sql requires an EXPLAIN statement";
for (const option of node.ExplainStmt.options ?? []) {
const name = "DefElem" in option ? option.DefElem.defname : void 0;
if (name === "analyze")
return "explain_sql does not support ANALYZE (it must never execute the statement)";
if (!name || !postgresExplainOptions.has(name)) {
return "explain_sql only accepts these EXPLAIN options: " + [...postgresExplainOptions].join(", ");
}
}
return null;
}
export {
assertPostgresParserLoaded,
postgresExplainOptions,
postgresSyntaxError,
classifyPostgresSQL,
isPostgresSelect,
validatePostgresExplain
};