UNPKG

@bytebase/dbhub

Version:

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

211 lines (209 loc) • 6.82 kB
import { MARIADB_READ_ONLY_BACKSTOP, MissingDatabaseError, MySQLFamilyConnector, readMySQLFamilySslMode, requireDatabaseInDSN, withReadOnlyTransaction } from "./chunk-JMHM2U5L.js"; import { clientQueryTimeoutMs, isClientSideTimeout, withClientQueryDeadline } 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/mariadb/index.ts import * as mariadb from "mariadb"; function mariadbSslOptions(mode) { switch (mode) { case "disable": return void 0; case "require": return { rejectUnauthorized: false }; case "verify-ca": return { rejectUnauthorized: true, checkServerIdentity: () => void 0 }; case "verify-full": return { rejectUnauthorized: true }; } } var MariadbDSNParser = class { async parse(dsn, config) { const connectionTimeoutSeconds = config?.connectionTimeoutSeconds; const queryTimeoutSeconds = config?.queryTimeoutSeconds; if (!this.isValidDSN(dsn)) { const obfuscatedDSN = obfuscateDSNPassword(dsn); const expectedFormat = this.getSampleDSN(); throw new Error( `Invalid MariaDB DSN format. Provided: ${obfuscatedDSN} Expected: ${expectedFormat}` ); } try { const url = new SafeURL(dsn); const database = url.pathname ? url.pathname.substring(1) : ""; requireDatabaseInDSN(database, dsn, "MariaDB"); const connectionConfig = { host: url.hostname, port: url.port ? parseInt(url.port) : 3306, database, user: url.username, password: url.password, multipleStatements: true, // Enable native multi-statement support ...connectionTimeoutSeconds !== void 0 && { connectTimeout: connectionTimeoutSeconds * 1e3 }, // Server-side limit: the driver applies `queryTimeout` on each new // connection as the session variable max_statement_time. ...queryTimeoutSeconds !== void 0 && { queryTimeout: queryTimeoutSeconds * 1e3 }, // Controls how the driver interprets DATETIME values ("Z", "local", or "±HH:MM"). ...config?.timezone !== void 0 && { timezone: config.timezone }, // Connection character set (e.g. "utf8mb4") / collation (e.g. // "utf8mb4_general_ci"). The mariadb driver exposes both as distinct // options, but a configured collation is authoritative (it implies its // character set) and the driver ignores `collation` when `charset` is also // passed. So forward the collation when present, otherwise the charset // (which uses that character set's default collation). ...config?.collation !== void 0 ? { collation: config.collation } : config?.charset !== void 0 ? { charset: config.charset } : {} }; const sslmode = readMySQLFamilySslMode(dsn); if (sslmode !== void 0) { connectionConfig.ssl = mariadbSslOptions(sslmode); } if (url.password && url.password.includes("X-Amz-Credential")) { if (connectionConfig.ssl === void 0) { connectionConfig.ssl = { rejectUnauthorized: false }; } } return connectionConfig; } catch (error) { if (error instanceof MissingDatabaseError) { throw error; } throw new Error( `Failed to parse MariaDB DSN: ${error instanceof Error ? error.message : String(error)}` ); } } getSampleDSN() { return "mariadb://root:password@localhost:3306/db?sslmode=require"; } isValidDSN(dsn) { try { return dsn.startsWith("mariadb://"); } catch (error) { return false; } } }; var MariaDBConnector = class _MariaDBConnector extends MySQLFamilyConnector { constructor() { super(...arguments); this.id = "mariadb"; this.name = "MariaDB"; this.dsnParser = new MariadbDSNParser(); this.pool = null; } clone() { return new _MariaDBConnector(); } async connect(dsn, initScript, config) { try { const connectionConfig = await this.dsnParser.parse(dsn, config); this.clientQueryTimeoutMs = config?.queryTimeoutSeconds !== void 0 ? clientQueryTimeoutMs(config.queryTimeoutSeconds * 1e3) : void 0; this.pool = mariadb.createPool(connectionConfig); this.pool.on("error", (err) => { console.error( `MariaDB pool (source "${this.sourceId}"): background connection error, pool will retry:`, err.message ); }); await this.pool.query("SELECT 1"); } catch (err) { if (this.pool) { const pool = this.pool; this.pool = null; await closeQuietly(() => pool.end()); } console.error("Failed to connect to MariaDB database:", err); throw err; } } 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. The mariadb driver already * resolves to the rows themselves. */ requireQuery() { if (!this.pool) { throw new Error("Not connected to database"); } const pool = this.pool; return (sql, params) => params === void 0 ? pool.query(sql) : pool.query(sql, params); } async executeSQL(sql, options, parameters) { if (!this.pool) { throw new Error("Not connected to database"); } const conn = await this.pool.getConnection(); let isConnectionDiscarded = false; try { return await withReadOnlyTransaction( conn, options.readonly, MARIADB_READ_ONLY_BACKSTOP, () => this.executeStatements(sql, options, (processedSQL) => { const queryOptions = { sql: processedSQL, rowsAsArray: true, metaAsArray: true }; return withClientQueryDeadline( parameters && parameters.length > 0 ? conn.query(queryOptions, parameters) : conn.query(queryOptions), this.clientQueryTimeoutMs ); }) ); } catch (error) { if (isClientSideTimeout(error)) { isConnectionDiscarded = true; conn.destroy(); } throw error; } finally { if (!isConnectionDiscarded) { conn.release(); } } } }; var mariadbConnector = new MariaDBConnector(); ConnectorRegistry.register(mariadbConnector); export { MariaDBConnector };