DistillQL

Connect a database

DistillQL runs in your Python process and logs in to Postgres the way psql and your other tools do. No password goes in its config.

Set it up

distillql init

init asks for the connection: a connection string, a service name from pg_service.conf, or nothing, to use the settings psql already uses. It tests the login. If a password is needed, it asks where to keep it (below). Then it writes distillql.yaml, crawls the database, and adds DistillQL to Claude Code if Claude Code is installed. It prints the setup for other AI apps.

Every question has a flag, so a script or an agent can run it with no questions:

distillql init --postgres 'postgresql://[email protected]:5432/app' --password-stdin --password-store keychain --crawl --claude
distillql init --service analytics --crawl
distillql init --duckdb sales.duckdb

distillql check distillql.yaml tests the login again later and says what to fix.

Where the password comes from

You choose. DistillQL writes a password into a file only if you pick that.

Option In the config Good for What to know
System keychain password: {keyring: ana@db:5432/app} Your own machine, and AI apps on it Encrypted, unlocked by your computer login. macOS Keychain, Windows Credential Manager, or Secret Service on Linux.
Environment variable password: ${APP_PASSWORD}, or nothing for PGPASSWORD Servers, CI, containers Set it wherever DistillQL runs. A desktop app does not see variables set in .zshrc; set them in the app's MCP settings.
A command password: {command: "op read op://vault/app/password"} 1Password, AWS Secrets Manager, Vault; cloud sign-in tokens Runs each time DistillQL connects, so short-lived tokens work: aws rds generate-db-auth-token ..., gcloud sql generate-login-token. Runs as you, so use only configs you trust.
Ask each time password: {prompt: true} Notebooks and terminals Nothing saved; asked once per session. An AI app cannot answer a prompt.
~/.pgpass nothing People who already use it with psql Postgres's own password file: plain text that only you can read. init adds a line only if you choose it.
pg_service.conf and PG* variables service: analytics, or nothing People who already use them Read the way psql reads them.
The config file password: s3cret Quick local tests Plain text. init makes the file readable only by you, and DistillQL warns each time it reads one.

A password, token or key typed into a config anywhere, including inside a URI, works but brings a warning. The same sources work for every secret in a config, such as a Snowflake token.

Encryption, client certificates and jump hosts

DistillQL hands its connection settings to Postgres's own client library, libpq, so anything psql accepts works. Put the TLS settings in the URI, a service in pg_service.conf, or the PGSSL* variables:

engines:
  app:
    kind: postgres
    uri: "postgresql://[email protected]:5432/app?sslmode=verify-full&sslrootcert=/etc/ssl/db-ca.pem"
Need Setting
Encrypt, and check the server's certificate sslmode=verify-full and sslrootcert= the CA file. Cloud providers publish theirs: AWS RDS, Google Cloud SQL, Azure.
Log in with a client certificate sslcert= and sslkey= in the URI. Postgres takes the user from the certificate.
An encrypted client key sslpassword: on the engine, from any password source.
A jump host (bastion) ssh: [email protected] on the engine, or distillql init --ssh ana@bastion.

For a jump host, DistillQL runs your system's ssh to open a tunnel, so your ~/.ssh/config, keys and ssh-agent work as they do in your terminal. The tunnel opens when DistillQL connects and closes with it. TLS still checks the certificate against the database's own name. An AI app cannot type an SSH password, so log in with a key or ssh-agent. Longer form:

    ssh: {destination: bastion, port: 2222, identity_file: ~/.ssh/id_ed25519, options: ["ProxyJump=outer"]}

A database reached through a VPN, or a proxy such as the Cloud SQL Auth Proxy, needs nothing from DistillQL: point the URI at the address the VPN or proxy gives.

From Python and notebooks

Hand over a connection you already have open. DistillQL reads its settings and opens its own connection with them. It keeps the password in memory and writes it nowhere:

import distillql, psycopg

pg = psycopg.connect("service=analytics")
con = distillql.connect(engines=[distillql.Postgres.from_connection("app", pg)])

It takes psycopg 3, psycopg2, and SQLAlchemy engines and connections. Or pass the password from wherever you keep it:

import getpass, keyring

con = distillql.connect({"engines": {"app": {"kind": "postgres", "uri": "postgresql://ana@db/app",
                                               "password": getpass.getpass()}}})        # or keyring.get_password(...)

A password typed into a notebook cell is saved in the .ipynb file and in IPython's history. Typing it into a prompt avoids both.

Whose rights each query uses

The identity in the config names who is asking, and what each database should see:

Credential Meaning
{login: true} The config's login is this person. init writes this.
{uri: ...} This person's own login, separate from the config's.
{role: analyst} The config's login is shared: every query runs SET LOCAL ROLE analyst in a read-only transaction.

On BigQuery, a person's credential is their own Google login, a service account to impersonate ({impersonate: [email protected]}), a token or a key file; see configuration. BigQuery then applies that person's IAM grants, row access policies and policy tags itself. A query that names a column under a policy tag the person may not read fails with BigQuery's reason, and so does select * over such a column; select * except (...) works. The explain record names the account BigQuery saw and the policies on each table the query read.

On Trino, each query carries the person's name as its Trino user, so Trino's own access control (file rules, Ranger, OPA) applies its grants, row filters and column masks to them. A person signs in with {user: ..., password: ...}, {token: ...} (a JWT) or {oauth: true} (a browser sign-in, once). With no credential, the engine's crawler login signs in and sends their name, and Trino's impersonation rules decide whether that login may act for them; a name it may not act for is refused. DistillQL reads current_user back and refuses a query that ran as anyone else.

The crawl reads as the crawler, and every person's agent reads what it keeps. So it keeps nothing a person could not read themselves:

  • A table with row-level security keeps its schema and no values in any column: no samples, no minimum or maximum, no date range, nothing drawn from its rows. On BigQuery that is a table with row access policies, or one whose policies the crawler may not list. On Postgres it is a table with row-level security enabled (ALTER TABLE ... ENABLE ROW LEVEL SECURITY), forced or not.
  • A column under a column-level policy is never read, not even by the crawl's sampling query. The rest of its table is profiled as usual. On BigQuery that is a column with a policy tag. On Postgres it is a column that some role holding SELECT on part of its table may not select: the table has column grants (GRANT SELECT (id, band) ON pay TO analyst) and the column is not among some role's.
  • A column that holds personal data is tagged with its kind (email, phone, name, government id, address, birth date, payment card or bank account, IP address, credential) and keeps no values. Its name can say so (email, ssn), or its values can: a text column most of whose sampled values are email addresses, phone numbers, US social security numbers, card numbers that pass the Luhn check, IBANs or IP addresses. distillql review lists every tagged column, search_context names them for each table, and distillql ask sends the model none of their values.
  • A past query stays in the history with its shape and run count. A value compared against a column a row policy filters on, or a column under a column-level policy, or inside an expression over one, becomes a parameter, as pg_stat_statements writes it: where region = 'west' becomes where region = $1, since it tells an analyst who sees only the east what the west holds. The crawl reads a policy's columns from its filter: the USING expression of a Postgres policy that applies to SELECT, or a BigQuery row access policy's filter predicate. Where it cannot read them (a filter it cannot parse, policies that name no column, no policy for reading, a list it may not see), every value on that table's columns is masked. A query is left out only when it names such a table and cannot be parsed.

One exposure remains: a value a person typed into a past query on any other column stays in the shared history text. where name = 'Acme' on a table with row-level security keeps 'Acme', which another person's agent can find through search_context even if that person cannot see Acme's row.

The crawl's notes say which tables and columns keep no values, how many values were masked, which queries were left out, and when the crawl's Postgres login bypasses row-level security (a superuser, BYPASSRLS, or the owner of a table without FORCE ROW LEVEL SECURITY). Row counts come from the table's metadata, which BigQuery and Postgres show to anyone who may read the table.

Trino shows no one its row filters and column masks, so the crawl cannot tell which tables have them, and keeps samples from every table. Its samples are what the config's identity may read. Share a Trino context only with people whose rights match that identity's.

A person with no credential for an engine cannot query it. A shared login is a weaker boundary than one login per person, because SQL can try to change the role. DistillQL refuses any function it does not know under a shared login, and checks the role again after the rows come back. Under every login it refuses functions that act outside the read-only transaction, such as dblink_exec and set_config. Use a login per person where people you do not trust write the SQL.

Query history

The glossary is drafted from past queries, so the history matters more than anything else in the config.

Postgres keeps history in the pg_stat_statements extension:

  • It must be in shared_preload_libraries, and create extension pg_stat_statements must have run in the database. Most managed services (RDS, Cloud SQL, Azure, Supabase, Neon) offer it.
  • The login needs pg_read_all_stats to see other people's queries; without it, it sees only its own.

pg_stat_statements stores status = 'paid' as status = $1. A term built on a hidden value stays undefined, because DistillQL never guesses it. Point history: at SQL that still has its values, such as saved queries, dbt's compiled models (target/compiled/**/*.sql) or a BI tool's export. A file query with the same shape as a logged one lends it its values, and the log keeps its count of runs.

engines:
  app: {kind: postgres, service: analytics, history: "analytics/target/compiled/**/*.sql"}

With the log alone, an agent asked about such a term says it cannot answer and asks what the term means. In our test on one company's database, Claude Haiku answered 17 of 25 questions right from the log alone and declined the other 8. With the company's saved report SQL added as history:, it answered 22 right. The crawl tells you when this applies: 12 past queries have values the server log hides ($1). If you see that line, add a history: source before you give the agent its tools.

Trino keeps no lasting log. The crawl reads system.runtime.queries, which holds only the queries the coordinator still remembers, about the last 100 by default, and only the crawler's own unless the access rules let it view other people's. Point history: at the files a query event listener writes, or at saved queries, as for Postgres.

DuckDB keeps no log, so its history: is the only source: a JSON-lines file with one query per line, or .sql files.

{"sql": "select sum(amount) from orders where status = 'paid'", "calls": 40, "user": "ana"}

calls and user are optional. A query in a .sql file counts as one run. The crawl reads every line. Write the SQL in the engine's own dialect: the crawl skips what it cannot parse, such as SQL Server's [brackets] on a DuckDB engine, and its notes say how many it skipped.

The crawl leaves out queries that say nothing about what people ask:

  • DistillQL's own. Every query DistillQL sends ends with the comment /* distillql */: the crawl's profiling, con.sql() from Python, and an agent's questions. The crawl's notes count them, so the glossary never counts its own definitions as use. Queries an older version sent carry no tag.
  • dbt's tests, which dbt wraps in a subquery it names dbt_internal_test.
  • Queries that read no table, such as a driver's select current_user, and queries that read only the database's catalog.

More than one database

Name each engine in the config. SQL names a table as engine.schema.table, or as schema.table when only one engine has it. DistillQL runs each engine's part there, as the person asking, and joins the parts in a local DuckDB.

engines:
  sales: {kind: duckdb, path: sales.duckdb, history: sales-queries.jsonl}
  app:   {kind: postgres, service: analytics}
identity:
  user: ana
  credentials:
    app: {login: true}

Here accounts live in Postgres and invoices in BigQuery:

engines:
  app: {kind: postgres, service: analytics}
  wh:  {kind: bigquery, project: acme-data, datasets: [billing], maximum_bytes_billed: 1000000000}
identity:
  user: ana
  credentials:
    app: {login: true}
    wh: {}                  # Ana's own Google login (application default credentials)
con.sql("""select a.industry, sum(i.amount_usd) as billed
           from app.app.accounts a join wh.billing.invoices i on i.account_id = a.account_id
           where a.country = 'DE' and i.status = 'paid' group by 1""")

The smaller side runs first. Postgres returns the 104 German accounts. BigQuery then gets status = 'paid' and those 104 account ids in its own query, so 540 invoice rows come back, not all 10,347. The explain record lists each part's SQL, the login each engine saw, the rows and bytes it returned, BigQuery's dry-run estimate and the bytes it billed. maximum_bytes_billed and caps.bytes apply to the BigQuery part as they would to a query on BigQuery alone. When both engines hold a table called accounts, write app.app.accounts or wh.billing.accounts; a bare accounts is refused, and the error lists both.

BigQuery bills by the columns a query reads, however few rows it returns. The account ids sent across cut the rows that come back, and they cut the bytes billed only when the table is clustered on that column. On a table that is not clustered, the BigQuery part bills every row of the columns it names, so keep its columns few and filter on its partition column. On the public wikipedia.pageviews_2024 table, clustered on title, one day of English pages billed 176 MB with three titles sent across, against 1.08 GB for the whole day. On usa_names.usa_1910_current, which is not clustered, three names sent across billed the full 100 MB of the two columns.

What a BigQuery query costs

Before each BigQuery part runs, DistillQL asks BigQuery for a dry run, which is free. Its figure goes in the explain record as estimated_bytes, next to bytes_scanned, what BigQuery billed; cost.bytes_scanned adds up the parts. A part whose estimate is over maximum_bytes_billed is refused before any job starts and bills nothing; the error gives the estimate and the cap, and an agent sees over_cap. caps.bytes refuses in the same way for any engine.

Three things to expect from the figures:

  • LIMIT does not lower the bytes. select * from github_repos.commits limit 10 bills the whole 910 GB table; naming one column bills that column.
  • BigQuery bills at least 10 MB for each table a query reads, so a 2.6 MB dry run bills 10 MB. Otherwise the bill matched the dry run within 0.1% on every query checked, including a filter on a partition column and a filter on clustering columns.
  • A filter on the partition column lowers the estimate as much as the bill. A filter on clustering columns lowered both on the tables checked; where BigQuery cannot tell from the dry run how many blocks the filter skips, it reports the larger figure, so the estimate errs high.

To query a dataset someone else owns, such as bigquery-public-data, set project to the project that holds the tables and billing_project to your own:

engines:
  pub: {kind: bigquery, project: bigquery-public-data, billing_project: my-project, datasets: [github_repos], maximum_bytes_billed: 1000000000}

Table names follow BigQuery's rules on a BigQuery engine:

  • pub.github_repos.commits and BigQuery's own `bigquery-public-data.github_repos.commits` name the same table: the project stands for the engine whose project it is.
  • Table and column names match in any case; dataset names keep theirs, so Sales.orders finds Sales.Orders and sales.Orders does not.
  • A wildcard table, `ga4.events_*` with a _TABLE_SUFFIX filter, is one table over every table of the dataset whose name starts with events_. Its columns are theirs together, and _TABLE_SUFFIX. The query goes to BigQuery as written, and the dry run and maximum_bytes_billed apply as to any other. The explain record's validation lines name the pattern and how many tables it matched. A query that joins a wildcard table with another engine's table is refused: run the BigQuery part on its own.
  • A dataset's INFORMATION_SCHEMA views can be queried: select column_name, data_type from ga4.INFORMATION_SCHEMA.COLUMNS where table_name = 'events_20210131'. The views allowed are TABLES, COLUMNS, COLUMN_FIELD_PATHS, TABLE_OPTIONS, TABLE_CONSTRAINTS, KEY_COLUMN_USAGE, CONSTRAINT_COLUMN_USAGE, PARTITIONS, VIEWS, MATERIALIZED_VIEWS, ROUTINES and PARAMETERS, on the engine's own datasets. BigQuery runs them as the person asking. JOBS and the other region and project views are refused, since they hold other people's query text, and so is a join with another engine's table.
  • In GROUP BY and ORDER BY, a name that is also a SELECT-list alias means the alias, as BigQuery reads it.

Which databases work

Engine Status
DuckDB Tested
Postgres Tested, including row-level security and per-user roles
BigQuery Tested on a live project: the crawl, its query log, keys and descriptions, per-user credentials, row access policies, policy tags and the byte cap. Install with pip install 'distillql[bigquery]'.
Trino Tested on a local Trino 484 server: per-user rows and masks through impersonation, a person's own password, the time limit, the query log and the SQL subset. Install with pip install 'distillql[trino]'.
Snowflake, Databricks Experimental. Written to each warehouse's documented API but not yet run against a live account. They warn on first use. Install with pip install 'distillql[snowflake]' or [databricks].

Their settings are on the configuration page.