@bytebase/dbhub
Version:
Token-efficient database MCP server for PostgreSQL, MySQL, MariaDB, SQL Server, Oracle, ClickHouse, SQLite
770 lines (764 loc) • 24.3 kB
JavaScript
// src/connectors/interface.ts
var ConnectorRegistry = class _ConnectorRegistry {
static {
this.connectors = /* @__PURE__ */ new Map();
}
/**
* Register a new connector
*/
static register(connector) {
_ConnectorRegistry.connectors.set(connector.id, connector);
}
/**
* Get connector for a DSN string
* Tries to find a connector that can handle the given DSN format
*/
static getConnectorForDSN(dsn) {
for (const connector of _ConnectorRegistry.connectors.values()) {
if (connector.dsnParser.isValidDSN(dsn)) {
return connector;
}
}
return null;
}
/**
* Get all available sample DSNs
*/
static getAllSampleDSNs() {
const samples = {};
for (const [id, connector] of _ConnectorRegistry.connectors.entries()) {
samples[id] = connector.dsnParser.getSampleDSN();
}
return samples;
}
};
// src/utils/safe-url.ts
var SafeURL = class {
/**
* Parse a URL and handle special characters in passwords
* This is a safe alternative to the URL constructor
*
* @param urlString - The DSN string to parse
*/
constructor(urlString) {
this.protocol = "";
this.hostname = "";
this.port = "";
this.pathname = "";
this.username = "";
this.password = "";
this.searchParams = /* @__PURE__ */ new Map();
if (!urlString || urlString.trim() === "") {
throw new Error("URL string cannot be empty");
}
try {
const protocolSeparator = urlString.indexOf("://");
if (protocolSeparator !== -1) {
this.protocol = urlString.substring(0, protocolSeparator + 1);
urlString = urlString.substring(protocolSeparator + 3);
} else {
throw new Error('Invalid URL format: missing protocol (e.g., "mysql://")');
}
const questionMarkIndex = urlString.indexOf("?");
let queryParams = "";
if (questionMarkIndex !== -1) {
queryParams = urlString.substring(questionMarkIndex + 1);
urlString = urlString.substring(0, questionMarkIndex);
queryParams.split("&").forEach((pair) => {
const eq = pair.indexOf("=");
if (eq === -1) {
return;
}
const key = pair.substring(0, eq);
const value = pair.substring(eq + 1);
if (key && value) {
this.searchParams.set(key, decodeURIComponent(value));
}
});
}
const pathStart = urlString.indexOf("/");
const authorityEnd = pathStart === -1 ? urlString.length : pathStart;
const atIndex = urlString.lastIndexOf("@", authorityEnd - 1);
if (atIndex !== -1) {
const auth = urlString.substring(0, atIndex);
urlString = urlString.substring(atIndex + 1);
const colonIndex = auth.indexOf(":");
if (colonIndex !== -1) {
this.username = auth.substring(0, colonIndex);
this.password = auth.substring(colonIndex + 1);
this.username = decodeURIComponent(this.username);
this.password = decodeURIComponent(this.password);
} else {
this.username = auth;
}
}
const pathSeparatorIndex = urlString.indexOf("/");
if (pathSeparatorIndex !== -1) {
this.pathname = urlString.substring(pathSeparatorIndex);
urlString = urlString.substring(0, pathSeparatorIndex);
}
if (urlString.startsWith("[")) {
const ipv6Host = /^\[([^\]]+)\](?::(.*))?$/.exec(urlString);
if (!ipv6Host) {
throw new Error("Invalid bracketed IPv6 host");
}
this.hostname = ipv6Host[1];
this.port = ipv6Host[2] ?? "";
} else {
const colonIndex = urlString.indexOf(":");
if (colonIndex !== -1) {
this.hostname = urlString.substring(0, colonIndex);
this.port = urlString.substring(colonIndex + 1);
} else {
this.hostname = urlString;
}
}
if (this.protocol === "") {
throw new Error("Invalid URL: protocol is required");
}
} catch (error) {
throw new Error(`Failed to parse URL: ${error instanceof Error ? error.message : String(error)}`);
}
}
/**
* Helper method to safely get a parameter from query string
*
* @param name - The parameter name to retrieve
* @returns The parameter value or null if not found
*/
getSearchParam(name) {
return this.searchParams.has(name) ? this.searchParams.get(name) : null;
}
/**
* Helper method to iterate over all parameters
*
* @param callback - Function to call for each parameter
*/
forEachSearchParam(callback) {
this.searchParams.forEach((value, key) => callback(value, key));
}
};
function replaceDSNHostPort(dsn, host, port) {
const protocolSeparator = dsn.indexOf("://");
if (protocolSeparator === -1) {
throw new Error('Invalid URL format: missing protocol (e.g., "mysql://")');
}
const authorityStart = protocolSeparator + 3;
const queryStart = dsn.indexOf("?", authorityStart);
const beforeQuery = queryStart === -1 ? dsn.length : queryStart;
const pathStart = dsn.indexOf("/", authorityStart);
const authorityEnd = pathStart === -1 || pathStart > beforeQuery ? beforeQuery : pathStart;
const atIndex = dsn.lastIndexOf("@", authorityEnd - 1);
const hostStart = atIndex >= authorityStart ? atIndex + 1 : authorityStart;
const bracketedHost = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
return `${dsn.slice(0, hostStart)}${bracketedHost}:${port}${dsn.slice(authorityEnd)}`;
}
function rawQueryParamValues(dsn, name) {
const queryStart = dsn.indexOf("?");
if (queryStart === -1) {
return [];
}
return new URLSearchParams(dsn.substring(queryStart + 1)).getAll(name);
}
// src/utils/sqlite-dsn.ts
import { homedir } from "os";
import path from "path";
var SQLITE_DSN_PREFIX = "sqlite://";
var SQLITE_MEMORY_PATH = ":memory:";
var WINDOWS_DRIVE_PATH = /^[A-Za-z]:[\\/]/;
var EXPLICITLY_RELATIVE_PATH = /^(\.\.?|~)([\\/]|$)/;
var UNC_PATH = /^(\/\/|\\\\)/;
function escapePath(filePath) {
return filePath.replace(/%/g, "%25").replace(/\?/g, "%3F");
}
function unescapePath(filePath) {
return filePath.replace(/%(25|3F)/gi, (escape) => escape === "%25" ? "%" : "?");
}
function overridesRoot(afterSlash) {
return afterSlash.startsWith("/") || UNC_PATH.test(afterSlash) || WINDOWS_DRIVE_PATH.test(afterSlash) || EXPLICITLY_RELATIVE_PATH.test(afterSlash);
}
function splitQuery(dsn) {
const queryStart = dsn.indexOf("?");
return queryStart === -1 ? { body: dsn, query: "" } : { body: dsn.substring(0, queryStart), query: dsn.substring(queryStart) };
}
function parseSqliteDsnPath(dsn) {
if (!dsn.startsWith(SQLITE_DSN_PREFIX)) {
throw new Error(`not a SQLite DSN (expected it to start with "${SQLITE_DSN_PREFIX}")`);
}
const rest = splitQuery(dsn).body.substring(SQLITE_DSN_PREFIX.length);
if (rest === SQLITE_MEMORY_PATH || rest === `/${SQLITE_MEMORY_PATH}`) {
return SQLITE_MEMORY_PATH;
}
const written = rest.startsWith("/") && overridesRoot(rest.substring(1)) ? rest.substring(1) : rest;
if (written === "" || written === "/") {
throw new Error("the DSN does not name a database file");
}
return unescapePath(written);
}
function resolveSqliteFilePath(database, baseDir = process.cwd()) {
if (database === SQLITE_MEMORY_PATH) {
return database;
}
const expanded = /^~[\\/]/.test(database) ? path.join(homedir(), database.substring(2)) : database;
if (path.isAbsolute(expanded) || WINDOWS_DRIVE_PATH.test(expanded)) {
return expanded;
}
return path.resolve(baseDir, expanded);
}
function resolveSqliteDsnPath(dsn, baseDir = process.cwd()) {
return resolveSqliteFilePath(parseSqliteDsnPath(dsn), baseDir);
}
function buildSqliteDSN(database) {
if (database === SQLITE_MEMORY_PATH) {
return `${SQLITE_DSN_PREFIX}/${SQLITE_MEMORY_PATH}`;
}
const escaped = escapePath(database);
const afterSlash = escaped.substring(1);
const readsAsRooted = escaped.startsWith("/") && !overridesRoot(afterSlash) && afterSlash !== SQLITE_MEMORY_PATH;
return readsAsRooted ? `${SQLITE_DSN_PREFIX}${escaped}` : `${SQLITE_DSN_PREFIX}/${escaped}`;
}
function normalizeSqliteDsn(dsn, baseDir = process.cwd()) {
return buildSqliteDSN(resolveSqliteDsnPath(dsn, baseDir)) + splitQuery(dsn).query;
}
// src/utils/dsn-obfuscate.ts
function parseConnectionInfoFromDSN(dsn) {
if (!dsn) {
return null;
}
try {
const type = getDatabaseTypeFromDSN(dsn);
if (typeof type === "undefined") {
return null;
}
if (type === "sqlite") {
try {
return { type, database: parseSqliteDsnPath(dsn) };
} catch {
return { type };
}
}
const url = new SafeURL(dsn);
const info = { type };
if (url.hostname) {
info.host = url.hostname;
}
if (url.port) {
info.port = parseInt(url.port, 10);
}
if (url.pathname && url.pathname.length > 1) {
info.database = url.pathname.substring(1);
}
if (url.username) {
info.user = url.username;
}
return info;
} catch {
return null;
}
}
var REDACTED_DSN = "<redacted DSN>";
var SECRET_QUERY_PARAM = /password/i;
function decodeLoosely(value) {
try {
return decodeURIComponent(value);
} catch {
return value;
}
}
function maskSecretQueryParams(rawQuery) {
let hasSecretParam = false;
const pairs = rawQuery.split("&").map((pair) => {
const eq = pair.indexOf("=");
if (eq === -1) {
return pair;
}
const key = pair.substring(0, eq);
const value = pair.substring(eq + 1);
if (!value || !(SECRET_QUERY_PARAM.test(key) || SECRET_QUERY_PARAM.test(decodeLoosely(key)))) {
return pair;
}
hasSecretParam = true;
return `${key}=${"*".repeat(Math.min(decodeLoosely(value).length, 8))}`;
});
return { query: pairs.join("&"), hasSecretParam };
}
function obfuscateDSNPassword(dsn) {
if (!dsn) {
return dsn;
}
try {
const type = getDatabaseTypeFromDSN(dsn);
if (type === "sqlite") {
return dsn;
}
const url = new SafeURL(dsn);
if (url.port && !/^\d+$/.test(url.port)) {
return REDACTED_DSN;
}
const queryStart = dsn.indexOf("?");
const rawQuery = queryStart === -1 ? "" : dsn.substring(queryStart + 1);
const { query, hasSecretParam } = maskSecretQueryParams(rawQuery);
if (!url.password && !hasSecretParam) {
return dsn;
}
const protocol = dsn.split(":")[0];
const host = url.hostname.includes(":") ? `[${url.hostname}]` : url.hostname;
let userinfo = url.username;
if (url.password) {
const obfuscatedPassword = "*".repeat(Math.min(url.password.length, 8));
userinfo = url.username ? `${url.username}:${obfuscatedPassword}` : obfuscatedPassword;
}
let result = userinfo ? `${protocol}://${userinfo}@${host}` : `${protocol}://${host}`;
if (url.port) {
result += `:${url.port}`;
}
result += url.pathname;
if (rawQuery) {
result += `?${query}`;
}
return result;
} catch {
return REDACTED_DSN;
}
}
function getDatabaseTypeFromDSN(dsn) {
if (!dsn) {
return void 0;
}
const protocol = dsn.split(":")[0];
return protocolToConnectorType(protocol);
}
function protocolToConnectorType(protocol) {
const mapping = {
"postgres": "postgres",
"postgresql": "postgres",
"mysql": "mysql",
"mariadb": "mariadb",
"sqlserver": "sqlserver",
"sqlite": "sqlite",
"oracle": "oracle",
"clickhouse": "clickhouse"
};
return mapping[protocol];
}
function getDefaultPortForType(type, sslmode) {
const ports = {
"postgres": 5432,
"mysql": 3306,
"mariadb": 3306,
"sqlserver": 1433,
"oracle": 1521,
"clickhouse": sslmode === "require" || sslmode === "verify-full" ? 8443 : 8123,
"sqlite": void 0
};
return ports[type];
}
// src/utils/sql-parser.ts
var TokenType = { Plain: 0, Comment: 1, QuotedBlock: 2 };
function plainToken(i) {
return { type: TokenType.Plain, end: i + 1 };
}
function scanSingleLineComment(sql, i) {
if (sql[i] !== "-" || sql[i + 1] !== "-") {
return null;
}
let j = i;
while (j < sql.length && sql[j] !== "\n") {
j++;
}
return { type: TokenType.Comment, end: j };
}
function scanSingleLineCommentMySQL(sql, i) {
if (sql[i] !== "-" || sql[i + 1] !== "-") {
return null;
}
const next = sql[i + 2];
if (next !== void 0 && next.charCodeAt(0) > 32 && next.charCodeAt(0) !== 127) {
return null;
}
let j = i;
while (j < sql.length && sql[j] !== "\n") {
j++;
}
return { type: TokenType.Comment, end: j };
}
function scanMultiLineComment(sql, i) {
if (sql[i] !== "/" || sql[i + 1] !== "*") {
return null;
}
let j = i + 2;
while (j < sql.length && !(sql[j] === "*" && sql[j + 1] === "/")) {
j++;
}
if (j < sql.length) {
j += 2;
}
return { type: TokenType.Comment, end: j };
}
function scanMultiLineCommentMySQL(sql, i) {
if (sql[i] !== "/" || sql[i + 1] !== "*") {
return null;
}
const next = sql[i + 2];
const nextNext = sql[i + 3];
if (next === "!" || next === "M" && nextNext === "!") {
return null;
}
return scanMultiLineComment(sql, i);
}
function scanNestedMultiLineComment(sql, i) {
if (sql[i] !== "/" || sql[i + 1] !== "*") {
return null;
}
let j = i + 2;
let depth = 1;
while (j < sql.length && depth > 0) {
if (sql[j] === "/" && sql[j + 1] === "*") {
depth++;
j += 2;
} else if (sql[j] === "*" && sql[j + 1] === "/") {
depth--;
j += 2;
} else {
j++;
}
}
return { type: TokenType.Comment, end: j };
}
function scanSingleQuotedString(sql, i) {
if (sql[i] !== "'") {
return null;
}
let j = i + 1;
while (j < sql.length) {
if (sql[j] === "'" && sql[j + 1] === "'") {
j += 2;
} else if (sql[j] === "'") {
j++;
break;
} else {
j++;
}
}
return { type: TokenType.QuotedBlock, end: j };
}
function scanDoubleQuotedString(sql, i) {
if (sql[i] !== '"') {
return null;
}
let j = i + 1;
while (j < sql.length) {
if (sql[j] === '"' && sql[j + 1] === '"') {
j += 2;
} else if (sql[j] === '"') {
j++;
break;
} else {
j++;
}
}
return { type: TokenType.QuotedBlock, end: j };
}
function scanBackslashQuoted(sql, i, quote) {
let j = i + 1;
while (j < sql.length) {
if (sql[j] === "\\") {
j += 2;
} else if (sql[j] === quote && sql[j + 1] === quote) {
j += 2;
} else if (sql[j] === quote) {
j++;
break;
} else {
j++;
}
}
return { type: TokenType.QuotedBlock, end: Math.min(j, sql.length) };
}
function scanSingleQuotedStringBackslash(sql, i) {
return sql[i] === "'" ? scanBackslashQuoted(sql, i, "'") : null;
}
function scanDoubleQuotedStringBackslash(sql, i) {
return sql[i] === '"' ? scanBackslashQuoted(sql, i, '"') : null;
}
function scanPostgresEscapeString(sql, i) {
if (sql[i] !== "e" && sql[i] !== "E" || sql[i + 1] !== "'") {
return null;
}
const prev = i > 0 ? sql[i - 1] : "";
if (/[\w$]/.test(prev) || prev.charCodeAt(0) > 127) {
return null;
}
let token = scanBackslashQuoted(sql, i + 1, "'");
for (let next = continuedQuote(sql, token.end); next !== -1; next = continuedQuote(sql, token.end)) {
token = scanBackslashQuoted(sql, next, "'");
}
return token;
}
function continuedQuote(sql, j) {
const isNewline = (ch) => ch === "\n" || ch === "\r";
const skipComment = (k) => {
while (k < sql.length && !isNewline(sql[k])) {
k++;
}
return k;
};
while (j < sql.length) {
const ch = sql[j];
if (ch === " " || ch === " " || ch === "\f" || ch === "\v") {
j++;
} else if (ch === "-" && sql[j + 1] === "-") {
j = skipComment(j);
} else {
break;
}
}
if (j >= sql.length || !isNewline(sql[j])) {
return -1;
}
while (j < sql.length) {
const ch = sql[j];
if (ch === " " || ch === " " || ch === "\f" || ch === "\v" || isNewline(ch)) {
j++;
} else if (ch === "-" && sql[j + 1] === "-") {
j = skipComment(j);
if (j >= sql.length) {
return -1;
}
} else {
break;
}
}
return sql[j] === "'" ? j : -1;
}
var dollarQuoteOpenRegex = /^\$([a-zA-Z_]\w*)?\$/;
function scanDollarQuotedBlock(sql, i) {
if (sql[i] !== "$") {
return null;
}
const next = sql[i + 1];
if (next >= "0" && next <= "9") {
return null;
}
const remaining = sql.substring(i);
const m = dollarQuoteOpenRegex.exec(remaining);
if (!m) {
return null;
}
const tag = m[0];
const bodyStart = i + tag.length;
const closeIdx = sql.indexOf(tag, bodyStart);
const end = closeIdx !== -1 ? closeIdx + tag.length : sql.length;
return { type: TokenType.QuotedBlock, end };
}
function scanBacktickQuotedIdentifier(sql, i) {
if (sql[i] !== "`") {
return null;
}
let j = i + 1;
while (j < sql.length) {
if (sql[j] === "`" && sql[j + 1] === "`") {
j += 2;
} else if (sql[j] === "`") {
j++;
break;
} else {
j++;
}
}
return { type: TokenType.QuotedBlock, end: j };
}
function scanBracketQuotedIdentifier(sql, i) {
if (sql[i] !== "[") {
return null;
}
let j = i + 1;
while (j < sql.length) {
if (sql[j] === "]" && sql[j + 1] === "]") {
j += 2;
} else if (sql[j] === "]") {
j++;
break;
} else {
j++;
}
}
return { type: TokenType.QuotedBlock, end: j };
}
function scanTokenAnsi(sql, i) {
return scanSingleLineComment(sql, i) ?? scanMultiLineComment(sql, i) ?? scanSingleQuotedString(sql, i) ?? scanDoubleQuotedString(sql, i) ?? plainToken(i);
}
var postgresIdentifierRegex = /[A-Za-z_\u0080-][\w$\u0080-]*/y;
function scanPostgresIdentifier(sql, i) {
postgresIdentifierRegex.lastIndex = i;
return postgresIdentifierRegex.test(sql) ? { type: TokenType.Plain, end: postgresIdentifierRegex.lastIndex } : null;
}
function scanTokenPostgres(sql, i) {
return scanSingleLineComment(sql, i) ?? scanNestedMultiLineComment(sql, i) ?? scanPostgresEscapeString(sql, i) ?? scanPostgresIdentifier(sql, i) ?? scanSingleQuotedString(sql, i) ?? scanDoubleQuotedString(sql, i) ?? scanDollarQuotedBlock(sql, i) ?? plainToken(i);
}
function scanTokenMySQL(sql, i) {
return scanSingleLineCommentMySQL(sql, i) ?? scanMultiLineCommentMySQL(sql, i) ?? scanSingleQuotedStringBackslash(sql, i) ?? scanDoubleQuotedStringBackslash(sql, i) ?? scanBacktickQuotedIdentifier(sql, i) ?? plainToken(i);
}
function scanTokenMySQLAnsiQuotes(sql, i) {
return scanSingleLineCommentMySQL(sql, i) ?? scanMultiLineCommentMySQL(sql, i) ?? scanSingleQuotedStringBackslash(sql, i) ?? scanDoubleQuotedString(sql, i) ?? scanBacktickQuotedIdentifier(sql, i) ?? plainToken(i);
}
function scanTokenMySQLNoBackslashEscapes(sql, i) {
return scanSingleLineCommentMySQL(sql, i) ?? scanMultiLineCommentMySQL(sql, i) ?? scanSingleQuotedString(sql, i) ?? scanDoubleQuotedString(sql, i) ?? scanBacktickQuotedIdentifier(sql, i) ?? plainToken(i);
}
function scanTokenSQLite(sql, i) {
return scanSingleLineComment(sql, i) ?? scanMultiLineComment(sql, i) ?? scanSingleQuotedString(sql, i) ?? scanDoubleQuotedString(sql, i) ?? scanBacktickQuotedIdentifier(sql, i) ?? scanBracketQuotedIdentifier(sql, i) ?? plainToken(i);
}
function scanTokenSQLServer(sql, i) {
return scanSingleLineComment(sql, i) ?? scanMultiLineComment(sql, i) ?? scanSingleQuotedString(sql, i) ?? scanDoubleQuotedString(sql, i) ?? scanBracketQuotedIdentifier(sql, i) ?? plainToken(i);
}
function scanOracleAlternativeQuotedString(sql, i) {
if (sql[i] !== "q" && sql[i] !== "Q" || sql[i + 1] !== "'") {
return null;
}
const open = sql[i + 2];
if (open === void 0 || open === " " || open === " " || open === "\n") {
return null;
}
const mirrors = { "(": ")", "[": "]", "{": "}", "<": ">" };
const close = (mirrors[open] ?? open) + "'";
const closeIdx = sql.indexOf(close, i + 3);
const end = closeIdx !== -1 ? closeIdx + close.length : sql.length;
return { type: TokenType.QuotedBlock, end };
}
function scanTokenOracle(sql, i) {
return scanSingleLineComment(sql, i) ?? scanMultiLineComment(sql, i) ?? scanOracleAlternativeQuotedString(sql, i) ?? scanSingleQuotedString(sql, i) ?? scanDoubleQuotedString(sql, i) ?? plainToken(i);
}
function scanSingleLineCommentClickHouse(sql, i) {
const isComment = sql[i] === "-" && sql[i + 1] === "-" || sql[i] === "/" && sql[i + 1] === "/" || sql[i] === "#" && (sql[i + 1] === " " || sql[i + 1] === "!");
if (!isComment) {
return null;
}
let j = i;
while (j < sql.length && sql[j] !== "\n") {
j++;
}
return { type: TokenType.Comment, end: j };
}
function scanBacktickQuotedIdentifierBackslash(sql, i) {
return sql[i] === "`" ? scanBackslashQuoted(sql, i, "`") : null;
}
function scanTokenClickHouse(sql, i) {
return scanSingleLineCommentClickHouse(sql, i) ?? scanNestedMultiLineComment(sql, i) ?? scanSingleQuotedStringBackslash(sql, i) ?? scanDoubleQuotedStringBackslash(sql, i) ?? scanBacktickQuotedIdentifierBackslash(sql, i) ?? scanDollarQuotedBlock(sql, i) ?? plainToken(i);
}
var dialectScanners = {
postgres: scanTokenPostgres,
mysql: scanTokenMySQL,
mariadb: scanTokenMySQL,
sqlite: scanTokenSQLite,
sqlserver: scanTokenSQLServer,
oracle: scanTokenOracle,
clickhouse: scanTokenClickHouse
};
function getScanner(dialect) {
return dialect ? dialectScanners[dialect] ?? scanTokenAnsi : scanTokenAnsi;
}
var alternateScanners = {
mysql: [scanTokenMySQLNoBackslashEscapes, scanTokenMySQLAnsiQuotes],
mariadb: [scanTokenMySQLNoBackslashEscapes, scanTokenMySQLAnsiQuotes]
};
function getAllScanners(dialect) {
return [getScanner(dialect), ...dialect && alternateScanners[dialect] || []];
}
function stripCommentsAndStrings(sql, dialect) {
return stripWith(sql, getScanner(dialect));
}
function stripCommentsAndStringsVariants(sql, dialect) {
return [...new Set(getAllScanners(dialect).map((scanToken) => stripWith(sql, scanToken)))];
}
function stripWith(sql, scanToken) {
const parts = [];
let plainStart = -1;
let i = 0;
while (i < sql.length) {
const token = scanToken(sql, i);
if (token.type === TokenType.Plain) {
if (plainStart === -1) {
plainStart = i;
}
} else {
if (plainStart !== -1) {
parts.push(sql.substring(plainStart, i));
plainStart = -1;
}
parts.push(" ");
}
i = token.end;
}
if (plainStart !== -1) {
parts.push(sql.substring(plainStart));
}
return parts.join("");
}
function blankCommentsAndStrings(sql, dialect) {
const scanToken = getScanner(dialect);
let result = "";
let i = 0;
while (i < sql.length) {
const token = scanToken(sql, i);
if (token.type === TokenType.Plain) {
result += sql.substring(i, token.end);
} else {
result += " ".repeat(token.end - i);
}
i = token.end;
}
return result;
}
var LEADING_SQL_NOISE = /^(?:\s+|--[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/)*/;
function splitSQLStatements(sql, dialect) {
return splitWith(sql, getScanner(dialect));
}
function splitSQLStatementVariants(sql, dialect) {
return getAllScanners(dialect).map((scanToken) => splitWith(sql, scanToken));
}
function splitWith(sql, scanToken) {
const statements = [];
let stmtStart = 0;
let i = 0;
while (i < sql.length) {
if (sql[i] === ";") {
const trimmed2 = sql.substring(stmtStart, i).trim();
if (trimmed2.length > 0) {
statements.push(trimmed2);
}
stmtStart = i + 1;
i++;
continue;
}
const token = scanToken(sql, i);
i = token.end;
}
const trimmed = sql.substring(stmtStart).trim();
if (trimmed.length > 0) {
statements.push(trimmed);
}
return statements;
}
export {
ConnectorRegistry,
SafeURL,
replaceDSNHostPort,
rawQueryParamValues,
SQLITE_DSN_PREFIX,
SQLITE_MEMORY_PATH,
parseSqliteDsnPath,
resolveSqliteFilePath,
resolveSqliteDsnPath,
buildSqliteDSN,
normalizeSqliteDsn,
parseConnectionInfoFromDSN,
obfuscateDSNPassword,
getDatabaseTypeFromDSN,
getDefaultPortForType,
stripCommentsAndStrings,
stripCommentsAndStringsVariants,
blankCommentsAndStrings,
LEADING_SQL_NOISE,
splitSQLStatements,
splitSQLStatementVariants
};