UNPKG

@bytebase/dbhub

Version:

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

321 lines (319 loc) • 10.2 kB
import { buildMySQLSessionStatement } from "./chunk-FRYLTOWC.js"; import { MissingDatabaseError, MySQLFamilyConnector, VERSION_COMMENT_QUERY, detectReadOnlyBackstop, noBackstopWarning, readMySQLFamilySslMode, requireDatabaseInDSN, withReadOnlyTransaction } from "./chunk-JMHM2U5L.js"; import { CANCEL_QUERY_TIMEOUT_MS, clientQueryTimeoutMs, isClientSideTimeout } from "./chunk-6UGT3UWA.js"; import "./chunk-7TOVHKBQ.js"; import "./chunk-FU2ZJE4E.js"; import "./chunk-IGQAAKFF.js"; import "./chunk-5ACPKE4X.js"; import "./chunk-SR7SSJAL.js"; import { closeQuietly } from "./chunk-CZ5B3EO3.js"; import "./chunk-7546W2OD.js"; import "./chunk-GZXZQJYW.js"; import { ConnectorRegistry, SafeURL, obfuscateDSNPassword } from "./chunk-HJNFFBF4.js"; // src/connectors/mysql/index.ts import mysql from "mysql2/promise"; function mysqlSslOptions(mode) { switch (mode) { case "disable": return void 0; case "require": return { rejectUnauthorized: false }; case "verify-ca": return { rejectUnauthorized: true }; case "verify-full": return { rejectUnauthorized: true, verifyIdentity: true }; } } var MySQLDSNParser = class { async parse(dsn, config) { const connectionTimeoutSeconds = config?.connectionTimeoutSeconds; const poolMaxConnections = config?.poolMaxConnections; const timezone = config?.timezone; const charset = config?.charset; const collation = config?.collation; if (!this.isValidDSN(dsn)) { const obfuscatedDSN = obfuscateDSNPassword(dsn); const expectedFormat = this.getSampleDSN(); throw new Error( `Invalid MySQL DSN format. Provided: ${obfuscatedDSN} Expected: ${expectedFormat}` ); } try { const url = new SafeURL(dsn); const database = url.pathname ? url.pathname.substring(1) : ""; requireDatabaseInDSN(database, dsn, "MySQL"); const config2 = { host: url.hostname, port: url.port ? parseInt(url.port) : 3306, database, user: url.username, password: url.password, multipleStatements: true, // Enable native multi-statement support supportBigNumbers: true // Return BIGINT as string when value exceeds Number.MAX_SAFE_INTEGER }; const sslmode = readMySQLFamilySslMode(dsn); if (sslmode !== void 0) { config2.ssl = mysqlSslOptions(sslmode); } if (connectionTimeoutSeconds !== void 0) { config2.connectTimeout = connectionTimeoutSeconds * 1e3; } if (poolMaxConnections !== void 0) { config2.connectionLimit = poolMaxConnections; } if (timezone !== void 0) { config2.timezone = timezone; } const charsetOrCollation = collation ?? charset; if (charsetOrCollation !== void 0) { config2.charset = charsetOrCollation; } if (url.password && url.password.includes("X-Amz-Credential")) { config2.authPlugins = { mysql_clear_password: () => () => { return Buffer.from(url.password + "\0"); } }; if (config2.ssl === void 0) { config2.ssl = { rejectUnauthorized: false }; } } return config2; } catch (error) { if (error instanceof MissingDatabaseError) { throw error; } throw new Error( `Failed to parse MySQL DSN: ${error instanceof Error ? error.message : String(error)}` ); } } getSampleDSN() { return "mysql://root:password@localhost:3306/mysql?sslmode=require"; } isValidDSN(dsn) { try { return dsn.startsWith("mysql://"); } catch (error) { return false; } } }; function applyOnEveryConnection(pool, statement) { pool.on("connection", (connection) => { connection.query(statement, (err) => { if (err) { connection.stream.destroy(err instanceof Error ? err : new Error(String(err))); } }); }); } async function getConnectionWithin(pool, timeoutMs) { const pending = pool.getConnection(); if (timeoutMs === void 0) { return pending; } let timer; let timedOut = false; const timeout = new Promise((_, reject) => { timer = setTimeout(() => { timedOut = true; reject(new Error(`Timed out after ${timeoutMs} ms waiting for a free connection from the pool`)); }, timeoutMs); }); try { return await Promise.race([pending, timeout]); } finally { clearTimeout(timer); if (timedOut) { pending.then( (conn) => conn.release(), () => { } ); } } } var MySQLConnector = class _MySQLConnector extends MySQLFamilyConnector { constructor() { super(...arguments); this.id = "mysql"; this.name = "MySQL"; this.dsnParser = new MySQLDSNParser(); this.pool = null; // How the read-only backstop takes effect on this server (which session // variable to save/restore; TiDB rejects `START TRANSACTION READ ONLY` // unless tidb_enable_noop_functions is on; Apache Doris has no transactional // backstop at all). Detected once at connect time. MySQL-compatible servers // are special-cased here only: the MariaDB connector does no such detection. this.readOnlyBackstop = { kind: "session", variable: "transaction_read_only" }; } clone() { return new _MySQLConnector(); } async connect(dsn, initScript, config) { try { const connectionOptions = await this.dsnParser.parse(dsn, config); const queryTimeoutMs = config?.queryTimeoutSeconds !== void 0 ? Math.ceil(config.queryTimeoutSeconds * 1e3) : void 0; this.clientQueryTimeoutMs = queryTimeoutMs !== void 0 ? clientQueryTimeoutMs(queryTimeoutMs) : void 0; this.pool = mysql.createPool(connectionOptions); this.connectionTimeoutMs = config?.connectionTimeoutSeconds !== void 0 ? config.connectionTimeoutSeconds * 1e3 : void 0; if (queryTimeoutMs !== void 0) { const setServerLimit = `SET SESSION max_execution_time = ${queryTimeoutMs}`; this.pool.on( "connection", (connection) => { connection.query(setServerLimit, () => { }); } ); } const sessionStatement = config?.sessionSettings !== void 0 ? buildMySQLSessionStatement(config.sessionSettings) : void 0; if (sessionStatement !== void 0) { applyOnEveryConnection(this.pool, sessionStatement); } const [rows] = await this.pool.query("SELECT VERSION() AS version"); this.readOnlyBackstop = detectReadOnlyBackstop( rows[0]?.version, await this.probeVersionComment() ); if (this.readOnlyBackstop.kind === "none") { console.error(noBackstopWarning(this.sourceId)); } } catch (err) { if (this.pool) { const pool = this.pool; this.pool = null; await closeQuietly(() => pool.end()); } console.error("Failed to connect to MySQL database:", err); throw err; } } /** * Reads `@@version_comment`, which identifies MySQL-protocol servers whose * `VERSION()` looks stock (Apache Doris). Best effort: a server without the * variable yields undefined, which keeps the default read-only backstop. */ async probeVersionComment() { try { const [rows] = await this.pool.query(VERSION_COMMENT_QUERY); return rows[0]?.version_comment; } catch { return void 0; } } async disconnect() { if (this.pool) { await this.pool.end(); this.pool = null; } } /** * Row-array query adapter over the pool for the shared MySQL-family * introspection and health-check code. Throws when not connected, so the * shared functions never see a missing pool. mysql2 resolves to * [rows, fields]; only the rows are handed on. */ requireQuery() { if (!this.pool) { throw new Error("Not connected to database"); } const pool = this.pool; return async (sql, params) => { const [rows] = await (params === void 0 ? pool.query(sql) : pool.query(sql, params)); return rows; }; } async executeSQL(sql, options, parameters) { if (!this.pool) { throw new Error("Not connected to database"); } const conn = await getConnectionWithin(this.pool, this.connectionTimeoutMs); const threadId = conn.threadId; let isConnectionDiscarded = false; const timeout = this.clientQueryTimeoutMs; try { return await withReadOnlyTransaction( conn, options.readonly, this.readOnlyBackstop, () => this.executeStatements(sql, options, (processedSQL) => { const queryOptions = { sql: processedSQL, timeout, rowsAsArray: true }; return parameters && parameters.length > 0 ? conn.query(queryOptions, parameters) : conn.query(queryOptions); }) ); } catch (error) { if (isClientSideTimeout(error)) { isConnectionDiscarded = true; conn.destroy(); await this.killQuery(threadId); } throw error; } finally { if (!isConnectionDiscarded) { conn.release(); } } } /** * Best-effort server-side kill for a query abandoned by mysql2's client-side * timeout. Uses a separate connection: the original connection's command * queue is stuck behind the abandoned statement (see isClientSideTimeout) * and cannot itself be used to send KILL QUERY. * * Bounded by its own short timeout (CANCEL_QUERY_TIMEOUT_MS), independent * of the user's query_timeout. */ async killQuery(threadId) { if (!this.pool) return; let killer; let killerPoisoned = false; try { killer = await this.pool.getConnection(); await killer.query({ sql: `KILL QUERY ${threadId}`, timeout: CANCEL_QUERY_TIMEOUT_MS }); } catch (error) { killerPoisoned = isClientSideTimeout(error); } finally { if (killer) { if (killerPoisoned) { killer.destroy(); } else { killer.release(); } } } } }; var mysqlConnector = new MySQLConnector(); ConnectorRegistry.register(mysqlConnector); export { MySQLConnector, applyOnEveryConnection, getConnectionWithin };