@bytebase/dbhub
Version:
Token-efficient database MCP server for PostgreSQL, MySQL, MariaDB, SQL Server, Oracle, ClickHouse, SQLite
845 lines (843 loc) • 30.9 kB
JavaScript
import {
toClickHouseSettings
} from "./chunk-FRYLTOWC.js";
import {
ClientQueryTimeoutError,
clientQueryTimeoutMs
} from "./chunk-6UGT3UWA.js";
import {
computeHitRatioPct
} from "./chunk-FU2ZJE4E.js";
import {
objectRows
} from "./chunk-SR7SSJAL.js";
import {
closeQuietly
} from "./chunk-CZ5B3EO3.js";
import {
ConnectorRegistry,
SafeURL,
getDefaultPortForType,
obfuscateDSNPassword,
rawQueryParamValues,
splitSQLStatements,
stripCommentsAndStrings
} from "./chunk-HJNFFBF4.js";
// src/connectors/clickhouse/index.ts
import https from "node:https";
import {
createClient,
parseError,
ClickHouseError,
ClickHouseLogLevel
} from "@clickhouse/client";
var SSL_MODES = ["disable", "require", "verify-full"];
var ClickHouseDSNParser = class {
async parse(dsn, _config) {
if (!this.isValidDSN(dsn)) {
throw new Error(
`Invalid ClickHouse DSN format.
Provided: ${obfuscateDSNPassword(dsn)}
Expected: ${this.getSampleDSN()}`
);
}
try {
const url = new SafeURL(dsn);
const sslmodes = rawQueryParamValues(dsn, "sslmode");
for (const mode of sslmodes) {
if (!SSL_MODES.includes(mode)) {
throw new Error(
`Unsupported sslmode '${mode}' for ClickHouse. Supported: ${SSL_MODES.join(", ")}`
);
}
}
const sslmode = sslmodes.at(-1) ?? "disable";
const host = url.hostname;
if (!host) {
throw new Error("ClickHouse DSN must include a host");
}
const port = url.port ? parseInt(url.port, 10) : getDefaultPortForType("clickhouse", sslmode);
const scheme = sslmode === "disable" ? "http" : "https";
return {
// SafeURL hands back an IPv6 address without its brackets
url: `${scheme}://${host.includes(":") ? `[${host}]` : host}:${port}`,
username: url.username || "default",
password: url.password ?? "",
database: (url.pathname ? url.pathname.substring(1) : "") || "default",
sslmode
};
} catch (error) {
throw new Error(
`Failed to parse ClickHouse DSN: ${error instanceof Error ? error.message : String(error)}`
);
}
}
getSampleDSN() {
return "clickhouse://default:password@localhost:8123/default?sslmode=disable";
}
isValidDSN(dsn) {
return dsn.startsWith("clickhouse://");
}
};
var ROW_FORMAT = "JSONCompactEachRowWithNamesAndTypes";
var RESPONSE_BUFFER_BYTES = 1024 * 1024;
var NO_REQUEST_TIMEOUT_MS = 2147483647;
var EXCEPTION_IN_FORMAT_SETTING = "http_write_exception_in_output_format";
var VIEW_ENGINES = "('View', 'MaterializedView', 'LiveView', 'WindowView')";
var MAX_ERROR_TEXT = 2e3;
var CLIENT_CONNECTION_METRICS = "('TCPConnection', 'HTTPConnection', 'MySQLConnection', 'PostgreSQLConnection')";
function keepExactNumbers(_key, value, context) {
const source = context?.source;
if (typeof value !== "number" || source === void 0 || !/^-?\d+(?:\.\d+)?$/.test(source)) {
return value;
}
const digits = source.includes(".") ? source.replace(/\.?0+$/, "") : source;
return digits === String(value) || value === 0 ? value : source;
}
function unwrapType(type) {
const wrapped = /^(?:LowCardinality|Nullable)\((.*)\)$/s.exec(type);
return wrapped ? unwrapType(wrapped[1]) : type;
}
function holdsFreeText(type) {
return /^(?:String|FixedString|Enum|Variant|Dynamic|JSON|Object)/.test(unwrapType(type));
}
function isErrorMessageRow(values) {
return values.length === 1 && typeof values[0] === "string" && parseError(values[0]) instanceof ClickHouseError;
}
function hasSettingsClause(statement) {
return /\bsettings\b\s*(?:[a-z_][\w.]*\s*)?=/i.test(
stripCommentsAndStrings(statement, "clickhouse")
);
}
var Deadline = class {
constructor(timeoutMs) {
this.timeoutMs = timeoutMs;
this.controller = new AbortController();
this.expired = false;
if (timeoutMs !== void 0) {
this.timer = setTimeout(() => {
this.expired = true;
this.controller.abort();
this.closeResponse?.();
}, timeoutMs);
}
}
/** Signal for the request; undefined when there is no limit. */
get signal() {
return this.timeoutMs === void 0 ? void 0 : this.controller.signal;
}
/** Register how to stop reading the response the request produced. */
whileReading(close) {
this.closeResponse = close;
if (this.expired) {
close();
}
}
/** The error to report for `error`: the timeout, when that is what ended the request. */
explain(error) {
return this.expired ? new ClientQueryTimeoutError(this.timeoutMs) : error;
}
clear() {
clearTimeout(this.timer);
}
};
function splitKeyExpression(expression) {
const parts = [];
let depth = 0;
let quote = null;
let start = 0;
for (let i = 0; i < expression.length; i++) {
const ch = expression[i];
if (quote) {
if (ch === "\\") {
i++;
} else if (ch === quote) {
quote = null;
}
} else if (ch === "'" || ch === '"' || ch === "`") {
quote = ch;
} else if (ch === "(" || ch === "[") {
depth++;
} else if (ch === ")" || ch === "]") {
depth--;
} else if (ch === "," && depth === 0) {
parts.push(expression.slice(start, i));
start = i + 1;
}
}
parts.push(expression.slice(start));
return parts.map((part) => part.trim()).filter((part) => part.length > 0);
}
function responseError(text) {
const shown = text.length > MAX_ERROR_TEXT ? `${text.slice(0, MAX_ERROR_TEXT)}...` : text;
const parsed = parseError(shown);
return parsed instanceof Error ? parsed : new Error(shown);
}
function parseRowLine(text) {
let value;
try {
value = JSON.parse(text, keepExactNumbers);
} catch {
return void 0;
}
if (!Array.isArray(value)) {
const exception = value?.exception;
throw responseError(typeof exception === "string" ? exception : text);
}
return value;
}
function parseSummary(header) {
if (typeof header !== "string") {
return void 0;
}
try {
const parsed = JSON.parse(header);
return typeof parsed === "object" && parsed !== null ? parsed : void 0;
} catch {
return void 0;
}
}
function counter(value) {
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : 0;
}
function describeSummary(summary) {
const parts = [];
const readRows = counter(summary.read_rows);
const writtenRows = counter(summary.written_rows);
if (readRows > 0) {
parts.push(`read ${readRows} rows (${counter(summary.read_bytes)} bytes)`);
}
if (writtenRows > 0) {
parts.push(`wrote ${writtenRows} rows (${counter(summary.written_bytes)} bytes)`);
}
if (parts.length === 0) {
return void 0;
}
const elapsedNs = counter(summary.elapsed_ns);
const elapsed = elapsedNs > 0 ? ` in ${(elapsedNs / 1e9).toFixed(3)}s` : "";
const text = parts.join(", ") + elapsed;
return text[0].toUpperCase() + text.slice(1);
}
var ClickHouseConnector = class _ClickHouseConnector {
constructor() {
this.id = "clickhouse";
this.name = "ClickHouse";
this.dsnParser = new ClickHouseDSNParser();
/** Database named in the DSN, as the server resolved it at connect time */
this.defaultDatabase = "default";
/** The connected user's own `readonly` setting: 0, 1 or 2 */
this.userReadonly = 0;
/** Settings sent with every request, when the user may change settings */
this.baseSettings = {};
/**
* Whether the server may report an error as a row of the result (see
* EXCEPTION_IN_FORMAT_SETTING). False wherever the connector could turn that
* off; it can stay true only for a user restricted to `readonly = 1`.
*/
this.errorsAsRows = false;
// Source ID is set by ConnectorManager after cloning
this.sourceId = "default";
}
getId() {
return this.sourceId;
}
clone() {
return new _ClickHouseConnector();
}
async connect(dsn, initScript, config) {
try {
const parsed = await this.dsnParser.parse(dsn, config);
const queryTimeoutMs = config?.queryTimeoutSeconds !== void 0 ? Math.ceil(config.queryTimeoutSeconds * 1e3) : void 0;
this.clientDeadlineMs = queryTimeoutMs !== void 0 ? clientQueryTimeoutMs(queryTimeoutMs) : void 0;
this.client = createClient({
url: parsed.url,
username: parsed.username,
password: parsed.password,
database: parsed.database,
application: "dbhub",
request_timeout: NO_REQUEST_TIMEOUT_MS,
// Failures are thrown to the caller; the client's own logging of them
// would only repeat each one on stderr.
log: { level: ClickHouseLogLevel.OFF },
// `require` encrypts without verifying the certificate, which the
// client only allows through an agent of our own. `verify-full` is the
// client's default HTTPS behaviour: chain and host name are checked.
...parsed.sslmode === "require" && {
http_agent: new https.Agent({ keepAlive: true, rejectUnauthorized: false })
}
});
const probe = await this.probe(config?.connectionTimeoutSeconds);
this.defaultDatabase = probe.database || parsed.database;
this.userReadonly = probe.readonly;
const sessionSettings = config?.sessionSettings;
const hasSessionSettings = sessionSettings !== void 0 && Object.keys(sessionSettings).length > 0;
if (this.userReadonly === 1) {
if (hasSessionSettings) {
throw new Error(
`ClickHouse user '${parsed.username}' is restricted to readonly = 1 and cannot change settings, so [sources.session] cannot be applied. Set these in the user's settings profile on the server instead.`
);
}
if (queryTimeoutMs !== void 0) {
console.error(
`Source '${this.sourceId}': ClickHouse user '${parsed.username}' is restricted to readonly = 1, so query_timeout cannot be sent as max_execution_time. It applies on the client only.`
);
}
this.baseSettings = {};
this.errorsAsRows = await this.profileWritesErrorsAsRows();
} else {
this.baseSettings = {
// 64-bit integers as JSON numbers (keepLargeIntegers keeps the ones a
// double cannot hold as text) and decimals as strings, whatever the
// server's defaults, so results look the same on every version.
output_format_json_quote_64bit_integers: 0,
output_format_json_quote_decimals: 1,
// Stop a read-only query when its request is dropped: a max_rows cap
// that stops reading, or a client-side timeout.
cancel_http_readonly_queries_on_client_close: 1,
...queryTimeoutMs !== void 0 && {
max_execution_time: Math.ceil(queryTimeoutMs / 1e3)
},
...sessionSettings !== void 0 && toClickHouseSettings(sessionSettings),
[EXCEPTION_IN_FORMAT_SETTING]: 0
};
this.errorsAsRows = false;
try {
await this.catalog("SELECT 1");
} catch (error) {
if (!_ClickHouseConnector.isUnknownSetting(error, EXCEPTION_IN_FORMAT_SETTING)) {
throw error;
}
delete this.baseSettings[EXCEPTION_IN_FORMAT_SETTING];
await this.catalog("SELECT 1");
}
}
if (initScript) {
await this.executeSQL(initScript, {});
}
} catch (error) {
await closeQuietly(() => this.disconnect());
throw error;
}
}
/**
* First round trip: proves the credentials work and reads the database the
* session landed in and the user's own `readonly` level. Bounded by
* connection_timeout, reported the way a refused connection is.
*/
async probe(connectionTimeoutSeconds) {
const signal = connectionTimeoutSeconds !== void 0 ? AbortSignal.timeout(connectionTimeoutSeconds * 1e3) : void 0;
try {
const resultSet = await this.requireClient().query({
query: "SELECT currentDatabase() AS database, toString(getSetting('readonly')) AS readonly",
format: "JSONEachRow",
abort_signal: signal
});
const rows = await resultSet.json();
return { database: rows[0]?.database ?? "", readonly: Number(rows[0]?.readonly ?? 0) || 0 };
} catch (error) {
if (signal?.aborted) {
throw Object.assign(
new Error(`Timed out connecting to ClickHouse after ${connectionTimeoutSeconds}s`),
{ code: "ETIMEDOUT", cause: error }
);
}
throw error;
}
}
static isUnknownSetting(error, setting) {
return error instanceof ClickHouseError && error.type === "UNKNOWN_SETTING" && error.message.includes(setting);
}
/**
* For a user who cannot change settings: whether their profile has the
* server write errors as rows. Anything short of a clear "no" counts as
* yes, which only costs the extra scrutiny runStatement gives a last row.
*/
async profileWritesErrorsAsRows() {
try {
const rows = await this.catalog(
"SELECT value FROM system.settings WHERE name = {name:String}",
{ name: EXCEPTION_IN_FORMAT_SETTING }
);
return rows.length > 0 && rows[0].value !== "0";
} catch {
return true;
}
}
async disconnect() {
if (this.client) {
const client = this.client;
this.client = void 0;
await client.close();
}
}
requireClient() {
if (!this.client) {
throw new Error("Not connected to ClickHouse database");
}
return this.client;
}
/**
* Settings for one request. `readonly = 1` is added for a read-only tool
* when the user is not read-only already: a readonly=2 user may not change
* `readonly` (and is read-only without it), and a readonly=1 user may not
* change anything, which is why baseSettings is empty for one.
*
* ClickHouse checks every setting of a request against the settings in
* force before the request, so `readonly = 1` and the settings sent beside
* it are accepted together.
*/
settingsFor(readonly) {
return {
...this.baseSettings,
...readonly && this.userReadonly === 0 && { readonly: "1" },
buffer_size: String(RESPONSE_BUFFER_BYTES)
};
}
/** Run a catalog query, read-only, and return its rows as objects. */
async catalog(query, params = {}) {
const deadline = new Deadline(this.clientDeadlineMs);
try {
const resultSet = await this.requireClient().query({
query,
format: "JSONEachRow",
query_params: params,
clickhouse_settings: this.settingsFor(true),
abort_signal: deadline.signal
});
deadline.whileReading(() => resultSet.close());
return await resultSet.json();
} catch (error) {
throw deadline.explain(error);
} finally {
deadline.clear();
}
}
databaseOrDefault(schema) {
return schema || this.defaultDatabase;
}
async getSchemas() {
const rows = await this.catalog(
`SELECT name FROM system.databases
WHERE name NOT IN ('system', 'INFORMATION_SCHEMA', 'information_schema')
ORDER BY name`
);
return rows.map((row) => row.name);
}
async getDefaultSchema() {
return this.defaultDatabase;
}
async getTables(schema) {
const rows = await this.catalog(
`SELECT name FROM system.tables
WHERE database = {database:String} AND engine NOT IN ${VIEW_ENGINES} AND is_temporary = 0
ORDER BY name`,
{ database: this.databaseOrDefault(schema) }
);
return rows.map((row) => row.name);
}
async getViews(schema) {
const rows = await this.catalog(
`SELECT name FROM system.tables
WHERE database = {database:String} AND engine IN ${VIEW_ENGINES}
ORDER BY name`,
{ database: this.databaseOrDefault(schema) }
);
return rows.map((row) => row.name);
}
async getTableSchema(tableName, schema) {
const rows = await this.catalog(
`SELECT name, type, default_kind, default_expression, comment FROM system.columns
WHERE database = {database:String} AND table = {table:String}
ORDER BY position`,
{ database: this.databaseOrDefault(schema), table: tableName }
);
return rows.map((row) => ({
column_name: row.name,
data_type: row.type,
// Nullability is part of the type: Nullable(T), or LowCardinality(Nullable(T)).
is_nullable: /^(?:LowCardinality\()?Nullable\(/.test(row.type) ? "YES" : "NO",
column_default: _ClickHouseConnector.formatDefault(row.default_kind, row.default_expression),
description: row.comment || null
}));
}
/**
* A column's default as its DDL shows it. MATERIALIZED, ALIAS and EPHEMERAL
* keep their keyword: such a column is computed, and (unlike DEFAULT) is
* left out of `SELECT *`.
*/
static formatDefault(kind, expression) {
if (!kind) {
return null;
}
return kind === "DEFAULT" ? expression : `${kind} ${expression}`.trim();
}
/**
* ClickHouse has no unique indexes. What it has is reported in their place,
* none of it marked unique:
* - `PRIMARY KEY`: the sparse index a MergeTree table is read through,
* - `ORDER BY`: the sorting key, when it has more columns than the primary key,
* - each data-skipping index, under its own name.
* A "column" may be an expression such as `toDate(ts)`.
*/
async getTableIndexes(tableName, schema) {
const params = { database: this.databaseOrDefault(schema), table: tableName };
const [tables, skipping] = await Promise.all([
this.catalog(
`SELECT primary_key, sorting_key FROM system.tables
WHERE database = {database:String} AND name = {table:String}`,
params
),
this.catalog(
`SELECT name, expr FROM system.data_skipping_indices
WHERE database = {database:String} AND table = {table:String}
ORDER BY name`,
params
)
]);
const indexes = [];
const primaryKey = splitKeyExpression(tables[0]?.primary_key ?? "");
const sortingKey = splitKeyExpression(tables[0]?.sorting_key ?? "");
if (primaryKey.length > 0) {
indexes.push({
index_name: "PRIMARY KEY",
column_names: primaryKey,
is_unique: false,
is_primary: true
});
}
if (sortingKey.length > 0 && sortingKey.join(",") !== primaryKey.join(",")) {
indexes.push({
index_name: "ORDER BY",
column_names: sortingKey,
is_unique: false,
is_primary: false
});
}
for (const index of skipping) {
indexes.push({
index_name: index.name,
column_names: splitKeyExpression(index.expr),
is_unique: false,
is_primary: false
});
}
return indexes;
}
async getTableComment(tableName, schema) {
const rows = await this.catalog(
`SELECT comment FROM system.tables
WHERE database = {database:String} AND name = {table:String}`,
{ database: this.databaseOrDefault(schema), table: tableName }
);
return rows[0]?.comment || null;
}
async getTableRowCount(tableName, schema) {
const rows = await this.catalog(
`SELECT total_rows FROM system.tables
WHERE database = {database:String} AND name = {table:String}`,
{ database: this.databaseOrDefault(schema), table: tableName }
);
const totalRows = rows[0]?.total_rows;
return totalRows === null || totalRows === void 0 ? null : Number(totalRows);
}
/**
* ClickHouse has no stored procedures. Its SQL user-defined functions are
* reported as functions; they are server-wide, so the same list is returned
* whatever the schema.
*/
async getStoredProcedures(_schema, routineType) {
if (routineType === "procedure") {
return [];
}
const rows = await this.catalog(
`SELECT name FROM system.functions WHERE origin = 'SQLUserDefined' ORDER BY name`
);
return rows.map((row) => row.name);
}
async getStoredProcedureDetail(procedureName, _schema) {
const rows = await this.catalog(
`SELECT name, create_query FROM system.functions
WHERE origin = 'SQLUserDefined' AND name = {name:String}`,
{ name: procedureName }
);
if (rows.length === 0) {
throw new Error(`Function '${procedureName}' not found`);
}
const parameters = /\bAS\s+(?:\(([^)]*)\)|([A-Za-z_]\w*))\s*->/i.exec(rows[0].create_query);
return {
procedure_name: rows[0].name,
procedure_type: "function",
language: "sql",
parameter_list: (parameters?.[1] ?? parameters?.[2] ?? "").trim(),
definition: rows[0].create_query
};
}
/**
* Health metrics, from the server's own counters.
*
* Connections: `system.metrics` counts client connections per protocol and
* `system.processes` lists the queries running. The server counts an HTTP
* connection only while it is handling a request, so `idle` is in practice
* the native-protocol clients with no query running: a kept-alive HTTP
* connection between two requests is counted nowhere. ClickHouse has no
* transaction a session could sit idle in.
*
* Cache: ClickHouse has no buffer pool. Table data is read through the
* operating system's page cache, which the server keeps no hit counters
* for. What it does cache and count for every MergeTree read is marks (the
* offsets that turn a primary key range into file positions), so the mark
* cache is what `bufferCache` reports, with a note saying so.
*
* Every table read here needs its own SELECT grant on servers where system
* tables are not open to all users (`select_from_system_db_requires_grant`,
* on in the configuration ClickHouse ships). What a missing grant hides is
* left out and named in a note.
*
* The queries run one after the other, not together, so that this check is
* one connection and one query at any moment: the one that is subtracted.
*/
async getHealthCheck() {
const denied = [];
const read = async (table, query) => {
try {
return await this.catalog(query);
} catch (error) {
if (error instanceof ClickHouseError && error.type === "ACCESS_DENIED") {
denied.push(table);
return void 0;
}
throw error;
}
};
const metrics = await read(
"system.metrics",
`SELECT sum(value) AS connections FROM system.metrics WHERE metric IN ${CLIENT_CONNECTION_METRICS}`
);
const processes = await read(
"system.processes",
`SELECT count() AS active, max(elapsed) AS longest_seconds FROM system.processes
WHERE query_id != queryID()`
);
let serverSettings;
try {
serverSettings = await read(
"system.server_settings",
`SELECT value FROM system.server_settings WHERE name = 'max_connections'`
);
} catch (error) {
if (!(error instanceof ClickHouseError && error.type === "UNKNOWN_TABLE")) {
throw error;
}
serverSettings = [];
}
const events = await read(
"system.events",
`SELECT event, value FROM system.events WHERE event IN ('MarkCacheHits', 'MarkCacheMisses')`
);
const result = {};
const notes = [];
const notReported = [];
if (metrics && processes) {
const total = Math.max(0, Number(metrics[0]?.connections ?? 0) - 1);
const active = Number(processes[0]?.active ?? 0);
const maxConnections = Number(serverSettings?.[0]?.value);
result.connections = {
total,
active,
// The two counts are read by separate requests, and a query need not
// belong to a counted connection (see above), hence the floor.
idle: Math.max(0, total - active),
idleInTransaction: 0,
maxConnections: Number.isFinite(maxConnections) && maxConnections > 0 ? maxConnections : null,
longestIdleInTransactionSeconds: null,
// max() over no rows is 0, not NULL.
longestActiveQuerySeconds: active > 0 ? Number(processes[0].longest_seconds) : null
};
if (serverSettings === void 0) {
notReported.push("max_connections");
}
} else {
notReported.push("connections");
}
if (events) {
const counts = Object.fromEntries(events.map((row) => [row.event, Number(row.value)]));
const hits = counts.MarkCacheHits ?? 0;
const misses = counts.MarkCacheMisses ?? 0;
result.bufferCache = {
hitRatioPct: computeHitRatioPct(hits + misses, misses),
blocksHit: hits,
blocksRead: misses
};
notes.push(
"buffer_cache is the mark cache: lookups of MergeTree marks served from memory (blocks_hit) or loaded from disk (blocks_read) since the server started. ClickHouse has no buffer pool; table data is cached by the operating system."
);
} else {
notReported.push("buffer_cache");
}
if (denied.length > 0) {
notes.unshift(
`Connected user lacks the SELECT grant on ${denied.join(", ")}: ${notReported.join(" and ")} ${notReported.length > 1 ? "are" : "is"} not reported.`
);
}
return { ...result, ...notes.length > 0 && { notes } };
}
/**
* Run a batch: one HTTP request per statement, in order, stopping at the
* first failure. Positional `parameters` bind to `{p1:Type}`, `{p2:Type}`,
* ... placeholders (see parameter-mapper.ts).
*/
async executeSQL(sql, options, parameters) {
const client = this.requireClient();
const statements = splitSQLStatements(sql, "clickhouse");
if (options.readonly && this.userReadonly === 2 && statements.some(hasSettingsClause)) {
throw new Error(
"Read-only mode: a SETTINGS clause is not allowed, as it could override the limits configured for this source"
);
}
const queryParams = parameters && parameters.length > 0 ? Object.fromEntries(parameters.map((value, index) => [`p${index + 1}`, value])) : void 0;
const resultSets = [];
const messages = [];
for (const [index, statement] of statements.entries()) {
const { resultSet, summary } = await this.runStatement(client, statement, options, queryParams);
resultSets.push(resultSet);
const cost = summary && describeSummary(summary);
if (cost) {
messages.push({
text: statements.length > 1 ? `Statement ${index + 1}: ${cost}` : cost
});
}
}
return { resultSets, ...messages.length > 0 && { messages } };
}
/**
* Run one statement and read its rows.
*
* The row cap is applied by reading: rows are taken off the response a line
* at a time, and once `maxRows` are held and one more arrives, the response
* is closed and the result marked truncated. The statement is sent exactly
* as written, with no LIMIT spliced in, so the cap is right for every form
* of query (LIMIT BY, WITH TIES, trailing SETTINGS, SHOW, DESCRIBE, ...).
*
* The returned summary is only present when it is known to be final: the
* whole response was read and it fit the server's buffer (see
* RESPONSE_BUFFER_BYTES).
*/
async runStatement(client, statement, options, queryParams) {
const maxRows = options.maxRows;
let columnNames;
let columnTypes;
const rows = [];
let truncated = false;
let bytes = 0;
let summary;
let heldBack;
let appendedError;
const accept = (values) => {
if (maxRows && rows.length >= maxRows) {
truncated = true;
return false;
}
rows.push(values);
return true;
};
const deadline = new Deadline(this.clientDeadlineMs);
try {
const response = await client.query({
query: statement,
format: ROW_FORMAT,
query_params: queryParams,
clickhouse_settings: this.settingsFor(options.readonly),
abort_signal: deadline.signal
});
deadline.whileReading(() => response.close());
summary = parseSummary(response.response_headers["x-clickhouse-summary"]);
try {
reading: for await (const lines of response.stream()) {
for (const line of lines) {
bytes += Buffer.byteLength(line.text) + 1;
const values = appendedError === void 0 ? parseRowLine(line.text) : void 0;
if (values === void 0) {
if ((appendedError?.length ?? 0) < MAX_ERROR_TEXT) {
appendedError = `${appendedError ?? ""}${line.text}
`;
}
continue;
}
if (columnNames === void 0) {
columnNames = values.map(String);
continue;
}
if (columnTypes === void 0) {
columnTypes = values.map(String);
continue;
}
if (values.length !== columnNames.length) {
throw responseError(isErrorMessageRow(values) ? values[0] : line.text);
}
if (heldBack !== void 0) {
const wasData = heldBack;
heldBack = void 0;
if (!accept(wasData)) {
break reading;
}
}
if (this.errorsAsRows && isErrorMessageRow(values)) {
heldBack = values;
} else if (!accept(values)) {
break reading;
}
}
}
} catch (error) {
if (appendedError === void 0 || deadline.expired) {
throw error;
}
} finally {
response.close();
}
if (appendedError !== void 0) {
throw responseError(appendedError.trim());
}
if (heldBack !== void 0 && !truncated) {
const isError = !holdsFreeText(columnTypes?.[0] ?? "") || bytes >= RESPONSE_BUFFER_BYTES;
if (isError) {
throw responseError(heldBack[0]);
}
accept(heldBack);
}
} catch (error) {
throw deadline.explain(error);
} finally {
deadline.clear();
}
columnTypes?.forEach((type, column) => {
if (unwrapType(type).startsWith("Decimal")) {
for (const row of rows) {
if (typeof row[column] === "number") {
row[column] = String(row[column]);
}
}
}
});
const summaryIsFinal = !truncated && bytes < RESPONSE_BUFFER_BYTES;
const resultSet = {
sql: statement,
rows: columnNames ? objectRows(columnNames, rows) : [],
// A statement with no result (INSERT ... SELECT, DDL) reports what it wrote.
rowCount: columnNames ? rows.length : counter(summary?.written_rows),
...truncated && { truncated: true }
};
return { resultSet, ...summaryIsFinal && summary && { summary } };
}
};
var clickhouseConnector = new ClickHouseConnector();
ConnectorRegistry.register(clickhouseConnector);
export {
ClickHouseConnector,
ClickHouseDSNParser,
describeSummary,
hasSettingsClause,
keepExactNumbers,
splitKeyExpression
};