NAME

DBD::ClickHouse - DBI driver for ClickHouse over HTTP

SYNOPSIS

use DBI;

my $dbh = DBI->connect(
    'dbi:ClickHouse:database=default;host=localhost;port=8123',
    $user, $password,
    { RaiseError => 1, PrintError => 0 },
);

my $rows = $dbh->selectall_arrayref(
    'SELECT city, temp_c FROM observations WHERE day = ?',
    { Slice => {} },
    '2026-01-15',
);

my $sth = $dbh->prepare('INSERT INTO observations (city, temp_c) VALUES (?, ?)');
$sth->execute('Seattle', 11.5);

$dbh->disconnect;

DESCRIPTION

AI disclosure: this module was written with AI assistance. The maintainer, Mike Schienle, reviewed, tested, and released it. See AI_POLICY.md in the distribution.

The maintainer uses DBD::ClickHouse in production, in his own weather-data processing pipelines.

DBD::ClickHouse is a pure-Perl DBI driver for ClickHouse. It speaks the ClickHouse HTTP interface (port 8123, or 8443 with TLS) and is intended for queries, DDL, metadata, and small or medium inserts. It is the library equivalent of the clickhouse-client invocations many scripts shell out to.

Bulk loading through an external pipe or clickhouse-client CSV stream is not this driver's job. "clickhouse_insert" and execute_array cover multi-row inserts that still fit in a request.

The driver targets Perl 5.16 or newer and ClickHouse servers that provide TabSeparatedWithNamesAndTypes, RowBinaryWithNamesAndTypes and JSONCompactEachRowWithNamesAndTypes (current 23.x through 26.x releases). Version 0.11 was tested against ClickHouse 26.10.2.103.

TRANSPORT AND DESIGN

ClickHouse has two client protocols. The native TCP protocol is fast and precise, and it is also version-fragile: a client has to track blocks, revisions, and every nested type. The HTTP interface is stable, already speaks TLS, and is what clickhouse-client uses when you pass --port 8123. For queries and modest inserts from the same host or the LAN, HTTP is the robust choice. This driver does not implement the native protocol.

Result formats (0.10)

Every result format carries column names and ClickHouse types ahead of the rows, which is enough to fill DBI's NAME, TYPE, PRECISION, SCALE, and NULLABLE without a second round trip. clickhouse_format picks the wire format:

auto (default)

RowBinaryWithNamesAndTypes when every column can be decoded (see rowbinary below), otherwise the same fallbacks as asking for rowbinary explicitly: TSV, then JSON for composite types. The format actually used is in clickhouse_effective_format.

rowbinary

RowBinaryWithNamesAndTypes, opt-in. Decoded by a generated per-result Perl routine: the fastest reader for wide numeric results. Supported column types: (U)Int8-64, Float32/64, Bool, String, FixedString, Date, Date32, DateTime[(tz)], DateTime64(p[, tz]), UUID, IPv4, Enum8/16, Decimal up to 18 digits, and Nullable/LowCardinality of those. Anything else (for example Int128/256, wide Decimal, IPv6, composite types) makes the driver re-run the query as tsv (or json for composite types). DateTime values are formatted in the column time zone, or the server time zone, as the same strings tsv returns; set clickhouse_epoch_dates to get epoch seconds (DateTime) and fractional epoch seconds (DateTime64) instead. Date/Date32 stay YYYY-MM-DD. Float32 values are exact. Columns with Nullable take a slower general path than non-nullable results.

json

JSONCompactEachRowWithNamesAndTypes, the only format in 0.02 and still the fallback for composite types.

A query that already ends in an explicit FORMAT clause is never rewritten. Read the format actually used from the statement attribute clickhouse_effective_format.

For json: the first line is column names, the second is ClickHouse types, and each later line is one row. Integers wider than 32 bits, decimals, and non-finite floats are requested as JSON strings so Perl does not round them. Float32 values are snapped with pack('f') because JSON prints both Float32 and Float64 in decimal.

RowBinary would preserve raw bytes and exact float bits with less parsing, at the cost of a hand-written decoder for Array, Map, Tuple, Variant, and the rest of the type system. JSON plus the quote settings is the smaller surface that still round-trips the types this driver promises. The cost is documented under "LIMITATIONS": a ClickHouse String that is not valid UTF-8 is replaced by the server before it becomes JSON.

Placeholders are ? and are substituted in the client by default, which is the same idea as DBD::MariaDB's emulated prepare. The server never sees a raw ?. Set clickhouse_bind_mode to server to send ClickHouse {name:Type} parameters instead. Server parameters travel in the URL, so a statement whose encoded parameters exceed 32KiB falls back to client substitution. prepare does not contact the server.

REQUIREMENTS

DBI itself is XS and needs a compiler. DBD::ClickHouse does not. The JSON modules above are optional and, on a Mac, cpanm Cpanel::JSON::XS is the one to install if large selects matter.

CONNECTING

DBI->connect($dsn, $user, $password, \%attr);

The DSN looks like dbi:ClickHouse: followed by key=value pairs separated by semicolons. Unknown keys are sent to ClickHouse as settings.

dbi:ClickHouse:database=default;host=localhost;port=8123
dbi:ClickHouse:database=default;host=ch.example.net;port=8443;ssl=1
dbi:ClickHouse:url=http://127.0.0.1:8123/?database=default
dbi:ClickHouse:host=localhost;max_threads=2;connect_timeout=5

The user and password belong in connect's second and third arguments. A password in the DSN works and is kept out of the handle's public attributes, trace output, and the request URL. An empty password omits X-ClickHouse-Key, which is what the default user on a local server expects.

DSN keys

host, port

Default host is localhost. Default port is 8123, or 8443 when ssl=1.

database

Default database. Sent on every request. Change it later with clickhouse_database. There is no schema level.

ssl, ssl_verify, ssl_ca_file, ssl_ca_path, ssl_cert, ssl_key, ssl_hostname

ssl=1 turns on HTTPS. Certificate verification is on unless ssl_verify=0. Client certificates are optional.

compression

Default on for remote hosts and off for loopback hosts (localhost, 127.0.0.0/8, ::1), where gzip costs more CPU than it saves (0.02 had it on everywhere). When on, the driver sends Accept-Encoding: gzip and gzips "clickhouse_insert" bodies (streamed inserts use a level-1 deflate stream).

format

auto (default: RowBinary, with TSV/JSON fallback), tsv, rowbinary, or json. See "Result formats (0.10)".

epoch_dates

Default off. With format=rowbinary, return DateTime/DateTime64 as epoch seconds instead of formatted strings.

insert_format

tsv (default) or legacy (the 0.02 JSONEachRow chunked inserts).

insert_rows_per_request

Default 0: one streamed HTTP request per "clickhouse_insert" call. A positive value starts a new request every that many rows.

connect_timeout, read_timeout, write_timeout, timeout

Seconds. timeout sets all three. Defaults are 10, 300, and 300. 0 disables the corresponding read or write deadline. A read deadline covers the wait for the first byte, so a buffered query that runs longer than read_timeout fails on the client.

session_id, session_timeout

Optional ClickHouse session. Temporary tables live in the session. A session runs one query at a time; finish a streaming statement before starting another.

bind_mode

client (default) or server.

streaming

Default for new statements. On. Set clickhouse_streaming => 0 (or streaming=0 in the DSN) for the pre-0.11 buffered behaviour. See "STREAMING".

nested

perl (default), json, or text. Controls Array, Map, and Tuple results.

batch_size, insert_chunk

Defaults 1000 and 100000. batch_size is the execute_array tuple chunk for statements that cannot use the TSV path and the row batch for json streaming. insert_chunk is the number of rows per HTTP body chunk in a streamed insert (0.02: rows per request, default 5000).

auto_reconnect

Default on. A dead socket is reopened. A request that was fully written is not retried, because ClickHouse would run an insert twice.

keep_fixed_padding

Default off. FixedString values lose trailing NUL padding unless this is set.

Any other key

Passed through as a ClickHouse setting, for example max_threads=4. The name query is rejected. Settings that change the output format can break the decoder; use clickhouse_raw for a custom FORMAT.

ATTRIBUTES

Application attributes such as RaiseError, PrintError, HandleError, ChopBlanks, and ShowErrorStatement behave as DBI documents. AutoCommit is always on. Assigning a false value throws.

Driver attributes use the clickhouse_ prefix. They can be set in connect's attribute hash, assigned on the database handle, or, where noted, passed to prepare.

Database handle

clickhouse_database, clickhouse_host, clickhouse_port, clickhouse_user, clickhouse_compression, the timeout attributes, clickhouse_session_id, clickhouse_session_timeout, clickhouse_bind_mode, clickhouse_streaming, clickhouse_nested, clickhouse_batch_size, clickhouse_insert_chunk, clickhouse_auto_reconnect, clickhouse_keep_fixed_padding, clickhouse_format, clickhouse_epoch_dates, clickhouse_insert_format, clickhouse_insert_rows_per_request, clickhouse_ssl and the other clickhouse_ssl_* keys, and clickhouse_settings (a hash reference).

clickhouse_password is write-only.

Read-only: clickhouse_server_version, clickhouse_server_info (hash with version, display_name, timezone, protocol), clickhouse_summary, clickhouse_query_id, clickhouse_exception_name.

clickhouse_summary is the latest user statement's X-ClickHouse-Summary: read_rows, read_bytes, written_rows, written_bytes, total_rows_to_read, result_rows, result_bytes, elapsed_ns, memory_usage, when the server sends them. Internal catalog queries do not replace it.

Statement handle

Set before execute: clickhouse_settings, clickhouse_query_id, clickhouse_streaming, clickhouse_raw, clickhouse_nested, clickhouse_format, clickhouse_epoch_dates.

Read after execute: clickhouse_summary, clickhouse_types (ClickHouse type strings), clickhouse_is_num, clickhouse_max_length, clickhouse_rows_fetched, clickhouse_effective_bind_mode, clickhouse_exception_name, clickhouse_rendered, clickhouse_query_id, clickhouse_effective_format (tsv, rowbinary or json).

clickhouse_max_length is the longest Perl string length seen for each string-like or date column, including LowCardinality(String), enums, UUID, IPv4, IPv6, and the date types. Numeric columns stay 0. Measuring them would stringify every value on a large result.

NAME, NAME_lc, NAME_uc, TYPE, PRECISION, SCALE, NULLABLE, NUM_OF_FIELDS, and NUM_OF_PARAMS are the usual DBI fields. TYPE uses the concise DBI type codes (SQL_INTEGER, SQL_VARCHAR, SQL_TIMESTAMP, and so on). RowsInCache is the number of buffered rows not yet fetched, or 0 while streaming.

PLACEHOLDERS AND BINDING

? is a placeholder outside of strings, quoted identifiers, and comments. Bind with bind_param or pass values to execute. undef is SQL NULL and is distinct from ''.

$sth->bind_param(1, '2026-01-15', { clickhouse_type => 'Date' });
$sth->bind_param(2, 10, { TYPE => DBI::SQL_INTEGER });
$sth->bind_param(3, undef, { clickhouse_type => 'Nullable(Float64)' });

In client mode the driver renders a ClickHouse literal. Perl strings stay quoted, so leading zeros survive. Perl numbers (the internal IV/NV flags, not merely a string of digits) are sent as numbers. Array references become array literals and hash references become map() calls. Pass clickhouse_type when the column is not a string, especially for dates, decimals, and typed arrays. An empty array with no type is CAST([] AS Array(String)).

clickhouse_type is checked against a type grammar. Names that contain statement breaks, comments, or backticks are rejected.

Server mode rewrites each ? to {pN:Type} and sends param_pN. The type comes from clickhouse_type, then from the DBI TYPE, then from a guess. execute_array always uses client literals, because one HTTP insert carries many rows.

TYPE MAPPING

Integers

Int8 through Int32 and UInt8 through UInt32 become Perl integers. Int64 and UInt64 become Perl integers when they fit in a native IV/UV (the full unsigned 64-bit range on a 64-bit Perl) and decimal strings otherwise. Wider integers are strings.

Floats

Float64 is the JSON number. Float32 is that number snapped to IEEE binary32. inf, -inf, and nan are Perl infinities and NaN.

Decimals

Strings, padded to the type's scale. 1.23 from Decimal(9, 4) is 1.2300.

Strings, enums, UUID, IPv4, IPv6

Perl Unicode strings. ChopBlanks strips trailing spaces from String and Enum. FixedString drops trailing NUL bytes unless clickhouse_keep_fixed_padding is set.

Dates

Date, Date32, DateTime, and DateTime64 are strings in ClickHouse's own rendering (YYYY-MM-DD and YYYY-MM-DD HH:MM:SS with an optional fraction).

Bool

1 or 0, not a JSON boolean object.

Array, Map, Tuple

An array reference, hash reference, or array reference by default. clickhouse_nested can be json or text instead. LowCardinality and Nullable are unwrapped for the value; the original type string is still exposed in clickhouse_types.

NULL

SQL NULL is Perl undef. An empty string stays an empty string.

UNICODE

The HTTP body is UTF-8. Result strings are Perl character strings. Bind values that are character strings are encoded as UTF-8. Byte strings that already contain UTF-8 octets should be decoded with Encode before you bind them; Perl will otherwise treat a string without the UTF-8 flag as Latin-1.

TRANSACTIONS

ClickHouse does not run the statements in this driver inside a transaction. AutoCommit is on and cannot be turned off. begin_work fails for that reason. commit warns and returns true while AutoCommit is on. rollback warns and returns false. Neither warning is a database error, so RaiseError does not fire.

There is no last_insert_id. The method returns undef and does not raise. MergeTree tables do not allocate an insert id.

STREAMING

From 0.11 the default is on: execute starts returning rows as the HTTP body arrives, and the statement owns the connection until finish or the last fetch. To buffer the whole result first (the 0.10 default):

my $sth = $dbh->prepare(
    'SELECT number FROM system.numbers LIMIT 1000000',
    { clickhouse_streaming => 0 },
);

Or set clickhouse_streaming => 0 on the database handle or streaming=0 in the DSN.

Buffered execute reads the whole result before it returns, and rows is the row count (or 0E0 when the result is empty). Streaming execute returns -1. rows stays -1 until the last row has been fetched, and then returns the total (0.02 kept -1); clickhouse_rows_fetched counts rows the application has pulled.

Batch fetch

while (my $rows = $sth->clickhouse_fetch_batch(10_000)) {
    for my $r (@$rows) { ... }   # $r is a fresh array reference
}

clickhouse_fetch_batch($max) returns up to $max rows as an array of array references ($max of 0 or undef: whatever the next network batch decoded, about 1MiB of input), and undef at the end or on error. It works for buffered and streaming statements and every format, and skips DBI's per-row field copy, so it is the fastest way to read a large result. fetchall_arrayref without a slice or max_rows uses the same batches.

A streaming statement owns the connection until finish or the last fetch. Another query on the same handle fails with a message telling you to finish the active statement. finish drops the socket instead of reading a large remainder. The next statement opens a new one. Catalog helpers (table_info, column_info, ping, and the like) force streaming off for that call. selectall_* still works; it just holds the connection for the whole fetch. If you need to start another statement mid-result, turn streaming off or call finish first.

BULK INSERT

execute_array / execute_for_fetch collapse a single INSERT ... VALUES whose placeholders all sit in the final parenthesised list:

my $sth = $dbh->prepare('INSERT INTO t (id, name) VALUES (?, ?)');
my @status;
my $tuples = $sth->execute_array(
    { ArrayTupleStatus => \@status },
    \@ids, \@names,
);

When the final list is exactly (?, ?, ...), 0.10 sends the tuples as one streamed TabSeparated body (one request per execute_array). Tuples whose list also holds expressions keep the 0.02 VALUES chunks of clickhouse_batch_size (default 1000); earlier chunks are already visible and there is nothing to roll back. On the first failed chunk the driver stops pulling tuples. Each failed tuple's status entry is [err, errstr, state].

"clickhouse_insert" (0.10) writes TabSeparated as one chunked HTTP request per call: rows are pulled from the array or coderef and written clickhouse_insert_chunk rows (default 100000) per HTTP chunk, so memory stays flat however many rows the coderef yields. The body is gzipped (deflate level 1) when compression is on. clickhouse_insert_rows_per_request splits a call into several requests. Array, hash and boolean values are written as ClickHouse literals; undef is NULL. A die inside the coderef aborts the request, and ClickHouse discards an incomplete body. clickhouse_insert_format => 'legacy' restores the 0.02 JSONEachRow chunks.

my $n = $dbh->clickhouse_insert(
    'observations',
    [qw(city temp_c)],
    $rows,    # array of arrayrefs, or a coderef returning them
    { types => ['String', 'Float32'] },
);

With an empty column list, rows are hash references; the column list is taken from the sorted keys of the first row (TSV) or the JSON field names (legacy). Columns missing from a hash row are sent as NULL; list them explicitly if you need the column DEFAULT. The return value is the number of written rows, or 0E0 when nothing was written. A table argument may be db.table or [$db, $table].

METADATA

table_info, column_info, primary_key_info, and tables / primary_key query system.tables and system.columns.

The database name is the DBI catalog, the first argument, the same slot DBD::MariaDB uses for the database. There is no schema. Pass undef (or '') as the schema. A schema other than undef or '' matches nothing and returns zero rows, without an error. That includes the mistake of putting the database name in the schema position:

# mydb.events
my $tables = $dbh->table_info('mydb', undef, 'events', 'TABLE');
my $cols   = $dbh->column_info('mydb', undef, 'events', '%');

# schema is the second argument; this is empty on purpose
my $none = $dbh->table_info(undef, 'mydb', 'events');

foreign_key_info returns an empty active statement: ClickHouse has no foreign keys.

primary_key_info reports the MergeTree sorting key named PRIMARY. That key does not mean "unique".

type_info_all lists the common ClickHouse types against DBI type codes, including both SQL_DATE and SQL_TYPE_DATE (and the timestamp pair) so either lookup works. get_info answers the usual ODBC questions: quote character backtick (29), catalog separator . (41), catalog term database (42), no schema term (39), transactions unsupported (46 = SQL_TC_NONE), identifiers case-sensitive (28). An unknown info type returns undef.

data_sources lists dbi:ClickHouse:database=...;host=...;port=... for each database. Passwords are not included. On the driver handle it connects with RaiseError off and returns an empty list if the server cannot be reached. On a database handle it uses the open connection.

ERROR HANDLING

Server failures use the ClickHouse code as err, the server message as errstr, and a SQLSTATE in state. X-ClickHouse-Exception-Code wins when both the header and the body carry a code. Familiar codes include 60 UNKNOWN_TABLE (42S02), 62 SYNTAX_ERROR (42000), 81 UNKNOWN_DATABASE (3D000), 159 TIMEOUT_EXCEEDED (HYT00), and 194 AUTHENTICATION_FAILED (28000). clickhouse_exception_name holds the symbolic name when the message has one.

Client failures use a negative err so they stay true in boolean context: -1 / 08001 connect, -2 / HYT00 timeout, -3 / 08S01 protocol or a dropped connection. Other client mistakes use -3 and a specific SQLSTATE such as 42000 or 07001.

A peer that has already closed a keep-alive socket is that dropped connection, not a fatal signal. Writes and shutdown ignore SIGPIPE (and the socket is created with SO_NOSIGPIPE where the kernel has it), so the process is not killed. The driver reports a connection error and, when clickhouse_auto_reconnect is on, opens a new socket and retries a write that never reached the server.

RaiseError, PrintError, HandleError, and ShowErrorStatement are honoured by DBI. A successful call clears the previous error.

SETTINGS AND QUERY ID

Connection settings from the DSN and clickhouse_settings are sent on every request. A statement's clickhouse_settings override the connection for that statement only. The driver also sends default_format and the JSON quoting settings it needs. Put those keys in clickhouse_settings only when you mean to override the decoder, and prefer clickhouse_raw plus an explicit FORMAT for anything else.

clickhouse_query_id on a statement becomes ClickHouse's query_id. Omit it and the driver generates a UUID. The id that comes back is stored on the statement and, for ordinary statements, on the database handle.

MIGRATING FROM clickhouse-client

# shell
open my $fh, '-|', 'clickhouse-client', '--database', 'default',
    '--query', $sql;

# library
my $dbh = DBI->connect('dbi:ClickHouse:database=default;host=localhost',
    $user, $password, { RaiseError => 1 });
my $sth = $dbh->prepare($sql);
$sth->execute(@bind);
while (my $row = $sth->fetchrow_hashref) { ... }

Keep piping CSV at the client for multi-gigabyte loads. Use placeholders instead of interpolating values into --query. do returns the number of written rows for inserts (or 0E0 when that number is zero) rather than a shell exit code.

MIGRATING FROM DBD::MariaDB

The call pattern is the same: connect, prepare, execute, fetch, do, selectall_arrayref, raise error, quote, quote_identifier. The differences that matter:

  • mariadb_server_prepare corresponds to clickhouse_bind_mode => 'server'. Both drivers emulate prepares in the client by default.

  • mariadb_use_result corresponds to clickhouse_streaming. Both report rows of -1 and block other statements on the handle until the result is finished.

  • Compression and connect/read/write timeouts exist in both drivers (clickhouse_compression, clickhouse_connect_timeout, clickhouse_read_timeout, clickhouse_write_timeout).

  • clickhouse_auto_reconnect defaults on, but a request that already reached the server is not sent again. MariaDB's reconnect has a similar "do not retry a write" hazard; this driver refuses the retry instead of guessing.

  • There is no insert id, no multi-statement strings, no LOAD DATA, and no Unix-socket DSN. Quote with backslash escapes, not by doubling quotes. Identifiers use backticks.

  • clickhouse_types and clickhouse_is_num are the column type metadata. clickhouse_summary replaces the habit of parsing clickhouse-client progress lines.

LIMITATIONS

  • No transactions, no savepoints, no last_insert_id, no multi-statement text, no server-side cursor beyond streaming the HTTP body.

  • prepare does not round-trip to the server, so a bad table name is reported at execute.

  • Streaming rows is -1 until the last row has been fetched. The summary on a streaming response can be incomplete because the driver does not set wait_end_of_query for that mode.

  • A streamed "clickhouse_insert" larger than the server's max_insert_block_size (about 1M rows by default) may commit earlier blocks before a later row fails to parse. Use clickhouse_insert_rows_per_request or insert_format=legacy if you need smaller units of failure, and insert_deduplication_token or a staging table if you need all-or-nothing.

  • rowbinary does not decode Int128/Int256/UInt128/UInt256, Decimal wider than 18 digits, IPv6, or composite types; those results are re-run as tsv or json (one extra round trip per statement handle).

  • A streaming statement holds the connection.

  • execute_array chunks are durable as soon as each request succeeds.

  • Binary String values that are not UTF-8 are not preserved by json; ClickHouse's JSON output replaces them. tsv and rowbinary return them as byte strings.

  • Float32 is recovered by snapping the decimal JSON number, not by reading the original bits. Values that survive toFloat32 match; a number that was not a binary32 to begin with is the nearest binary32.

  • Decimals and integers wider than the native Perl integer are strings.

  • Server-side parameters are limited to about 32KiB in the URL, then the driver switches to client substitution for that call.

  • One HTTP session runs one statement at a time. Do not share a connected handle across ithreads. After fork, call clickhouse_reset_connection in the child before the next query.

  • primary_key_info is the MergeTree key, not a uniqueness constraint.

METHODS

clickhouse_insert

$written = $dbh->clickhouse_insert($table, \@columns, $rows_or_code, \%attr);

Described in "BULK INSERT". \%attr accepts types, clickhouse_settings, clickhouse_query_id, clickhouse_insert_chunk, clickhouse_insert_format, and clickhouse_insert_rows_per_request.

clickhouse_fetch_batch

$rows = $sth->clickhouse_fetch_batch($max);

Described in "Batch fetch".

clickhouse_reset_connection

$dbh->clickhouse_reset_connection;

Closes the keep-alive socket. The next statement connects again.

INSTALLATION

On a Mac, Homebrew Perl is the practical interpreter. The system Perl is often missing or older than 5.16.

brew install perl
brew install cpanminus   # or: curl -L https://cpanmin.us | perl - App::cpanminus

cpanm DBI Cpanel::JSON::XS
cpanm DBD::ClickHouse

From a checkout of this distribution:

perl Makefile.PL
make
make test
make install

# or
cpanm .

cpanm DBI compiles DBI, so the Xcode command-line tools need to be present. Installing DBD::ClickHouse after that is pure Perl. For TLS:

cpanm IO::Socket::SSL

TESTING

Unit tests always run. Live tests run only when a server is reachable:

export DBD_CLICKHOUSE_TEST_DSN='dbi:ClickHouse:database=default;host=127.0.0.1;port=8123'
export DBD_CLICKHOUSE_TEST_USER=default
export DBD_CLICKHOUSE_TEST_PASSWORD=...
# or: export DBD_CLICKHOUSE_TEST_CLIENT_CONFIG=1  (~/.clickhouse-client/config.xml)
prove -lr t

Without DBD_CLICKHOUSE_TEST_DSN the live scripts skip. They create scratch tables named <db>.<prefix>_<pid>_<time>_<n> and drop them at the end or on INT/TERM; they never touch any other table. DBD_CLICKHOUSE_TEST_DB selects the database (otherwise the DSN database= key, or default). DBD_CLICKHOUSE_TEST_PREFIX sets the table-name prefix (default DBD_CH_Test). DBD_CLICKHOUSE_JSON may be PP, XS, or Cpanel to force a decoder. An unknown or missing choice falls back to JSON::PP.

EXAMPLES

Select rows into hashes:

my $rows = $dbh->selectall_arrayref(
    'SELECT city, temp_c FROM observations WHERE day = ?',
    { Slice => {} }, '2026-01-15');

Streaming read of a large result, one batch at a time:

my $sth = $dbh->prepare('SELECT * FROM observations');
$sth->execute;
while (my $batch = $sth->clickhouse_fetch_batch(0)) {
    process_row($_) for @$batch;
}

Batch insert (one streamed HTTP request):

$dbh->clickhouse_insert('observations', [qw(city temp_c)],
    [ ['Seattle', 11.5], ['Austin', 24.0] ]);

DDL:

$dbh->do('CREATE TABLE IF NOT EXISTS observations
          (day Date, city String, temp_c Float32)
          ENGINE = MergeTree ORDER BY (day, city)');

AUTHOR

Mike Schienle <mschienle@cpan.org> (PAUSE ID MSCHIENLE).

COPYRIGHT AND LICENSE

Copyright (C) 2026 by Mike Schienle

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.

SEE ALSO

DBI, DBD::MariaDB, the ClickHouse HTTP interface documentation.