import type { ClickHouseExecutor, QueryControlOptions, ClickHouseInsertParams, ClickHouseJsonQueryResult, ClickHouseSettings, SchemaObjectRef, } from '@chkit/clickhouse' import { STRICT_CONTROL_SETTINGS, allReplicas, buildIntrospectedTables, inferSchemaKindFromEngine, queryLogOutcome, type QueryLogRow, resolveReplicaFanout, type SystemColumnRow, type SystemSkippingIndexRow, type SystemTableRow, } from '@chkit/clickhouse' import { unquoteIdentifiers } from '@chkit/core' import type { Credentials } from '../auth/index.js' import { type ApiClient, createApiClient } from '../client.js' function throwIfError( res: Awaited>, ): void { if (res.error) { throw new Error(res.error) } } /** * The workbench query API accepts only string/number setting values. Drop * undefined entries and coerce booleans so chkit can forward ClickHouse query * settings (e.g. `enable_parallel_replicas: 0` used by backfill planning). */ function toApiSettings( settings?: ClickHouseSettings, ): Record | undefined { if (!settings) return undefined const out: Record = {} for (const [key, value] of Object.entries(settings)) { if (typeof value === 'string' || typeof value === 'number') { out[key] = value } else if (typeof value === 'boolean') { out[key] = value ? 1 : 0 } // Skip undefined and nested setting maps — the workbench API only // accepts scalar setting values. } return Object.keys(out).length > 0 ? out : undefined } export function normalizeQueryData( res: Awaited>, ): T[] { const columnNames = res.meta.map((col) => col.name) return res.data.map((row) => { if (!Array.isArray(row)) return row as T return Object.fromEntries( row.map((value, idx) => [columnNames[idx] ?? String(idx), value]), ) as T }) } export function normalizeQueryJsonResult>( res: Awaited>, ): ClickHouseJsonQueryResult { const out: ClickHouseJsonQueryResult = { data: normalizeQueryData(res), meta: res.meta, rows: res.rows, } if (res.statistics) out.statistics = res.statistics if (res.query_id) out.query_id = res.query_id return out } /** * The `INSERT ... VALUES` statement for an insert, or undefined when there are no * rows. An explicit column list (required to supply EPHEMERAL inputs) takes * precedence over the first row's keys. A field a row omits takes the column's * DEFAULT; an explicit null is sent as NULL. */ export function renderValuesInsert>( params: ClickHouseInsertParams, ): string | undefined { const [firstValue] = params.values if (!firstValue) return undefined const columns = params.columns?.length ? params.columns.map((sql) => ({ sql, key: unquoteIdentifiers(sql) })) : Object.keys(firstValue).map((key) => ({ sql: key, key })) const rows = params.values .map( (row) => `(${columns .map(({ key }) => { const val = row[key] if (val === undefined) return 'DEFAULT' if (val === null) return 'NULL' if (typeof val === 'number') return String(val) return quoteString(String(val)) }) .join(', ')})`, ) .join(', ') return `INSERT INTO ${params.table} (${columns.map(({ sql }) => sql).join(', ')}) VALUES ${rows}` } export function createRemoteExecutor(deps: { credentials: Credentials serviceSlug: string }): ClickHouseExecutor { const { credentials, serviceSlug } = deps const client = createApiClient(credentials) const executor: ClickHouseExecutor = { queryControlCluster: 'default', async commandTracked(sql, check, beforeAttempt, settings?) { check() const queryId = await beforeAttempt() check() const apiSettings = toApiSettings(settings) ?? {} delete apiSettings.query_id const res = await client.workbench.query.execute({ serviceSlug, query: sql, queryId, ...(Object.keys(apiSettings).length > 0 ? { settings: apiSettings } : {}), }) throwIfError(res) }, async queryControl(sql: string, timeoutMs: number, options?: QueryControlOptions): Promise { if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) { throw new Error('Cancellation control deadline expired') } const settings = toApiSettings({ ...options?.settings, ...STRICT_CONTROL_SETTINGS }) if (settings) delete settings.query_id const controller = new AbortController() let timer: ReturnType | undefined const deadline = new Promise((_, reject) => { timer = setTimeout(() => { reject(new Error('Cancellation control deadline expired')) controller.abort() }, timeoutMs) }) try { // The race also bounds client-side error enrichment after an HTTP // response. Aborting fetch alone does not bound those extra lookups. const res = await Promise.race([ client.workbench.query.execute( { serviceSlug, query: sql, ...(options?.queryId ? { queryId: options.queryId } : {}), ...(settings ? { settings } : {}) }, { signal: controller.signal }, ), deadline, ]) throwIfError(res) if ('truncated' in res && res.truncated === true) throw new Error('Cancellation control result was truncated; complete proof is required') return normalizeQueryData(res) } finally { clearTimeout(timer) } }, async command(sql, settings?) { const apiSettings = toApiSettings(settings) const res = await client.workbench.query.execute({ serviceSlug, query: sql, ...(apiSettings ? { settings: apiSettings } : {}), }) throwIfError(res) }, async query(sql: string, settings?: ClickHouseSettings): Promise { const apiSettings = toApiSettings(settings) const res = await client.workbench.query.execute({ serviceSlug, query: sql, ...(apiSettings ? { settings: apiSettings } : {}), }) throwIfError(res) return normalizeQueryData(res) }, async queryJson>( sql: string, ): Promise> { const res = await client.workbench.query.execute({ serviceSlug, query: sql, }) throwIfError(res) return normalizeQueryJsonResult(res) }, async insert>( params: ClickHouseInsertParams, ) { const query = renderValuesInsert(params) if (!query) return // Per-insert settings such as insert_deduplication_token must reach // ClickHouse, so this cannot go through command(), which sends none. const apiSettings = toApiSettings(params.settings) const res = await client.workbench.query.execute({ serviceSlug, query, ...(apiSettings ? { settings: apiSettings } : {}), }) throwIfError(res) }, async submit(sql, queryId?, settings?, options?) { // Never start a request after the caller gave up on it (#767): the // signal also aborts the fetch while it connects. options?.signal?.throwIfAborted() const apiSettings = toApiSettings(settings) const res = await client.workbench.query.execute( { serviceSlug, query: sql, ...(apiSettings ? { settings: apiSettings } : {}), // The API takes the id as a top-level field and ignores a // `query_id` setting, which would leave the query under a random id. ...(queryId ? { queryId } : {}), }, options?.signal ? { signal: options.signal } : undefined, ) throwIfError(res) return queryId ?? res.query_id ?? 'submitted' }, async queryStatus(queryId, options?) { // afterTime bounds the query's start, as in the native executor. A // string compared with a DateTime column may carry neither fractional // seconds nor a zone (TYPE_MISMATCH), so an ISO 8601 bound such as // '2026-10-02T16:22:23.641Z' goes through parseDateTimeBestEffort. // event_date prunes query_log's partitions: the entry is logged no // earlier than the query started. A day of slack covers a session time // zone other than the server's; toDate32, as a Date before 1970 wraps around. const afterFilter = options?.afterTime ? `AND query_start_time >= parseDateTimeBestEffort(${quoteString(options.afterTime)}) AND event_date >= toDate32(parseDateTimeBestEffort(${quoteString(options.afterTime)})) - 1` : '' // The query runs on the replica that received it, so a multi-replica // service reads every replica (#246). A poll skips a replica it cannot // reach; with everyReplica the read fails instead. const fanout = await resolveReplicaFanout(executor) const from = (table: string) => (fanout ? allReplicas(fanout, table) : table) const readSettings = `SETTINGS skip_unavailable_shards = ${options?.everyReplica ? 0 : 1}` // migrate bounds an attach by how long the running attempt has run. // The API returns every cell as a string. const running = await executor.query<{ elapsed: string }>( `SELECT elapsed FROM ${from('system.processes')} WHERE user = currentUser() AND query_id = '${queryId}' LIMIT 1 ${readSettings}`, ) const [proc] = running if (proc) { return { status: 'running' as const, elapsedMs: Math.round(Number(proc.elapsed) * 1000), } } if (options?.runningOnly) return { status: 'unknown' as const } // With ExceptionBeforeStart, every entry of the id is read: a rejected // duplicate delivery logs one early, which must not hide the // QueryFinish of the attempt that ran (#767). const log = await executor.query( `SELECT type, written_rows, written_bytes, query_duration_ms, exception, exception_code, toString(serverUUID()) AS server, toString(event_time_microseconds) AS event_at FROM ${from('system.query_log')} WHERE user = currentUser() AND query_id = '${queryId}' AND type IN (${options?.includeBeforeStart ? "'QueryFinish', 'ExceptionWhileProcessing', 'ExceptionBeforeStart'" : "'QueryFinish', 'ExceptionWhileProcessing'"}) ${afterFilter} ORDER BY event_time DESC ${options?.includeBeforeStart ? '' : 'LIMIT 1'} ${readSettings}`, ) return queryLogOutcome(log) }, async listSchemaObjects() { const rows = await executor.query<{ database: string name: string engine: string comment?: string }>( `SELECT database, name, engine, comment FROM system.tables WHERE is_temporary = 0 AND database NOT IN ('system', 'information_schema', 'INFORMATION_SCHEMA') AND NOT startsWith(name, '_chkit_')`, ) const out: SchemaObjectRef[] = [] for (const row of rows) { const kind = inferSchemaKindFromEngine(row.engine) if (!kind) continue out.push({ kind, database: row.database, name: row.name, comment: row.comment ?? '', }) } return out }, async listTableDetails(databases) { if (databases.length === 0) return [] const quoted = databases .map((db) => `'${db.replace(/'/g, "''")}'`) .join(', ') const [tables, columns, indexes] = await Promise.all([ executor.query( `SELECT database, name, engine, create_table_query, primary_key, comment FROM system.tables WHERE is_temporary = 0 AND database IN (${quoted})`, ), executor.query( `SELECT database, \`table\`, name, type, default_kind, default_expression, comment, position, compression_codec FROM system.columns WHERE database IN (${quoted})`, ), executor.query( `SELECT database, \`table\`, name, expr, type_full AS type, granularity FROM system.data_skipping_indices WHERE database IN (${quoted})`, ), ]) return buildIntrospectedTables(tables, columns, indexes) }, async close() {}, } return executor } function quoteString(value: string): string { return `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'` }