@bytebase/dbhub
Version:
Token-efficient database MCP server for PostgreSQL, MySQL, MariaDB, SQL Server, Oracle, ClickHouse, SQLite
645 lines (635 loc) • 21.8 kB
JavaScript
import {
isClientSideTimeout
} from "./chunk-6UGT3UWA.js";
import {
groupIndexColumns
} from "./chunk-7TOVHKBQ.js";
import {
computeHitRatioPct,
toNullableNumber
} from "./chunk-FU2ZJE4E.js";
import {
quoteIdentifier
} from "./chunk-IGQAAKFF.js";
import {
SQLRowLimiter
} from "./chunk-5ACPKE4X.js";
import {
objectRows
} from "./chunk-SR7SSJAL.js";
import {
obfuscateDSNPassword,
rawQueryParamValues,
splitSQLStatements
} from "./chunk-HJNFFBF4.js";
// src/connectors/mysql-family-health-check.ts
async function getMySQLFamilyHealthCheck(query) {
const [processlistRows, maxConnRows, bufferPoolRows, trxOutcome] = await Promise.all([
query(`
SELECT
COUNT(*) AS total,
SUM(CASE WHEN COMMAND != 'Sleep' THEN 1 ELSE 0 END) AS active,
SUM(CASE WHEN COMMAND = 'Sleep' THEN 1 ELSE 0 END) AS idle,
MAX(CASE WHEN COMMAND != 'Sleep' THEN TIME ELSE NULL END) AS longest_active_query_seconds
FROM information_schema.PROCESSLIST
WHERE ID <> CONNECTION_ID()
`),
query(`SHOW VARIABLES LIKE 'max_connections'`),
query(`
SHOW GLOBAL STATUS WHERE Variable_name IN ('Innodb_buffer_pool_read_requests', 'Innodb_buffer_pool_reads')
`),
// Joining PROCESSLIST against INNODB_TRX to detect idle-in-transaction
// sessions requires the PROCESS privilege - unlike a plain PROCESSLIST
// select, which silently narrows to the caller's own session instead of
// erroring. Run concurrently with the other queries above, but resolve
// rather than reject on failure so it degrades instead of failing the
// whole health check.
query(`
SELECT
COUNT(*) AS idle_in_transaction,
MAX(TIMESTAMPDIFF(SECOND, t.trx_started, NOW())) AS longest_idle_in_transaction_seconds
FROM information_schema.INNODB_TRX t
JOIN information_schema.PROCESSLIST p ON p.ID = t.trx_mysql_thread_id
WHERE p.COMMAND = 'Sleep'
`).then(
(rows) => ({ ok: true, rows }),
() => ({ ok: false })
)
]);
const notes = [];
let idleInTransaction = 0;
let longestIdleInTransactionSeconds = null;
if (trxOutcome.ok) {
idleInTransaction = Number(trxOutcome.rows[0].idle_in_transaction);
longestIdleInTransactionSeconds = toNullableNumber(trxOutcome.rows[0].longest_idle_in_transaction_seconds);
} else {
notes.push(
"Connected user lacks the PROCESS privilege: PROCESSLIST visibility is restricted to the connecting user's own sessions, and this diagnostic session is excluded from the count, so connection counts and active-query duration may under-report (down to 0). Idle-in-transaction detection is unavailable."
);
}
const proc = processlistRows[0];
const bufferPoolStats = Object.fromEntries(bufferPoolRows.map((row) => [row.Variable_name, row.Value]));
const readRequests = Number(bufferPoolStats.Innodb_buffer_pool_read_requests ?? 0);
const reads = Number(bufferPoolStats.Innodb_buffer_pool_reads ?? 0);
return {
connections: {
total: Number(proc.total),
active: Number(proc.active),
idle: Number(proc.idle),
idleInTransaction,
// MySQL/MariaDB's InnoDB has no equivalent of Postgres's "idle in
// transaction (aborted)" state - a failed statement doesn't leave the
// session's transaction in a distinct aborted-but-open state the way
// Postgres does - so idleInTransactionAborted is left undefined.
maxConnections: maxConnRows.length > 0 ? Number(maxConnRows[0].Value) : null,
longestIdleInTransactionSeconds,
longestActiveQuerySeconds: toNullableNumber(proc.longest_active_query_seconds)
},
bufferCache: {
hitRatioPct: computeHitRatioPct(readRequests, reads),
blocksHit: readRequests - reads,
blocksRead: reads
},
...notes.length > 0 ? { notes } : {}
};
}
// src/connectors/mysql-family-introspection.ts
async function getSchemas(query) {
try {
const rows = await query(`
SELECT SCHEMA_NAME
FROM INFORMATION_SCHEMA.SCHEMATA
WHERE SCHEMA_NAME NOT IN ('information_schema', 'performance_schema', 'mysql', 'sys')
ORDER BY SCHEMA_NAME
`);
return rows.map((row) => row.SCHEMA_NAME);
} catch (error) {
console.error("Error getting schemas:", error);
throw error;
}
}
async function getTables(query, schema) {
try {
const schemaClause = schema ? "WHERE TABLE_SCHEMA = ?" : "WHERE TABLE_SCHEMA = DATABASE()";
const queryParams = schema ? [schema] : [];
const rows = await query(
`
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
${schemaClause}
AND TABLE_TYPE = 'BASE TABLE'
ORDER BY TABLE_NAME
`,
queryParams
);
return rows.map((row) => row.TABLE_NAME);
} catch (error) {
console.error("Error getting tables:", error);
throw error;
}
}
async function getViews(query, schema) {
try {
const schemaClause = schema ? "WHERE TABLE_SCHEMA = ?" : "WHERE TABLE_SCHEMA = DATABASE()";
const queryParams = schema ? [schema] : [];
const rows = await query(
`
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
${schemaClause}
AND TABLE_TYPE = 'VIEW'
ORDER BY TABLE_NAME
`,
queryParams
);
return rows.map((row) => row.TABLE_NAME);
} catch (error) {
console.error("Error getting views:", error);
throw error;
}
}
async function getTableIndexes(query, tableName, schema) {
try {
const schemaClause = schema ? "TABLE_SCHEMA = ?" : "TABLE_SCHEMA = DATABASE()";
const queryParams = schema ? [schema, tableName] : [tableName];
const indexRows = await query(
`
SELECT
INDEX_NAME,
COLUMN_NAME,
NON_UNIQUE,
SEQ_IN_INDEX
FROM
INFORMATION_SCHEMA.STATISTICS
WHERE
${schemaClause}
AND TABLE_NAME = ?
ORDER BY
INDEX_NAME,
SEQ_IN_INDEX
`,
queryParams
);
return groupIndexColumns(indexRows, (row) => ({
indexName: row.INDEX_NAME,
columnName: row.COLUMN_NAME,
isUnique: row.NON_UNIQUE === 0,
// In MySQL and MariaDB, NON_UNIQUE=0 means the index is unique
isPrimary: row.INDEX_NAME === "PRIMARY"
}));
} catch (error) {
console.error("Error getting table indexes:", error);
throw error;
}
}
async function getTableSchema(query, tableName, schema) {
try {
const schemaClause = schema ? "WHERE TABLE_SCHEMA = ?" : "WHERE TABLE_SCHEMA = DATABASE()";
const queryParams = schema ? [schema, tableName] : [tableName];
const rows = await query(
`
SELECT
COLUMN_NAME as column_name,
DATA_TYPE as data_type,
IS_NULLABLE as is_nullable,
COLUMN_DEFAULT as column_default,
COLUMN_COMMENT as description
FROM INFORMATION_SCHEMA.COLUMNS
${schemaClause}
AND TABLE_NAME = ?
ORDER BY ORDINAL_POSITION
`,
queryParams
);
return rows.map((row) => ({
...row,
description: row.description || null
}));
} catch (error) {
console.error("Error getting table schema:", error);
throw error;
}
}
async function getTableComment(query, tableName, schema) {
try {
const schemaClause = schema ? "WHERE TABLE_SCHEMA = ?" : "WHERE TABLE_SCHEMA = DATABASE()";
const queryParams = schema ? [schema, tableName] : [tableName];
const rows = await query(
`
SELECT TABLE_COMMENT
FROM INFORMATION_SCHEMA.TABLES
${schemaClause}
AND TABLE_NAME = ?
`,
queryParams
);
if (rows.length > 0) {
return rows[0].TABLE_COMMENT || null;
}
return null;
} catch (error) {
return null;
}
}
async function getStoredProcedures(query, schema, routineType) {
try {
const schemaClause = schema ? "WHERE ROUTINE_SCHEMA = ?" : "WHERE ROUTINE_SCHEMA = DATABASE()";
const queryParams = schema ? [schema] : [];
let typeFilter = "";
if (routineType === "function") {
typeFilter = " AND ROUTINE_TYPE = 'FUNCTION'";
} else if (routineType === "procedure") {
typeFilter = " AND ROUTINE_TYPE = 'PROCEDURE'";
}
const rows = await query(
`
SELECT ROUTINE_NAME
FROM INFORMATION_SCHEMA.ROUTINES
${schemaClause}${typeFilter}
ORDER BY ROUTINE_NAME
`,
queryParams
);
return rows.map((row) => row.ROUTINE_NAME);
} catch (error) {
console.error("Error getting stored procedures:", error);
throw error;
}
}
async function getStoredProcedureDetail(query, procedureName, schema) {
try {
const schemaClause = schema ? "WHERE r.ROUTINE_SCHEMA = ?" : "WHERE r.ROUTINE_SCHEMA = DATABASE()";
const queryParams = schema ? [schema, procedureName] : [procedureName];
const rows = await query(
`
SELECT
r.ROUTINE_NAME AS procedure_name,
CASE
WHEN r.ROUTINE_TYPE = 'PROCEDURE' THEN 'procedure'
ELSE 'function'
END AS procedure_type,
LOWER(r.ROUTINE_TYPE) AS routine_type,
r.ROUTINE_DEFINITION,
r.DTD_IDENTIFIER AS return_type,
(
SELECT GROUP_CONCAT(
CONCAT(p.PARAMETER_NAME, ' ', p.PARAMETER_MODE, ' ', p.DATA_TYPE)
ORDER BY p.ORDINAL_POSITION
SEPARATOR ', '
)
FROM INFORMATION_SCHEMA.PARAMETERS p
WHERE p.SPECIFIC_SCHEMA = r.ROUTINE_SCHEMA
AND p.SPECIFIC_NAME = r.ROUTINE_NAME
AND p.PARAMETER_NAME IS NOT NULL
) AS parameter_list
FROM INFORMATION_SCHEMA.ROUTINES r
${schemaClause}
AND r.ROUTINE_NAME = ?
`,
queryParams
);
if (rows.length === 0) {
const schemaName = schema || "current schema";
throw new Error(`Stored procedure '${procedureName}' not found in ${schemaName}`);
}
const procedure = rows[0];
let definition = procedure.ROUTINE_DEFINITION;
try {
const schemaValue = schema || await getCurrentSchema(query);
const quotedSchema = quoteIdentifier(schemaValue, "mysql");
const quotedProcName = quoteIdentifier(procedureName, "mysql");
if (procedure.procedure_type === "procedure") {
try {
const defRows = await query(`
SHOW CREATE PROCEDURE ${quotedSchema}.${quotedProcName}
`);
if (defRows && defRows.length > 0) {
definition = defRows[0]["Create Procedure"];
}
} catch (err) {
console.error(`Error getting procedure definition with SHOW CREATE: ${err}`);
}
} else {
try {
const defRows = await query(`
SHOW CREATE FUNCTION ${quotedSchema}.${quotedProcName}
`);
if (defRows && defRows.length > 0) {
definition = defRows[0]["Create Function"];
}
} catch (innerErr) {
console.error(`Error getting function definition with SHOW CREATE: ${innerErr}`);
}
}
if (!definition) {
const bodyRows = await query(
`
SELECT ROUTINE_DEFINITION, ROUTINE_BODY
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_SCHEMA = ? AND ROUTINE_NAME = ?
`,
[schemaValue, procedureName]
);
if (bodyRows && bodyRows.length > 0) {
if (bodyRows[0].ROUTINE_DEFINITION) {
definition = bodyRows[0].ROUTINE_DEFINITION;
} else if (bodyRows[0].ROUTINE_BODY) {
definition = bodyRows[0].ROUTINE_BODY;
}
}
}
} catch (error) {
console.error(`Error getting procedure/function details: ${error}`);
}
return {
procedure_name: procedure.procedure_name,
procedure_type: procedure.procedure_type,
language: "sql",
// MySQL/MariaDB procedures are generally in SQL
parameter_list: procedure.parameter_list || "",
return_type: procedure.routine_type === "function" ? procedure.return_type : void 0,
definition: definition || void 0
};
} catch (error) {
console.error("Error getting stored procedure detail:", error);
throw error;
}
}
async function getCurrentSchema(query) {
const rows = await query("SELECT DATABASE() AS DB");
return rows[0].DB;
}
async function getDefaultSchema(query) {
const rows = await query("SELECT DATABASE() AS DB");
return rows[0]?.DB ?? null;
}
// src/utils/multi-statement-result-parser.ts
function columnName(field) {
const name = typeof field?.name === "function" ? field.name() : field?.name;
return typeof name === "string" ? name : String(name ?? "");
}
function toObjectRows(rows, fields) {
if (!Array.isArray(fields) || !rows.some(Array.isArray)) {
return rows;
}
return objectRows(fields.map(columnName), rows);
}
function isMetadataObject(element) {
if (!element || typeof element !== "object" || Array.isArray(element)) {
return false;
}
return "affectedRows" in element || "insertId" in element || "fieldCount" in element || "warningStatus" in element;
}
function isMultiStatementResult(results, fields) {
if (!Array.isArray(results) || results.length === 0) {
return false;
}
const firstElement = results[0];
if (isMetadataObject(firstElement)) {
return true;
}
if (!Array.isArray(firstElement)) {
return false;
}
if (fields === void 0) {
return true;
}
return fields.every((entry) => entry == null || Array.isArray(entry));
}
function buildResultSetsFromMultiStatement(results, statementTexts, fields) {
const sql = statementTexts?.length === results.length ? statementTexts : void 0;
return results.map((result, index) => {
if (Array.isArray(result)) {
const rows = toObjectRows(result, fields?.[index]);
return { sql: sql?.[index], rows, rowCount: rows.length };
}
if (isMetadataObject(result)) {
return { sql: sql?.[index], rows: [], rowCount: result.affectedRows || 0 };
}
return { sql: sql?.[index], rows: [], rowCount: 0 };
});
}
function parseQueryResultSets(results, statementTexts, fields) {
const singleStatementSql = statementTexts?.length === 1 ? statementTexts[0] : void 0;
if (isMetadataObject(results)) {
return [{ sql: singleStatementSql, rows: [], rowCount: results.affectedRows || 0 }];
}
if (!Array.isArray(results)) {
return [{ sql: singleStatementSql, rows: [], rowCount: 0 }];
}
if (isMultiStatementResult(results, fields)) {
return buildResultSetsFromMultiStatement(results, statementTexts, fields);
}
const rows = toObjectRows(results, fields);
return [{ sql: singleStatementSql, rows, rowCount: rows.length }];
}
// src/connectors/mysql-family-connector.ts
var MySQLFamilyConnector = class {
constructor() {
// Source ID is set by ConnectorManager after cloning
this.sourceId = "default";
}
getId() {
return this.sourceId;
}
async getSchemas() {
return getSchemas(this.requireQuery());
}
async getTables(schema) {
return getTables(this.requireQuery(), schema);
}
async getViews(schema) {
return getViews(this.requireQuery(), schema);
}
async getTableIndexes(tableName, schema) {
return getTableIndexes(this.requireQuery(), tableName, schema);
}
async getTableSchema(tableName, schema) {
return getTableSchema(this.requireQuery(), tableName, schema);
}
async getTableComment(tableName, schema) {
return getTableComment(this.requireQuery(), tableName, schema);
}
async getHealthCheck() {
return getMySQLFamilyHealthCheck(this.requireQuery());
}
async getStoredProcedures(schema, routineType) {
return getStoredProcedures(this.requireQuery(), schema, routineType);
}
async getStoredProcedureDetail(procedureName, schema) {
return getStoredProcedureDetail(this.requireQuery(), procedureName, schema);
}
async getDefaultSchema() {
return getDefaultSchema(this.requireQuery());
}
/**
* Run a statement batch the way both drivers need it run: split it, apply
* the row cap (with a truncation probe row) to each statement, send the
* rewritten batch in one round trip, and turn what comes back into one
* result set per statement.
*
* `runQuery` issues the rewritten SQL on the caller's dedicated connection
* and resolves to `[results, fields]` as fetched positionally — rows as
* arrays with the column metadata alongside — so parseQueryResultSets can
* rebuild them under unique column names (bytebase/dbhub#484).
*/
async executeStatements(sql, options, runQuery) {
const statements = splitSQLStatements(sql, this.id);
let processedSQL = sql;
let probes = [];
if (options.maxRows) {
const rewrites = statements.map(
(statement) => SQLRowLimiter.applyMaxRowsWithTruncationProbe(statement, options.maxRows, this.id)
);
probes = rewrites.map((rewrite) => rewrite.probeApplied);
processedSQL = rewrites.map((rewrite) => rewrite.sql).join("; ");
if (sql.trim().endsWith(";")) {
processedSQL += ";";
}
}
const [results, fields] = await runQuery(processedSQL);
const resultSets = parseQueryResultSets(results, statements, fields);
if (resultSets.length === probes.length) {
resultSets.forEach(
(set, index) => SQLRowLimiter.flagTruncation(set, options.maxRows, probes[index])
);
}
return { resultSets };
}
};
// src/connectors/mysql-family-ssl.ts
var MYSQL_FAMILY_SSL_MODES = ["disable", "require", "verify-ca", "verify-full"];
function parseMySQLFamilySslMode(value) {
if (!MYSQL_FAMILY_SSL_MODES.includes(value)) {
throw new Error(
`Unsupported sslmode '${value}'. Valid values: ${MYSQL_FAMILY_SSL_MODES.join(", ")}`
);
}
return value;
}
function readMySQLFamilySslMode(dsn) {
return rawQueryParamValues(dsn, "sslmode").map(parseMySQLFamilySslMode).at(-1);
}
// src/utils/dsn-database.ts
var MissingDatabaseError = class extends Error {
constructor(message) {
super(message);
this.name = "MissingDatabaseError";
}
};
function requireDatabaseInDSN(database, dsn, label) {
if (database) {
return;
}
throw new MissingDatabaseError(
`${label} DSN must name a database.
Provided: ${obfuscateDSNPassword(dsn)}
Add the database to the DSN, e.g. ...:3306/mydb
To work with several databases, define one [[sources]] entry per database in a TOML config file: https://dbhub.ai/config/toml`
);
}
// src/utils/server-flavor.ts
function isTiDBVersion(version) {
return typeof version === "string" && /tidb/i.test(version);
}
function isDorisVersionComment(versionComment) {
return typeof versionComment === "string" && /^\s*doris\b/i.test(versionComment);
}
// src/utils/readonly-transaction.ts
var MARIADB_READ_ONLY_BACKSTOP = {
kind: "session",
variable: "tx_read_only"
};
function detectReadOnlyBackstop(version, versionComment) {
if (isDorisVersionComment(versionComment)) {
return { kind: "none" };
}
if (isTiDBVersion(version)) {
return { kind: "rollback" };
}
return { kind: "session", variable: readOnlyVariableFor(version) };
}
function readOnlyVariableFor(version) {
if (typeof version !== "string") {
return "transaction_read_only";
}
if (/mariadb/i.test(version)) {
return "tx_read_only";
}
const match = /^(\d+)\.(\d+)\.(\d+)/.exec(version);
if (match) {
const [major, minor, patch] = match.slice(1).map(Number);
const before5720 = major < 5 || major === 5 && (minor < 7 || minor === 7 && patch < 20);
if (before5720) {
return "tx_read_only";
}
}
return "transaction_read_only";
}
var VERSION_COMMENT_QUERY = "SELECT @@version_comment AS version_comment";
function noBackstopWarning(sourceId) {
return `MySQL source "${sourceId}": Apache Doris detected. Doris cannot run queries inside a read-only transaction, so read-only tools on this source are enforced by SQL validation alone. Connect with a least-privilege, read-only database account.`;
}
function readOnlyFlagQuery(variable) {
return `SELECT @@session.${variable} AS ro`;
}
var READ_ONLY_OPEN = "SET SESSION TRANSACTION READ ONLY; START TRANSACTION READ ONLY";
function readOnlyClose(variable, end, saved) {
return `${end}; SET SESSION ${variable} = ${saved}`;
}
var TIDB_OPEN = "START TRANSACTION";
var TIDB_CLOSE = "ROLLBACK";
async function readFlag(conn, variable) {
const result = await conn.query(readOnlyFlagQuery(variable));
const rows = Array.isArray(result) && Array.isArray(result[0]) ? result[0] : result;
const value = parseFlag(rows?.[0]?.ro);
if (value === void 0) {
throw new Error(`Could not read @@session.${variable} before a read-only execution`);
}
return value;
}
function parseFlag(raw) {
if (raw === 0 || raw === 0n || raw === "0") return 0;
if (raw === 1 || raw === 1n || raw === "1") return 1;
return void 0;
}
async function withReadOnlyTransaction(conn, readonly, backstop, execute) {
if (!readonly || backstop.kind === "none") {
return execute();
}
let rollback = TIDB_CLOSE;
try {
let commit;
if (backstop.kind === "session") {
const saved = await readFlag(conn, backstop.variable);
rollback = readOnlyClose(backstop.variable, "ROLLBACK", saved);
commit = readOnlyClose(backstop.variable, "COMMIT", saved);
await conn.query(READ_ONLY_OPEN);
} else {
commit = TIDB_CLOSE;
await conn.query(TIDB_OPEN);
}
const result = await execute();
await conn.query(commit);
return result;
} catch (error) {
if (!isClientSideTimeout(error)) {
try {
await conn.query(rollback);
} catch {
}
}
throw error;
}
}
export {
MySQLFamilyConnector,
readMySQLFamilySslMode,
MissingDatabaseError,
requireDatabaseInDSN,
MARIADB_READ_ONLY_BACKSTOP,
detectReadOnlyBackstop,
VERSION_COMMENT_QUERY,
noBackstopWarning,
withReadOnlyTransaction
};