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

> ## Agent Instructions
> To set up Hatchmark for a user, follow https://hatchmark.dev/docs/get-started/agent-setup.md. Inside a Hatchmark project, prefer `hatchmark docs`: it prints the docs of the installed version.

# Data sources

> Every source type and option: CSV, Parquet and JSON files, DuckDB and SQLite files, cloud storage, PostgreSQL, MySQL, SQL Server, BigQuery and PostHog.

Each entry under `sources` in `hatchmark.yaml` is one table that metrics read: a file in the project,
a table in a DuckDB or SQLite file, files in cloud storage, or a table or query in a database. Its
name is lowercase snake\_case, such as `orders` or `web_sessions`, and metrics name it in their
`table` field. [Connect your data](/docs/guides/connect-your-data.md) walks through adding one.

## Files

**`path` is relative to `hatchmark.yaml`**, not to `dataDir`: a file at `data/orders.csv` is
`path: data/orders.csv`. Paths stay inside the project: no absolute paths, no `..`, and no link
(to the file or a folder on the way) that leads outside the project (HM2074). Links that stay inside
the project work.

| `type` | Options |
| - | - |
| `csv` | `delimiter`: one character, default `,`. `header`: whether the first row names the columns, default `true`. |
| `parquet` | None; Parquet carries its own column types. |
| `json` | `format`: `array` (one array of objects, the default) or `ndjson` (one object per line). |
| `duckdb` | `table`: the table or view to read from the DuckDB file; see [DuckDB files](#duckdb-files). |
| `sqlite` | `table`: the table or view to read from the SQLite file; see [SQLite files](#sqlite-files). |

```yaml theme={null}
sources:
  orders:
    type: csv
    path: data/orders.csv
  events:
    type: parquet
    path: data/events.parquet
  refunds:
    type: json
    path: data/refunds.ndjson
    format: ndjson
  stores:
    type: csv
    path: data/stores.tsv
    delimiter: "\t"
```

Every file source also takes these options:

| Option | Meaning |
| - | - |
| `timezone` | IANA time zone that the file's timestamps without an offset were written in, such as `America/Chicago`. Without it they are read as UTC; a project whose `timezone` isn't UTC gets note `HM4016` when a source has them. Timestamps with an offset and dates never shift. |
| `freshness` | How complete the source is (its horizon). By default it is complete through the latest value of the time column a metric uses, over all rows. `{ column: exported_at }` measures another column, `{ lag: { days: 1 } }` or `{ lag: { hours: 6 } }` takes the still-filling end off, `{ through: 2026-11-26 }` fixes the last complete date, and `{ through: as_of }` says the source is complete whenever the build runs (sparse logs). |

```yaml theme={null}
usage:
  type: csv
  path: data/usage_daily.csv
  freshness:
    lag:
      days: 1
```

[Numbers](/docs/reference/numbers.md#time) says how horizons decide `latest_data`.

Column types are inferred from every row of the file (see [Numbers](/docs/reference/numbers.md#reading-files)).
A metric or block that names a column the file does not have fails `hatchmark build` with `HM2015`,
which names the source and the column; `hatchmark check` does not catch every such case.

## Row-count tests

A file source can carry `tests` that `hatchmark test` runs: each counts the rows of its file,
optionally only those that match `where` ([metric filters](/docs/reference/metrics.md#filters)), against inclusive
bounds. A snapshot source counts the rows of every snapshot. A lookup source takes no tests; test the
sources it joins.

```yaml theme={null}
sources:
  orders:
    type: csv
    path: data/orders.csv
    tests:
      - name: full export
        rows: { min: 1000 }
      - rows: { max: 0 }
        where:
          - column: amount
            op: is_null
```

`rows` needs `min`, `max` or both. A count outside them is `HM4030`. Tests never change what a query
reads, so editing them keeps the build cache.

## DuckDB files

A `duckdb` source reads one table or view from a DuckDB database file in the project. The file is
attached read-only, so DuckDB's own types arrive unchanged: `HUGEINT`, `DECIMAL` up to 38 digits,
`TIMESTAMP_NS` and time zones follow the [numbers rules](/docs/reference/numbers.md) exactly as for Parquet.

```yaml theme={null}
sources:
  orders:
    type: duckdb
    path: data/shop.duckdb
    table: analytics.orders
```

`table` is `name` or `schema.name` (`main` without a schema). `timezone`, `freshness` and
`snapshot` work as for other files. DuckDB keeps recent changes in a `.wal` file next to the
database until it checkpoints; Hatchmark reads that file with the database, read-only, and the build
cache keys the source by the contents of both. Close the writing process before building, so the
two files are read in one state.

The file is opened in its own DuckDB instance that can reach nothing but the file and its `.wal`:
no other files, no network, no stored DuckDB secrets and no extensions. A view that reads another
file or a URL (`read_csv`, `read_parquet`, `s3://`) stops with `HM2015` naming the view; declare
that file as its own source instead.

## SQLite files

A `sqlite` source reads one table or view from a SQLite database file in the project through
DuckDB's `sqlite` extension (downloaded once from extensions.duckdb.org and checked against its
signature; `HM2044` when the download fails or the cached copy is damaged; see
[Network access](/docs/reference/build.md#network-access)).

```yaml theme={null}
sources:
  orders:
    type: sqlite
    path: data/shop.db
    table: orders
```

Every command copies the database with its `-wal`, `-shm` and `-journal` files into a private
directory and reads the copy, so the project's files are never written. SQLite recovers the copy as
it would the original: a `-wal` left by a writer in WAL mode is read with the database, and a hot
`-journal` left by a writer that stopped mid-transaction is rolled back. The cache keys the source by
the contents of all four files.

SQLite itself evaluates the table or view, so a view's casts, integer division and `LIKE` give
SQLite's results. SQLite stores a type per value; Hatchmark reads each column by the affinity SQLite
gives its declared type and the values it holds:

* Whole numbers, in any column, as 64-bit integers, exactly.
* Floats, or floats mixed with whole numbers up to 2^53, as floating-point numbers. A whole number
  beyond 2^53 beside floats in the same column stops `check` and the build with `HM2043`, since a
  float cannot keep it exactly.
* Columns whose declared type names `DATE` or `TIME` (such as `DATETIME`) through SQLite's
  `strftime`: ISO 8601 text with a UTC offset is converted to UTC, and numbers are Julian day numbers.
  The source's `timezone` applies to text without an offset.
* Text as text, and blobs as blobs.

A value SQLite would not compute with as the declared type, such as `'two'` in an `INTEGER` column,
`'1,5'` in a `REAL` column, a blob in a numeric column, or text that is not a date in a `DATETIME`
column, stops `check` and the build with `HM2043` naming the column and the value; fix the values or
read the table through a view that casts the column. As for DuckDB files, the copy is opened in its
own DuckDB instance that reaches only the database and its companion files.

## Cloud storage

A `csv`, `parquet` or `json` source can read objects from Amazon S3 (or an S3-compatible store such
as Cloudflare R2), Google Cloud Storage or Azure Blob Storage. The path is a URL with a bucket, and
may be a glob that matches several objects; `storage` names the environment variables that hold the
credentials, never the credentials themselves, or asks for the machine's own identity with
`credentials: ambient` ([Ambient credentials](#ambient-credentials)).

```yaml theme={null}
sources:
  orders:
    type: parquet
    path: s3://shop-data/orders/*.parquet
    storage:
      key_id_env: SHOP_S3_KEY_ID
      secret_env: SHOP_S3_SECRET
      region: us-east-2
    max_age: { hours: 6 }
```

| Scheme | Credentials in `storage` | Other `storage` fields |
| - | - | - |
| `s3://` | `key_id_env` and `secret_env`: an access key id and secret | `region` (default `us-east-1`), `endpoint`, `url_style`, `use_ssl` |
| `gs://` or `gcs://` | `key_id_env` and `secret_env`: an HMAC key for the bucket | `endpoint`, `use_ssl` |
| `az://` or `azure://` | `connection_string_env`: a storage account connection string | |

Hatchmark uses only the variables a source names, and reads the credentials it finds on the machine
only when the source asks for them with `credentials: ambient`. Without it, AWS, Google and Azure
variables or credential files (such as `AWS_ACCESS_KEY_ID`, `AWS_SESSION_TOKEN` or
`AZURE_STORAGE_CONNECTION_STRING`) are not read, and a credential never appears in a message or
in `--json` output. `check` warns with `HM2047` when a named variable is unset or empty, and `build`
stops with it.

Each command lists the objects the path matches (their keys, sizes and modification times),
downloads them with DuckDB's `httpfs` extension (`azure` for Azure, downloaded once from
extensions.duckdb.org; `HM2044` when that fails), reads them with the same reader options as a
local file, and keeps a Parquet copy in `.hatchmark/cache/v1/s/`. The next command lists the objects
again and downloads them only when the listing changed. With `max_age`, a copy younger than that
is reused without contacting the store at all. The store refusing the credentials, or a path that
matches no object, stops the build with `HM2048`; objects that change while they download stop it
with `HM2049`. `check` does not contact the store, so it does not check the columns of a cloud
storage source; `build` does.

Hatchmark sends storage requests through a proxy on `127.0.0.1` that forwards only to the
source's allowed host and port. For S3 and GCS, `url_style: vhost` uses the bucket's virtual
host under the endpoint (the S3 default), and `url_style: path` uses the endpoint itself
(the GCS default). Without `endpoint`, an S3 source reaches its region's endpoint,
`s3.<region>.amazonaws.com` (`s3.<region>.amazonaws.com.cn` in China), so `region` must be the
bucket's region: a bucket in another region stops the build with `HM2048`, which says to set
`region`. Over HTTPS, a bucket whose name has a dot is always read with path-style URLs, so it
cannot use `credentials: ambient` (`HM3001`); name the credential variables instead. Azure uses the connection string's `BlobEndpoint` or, if it is unset or
empty, the account's blob host. A nonempty `BlobEndpoint` must be a valid `http://` or
`https://` URL; a missing scheme, for example, gives `HM2015`.

A redirect to another host or port fails with `HM2015` and names the destination. With
virtual-host URLs, another bucket has a different host, so the same rule applies. With
path-style S3 or GCS over plain HTTP (`use_ssl: false`), the proxy also checks the bucket
in the path and rejects encoded `/` or `\` in the path. A refused path gives `HM2015` and
names the path. For path-style HTTPS and for Azure, the proxy checks only the host and port (see
[Ambient credentials](#ambient-credentials) for what that means for a machine identity).
A corporate proxy set in `HTTPS_PROXY` or `http_proxy` carries the requests the local proxy
allows, so these rules still apply ([Proxy and certificates](#proxy-and-certificates)). Hatchmark verifies the
certificate of every HTTPS store against the system's trusted roots, or against
`HATCHMARK_CA_FILE` when it is set.

### Ambient credentials

On a machine that has its own cloud identity, such as an EC2 instance role, an ECS task role or an
AKS workload identity, a source can use it instead of a stored key. It has to ask for it: a project
never reads the machine's credentials unless its source sets `credentials: ambient`. The project
still chooses the path, so the identity reaches whatever bucket the source names and the role may
read; what Hatchmark guarantees is that the store cannot send the requests elsewhere. For S3 over
HTTPS that holds per bucket only with virtual-host URLs, where the bucket is part of the host the
proxy sees, so `credentials: ambient` with `url_style: path` over HTTPS is an error. Azure serves
every container of an account from one host, `<account>.blob.core.windows.net`, so an Azure
source is held to its storage account, not its container. A credential scoped to the account can
read every container in that account. For Azure, the boundary is the identity's role assignment:
assign Storage Blob Data Reader on the container, not the account, when a source should reach one
container only.

Because the project file opts in, building someone else's project can use your machine's identity:
a `hatchmark.yaml` you did not write can set `credentials: ambient` and read whatever your instance
role, task role or managed identity may read, or `chain: [env]` and use the AWS keys in your shell.
This is the same trust you give a project that names your variables in `key_id_env`. Set
`HATCHMARK_NO_AMBIENT_CREDENTIALS` wherever you build projects you do not trust, such as a CI runner
for pull requests from forks.

```yaml theme={null}
sources:
  orders:
    type: parquet
    path: s3://shop-data/orders/*.parquet
    storage:
      credentials: ambient
      region: us-east-2
  refunds:
    type: csv
    path: az://finance/refunds/*.csv
    storage:
      credentials: ambient
      account: shopfinance
```

Hatchmark tries the sources of `storage.chain` in order and uses the first one this machine offers:

| `chain` entry | Cloud | Where the credentials come from |
| - | - | - |
| `web_identity` | S3 | `AWS_WEB_IDENTITY_TOKEN_FILE` and `AWS_ROLE_ARN`, exchanged at STS (EKS IAM roles for service accounts, or any OIDC provider) |
| `container` | S3 | `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI` or `AWS_CONTAINER_CREDENTIALS_FULL_URI` (an ECS task role, or EKS Pod Identity) |
| `instance` | S3 | The EC2 instance role, through the instance metadata service with IMDSv2 (`AWS_EC2_METADATA_DISABLED=true` turns it off) |
| `env` | S3 | `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` and `AWS_SESSION_TOKEN` in the environment |
| `workload_identity` | Azure | `AZURE_FEDERATED_TOKEN_FILE`, `AZURE_CLIENT_ID` and `AZURE_TENANT_ID` (AKS workload identity) |
| `managed_identity` | Azure | The managed identity of the VM, App Service or Container App (`AZURE_CLIENT_ID` picks one of several) |
| `env` | Azure | A service principal in `AZURE_TENANT_ID`, `AZURE_CLIENT_ID` and `AZURE_CLIENT_SECRET` |

Without `chain`, an S3 source tries `web_identity`, `container` and `instance`, and an Azure source
`workload_identity` and `managed_identity`: only the machine's own identity. Keys in the environment
are used only when `chain` names `env`, so a developer's shell does not lend its keys to a project by
accident. On a laptop signed in with AWS SSO, export short-lived keys with
`eval "$(aws configure export-credentials --format env)"` and set `chain: [env]`; profiles in
`~/.aws` and the Azure CLI login are not read. A source whose settings are present but that fails,
such as a role STS refuses, stops the build with `HM2053` instead of falling back to the next
identity, and so does a machine that offers none of them; the message names each source it tried.

The STS, metadata and token endpoints are reached by Hatchmark itself, before DuckDB reads the
store, through a proxy of their own that reaches only the endpoints of the sources in `chain`; the
store's proxy still reaches only the source's store, so a store cannot send DuckDB on to the
metadata service, and a `storage.endpoint` or `BlobEndpoint` on a link-local address such as
`169.254.169.254` is refused with `HM2015`. `HATCHMARK_NO_AMBIENT_CREDENTIALS` also stops a source
whose local copy is still within `max_age`, so a cached copy never outlives the switch. `hatchmark doctor` says which identity each ambient source uses on this machine,
such as `the instance role shop-reader from the instance metadata service at 169.254.169.254`, and
until when its credentials are valid, and errors name it too; a key, token or secret never appears.
Hatchmark gets the credentials once per source and command and does not renew them, so credentials
that expire before the download ends stop it with `HM2055`.

Google Cloud Storage keeps using an HMAC key: DuckDB cannot read Google's application default
credentials yet ([duckdb#23207](https://github.com/duckdb/duckdb/issues/23207)), so
`credentials: ambient` on a `gs://` path is an error. An Azure source with ambient credentials
reads from the public cloud's `<account>.blob.core.windows.net`.

Whoever runs Hatchmark can forbid ambient credentials on a machine, for example a CI runner that
builds other people's projects, by setting `HATCHMARK_NO_AMBIENT_CREDENTIALS` to any value: `check`
then warns with `HM2054` for each source that asks for them, and `build` stops before contacting
the machine's identity.

### Proxy and certificates

Hatchmark reaches cloud storage, ambient credential endpoints and DuckDB's extension downloads
directly unless whoever runs it sets a proxy in the standard variables. These variables come from
the environment of the command, never from the project, and are read as curl reads them:
`https_proxy` wins over `HTTPS_PROXY` and `no_proxy` over `NO_PROXY`, the `http://` proxy is read
only from lower-case `http_proxy` (curl ignores `HTTP_PROXY`, which a CGI request can set), and
`ALL_PROXY` is not read:

| Variable | Meaning |
| - | - |
| `HTTPS_PROXY` | The `http://` proxy for `https://` stores, STS and the Microsoft Entra token endpoint, such as `http://proxy.example.com:3128`; a user and password go in the URL, percent-encoded |
| `http_proxy` | The `http://` proxy for `http://` stores and DuckDB's extension downloads, in the same form; set both when one proxy carries everything |
| `NO_PROXY` | Hosts reached directly, separated by commas or spaces: `host`, `.domain` or `*.domain` (the domain and every host under it), `host:port`, an IP range such as `10.0.0.0/8` or `fd00::/8`, or `*` for all. A range matches IP addresses only; a host name is never resolved to check it |
| `HATCHMARK_CA_FILE` | A PEM file of the certificate authorities to trust; it replaces the system's trusted roots for cloud storage and credential requests |

The local proxy that guards each source passes the requests it allows on to the corporate proxy
(plain HTTP to `http_proxy` as an absolute URL, HTTPS to `HTTPS_PROXY` with `CONNECT`), so the
bucket and host rules above still apply. A machine that already sets these variables for other
tools sends cloud storage through the same proxy. Metadata services and local credential agents are
always reached directly, whatever the proxy variables and `NO_PROXY` say: the instance metadata service and container agents
on link-local addresses (`169.254.169.254`, `169.254.170.2`, `fd00:ec2::254`), and the loopback
endpoints that `AWS_CONTAINER_CREDENTIALS_FULL_URI` or `IDENTITY_ENDPOINT` name. STS and the
Microsoft Entra token endpoint go through the proxy like the stores. A proxy that inspects TLS signs the store's
certificate with its own authority: put that authority in `HATCHMARK_CA_FILE`, together with the
public roots if some hosts are listed in `NO_PROXY`. For Azure sources, DuckDB's `azure`
extension takes the bundle from libcurl's `CURL_CA_INFO`, which is shared by the whole process:
Hatchmark sets it to `HATCHMARK_CA_FILE` while it reads Azure sources and restores it afterwards,
and Azure reads that need a different bundle, or none, wait for each other instead of running
together. DuckDB documents that variable as working on Linux. A proxy variable that is not an
`http://` URL, such as `socks5://`, is checked only when a request needs it: a cloud storage read
or credential request that would go through it stops with `HM2056` naming the variable, while
local files, database sources and requests that `NO_PROXY` exempts are unaffected, and
`hatchmark doctor` warns about it. Hatchmark's own requests to metadata services, credential
agents and the local proxy never take a proxy from Node.js's `--use-env-proxy` or
`NODE_USE_ENV_PROXY`. A proxy that cannot be reached, asks for authentication (407) or
refuses the store, a bundle that cannot be read, and a store certificate that does not verify stop
the build with `HM2056`, with the proxy's address but never its password; a certificate failure
without `HATCHMARK_CA_FILE` says how to set it. Error messages keep a provider's status and error
code, such as `AccessDenied` or `AADSTS700016`, and leave out its free text.

The tests run against S3-compatible, GCS-compatible and Azure emulators, not the hosted services.

## Database sources

A `postgres`, `mysql` or `sqlserver` source reads a table, a view or a query from PostgreSQL, from MySQL or
MariaDB (`type: mysql`; tested against MySQL 8.4 and MariaDB 11.4), or from SQL Server and Azure SQL
(`type: sqlserver`, a preview; tested against SQL Server 2022, see [SQL Server](#sql-server)). A
`bigquery` source reads Google BigQuery (see [BigQuery](#bigquery)), and a `posthog` source the result
of a HogQL query in PostHog (see [PostHog](#posthog)). Metrics use it exactly like a file source.

```yaml theme={null}
sources:
  orders:
    type: postgres
    env: SHOP_DATABASE_URL
    table: public.orders
  refunds:
    type: mysql
    env: BILLING_DATABASE_URL
    query: SELECT id, order_id, amount, refunded_at FROM refunds WHERE refunded_at >= '2024-01-01'
    max_age:
      hours: 1
```

| Option | Meaning |
| - | - |
| `env` | Required. The name of the environment variable that holds the connection string. The connection string never goes in `hatchmark.yaml`; `env` takes only a variable name. |
| `table` | A table or view, as `name` or `schema.name`. Without a schema, PostgreSQL uses the first match on the connection's search path, MySQL uses the connection's database, and SQL Server looks first in the database user's default schema, then in `dbo`. Use the table or view name as it appears in the database. |
| `query` | Instead of `table`: a query that returns rows, such as a `SELECT`, that the database runs in its own SQL dialect. Use it to cast columns, filter rows or join tables before Hatchmark reads them. One statement: a final `;` and comments around it are fine; a second statement, or a MySQL or MariaDB executable comment or hint (`/*!`, `/*M!`, `/*+`), fails with `HM2015`. |
| `max_age` | `{ minutes: n }`, `{ hours: n }` or `{ days: n }`: reuse the local copy of the rows while it is younger than this. Without it, `build` fetches the rows on every run and `dev` once per session. |
| `read` | `window` (default): the copy holds only the columns the project's dashboards read; for a `table` source, unused wide columns never leave the database, while a `query` source still sends its whole result, of which only those columns are kept. `copy`: every column, so adding a metric on another column does not fetch again. `aggregate` (PostgreSQL only): queries run in the database where they can; see [Running queries in PostgreSQL](#running-queries-in-postgresql). |

`timezone`, `freshness` and `snapshot` work as for file sources.

### Credentials

The variable holds the connection string in the form DuckDB's extensions take:

* PostgreSQL: a URL or a libpq string, such as `postgresql://reader:secret@db.example.com:5432/shop?sslmode=require`.
* MySQL: `host=db.example.com port=3306 user=reader password=secret database=shop`.
* SQL Server: `Server=db.example.com,1433;Database=shop;User Id=reader;Password=secret;Encrypt=yes`.

Percent-encode `@`, `/`, `?` and `#` in a URL password (`%40`, `%2F`, `%3F`, `%23`); a URL
password with a raw `@` or `/` fails with `HM2041` before Hatchmark connects, because PostgreSQL
would read part of the password as the host.

The variable alone says where to connect and as whom. Hatchmark ignores every `PG*` and `MYSQL_*`
environment variable, `PGUSER`, `PGPASSWORD`, `PGPASSFILE`, `PGSERVICE` and `MYSQL_PWD` among
them, as well as `~/.pgpass` and PostgreSQL service files; a connection string that names a
`service` fails with `HM2041`. A connection string without a password connects only to a
database that asks for none, such as a MySQL user created with an empty password.

Set it in the environment of the process that runs Hatchmark, on a machine that can reach the
database. Hatchmark never writes it to disk: diagnostics, `--json` output and logs replace the connection string and every password in it (`password=`, `passwd=`,
`pwd=` and URL passwords) with `***`. The local copy is keyed by an HMAC of the connection string, exactly as
written, and the source: the HMAC key is a random secret that Hatchmark creates once in
`.hatchmark/copy-key`, readable only by its owner, so no hash of a password reaches disk. Two
connection strings written differently never share a copy, even when they reach the same database.
The copy stores a SHA-256 of a source's query rather than its text.

Hatchmark attaches the database read-only. PostgreSQL runs every read in a read-only transaction,
so a query that writes fails. DuckDB's MySQL extension refuses statements that return no rows, such
as `DELETE`, but MySQL itself does not enforce read-only reads. SQL Server does not either (see
[SQL Server](#sql-server)). Give Hatchmark a user that may only read the tables it needs.

### How queries run

`build`, `dev`, `explain` and `check --sql` load DuckDB's `postgres`, `mysql` or `mssql` extension
(downloaded once from extensions.duckdb.org, `mssql` from community-extensions.duckdb.org; `HM2044`
when that fails), attach the database
read-only, and copy the table or query into `.hatchmark/cache/v1/s/<source>.<key>.parquet`: with
`read: window`, only the columns that the dashboards' metrics, dimensions, filters, segments and
time columns read (every column when a metric of type `sql` reads the source, since its SQL may
name any column; `dev` and `hatchmark data` always copy every column). A new column in a dashboard
fetches a new copy. The copy lists the rows in the order of the table's primary key, or of all its
columns when it has none, whichever columns it keeps, so `read: window` and `read: copy` add floats
in the same order. On a large table without a primary key that sort reads every column of every
row, so the database sends every column even though the copy keeps fewer; a primary key keeps the
sort to the key. Every
query of the command then reads that copy as it reads a Parquet file: the same SQL, the same
[numbers rules](/docs/reference/numbers.md), and one set of rows in one order, so a build never mixes rows fetched
at different moments and float sums come out the same on every run over the same copy. The
database reads each source once per command; filtering, grouping and totals happen in DuckDB.

The query cache keys entries by the query plan and the copy's SHA-256, as for files, so queries
reuse their results exactly when the copy is reused (`max_age`). `hatchmark explain` shows when
each copy was fetched. A copy holds the source's rows on the build machine: `.hatchmark/` is in the
`.gitignore` that `hatchmark init` writes. Deleting `.hatchmark/` is always safe; the next command
fetches again.

### Size of a database source

Every fetch copies the source's rows to the build machine: all of the rows the table or query
returns, in the columns the copy keeps. Without `max_age`, `build` fetches again on every run. So
the size of a database source is the size of that result, and the database, the network and the
build machine's disk under `.hatchmark/` all carry it on each fetch. Measure it in the database
before pointing a scheduled build at a large table, such as with `SELECT count(*)` over the table or
query.

To keep a source small:

* Use `query` instead of `table` to keep only the rows the dashboards need, such as a date range
  (`WHERE ordered_at >= '2024-01-01'`) or the columns they read.
* Use `query` to group the rows in the database first, such as one row per day and region with a
  sum, and write the metrics against that result (a `sum` of the daily sums). Counts become sums of
  daily counts; a `count_distinct` or `median` cannot be rebuilt from grouped rows, so keep those
  on a source with the original rows.
* On PostgreSQL, `read: aggregate` runs the queries it can in the database and fetches only their
  result rows ([Running queries in PostgreSQL](#running-queries-in-postgresql)).
* Set `max_age` so builds within that time reuse the copy instead of fetching again.

### Running queries in PostgreSQL

With `read: aggregate` on a `postgres` source, each query whose result PostgreSQL computes exactly
runs there, and only its result rows are fetched. The others run on a `read: window` copy, query by
query. A query runs in PostgreSQL when every part of it is exact and independent of row order:

* `count`, `count_distinct`, and `sum`, `min` and `max` of integer and `numeric` columns (`avg` is
  a sum and a count)
* dimensions on text, boolean, integer and date columns, and time buckets of `date`, `timestamptz`
  and UTC `timestamp` columns at any grain
* `in`, `not_in`, `eq`, `neq`, `is_null` and `not_null` filters on text, boolean and integer columns,
  in metrics, segments and filter controls

A median, a quantile, a float sum, a metric of type `sql`, a snapshot metric, a map region, an
Other row, an `in_table` filter, a filter on a time column or a range filter runs on the copy.
`hatchmark explain` prints `-- runs in PostgreSQL` above the SQL of each query that runs there,
or `-- runs on the local copy:` and the reason.

Text is compared, grouped and counted by its bytes, as on the copy: PostgreSQL reads each text
column as `text` in the `"C"` collation, so `citext`, enums and nondeterministic collations group and
count as the copy does. A query whose time column holds `infinity` or `-infinity` runs on the copy, and
so does a query whose pushed result cannot be read back, such as a `NaN` in a `numeric` column.
`hatchmark dev` opens a new transaction for every rebuild and keeps it open, idle, until the next
one, so a long `dev` session holds back `VACUUM` on the database as any long-running transaction
does. Stop `dev` when you are done, or set `idle_in_transaction_session_timeout` for its user:
after the server ends an idle session, the next rebuild connects again.

Time buckets are computed by Hatchmark: it reads the column's first and last value, lists the
buckets between them in the project time zone, and sends their start instants, so PostgreSQL's own
time zone data and `TimeZone` setting never place a row. Each result column is cast to the type the
copy would give it, so a number reads the same on both routes. Every query of a command that runs
in PostgreSQL reads one snapshot: they run in one `REPEATABLE READ` read-only transaction per
source. A query that runs on the copy reads a copy fetched during the same command: `max_age` does not
apply to a `read: aggregate` source, so one build never reuses rows from an earlier one. Results of a `read: aggregate` source are not kept in the query cache.

### Types

| Database type | Read as | Numbers rule |
| - | - | - |
| `smallint`, `integer`, `bigint`, MySQL unsigned integers | DuckDB integers | Summed exactly (as `HUGEINT`), like integers in files. |
| `numeric(p,s)`, `decimal(p,s)` with p ≤ 38 | `DECIMAL(p,s)` | Exact, summed in at most 38 digits: a total that needs more stops with `HM2015`. A scale above the precision, such as `numeric(3,5)`, reads as `DECIMAL(s,s)`; a negative scale fails with `HM2043`. |
| PostgreSQL `numeric` without a precision; `numeric`/`decimal` with p > 38 | `DOUBLE` (the driver's choice) | Float rules (`HM4004`); a metric that aggregates it gets warning `HM4080` with `table`. With `query` Hatchmark cannot see the declared type, so no warning: cast it, such as `amount::numeric(18,2)`. |
| `real`, `double precision`, `float`, `double` | `DOUBLE` | Float rules. |
| PostgreSQL `timestamptz`, MySQL `TIMESTAMP` | `TIMESTAMP WITH TIME ZONE` | An instant; MySQL is read with session time zone UTC, so the server's zone never shifts it. MySQL through `query`: see below. |
| PostgreSQL `timestamp`, MySQL `DATETIME` | `TIMESTAMP` | Wall-clock time in the source's `timezone` (default UTC; note `HM4016`). |
| `date` | `DATE` | A calendar date. |
| `text`, `varchar`, `char`, `uuid`, `json`, `jsonb`, `time`, enums | `VARCHAR` | Text. MySQL text must not collide under its collation (`HM2046`, below). |
| PostgreSQL `money` | `VARCHAR`, such as `$1,000.50` | Text: a metric that sums it fails with `HM2043`. Cast it in `query`, such as `cash::numeric(18,2)`. |
| PostgreSQL `"char"`, `"char"[]` | `VARCHAR` | DuckDB reads its space value as an empty string, so a query that groups, counts distinct, filters or offers a select control on it fails with `HM2043`, and so does a `sql` metric that reads it in any way, by name, by position, through `COLUMNS(*)` or as the whole row. A `sql` metric that never reads it runs. Casting it in `query`, such as `code::text`, avoids all of these. |
| `boolean`, MySQL `TINYINT(1)` and `BIT(1)` | `BOOLEAN` | A MySQL `TINYINT(1)` holding any value other than 0 reads as true; cast it in `query` to keep the number. |
| `interval`, `bytea`/`BLOB`, arrays, composite types | kept as DuckDB reads them | A metric that uses one fails `check` with `HM2043`. |

Both databases deliver microseconds; nanosecond timestamps (`TIMESTAMP_NS`) only come from Parquet
files. Integer sums that pass 64 bits stay exact in `HUGEINT`, as for files. A PostgreSQL `NaN` in
a `numeric(p,s)` column reads as `NULL`, and in a plain `numeric` column as the float `NaN`.

A MySQL query reads `DATETIME` and `TIMESTAMP` columns as the same type, so Hatchmark cannot tell a
wall-clock time from an instant. Without `timezone` on the source both read the same and the query
is fine. With `timezone`, a date-time column in the query fails with `HM2045`: read it with
`table`, or convert it to UTC in the query, such as `CONVERT_TZ(created_at, 'America/New_York',
'+00:00')` for a `DATETIME`, and remove `timezone`.

### MySQL text and collations

MySQL compares text with the column's collation; the default, `utf8mb4_0900_ai_ci`, ignores case and
accents, so `West`, `west` and `Wést` form one group in MySQL's own SQL. Hatchmark groups, counts
and filters the copied rows by their bytes. So that a dashboard never shows more groups, a higher
distinct count or a different filtered total than MySQL would, `build` and `dev` ask MySQL, for
each text column a query groups by or counts distinct values of and each text filter it applies,
whether its collation and a byte comparison agree, and stop with `HM2046` when they do not: two
stored values that differ only in case, accents or trailing spaces, or a filter value such as `west`
that matches `West` only under the collation. Equality filters (`eq`, `neq`, `in`, `not_in`) are
checked row by row. Filters that order text (`gt`, `gte`, `lt`, `lte`, `between`) and `in_table`
or `not_in_table` on a MySQL text column, or with a MySQL text column as the key, always stop
with `HM2046`, since MySQL orders and joins
text by the collation and Hatchmark by bytes. Column names match regardless of case, as in MySQL.
A text column no metric groups, counts or filters never stops a build. Write filter values exactly as the data stores them, normalize the column in
`query`, such as `SELECT LOWER(region) AS region`, or
make it case- and accent-sensitive, such as `SELECT region COLLATE utf8mb4_0900_as_cs AS region`. A
binary collation such as `utf8mb4_bin` reaches DuckDB as `BLOB` (`HM2043`). Each comparison is
checked once per copy, all of a query's in one MySQL read.

### SQL Server

A `sqlserver` source reads SQL Server 2019 or later and Azure SQL Database through DuckDB's
community `mssql` extension. It is a preview: `read` takes `window` (default) or `copy`, and
`read: aggregate` is not available yet. SQL Server logins (`User Id` and `Password`) are supported;
Microsoft Entra ID sign-in is not.

A `query` source reaches SQL Server only inside an outer `SELECT`, as
`SELECT * FROM (<query>) AS hm_q`, with a `WITH` clause and its common table expressions kept in
front. So the query must be one `SELECT` that names every column, and it cannot end in `ORDER BY`
without `TOP` or `OFFSET`: Hatchmark orders the copy itself, so leave the `ORDER BY` out. A query
that SQL Server refuses stops with `HM2051` and SQL Server's own error, before any of it runs. Three shapes are not supported: a query that starts with `;WITH` (drop the semicolon), one that ends in
`OPTION (MAXRECURSION n)`, and a common table expression named `hm_q` (rename it).

**Use a login that may only read: it is the security boundary.** Hatchmark attaches the database
read-only, wraps the query in an outer `SELECT` and rolls back the transaction of every read, but
none of these stops a query written to change data, since the extension does not enforce read-only
access and a query can commit its own transaction. Create a login whose user is only in
`db_datareader`, or has `SELECT` on the tables Hatchmark reads.

| SQL Server type | Read as | Numbers rule |
| - | - | - |
| `tinyint`, `smallint`, `int`, `bigint` | DuckDB integers | Summed exactly (as `HUGEINT`). |
| `decimal(p,s)`, `numeric(p,s)` | `DECIMAL(p,s)` | Exact, as for PostgreSQL. |
| `money`, `smallmoney` | `DECIMAL(19,4)`, `DECIMAL(10,4)` | Exact. |
| `float`, `real` | `DOUBLE`, `FLOAT` | Float rules (`HM4004`). |
| `bit` | `BOOLEAN` | |
| `date` | `DATE` | A calendar date. |
| `datetime`, `smalldatetime`, `datetime2` | `TIMESTAMP` | Wall-clock time in the source's `timezone` (default UTC). `datetime2(7)` keeps microseconds. |
| `datetimeoffset` | `TIMESTAMP WITH TIME ZONE` | An instant. |
| `char`, `varchar`, `nchar`, `nvarchar`, `text`, `ntext`, `xml` | `VARCHAR` | Text, read as Unicode whatever the column's code page; `char(n)` and `nchar(n)` without their padding. Must not collide under its collation (`HM2046`, as for MySQL). |
| `uniqueidentifier` | `UUID` | |
| `binary`, `varbinary` | `BLOB` | A metric that uses one fails `check` with `HM2043`. |

SQL Server compares text with the column's collation, and the default, such as
`SQL_Latin1_General_CP1_CI_AS`, ignores case and trailing spaces. Hatchmark checks a SQL Server
text column as it checks a MySQL one (see above), and suggests a case- and accent-sensitive
collation such as `SELECT region COLLATE Latin1_General_100_CS_AS AS region`.

### BigQuery

A `bigquery` source reads a table, a view or a GoogleSQL query from Google BigQuery through DuckDB's
community `bigquery` extension, downloaded once from community-extensions.duckdb.org. `read` takes
`window` (default) or `copy`.

```yaml theme={null}
sources:
  orders:
    type: bigquery
    env: BIGQUERY_CREDENTIALS
    project: acme-analytics
    table: sales.orders
  signups:
    type: bigquery
    env: BIGQUERY_CREDENTIALS
    project: acme-analytics
    location: EU
    query: SELECT user_id, plan, created_at FROM growth.signups WHERE created_at >= '2024-01-01'
```

| Option | Meaning |
| - | - |
| `project` | Required. The Google Cloud project that runs the queries and is billed for them. A `table` is read from this project; a `query` may name `other-project.dataset.table`. |
| `table` | A table or view as `dataset.table`. Views, materialized views and external tables are read through a query job. |
| `query` | Instead of `table`: one GoogleSQL `SELECT`. Tables without a project are read from `project`. |
| `location` | Where the queries run: the location of the datasets they read, such as `EU` or `asia-northeast1`. Default `US`. |

`env`, `max_age`, `read`, `timezone`, `freshness` and `snapshot` work as for the other database sources.

**Credentials.** The variable that `env` names holds one of:

* the path of a credential file: a service account key, an external account file for workload
  identity federation (as `gcloud iam workload-identity-pools create-cred-config` writes it), or an
  authorized user file (as `gcloud auth application-default login` writes it, under
  `~/.config/gcloud/application_default_credentials.json`). Use an absolute path.
* the JSON of one of those files.
* an OAuth access token, such as the output of `gcloud auth print-access-token`. A token lasts
  about an hour, so use it for CI jobs that mint one per run, not for scheduled builds.

Only that credential is used. Hatchmark never falls back to Application Default Credentials:
`GOOGLE_APPLICATION_CREDENTIALS`, gcloud's default credential file, the metadata server of a Google
Cloud machine and DuckDB's saved secrets are all ignored, so a build reads BigQuery as exactly the
account you named. A credential that cannot be read, parsed or used fails with `HM2041`, and
diagnostics replace the variable's value, the file's contents, private keys and tokens with `***`.

**Permissions.** Give the account BigQuery Job User and BigQuery Read Session User on `project`
and BigQuery Data Viewer on the datasets it reads. Hatchmark attaches the project read-only: it
runs only `SELECT` statements, and a query that is a script, DDL or DML fails with `HM2015`
before BigQuery runs it. Data Viewer keeps the account from writing anyway.

**How it reads.** A table is read through the BigQuery Storage Read API without a query job; a view,
materialized view, external table or `query` runs as a query job whose result is read the same
way. Checking a table's columns runs one small query on the dataset's `INFORMATION_SCHEMA`. Query
jobs are billed by bytes processed, so `max_age` and a `query` that selects only the rows and
columns the dashboards need keep the cost down (see [Size of a database source](#size-of-a-database-source)).
The copy is sorted by all of its columns, since BigQuery primary keys are not enforced.

| BigQuery type | Read as | Numbers rule |
| - | - | - |
| `INT64` | `BIGINT` | Summed exactly (as `HUGEINT`). |
| `NUMERIC` | `DECIMAL(38,9)` | Exact, summed in at most 38 digits. `avg` is the sum divided by the count, as for every source, not BigQuery's `AVG` rounded to 9 decimals. |
| `BIGNUMERIC` | none | More digits than DuckDB keeps: a table with one fails with `HM2043`. Cast it in `query`, such as `CAST(amount AS NUMERIC)`. Through `query` it arrives as text, so a metric that sums it fails with `HM2043`. |
| `FLOAT64` | `DOUBLE` | Float rules (`HM4004`). |
| `TIMESTAMP` | `TIMESTAMP WITH TIME ZONE` | An instant. Through `query`: see below. |
| `DATETIME` | `TIMESTAMP`, or `TIMESTAMP WITH TIME ZONE` with `timezone` | Wall-clock time in the source's `timezone` (default UTC), placed as BigQuery's `TIMESTAMP(datetime, zone)` does: a repeated hour takes the earlier instant. |
| `DATE` | `DATE` | A calendar date. |
| `STRING`, `JSON`, `TIME` | `VARCHAR` | Text, compared by its bytes as BigQuery does unless the column has a collation (below). |
| `GEOGRAPHY` | `VARCHAR` | Well-known text, such as `POINT (1 2)`. |
| `BOOL` | `BOOLEAN` | |
| `BYTES`, `INTERVAL`, `ARRAY`, `STRUCT` | kept as DuckDB reads them | A metric that uses one fails `check` with `HM2043`. |

A query reads `DATETIME` and `TIMESTAMP` columns as the same type, as for MySQL. Without
`timezone` on the source both read the same and the query is fine. With `timezone`, a date-time
column in the query fails with `HM2045`: read it with `table`, or convert it to a UTC `DATETIME`
in the query, such as `DATETIME(TIMESTAMP(created_at, 'America/New_York'))`, and remove `timezone`.

BigQuery compares text by its bytes, so groups and filters on the copy match BigQuery's own SQL.
A column with a collation, such as `COLLATE 'und:ci'` or a dataset's default collation, compares
case-insensitively, and Hatchmark checks it as it checks a MySQL text column: `HM2046` when the
collation and the bytes disagree on a group, a distinct count or a filter. Columns of a table
are checked only when BigQuery declares a collation for them; every text column of a view or a `query` that
a dashboard groups or filters is checked, which runs one more query job per copy. Remove the
collation in the query to compare by bytes, such as `SELECT COLLATE(region, '') AS region`.

### PostHog

A `posthog` source reads the result of one HogQL query from PostHog Cloud or a self-hosted PostHog
through PostHog's query API. The result is copied like any database source, so metrics, filters and
`max_age` work on it as on a table. [Use PostHog data](/docs/guides/posthog.md) walks through a first
source.

```yaml theme={null}
sources:
  signups:
    type: posthog
    env: POSTHOG_API_KEY
    host: https://eu.posthog.com
    project: 12345
    query: SELECT toDate(timestamp, 'Europe/London') AS day, count() AS signups FROM events WHERE event = 'signed_up' GROUP BY day
```

| Option | Meaning |
| - | - |
| `env` | Required. The variable that holds a personal API key with the Query Read scope. |
| `project` | Required. The project's id, a number, from the project's settings in PostHog. |
| `query` | Required. One HogQL `SELECT` returning fewer than 50,000 rows. Name every column, such as `count() AS signups`. |
| `host` | The PostHog instance: `https://us.posthog.com` (default), `https://eu.posthog.com`, or a self-hosted URL. The `*.i.posthog.com` ingestion hosts don't answer queries. |

`max_age`, `timezone`, `freshness`, `snapshot` and `tests` work as for the other database sources. There is no
`table` or `read` option.

**How it reads.** Hatchmark runs `SELECT * FROM (<query>) LIMIT 0` for the column names and types, then
runs the query itself and copies the rows. `check` validates columns from that first query alone, but
the checks that need rows still run the query: `check --sql`, map region matching, and the distinct
counts of a dashboard with a multi-select filter. Both run without PostHog's result
cache and with timestamps in UTC. PostHog proves a result complete with one row past its limit, so a
result of 50,000 rows or more fails with `HM2051` instead of being cut short. A request goes through
`HTTPS_PROXY` (or `http_proxy` for an `http://` host) and trusts `HATCHMARK_CA_FILE`, as cloud storage does.

**Limits.** PostHog's query API is meant for aggregate queries, and PostHog asks third-party tools not
to use it to export events in bulk. It runs a query for at most 10 seconds, three at once per project,
and counts queries against hourly limits and a budget of bytes read. Aggregate in the query, bound
`timestamp`, and set `max_age`. A rate limit fails with `HM2059`, with the wait PostHog asks for when it sends one.

**Errors.** A refused key, a missing project or an unreachable host fails with `HM2041`, a query PostHog
rejects with `HM2051` and PostHog's message. The key is replaced with `***` in every diagnostic.

| ClickHouse type | Read as | Numbers rule |
| - | - | - |
| `Int8` to `Int64`, `UInt8` to `UInt64` | the same width | Exact, as `count()` and `uniqExact()` return. 64-bit values are sent as text, so no digit is lost. |
| `Decimal(P, S)` with P up to 38 | `DECIMAL(P,S)` | Exact: sent as text, since PostHog's JSON writes decimals as floats. |
| `Float32`, `Float64` | `FLOAT`, `DOUBLE` | Float rules (`HM4004`). NaN and infinity are kept. |
| `DateTime`, `DateTime64` | `TIMESTAMP WITH TIME ZONE` | An instant, whatever zone the column carries. |
| `Date`, `Date32` | `DATE` | A calendar date, as the query computed it. |
| `String`, `UUID`, `Enum`, `IPv4`, `IPv6` | `VARCHAR` | Text, compared by its bytes, as ClickHouse compares it. |
| `Bool` | `BOOLEAN` | |
| `Array`, `Map`, `Tuple` and others | `VARCHAR` | ClickHouse's text form, such as `['a','b']`. |
| `Int128` and wider, `Decimal` with P over 38 | none | `HM2043`: cast it in the query, such as `toDecimal(amount, 2)`. |

Hatchmark asks PostHog to run the query in UTC, so date functions and date literals without a zone use
UTC, not the PostHog project's time zone that PostHog's SQL editor uses. Name the zone, such as
`toDate(timestamp, 'America/New_York')`, or return date-times and let Hatchmark bucket them. Count distinct people with `uniqExact`; `uniq` is an estimate.

### Checking without a connection

`hatchmark check` reads a database source's column names and types, never its rows:

1. When the variable is set, from the database itself. `HM2041` when it cannot connect, `HM2042` when
   the table is missing, `HM2018` for a column the table does not have, `HM2043` for a type a
   metric cannot use.
2. When it is not set, from the newest local copy of the same table or query in `.hatchmark/cache`,
   with note `HM2040` naming when that copy was fetched.
3. With neither, the source's columns are not checked: warning `HM2040` (exit 0 unless `--strict`).
   Everything else in the project is still checked, except the regions of map blocks over that
   source, which need its rows.

With `max_age`, a copy younger than `max_age` stands for the database: `check`, `build` and `dev`
check the columns against the copy they then read, without connecting. `check --sql` and map
region matching read rows, so they need the variable, or a copy younger than `max_age`.

`build` and `dev` need the rows, so a missing variable is an error there, and they must run on a
machine that can connect to the database, such as a host inside the database's network. A hosted
CI runner usually cannot reach a private database, so don't run `build` there for such a source.
A `check` job needs no database access: without the variable it still checks every file and
reference and only warns about the database columns (`HM2040`), so it can run anywhere, such as on
every pull request.


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