Opine SQL: Safe, multi-tenant SQL on ClickHouse

When I joined Opine, I was asked to implement “better reporting.” It was an ambiguous request and a familiar one. For most products, reporting means the product and engineering teams have to guess which questions customers will want answered. Before building any of it, I introduced ClickHouse as our data warehouse, which gave us a fast, flexible foundation. My first attempt at implementing reporting involved a highly configurable API endpoint, and it didn’t last: every new question needed another parameter, and maintaining it got painful. So I changed course and built a query language instead. That became Opine SQL. It was a smaller leap than it sounds. SQL can already express almost any question the data can answer, and people and AI models both know how to write SQL queries. I also didn’t have to invent a language: Opine SQL is a subset of the ClickHouse SQL our warehouse already ran.
SQL vs. API endpoint
Opine’s built-in reports answer the common questions. Every sales team also has nuanced questions specific to its own CRM and workflow: filtering on a custom field, slicing by a particular segment, or tracking how a metric changed since last quarter. We wanted customers to be able to ask those too, and we wanted the same flexibility for ourselves when building analytics and insights into Opine.
An API endpoint answers only the questions it was designed for. Every new question meant another parameter, and the endpoint got harder to maintain with each one. SQL answers the questions nobody designed for as well.
The obvious way to offer SQL is a read-only database login. That doesn’t work for us, for two reasons:
- One warehouse, many customers. Our analytics live in one ClickHouse Cloud service that holds every customer’s data. A read-only login can still read every tenant.
- Users inside a customer see different things. Opine enforces the per-user permissions each customer has set up in their CRM. A sales engineer in EMEA may not be allowed to see a North American deal, or a particular field on a deal they can otherwise see. A database login knows nothing about either.
So customers write ordinary SQL, and a compiler turns it into a query that can see only what that user is allowed to see.
We’re not the first team to take this path. PostHog’s HogQL adds each team’s filter to every table a query touches. Trigger.dev wrote about how TRQL gives every user SQL access to a shared ClickHouse cluster. Inngest’s Insights puts a SQL editor over runs stored in ClickHouse. Opine SQL belongs to the same family, with two differences: it enforces each user’s CRM visibility inside the tenant, and AI agents are its main authors.
The dialect: ClickHouse SQL, minus the dangerous parts
Opine SQL is a strict, SELECT-only subset of ClickHouse SQL. If you can write a SELECT statement, you can use it, and anything you learn transfers directly to ClickHouse. We deliberately chose that approach over creating a language of our own. A custom dialect has no value outside one tool, and both people and AI models would have to learn it from scratch.
Customers query a curated catalog of about 80 tables rather than our raw schema:
- Every table and column is described, and hundreds of ClickHouse functions are allowlisted and documented.
my_dealand the othermy_*tables return only the records you work on.crmProperty(deal, 'Industry')reads a custom CRM field without knowing how it’s stored.- Date helpers such as
startOfPeriod('quarter', -1)follow your company’s fiscal calendar. - Every table has a
_historytwin for querying the past.
The catalog works like a public API. Its table and column names stay the same while the storage underneath changes: which snapshot a row came from, how custom fields are encoded, and what the internal columns are called. We can restructure the ClickHouse tables without breaking the queries customers have saved, the dashboards built on them, or the prompts their agents use. When the catalog itself changes, the change goes into a changelog that people and agents can read.
Columns also carry display hints: a currency, a percentage, a date, or a link back to the record in Opine. A result renders the same way in the playground, on a dashboard, or in an agent’s answer.
Inside the compiler
The compiler has three stages.
- Parse. Our own parser turns the query into a typed syntax tree. Writes, settings changes, and any other syntax outside the subset fail here with an error that says what isn’t supported.
- Validate. Every table, column, and function reference is checked against the catalog. An unknown name is an error, often with a “did you mean” suggestion.
- Transform. The compiler builds the query that ClickHouse actually runs. Every table reference becomes a scoped version of that table, and every literal becomes a typed query parameter instead of text spliced into the SQL.
Here’s a simplified example:
-- What the user writes
SELECT deal_id FROM deal-- What ClickHouse runs (simplified)
WITH _scoped_deal AS (
SELECT * FROM deal AS deal
WHERE deal.organization_id = {org}
AND deal.org_snapshot_id = {pinned_snapshot}
/* + the user's visibility rules */
)
SELECT deal_id FROM _scoped_deal AS deal
LIMIT 10001 -- row cap + 1, so we can tell the user results were cappedIsolation is part of how the compiler builds every query. We never take the user’s SQL, check it for problems, and pass it along. We build a new query from a validated syntax tree, and every table reference in it comes out scoped, including the ones inside subqueries, CTEs, and joins. There’s no path to an unscoped table because the compiler can’t produce one.
Complete example
The transform step does more than add scoping. Here’s a history query that reads a custom CRM field:
-- What the user writes: open pipeline per region, per day, last 90 days
SELECT
toDate(snapshotted_at) AS day,
crmProperty(deal_history, 'Region__c', 'String') AS region,
sum(deal_converted_amount) AS open_pipeline_value
FROM deal_history(
startDateInclusive = startOfPeriod('day', -89),
endDateInclusive = endOfPeriod('day')
)
WHERE deal_closed = 0
GROUP BY ALL-- What ClickHouse runs (simplified; the user's visibility rules are omitted)
WITH
_org_snapshots AS (
SELECT org_snapshot_id, org_snapshot_started_at, org_snapshot_trigger
FROM org_snapshot_multi_day_view(
organizationId = {org},
startDateInclusive = {start_date},
endDateInclusive = {end_date}
)
),
_scoped_deal AS (
SELECT * FROM deal AS deal
WHERE deal.organization_id = {org}
AND (deal.org_snapshot_id, deal.org_snapshot_started_at, deal.org_snapshot_trigger)
IN (SELECT * FROM _org_snapshots)
)
SELECT
toDate(toDateTime(deal.org_snapshot_started_at)) AS day,
if(JSONHas(deal.deal_properties, 'Region__c'),
JSONExtractString(deal.deal_properties, 'Region__c'), NULL) AS region,
sum(deal_converted_amount) AS open_pipeline_value
FROM _scoped_deal AS deal
WHERE deal_closed = 0
GROUP BY ALL
LIMIT 10001In this example, the compiler made five changes:
- History table:
deal_history(...)became a parameterized view that picks the last successful snapshot of the organization for each day in the range. - Dates:
startOfPeriodandendOfPeriodwere resolved to concrete dates (using the customer’s fiscal calendar for fiscal periods) and passed as parameters. - Column name:
snapshotted_at, the public name, became the internal snapshot column. - Custom field:
crmProperty(...)became a JSON extraction that returnsNULLwhen a deal doesn’t have the field. An empty string there would look like a real value. - Row cap:
LIMIT 10001enforces the row cap and tells us whether the result was cut off.
Why we skipped the parser generator
The lexer and parser are about 2,700 lines of code, written without a parser generator. They handle ClickHouse’s own syntax: typed placeholders, lambdas, and ARRAY JOIN. We built the first version by having an AI model write three competing implementations, reviewing them, and asking for a fourth that combined the best ideas. Coding agents have extended the grammar since then with small, readable changes. PostHog made the same trade later: it replaced HogQL’s ANTLR-generated parser with a handwritten one in Rust, written with an AI coding agent and checked against the old parser.
Parsing is also the cheap part. We timed the whole compile on the roughly 200 example queries in our catalog:
| Stage | Median | 95th percentile |
|---|---|---|
| Parse | 3 µs | 10 µs |
| Validate and transform | 36 µs | 0.48 ms |
| Generate ClickHouse SQL | 11 µs | 0.24 ms |
| Whole compile | 51 µs | 0.78 ms |
These runs didn’t apply any user’s visibility rules, which add even more work to the transform step. Transformation is the hard part. Its code is about three times the size of the lexer and parser combined, and it takes most of the compile time. Even at the 95th percentile, compiling a query takes less than a millisecond. Our median Opine SQL query takes about a quarter of a second end to end, so compilation is a rounding error next to running it.
Row-level and field-level visibility
Tenant isolation is the minimum. The harder requirement is enforcing each user’s permissions from the CRM, even in free-form SQL. Those permissions work at two levels:
- Row-level visibility decides which records a user can see. If you can’t see a deal in your CRM, it doesn’t appear in your Opine SQL results, whether you query it directly, join to it, count it, or aggregate over it.
- Field-level visibility decides which fields on those records a user can see. If you can see a deal but not one of its fields, a query that names that field fails with an error saying the field isn’t available, and
SELECT *leaves it out. The same check covers custom CRM fields read withcrmProperty, and no alias, CTE, or subquery gets around it.
The same rules apply to dashboards, exports, and AI agents, so a query never sees more than the person it runs for.
Multiple layers of tenant isolation
People who hear about this design often ask why we don’t just use ClickHouse’s row policies. Some teams build tenant isolation around row policies, as LaunchDarkly describes. We use them too, but they’re not the only layer of protection. Tenant isolation has two independent safeguards:
- The compiler handles everything that depends on the user: their organization, their row-level and field-level visibility, and the snapshot they’re reading.
- ClickHouse runs every compiled query as a database user that belongs to the customer’s organization. Row policies on every table that user can read limit it to that organization’s rows. The user’s grants cover only the tables the compiler can reach, and a settings profile caps memory, data read, and runtime at limits no query can raise.
If a compiler bug ever dropped the organization filter, the database would still return only that organization’s rows. Row policies can’t replace the compiler, though. Per-user visibility depends on the user and the snapshot, and a row policy has no way to express either.
How we keep Opine SQL secure
We design and test Opine SQL to prevent the following risks:
- Access to another tenant’s data
- Users seeing records or fields that their CRM permissions hide
- SQL injection through the compiled query
- Information leaking through error messages or metadata
- One customer’s queries exhausting resources and slowing down their neighbors
- Writes or side effects through a read-only interface
- Misuse by AI agents, including prompt injection
Here’s how we verify it:
- By construction. Scoping is built into how the compiler produces every table reference.
- Automated checks on every change. A large test suite covers the isolation and visibility rules, including adversarial queries written to break them.
- Recurring adversarial audits. We regularly run deep audits of the compiler, including runs driven by AI agents acting as red-teamers. Every finding must be confirmed or refuted with a working proof of concept before it’s closed.
- Recurring external penetration tests.
- Defense in depth. The database-level isolation described above, least-privilege read-only credentials, and resource limits that ClickHouse itself enforces.
One query language, many surfaces
Every way of querying customer data through Opine SQL goes through the same compiler:
- The SQL playground, where people write queries by hand or explore example queries
- Custom dashboards, where a chart definition compiles to Opine SQL and dashboard filters bind to placeholders in the query
- Scheduled exports to the customer’s own storage as Parquet, CSV, or JSON
- The public API
- AI agents, through Opine’s MCP server and our own assistants
One compiler gives us one place to get isolation right and one test suite to prove it, no matter who writes the query.
That design paid off in a way I didn’t anticipate. When AI agents started writing most of our queries, we didn’t have to build a separate safety system for them. An agent’s query goes through the same parser, catalog, and transform as a person’s query, with the permissions of the person it works for. The agent can ask anything it likes. It still sees only what that person can see.
To write your own queries, start by requesting free access to the Opine SQL documentation, which has syntax guides and example queries. Custom dashboards are built on the same compiler.