# Writing tables

How a DSL query writes its result to a table with `.output()`, how to choose a write mode, and the related tools for incremental reads, data quality, history tables, time rollups, table maintenance, semantic search and machine learning. This page is for anyone building pipelines; for the query language itself start with the [DSL overview](/docs/dsl/overview).

## .output

```dsl
.output("namespace.table", mode: mode, keys: [...], order: col, track: [...], partition_by: [...])
```

`.output()` ends a chain and writes its rows to the named table, creating the table if needed. Only `mode:` and the options that mode needs are required; the default mode is `append`.

```dsl
source("raw.github_pull_requests")
  .dedupe([id], keep: latest_by(_extracted_at))
  .select([id, repo, state, user.login as author, created_at, merged_at, _extracted_at])
  .output("bronze.pull_requests", mode: merge_replace, keys: [id])
```

In a pipeline, a transform step's DSL ends in `.output()`. From the CLI, run it with `solidafy dsl -x`. See [Pipelines](/docs/pipelines/overview) and [CLI commands](/docs/cli/commands).

### System columns

Every write adds two columns, replacing any values your query carries for them:

| Column | Value |
| --- | --- |
| `_extracted_at` | the time of this write (UTC) |
| `_row_hash` | a hash of the row, used by `upsert` and `scd2` to spot changes |

`mode: scd2` also manages `is_current`, `valid_from` and `valid_to`, and these names are reserved in every mode: a column with one of them is dropped on write. Do not use any of the five as `keys`; for `merge_sorted` doing so is rejected outright.

## Write modes

| Mode | What it does | Needs |
| --- | --- | --- |
| `append` | Adds the rows to the table. | nothing |
| `replace` | Swaps the whole table for the result. An empty result leaves the old table in place. | nothing |
| `replace_partition` | Rewrites only the partitions present in the result. Without `partition_by` it behaves like `replace`. | `partition_by` |
| `upsert` | Inserts rows with new keys, updates rows whose key exists and whose content changed, and skips unchanged rows. | `keys` |
| `merge_replace` | Reads the whole existing table, adds the new rows, keeps one row per key (the new one wins) and writes the table back. | `keys` |
| `merge_sorted` | The same result as `merge_replace`, but merges on disk instead of in memory, so it suits large tables. With `order:` the row with the greatest `order` value wins instead of the newest. | `keys`, optional `order` |
| `scd2` | Keeps history: a changed row closes the current version and adds a new one. See [SCD2 history](#scd2-history). | `keys`, `track` |
| `compact` | Merges the result with the existing rows and rewrites them as one file per partition (or one table, without `partition_by`). | nothing |

### Choosing a mode

- **Raw data from a connector:** `append`, partitioned by day. Raw tables only grow; you remove duplicates in the next layer.
- **One clean row per entity** (a pull request, a deployment, an invoice line): `merge_replace` with the entity's ID as `keys`. Switch to `merge_sorted` once the table is large, since `merge_replace` holds the whole table in memory.
- **A table you fully recompute each run** (team metrics, a dashboard table): `replace`.
- **One row per day per entity that can still change** (daily cost per service): `merge_replace` with `keys: [day, service]`.
- **Attribute history** (which team a developer was on, and when): `scd2`.

`merge_sorted` cannot be combined with an incremental connector cursor or an `audit:` source in the same query; use `merge_replace` there. `replace` and `replace_partition` are rejected when the source reads incrementally from a connector cursor, because each run only sees the new slice and would wipe the history.

## Options

| Option | Meaning |
| --- | --- |
| `mode:` | One of the modes above. Defaults to `append`. |
| `keys: [col, ...]` | Columns that identify a row, for `upsert`, `merge_replace`, `merge_sorted` and `scd2`. |
| `order: col` | For `merge_sorted`: within a key, the row with the greatest value wins. |
| `track: [col, ...]` | For `scd2`: the columns whose changes start a new version. |
| `partition_by: [...]` | How the table's files are split. A column (`partition_by: [region]`) or a time column cut to `hour`, `day`, `month` or `year` (`partition_by: [_extracted_at.truncate(day)]`). Partitioning lets reads with a matching filter skip files. |
| `policy: {pii: [col with: pseudonymize, ...]}` | Declares personal-data columns. Readers without access to personal data see these columns pseudonymized. List all of the table's personal-data columns every time; the list replaces the previous one. See [Security](/docs/access/security). |
| `distribute: {by: [col, ...], segments: n}` | Runs the query in `n` smaller pieces, one after another, to keep memory down on large writes. See [Writing in segments](#writing-in-segments). |
| `catalog_url: "..."`, `api_key: "..."` | Writes to another environment's catalog instead of your own. Give both; with only one of them the write goes to your own environment. See [Reading from another environment](/docs/dsl/overview#reading-from-another-environment) for what the values are. |

```dsl
source("bronze.cloud_costs")
  .since(usage_date, "last_3_months")
  .add([date_trunc("day", usage_date) as day, strftime("%Y-%m", usage_date) as month])
  .group_by([month, day, provider, service])
  .agg([sum(cost) as cost])
  .output("silver.daily_costs", mode: replace_partition, partition_by: [month])
```

This recomputes the last three months and rewrites only the monthly partitions those rows fall in, leaving older months untouched.

### Writing in segments

A large `.dedupe()` or `.group_by()` holds its whole input in memory. `distribute:` splits the work instead: the rows are spread over `segments` buckets by a hash of the `by` columns, and the query runs once per bucket, one after another, so only about one bucket's worth of rows is in memory at a time.

```dsl
source("raw.github_events")
  .dedupe([id], keep: latest_by(_extracted_at))
  .output("bronze.github_events", mode: replace, distribute: {by: [id], segments: 8})
```

Every bucket has to produce final rows on its own, so the rules are strict and checked before the query runs:

- Only `mode: replace` and `mode: append` are allowed.
- `by:` is required, and its columns must be part of every `.dedupe()` key and every `.group_by()` key in the chain. Each key's rows then land in one bucket.
- `.group_by()` keys must be plain columns, not expressions.
- A chain with a `.join()` is rejected.
- `segments:` must be above 0. It defaults to `auto`, which picks the number for you.
- `method: hash` is the only accepted method.

The `by` columns must exist in the source table itself; a column you create in a step such as `.add()` fails when the query runs.

With `replace`, a run that produces no rows leaves the old table in place. While a `replace` run is in progress, a reader can briefly see the old rows plus the buckets already written; the table switches to only the new rows at the end of the run.

## Incremental reads with audit

To process only rows that arrived since the last successful run, give the source an `audit:` table and filter on `@watermark`:

```dsl
source("raw.github_pull_requests", audit: "meta.audit_bronze_pull_requests")
  .filter(_extracted_at > @watermark)
  .dedupe([id], keep: latest_by(_extracted_at))
  .select([id, repo, state, user.login as author, created_at, merged_at, _extracted_at])
  .output("bronze.pull_requests", mode: merge_replace, keys: [id])
```

How it works:

- `@watermark` is the largest `_extracted_at` the previous successful run wrote. On the first run it is `1970-01-01T00:00:00Z`, so everything passes.
- After a successful `.output()`, the largest `_extracted_at` among the rows this run produced is recorded in the audit table and becomes the next watermark. Keep `_extracted_at` in every `.select()`, or the watermark cannot move.
- `audit: true` keeps the bookkeeping in the output table itself instead of a separate one.
- `audit:` only takes effect when the query ends in `.output()`.

A watermark is safer than a time window such as `.since(_extracted_at, "1d")`: if a run is skipped or fails, the next run still picks up everything it missed.

## Data quality

### validate

`.validate([check(condition, severity: level, name: "label"), ...])`

Each check is a condition every row should meet. Rows that fail a check with `severity: error` are dropped from the result before it is written. Checks with `severity: warn` or `severity: info` are accepted but have no effect. Without `name:`, a check is labelled by its position.

```dsl
source("raw.deployments")
  .dedupe([id], keep: latest_by(_extracted_at))
  .validate([
    check(id is not null, severity: error, name: "id_required"),
    check(service is not null, severity: error, name: "service_required"),
    check(status in ["success", "failed", "rolled_back"], severity: error, name: "known_status")
  ])
  .output("bronze.deployments", mode: merge_replace, keys: [id])
```

### Keeping the rejected rows

`.on_error(quarantine: "ns.table")` placed before `.validate()` collects the failing rows with a `_validation_errors` column naming the failed checks, but only for the duration of the query; it does not write them to a table in your catalog. `.route(errors: ..., warnings: ...)` is accepted and does nothing.

To keep rejected rows, write them from their own step with the opposite condition:

```dsl
source("raw.deployments")
  .filter(id is null or service is null or status not in ["success", "failed", "rolled_back"])
  .output("quarantine.deployments", mode: append)
```

## SCD2 history

`mode: scd2` keeps every version of a row. Rows are matched on `keys`; when any `track` column differs from the current version, the current version is closed and a new one is added.

```dsl
source("raw.hr_developers")
  .dedupe([employee_id], keep: latest_by(_extracted_at))
  .select([employee_id, email, display_name, team, manager, _extracted_at])
  .output("silver.dim_developers", mode: scd2, keys: [employee_id], track: [team, manager])
```

The table gets three extra columns:

| Column | Meaning |
| --- | --- |
| `is_current` | true for the version in effect now |
| `valid_from` | when this version was written |
| `valid_to` | when it was replaced; empty for the current version |

Read the current state with `.filter(is_current == true)`. To see which team someone was on when they merged a pull request, join on the key and keep the version whose `valid_from` and `valid_to` surround the merge time.

The `.scd2()` transform only adds similarly named columns to the rows in hand and does not compare with the stored table, so use the output mode for real history.

## Change data capture

For change records that carry an operation code and `before`/`after` images, [cdc](/docs/dsl/transforms#cdc) drops deletes and turns `after` into columns. Combine it with `merge_replace` to keep a current copy:

```dsl
source("raw.orders_changes")
  .cdc(operation: op, before: before, after: after)
  .output("bronze.orders", mode: merge_replace, keys: [id])
```

Deletes are always dropped, so rows deleted at the source stay in the copy.

## Time rollups

`.rollup()` ends a chain like `.output()`, but writes one pre-aggregated table per time granularity: hourly, daily, monthly and yearly totals from a single query.

```dsl
source("bronze.pos_events")
  .group_by([store_id, product_category])
  .agg([sum(amount) as total_amount, count() as txn_count])
  .rollup("silver.pos_events",
    time_column: event_time,
    levels: [
      hourly: [store_id, product_category],
      daily: [store_id, product_category],
      monthly: [store_id]
    ]
  )
```

This writes `silver.pos_events_hourly`, `silver.pos_events_daily` and `silver.pos_events_monthly`. Each table has a time bucket column named after `time_column` (`event_time_hour`, `event_time_date`, `event_time_month`, or `event_time_year` for a `yearly` level), the dimensions listed for that level, and the measures from `.agg()`.

How it works:

- `levels:` needs at least two of `hourly`, `daily`, `monthly` and `yearly`, each at most once, from finest to coarsest. Each level lists the dimension columns it keeps; these replace the `.group_by()` keys.
- The finest level aggregates the source rows. Each coarser level re-aggregates the table of the level below it, so its dimensions should be ones that level kept.
- Measures can only use `sum`, `count`, `min` and `max`, because those can be combined again at the next level (a sum of hourly counts is the daily count). `avg` and `count_distinct` are rejected; for an average, store `sum` and `count` and divide when you read.
- Steps before `.group_by()` and `.agg()` filter and shape the source rows. Steps after `.agg()` are not applied.
- Each table is partitioned by its time bucket. A run replaces the buckets its rows fall in, matched on the bucket and the level's dimensions, and leaves other buckets alone. So a pipeline that reads only recent data updates only the recent hours, and the coarser levels are rebuilt from the level below.
- `mode:` is accepted but has no effect; every level is written as described above.

`.rollup()` writes, so run it with `solidafy dsl -x`.

## Table maintenance

Frequent small writes leave many small files and old snapshots behind. Three commands tidy them up. Each is a statement of its own rather than a chain, only one runs per query, and they write, so run them with `solidafy dsl -x`.

A command on a table that does not exist succeeds and reports no work, dry runs included, so a maintenance step can sit next to a write that has not produced any rows yet. The same goes for a misspelled table name: it also succeeds with nothing done, so check the name if a command never seems to do anything. Any other catalog error still fails the command.

### compact

```dsl
compact("raw.github_events")
compact("bronze.cloud_costs", partition: provider == "aws", target_size: 128, min_files: 4, dry_run: true)
```

Merges small files within each partition into larger ones.

| Option | Default | Meaning |
| --- | --- | --- |
| `partition:` | all partitions | Which partitions to compact, as a condition on the table's partition columns. Same operators as a source `partition:` filter, combined with `AND`. |
| `target_size:` | `256` | Target file size in MB. |
| `min_files:` | `2` | Skip partitions with fewer files than this. |
| `dry_run:` | `false` | Report what would be compacted without writing. |

### clean

```dsl
clean("raw.github_events", keep: 3)
clean("raw.github_events", keep: 1, dry_run: true)
```

Moves the files that only old snapshots still use into a trash area. `keep:` is how many recent snapshots to keep (default and minimum 1). Each run handles up to 500 old snapshots, so a table with a long history may need several runs.

### purge

```dsl
purge("raw.github_events")
```

Permanently deletes the files `clean` moved to the trash. Until you purge, they stay in the trash area and still take up storage.

## Semantic search

Solidafy can turn text into embedding vectors (lists of numbers that place similar meanings close together) and search by meaning instead of exact words.

The pattern is to embed once, when you write the table, and search many times:

```dsl
// Pipeline step: embed while writing
source("bronze.jira_issues")
  .select([key, summary, description, status, _extracted_at])
  .embed([summary, description], as: issue_embedding)
  .output("silver.jira_issues", mode: replace)
```

```dsl
// Query: search by meaning
source("silver.jira_issues")
  .filter(status != "Done")
  .find_similar("checkout payment times out", column: issue_embedding, top: 10, threshold: 0.3)
  .select([key, summary, _similarity])
```

`.embed()` joins the listed text columns and stores a vector of 384 numbers per row. `.find_similar()` embeds only the search text when the query runs and adds `_similarity` (higher is closer). It also accepts a plain text column, but then every row is embedded at query time, which is slow on large tables.

`.correlate()` matches rows across two embedded tables, for example incidents to the tickets that describe them:

```dsl
source("silver.incidents")
  .correlate("silver.jira_issues", left: incident_embedding, right: issue_embedding, top: 3, threshold: 0.5)
  .select([incident_id, title, right_key, right_summary, _similarity])
```

See [find_similar](/docs/dsl/transforms#find_similar), [correlate](/docs/dsl/transforms#correlate) and [embed](/docs/dsl/transforms#embed) for every option.

## Machine learning

Solidafy can fit simple prediction models on your tables and use them in later queries. Train with `.train()`, then add predictions to any rows with the [score](/docs/dsl/transforms#score) transform.

### train

```dsl
.train(algo: algorithm, target: col, features: [col, ...], name: "model")
```

`.train()` ends a chain. It fits a model on the query's rows, stores it under `name`, and returns one summary row. Training the same name again adds a new version, and `.score()` always uses the latest one.

| Option | Meaning |
| --- | --- |
| `algo:` | `linear_regression` to predict a number, or `logistic_regression` to predict a yes/no outcome. Any other name fails when the query runs. |
| `target:` | The column to predict. For `logistic_regression`, any value other than 0 counts as yes. |
| `features: [col, ...]` | The columns the model learns from. |
| `name:` | The model's name, which `.score()` refers to. |

The target and feature columns must be numbers with no nulls; filter them out or use [fill_null](/docs/dsl/transforms#fill_null) first, or the run fails and names the column.

The summary row has `name`, `version` and `rows`, plus `accuracy` for a logistic model or `r2` and `rmse` for a linear one. These are measured on the same rows the model was trained on. Every version is also recorded in the `models.registry` table.

`.train()` writes, so run it with `solidafy dsl -x`:

```dsl
source("features.customers")
  .filter(recency is not null and spend is not null)
  .train(algo: logistic_regression, target: churned, features: [recency, spend], name: "churn_risk")
```

```dsl
// Later, in any query
source("features.customers")
  .score("churn_risk", as: churn_prob)
  .filter(churn_prob > 0.7)
```
