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

# CrateDB Connector

> Store MQTT data in CrateDB for distributed time-series analytics and SQL queries

## CrateDB Overview

The `CRATEDB` connector stores MQTT messages in CrateDB, a distributed SQL database optimized for time-series and machine data. It combines the familiarity of SQL with the scalability needed for IoT workloads.

> [!NOTE]
>
> CrateDB excels at high-volume time-series data with fast ingestion and SQL query capabilities. Use it when you need real-time analytics on sensor data at scale.

## Basic Syntax

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE CONNECTOR SensorDB WITH TYPE CRATEDB
    ADD CRATEDB_CONFIG
        WITH HOST "cratedb.example.com"
        WITH PORT '5432'
        WITH DATABASE "iot"
        WITH USERNAME "crate"
        WITH PASSWORD "secure_password"
    ADD EVENT StoreSensorReading
        WITH SOURCE_TOPIC "sensors/+/reading"
        WITH QUERY "INSERT INTO sensor_data (ts, sensor_id, value) VALUES (NOW(), '{sensor_id}', '{value.json}')"
```

***

## Connection Configuration

### CRATEDB\_CONFIG Parameters

**HOST** `string` *required*

CrateDB server hostname or IP address.

**USERNAME** `string` *required*

Database username.

**PASSWORD** `string` *required*

Database password.

> [accordion] Optional Settings
>
> **PORT** `integer`
>
> CrateDB PostgreSQL protocol port. Default: 5432.
>
> **DATABASE** `string`
>
> Schema for unqualified table names and for `STORE IN`. Default: `doc`. Kept exactly as written, so it is case-sensitive.
>
> **USE\_SSL** `boolean`
>
> Connect over TLS. Default: false. Without it the connection is plain text. See [TLS](#tls).
>
> **TRUST\_SERVER\_CERTIFICATE** `boolean`
>
> Require TLS and accept a certificate the broker cannot verify, such as a self-signed one. Default: false. Applies only when `USE_SSL` is true.
>
> **CONNECTION\_TIMEOUT** `integer`
>
> Seconds to wait for a connection to open. A whole number, 1 or more. Default: 15.
>
> **COMMAND\_TIMEOUT** `integer`
>
> Seconds to wait for an event query or a `STORE IN` insert. A whole number, 0 or more; 0 waits forever. Default: 30.

Deploy refuses a missing `HOST`, a `PORT` outside 1–65535, a `CONNECTION_TIMEOUT` below 1, a `COMMAND_TIMEOUT` that is not a whole number, and a `USE_SSL` or `TRUST_SERVER_CERTIFICATE` that is not `true` or `false`. A password, user, or database that contains `;`, `=`, or a quote is sent as typed.

> [!WARNING]
>
> **Never hardcode credentials in production.** Use environment variables and encrypted secrets to keep sensitive values out of your connector definitions:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> WITH HOST GET ENV "DB_HOST"
> WITH USERNAME GET ENV "DB_USER"
> WITH PASSWORD GET SECRET "DB_PASSWORD"
> ```
>
> See [Environment Variables & Secrets](https://docs.coreflux.org/latest/mqtt-broker/secrets-and-env.md) for setup and usage.

### TLS

| `USE_SSL` | `TRUST_SERVER_CERTIFICATE` | Connection |
| - | - | - |
| `false` or omitted | ignored | Plain text. TLS is not used, even when the server offers it |
| `true` | `false` or omitted | TLS when the server offers it. A plain-text connection is still allowed |
| `true` | `true` | TLS is required, and the server certificate is not validated |

Use `USE_SSL "true"` with `TRUST_SERVER_CERTIFICATE "true"` for a CrateDB node with a self-signed certificate:

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE CONNECTOR PlantCrate WITH TYPE CRATEDB
    ADD CRATEDB_CONFIG
        WITH HOST GET ENV "CRATE_HOST"
        WITH PORT 5432
        WITH DATABASE "plant"
        WITH USERNAME GET ENV "CRATE_USER"
        WITH PASSWORD GET SECRET "CRATE_PASSWORD"
        WITH USE_SSL "true"
        WITH TRUST_SERVER_CERTIFICATE "true"
        WITH CONNECTION_TIMEOUT 15
```

> [!WARNING]
>
> **Action:** A CrateDB node that only accepts TLS now needs `USE_SSL "true"`. Without it the broker no longer tries TLS on its own.

***

## Agent queries

An agent can read this database when the connector opts in and the agent grants `connector_query`. The agent runs one read statement. It cannot insert, update, or delete. See [Database queries](https://docs.coreflux.org/latest/lot-language/agents/syntax.md#database-queries).

The clauses below belong in `CRATEDB_CONFIG`.

| Clause | Default | Effect |
| - | - | - |
| `AGENT_QUERIES` | `"off"` | `"off"` or `"read"`. `"write"` is refused |
| `AGENT_USERNAME` / `AGENT_PASSWORD` | — | Login the agent uses. A separate read-only user is required |
| `AGENT_CONNECTION_STRING` | — | Alternative to the agent user and password |
| `AGENT_MAX_ROWS` | `200` | Most rows returned to the model |

CrateDB is refused unless you set `AGENT_USERNAME` and `AGENT_PASSWORD`, or `AGENT_CONNECTION_STRING`. It does not fall back to a read-only transaction on the connector login.

The person who asks and the agent's `DEFAULT_USER` both need `PublishSys` on `$SYS/Coreflux/Routes/<connector>/Query`.

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE CONNECTOR PlantDB WITH TYPE CRATEDB
    ADD CRATEDB_CONFIG
        WITH HOST GET ENV "CRATEDB_HOST"
        WITH PORT 5432
        WITH DATABASE "plant"
        WITH USERNAME GET ENV "CRATEDB_USER"
        WITH PASSWORD GET SECRET "CRATEDB_PASSWORD"
        WITH AGENT_QUERIES "read"
        WITH AGENT_USERNAME GET ENV "CRATEDB_AGENT_USER"
        WITH AGENT_PASSWORD GET SECRET "CRATEDB_AGENT_PASSWORD"
        WITH AGENT_MAX_ROWS 200
```

***

## How placeholders are quoted

The broker places each placeholder in an event `QUERY` by the quotes around it. A publisher on the source topic can no longer change the SQL by putting SQL in the payload.

> [!WARNING]
>
> **Action:** Put every placeholder that carries text in single quotes (`WHERE status = '{payload}'`). Put a placeholder that names a table or column in double quotes (`FROM "{topic.2}"`). An unquoted placeholder must be a number, a comma-separated list of numbers, `true`, `false`, or `null`. Anything else, including a bare name such as `line_1`, refuses the event. The message names the placeholder.

| Where the placeholder sits | What happens to the value |
| - | - |
| Inside single quotes: `'{payload}'` | Quotes in the value are doubled. |
| Inside double quotes: `"{topic.2}"` | Double quotes in the value are doubled. Use this for a table or column name. |
| Unquoted: `VALUES ({value})` | Only a number, a comma-separated list of numbers, `true`, `false`, or `null`. |
| In a SQL comment | Left as written. |

`{env.NAME}` and `{secret.NAME}` are placed as written. A value that itself contains `{topic}` is stored as text and is not expanded again. The same rules on the other SQL engines are in [How placeholders are quoted](https://docs.coreflux.org/latest/connectors/data-storage/overview#how-placeholders-are-quoted). MongoDB and OpenSearch JSON queries place each value as one JSON value instead (see [OpenSearch placeholders](https://docs.coreflux.org/latest/connectors/data-storage/opensearch.md#placeholders)).

***

## Writing Data

> [tab] Basic Time-Series
>
> Store sensor readings with timestamps:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE CONNECTOR TimeSeriesDB WITH TYPE CRATEDB
>     ADD CRATEDB_CONFIG
>         WITH HOST "cratedb.example.com"
>         WITH PORT '5432'
>         WITH DATABASE "iot"
>         WITH USERNAME "crate"
>         WITH PASSWORD "secure_password"
>     ADD EVENT StoreTimeSeries
>         WITH SOURCE_TOPIC "sensors/+/reading"
>         WITH DESTINATION_TOPIC "db/crate/status"
>         WITH QUERY "INSERT INTO sensor_data (ts, sensor_id, value) VALUES (NOW(), '{sensor_id}', '{value.json}')"
> ```

> [tab] High-Volume Metrics
>
> Optimized for high ingestion rates:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE CONNECTOR MetricsDB WITH TYPE CRATEDB
>     ADD CRATEDB_CONFIG
>         WITH HOST "cratedb.example.com"
>         WITH PORT '5432'
>         WITH DATABASE "metrics"
>         WITH USERNAME "metrics_writer"
>         WITH PASSWORD "secure_password"
>     ADD EVENT StoreMetrics
>         WITH SOURCE_TOPIC "metrics/#"
>         WITH QUERY "INSERT INTO metrics (ts, topic, data) VALUES (NOW(), '{source_topic}', '{value.json}')"
> ```

> [tab] Multiple Tables
>
> Connector to different tables by topic:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE CONNECTOR MultiTableDB WITH TYPE CRATEDB
>     ADD CRATEDB_CONFIG
>         WITH HOST "cratedb.example.com"
>         WITH PORT '5432'
>         WITH DATABASE "iot"
>         WITH USERNAME "crate"
>         WITH PASSWORD "secure_password"
>
>     ADD EVENT StoreSensors
>         WITH SOURCE_TOPIC "sensors/#"
>         WITH QUERY "INSERT INTO sensors (ts, topic, data) VALUES (NOW(), '{source_topic}', '{value.json}')"
>
>     ADD EVENT StoreAlerts
>         WITH SOURCE_TOPIC "alerts/#"
>         WITH QUERY "INSERT INTO alerts (ts, topic, data) VALUES (NOW(), '{source_topic}', '{value.json}')"
> ```

> [tab] UPSERT
>
> Insert or ignore on conflict. CrateDB supports `ON CONFLICT DO NOTHING` to skip duplicate inserts for idempotent ingestion:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE CONNECTOR EventLog WITH TYPE CRATEDB
>     ADD CRATEDB_CONFIG
>         WITH HOST "cratedb.example.com"
>         WITH PORT '5432'
>         WITH DATABASE "iot"
>         WITH USERNAME "crate"
>         WITH PASSWORD "secure_password"
>     ADD EVENT StoreUniqueEvent
>         WITH SOURCE_TOPIC "events/+/occurred"
>         WITH QUERY "INSERT INTO events (event_id, device_id, event_type, ts) VALUES ('{value.json.event_id}', '{value.json.device_id}', '{value.json.event_type}', '{value.json.timestamp}') ON CONFLICT (event_id) DO NOTHING"
> ```
>
> `ON CONFLICT (event_id) DO NOTHING` ensures duplicate messages — common in IoT delivery — never create duplicate rows.

> [tab] UPDATE
>
> Modify existing records when a status change arrives:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE CONNECTOR DeviceRegistry WITH TYPE CRATEDB
>     ADD CRATEDB_CONFIG
>         WITH HOST "cratedb.example.com"
>         WITH PORT '5432'
>         WITH DATABASE "iot"
>         WITH USERNAME "crate"
>         WITH PASSWORD "secure_password"
>     ADD EVENT UpdateDeviceStatus
>         WITH SOURCE_TOPIC "devices/+/status"
>         WITH QUERY "UPDATE devices SET current_status = '{value.json.status}', last_seen = NOW() WHERE device_id = '{value.json.device_id}'"
> ```

> [tab] DELETE
>
> Remove records on a decommission or cleanup event:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE CONNECTOR DeviceRegistry WITH TYPE CRATEDB
>     ADD CRATEDB_CONFIG
>         WITH HOST "cratedb.example.com"
>         WITH PORT '5432'
>         WITH DATABASE "iot"
>         WITH USERNAME "crate"
>         WITH PASSWORD "secure_password"
>     ADD EVENT DecommissionDevice
>         WITH SOURCE_TOPIC "devices/+/decommissioned"
>         WITH QUERY "DELETE FROM devices WHERE device_id = '{value.json.device_id}'"
> ```

> [!NOTE]
>
> **Alternative: STORE IN with Models** — Instead of writing EVENT queries, you can bind a [model](https://docs.coreflux.org/latest/lot-language/models/overview) directly to this connector. Every `PUBLISH MODEL` call automatically inserts a row — no query needed:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE MODEL SensorReading
>     ADD STRING "sensor_id"
>     ADD DOUBLE "value"
>     STORE IN "TimeSeriesDB"
>         WITH TABLE "sensor_data"
> ```
>
> See [Data Storage Overview](https://docs.coreflux.org/latest/connectors/data-storage/overview#with-models-store-in) for the full STORE IN workflow.

***

## Storing models with STORE IN

`STORE IN` writes to the schema set by `DATABASE`, or to `doc` when `DATABASE` is omitted or blank. That is the same schema an event uses for a table name without a schema, so an event can read back what a model stored. The table name is folded to lower case, and column names come from the model fields in lower case.

The first store creates a missing table. A table that already exists keeps its columns. If the table is dropped later, the next store creates it again.

| Model field | New CrateDB column |
| - | - |
| `INT` | `BIGINT` |
| `DOUBLE` | `DOUBLE PRECISION` |
| `BOOL` | `BOOLEAN` |
| `STRING` | `TEXT` |

A model `INT` is a 32-bit whole number. A topic value outside -2147483648 to 2147483647 is logged and the model does not publish, so nothing is stored. The value is no longer stored as 2147483647.

> [!NOTE]
>
> **Upgrading:** Rows that earlier versions stored are in the `doc` schema. When `DATABASE` names another schema, new rows go to that schema, and the old rows stay in `doc`. Copy them over, or query `doc.<table>`, if you still need them.

***

## Reading Data

EVENTs also support SELECT queries to read data back from the database. Publish a message to the event's `SOURCE_TOPIC`, and the query result is published to `DESTINATION_TOPIC`:

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE CONNECTOR SensorDB WITH TYPE CRATEDB
    ADD CRATEDB_CONFIG
        WITH HOST "cratedb.example.com"
        WITH PORT '5432'
        WITH DATABASE "iot"
        WITH USERNAME "crate"
        WITH PASSWORD "secure_password"
    ADD EVENT GetLatestReading
        WITH SOURCE_TOPIC "db/query/latest"
        WITH DESTINATION_TOPIC "db/result/latest"
        WITH QUERY "SELECT sensor_id, value FROM sensor_data WHERE sensor_id = '{payload}' ORDER BY ts DESC LIMIT 1"
```

To trigger this query, publish the sensor ID to the source topic:

```
Topic:   db/query/latest
Payload: temp001
```

The query result is published to `db/result/latest`, where your actions or external clients can consume it.

> [!NOTE]
>
> CrateDB makes new rows visible to reads about once a second. A `SELECT` event that runs right after an insert may not see that row yet. Run `REFRESH TABLE <table>` first when you need it.

### Timed Polling

EVENTs can also run SELECT queries on a fixed schedule using `WITH EVERY`. This is especially powerful with CrateDB's fast aggregations:

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE CONNECTOR TimeSeriesDB WITH TYPE CRATEDB
    ADD CRATEDB_CONFIG
        WITH HOST "cratedb.example.com"
        WITH PORT '5432'
        WITH DATABASE "iot"
        WITH USERNAME "crate"
        WITH PASSWORD "secure_password"
    ADD EVENT PollLatestReadings
        WITH EVERY 5 SECONDS
        WITH DESTINATION_TOPIC "dashboard/sensors/latest"
        WITH QUERY "SELECT device_id, AVG(value) as avg_value, MAX(ts) as last_seen FROM sensor_data WHERE ts > NOW() - INTERVAL '1 minute' GROUP BY device_id ORDER BY device_id"
```

***

## While CrateDB is unreachable

After a connection failure, the next event or `STORE IN` checks CrateDB at once. If CrateDB answers, the work runs. If not, the work is skipped and later checks run at most every 5 seconds. Work that arrives between checks is skipped instead of waiting out `CONNECTION_TIMEOUT`.

Each check logs how many events and `STORE IN` rows were skipped: a warning while CrateDB is still down, and an information line with the total when the connector reconnects.

***

## Checking the connection

`-checkConnectorConnection <Name>` connects to CrateDB and runs `SELECT 1`. A wrong host, port, or login fails the check, and the reply names the host and port it tried. The password is not included. The check waits at most 10 seconds.

```
Topic:   $SYS/Coreflux/Command
Payload: -checkConnectorConnection SensorDB
```

***

## Table Schema Examples

Create tables optimized for time-series:

```sql wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
-- Partitioned time-series table
CREATE TABLE sensor_data (
    ts TIMESTAMP WITH TIME ZONE,
    sensor_id TEXT,
    value DOUBLE PRECISION
) PARTITIONED BY (ts);

-- Metrics with JSON storage
CREATE TABLE metrics (
    ts TIMESTAMP WITH TIME ZONE,
    topic TEXT,
    data OBJECT(DYNAMIC)
) PARTITIONED BY (ts);
```

***

## Troubleshooting

> [accordion] Connection Failed
>
> * Run `-checkConnectorConnection` and read the host and port in the reply
> * Verify HOST and PORT are correct
> * Check CrateDB is running and accepting connections
> * Verify firewall allows connections on port 5432
> * If the node only accepts TLS, set `USE_SSL "true"`. See [TLS](#tls)

> [accordion] Authentication Failed
>
> * Verify USERNAME and PASSWORD are correct
> * Check user has permissions on the DATABASE

> [accordion] Query Errors
>
> * Verify table exists and has correct schema
> * Put text placeholders in single quotes, and table or column placeholders in double quotes. An unquoted text value refuses the event. See [How placeholders are quoted](#how-placeholders-are-quoted)
> * Check column types match inserted data

> [accordion] STORE IN rows are missing
>
> * Look in the schema set by `DATABASE`, or `doc` when it is omitted. The name is case-sensitive
> * An `INT` value outside the 32-bit range is logged and not stored

***

## Next Steps

> [card] [Data Storage Connectors Overview](https://docs.coreflux.org/latest/connectors/data-storage/overview)
>
> Compare all storage options.

> [card] [Snowflake Connector](https://docs.coreflux.org/latest/connectors/data-storage/snowflake.md)
>
> Configure Snowflake cloud data warehouse.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.