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 versions | 25.11 or later |
| Connection | A 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 checking | Reylo's engine asks ClickHouse itself, over HTTP, so your project needs no client for it |
| Example | clickhouse, 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+:
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:
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 URL | What 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 type | TypeScript | The value .run() returns |
|---|---|---|
Int8, Int16, Int32, UInt8, UInt16, UInt32 | number | 2026 |
Int64 to Int256, UInt64 to UInt256, count() | bigint | 9007199254740993n |
Float32, Float64, BFloat16 | number | 1.5 |
Decimal | string | "12.5" |
Bool | boolean | true |
String, FixedString | string | "Ada" |
UUID | string | "6f9619ff-8b86-d011-b42d-00c04fc964ff" |
IPv4, IPv6 | string | "203.0.113.7" |
Date, Date32 | string | "2026-10-20" |
DateTime, DateTime64 | string, the instant in UTC | "2026-10-20T08:00:00.123Z" |
Enum8, Enum16 | the 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 names | an 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 name | an array of objects | [{ sku: "A1", quantity: 2 }] |
Nullable(T) | T | null | null |
LowCardinality(T) | the type of T | "pro" |
Variant(T1, T2) | the union of its types, or null | 7 |
Point, Ring, Polygon and the other geometric types | the 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 });SELECT id, total, placed_at, ships_on, items, attributes
FROM
WHERE id = {id:UInt64}
LIMIT 1Reylo 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 .();SELECT user_id, sum(total) AS spent, count() AS orders
FROM
GROUP BY user_idDates 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" });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 type | Instead |
|---|---|
JSON, Dynamic | toJSONString(x), or one path as its own type, x.price::Float64 |
AggregateFunction | The finished value, finalizeAggregation(x), or an aggregate with -Merge |
An interval, Time, Time64 | toString(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,0or'', notNULL. With the settingjoin_use_nulls, its columns areNullableinstead. 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-OrNullform,maxOrNull(total), returnsNULL. - 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 .();SELECT u.name, u.email, o.total, o.ships_on
FROM u
LEFT JOIN o ON o.user_id = u.idA 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 .();SELECT u.name, o.total
FROM u
LEFT JOIN o ON o.user_id = u.id
SETTINGS join_use_nulls = 1A 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 BYreturns 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 saysLIMIT 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 stats = await .(, { : 1 });SELECT id, name, email
FROM
WHERE id = {id:UInt64}
LIMIT 1SELECT 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:
| Where | What drops the row |
|---|---|
| The query | HAVING, QUALIFY, OFFSET, LIMIT BY, WITH TIES, a LIMIT of 0 or of a parameter |
| The session's settings | limit, 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::StringWrite 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 type | A parameter takes |
|---|---|
Int8 to Int32, UInt8 to UInt32 | number |
Int64 to Int256, UInt64 to UInt256 | number or bigint |
Float32, Float64, BFloat16 | number |
Decimal | string |
Bool | boolean |
String, FixedString, UUID, IPv4, IPv6 | string |
Date, Date32, DateTime, DateTime64 | string |
Enum8, Enum16 | the 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"] });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
numberpast 2^53 - 1 where the type is wider (pass abigint) - 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'tNullable
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:
| Function | What it reads from the query |
|---|---|
toDateTime64 | its scale |
CAST | the type it names |
toTimeZone | its zone |
tupleElement | which 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 placedFROM 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 });SELECT formatDateTime(placed_at, {format:String}) AS period,
quantile({level:Float64})(toFloat64(total)) AS typical
FROM
GROUP BY periodClickHouse 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
INSERTis built, each row of itsVALUESas theSELECTof its values. A table, a column or a value that doesn't fit is an error. - A
DELETEor anUPDATEis checked as theSELECTof the rows it changes and the values it writes. So areALTER TABLE … UPDATEandALTER 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))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))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
UInt8in aUInt64column - a whole number in a float or a decimal that holds it exactly, as a
UInt32in aFloat64column - a
Float32in aFloat64column, and a decimal with no more digits on either side of the point - a
Boolin a whole number, and aDatein aDate32 - a
DateTimein aDateTime64, and aDateTime64in 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
Nullablecolumn - any type, in a
Dynamiccolumn
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 }:
| Field | What it holds |
|---|---|
code | The error's name, as "VIOLATED_CONSTRAINT" |
number | The error's number, as 469 |
message | The server's message |
An insert a constraint refuses:
import from "./ch_add_order.sql";
const = await .(, { : 8, : 1, : "-1" });
if (.?. === "VIOLATED_CONSTRAINT") {
..number;}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:
| Limit | Instead |
|---|---|
A JSON, Dynamic, AggregateFunction, interval, Time or Time64 column | Select it as a type Reylo reads (above) |
A String or FixedString value that isn't UTF-8 text, such as a hash's bytes | Select it as text: hex(x) or base64Encode(x) |
A Tuple with no elements, as tuple() returns | Leave 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 Variant | Write 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 UTC | Declare the parameter with the zone, as DateTime64(3, 'UTC') |
| A parameter whose text is over 128 KiB, such as an array of several thousand ids | Send 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 column | Give it an alias: count() AS orders |
An INSERT … FORMAT, whose rows are the request's body | VALUES with parameters, or your client's insert() |
A row of VALUES past the 32nd, or one that writes DEFAULT or a map in braces | None: 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 function | None: 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 text | Convert 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 type | Turn the setting off |
A String value with a parameter written to a Variant of several types, which ClickHouse reads as any of them | Convert 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 value | Convert 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 declares | Declare 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 column | None: the type check runs no write |
An ALTER TABLE with several commands | One statement for each command |
WITH TOTALS and the extremes setting, whose extra rows a typed result has no place for | WITH ROLLUP, whose totals are rows, or a second query |
A SETTINGS clause that names the result's format, default_format | Leave 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 table | Run it on your client |
A clickhouse+https:// server whose certificate no public authority signed, such as a self-signed one | None: 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 marked | None: the type check stops at an older server, and .run() refuses the result |
| The Rust crate | None: sqlx has no ClickHouse driver |