DistillQL

Python API

import distillql

con = distillql.connect("distillql.yaml")
res = con.sql("""
  select o.customer_id, sum(o.amount) as spend, s.plan
  from sales.main.orders o
  join app.public.subscriptions s on s.customer_id = o.customer_id
  group by 1, 3
""")
res.head()                                        # rows stay in DuckDB; you hold a handle
res.aggregate({"total": "sum(spend)"}, by=["plan"]).rows()
print(res.explain().summary())

A query returns a handle. Its rows stay in a local DuckDB until you ask for them, so an agent can work with a large result without reading all of it. A query DistillQL refuses raises distillql.PlanError, and one over a limit raises distillql.CapExceeded.

This page is built from the code's own signatures and docstrings.

Connect

connect

distillql.connect(config: str | Path | dict | None = None, *, identity: Identity | None = None, engines: list[Connector] | None = None, metrics: dict[str, Metric] | None = None, cap_rows: int | None = None, cap_bytes: int | None = None, cache: bool | None = None, strict_caps: bool | None = None, allow_local_files: bool | None = None) -> Connection

Open a connection. Pass connectors directly, or a YAML/dict config. The local DuckDB that joins the parts cannot read files or reach the network unless allow_local_files (config: local_files: true) says it may:

engines:
  sales:     {kind: duckdb, path: sales.duckdb}
  postgres:  {kind: postgres, uri: postgresql://${PGUSER}@localhost:5432/app}
identity:
  user: ana
  credentials: {postgres: {role: analyst}}
metrics:
  net_revenue: {engine: sales, table: main.orders, expression: "sum(amount) - sum(refunds)"}
caps:
  rows: 1000000          # refuse a part whose estimate is over this, before it runs (bytes: the same in bytes)
  timeout_seconds: 60    # stop a query that runs longer (0: no limit)
  result_rows: 100000    # keep at most this many result rows; the record says how many were cut (0: no limit)

load_config

distillql.load_config(path: str | Path) -> dict

Read a YAML config as a dict, as written; connect() fills ${NAME} values from the environment.

expand_env

distillql.expand_env(value)

${NAME} and $NAME in every string, from the environment, so no secret has to sit in the config. A name that is not set is an error, never left in place.

Identity

distillql.Identity(user: str, credentials: dict[str, dict] = <factory>) -> None

Identity(user: 'str', credentials: 'dict[str, dict]' = )

Postgres

distillql.Postgres(name: str, uri: str | None = None, allow_functions: Iterable[str] = (), *, service: str | None = None, history: Iterable[HistoryEntry] = (), own_login: bool = False, password: str | None = None, sslpassword: str | None = None, ssh: str | dict | None = None)

uri: a postgresql:// uri or a libpq keyword string; with neither uri nor service, libpq reads the PG environment variables and ~/.pgpass, as psql does. history: past queries that keep their values, filling pg_stat_statements' $1s. own_login: this login is the person querying, so an identity with no credential for it runs as the login. password: added to the uri, from wherever the caller keeps it (distillql.credentials). sslpassword: the passphrase of an encrypted client key (sslkey). TLS settings (sslmode, sslrootcert, sslcert, sslkey) go in the uri or the PGSSL variables, as for psql. ssh: a jump host to tunnel through (distillql.tunnel).

from_connection

distillql.Postgres.from_connection(name: str, connection, **kw) -> "Postgres"

A connector with the same login as a connection the caller already has open: psycopg 3, psycopg2, or a SQLAlchemy engine or connection. It opens its own connection with those settings, so the caller's stays as it is.

DuckDBLocal

distillql.DuckDBLocal(name: str, path: str = :memory:, history: list[str | HistoryEntry] | None = None, read_only: bool | None = None)

read_only: None (the default) opens a file that exists read-only and creates a missing one; True or False decides it. An in-memory database cannot be read-only.

Connection.sql

Connection.sql(sql: str, tokens: dict | None = None, timeout_ms: int | None = None) -> ResultHandle

timeout_ms bounds each fragment on its engine and the local join; an engine that cannot bound a statement refuses it. Without it, the connection's own timeout_ms applies, and an engine that cannot bound a statement runs it unbounded with a warning in the record.

Connection.close

Connection.close() -> None

Close every engine's connection and the local DuckDB.

Ask any LLM

ask

distillql.ask(config: str | Path | dict, question: str, *, context: str | Path | None = None, model: str | None = None, base_url: str | None = None, con=None, post: Callable[[str, dict, str | None, float], dict] | None = None, notice: Callable[[str], None] | None = None) -> Answer

Answer a question with the model the config's llm: section (or model and base_url) names, through DistillQL's tools, under the limits in this module's docstring. context: the crawl's output (default .distillql/context.yaml, else context.yaml, beside the config). config may be a dict, read as the file would be, with paths from the current folder. con: an open Connection to use in place of the config's engines; the config still sets llm:. post: replaces the HTTP call, for tests. notice: where the line naming an address off this machine goes (default standard error).

Results

ResultHandle.head

ResultHandle.head(n: int = 5) -> list[dict]

The first n rows, as dicts.

ResultHandle.count

ResultHandle.count() -> int

How many rows, counted in the sandbox.

ResultHandle.schema

ResultHandle.schema() -> list[tuple[str, str]]

(column name, type) for each column.

ResultHandle.profile

ResultHandle.profile(sample: int = 5) -> dict

Row count, per-column type, null rate, distinct count, min/max and a few sample values.

ResultHandle.aggregate

ResultHandle.aggregate(spec: dict[str, str], by: list[str] | None = None) -> "ResultHandle"

spec: {"spend": "sum(amount)", "n": "count(*)"}; by: group columns.

ResultHandle.filter

ResultHandle.filter(expr: str) -> "ResultHandle"

A new handle with the rows where the SQL expression holds, such as "spend > 100".

ResultHandle.sql

ResultHandle.sql(query: str) -> "ResultHandle"

Run SQL over this handle; refer to it as self. Only a table reference named self is replaced: the word inside a string, a column name or an alias stays as written.

ResultHandle.chart

ResultHandle.chart(spec: dict, max_rows: int = 2000) -> dict

Return a Vega-Lite spec with the handle's rows inline. A chart draws a few hundred marks, not a table: over max_rows this refuses, so aggregate or filter the handle first.

ResultHandle.rows

ResultHandle.rows() -> list[dict]

Every row, as a list of dicts.

ResultHandle.arrow

ResultHandle.arrow() -> pa.Table

Every row, as an Arrow table. Reads the whole result out of the sandbox.

ResultHandle.to_pandas

ResultHandle.to_pandas()

Every row, as a pandas DataFrame (needs pandas).

ResultHandle.explain

ResultHandle.explain() -> ExplainRecord

The explain record of the query that made this handle.

Agent tools

Tools.glossary

Tools.glossary(question: str | None = None, terms: list[str] | None = None, max_bytes: int = 4000) -> str

One page of the company's terms, drafted from query history; the thing to read before writing SQL.

question: the question (and the columns the answer must return). Terms it names, by name, alias, a simple variant (plural, spaces for underscores) or initials ("net revenue retention" for nrr), come first and in full with the terms they are built from and a few other terms over the same tables, whatever the budget; a term built from query steps or a window function comes with its source query, dates as :d. A term the question uses most of a name of comes in full too. Each matched term also gets the schema comments that define it, its period column, the columns other terms filter that it never does, and a note for a table whose status sits beside a date range. The rest follow by how well they match, counting the columns the question names. terms: names to return in full, such as ones the page listed as cut to fit. A name that matches nothing gets its closest entries. With neither, the page is ordered by use.

Tools.search_context

Tools.search_context(question: str, top: int = 5) -> list[dict]

The tables, metrics and reviewed queries that best fit a question, best first, then the glossary terms it matches with their whole definitions. A column the question names that several tables hold says so under two_readings, and the table of the entity the question names ("customer region") comes first. A table whose status column sits beside a date range has a status_note. Words of the question that no table, column, value, comment or term uses come last, as an unmatched hit: when no table holds what one names, the data cannot answer.

Tools.query

Tools.query(sql: str, tokens: dict | None = None, expect_columns: list[str] | None = None, explain: bool = True) -> dict

Run SQL. status says what happened: ok or empty when it ran; plan_error, permission_denied, timeout, over_cap or error when it did not, with error in one line. A failure is never an empty result. notes (present when there are any) holds the warnings to read before using the answer, and, for an empty or all-null result, one quick count that shows where the rows went.

expect_columns: the columns the question asks the answer to return. When given, a note names any the result lacks and any it adds; nothing is dropped. Names match without regard to case, spaces or underscores.

explain: include the explain record. An agent is better without it: it is most of the result's size and nothing in it changes the answer, so the MCP server leaves it out and profile(handle, op="explain") returns it.

Tools.profile

Tools.profile(handle: str, op: str = describe, **kwargs) -> dict

Inspect a handle without reading all its rows. op: describe (sample=), head (n=), aggregate (spec=, by=), filter (expr=, returns a new handle), chart (spec=) or explain (the query's explain record).

Tools.write

Tools.write(handle: str, target: str) -> dict

target: a local table name, or a file name ending in .parquet or .csv inside write_dir.

Tools.verify

Tools.verify(name: str, question: str, handle: str, note: str = ) -> dict

The agent proposes this answer's SQL as a verified query. It stays "proposed", at half confidence, until a person accepts it with ContextModel.review; an agent cannot bless its own SQL.

Context

ContextModel.from_yaml

ContextModel.from_yaml(path: str | Path) -> "ContextModel"

Read a context file written by the crawl.

ContextModel.metrics

ContextModel.metrics(include_generated: bool = True) -> dict[str, Metric]

The metric definitions, keyed by name. include_generated=False keeps only those a person accepted.

ContextModel.review

ContextModel.review(ref: str, accept: bool, note: str | None = None, sql: str | None = None) -> None

A human decision. Accepted items become verified; the queue drops the item.