# DSL patterns

Worked examples for the questions engineering teams ask most: how layers of tables fit together, how to model dimensions and facts, and how to compute changes, running totals, rankings, gaps and pivots. Copy a pattern and swap in your own tables; the table and column names here are examples.

Each pattern uses transforms and functions documented in [DSL transforms](/docs/dsl/transforms), [DSL functions](/docs/dsl/functions) and [Writing tables](/docs/dsl/output).

## Medallion layering

Solidafy pipelines usually move data through four layers of namespaces, each with one job:

![From raw data to dashboards in four layers. raw holds records exactly as the connector delivered them, written with append. bronze holds one clean, typed row per entity, written with merge_replace. silver holds business facts with people and teams resolved, written with replace. gold holds aggregates that dashboards read directly, written with replace.](/illustrations/medallion.svg)

Partition `raw` by day, and use `merge_sorted` instead of `merge_replace` for `bronze` when the table is large.

Keeping the layers apart means a fix to a metric only touches `silver` or `gold`, and you can rebuild either from the layer below at any time.

**Raw** tables are written by connector steps; see [Connectors](/docs/pipelines/connectors).

**Bronze** reads only what is new, removes duplicate copies, flattens nested fields and fixes types:

```dsl
source("raw.github_pull_requests", audit: "meta.audit_bronze_pull_requests")
  .filter(_extracted_at > @watermark)
  .select([id, number, repo, state, title, user, created_at, merged_at, additions, deletions, _extracted_at])
  .unnest(user)
  .dedupe([id], keep: latest_by(_extracted_at))
  .select([
    id.cast(string) as id,
    number,
    repo,
    state,
    title,
    user_login as author,
    created_at.try_cast(timestamp) as created_at,
    merged_at.try_cast(timestamp) as merged_at,
    additions,
    deletions,
    _extracted_at
  ])
  .output("bronze.pull_requests", mode: merge_replace, keys: [id])
```

Carry `_extracted_at` through every `.select()`: the audit watermark is read from it.

**Silver** joins in the people data and settles the definitions everyone else relies on:

```dsl
source("bronze.pull_requests")
  .filter(state == "merged")
  .join("enrich.developers", left_on: [author], right_on: [github_handle], type: left, prefix: "dev_")
  .add([
    dev_team ?? "Unassigned" as team,
    additions + deletions as lines_changed,
    hours_between(created_at, merged_at) as cycle_hours
  ])
  .select([id, repo, author, team, title, created_at, merged_at, lines_changed, cycle_hours])
  .output("silver.merged_pull_requests", mode: replace)
```

**Gold** shapes the numbers a dashboard shows:

```dsl
source("silver.merged_pull_requests")
  .add([date_trunc("week", merged_at) as week])
  .group_by([week, team])
  .agg([
    count() as merged_prs,
    percentile_cont(cycle_hours, 50) as median_cycle_hours,
    round(avg(lines_changed), 0) as avg_lines_changed
  ])
  .output("gold.team_weekly_delivery", mode: replace)
```

Run the steps in order (raw, bronze, silver, gold) so each layer reads fresh input. [Triggers](/docs/pipelines/triggers-and-webhooks) can chain them for you.

## Dimensional modelling

A dimension describes things (developers, services, repositories); a fact records events (merges, deployments, costs) and points at dimensions by key.

### A dimension with history

Use `mode: scd2` when you want to know what an attribute was at the time of an event, such as which team a developer belonged to:

```dsl
source("enrich.developers")
  .select([github_handle, display_name, email, team, role])
  .output("silver.dim_developers", mode: scd2, keys: [github_handle], track: [team, role])
```

### A fact table

Join facts to the current version of each dimension:

```dsl
devs = source("silver.dim_developers")
  .filter(is_current == true)
  .select([github_handle, team, role])

source("bronze.deployments")
  .select([id, service, environment, status, deployed_by, deployed_at, duration_s])
  .join(devs, left_on: [deployed_by], right_on: [github_handle], type: left)
  .add([date_trunc("day", deployed_at) as deploy_day])
  .select([id, deploy_day, deployed_at, service, environment, status, deployed_by, team, role, duration_s])
  .output("silver.fact_deployments", mode: replace)
```

### An aggregate fact

```dsl
source("silver.fact_deployments")
  .filter(environment == "production")
  .group_by([deploy_day, team])
  .agg([
    count() as deployments,
    sum(if(status == "failed", 1, 0)) as failed,
    round(sum(if(status == "failed", 1, 0)) * 100.0 / count(), 1) as change_failure_pct
  ])
  .output("gold.daily_deployments_by_team", mode: replace)
```

## Day-over-day change

Daily cloud cost per service, with the change from the day before:

```dsl
source("bronze.cloud_costs")
  .since(usage_date, "30d")
  .add([date_trunc("day", usage_date) as day])
  .group_by([day, service])
  .agg([round(sum(cost), 2) as daily_cost])
  .window(partition: [service], order: [day: asc])
  .add([lag(daily_cost, 1) as prev_cost])
  .add([
    round(daily_cost - (prev_cost ?? 0.0), 2) as change,
    case(when: prev_cost > 0 then round((daily_cost - prev_cost) * 100.0 / prev_cost, 1), else: null) as pct_change
  ])
  .sort([day: desc, change: desc])
```

For week-over-week on daily rows, use `lag(daily_cost, 7)`. If you only need the change column, the [diff](/docs/dsl/transforms#diff) and [change](/docs/dsl/transforms#change) shortcuts do it in one step.

### This period against the last

`since` with `previous: true` gives the matching earlier window, so you can compare month-to-date with the same days last month:

```dsl
last_period = source("ai.usage_events")
  .since(ts, "mtd", previous: true)
  .group_by([model])
  .agg([sum(cost_usd) as cost_before])

source("ai.usage_events")
  .since(ts, "mtd")
  .group_by([model])
  .agg([sum(cost_usd) as cost_now])
  .join(last_period, on: model, type: left)
  .add([round(cost_now - (cost_before ?? 0.0), 2) as delta])
  .sort([delta: desc])
```

Because the key has the same name on both sides, the result has a single `model` column. Models used last month but not this month drop out with a `left` join; start from `last_period` instead if those matter to you.

## Running totals

Month-to-date AI spend per team, day by day:

```dsl
source("ai.usage_events")
  .since(ts, "mtd")
  .add([date_trunc("day", ts) as day])
  .group_by([day, team])
  .agg([sum(cost_usd) as daily_cost])
  .window(partition: [team], order: [day: asc])
  .add([sum(daily_cost) as mtd_cost])
  .sort([team: asc, day: asc])
```

The [cumsum](/docs/dsl/transforms#cumsum) shortcut does the same: `.cumsum(daily_cost, order: day, partition: team)` adds `daily_cost_cumsum`.

## Moving averages and spikes

A 7-day moving average smooths out weekends:

```dsl
source("bronze.cloud_costs")
  .add([date_trunc("day", usage_date) as day])
  .group_by([day, service])
  .agg([sum(cost) as daily_cost])
  .window(partition: [service], order: [day: asc])
  .add([rolling_avg(daily_cost, 7) as cost_7d_avg])
```

To flag days that are far from normal, score each day against the ones before it:

```dsl
source("bronze.cloud_costs")
  .add([date_trunc("day", usage_date) as day])
  .group_by([day])
  .agg([sum(cost) as daily_cost])
  .sort([day: asc])
  .anomaly(daily_cost, window: 14, threshold: 3.0)
  .filter(daily_cost_is_anomaly)
```

## Top N per group

The three people with the most merged pull requests in each team over the last 30 days:

```dsl
source("silver.merged_pull_requests")
  .since(merged_at, "30d")
  .group_by([team, author])
  .agg([count() as merged_prs])
  .window(partition: [team], order: [merged_prs: desc])
  .add([row_number() as rn])
  .filter(rn <= 3)
  .sort([team: asc, rn: asc])
```

`row_number()` breaks ties arbitrarily; use `rank()` if tied people should share a place. For a single overall top N, `.top(merged_prs, 10)` is enough.

## Latest row per entity

The most recent deployment of every service:

```dsl
source("silver.fact_deployments")
  .filter(environment == "production")
  .dedupe([service], keep: latest_by(deployed_at))
  .select([service, deployed_at, status, deployed_by])
```

## Gap detection

Long gaps between production deployments of the same service:

```dsl
source("silver.fact_deployments")
  .filter(environment == "production")
  .window(partition: [service], order: [deployed_at: asc])
  .add([lag(deployed_at, 1) as prev_deploy])
  .add([hours_between(prev_deploy, deployed_at) as gap_hours])
  .filter(gap_hours > 72)
  .sort([gap_hours: desc])
```

Services that have not deployed at all for a week:

```dsl
source("silver.fact_deployments")
  .filter(environment == "production")
  .group_by([service])
  .agg([max(deployed_at) as last_deploy])
  .before(last_deploy, "7d")
```

## Pivots

Monthly cost with one column per cloud provider:

```dsl
source("bronze.cloud_costs")
  .since(usage_date, "last_6_months")
  .add([strftime("%Y-%m", usage_date) as month])
  .group_by([month, provider])
  .agg([round(sum(cost), 2) as cost])
  .pivot(index: [month], columns: provider, values: cost, agg: sum, fill_null: 0)
  .sort([month: asc])
```

The new columns are named after the provider values, for example `aws`, `gcp` and `azure`. To go the other way, from columns to rows, use [unpivot](/docs/dsl/transforms#unpivot).

When you need several measures per pivot value, aggregate them conditionally instead:

```dsl
source("ai.usage_events")
  .since(ts, "30d")
  .group_by([team])
  .agg([
    sum(if(model_family == "claude", cost_usd, 0.0)) as claude_cost,
    sum(if(model_family == "gpt", cost_usd, 0.0)) as gpt_cost,
    sum(if(model_family == "claude", input_tokens + output_tokens, 0)) as claude_tokens
  ])
```

## Distributions

How long pull requests take to merge, bucketed for a bar chart:

```dsl
source("silver.merged_pull_requests")
  .since(merged_at, "90d")
  .histogram(cycle_hours, [4, 24, 72, 168])
```

And the percentiles behind it:

```dsl
source("silver.merged_pull_requests")
  .since(merged_at, "90d")
  .agg([
    percentile_cont(cycle_hours, 50) as p50,
    percentile_cont(cycle_hours, 90) as p90,
    max(cycle_hours) as worst
  ])
```
