SQL: PostgreSQL and ClickHouse
Use SQL steps to check the data behind a user journey: the business rows in
PostgreSQL, or the telemetry, events and usage records in ClickHouse. A query
keeps its column names and row values, so a reviewer sees the rows a step checked
beside screenshots and command output. No psql, clickhouse-client or
docker exec is needed: each plugin talks to its server directly.
There is one plugin per engine, and both work the same way: the same commands
(query, value, execute), the same expect, key, waits and branches, the
same satisfied predicate and the same evidence. Declare the plugin for your
database’s engine in providers:; a flow can declare both.
| Engine | Declare | Install | Binding |
|---|---|---|---|
| PostgreSQL | db: PostgreSQL | Installed by default with reflow init --collection <collection-id> | connectionString |
| ClickHouse | ch: ClickHouse | Optional: reflow init --upgrade ClickHouse --collection <collection-id> | host, port, user, password … |
db and ch are the usual aliases; any alias works, and it selects the private
connection with the same name. The flow names the engine because the SQL dialects
differ.
Install
Section titled “Install”PostgreSQL is part of the default plugin selection: reflow init --collection <collection-id>
installs it with the other bundled plugins.
ClickHouse is an optional plugin: it is not in the CLI download and not in the default selection. Add it to an application that already has a plugin selection:
reflow init --upgrade ClickHouse --collection <collection-id>For an application without a plugin selection yet, name every plugin it needs in
one command, for example reflow init PostgreSQL ClickHouse --collection <collection-id>:
reflow init ClickHouse alone selects ClickHouse alone. reflow init downloads it once for your platform
from the release your CLI was installed from, checks it against that release’s
manifest and installs it; plan and apply never download. The other selected
plugins stay exactly as locked. A teammate’s device, or CI, installs it with plain
reflow init, because the application’s lock names it.
Connect
Section titled “Connect”Your database must be running and reachable from the machine that runs Reflow.
Save its connection in a private bindings.json, keyed by the alias, and keep the
file out of Git: credentials belong in the private connection, never in the flow.
allowWrites is an optional boolean on both engines and defaults to false; see
Setup writes.
chmod 600 /absolute/path/to/bindings.jsonreflow target --group database-tests --collection <collection-id> --bindings /absolute/path/to/bindings.jsonPostgreSQL connection
Section titled “PostgreSQL connection”{ "db": { "provider": "PostgreSQL", "configuration": { "connectionString": "postgresql://test_user:replace-me@127.0.0.1:5432/test_db" } }}connectionString is required. The plugin uses pgx v5 to parse URL or
keyword/value connection strings. PostgreSQL session parameters such as
search_path are supported in the DSN, for example
postgresql://test_user:replace-me@127.0.0.1:5432/test_db?search_path=public.
Percent-encode parameter values when needed and keep the complete DSN private.
The server must recognize each runtime parameter; application-specific URL options
are not PostgreSQL settings: use search_path=public, not an application-only
option such as schema=public. Reflow sets application_name to
reflow-plugin-postgresql and uses a five-second connection timeout.
ClickHouse connection
Section titled “ClickHouse connection”The plugin uses the server’s HTTP interface (port 8123, or 8443 over HTTPS):
{ "ch": { "provider": "ClickHouse", "configuration": { "host": "127.0.0.1", "port": 8123, "database": "default", "user": "test_user", "password": "replace-me" } }}| Field | Meaning |
|---|---|
host | Required. Host name or IP address, without scheme or port. |
port | HTTP interface port; 8123, or 8443 when secure is true. |
secure | Use HTTPS. Defaults to false. |
database | Database for unqualified table names; default when omitted. |
user | ClickHouse user; default when omitted. |
password | The user’s password. |
passwordFile | Instead of password: the absolute path of a private file holding only the password. |
allowWrites | Allow ch.execute. Defaults to false; query stays read-only. |
The user, password and database travel in request headers, never in a URL.
Binding runs SELECT 1, so a wrong password or a missing database fails at once.
Redirects are never followed and no proxy is used, so the password cannot reach
another host. A read-only user works for query and value when its profile
sets readonly=2; a readonly=1 profile refuses the settings the plugin needs
for exact values, so binding it fails with that reason.
Write a flow
Section titled “Write a flow”Copy this into /tmp/database-check.md, outside your checkout. It returns one row
without requiring an application table:
---name: Capture database rowsproviders: db: PostgreSQL---
### Capture database rows
```rfldb.query ( sql="SELECT 1 AS id, 'ready' AS status" key="id" expect=json( {"rows": 1, "json": [{"pointer": "/0/status", "equals": "ready"}]} ) checkpoint="database-ready")```Create the test in the team’s chosen location, then run it:
reflow flows create --name database-check --file /tmp/database-check.mdreflow plan database-checkreflow apply database-checkreflow dashboardA ClickHouse flow reads the same way:
---name: Check session eventsproviders: ch: ClickHouse---
### The test user's latest session recorded its tool calls
```rflch.value sql="SELECT session_id FROM events WHERE user_id = 'zz-e2e-user' ORDER BY time DESC, session_id LIMIT 1" -> session_idch.query ( sql="SELECT count() AS n FROM events WHERE session_id = '${session_id}' AND name = 'tool_call'" expect=json( {"rows": 1, "json": [{"pointer": "/0/n", "greaterThanOrEqual": 1}]} ) checkpoint="session-tool-calls")```Query arguments and stable rows
Section titled “Query arguments and stable rows”| Argument | Type | Meaning |
|---|---|---|
sql | string, required | One SQL statement, run read-only (see How the engines differ). |
key | string, optional | A unique, non-null returned column used to identify and sort rows. |
expect | JSON text, optional | What the rows must hold; see Check rows with expect. |
db.query sql="SELECT id, status, refunded FROM orders ORDER BY id" key="id" checkpoint="orders"checkpoint is a host RFL modifier, not a command argument. RFL removes it before
validating and dispatching the provider arguments, so it does not appear in the
query descriptor returned by list_plugins. Use a literal label of 1-128
letters, digits, underscores or hyphens. Other unknown arguments are rejected. A
query already captures its result; there is no separate snapshot command.
Use a key or an explicit ORDER BY to make ordering repeatable. A missing, null
or duplicate key fails the step; the step keeps its rows, and its error names the
key values. Returned column names must be unique. A capture is
limited to 10,000 rows and 7 MiB of serialized snapshot state. A larger result
fails the step and keeps no partial rows: narrow or aggregate in SQL.
A statement the server refuses fails the step with the server’s message and code,
and keeps that error, with no rows, as evidence. The connection’s password, and its
user, database and host where they appear as whole words, appear as [withheld].
Other failures, such as a lost connection, report fixed text. Do not concatenate
untrusted text into SQL: neither plugin supports bind or query parameters.
Typed inputs can supply numeric
limits and booleans.
Check rows with expect
Section titled “Check rows with expect”Give expect to state in the flow what the rows must hold. Write it as a json(
block in a grouped call:
db.query ( sql="SELECT id, status, refunded FROM orders WHERE id = 1042" expect=json( {"rows": 1, "json": [{"pointer": "/0/status", "equals": "refunded"}, {"pointer": "/0/refunded", "equals": true}]} ) checkpoint="order-refunded")db.query ( sql="SELECT id FROM api_keys WHERE name = 'zz-e2e-revoked' AND deleted_at IS NULL" expect=json( {"rows": 0} ))| Key | Meaning |
|---|---|
rows | The exact number of returned rows. |
json | Assertions over the returned rows as a JSON array of row objects. Each has an RFC 6901 pointer and one operator. |
/0/status is the first row’s status column, /1/status the second row’s, and
"" the whole array. With key, rows are sorted by the key first. The operators
are the same as in the shell plugins’ expect: exists, equals, type,
count, includes, lessThan, lessThanOrEqual, greaterThan and
greaterThanOrEqual. Values are the ones the snapshot keeps, which differ by
engine (see Values): compare exact decimals and very large integers as
strings, such as {"pointer": "/0/amount", "equals": "12.50"}.
Every check must hold. Otherwise the step fails, keeps its rows, and the error says what was expected and what was received:
expect.rows: expected 1 row, received 0 rows (count_differs)expect.json[0] "/0/status": expected equals "refunded", received "paid" (value_differs)An invalid expectation, such as an unknown key or operator, is refused before any SQL is sent. A refused statement or a key violation fails with its own error and is not judged. Do not make the statement raise an error on purpose: PostgreSQL may evaluate a constant expression while it plans the statement, so a deliberate error can fail every run.
Wait for rows, or branch on them
Section titled “Wait for rows, or branch on them”A query with expect can wait for its rows to hold with within=. Data often
arrives a moment after the action that produced it. The query runs again, every
second unless every= says otherwise, while the rows do not satisfy expect, and
ends at once on a refused statement or a lost connection:
ch.query ( sql="SELECT count() AS n FROM events WHERE session_id = '${session_id}' AND name = 'tool_call'" expect=json( {"json": [{"pointer": "/0/n", "greaterThanOrEqual": 1}]} ) within=30s every=2s)within is the last time an attempt may start. When it has passed, the step
fails with the last attempt’s rows and its expect message, after
did not hold within 30s: 15 attempts in 30.2 s (28.0 s between attempts). The
same query can decide an if or unless: rows that satisfy expect take the
block, rows that do not take else, and a statement that fails stops the step:
if db.query sql="SELECT id FROM agents WHERE name = 'zz-e2e-agent'" expect="{\"rows\":1}" db.execute sql="DELETE FROM agents WHERE name = 'zz-e2e-agent'"execute and value cannot wait or decide a branch: execute writes, and
value has no expect.
A query whose result is a single row with one column named satisfied sets the
step’s predicate, for example SELECT EXISTS(SELECT 1 FROM fixture_users WHERE id = 7) AS satisfied.
The column is a PostgreSQL boolean, or a ClickHouse Bool or UInt8 0 or 1
(which ClickHouse comparisons and EXISTS return). Any other result sets no
predicate.
Return a value with value
Section titled “Return a value with value”value runs one read-only statement like query and returns one cell of the
first row for later steps: the column named by column, or the first column.
db.value sql="SELECT id FROM agents WHERE name = 'zz-e2e-agent' ORDER BY created_at DESC, id LIMIT 1" -> agent_iddb.query ( sql="SELECT count(*) AS keys FROM agent_keys WHERE agent_id = '${agent_id}'" expect=json( {"json": [{"pointer": "/0/keys", "equals": 2}]} ))| Argument | Type | Meaning |
|---|---|---|
sql | string, required | One SQL statement, run read-only like query. |
column | string, optional | The column to return; the first column when omitted. |
raw | "true", optional | Return any printable text, not only a safe token. |
The value is returned as text: numbers in their JSON spelling and booleans as
true or false. Look up a unique row; when several rows can match, add
ORDER BY with a unique tie-break column and LIMIT 1, as above, or the first row
is arbitrary. No rows, a missing column, NULL, a composite value (a JSON object or
array in PostgreSQL; an array, map or tuple in ClickHouse) or a value over 4 KiB
fail the step, for example with value: column "id" is NULL in the first row.
The value must be a safe token of letters, digits and . _ : / @ + -, not
starting with -, unless raw="true". A safe token has no quotes or backslashes, so it can be single-quoted
into a later statement, as the example does. That is still not a bind parameter:
never interpolate raw text into SQL, neither a raw="true" value nor a free-text
input such as a name (O'Brien breaks the statement). Pass a raw value only to an
argument that treats it as data. The value and the rows it was taken from are kept
as evidence, so never select a secret.
Setup writes with execute
Section titled “Setup writes with execute”execute accepts a required sql string. It runs only when the private connection
explicitly sets "allowWrites": true; without it, or with empty SQL, the step fails
before any SQL is sent. Enabling writes does not make query or value writable.
When the server refuses a statement in execute, the step ends with its completion
unknown, not failed: part of the work may already be done (an earlier PostgreSQL
statement may have committed; a ClickHouse INSERT may have written some of its
rows). Reflow does not run that step again by itself. Check the test database, then
taint the step to run it again.
Use a separate, deliberate setup step against your test database, and make it safe to repeat: rerunning a flow does not reset database contents, and reflow reset rotates named test values and leaves application data in place. Name what setup writes with a run-specific key, and undo exactly that in a cleanup step below it, which runs after the flow’s steps even when one of them failed:
### Record this run's test events
```rflcapture sfx = random.string length=8ch.execute sql="INSERT INTO events (session_id, name) VALUES ('zz-e2e-${sfx}', 'tool_call')"```
```rfl cleanup step="Delete this run's test events"ch.execute sql="ALTER TABLE events DELETE WHERE session_id = 'zz-e2e-${sfx}'"```How the engines differ
Section titled “How the engines differ”| PostgreSQL | ClickHouse | |
|---|---|---|
query and value | One statement in a read-only transaction | One statement with the server’s readonly=1 setting: the server refuses an INSERT, DDL or a SETTINGS clause. A user whose profile sets readonly=2 runs under that profile instead: writes are still refused, settings changes are not. Do not add FORMAT: the plugin reads JSONCompact |
execute | One or more statements | One statement per step. Inserts are synchronous and mutations (ALTER TABLE … UPDATE or DELETE) wait until they finish, so the next step sees their effect |
execute state | commandTag and rowsAffected of the last statement | writtenRows (0 for DDL) |
| Refused statement | PostgreSQL error: <message> (SQLSTATE <code>); the server’s detail, hint and position are not kept | ClickHouse error: <message> (code <n> <NAME>) |
| Over the capture limit | The step fails | The step fails, also when a result-size limit of the user’s profile is reached first; a truncated result is never kept |
satisfied predicate | boolean | Bool, or UInt8 0 or 1 |
| Connection | One connectionString (pgx v5) | host, port, secure, database, user, password or passwordFile, over HTTP(S); no redirects or proxy |
A refused PostgreSQL statement reads, for example,
PostgreSQL error: invalid input syntax for type integer: "abc" (SQLSTATE 22P02),
and a refused ClickHouse one
ClickHouse error: Unknown table expression identifier 'evnts' in scope SELECT * FROM evnts (code 60 UNKNOWN_TABLE).
On both engines, a value Reflow knows as private, such as a binding value or an
input substituted into the SQL, appears in the error as its ${…} name. Other
PostgreSQL failures report PostgreSQL statement failed (connection and statement details withheld).
Values
Section titled “Values”Both plugins keep every value exact, so a number JSON cannot hold exactly is a
string. What expect compares therefore depends on the engine.
PostgreSQL:
- SQL NULL is
null.numericvalues, and integers beyond ±2^53-1, are strings: compare"12.50", not12.5. Non-finite floats areNaN,+Infor-Infstrings. - JSON and JSONB values are objects and arrays, with the same number rule inside.
- UUIDs are strings,
byteais base64, timestamp infinities areinfinityor-infinity, and ranges and intervals keep their named fields.
ClickHouse:
Decimalvalues are strings with their scale:"12.50".- Integers within ±2^53-1 are numbers whatever their type, so
count()is a number.UInt64,Int64,Int128and wider values beyond that range are strings, such as"18446744073709551615". - Floats a JavaScript number holds exactly are numbers; others, and
nan,infand-inf, are strings. NULLisnullandBoolistrueorfalse. Dates, times, UUIDs, IP addresses and enums are strings. Arrays and tuples are arrays; maps, named tuples andJSONvalues are objects, with the same number rule inside.
Replace psql or clickhouse-client in a script
Section titled “Replace psql or clickhouse-client in a script”A LocalBash step that runs psql, clickhouse-client (often through
docker exec) or a database driver hides the check in a script’s exit code.
Saving such a flow warns (wrong-tool-db). Write the query as a query step of
the plugin for your engine, with expect: the rows and the check are both visible
in the flow and in its evidence.
Review the result
Section titled “Review the result”The snapshot keeps the returned columns and exact represented row values. Compare
those retained results across runs and relate differences to the application’s
rules; see database evidence. A query without
expect records its rows and judges nothing; with expect, the snapshot also
records each check and whether it held.
Flows using these plugins can be saved in Reflow or in your repository. Read test storage for the team preference, private bindings and the shared plan/apply workflow.