ClickHouse

How Reylo types queries on ClickHouse

Reylo is an engine that infers the types of SQL queries from your live database, for TypeScript.

ClickHouse versions25.11 or later
ConnectionA clickhouse+http:// or clickhouse+https:// URL, the server's HTTP interface, in DATABASE_URL or direct_url
Client@clickhouse/client or @clickhouse/client-web (Client)
Type checkingReylo's engine asks ClickHouse itself, over HTTP, so your project needs no client for it
Exampleclickhouse, a Node project on @clickhouse/client with a lookup, a join, an insert and a delete

The examples on this page use this schema:

View the schema behind the examples
CREATE TABLE users (
  id UInt64,
  name String,
  email Nullable(String),
  role Enum8('admin' = 1, 'member' = 2),
  tags Array(String),
  created_at DateTime64(3, 'UTC')
) ENGINE = MergeTree ORDER BY id;
CREATE TABLE orders (
  id UInt64,
  user_id UInt64,
  total Decimal(12, 2),
  placed_at DateTime64(3, 'UTC'),
  ships_on Nullable(Date),
  items Array(Tuple(sku String, quantity UInt32)),
  attributes Map(String, String),
  CONSTRAINT total_is_positive CHECK total >= 0
) ENGINE = MergeTree ORDER BY (user_id, id);

Connection

Name the database with the URL of ClickHouse's HTTP interface, after clickhouse+:

.env
DATABASE_URL="clickhouse+http://default:secret@localhost:8123/app"

After clickhouse+, the URL reads as @clickhouse/client reads one. A server behind TLS takes clickhouse+https://, as ClickHouse Cloud does on port 8443:

.env
DATABASE_URL="clickhouse+https://default:secret@abc123.us-east-1.aws.clickhouse.cloud:8443/default"

Your client takes the URL without the prefix, http:// or https://.

In the URLWhat it sets
clickhouse_setting_<name>=, or ch_<name>=A setting of the session, as ch_join_use_nulls=1
role=A role for the type check to run as. Your client takes its role as an option, so leave it out of the client's URL
access_token=A bearer token, in place of a user and password
http_header_<name>=A header on every request
pathname=A path in front of the interface, behind a proxy

The type check sets the format it reads and the settings the URL names, and no other. A user who can only read is enough for a SELECT, a DELETE and an UPDATE. An INSERT needs a user who may insert, since ClickHouse builds one to check it.

Where types come from

Reylo types each query from ClickHouse's own description of it.

Reylo asks the live database to DESCRIBE the query, which gives each column's exact type without running it. A scalar subquery is the exception: ClickHouse computes one as it reads the query. ClickHouse's types say everything a result can hold: a column can be null only where its type is Nullable. Reylo adds how many rows the query returns, from EXPLAIN QUERY TREE.

Data types

Each ClickHouse type has one TypeScript type:

SQL typeTypeScriptThe value .run() returns
Int8, Int16, Int32, UInt8, UInt16, UInt32number2026
Int64 to Int256, UInt64 to UInt256, count()bigint9007199254740993n
Float32, Float64, BFloat16number1.5
Decimalstring"12.5"
Boolbooleantrue
String, FixedStringstring"Ada"
UUIDstring"6f9619ff-8b86-d011-b42d-00c04fc964ff"
IPv4, IPv6string"203.0.113.7"
Date, Date32string"2026-10-20"
DateTime, DateTime64string, the instant in UTC"2026-10-20T08:00:00.123Z"
Enum8, Enum16the union of its labels"admin"
Array(T)an array of its element type["a", "b"]
Tuple(T1, T2)a tuple[1, "a"]
Tuple(x T1, y T2), a tuple with namesan object of its fields{ x: 1, y: "a" }
Map(K, V)an array of its pairs, since a map's keys can repeat[{ key: "color", value: "red" }]
Nested(…), read by its namean array of objects[{ sku: "A1", quantity: 2 }]
Nullable(T)T | nullnull
LowCardinality(T)the type of T"pro"
Variant(T1, T2)the union of its types, or null7
Point, Ring, Polygon and the other geometric typesthe tuples and arrays they stand for[1.5, 2.5]

How each type comes back:

import  from "./ch_get_order.sql";

const order = await .(, { : 1 });
const order: {
    id: bigint;
    total: string;
    placed_at: string;
    ships_on: string | null;
    items: {
        sku: string;
        quantity: number;
    }[];
    attributes: {
        key: string;
        value: string;
    }[];
} | null
SELECT id, total, placed_at, ships_on, items, attributes
FROM 
WHERE id = {id:UInt64}
LIMIT 1

Reylo reads every result in ClickHouse's RowBinaryWithNamesAndTypes format, whatever JSON settings your client has. A UInt64 past 2^53 keeps every digit, and a Float64 can be NaN or Infinity.

A Float32 is the number it stores, as a Float32Array gives one: 0.1 kept in a Float32 column reads 0.10000000149011612, where ClickHouse prints 0.1. A FixedString(4) that holds ab reads "ab\0\0", with the null bytes ClickHouse fills it with.

Decimals

A Decimal comes back as its exact text, without trailing zeros:

import  from "./ch_totals.sql";

const sums = await .();
const sums: {
    user_id: bigint;
    spent: string;
    orders: bigint;
}[]
SELECT user_id, sum(total) AS spent, count() AS orders
FROM 
GROUP BY user_id

Dates and times

A DateTime or a DateTime64 comes back as its instant in UTC, whatever time zone the column names. A Date is its ISO 8601 text:

import  from "./ch_recent_orders.sql";

const recent = await .(, { : "2026-10-01T00:00:00Z" });
const recent: {
    id: bigint;
    placed_at: string;
    ships_on: string | null;
}[]
SELECT id, placed_at, ships_on
FROM 
WHERE placed_at >= {since:DateTime64(3, 'UTC')}

An instant has as many fraction digits as its type keeps. Pass one as the same text, with Z or an offset: Reylo refuses one that names no zone.

Types Reylo doesn't read yet

A column of one of these types is an error at the type check, which says what to select instead:

SQL typeInstead
JSON, DynamictoJSONString(x), or one path as its own type, x.price::Float64
AggregateFunctionThe finished value, finalizeAggregation(x), or an aggregate with -Merge
An interval, Time, Time64toString(x), or the number it counts, toInt64(x)

Nullability

A column can be null only where ClickHouse says its type is Nullable, or a Variant.

ClickHouse doesn't make a value NULL the way other databases do, and Reylo reads each case from the server:

  • A LEFT JOIN's missing row holds each column's default value, 0 or '', not NULL. With the setting join_use_nulls, its columns are Nullable instead. An array or a map can't be, and stays empty.
  • An aggregate over no rows, such as max(total), returns the type's default value. Its -OrNull form, maxOrNull(total), returns NULL.
  • A scalar subquery is Nullable, since it can return no row.

How a left join's missing row comes back:

import  from "./ch_users_with_orders.sql";

const rows = await .();
const rows: {
    name: string;
    email: string | null;
    total: string;
    ships_on: string | null;
}[]
SELECT u.name, u.email, o.total, o.ships_on
FROM  u
LEFT JOIN  o ON o.user_id = u.id

A setting such as join_use_nulls or group_by_use_nulls changes a result's types. Write it in the query's own SETTINGS clause, so the type check and your app read the same types:

import  from "./ch_users_with_orders_nulls.sql";

const rows = await .();
const rows: {
    name: string;
    total: string | null;
}[]
SELECT u.name, o.total
FROM  u
LEFT JOIN  o ON o.user_id = u.id
SETTINGS join_use_nulls = 1

A setting in the profile of the user both connections sign in as works the same way.

Every result names its columns' types beside its rows, and .run() holds them against the types the type check read. A difference throws before any row is returned, and names the column. It means your client's session has a setting the type check's lacks, or the table changed after the build.

Cardinality

Reylo infers how many rows a query returns from its aggregates and its LIMIT:

  • An aggregate with no GROUP BY returns exactly one row.
  • A LIMIT 1, written as a number, returns at most one row.
  • Everything else returns any number of rows. ClickHouse enforces no unique key. A table's primary key is the order its rows are stored in, and two rows can share it. So WHERE id = {id:UInt64} can return several rows, and a lookup by key says LIMIT 1.

How a lookup and an aggregate come back:

import  from "./ch_get_user.sql";
import  from "./ch_stats.sql";

const user = await .(, { : 1 });
const user: {
    id: bigint;
    name: string;
    email: string | null;
} | null
const stats = await .(, { : 1 });
const stats: {
    orders: bigint;
    largest: string;
}
SELECT id, name, email
FROM 
WHERE id = {id:UInt64}
LIMIT 1
SELECT count() AS orders, max(total) AS largest
FROM 
WHERE user_id = {user:UInt64}

An aggregate returns at most one row where something can drop its row:

WhereWhat drops the row
The queryHAVING, QUALIFY, OFFSET, LIMIT BY, WITH TIES, a LIMIT of 0 or of a parameter
The session's settingslimit, offset, empty_result_for_aggregation_by_empty_set, additional_result_filter

Parameters

ClickHouse requires every parameter to declare its own type in the query, and Reylo validates values against those types before sending them.

Placeholders

Write parameters as {name:Type}, as ClickHouse does, and pass .run() an object with those names:

SELECT id, name FROM  WHERE email = {email:String}

ClickHouse deduces no parameter's type, so each one declares its own. Reylo's :name works with a cast that gives the type, :email::String, but one statement uses one of the two forms. A name used twice declares the same type each time.

SELECT id, name FROM  WHERE email = :email::String

Write a type by any name ClickHouse knows it by: int for Int32, text for String.

What a parameter takes

A parameter accepts the same values .run() returns for its type:

SQL typeA parameter takes
Int8 to Int32, UInt8 to UInt32number
Int64 to Int256, UInt64 to UInt256number or bigint
Float32, Float64, BFloat16number
Decimalstring
Boolboolean
String, FixedString, UUID, IPv4, IPv6string
Date, Date32, DateTime, DateTime64string
Enum8, Enum16the union of its labels
Array(T)an array
Tuple(…)a tuple, or an object where the tuple has names
Map(K, V)an array of { key, value } pairs
Nullable(T)what T takes, or null; such a parameter can be left out

How arrays go in:

import  from "./ch_users_in.sql";

const users = await .(, { : [1, 2, 3n], : ["admin"] });
const users: {
    id: bigint;
    name: string;
    role: "admin" | "member";
}[]
SELECT id, name, role
FROM 
WHERE id IN {ids:Array(UInt64)}
  AND role IN {roles:Array(Enum8('admin' = 1, 'member' = 2))}

Reylo checks each value against its type before the query runs. ClickHouse doesn't always: it reads 300 for a UInt8 as 44. Each of these throws, and names the parameter:

  • a number outside its type's range
  • a number past 2^53 - 1 where the type is wider (pass a bigint)
  • a decimal with more digits than its type holds
  • a date or a time outside its type's range (1900 through 2299 for a DateTime64)
  • a date that isn't on the calendar, such as 30 February
  • a string that holds half of a surrogate pair
  • a named tuple with a member missing, or one the type doesn't have
  • a null, or an empty slot of an array, where the type isn't Nullable

Where a parameter can't go

A parameter can't stand where its value would change the query's types.

ClickHouse writes a parameter's value into the query before it reads it. So some functions read one as part of the query:

FunctionWhat it reads from the query
toDateTime64its scale
CASTthe type it names
toTimeZoneits zone
tupleElementwhich element

Such a query has no one type, so the type check refuses the parameter where it stands:

SELECT toDateTime64(placed_at, {scale:UInt8}) AS placed
ClickHouse reads {scale:UInt8} as a constant here, and the result's types change with its value: column 1 (placed) has the type DateTime64(1, 'UTC') with 1 and DateTime64(2, 'UTC') with 2. Write the value in the statement. reylo(10)
FROM

A parameter works where ClickHouse needs a constant whose value changes no type:

  • a LIMIT
  • the right side of an IN
  • the format of formatDateTime
  • the unit of dateDiff
  • an aggregate's own parameter

Reylo checks that by describing the query with several values of it:

import  from "./ch_spent_by.sql";

const spent = await .(, { : "%Y-%m", : 0.9 });
const spent: {
    period: string;
    typical: number;
}[]
SELECT formatDateTime(placed_at, {format:String}) AS period,
  quantile({level:Float64})(toFloat64(total)) AS typical
FROM 
GROUP BY period

ClickHouse also computes with a constant as it reads the query. So the type check describes each query with values it can compute with. For a String, those are texts a query commonly reads, such as a date or a time zone. Where the query takes none of them, declare the parameter as the type the query converts it to:

SELECT id, total
FROM 
WHERE placed_at >= {since:DateTime64(3, 'UTC')}

A parameter of the type Identifier stands for a table or a column, and is always refused. Write the name in the query.

Writes

An INSERT, a DELETE or an UPDATE returns nothing, and its parameters are typed as a query's are:

import  from "./ch_add_order.sql";

await .(, { : 7, : 1, : "12.50" });
INSERT INTO  (id, user_id, total, placed_at)
VALUES ({id:UInt64}, {user:UInt64}, {total:Decimal(12, 2)}, now64(3))

The type check has ClickHouse check each write without running it:

  • An INSERT is built, each row of its VALUES as the SELECT of its values. A table, a column or a value that doesn't fit is an error.
  • A DELETE or an UPDATE is checked as the SELECT of the rows it changes and the values it writes. So are ALTER TABLE … UPDATE and ALTER TABLE … DELETE. A value its column doesn't take is an error.

ClickHouse converts whatever a query writes to its column's type, and says nothing where that changes the value. A UInt64 of 300 goes into a UInt8 column as 44. So a value written with a parameter needs a type its column keeps:

INSERT INTO  (id, user_id, total, placed_at)
VALUES ({id:UInt64}, {user:UInt64}, {total:Decimal(18, 4)}, now64(3))
{total:Decimal(18, 4)} is written as it is to the column total, of the type Decimal(12, 2). ClickHouse converts a value of another type to the column's, and changes one the column cannot hold without an error. Declare the parameter as the column's type, {total:Decimal(12, 2)}. reylo(10)

A value computed from a parameter has the type ClickHouse gives it:

INSERT INTO  (id, user_id, total, placed_at)
VALUES ({id:UInt64}, {user:UInt64}, {total:Decimal(12, 2)} * 1.2, now64(3))
{total:Decimal(12, 2)} is in a value of the type Float64 that is written to the column total, of the type Decimal(12, 2). ClickHouse converts a value of another type to the column's, and changes one the column cannot hold without an error. Convert the value in the statement, as CAST(… AS Decimal(12, 2)) does. reylo(10)

A sum or a product has a wider type than its operands. It passes where the column keeps each operand's type:

INSERT INTO  (id, user_id, total, placed_at)
VALUES ({id:UInt64}, {user:UInt64}, {total:Decimal(12, 2)} * {rate:Decimal(12, 2)}, now64(3))

That holds in VALUES, in an INSERT … SELECT and in an UPDATE's assignment. A column keeps its own type, and each type it holds every value of:

  • a whole number of fewer bits, as a UInt8 in a UInt64 column
  • a whole number in a float or a decimal that holds it exactly, as a UInt32 in a Float64 column
  • a Float32 in a Float64 column, and a decimal with no more digits on either side of the point
  • a Bool in a whole number, and a Date in a Date32
  • a DateTime in a DateTime64, and a DateTime64 in one of a finer tick, short of nanoseconds
  • an enum whose labels the column's enum has, at the same numbers
  • a type that takes no null, in a Nullable column
  • any type, in a Dynamic column

To write a value of another type, convert it in the query:

INSERT INTO  (id, user_id, total, placed_at)
VALUES ({id:UInt64}, {user:UInt64}, {total:Decimal(12, 2)}, {placed:String}::DateTime64(3, 'UTC'))

An enum column takes a choice between its labels:

UPDATE  SET role = if({admin:Bool}, 'admin', 'member')
WHERE id = {id:UInt64}

To insert many rows in one query, pass them as one array of tuples:

INSERT INTO  (id, user_id, total, placed_at)
SELECT row.1, row.2, row.3, now64(3)
FROM (SELECT arrayJoin({rows:Array(Tuple(UInt64, UInt64, Decimal(12, 2)))}) AS row)

An INSERT … FORMAT takes its rows from the request's body, which a typed query doesn't have. For a bulk load, use your client's own insert().

Database errors

With .try(), an error ClickHouse raised comes back as { error }:

FieldWhat it holds
codeThe error's name, as "VIOLATED_CONSTRAINT"
numberThe error's number, as 469
messageThe server's message

An insert a constraint refuses:

import  from "./ch_add_order.sql";

const  = await .(, { : 8, : 1, : "-1" });
if (.?. === "VIOLATED_CONSTRAINT") {
  ..number;
number: number

The error's number, as 60: ClickHouse's own, which its message opens with.

}

ClickHouse can fail a query after it has sent its first rows, when a later row raises the error. Reylo reads that error from the end of the result. So .run() throws it and .try() returns it, and no partial result comes back.

Client

Reylo runs each query on your app's own client. Use @clickhouse/client in Node.js, and @clickhouse/client-web in a browser or on an edge runtime:

import {  } from "@clickhouse/client";
import  from "./ch_get_user.sql";

const  = ({ : .. });

const  = await .(, { : 1 });

How Reylo uses your client:

  • Reylo decodes results itself. Your client's format and JSON settings don't apply to Reylo's queries, and Reylo's don't change yours.
  • Each parameter goes to the server as ClickHouse's own query parameter, never written into the query's text.
  • The settings your client is made with apply to every query it runs, Reylo's included. Reylo adds only the format it reads and each parameter, which a read-only user may send too.
  • ClickHouse has no transactions across statements. Each query is its own.

Migrations

Reylo Migrate doesn't support ClickHouse yet. Keep your schema with the tool you use today: the type check reads whatever the database holds.

Limits

What Reylo can't type on ClickHouse, and what to do instead:

LimitInstead
A JSON, Dynamic, AggregateFunction, interval, Time or Time64 columnSelect it as a type Reylo reads (above)
A String or FixedString value that isn't UTF-8 text, such as a hash's bytesSelect it as text: hex(x) or base64Encode(x)
A Tuple with no elements, as tuple() returnsLeave it out of the result
A parameter whose value changes the result's types, one that is a partition's id, or one of the type Identifier or VariantWrite the value in the query, or declare the parameter with one type
A DateTime64 parameter given an instant within the second before 1970, which ClickHouse reads as one after it unless the type names UTCDeclare the parameter with the zone, as DateTime64(3, 'UTC')
A parameter whose text is over 128 KiB, such as an array of several thousand idsSend fewer values at a time, or raise the server's http_max_field_value_size
A bare :name, which declares no type{name:Type}, or :name::Type
A write that quotes a name with an escape or a control character in it, such as `a\x41`Write the name without the escape
A column with no name of its own, such as count() beside another columnGive it an alias: count() AS orders
An INSERT … FORMAT, whose rows are the request's bodyVALUES with parameters, or your client's insert()
A row of VALUES past the 32nd, or one that writes DEFAULT or a map in bracesNone: its values with parameters are held to their columns, and the rest is checked when the query runs
A parameter inside a map that VALUES writes in braces, as {'k': {v:UInt8}}Write the map with map('k', {v:UInt8})
A value with a parameter written to a column the query doesn't name, in an INSERT whose column list is a * or a COLUMNS(…)Name the columns
A value with a parameter written into a table functionNone: insert into a table
A parameter that VALUES writes to a Dynamic column alone, or in a value that opens with a parenthesis or a bracket: ClickHouse may store the placeholder's own textConvert the value, as CAST(…, 'Dynamic') does, or write the row as an INSERT … SELECT
A String value with a parameter written to a Dynamic column while the setting cast_string_to_dynamic_use_inference is on, which has ClickHouse read the text as another typeTurn the setting off
A String value with a parameter written to a Variant of several types, which ClickHouse reads as any of themConvert it by way of the text alone: CAST(CAST({v:String} AS Variant(String)) AS Variant(String, UInt64))
A value computed with a parameter that ClickHouse reads as a constant, such as a time zone's name: its type may change with the parameter's valueConvert the value in the query, as CAST(… AS DateTime64(3)) does
A parameter passed to a parameterized view, which ClickHouse converts to the type the view declaresDeclare the parameter with the view's type
What only running a write shows, such as a table whose engine takes no UPDATE, or an update of a key columnNone: the type check runs no write
An ALTER TABLE with several commandsOne statement for each command
WITH TOTALS and the extremes setting, whose extra rows a typed result has no place forWITH ROLLUP, whose totals are rows, or a second query
A SETTINGS clause that names the result's format, default_formatLeave it out: Reylo asks for the format it reads
A statement other than a SELECT, an INSERT, a DELETE or an UPDATE, such as CREATE TABLE, SHOW TABLES or an ALTER that changes the tableRun it on your client
A clickhouse+https:// server whose certificate no public authority signed, such as a self-signed oneNone: the type check verifies the certificate against Mozilla's roots
A server before 25.11, or a proxy that drops the X-ClickHouse-Exception-Tag header, where an error that ends a result isn't markedNone: the type check stops at an older server, and .run() refuses the result
The Rust crateNone: sqlx has no ClickHouse driver
Released under the MIT License. Copyright © 2026 Colin McDonnell.

On this page

reylosql/reylo