@bytebase/dbhub
Version:
Token-efficient database MCP server for PostgreSQL, MySQL, MariaDB, SQL Server, Oracle, ClickHouse, SQLite
419 lines (415 loc) • 14.6 kB
JavaScript
import {
quoteIdentifier
} from "./chunk-IGQAAKFF.js";
import {
SQLRowLimiter
} from "./chunk-5ACPKE4X.js";
import {
objectRows
} from "./chunk-SR7SSJAL.js";
import {
closeQuietly
} from "./chunk-CZ5B3EO3.js";
import "./chunk-7546W2OD.js";
import "./chunk-GZXZQJYW.js";
import {
ConnectorRegistry,
SQLITE_DSN_PREFIX,
SQLITE_MEMORY_PATH,
obfuscateDSNPassword,
resolveSqliteDsnPath,
splitSQLStatements,
stripCommentsAndStrings
} from "./chunk-HJNFFBF4.js";
// src/connectors/sqlite/index.ts
import fs from "fs";
import path from "path";
// src/connectors/sqlite/suppress-experimental-warning.ts
var installed = false;
function suppressSqliteExperimentalWarning() {
if (installed) {
return;
}
installed = true;
const originalEmitWarning = process.emitWarning.bind(process);
process.emitWarning = (warning, ...args) => {
const message = typeof warning === "string" ? warning : warning?.message;
if (message && message.includes("SQLite is an experimental feature")) {
return;
}
return originalEmitWarning(warning, ...args);
};
}
// src/connectors/sqlite/index.ts
var SQLiteDSNParser = class {
async parse(dsn, config) {
if (!this.isValidDSN(dsn)) {
const obfuscatedDSN = obfuscateDSNPassword(dsn);
const expectedFormat = this.getSampleDSN();
throw new Error(
`Invalid SQLite DSN format.
Provided: ${obfuscatedDSN}
Expected: ${expectedFormat}`
);
}
try {
return { dbPath: resolveSqliteDsnPath(dsn) };
} catch (error) {
throw new Error(
`Failed to parse SQLite DSN: ${error instanceof Error ? error.message : String(error)}`
);
}
}
getSampleDSN() {
return "sqlite:///path/to/database.db";
}
isValidDSN(dsn) {
return typeof dsn === "string" && dsn.startsWith(SQLITE_DSN_PREFIX);
}
};
function openFailure(dbPath, error, missingFileNote = "") {
const prefix = `Unable to open SQLite database file '${dbPath}'`;
const pathHint = "A SQLite DSN path is absolute after three slashes (sqlite:///path/to/database.db); write sqlite:///./database.db for a relative path.";
const directory = path.dirname(dbPath);
if (!fs.existsSync(directory)) {
return new Error(`${prefix}: directory '${directory}' does not exist. ${pathHint}`);
}
if (!fs.existsSync(dbPath)) {
return new Error(`${prefix}: the file does not exist.${missingFileNote} ${pathHint}`);
}
return new Error(`${prefix}: ${error instanceof Error ? error.message : String(error)}`, {
cause: error
});
}
var SQLiteConnector = class _SQLiteConnector {
constructor() {
this.id = "sqlite";
this.name = "SQLite";
this.dsnParser = new SQLiteDSNParser();
this.db = null;
this.dbPath = ":memory:";
// Default to in-memory database
// Source ID is set by ConnectorManager after cloning
this.sourceId = "default";
}
getId() {
return this.sourceId;
}
clone() {
return new _SQLiteConnector();
}
/**
* Prepare a user-facing query statement with BigInt reads enabled, so 64-bit
* integer values in the result rows keep full precision.
*
* better-sqlite3 exposed this connection-wide via `defaultSafeIntegers(true)`;
* `node:sqlite` only offers it per-statement via `setReadBigInts`. This is for
* `executeSQL` only — schema introspection reads small integer flags and uses
* `queryAll`/`queryOne` (plain numbers) so comparisons like `=== 1` work.
*/
prepare(sql) {
if (!this.db) {
throw new Error("Not connected to SQLite database");
}
const statement = this.db.prepare(sql);
statement.setReadBigInts(true);
return statement;
}
/**
* Reads every row of a prepared execute_sql statement as objects.
*
* node:sqlite's `all()` keys each row by column name, so a result with a
* repeated name (`SELECT 1 AS a, 2 AS a`) keeps only the last value
* (bytebase/dbhub#484). Where the runtime offers positional rows
* (`setReturnArrays`, with `columns()` for the names - Node 22.17+/24+),
* the rows are read that way and rebuilt under unique names, repeated ones
* suffixed `_1`, `_2`, ... (see result-columns.ts). Older runtimes fall
* back to the driver's own objects.
*/
readRows(statement, parameters) {
const positional = statement;
if (typeof positional.columns !== "function" || typeof positional.setReturnArrays !== "function") {
return statement.all(...parameters);
}
const names = positional.columns().map((column) => column.name);
positional.setReturnArrays(true);
return objectRows(names, statement.all(...parameters));
}
/**
* Run an introspection query and return all rows. Integers come back as plain
* numbers (no `setReadBigInts`), which is what the schema-reading callers need
* for boolean flag comparisons. node:sqlite types `.all()` as a generic record
* array, so the result is cast to the caller's expected row shape.
*/
queryAll(sql, ...params) {
if (!this.db) {
throw new Error("Not connected to SQLite database");
}
return this.db.prepare(sql).all(...params);
}
/** Run an introspection query and return a single row (or undefined). */
queryOne(sql, ...params) {
if (!this.db) {
throw new Error("Not connected to SQLite database");
}
return this.db.prepare(sql).get(...params);
}
/**
* Connect to SQLite database
* Note: SQLite does not support connection timeouts as it's a local file-based database.
* The config parameter is accepted for interface compliance but ignored.
*/
async connect(dsn, initScript, config) {
const parsedConfig = await this.dsnParser.parse(dsn, config);
this.dbPath = parsedConfig.dbPath;
const isMemory = this.dbPath === SQLITE_MEMORY_PATH;
suppressSqliteExperimentalWarning();
const { DatabaseSync } = await import("node:sqlite");
const dbOptions = {
// node:sqlite enables foreign key constraints by default, whereas
// better-sqlite3 (and SQLite's own default) leaves them off. Preserve
// the historical behavior; callers can opt in via `PRAGMA foreign_keys = ON`.
enableForeignKeyConstraints: false
};
if (config?.readonly && !isMemory) {
dbOptions.readOnly = true;
}
const existed = isMemory || fs.existsSync(this.dbPath);
if (!existed && config?.requireExistingFile) {
throw openFailure(
this.dbPath,
void 0,
" It was not created because no tool on this source can write to it."
);
}
try {
this.db = new DatabaseSync(this.dbPath, dbOptions);
} catch (error) {
throw openFailure(this.dbPath, error);
}
if (!existed) {
console.error(
`Warning: SQLite database file '${this.dbPath}' did not exist; created a new, empty database.`
);
}
try {
if (initScript) {
this.db.exec(initScript);
}
} catch (error) {
const db = this.db;
this.db = null;
await closeQuietly(() => db.close());
console.error("Failed to connect to SQLite database:", error);
throw error;
}
}
async disconnect() {
if (this.db) {
try {
const inTransaction = this.db.isTransaction;
if (!inTransaction) {
this.db.close();
} else {
try {
this.db.exec("ROLLBACK");
} catch (rollbackError) {
}
this.db.close();
}
this.db = null;
} catch (error) {
console.error("Error during SQLite disconnect:", error);
this.db = null;
}
}
return Promise.resolve();
}
async getSchemas() {
if (!this.db) {
throw new Error("Not connected to SQLite database");
}
return ["main"];
}
async getTables(schema) {
if (!this.db) {
throw new Error("Not connected to SQLite database");
}
const rows = this.queryAll(`
SELECT name FROM sqlite_master
WHERE type='table' AND name NOT LIKE 'sqlite_%'
ORDER BY name
`);
return rows.map((row) => row.name);
}
async getViews(schema) {
if (!this.db) {
throw new Error("Not connected to SQLite database");
}
const rows = this.queryAll(`
SELECT name FROM sqlite_master
WHERE type='view' AND name NOT LIKE 'sqlite_%'
ORDER BY name
`);
return rows.map((row) => row.name);
}
async getTableIndexes(tableName, schema) {
if (!this.db) {
throw new Error("Not connected to SQLite database");
}
const indexInfoRows = this.queryAll(
`
SELECT
name as index_name,
0 as is_unique
FROM sqlite_master
WHERE type = 'index'
AND tbl_name = ?
`,
tableName
);
const quotedTableName = quoteIdentifier(tableName, "sqlite");
const indexListRows = this.queryAll(
`PRAGMA index_list(${quotedTableName})`
);
const indexUniqueMap = /* @__PURE__ */ new Map();
for (const indexListRow of indexListRows) {
indexUniqueMap.set(indexListRow.name, indexListRow.unique === 1);
}
const tableInfo = this.queryAll(`PRAGMA table_info(${quotedTableName})`);
const pkColumns = tableInfo.filter((col) => col.pk > 0).map((col) => col.name);
const results = [];
for (const indexInfo of indexInfoRows) {
const quotedIndexName = quoteIdentifier(indexInfo.index_name, "sqlite");
const indexDetailRows = this.queryAll(
`PRAGMA index_info(${quotedIndexName})`
);
const columnNames = indexDetailRows.map((row) => row.name);
results.push({
index_name: indexInfo.index_name,
column_names: columnNames,
is_unique: indexUniqueMap.get(indexInfo.index_name) || false,
is_primary: false
});
}
if (pkColumns.length > 0) {
results.push({
index_name: "PRIMARY",
column_names: pkColumns,
is_unique: true,
is_primary: true
});
}
return results;
}
async getTableSchema(tableName, schema) {
if (!this.db) {
throw new Error("Not connected to SQLite database");
}
const quotedTableName = quoteIdentifier(tableName, "sqlite");
const rows = this.queryAll(
`PRAGMA table_xinfo(${quotedTableName})`
).filter((row) => row.hidden !== 1);
const columns = rows.map((row) => ({
column_name: row.name,
data_type: row.type,
// In SQLite, primary key columns are automatically NOT NULL even if notnull=0
is_nullable: row.notnull === 1 || row.pk > 0 ? "NO" : "YES",
column_default: row.dflt_value,
description: null
}));
return columns;
}
async getStoredProcedures(schema, routineType) {
if (!this.db) {
throw new Error("Not connected to SQLite database");
}
return [];
}
async getStoredProcedureDetail(procedureName, schema) {
if (!this.db) {
throw new Error("Not connected to SQLite database");
}
throw new Error(
"SQLite does not support stored procedures. Functions are defined programmatically through the SQLite API, not stored in the database."
);
}
/**
* Whether a statement returns rows (and so must run via `all()` rather than
* `run()`).
*
* The prepared statement's own column list is the driver's answer and is
* used where the runtime exposes it (`columns()`, Node 22.17+/24+): it covers
* every pragma that reports a value (`PRAGMA user_version`,
* `PRAGMA table_xinfo(t)`, ...) and `INSERT ... RETURNING`, none of which a
* keyword list can enumerate.
*
* The keyword check stays as the fallback for older supported runtimes
* (Node 22.5 - 22.16 have no `columns()`) and for statements that have always
* been read through `all()` despite having no columns (ANALYZE). It is
* classified on the comment/string-stripped text so a leading attribution
* comment cannot hide a SELECT, matching the row limiter and the read-only
* classifier. Every PRAGMA counts: `all()` runs a pragma that reports nothing
* just as well, returning no rows. A DML statement counts when it carries a
* RETURNING clause; the stripped text has no strings, comments or quoted
* identifiers left, so the word can only be the keyword.
*/
returnsRows(prepared, statement) {
const withColumns = prepared;
if (typeof withColumns.columns === "function" && withColumns.columns().length > 0) {
return true;
}
const stripped = stripCommentsAndStrings(statement, "sqlite").toLowerCase().trim();
return stripped.startsWith("select") || stripped.startsWith("with") || stripped.startsWith("explain") || stripped.startsWith("analyze") || stripped.startsWith("pragma") || /^(?:insert|update|delete|replace)\b/.test(stripped) && /\breturning\b/.test(stripped);
}
async executeSQL(sql, options, parameters) {
if (!this.db) {
throw new Error("Not connected to SQLite database");
}
if (options.readonly) {
this.db.exec("PRAGMA query_only = ON");
}
try {
const statements = splitSQLStatements(sql, "sqlite");
const isSingleStatement = statements.length === 1;
if (!isSingleStatement && parameters && parameters.length > 0) {
throw new Error("Parameters are not supported for multi-statement queries in SQLite");
}
const statementParameters = isSingleStatement ? parameters ?? [] : [];
const resultSets = [];
for (const statement of statements) {
if (options.readonly) {
this.db.exec("PRAGMA query_only = ON");
}
const { sql: processedStatement, probeApplied } = SQLRowLimiter.applyMaxRowsWithTruncationProbe(
statement,
options.maxRows,
"sqlite"
);
const prepared = this.prepare(processedStatement);
if (this.returnsRows(prepared, statement)) {
const rows = this.readRows(prepared, statementParameters);
const resultSet = { sql: statement, rows, rowCount: rows.length };
SQLRowLimiter.flagTruncation(resultSet, options.maxRows, probeApplied);
resultSets.push(resultSet);
} else {
const result = prepared.run(...statementParameters);
resultSets.push({ sql: statement, rows: [], rowCount: Number(result.changes) });
}
}
return { resultSets };
} finally {
if (options.readonly) {
try {
this.db.exec("PRAGMA query_only = OFF");
} catch {
}
}
}
}
};
var sqliteConnector = new SQLiteConnector();
ConnectorRegistry.register(sqliteConnector);
export {
SQLiteConnector
};