UNPKG

@bytebase/dbhub

Version:

Token-efficient database MCP server for PostgreSQL, MySQL, MariaDB, SQL Server, Oracle, ClickHouse, SQLite

243 lines (240 loc) • 7.49 kB
import { classifyPostgresSQL, postgresExplainOptions } from "./chunk-GZXZQJYW.js"; import { stripCommentsAndStringsVariants } from "./chunk-HJNFFBF4.js"; // src/utils/allowed-keywords.ts var allowedKeywords = { postgres: ["select", "with", "values", "table", "explain", "show"], mysql: ["select", "with", "explain", "show", "describe", "desc"], mariadb: ["select", "with", "explain", "show", "describe", "desc"], sqlite: ["select", "with", "explain", "pragma"], // SQL Server has no native EXPLAIN statement; the connector translates a // leading `EXPLAIN` into a SET SHOWPLAN_XML request (see SQLServerConnector). sqlserver: ["select", "with", "explain"], // Oracle's native form is `EXPLAIN PLAN FOR <stmt>`; the connector accepts // both that and a bare `EXPLAIN <stmt>` and reads the plan back through // DBMS_XPLAN (see OracleConnector.explainQuery). EXPLAIN PLAN only parses // the statement, it never executes it. oracle: ["select", "with", "explain"], // EXPLAIN never executes the statement on ClickHouse (there is no ANALYZE // form); EXISTS is its "does this table exist" statement. clickhouse: ["select", "with", "explain", "show", "describe", "desc", "exists"] }; var mutatingKeywords = [ "insert", "update", "delete", "drop", "alter", "create", "truncate", "merge", "grant", "revoke", "rename" ]; var mutatingPattern = new RegExp( `\\b(?:${mutatingKeywords.join("|")})\\b`, "i" ); var mutatingPatternWithReplace = new RegExp( `\\b(?:${mutatingKeywords.join("|")}|replace\\s+(?:(?:low_priority|delayed)\\s+)?into)\\b`, "i" ); var sqlServerDynamicSqlKeywords = [ "execute", "exec", "sp_executesql", "xp_cmdshell" ]; var sqlServerDynamicSqlPattern = new RegExp( `\\b(?:${sqlServerDynamicSqlKeywords.join("|")})\\b`, "i" ); var sqlServerPassThroughKeywords = [ "openquery", "openrowset", "opendatasource" ]; var sqlServerPassThroughPattern = new RegExp( `\\b(?:${sqlServerPassThroughKeywords.join("|")})\\s*\\(`, "i" ); var escapeHatchFunctionKeywords = { mysql: ["load_file", "get_lock", "release_lock", "release_all_locks"], mariadb: ["load_file", "get_lock", "release_lock", "release_all_locks"], sqlserver: sqlServerPassThroughKeywords, // Oracle packages a SELECT can call to reach outside the database, matched // as `package.member(` (see escapeHatchCallSuffix). oracle: [ "utl_http", "utl_tcp", "utl_smtp", "utl_inaddr", "utl_file", "dbms_ldap", "dbms_sql", "dbms_scheduler", "dbms_java", "dbms_lob", "dbms_xslprocessor", "dbms_advisor" ], clickhouse: [ "url", "urlCluster", "file", "fileCluster", "s3", "s3Cluster", "gcs", "azureBlobStorage", "azureBlobStorageCluster", "hdfs", "hdfsCluster", "remote", "remoteSecure", "mysql", "postgresql", "mongodb", "redis", "sqlite", "jdbc", "odbc", "executable", "deltaLake", "iceberg", "hudi" ] }; var escapeHatchCallSuffix = { oracle: "\\s*\\.\\s*[a-z_][a-z0-9_$#]*\\s*\\(" }; var DEFAULT_CALL_SUFFIX = "\\s*\\("; var escapeHatchFunctionPatterns = Object.fromEntries( Object.entries(escapeHatchFunctionKeywords).map(([type, keywords]) => [ type, new RegExp( `\\b(?:${keywords.join("|")})${escapeHatchCallSuffix[type] ?? DEFAULT_CALL_SUFFIX}`, "i" ) ]) ); function hasEscapeHatchFunction(strippedSQL, connectorType) { const pattern = escapeHatchFunctionPatterns[connectorType]; return pattern !== void 0 && pattern.test(strippedSQL); } var mutatingPatternSqlServer = new RegExp( `\\b(?:${[...mutatingKeywords, ...sqlServerDynamicSqlKeywords].join("|")})\\b`, "i" ); var mutatingPatterns = { mysql: mutatingPatternWithReplace, mariadb: mutatingPatternWithReplace, sqlite: mutatingPatternWithReplace, sqlserver: mutatingPatternSqlServer, oracle: mutatingPattern, clickhouse: mutatingPattern }; function hasMutatingKeyword(strippedSQL, connectorType) { return (mutatingPatterns[connectorType] ?? mutatingPattern).test(strippedSQL); } var selectIntoPattern = /\bselect\b[\s\S]+\binto\b/i; var sqliteReadOnlyArgPragmas = /* @__PURE__ */ new Set([ "table_info", "index_info", "index_list", "foreign_key_list" ]); var sqlitePragmaParenPattern = /^pragma\s+(?:[a-z0-9_]+\.)?([a-z0-9_]+)\s*\(/; var explainAnalyzeKeyword = /^analy[sz]e\b/i; var nonExecutingExplainOptions = postgresExplainOptions; var parenthesizedQueryStart = /^\(\s*(?:\(|(?:select|with|table|values)\b)/i; var disabledExplainOptionValue = /^\s*(?:=\s*)?(?:false|off|0)\b/i; function readExplainOptionList(afterExplain) { if (!afterExplain.startsWith("(") || parenthesizedQueryStart.test(afterExplain)) { return null; } const close = afterExplain.indexOf(")"); const end = close === -1 ? afterExplain.length : close; const options = afterExplain.slice(1, end).split(",").map((option) => { const m = /^\s*([a-z_][\w$]*)(?=[\s=]|$)([\s\S]*)$/i.exec(option); return m ? { name: m[1].toLowerCase(), value: m[2] } : { name: "", value: option }; }); return { options, rest: afterExplain.slice(end + 1) }; } function statementExecutedByExplain(afterExplain) { const optionList = readExplainOptionList(afterExplain); if (optionList) { const executes = optionList.options.some( ({ name, value }) => explainAnalyzeKeyword.test(name) ? !disabledExplainOptionValue.test(value) : !nonExecutingExplainOptions.has(name) ); return executes ? optionList.rest.trim() : null; } const analyze = explainAnalyzeKeyword.exec(afterExplain); if (!analyze) { return null; } const rest = afterExplain.slice(analyze[0].length); if (disabledExplainOptionValue.test(rest)) { return null; } return rest.replace(/^\s+verbose\b/i, "").trim(); } function isReadOnlySQL(sql, connectorType) { if (connectorType === "postgres") return classifyPostgresSQL(sql) === "read"; return stripCommentsAndStringsVariants(sql, connectorType).every( (cleaned) => checkReadOnly(cleaned.trim().toLowerCase(), connectorType) ); } function checkReadOnly(cleanedSQL, connectorType) { if (!cleanedSQL) { return false; } const firstWord = cleanedSQL.match(/\S+/)?.[0] ?? ""; const keywordList = allowedKeywords[connectorType] || []; if (!keywordList.includes(firstWord)) { return false; } if (hasEscapeHatchFunction(cleanedSQL, connectorType)) { return false; } if (firstWord === "with" && hasMutatingKeyword(cleanedSQL, connectorType)) { return false; } if (firstWord === "pragma" && connectorType === "sqlite") { if (cleanedSQL.includes("=")) { return false; } const parenMatch = cleanedSQL.match(sqlitePragmaParenPattern); if (parenMatch && !sqliteReadOnlyArgPragmas.has(parenMatch[1])) { return false; } } if ((firstWord === "select" || firstWord === "with") && selectIntoPattern.test(cleanedSQL)) { return false; } if (firstWord === "explain") { const executed = statementExecutedByExplain(cleanedSQL.slice(firstWord.length).trim()); if (executed && !checkReadOnly(executed, connectorType)) { return false; } } return true; } export { allowedKeywords, sqlServerDynamicSqlKeywords, sqlServerDynamicSqlPattern, sqlServerPassThroughKeywords, sqlServerPassThroughPattern, hasEscapeHatchFunction, hasMutatingKeyword, explainAnalyzeKeyword, nonExecutingExplainOptions, readExplainOptionList, isReadOnlySQL };