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

# Project file (hatchmark.yaml)

> Configure hatchmark.yaml at the project root: directories, the locale, currency and time zone for numbers and dates, data sources, and a minimal start.

`hatchmark.yaml` sits at the project root and holds the settings and the data sources. Every field
except `$schema` is required, so a reader sees what will happen without knowing defaults;
`hatchmark check` reports a missing field with a fix that adds the default. Print the full JSON
Schema with `hatchmark schema project`.

```yaml theme={null}
# yaml-language-server: $schema=./node_modules/hatchmark/schema/project.schema.json
version: 1
name: Global Sales
dataDir: data
metricsDir: metrics
dashboardsDir: dashboards
outDir: dist
locale: en-US
currency: USD
timezone: America/New_York
anchors:
  week: sunday
theme: default
telemetry: false
sources:
  orders:
    type: csv
    path: data/orders.csv
```

| Field | Meaning |
| - | - |
| `version` | Spec format version. Always `1`. |
| `name` | Project name, shown at the top of every page. |
| `dataDir` | Where data files live by convention (`data`). Source paths still name the full path. |
| `metricsDir` | Directory of `<name>.yaml` metric files. See [Metrics](/docs/reference/metrics.md). |
| `dashboardsDir` | Directory of `<name>.yaml` dashboard files. See [Dashboards](/docs/reference/dashboards.md). |
| `outDir` | Where `hatchmark build` writes the site. See [Build](/docs/guides/build.md). |
| `locale` | BCP 47 tag for numbers and dates, such as `en-US` or `de-DE`. See [Locale](#locale). |
| `currency` | ISO 4217 code used by currency metrics that do not set their own, such as `USD`. |
| `timezone` | IANA time zone that dates are bucketed in, such as `UTC` or `America/New_York`. |
| `anchors` | Optional. `week`: any weekday (default `monday`); `quarter`, `year`: `MM-DD` starts. |
| `theme` | `default`. |
| `telemetry` | `false`. Hatchmark sends nothing unless this is `true`. |
| `sources` | Tables by name. Metrics refer to these names in their `table` field. |

## Locale

`locale` sets how numbers, dates and times look on every page of the project. It is fixed per
project: every viewer sees the same formatting, whatever their browser's language, so a dashboard
for a German team reads `1.234,5` for everyone, and a screenshot or a link looks the same to
everyone who opens it.

What the locale formats:

* Numbers: decimal and thousands separators, percent spacing (`12,5 %` in de-DE and fr-FR), the
  minus sign, and compact units such as K, Mio., k, mil, 万 or 천. A compact value is rounded only
  when it shows a unit; see [Metrics](/docs/reference/metrics.md).
* Currency: the symbol's position and spacing (`92,51 $` in de-DE, `US$92.51` in en-GB). The
  currency itself comes from `currency` or the metric's format, and amounts are never converted.
* Dates and times: month names, date ranges (`25.–31. Okt. 2026` in de-DE), axis labels, tooltips,
  "Data through" and partial-period labels, and 12- or 24-hour times.
* The date range picker: its calendar's month and weekday names and the numeric dates in its
  custom-range fields.
* The order of text in a table sorted by a column, both when the page is built and when a viewer
  clicks a header.

What it doesn't change:

* The interface text stays English: labels such as Total, Other, "Showing 9 of 21 rows", the
  partial-period notes and the picker's presets.
* The first day of the week comes from `anchors.week`, not from the locale. `hatchmark init` writes
  the one that fits the locale it writes (`sunday` for en-US); change it to suit your team.
  `weekStart` is the older spelling of `anchors.week`.
* Dates are bucketed in `timezone`, and amounts are in `currency` or the metric's own currency.
* Dates use the Gregorian calendar, even for a locale whose default calendar is another one: a
  `th-TH` project shows 2026, not 2569.
* A table's CSV download uses the same syntax in every locale: comma-separated, with `.` as the
  decimal point and full-precision values, so other tools read it as numbers. Its rows follow the
  order the table shows. A spreadsheet app set to a locale that uses `;` as its list separator, such
  as German Excel, may put each row in one column when you double-click the file; open it through
  the app's text or CSV import and choose comma as the delimiter.

## Sources

A source is one file, or one database table or query (see [Database sources](#database-sources)), read as a table. Its name (the key under `sources`) is lowercase snake\_case,
such as `orders` or `web_sessions`.

**`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 and no `..`.

| `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/guides/numbers.md#time) says how horizons decide `latest_data`.

Column types are inferred from every row of the file (see [Numbers](/docs/guides/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/guides/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).

```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 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.

```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. AWS, Google and Azure variables or credential
files it finds on the machine (such as `AWS_ACCESS_KEY_ID`, `AWS_SESSION_TOKEN` or
`AZURE_STORAGE_CONNECTION_STRING`) are never 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.

Requests reach only the configured endpoint: for S3 and GCS the `endpoint` (and the bucket's
virtual host under it), for Azure the connection string's `BlobEndpoint` or its account's blob host.
Each command sends them through a proxy that Hatchmark runs on `127.0.0.1`, which forwards to that
host and port only. A redirect to another host fails with `HM2015` and names the host. A
virtual-host URL names the bucket in its host, so a redirect to another bucket fails the same way.
With path-style URLs over plain HTTP (`use_ssl: false`) the proxy checks the bucket in the path
and refuses an encoded `/` or `\` in it;
over HTTPS the path is encrypted, so the proxy checks only the host and port. Proxy variables in the environment (`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`, `NO_PROXY` and their
lower-case forms) are ignored for cloud storage sources.

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)). 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`, matched exactly as written. Without a schema: the first schema on the connection's search path that has it in PostgreSQL, the connection's database in MySQL. |
| `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 shell, or as a secret in CI. 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/guides/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.

### 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"` | `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 every `sql` metric on the source, whatever its SQL reads. Cast it in `query`, such as `code::text`. |
| `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`.

### 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. In CI, set the variable
as a secret where `build` runs; a `check` job without database access still checks every file and
reference and only warns about the database columns.

## Starting from `init --template minimal`

`hatchmark init --template minimal` writes `hatchmark.yaml` with `sources: {}` and empty
`data/`, `metrics/` and `dashboards/` directories. To get to a first page:

1. Put the data file under `data/`, for example `data/orders.csv`.
2. Add it to `sources` in `hatchmark.yaml`: `orders: { type: csv, path: data/orders.csv }`.
3. Write one metric per file under `metrics/`, such as `metrics/revenue.yaml`. See
   [Metrics](/docs/reference/metrics.md).
4. Write a dashboard under `dashboards/`, such as `dashboards/sales.yaml`. See
   [Dashboards](/docs/reference/dashboards.md).
5. Run `hatchmark check --json` and fix every error, then `hatchmark build`.

`hatchmark init` without `--template minimal` writes a complete sample project (US orders data,
metrics and a dashboard) to copy from instead.


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