Open History to see the last commit
1/**
2 * ClickHouse driver for Effect SQL, backed by `@clickhouse/client`.
3 *
4 * This module provides both the ClickHouse-specific {@link ClickhouseClient}
5 * service and the generic {@link Client.SqlClient} service. `make` creates a
6 * scoped client that pings ClickHouse by default, maps failures to `SqlError`,
7 * and aborts in-flight queries when interrupted. The
8 * ClickHouse-specific service adds typed parameters, command execution, insert
9 * queries, query id and settings helpers, a statement compiler, and direct or
10 * config-backed layers.
11 *
12 * @stability unstable
13 * @since 4.0.0
14 */
15import * as Clickhouse from "@clickhouse/client"
16import * as NodeStream from "@effect/platform-node/NodeStream"
17import * as Config from "effect/Config"
18import * as Context from "effect/Context"
19import * as Duration from "effect/Duration"
20import * as Effect from "effect/Effect"
21import * as Fiber from "effect/Fiber"
22import { dual } from "effect/Function"
23import * as Layer from "effect/Layer"
24import * as Reactivity from "effect/reactivity/Reactivity"
25import type * as Scope from "effect/Scope"
26import * as Client from "effect/sql/SqlClient"
27import type { Connection } from "effect/sql/SqlConnection"
28import {
29 AuthenticationError,
30 AuthorizationError,
31 ConnectionError,
32 SqlError,
33 SqlSyntaxError,
34 StatementTimeoutError,
35 UnknownError
36} from "effect/sql/SqlError"
37import * as Statement from "effect/sql/Statement"
38import * as Stream from "effect/Stream"
39import * as Crypto from "node:crypto"
40import type { Readable } from "node:stream"
41
42const ATTR_DB_SYSTEM_NAME = "db.system.name"
43const ATTR_DB_NAMESPACE = "db.namespace"
44
45const clickhouseCodeFromCause = (cause: unknown): number | undefined => {
46 if (typeof cause !== "object" || cause === null || !("code" in cause)) {
47 return undefined
48 }
49 const code = cause.code
50 if (typeof code === "number") {
51 return code
52 }
53 if (typeof code === "string") {
54 const parsed = Number(code)
55 return Number.isNaN(parsed) ? undefined : parsed
56 }
57 return undefined
58}
59
60const clickhouseSyntaxErrorCodes = new Set([36, 60, 62, 242])
61
62const classifyError = (
63 cause: unknown,
64 message: string,
65 operation: string,
66 fallback: "connection" | "unknown" = "unknown"
67) => {
68 const props = { cause, message, operation }
69 const code = clickhouseCodeFromCause(cause)
70 if (code !== undefined) {
71 if (code === 516) {
72 return new AuthenticationError(props)
73 }
74 if (code === 497) {
75 return new AuthorizationError(props)
76 }
77 if (clickhouseSyntaxErrorCodes.has(code)) {
78 return new SqlSyntaxError(props)
79 }
80 if (code === 159 || code === 469) {
81 return new StatementTimeoutError(props)
82 }
83 }
84 return fallback === "connection" ? new ConnectionError(props) : new UnknownError(props)
85}
86
87const killQuery = (client: Clickhouse.ClickHouseClient, queryId: string) =>
88 Effect.promise(() =>
89 client.command({
90 query: "KILL QUERY WHERE query_id = {queryId:String}",
91 query_params: { queryId }
92 })
93 )
94
95/**
96 * Unique runtime identifier used to tag `ClickhouseClient` values.
97 *
98 * @stability unstable
99 * @category type IDs
100 * @since 4.0.0
101 */
102export const TypeId: TypeId = "~@effect/sql-clickhouse/ClickhouseClient"
103
104/**
105 * Type-level literal for the `ClickhouseClient` runtime identifier.
106 *
107 * @stability unstable
108 * @category type IDs
109 * @since 4.0.0
110 */
111export type TypeId = "~@effect/sql-clickhouse/ClickhouseClient"
112
113/**
114 * ClickHouse-specific `SqlClient` extension with access to its configuration,
115 * the underlying `@clickhouse/client` instance, typed parameter fragments,
116 * command-mode execution, insert queries, and per-effect query ID and
117 * ClickHouse settings.
118 *
119 * @stability unstable
120 * @category services
121 * @since 4.0.0
122 */
123export interface ClickhouseClient extends Client.Base {
124 readonly [TypeId]: TypeId
125 readonly config: ClickhouseClientConfig
126 /**
127 * The `@clickhouse/client` instance behind this client, for driver features
128 * the SQL client does not wrap, such as `exec()` with raw output formats.
129 * Requests made on it bypass `withQueryId`, `withClickhouseSettings` and
130 * interruption handling; pass `query_id`, `clickhouse_settings` and
131 * `abort_signal` directly. It is closed with the client's scope.
132 */
133 readonly client: Clickhouse.ClickHouseClient
134 readonly param: (dataType: string, value: unknown) => Statement.Fragment
135 readonly asCommand: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>
136 readonly insertQuery: <T = unknown>(options: {
137 readonly table: string
138 readonly values: Clickhouse.InsertValues<Readable, T>
139 readonly format?: Clickhouse.DataFormat
140 readonly columns?: NonNullable<Clickhouse.InsertParams<Readable, T>["columns"]>
141 }) => Effect.Effect<Clickhouse.InsertResult, SqlError>
142 readonly withQueryId: {
143 (queryId: string): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>
144 <A, E, R>(effect: Effect.Effect<A, E, R>, queryId: string): Effect.Effect<A, E, R>
145 }
146 readonly withClickhouseSettings: {
147 (
148 settings: NonNullable<Clickhouse.BaseQueryParams["clickhouse_settings"]>
149 ): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>
150 <A, E, R>(
151 effect: Effect.Effect<A, E, R>,
152 settings: NonNullable<Clickhouse.BaseQueryParams["clickhouse_settings"]>
153 ): Effect.Effect<A, E, R>
154 }
155}
156
157/**
158 * Service tag for the active ClickHouse SQL client.
159 *
160 * **When to use**
161 *
162 * Use to access or provide a ClickHouse SQL client through the Effect context.
163 *
164 * @stability unstable
165 * @category services
166 * @since 4.0.0
167 */
168export const ClickhouseClient = Context.Service<ClickhouseClient, ClickhouseClient & Client.SqlClient>(
169 "@effect/sql-clickhouse/ClickhouseClient"
170)
171
172/**
173 * Configuration for creating a ClickHouse client, combining
174 * `@clickhouse/client` options with optional span attributes and query/result
175 * name transforms.
176 *
177 * @stability unstable
178 * @category models
179 * @since 4.0.0
180 */
181export interface ClickhouseClientConfig extends Clickhouse.ClickHouseClientConfigOptions {
182 /**
183 * Skip the startup ping (default: `false`). Set to `true` to build the
184 * client without contacting ClickHouse and handle connection failures per
185 * statement.
186 */
187 readonly disableInitialPing?: boolean | undefined
188 readonly spanAttributes?: Record<string, unknown> | undefined
189 readonly transformResultNames?: ((str: string) => string) | undefined
190 readonly transformQueryNames?: ((str: string) => string) | undefined
191}
192
193/**
194 * Creates a `ClickhouseClient` that pings ClickHouse by default and closes
195 * when its scope ends. It maps failures to `SqlError` and aborts and kills
196 * in-flight queries on interruption.
197 *
198 * @stability unstable
199 * @category constructors
200 * @since 4.0.0
201 */
202export const make = (
203 options: ClickhouseClientConfig
204): Effect.Effect<ClickhouseClient & Client.SqlClient, SqlError, Scope.Scope | Reactivity.Reactivity> =>
205 Effect.gen(function*() {
206 const compiler = makeCompiler(options.transformQueryNames)
207 const transformRows = options.transformResultNames
208 ? Statement.defaultTransforms(options.transformResultNames).array
209 : undefined
210
211 const client = yield* Effect.acquireRelease(
212 Effect.sync(() => Clickhouse.createClient(options)),
213 (client) => Effect.promise(() => client.close())
214 )
215
216 if (!options.disableInitialPing) {
217 yield* Effect.tryPromise({
218 try: async () => {
219 const result = await client.ping()
220 if (!result.success) {
221 throw result.error
222 }
223 return result
224 },
225 catch: (cause) =>
226 new SqlError({ reason: classifyError(cause, "ClickhouseClient: Failed to connect", "connect", "connection") })
227 }).pipe(
228 Effect.timeoutOrElse({
229 duration: Duration.seconds(5),
230 orElse: () =>
231 Effect.fail(
232 new SqlError({
233 reason: new ConnectionError({
234 message: "ClickhouseClient: Connection timeout",
235 cause: new Error("connection timeout"),
236 operation: "connect"
237 })
238 })
239 )
240 })
241 )
242 }
243
244 class ConnectionImpl implements Connection {
245 private conn: Clickhouse.ClickHouseClient
246 constructor(conn: Clickhouse.ClickHouseClient) {
247 this.conn = conn
248 }
249
250 private runRaw(sql: string, params: ReadonlyArray<unknown>, format: Clickhouse.DataFormat = "JSON") {
251 const paramsObj: Record<string, unknown> = {}
252 for (let i = 0; i < params.length; i++) {
253 paramsObj[`p${i + 1}`] = params[i]
254 }
255 return Effect.withFiber<Clickhouse.ResultSet<"JSON"> | Clickhouse.CommandResult, SqlError>((fiber) => {
256 const method = fiber.getRef(ClientMethod)
257 return Effect.callback<Clickhouse.ResultSet<"JSON"> | Clickhouse.CommandResult, SqlError>((resume) => {
258 const queryId = fiber.getRef(QueryId) ?? Crypto.randomUUID()
259 const settings = fiber.getRef(ClickhouseSettings)
260 const controller = new AbortController()
261 if (method === "command") {
262 this.conn.command({
263 query: sql,
264 query_params: paramsObj,
265 abort_signal: controller.signal,
266 query_id: queryId,
267 clickhouse_settings: settings
268 }).then(
269 (result) => resume(Effect.succeed(result)),
270 (cause) =>
271 resume(
272 Effect.fail(
273 new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
274 )
275 )
276 )
277 } else {
278 this.conn.query({
279 query: sql,
280 query_params: paramsObj,
281 abort_signal: controller.signal,
282 query_id: queryId,
283 clickhouse_settings: settings,
284 format
285 }).then(
286 (result) => resume(Effect.succeed(result)),
287 (cause) =>
288 resume(
289 Effect.fail(
290 new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
291 )
292 )
293 )
294 }
295 return Effect.suspend(() => {
296 controller.abort()
297 return killQuery(this.conn, queryId)
298 })
299 })
300 })
301 }
302
303 private run(sql: string, params: ReadonlyArray<unknown>, format?: Clickhouse.DataFormat) {
304 return this.runRaw(sql, params, format).pipe(
305 Effect.flatMap((result) => {
306 if ("json" in result) {
307 return Effect.tryPromise({
308 try: () => result.json().then((result) => "data" in result ? result.data : result as any),
309 catch: (cause) =>
310 new SqlError({ reason: classifyError(cause, "Failed to parse result", "parseResult") })
311 })
312 }
313 return Effect.succeed([])
314 })
315 )
316 }
317
318 execute(
319 sql: string,
320 params: ReadonlyArray<unknown>,
321 transformRows: (<A extends object>(row: ReadonlyArray<A>) => ReadonlyArray<A>) | undefined
322 ) {
323 return transformRows
324 ? Effect.map(this.run(sql, params), transformRows)
325 : this.run(sql, params)
326 }
327 executeRaw(sql: string, params: ReadonlyArray<unknown>) {
328 return this.runRaw(sql, params)
329 }
330 executeValues(sql: string, params: ReadonlyArray<unknown>) {
331 return this.run(sql, params, "JSONCompact")
332 }
333 executeValuesUnprepared(sql: string, params: ReadonlyArray<unknown>) {
334 return this.executeValues(sql, params)
335 }
336 executeUnprepared(sql: string, params: ReadonlyArray<unknown>, transformRows?: any) {
337 return this.execute(sql, params, transformRows)
338 }
339 executeStream(
340 sql: string,
341 params: ReadonlyArray<unknown>,
342 transformRows: (<A extends object>(row: ReadonlyArray<A>) => ReadonlyArray<A>) | undefined
343 ) {
344 const conn = this.conn
345 return Effect.withFiber((fiber) => {
346 const queryId = fiber.getRef(QueryId) ?? Crypto.randomUUID()
347 return this.runRaw(sql, params, "JSONEachRow").pipe(
348 Effect.provideService(QueryId, queryId),
349 Effect.map((result) => {
350 if (!("stream" in result)) {
351 return Stream.empty
352 }
353 // Closing the socket does not stop a query the server is still
354 // computing, so kill it unless the response was read to the end.
355 let done = false
356 return NodeStream.fromReadable<ReadonlyArray<Clickhouse.Row<any, "JSONEachRow">>, SqlError>({
357 evaluate: () => result.stream() as any,
358 onError: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute stream", "stream") })
359 }).pipe(
360 Stream.onEnd(Effect.sync(() => {
361 done = true
362 })),
363 Stream.ensuring(Effect.suspend(() => done ? Effect.void : Effect.ignoreCause(killQuery(conn, queryId))))
364 )
365 })
366 )
367 }).pipe(
368 Stream.unwrap,
369 Stream.chunks,
370 Stream.mapEffect((chunk) => {
371 const promises: Array<Promise<any>> = []
372 for (const rows of chunk) {
373 for (const row of rows) {
374 promises.push(row.json())
375 }
376 }
377 return Effect.tryPromise({
378 try: () => Promise.all(promises).then((rows) => transformRows ? transformRows(rows) : rows),
379 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to parse row", "parseRow") })
380 })
381 }),
382 Stream.flattenIterable
383 )
384 }
385 }
386
387 const connection = new ConnectionImpl(client)
388
389 return Object.assign(
390 yield* Client.make({
391 driver: "clickhouse",
392 acquirer: Effect.succeed(connection),
393 compiler,
394 spanAttributes: [
395 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
396 [ATTR_DB_SYSTEM_NAME, "clickhouse"],
397 [ATTR_DB_NAMESPACE, options.database ?? "default"]
398 ],
399 beginTransaction: "BEGIN TRANSACTION",
400 transformRows
401 }),
402 {
403 [TypeId]: TypeId as TypeId,
404 config: options,
405 client,
406 param(dataType: string, value: unknown) {
407 return Statement.fragment([clickhouseParam(dataType, value)])
408 },
409 asCommand<A, E, R>(effect: Effect.Effect<A, E, R>) {
410 return Effect.provideService(effect, ClientMethod, "command")
411 },
412 insertQuery<T = unknown>(options: {
413 readonly table: string
414 readonly values: Clickhouse.InsertValues<Readable, T>
415 readonly format?: Clickhouse.DataFormat
416 readonly columns?: NonNullable<Clickhouse.InsertParams<Readable, T>["columns"]>
417 }) {
418 return Effect.callback<Clickhouse.InsertResult, SqlError>((resume) => {
419 const fiber = Fiber.getCurrent()!
420 const queryId = fiber.getRef(QueryId) ?? Crypto.randomUUID()
421 const settings = fiber.getRef(ClickhouseSettings)
422 const controller = new AbortController()
423 client.insert({
424 format: "JSONEachRow",
425 ...options,
426 abort_signal: controller.signal,
427 query_id: queryId,
428 clickhouse_settings: settings
429 }).then(
430 (result) => resume(Effect.succeed(result)),
431 (cause) =>
432 resume(Effect.fail(new SqlError({ reason: classifyError(cause, "Failed to insert data", "insert") })))
433 )
434 return Effect.suspend(() => {
435 controller.abort()
436 return killQuery(client, queryId)
437 })
438 })
439 },
440 withQueryId: dual(
441 2,
442 <A, E, R>(effect: Effect.Effect<A, E, R>, queryId: string) => Effect.provideService(effect, QueryId, queryId)
443 ),
444 withClickhouseSettings: dual(
445 2,
446 <A, E, R>(
447 effect: Effect.Effect<A, E, R>,
448 settings: NonNullable<Clickhouse.BaseQueryParams["clickhouse_settings"]>
449 ) => Effect.provideService(effect, ClickhouseSettings, settings)
450 )
451 }
452 )
453 })
454
455/**
456 * Fiber reference read by the low-level ClickHouse connection to choose query
457 * or command execution for statements; defaults to `query`.
458 *
459 * @stability unstable
460 * @category services
461 * @since 4.0.0
462 */
463export const ClientMethod = Context.Reference<"query" | "command" | "insert">(
464 "@effect/sql-clickhouse/ClickhouseClient/ClientMethod",
465 {
466 defaultValue: () => "query"
467 }
468)
469
470/**
471 * Fiber reference for the ClickHouse `query_id` applied to queries and
472 * inserts; a random UUID is generated when no query ID is set.
473 *
474 * @stability unstable
475 * @category services
476 * @since 4.0.0
477 */
478export const QueryId = Context.Reference<string | undefined>(
479 "@effect/sql-clickhouse/ClickhouseClient/QueryId",
480 { defaultValue: () => undefined }
481)
482
483/**
484 * Fiber reference containing ClickHouse settings to attach to queries,
485 * commands, and inserts.
486 *
487 * @stability unstable
488 * @category services
489 * @since 4.0.0
490 */
491export const ClickhouseSettings: Context.Reference<
492 NonNullable<Clickhouse.BaseQueryParams["clickhouse_settings"]>
493> = Context.Reference("@effect/sql-clickhouse/ClickhouseClient/ClickhouseSettings", {
494 defaultValue: () => ({})
495})
496
497/**
498 * Provides both `ClickhouseClient` and generic `SqlClient` services from a
499 * `Config`-backed ClickHouse client configuration.
500 *
501 * @stability unstable
502 * @category layers
503 * @since 4.0.0
504 */
505export const layerConfig: (
506 config: Config.Wrap<ClickhouseClientConfig>
507) => Layer.Layer<ClickhouseClient | Client.SqlClient, Config.ConfigError | SqlError> = (
508 config: Config.Wrap<ClickhouseClientConfig>
509): Layer.Layer<ClickhouseClient | Client.SqlClient, Config.ConfigError | SqlError> =>
510 Layer.effectContext(
511 Config.unwrap(config).pipe(
512 Effect.flatMap(make),
513 Effect.map((client) =>
514 Context.make(ClickhouseClient, client).pipe(
515 Context.add(Client.SqlClient, client)
516 )
517 )
518 )
519 ).pipe(Layer.provide(Reactivity.layer))
520
521/**
522 * Provides both `ClickhouseClient` and generic `SqlClient` services from a
523 * ClickHouse client configuration.
524 *
525 * @stability unstable
526 * @category layers
527 * @since 4.0.0
528 */
529export const layer = (
530 config: ClickhouseClientConfig
531): Layer.Layer<ClickhouseClient | Client.SqlClient, Config.ConfigError | SqlError> =>
532 Layer.effectContext(
533 Effect.map(make(config), (client) =>
534 Context.make(ClickhouseClient, client).pipe(
535 Context.add(Client.SqlClient, client)
536 ))
537 ).pipe(Layer.provide(Reactivity.layer))
538
539const typeFromUnknown = (value: unknown): string => {
540 if (Statement.isFragment(value)) {
541 return typeFromUnknown(value.segments[0])
542 } else if (isClickhouseParam(value)) {
543 return value.paramA
544 } else if (Array.isArray(value)) {
545 return `Array(${typeFromUnknown(value[0])})`
546 }
547 switch (typeof value) {
548 case "number":
549 return "Float64"
550 case "bigint":
551 return "Int64"
552 case "boolean":
553 return "Bool"
554 case "object":
555 if (value instanceof Date) {
556 return "DateTime"
557 }
558 return "String"
559 default:
560 return "String"
561 }
562}
563
564/**
565 * Creates the SQL statement compiler for ClickHouse, emitting typed
566 * `{pN: Type}` placeholders and escaping identifiers with an optional query
567 * name transform.
568 *
569 * @stability unstable
570 * @category constructors
571 * @since 4.0.0
572 */
573export const makeCompiler = (transform?: (_: string) => string) =>
574 Statement.makeCompiler<ClickhouseCustom>({
575 dialect: "clickhouse",
576 placeholder(i, u) {
577 return `{p${i}: ${typeFromUnknown(u)}}`
578 },
579 onIdentifier: transform ?
580 function(value, withoutTransform) {
581 return withoutTransform ? escape(value) : escape(transform(value))
582 } :
583 escape,
584 onRecordUpdate() {
585 return ["", []]
586 },
587 onCustom(type, placeholder) {
588 return [placeholder(type), [type.paramB]]
589 }
590 })
591
592// compiler helpers
593
594const escape = Statement.defaultEscape("\"")
595
596/**
597 * Custom SQL fragment type used for ClickHouse typed parameters created by
598 * `ClickhouseClient.param`.
599 *
600 * @stability unstable
601 * @category models
602 * @since 4.0.0
603 */
604export type ClickhouseCustom = ClickhouseParam
605
606/**
607 * @category models
608 * @since 4.0.0
609 */
610interface ClickhouseParam extends Statement.Custom<"ClickhouseParam", string, unknown> {}
611
612const clickhouseParam = Statement.custom<ClickhouseParam>("ClickhouseParam")
613const isClickhouseParam = Statement.isCustom<ClickhouseParam>("ClickhouseParam")