> ## Documentation Index
> Fetch the complete documentation index at: https://www.artie.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# ClickHouse source: setup and configuration

> Replicate ClickHouse tables with Artie: create a read-only user, check each table's engine, and pick a cursor column for MergeTree tables.

ClickHouse has no change log to follow, so Artie snapshots each table once and then polls it for new rows. How a table streams depends on its engine.

> **Note:**
>
> ClickHouse sources are in preview. Ask Artie to turn them on for your company. Until then, ClickHouse isn't listed under sources.

## Prerequisites

* The address of your ClickHouse service, as `host:port`. Artie connects over the native protocol with TLS, so use the secure native port, `9440` on ClickHouse Cloud. See [Find the address](/docs/destinations/clickhouse#find-the-address).
* A network path from Artie. Add the [fixed IP addresses](/docs/connection-options#fixed-ip-addresses) for your data plane to your service's IP access list.
* The name of the database to replicate. It can only contain letters, digits, `.`, `_` and `-`, since it's part of each table's Kafka topic name.
* Tables Artie can stream. See [Table engines](#table-engines).

## Prepare ClickHouse

Do these steps before you connect ClickHouse in Artie. The **Prepare** step of the pipeline setup shows the same script, filled in with your user and database.

**Step 1: Create a read-only user**

Replace `<password>` with the user's password and `<database>` with the database you replicate:

```sql setup.sql
-- readonly = 2 blocks writes but lets the client set query settings like max_execution_time.
CREATE USER artie IDENTIFIED BY '<password>' SETTINGS readonly = 2;

GRANT SELECT ON <database>.* TO artie;

GRANT SELECT ON system.settings TO artie;
GRANT SELECT ON system.data_skipping_indices TO artie;
GRANT SELECT ON system.clusters TO artie;
GRANT SELECT ON system.macros TO artie;
```

Artie reads query settings, skipping indexes and, for a `Distributed` table, its cluster from these system tables. Recent ClickHouse versions require a grant for them by default, through `access_control_improvements.select_from_system_db_requires_grant`.

For a `Distributed` table whose local tables live in another database, also grant read access to that database:

```sql
GRANT SELECT ON <local_database>.* TO artie;
```

**Step 2: Check each table's engine**

A `ReplacingMergeTree` with a version column streams as is. A `MergeTree` table, or a `ReplacingMergeTree` without a version, needs a column that grows with every insert. [Table engines](#table-engines) covers each engine.

## Connect ClickHouse in Artie

These steps cover the source part of the pipeline setup.

**Step 1: Choose the source**

On **Choose your source**, select **ClickHouse**, then select **Continue**.

**Step 2: Prepare ClickHouse**

Run the script from [Prepare ClickHouse](#prepare-clickhouse), then select **Continue**.

**Step 3: Enter the connection settings**

Fill in the [connection settings](#connection-settings).

**Step 4: Verify the source**

Select **Verify source**. The step shows **Source verified**.

**Step 5: Choose tables**

Select **Continue** to choose the tables to replicate. Set a [cursor column](#cursor-columns) on each table that needs one, and a **Merge key** on each `MergeTree` table.

ClickHouse source readers can't be shared between pipelines, since each table's cursor column and merge key live on the reader. Each pipeline gets its own.

### Connection settings

| Field             | Value                                                                                                      |
| ----------------- | ---------------------------------------------------------------------------------------------------------- |
| **Address**       | The host and secure native port of your service, for example `abc123.us-east-1.aws.clickhouse.cloud:9440`. |
| **Username**      | The read-only user, `artie` in `setup.sql`.                                                                |
| **Password**      | The user's password.                                                                                       |
| **Database name** | The database you replicate. Only letters, digits, `.`, `_` and `-`.                                        |

## Replication behavior

These sections describe how Artie reads a ClickHouse source once the pipeline runs.

### How does Artie read changes from ClickHouse?

Artie snapshots each table once, then polls it for rows past its cursor: the table's version column, or the cursor column you picked.

* Each table is polled every 5 minutes. A table that's catching up is polled again right away.
* Every poll also reads the rows that arrived in the last 5 minutes again, since ClickHouse has no commit order and an insert can become visible after a higher value was read. The destination upserts by primary key, so reading a row twice is harmless.
* Up to 4 tables are read at a time.

### Table engines

| Engine                                                                                      | How it streams                                                                                                                                    |
| ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ReplacingMergeTree(version)` or `ReplacingMergeTree(version, is_deleted)`                  | By its version column. No cursor column.                                                                                                          |
| `ReplacingMergeTree` without a version                                                      | By a [cursor column](#cursor-columns).                                                                                                            |
| `MergeTree`, `ReplicatedMergeTree`, `SharedMergeTree`                                       | By a [cursor column](#cursor-columns), and a **Merge key**, since the sorting key isn't unique.                                                   |
| `Distributed`                                                                               | Like its local table. On more than one shard, it has to be sharded by a sorting key column, or a deterministic hash of one like `cityHash64(id)`. |
| `SummingMergeTree`, `AggregatingMergeTree`, `CollapsingMergeTree` and other merging engines | Can't stream. Their stored rows are merged into rows that were never inserted.                                                                    |
| Materialized views                                                                          | Can't be replicated. Replicate the table the view writes to instead.                                                                              |
| `Kafka`, `RabbitMQ`, `NATS`, `FileLog`, `S3Queue`, `AzureQueue`                             | Can't be replicated, since reading them consumes their messages.                                                                                  |

A `ReplacingMergeTree` version has to grow across the whole table, like an update time or a table-wide counter. A per-key revision counter (1, 2, 3 for each key) puts a key's new versions below values already read, so they're missed. A `Date` version can't stream, since rows written later in a day share a value already read.

### Cursor columns

A table without a version column streams by a cursor column you pick. It has to be a non-`Nullable` integer, `DateTime` or `DateTime64` column that grows with every insert. An ingestion time works well:

```sql
ALTER TABLE events ADD COLUMN inserted_at DateTime64(3) DEFAULT now64(3);
ALTER TABLE events MATERIALIZE COLUMN inserted_at;
```

`MATERIALIZE COLUMN` writes the value into rows that were already in the table, so they keep one value instead of computing a new one on every read.

Set the column in the pipeline setup with **Cursor column**, or later in the table's advanced settings. Leave it empty for a `ReplacingMergeTree` with a version column.

If the cursor column isn't in the sorting key or partition key and has no minmax index, every poll reads the whole column. Add an index:

```sql
ALTER TABLE events ADD INDEX inserted_at_minmax inserted_at TYPE minmax;
ALTER TABLE events MATERIALIZE INDEX inserted_at_minmax;
```

#### Changing a cursor column

Changing a deployed table's cursor column backfills that table again, since the old column's values can't be compared with the new one's. The change is refused while the table is paused or backfilling.

### Deletes

Only a `ReplacingMergeTree` with an `is_deleted` column sends deletes: a row marked deleted is deleted in the destination. Rows removed by a lightweight `DELETE`, `ALTER TABLE … DELETE`, `TRUNCATE` or a TTL aren't sent, and stay in the destination.

A `CLEANUP` merge, from `OPTIMIZE … FINAL CLEANUP` or `allow_experimental_replacing_merge_with_cleanup`, can remove a deleted row before Artie reads it. That delete is missed.

### Recreated and truncated tables

If a table is dropped and created again, the pipeline stops with `the table was dropped and created again`, since its saved position no longer matches the table. Contact Artie to reset the table's position and backfill it. A truncated table doesn't stop the pipeline, but its old rows stay in the destination until you [backfill](/docs/pipelines/backfill) it.

### User settings

Some settings on the ClickHouse user's profile would make Artie read part of a table, or rows it shouldn't, without an error. The pipeline stops with `the ClickHouse user's settings would make the snapshot incomplete or wrong` and the settings to change, for example `limit`, `offset`, or `apply_deleted_mask = 0`. Change them on the server for Artie's user.

### Schema changes

Each poll reads the table's columns again, so a column added or dropped is picked up on the next poll. [Schema evolution](/docs/guides/artie/schema-evolution) covers how Artie applies schema changes in the destination.

### Supported data types

* `Int8` to `Int256`, `UInt8` to `UInt256`
* `Decimal`, `Decimal32`, `Decimal64`, `Decimal128`, `Decimal256`
* `Float32`, `Float64`, `BFloat16`
* `Bool`
* `String`, `FixedString`, `Enum8`, `Enum16`
* `UUID`, `IPv4`, `IPv6`
* `Date`, `Date32`, `DateTime`, `DateTime64`
* `Array`, `Map`, `Tuple`, `Nested`, `JSON`, `Object`, `Variant`, `Dynamic` and the geo types, as JSON
* `Nullable`, `LowCardinality` and `SimpleAggregateFunction` of any of these

`String` and `FixedString` values have to be valid UTF-8. A value that isn't stops the pipeline with `value isn't valid UTF-8`. `ALIAS` and `EPHEMERAL` columns aren't stored, so they aren't replicated.

A column of any other type stops the pipeline with `unsupported type` and the column's name. To replicate the table, [exclude the column](/docs/guides/artie/column-inclusion-exclusion).

## Next steps

* [Backfill tables](/docs/pipelines/backfill)
* [Schema evolution](/docs/guides/artie/schema-evolution)
* [Column inclusion and exclusion](/docs/guides/artie/column-inclusion-exclusion)