> For the complete documentation index, see [llms.txt](https://docs.slingdata.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.slingdata.io/concepts/build/models.md). Agents can also search and read this documentation through its [MCP server](https://docs.slingdata.io/~gitbook/mcp).

# Models

SQL model files, config declaration, materialization modes, template functions, macros, seeds, hooks, and data tests.

A model is a `.sql` file with a SELECT query that defines a table or view in the target database. Models can use Jinja templating for dynamic SQL, reference other models for dependency resolution, and declare configuration with front-matter or a config block.

## Config Declaration

There are two ways to declare model configuration. If both are present, YAML front-matter takes priority and the `config()` block becomes a no-op.

### YAML Front-Matter (Recommended)

Sling reads front-matter from the leading comment of a model file. Any standard SQL comment style is accepted, so the file stays valid for editors and linters.

**Quick guide:**

* **A few keys?** Use `-- { ... }` on a single line — it stays out of the way.
* **More config (hooks, ranges, tests, multi-line lists)?** Use `/* { ... } */` or `/** ... **/` for a proper block.

#### `-- { ... }` line comment (best for short config)

Inline `{ ... }` flow object — good when you need only a key or two:

```sql
-- {schema: marts}
SELECT id, name FROM raw_customers
```

```sql
-- {mode: incremental, unique_key: id, update_key: updated_at}
SELECT id, name, updated_at FROM raw_customers WHERE {{ incremental_where_cond() }}
```

You can also span multiple `--` lines, as long as the joined body forms a `{ ... }` object:

```sql
-- {
--   mode: incremental,
--   unique_key: id,
--   update_key: updated_at
-- }
SELECT id, name, updated_at FROM raw_customers WHERE {{ incremental_where_cond() }}
```

#### `/* { ... } */` block comment (best for richer config)

Use a regular block comment with a `{ ... }` body when you have hooks, ranges, or anything that is easier in multi-line YAML:

```sql
/* {
  mode: incremental,
  unique_key: id,
  update_key: updated_at,
  hooks: {
    start: [{type: log, message: "starting"}],
    end:   [{type: log, message: "done"}]
  }
} */
SELECT id, name, updated_at FROM raw_customers WHERE {{ incremental_where_cond() }}
```

JSON syntax also works in `/* ... */`:

```sql
/* {"mode": "view", "schema": "marts"} */
SELECT * FROM {{ ref('stg_customers') }}
```

#### `/** ... **/` doc-block (plain YAML, no braces required)

A doc-block lets you write plain YAML, with bare keys, and no `{ }` around it. Use this when you prefer block YAML over flow syntax:

```sql
/**
mode: incremental
unique_key: id
merge_strategy: delete+insert
update_key: updated_at
tags:
  - daily
  - finance
tests:
  - not_null: [id, updated_at]
  - unique: id
hooks:
  start:
    - type: query
      connection: '{target.name}'
      query: "REFRESH MATERIALIZED VIEW upstream_mv"
  end:
    - type: log
      message: "Model build complete"
**/

SELECT id, name, updated_at
FROM {{ ref('stg_customers') }}
WHERE {{ incremental_where_cond() }}
```

{% hint style="info" %}
**Why the `{ ... }` requirement for the `--` and `/* */` styles?** It separates config from a regular comment. A line like `-- Pre-statement: build temp table` would otherwise look like YAML and be read as front-matter. The `/** ... **/` doc-block style is unambiguous and accepts any YAML, including bare keys.
{% endhint %}

### Jinja Config Block (dbt Compatibility)

Use `{%- config(...) -%}` for a syntax that dbt users know. Sling applies it only when the file has no YAML front-matter.

```sql
{%- config(mode='incremental', unique_key='id', update_key='updated_at') -%}

SELECT id, name, updated_at
FROM {{ ref('stg_customers') }}
{% if is_incremental() %}
WHERE updated_at > (SELECT MAX(updated_at) FROM {{ this }})
{% endif %}
```

{% hint style="warning" %}
The `config()` block accepts a **subset** of the keys. You cannot set `range`, `hooks`, or `tests` in `config()` — use YAML front-matter for those. Unknown keys give a warning and are ignored. A `schema` set in `config()` also does not change the resolved table name, because Sling computes the table name before it renders the template. Use front-matter `schema:` instead.
{% endhint %}

### Config Priority

1. YAML front-matter (`/** ... **/`, `-- {...}`, or `/* {...} */`)
2. Jinja `config()` block (ignored if front-matter exists)
3. `sling_build.yml` `defaults` section
4. Built-in default: `full-refresh`

`tags` and `hooks` are additive: model values are added to the `defaults` values instead of replacing them.

`settings` merges key by key. The `table` and `query` maps of `defaults`, front-matter and `config()` merge into one map for each model. The model value wins for a key that appears in more than one place.

## Config Options

| Option           | Type           | Default                      | Description                                                                                                                                                                                                                        |
| ---------------- | -------------- | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `mode`           | string         | `full-refresh`               | Materialization mode. See [Modes](#materialization-modes)                                                                                                                                                                          |
| `materialized`   | string         |                              | dbt alias for `mode`. Accepts `table`, `view`, `incremental`. An explicit `mode` wins                                                                                                                                              |
| `unique_key`     | string or list |                              | Primary key column(s) for incremental merge. Also the ClickHouse `ORDER BY`                                                                                                                                                        |
| `merge_strategy` | string         | `delete+insert`              | Merge strategy: `delete+insert`, `update+insert`, `insert`                                                                                                                                                                         |
| `update_key`     | string         |                              | Watermark column. Required for `mode: incremental`                                                                                                                                                                                 |
| `tags`           | list           | `[]`                         | Tags for [selector](https://docs.slingdata.io/concepts/build/structure.md#selectors) filtering                                                                                                                                     |
| `hooks`          | object         |                              | Start/end [hooks](https://docs.slingdata.io/concepts/hooks.md) to run before and after the model. See [Hooks](#hooks)                                                                                                              |
| `tests`          | list           | `[]`                         | Declarative data tests. See [Data Tests](#data-tests)                                                                                                                                                                              |
| `schema`         | string         | (from folder)                | Override the schema derived from the folder structure                                                                                                                                                                              |
| `database`       | string         |                              | Override the database. Three-part dialects only. See [Database](https://docs.slingdata.io/concepts/build/structure.md#database-three-part-names)                                                                                   |
| `enabled`        | bool           | `true`                       | Set to `false` to remove this model from the DAG                                                                                                                                                                                   |
| `engine`         | string         | `MergeTree()`                | ClickHouse `ENGINE` clause override. Also a `defaults` key                                                                                                                                                                         |
| `order_by`       | string         | `unique_key`, else `tuple()` | ClickHouse `ORDER BY` expression. Also a `defaults` key. See [ClickHouse table and query settings](#clickhouse-table-and-query-settings)                                                                                           |
| `partition_by`   | string or list |                              | `PARTITION BY` expression. ClickHouse, BigQuery and Databricks. A list renders joined with `,` . Also a `defaults` key. See [Table options, layout and session settings](#table-options-layout-and-session-settings-other-engines) |
| `primary_key`    | string         |                              | ClickHouse `PRIMARY KEY` expression. Needs `order_by` or `unique_key`. Also a `defaults` key                                                                                                                                       |
| `ttl`            | string         |                              | ClickHouse `TTL` expression. Also a `defaults` key                                                                                                                                                                                 |
| `settings.table` | object         |                              | Table settings or table options. ClickHouse: the `SETTINGS` clause. Other engines: the options clause of the `CREATE TABLE` (for example `WITH (...)`, `OPTIONS (...)`, `TBLPROPERTIES (...)`). Also a `defaults` key              |
| `settings.query` | object         |                              | Query or session settings. Sling sends them with the statements of the model. Not BigQuery or Athena. Also a `defaults` key                                                                                                        |
| `cluster_by`     | string or list |                              | `CLUSTER BY` expression. Snowflake, BigQuery and Databricks. Also a `defaults` key                                                                                                                                                 |
| `transient`      | bool           | `false`                      | Snowflake `TRANSIENT` table. Also a `defaults` key                                                                                                                                                                                 |
| `unlogged`       | bool           | `false`                      | Postgres `UNLOGGED` table. Also a `defaults` key                                                                                                                                                                                   |
| `dist`           | string         |                              | Redshift distribution: `even`, `all`, `auto`, or a column name. Also a `defaults` key                                                                                                                                              |
| `sort`           | string or list |                              | Redshift `COMPOUND SORTKEY` columns. Also a `defaults` key                                                                                                                                                                         |
| `range`          | object         |                              | Range block for incremental models: `start` / `advance` / `lookback`. See [Incremental](https://docs.slingdata.io/concepts/build/incremental.md)                                                                                   |
| `drop_cascade`   | bool           | `false`                      | Add `CASCADE` to `DROP TABLE` / `DROP VIEW` when the dialect supports it                                                                                                                                                           |
| `rewrite`        | bool           | `true`                       | Set `false` to skip bare-name table rewriting. `ref()`, `src()`, and `@name` still resolve                                                                                                                                         |

{% hint style="warning" %}
`pre_hook` and `post_hook` are not supported. Sling gives an error if it finds them. Use `hooks.start` and `hooks.end` instead.
{% endhint %}

## Materialization Modes

Each model has a materialization mode that sets how Sling writes its SQL output to the target database.

| Mode           | Description                                                           |
| -------------- | --------------------------------------------------------------------- |
| `full-refresh` | Default. Replaces the table with `CREATE TABLE AS SELECT`             |
| `truncate`     | Truncates the table and re-inserts. Keeps DDL, GRANTs, and indexes    |
| `incremental`  | Merges new and updated rows through a temp table and a merge strategy |
| `append`       | Appends the full result set with `INSERT INTO`. No deduplication      |
| `view`         | Creates or replaces a SQL view instead of a table                     |

Sling also accepts these aliases:

| Alias       | Resolves to    | Note                                                  |
| ----------- | -------------- | ----------------------------------------------------- |
| `table`     | `full-refresh` | dbt compatibility                                     |
| `snapshot`  | `append`       | Deprecated. Gives a warning                           |
| `ephemeral` |                | Not supported. Gives an error — use `view` or `table` |

{% hint style="warning" %}
`snapshot` is deprecated and means append-only insert. Use `append`. A future release will make `snapshot` mean SCD2.
{% endhint %}

Sling validates the mode at project load, before it runs anything. An unrecognized mode gives an error that lists the valid values:

> model '\<name>': unknown mode 'incremenal'; expected one of: append, full-refresh, incremental, truncate, view

The same check applies to `defaults.mode` in `sling_build.yml`:

> \<path>/sling\_build.yml: unknown defaults.mode 'bogus'; expected one of: append, full-refresh, incremental, truncate, view

### full-refresh

The default mode. Replaces the table on every run.

| Run        | SQL Behavior                                             |
| ---------- | -------------------------------------------------------- |
| First      | `CREATE TABLE {table} AS ({sql})`                        |
| Subsequent | `DROP TABLE {table}` → `CREATE TABLE {table} AS ({sql})` |

**When to use**: Dimension tables, lookup tables, and small tables where a full reload is fast.

```sql
/**
mode: full-refresh
**/

SELECT id, name, category
FROM {{ ref('stg_products') }}
```

If a view of the same name exists, Sling drops it first.

### truncate

Similar to `full-refresh`, but keeps the existing table structure: columns, constraints, permissions, and indexes.

| Run        | SQL Behavior                                                |
| ---------- | ----------------------------------------------------------- |
| First      | `CREATE TABLE {table} AS ({sql})`                           |
| Subsequent | `TRUNCATE TABLE {table}` → `INSERT INTO {table} SELECT ...` |

**When to use**: When you must keep GRANTs, indexes, or other DDL applied to the table.

### incremental

Merges new and updated rows into the target table. Needs a `unique_key` and an `update_key`.

| Run        | SQL Behavior                                                           |
| ---------- | ---------------------------------------------------------------------- |
| First      | Falls back to `full-refresh` (creates the table)                       |
| Subsequent | Load into a temp table → merge into the target with the merge strategy |

Sling supports two styles of incremental models: **dbt-compatible** (`is_incremental()` + `{{ this }}`) and **sling-native** (`{{ incremental_where_cond() }}` + optional `range:` front-matter). See [Incremental](https://docs.slingdata.io/concepts/build/incremental.md) for the full comparison.

#### Merge Strategies

| Strategy                  | Behavior                                                       | Best For                            |
| ------------------------- | -------------------------------------------------------------- | ----------------------------------- |
| `delete+insert` (default) | DELETE matching rows by `unique_key`, then INSERT all new rows | All databases, including ClickHouse |
| `update+insert`           | UPDATE existing rows, INSERT new rows (SQL MERGE)              | Postgres, Snowflake, BigQuery       |
| `insert`                  | Append only — no deduplication                                 | Event logs, append-only tables      |

An unrecognized value falls back to `delete+insert`.

```sql
/**
mode: incremental
unique_key: id
merge_strategy: delete+insert
update_key: created_at
**/

SELECT id, name, amount, created_at
FROM {{ ref('stg_orders') }}
WHERE {{ incremental_where_cond() }}
```

{% hint style="info" %}
Use `--full-refresh` to force a full rebuild of incremental models: `sling build run --full-refresh`. This drops and recreates the table, then runs the model with no incremental condition.
{% endhint %}

### append

Appends the complete result set to the target table on every run. No deduplication.

| Run        | SQL Behavior                      |
| ---------- | --------------------------------- |
| First      | `CREATE TABLE {table} AS ({sql})` |
| Subsequent | `INSERT INTO {table} SELECT ...`  |

**When to use**: Audit tables, change history, and time-series snapshots where you want to track state over time.

```sql
/**
mode: append
**/

SELECT id, status, balance, CURRENT_TIMESTAMP as snapshot_at
FROM {{ ref('stg_accounts') }}
```

### view

Creates a SQL view instead of a materialized table. No data is stored.

| Run       | SQL Behavior                                |
| --------- | ------------------------------------------- |
| Every run | `CREATE OR REPLACE VIEW {table} AS ({sql})` |

**When to use**: Logical groupings, lightweight transformations, or when queries must always show the latest source data.

```sql
/**
mode: view
**/

SELECT id, name, status
FROM {{ ref('stg_customers') }}
```

{% hint style="warning" %}
If a model was a table before and you change its mode to `view`, Sling drops the existing table before it creates the view.
{% endhint %}

### Mode Priority

1. `--full-refresh` CLI flag → forces `full-refresh` for all models
2. Model config (`mode` in front-matter or `config()`)
3. `sling_build.yml` `defaults.mode`
4. Built-in default: `full-refresh`

### Database Specifics

**ClickHouse:**

* Sling adds `ENGINE = MergeTree()` and `ORDER BY` (from `unique_key`) to `CREATE TABLE` statements
* The `engine` config option overrides the default ENGINE clause
* The `order_by`, `partition_by`, `primary_key`, `ttl`, and `settings` options set the table layout and the settings. See [ClickHouse table and query settings](#clickhouse-table-and-query-settings)
* Incremental mode always uses `delete+insert`, because ClickHouse does not support standard SQL MERGE. Any other strategy gives a warning

```sql
/**
mode: incremental
unique_key: id
update_key: updated_at
engine: ReplacingMergeTree(updated_at)
**/

SELECT id, name, updated_at
FROM {{ ref('stg_events') }}
WHERE {{ incremental_where_cond() }}
```

**Other engines:** Postgres, Snowflake, BigQuery, Databricks, Redshift, Trino, Athena, and StarRocks accept table options, layout keys, and session settings. See [Table options, layout and session settings (other engines)](#table-options-layout-and-session-settings-other-engines).

#### ClickHouse table and query settings

A ClickHouse model can set the table layout, the table settings, and the query settings in its config. `engine`, `order_by`, `primary_key`, and `ttl` apply only to ClickHouse. For `partition_by`, `settings.table`, and `settings.query` on other engines, see [Table options, layout and session settings (other engines)](#table-options-layout-and-session-settings-other-engines).

| Key              | Type           | Description                                                      |
| ---------------- | -------------- | ---------------------------------------------------------------- |
| `engine`         | string         | `ENGINE` clause. Default: `MergeTree()`                          |
| `order_by`       | string         | `ORDER BY` expression. Default: the `unique_key`, else `tuple()` |
| `partition_by`   | string or list | `PARTITION BY` expression                                        |
| `primary_key`    | string         | `PRIMARY KEY` expression. Needs `order_by` or `unique_key`       |
| `ttl`            | string         | `TTL` expression                                                 |
| `settings.table` | object         | Settings for the `SETTINGS` clause of `CREATE TABLE`             |
| `settings.query` | object         | Settings that Sling sends with the statements of the model       |

```sql
/**
mode: incremental
unique_key: event_id
update_key: timestamp
order_by: (event_day, event_id)
partition_by: toYYYYMM(timestamp)
primary_key: event_day
ttl: timestamp + INTERVAL 2 YEAR
settings:
  table:
    storage_policy: analytics_nvme
  query:
    max_memory_usage: 10000000000
    mutations_sync: 2
**/

SELECT event_id, event_day, timestamp
FROM {{ ref('stg_events') }}
```

Sling renders this `CREATE TABLE` statement. It sends the statement on one line.

```sql
CREATE TABLE analytics.plausible_events
  ENGINE = MergeTree()
  PARTITION BY toYYYYMM(timestamp)
  PRIMARY KEY event_day
  ORDER BY (event_day, event_id)
  TTL timestamp + INTERVAL 2 YEAR
  SETTINGS allow_nullable_key = 1, storage_policy = 'analytics_nvme'
AS (SELECT ...)
```

The clause order is fixed: `ENGINE`, `PARTITION BY`, `PRIMARY KEY`, `ORDER BY`, `TTL`, `SETTINGS`. ClickHouse gives a syntax error for any other order. Sling sorts the settings by name, so the SQL stays stable. On ClickHouse, a list or a map in `settings.table` gives an error.

**Defaults.** Set the same keys in the `defaults` section of `sling_build.yml`. A model value wins over a `defaults` value. The `settings.table` and `settings.query` maps merge key by key. A child `sling_build.yml` merges with its parent in the same way.

```yaml
# sling_build.yml
target: CLICKHOUSE

defaults:
  engine: MergeTree()
  partition_by: toYYYYMM(timestamp)
  settings:
    table:
      storage_policy: analytics_nvme
    query:
      max_memory_usage: 10000000000
```

**Values.**

* Sling puts single quotes around a string in a `SETTINGS` clause. It escapes `'` and `\`.
* A number stays as it is. A float such as `1e10` renders as `10000000000`.
* A bool becomes `1` or `0`.
* A map or a list gives an error. A setting name must be a plain name, such as `max_memory_usage`.
* `order_by`, `partition_by`, `primary_key`, and `ttl` are raw expressions. Sling does not change them. Use parens when `order_by` has more than one column, for example `(event_day, event_id)`.
* A key under `settings` other than `table` and `query` gives an error.
* `primary_key` without `order_by` or `unique_key` gives an error.

**`allow_nullable_key`.** When `ORDER BY` is not `tuple()`, Sling adds `allow_nullable_key = 1` to the table settings. This lets a nullable `unique_key` column work. To change it, set `allow_nullable_key` in `settings.table`. Your value wins.

**Staging tables.** The `_sling_build_tmp_*` tables get `settings.table` and `settings.query`. They keep `ENGINE = MergeTree() ORDER BY tuple()`. They get no `PARTITION BY`, `PRIMARY KEY`, or `TTL`, and no `allow_nullable_key`.

**Query settings.** Sling sends `settings.query` with each statement. It does not add them to the SQL text. The settings apply to one statement only. They do not stay on the connection.

* They apply to: `CREATE TABLE ... AS SELECT`, the staging table `CREATE TABLE ... AS SELECT`, `INSERT INTO ... SELECT`, and the `DELETE` and `INSERT` statements of an incremental merge.
* They do not apply to: hooks, pre-statements and post-statements, `DROP`, `TRUNCATE`, `RENAME`, row counts, and data tests.

Query settings apply to the statements that Sling sends. A `DELETE` on ClickHouse also runs as a mutation in the background. Sling makes no promise that a query setting limits this mutation.

{% hint style="warning" %}
**`mutations_sync` on the merge `DELETE`.** The ClickHouse merge template keeps an inline `SETTINGS mutations_sync = 1` on the `DELETE`. This SQL clause wins over the client setting. So `settings.query.mutations_sync` may have no effect on the merge `DELETE`. Sling gives this warning for an incremental model that sets it:

> model '\<name>': the ClickHouse merge DELETE keeps its inline mutations\_sync = 1; settings.query.mutations\_sync may have no effect on it

Other query settings, such as `max_threads`, reach the merge `DELETE`.
{% endhint %}

**Existing tables.** Table settings and the layout keys apply only when Sling creates the table. A change in the config does not change a table that exists. Run a full refresh (`sling build run --full-refresh`) to create the table again. You can also run `ALTER TABLE ... MODIFY SETTING` yourself for a table setting.

**Views and seeds.** The keys have no effect on views. Seeds load through a replication, so they get no settings. Sling gives no warning for views or seeds.

**Other dialects.** On a target that does not support a key, Sling ignores the key. It gives one warning for each model. Proton is in this group. Proton keeps its current SQL.

> model '\<name>': order\_by, ttl do not apply to postgres; sling ignores them

**Compile output.** `sling build compile` shows the `CREATE TABLE` clauses before a run. For each ClickHouse table model (not views), it prints `table_clause`. It also prints `query_settings` when the model has query settings. `table_clause` shows the clauses of the final table. The `--json` output has the same two keys.

```yaml
  table: sling_settings.ch_set_inc
  mode: incremental
  table_clause: ENGINE = MergeTree() PARTITION BY toYYYYMM(event_day) ORDER BY (event_day, id) SETTINGS allow_nullable_key = 1, index_granularity = 4096
  query_settings: log_comment = 'sling_settings_test', max_threads = 3, mutations_sync = 2
```

**The `config()` form.** `config()` accepts `order_by`, `partition_by`, `primary_key`, `ttl`, `cluster_by`, `transient`, `unlogged`, `dist`, `sort`, and `settings`. `partition_by`, `cluster_by`, and `sort` take a string or a list of strings. A dict gives an error. Give `settings` as a dict with `table` and `query`. Use `{{ config(...) }}` when a value has parens. The `{%- config(...) -%}` form does not match when a value has a `)`. Sling does not rewrite that block.

```sql
{{ config(
  mode='incremental',
  unique_key='event_id',
  update_key='timestamp',
  order_by='(event_day, event_id)',
  settings={'table': {'storage_policy': 'analytics_nvme'}}
) }}
```

**dbt-clickhouse mapping.**

| dbt-clickhouse                              | Sling build                                                      |
| ------------------------------------------- | ---------------------------------------------------------------- |
| `settings`                                  | `settings.table`                                                 |
| `query_settings`                            | `settings.query`                                                 |
| `order_by`, `primary_key`, `ttl`            | Same names                                                       |
| `partition_by` (string, or list of strings) | `partition_by`. A list with two or more items renders as a tuple |
| `engine`                                    | `engine`                                                         |

#### Table options, layout and session settings (other engines)

A model can set table options, a table layout, table flags, and session settings on Postgres, Snowflake, BigQuery, Databricks, Redshift, Trino, Athena, and StarRocks. Sling adds them to the `CREATE TABLE ... AS` statement of the model. Each dialect has its own clause syntax. The clause templates are in the template file of the dialect.

**Supported keys.** For `settings.table`, a cell shows the clause that Sling renders. For `settings.query`, a cell shows the statement that sets a value. For the other keys, `yes` means that the dialect supports the key. An empty cell means that the dialect does not support the key.

| Key              | Postgres     | Snowflake              | BigQuery        | Databricks            | Redshift    | Trino         | Athena       | StarRocks          |
| ---------------- | ------------ | ---------------------- | --------------- | --------------------- | ----------- | ------------- | ------------ | ------------------ |
| `settings.table` | `WITH (...)` | properties before `AS` | `OPTIONS (...)` | `TBLPROPERTIES (...)` |             | `WITH (...)`  | `WITH (...)` | `PROPERTIES (...)` |
| `settings.query` | `SET LOCAL`  | `ALTER SESSION SET`    |                 | `SET`                 | `SET LOCAL` | `SET SESSION` |              | `SET`              |
| `partition_by`   |              |                        | yes             | yes                   |             |               |              |                    |
| `cluster_by`     |              | yes                    | yes             | yes                   |             |               |              |                    |
| `transient`      |              | yes                    |                 |                       |             |               |              |                    |
| `unlogged`       | yes          |                        |                 |                       |             |               |              |                    |
| `dist`, `sort`   |              |                        |                 |                       | yes         |               |              |                    |

* Trino and Athena: give the partitions in `settings.table`. For example, use `partitioned_by: [d]` for Trino Hive, or `partitioning: [d]` for Athena Iceberg. A list renders as `ARRAY['d']`.
* Databricks: `partition_by` and `cluster_by` together give an error.
* Redshift: `dist: key` gives an error. Give the column, for example `dist: id`. Sling does not support `INTERLEAVED` sort keys.
* Athena: when `settings.table` has no `location` or `external_location`, Sling adds a location from the `data_location` of the connection. See **Athena location** below.
* `partition_by`, `cluster_by`, and `sort` take a string or a list of strings. They are raw SQL expressions. Sling joins a list with `,` . A dict gives an error. The dbt dict form of `partition_by` is not supported.
* A key that the dialect does not support gives one warning for each model. Sling ignores the key.

> model '\<name>': partition\_by, unlogged do not apply to snowflake; sling ignores them

**Value rules.**

* A setting name has letters, digits, and `_`. Dots can join the parts, for example `delta.autoOptimize.optimizeWrite`. Any other name gives an error.
* `settings.table` accepts strings, numbers, bools, lists, and maps. `settings.query` accepts strings, numbers, and bools.
* A string renders as a quoted literal. Sling escapes the quote character. A number renders as it is. A bool renders as `true` or `false`. Databricks and StarRocks put quotes around each option value, also a number or a bool.
* A list renders with the array syntax of the dialect: `ARRAY['d']` on Trino and Athena, `['d']` on BigQuery. A map renders only on BigQuery, for example `labels = [('team', 'data')]`. On another dialect, a list or a map gives an error, such as `model 'm': settings.table.x: lists are not supported on postgres`.
* Sling sorts the options by name, so the SQL stays stable. Snowflake renders the options as `name = value` pairs with a space between them.
* `dist` accepts `even`, `all`, `auto`, or a column name. A column name renders as `DISTSTYLE KEY DISTKEY(<column>)`.

**Defaults.** Set the same keys in the `defaults` section of `sling_build.yml`. A model value wins over a `defaults` value. The `settings.table` and `settings.query` maps merge key by key.

```yaml
# sling_build.yml
target: SNOWFLAKE

defaults:
  transient: true
  cluster_by: [region]
  settings:
    query:
      query_tag: sling_build
```

**Rendered SQL.** The examples use the model `analytics.orders_daily`. Each example shows the config of the model and the statements that Sling sends. Sling quotes the names for the dialect. The examples show the names without quotes. `<SELECT>` is the compiled query of the model.

Postgres:

```yaml
unlogged: true
settings:
  table:
    fillfactor: 70
    autovacuum_enabled: false
  query:
    work_mem: 64MB
```

```sql
BEGIN
SET LOCAL work_mem = '64MB'
CREATE UNLOGGED TABLE analytics.orders_daily WITH (autovacuum_enabled = false, fillfactor = 70) AS (<SELECT>)
COMMIT
```

Snowflake:

```yaml
transient: true
cluster_by: [region, d]
settings:
  table:
    comment: orders
    data_retention_time_in_days: 0
  query:
    query_tag: sling_build
```

```sql
ALTER SESSION SET query_tag = 'sling_build'
CREATE OR REPLACE TRANSIENT TABLE analytics.orders_daily CLUSTER BY (region, d) comment = 'orders' data_retention_time_in_days = 0 AS (<SELECT>)
ALTER SESSION UNSET query_tag
```

BigQuery. A `settings.query` gives a warning on BigQuery.

```yaml
partition_by: d
cluster_by: [region, id]
settings:
  table:
    description: orders
    labels:
      team: data
    partition_expiration_days: 30
```

```sql
CREATE OR REPLACE TABLE analytics.orders_daily PARTITION BY d CLUSTER BY region, id OPTIONS (description = 'orders', labels = [('team', 'data')], partition_expiration_days = 30) AS (<SELECT>)
```

Databricks:

```yaml
cluster_by: region
settings:
  table:
    delta.autoOptimize.optimizeWrite: true
  query:
    timezone: Asia/Tokyo
```

```sql
SET timezone = 'Asia/Tokyo'
CREATE OR REPLACE TABLE analytics.orders_daily CLUSTER BY (region) TBLPROPERTIES ('delta.autoOptimize.optimizeWrite' = 'true') AS (<SELECT>)
RESET timezone
```

Redshift:

```yaml
dist: id
sort: [d, region]
settings:
  query:
    statement_timeout: 600000
```

```sql
BEGIN
SET LOCAL statement_timeout = 600000
CREATE TABLE analytics.orders_daily DISTSTYLE KEY DISTKEY(id) COMPOUND SORTKEY(d, region) AS (<SELECT>)
COMMIT
```

Trino. Each Trino catalog has its own table properties. Sling does not check them. The server gives an error for an unknown property.

```yaml
settings:
  table:
    format: PARQUET
    partitioned_by: [d]
  query:
    query_max_run_time: 10m
```

```sql
SET SESSION query_max_run_time = '10m'
CREATE TABLE analytics.orders_daily WITH (format = 'PARQUET', partitioned_by = ARRAY['d']) AS (<SELECT>)
RESET SESSION query_max_run_time
```

Athena. A `settings.query` gives a warning on Athena.

```yaml
settings:
  table:
    format: PARQUET
    partitioning: [d]
    table_type: ICEBERG
```

```sql
CREATE TABLE analytics.orders_daily WITH (format = 'PARQUET', partitioning = ARRAY['d'], table_type = 'ICEBERG', location = 's3://my-bucket/athena/data/analytics/orders_daily/20261111T101500abcd/', is_external = false) AS (<SELECT>)
```

StarRocks:

```yaml
settings:
  table:
    compression: ZSTD
    replication_num: 1
  query:
    query_timeout: 600
```

```sql
SET query_timeout = 600
CREATE TABLE analytics.orders_daily PROPERTIES ("compression" = "ZSTD", "replication_num" = "1") AS (<SELECT>)
SET query_timeout = DEFAULT
```

**Full refresh.** The statements above are the `CREATE` statement of the final table. The way to replace an existing table depends on the dialect:

* Snowflake, BigQuery, and Databricks run `CREATE OR REPLACE TABLE`.
* Postgres, Redshift, and Trino run the `CREATE` statement on a `_sling_build_tmp_*` table with the same clauses. Then they drop the old table and rename the tmp table.
* StarRocks and Athena do not use a tmp table. They drop the old table, then run the `CREATE` statement.

**Scope of `settings.query`.** Sling applies the settings to the statements of one model call only.

* For each statement call of the model, Sling opens one transaction (Postgres and Redshift) or one pinned session (Snowflake, Databricks, Trino, and StarRocks). Sling sets the values, runs the statements, and then resets the values (session only) or ends the transaction.
* A statement call is a `CREATE TABLE ... AS SELECT`, an `INSERT INTO ... SELECT`, or the `DELETE` and `INSERT` statements of an incremental merge. On Postgres and Redshift, a merge with `settings.query` runs its `DELETE` and `INSERT` in one transaction.
* Hooks, pre-statements and post-statements, `DROP`, `TRUNCATE`, and `RENAME` get no settings. Row counts and data tests get no settings.
* The settings do not go to other models or to later statements on the same connection. If a statement fails, Sling rolls back the transaction or closes the pinned connection, so the values do not stay.
* BigQuery and Athena have no session. A `settings.query` on them gives a warning, and Sling ignores it.

**Staging tables.**

* The final table and the full-refresh tmp table get the options, the layout, and the flags.
* The `_sling_build_tmp_*` staging tables of an incremental model get no options, no layout, and no flags. They get the query settings.
* Athena staging tables get only the default location.

**Athena location.**

* Sling adds a default location when `settings.table` has no `location` and no `external_location`, and the connection has `data_location`. A location from the user wins.
* For a Hive table, Sling adds `external_location`. For an Iceberg table (`table_type: ICEBERG`), Sling adds `location` and `is_external = false`.
* The location is `<data_location>/<schema>/<table>/<salt>/`. The salt is a new folder name for each run. Sling adds the salt only when it runs the build. The compile output shows the path without the salt.
* The default location is the last option in the list.
* A full refresh on Athena drops the table, then creates it. A Hive `DROP` keeps the data on S3. So the old data of a Hive table stays on S3 after a full refresh. Delete the old data yourself.

**Existing tables.** A change to `settings.table`, the layout keys, or the flags on a table that already exists applies at the next full refresh.

**BigQuery replace.** `CREATE OR REPLACE` fails on BigQuery when the new partition spec differs from the old one. Drop the table, then run the model again.

**Views and seeds.** The keys have no effect on views. Seeds load through a replication, so they get no settings. Sling gives no warning for views or seeds.

**Compile output.** For each table model, `sling build compile` prints `table_clause` (the layout and option clauses of the final table), and `table_kind` (for example `UNLOGGED`) when the model sets a flag. It prints `query_settings` when the model has query settings. The `--json` output has the same keys.

```yaml
  table: sling_build_pg.pg_set_full
  mode: full-refresh
  table_kind: UNLOGGED
  table_clause: WITH (autovacuum_enabled = false, fillfactor = 70)
  query_settings: work_mem = '64MB'
```

**dbt adapter mapping.**

| dbt adapter    | dbt config                                                   | Sling build                                                           |
| -------------- | ------------------------------------------------------------ | --------------------------------------------------------------------- |
| dbt-snowflake  | `transient`, `cluster_by`                                    | Same names                                                            |
|                | `query_tag`                                                  | `settings.query.query_tag`                                            |
| dbt-bigquery   | `partition_by`                                               | `partition_by`, as a raw expression. The dbt dict form gives an error |
|                | `cluster_by`                                                 | `cluster_by`                                                          |
|                | `labels`                                                     | `settings.table.labels`                                               |
| dbt-redshift   | `dist`, `sort`                                               | Same names. `sort_type` is not supported                              |
| dbt-postgres   | `unlogged`                                                   | `unlogged`                                                            |
|                | `WITH` storage parameters                                    | `settings.table`                                                      |
| dbt-databricks | `tblproperties`                                              | `settings.table`                                                      |
|                | `partition_by`                                               | `partition_by`                                                        |
|                | `liquid_clustered_by`                                        | `cluster_by`                                                          |
| dbt-trino      | `properties`                                                 | `settings.table`                                                      |
| dbt-athena     | `table_properties`, `format`, `partitioned_by`, `table_type` | `settings.table`                                                      |

**SQL Server family:** uses `SELECT * INTO ... FROM (...)` instead of CTAS, and `CREATE OR ALTER VIEW` for views.

**DuckDB family:** these are single-writer databases, so Sling forces the thread count to 1.

## Template Functions

### `ref()`

Resolves a model or seed name to its full table name and creates a DAG dependency.

```sql
SELECT *
FROM {{ ref('stg_orders') }}
JOIN {{ ref('country_codes') }} USING (country_code)
```

If `stg_orders` resolves to `staging.stg_orders` and `country_codes` is a seed at `staging.country_codes`, the compiled SQL becomes:

```sql
SELECT *
FROM staging.stg_orders
JOIN staging.country_codes USING (country_code)
```

An unknown name gives the error `ref('<name>'): model or seed not found in project`.

### `src()` / `source()`

References an external table that the build does not manage. This creates no DAG dependency.

```sql
-- Single argument: schema.table
SELECT * FROM {{ src('raw_data.events') }}

-- Two arguments: schema, table
SELECT * FROM {{ source('raw_data', 'events') }}
```

### `this`

Resolves to the model's own full table name. This is a variable, not a function.

```sql
{% if is_incremental() %}
WHERE updated_at > (SELECT MAX(updated_at) FROM {{ this }})
{% endif %}
```

### `is_incremental()`

Returns `true` when all of these are true:

1. The model's mode is `incremental`
2. The target table already exists
3. The `--full-refresh` flag is **not** set

```sql
{%- config(mode='incremental', unique_key='id', update_key='created_at') -%}

SELECT id, name, created_at
FROM {{ ref('stg_orders') }}
{% if is_incremental() %}
WHERE created_at > (SELECT MAX(created_at) FROM {{ this }})
{% endif %}
```

On the first run the table does not exist, so `is_incremental()` returns `false` and the full dataset loads. On later runs, only new rows are selected.

### `incremental_where_cond()`

A Jinja function that returns a `WHERE` clause body bounded by the model's `update_key` range. Sling-native incremental models use it in place of `is_incremental()`. On the first run, or with no state, it returns `1=1`.

```sql
/**
mode: incremental
unique_key: id
update_key: created_at
**/
SELECT id, name, created_at
FROM {{ ref('stg_orders') }}
WHERE {{ incremental_where_cond() }}
```

See [Incremental](https://docs.slingdata.io/concepts/build/incremental.md) for how Sling resolves the bounds and how to use the `range:` front-matter block.

### `incremental_value()`

A Jinja function that returns the current lower-bound value as a SQL literal (for example `'2024-01-01'`), or `null` on the first run. Use it for non-`WHERE` expressions that need the watermark value directly.

### `@model_name` Shorthand

Prefix a model or seed name with `@` to resolve it to the full table name and add a DAG dependency. This is a shorter form of `ref()`.

```sql
SELECT * FROM @stg_orders
```

Sling ignores `@@name` (MySQL system variables), and leaves an unknown `@name` untouched, so SQL Server `@variable` syntax still works.

### Bare Variable References

Model and seed names also work directly as variables. They resolve to the full table name but do **not** create an explicit DAG dependency. Auto-detection may still find them.

```sql
SELECT * FROM {{ stg_orders }}
```

### User Variables

Variables defined in `sling_build.yml` or passed with `--vars` are top-level template variables.

```yaml
# sling_build.yml
vars:
  start_date: '2024-01-01'
```

```sql
SELECT * FROM orders
WHERE created_at >= '{{ start_date }}'
```

```bash
# Override from CLI
sling build run --vars '{"start_date": "2024-06-01"}'
```

{% hint style="info" %}
Use `{{ my_var }}` directly. There is no `var()` function.
{% endhint %}

## Auto-Detection of References

Sling parses `FROM` and `JOIN` clauses in the compiled SQL to find references to other project models. It adds these detected dependencies to the DAG together with the explicit `ref()` calls.

For example, if your SQL has `FROM staging.stg_orders` and `stg_orders` is a model in the project, Sling adds it as a dependency even with no `ref()` call.

{% hint style="info" %}
Auto-detection supplements `ref()` but does not replace it. Use `ref()`, because it makes sure table names resolve correctly in both dev and prod modes. Set `rewrite: false` on a model to turn off bare-name rewriting.
{% endhint %}

## Multi-Statement SQL

A model file can hold more than one SQL statement, separated by semicolons. Sling splits them into:

* **Pre-statements** — statements before the main SELECT query, for example creating temp tables
* **Model query** — the single SELECT/WITH query used for materialization
* **Post-statements** — statements after the model query, for example cleanup or GRANT

```sql
-- Pre-statement: create a temp staging table
CREATE TEMP TABLE tmp_raw_data AS
SELECT id, name FROM raw_source;

-- Model query (the SELECT used for CTAS/merge)
SELECT id, UPPER(name) as name
FROM tmp_raw_data;

-- Post-statement: cleanup
DROP TABLE IF EXISTS tmp_raw_data;
```

Sling uses SQL classification to find the model query. A file must have **exactly one** SELECT query. Zero or more than one gives an error.

## Hooks

Models support `start` and `end` hooks that run before and after the model. They use the same [hook types](https://docs.slingdata.io/concepts/hooks.md) as replications and pipelines: query, log, check, http, command, and others.

Declare hooks in YAML front-matter under the `hooks` key:

```sql
/**
mode: incremental
unique_key: id
update_key: created_at
hooks:
  start:
    - type: query
      connection: postgres
      query: "REFRESH MATERIALIZED VIEW upstream_mv"
    - type: log
      message: "Starting model build"
  end:
    - type: check
      check: execution.status.error == 0
    - type: http
      url: https://slack.webhook/...
      body: "Model built successfully"
**/

SELECT * FROM {{ ref('stg_orders') }}
WHERE {{ incremental_where_cond() }}
```

### Execution Order

When a model has hooks, pre-statements, post-statements, and tests, the order is:

1. **Start hooks** — `hooks.start` from front-matter
2. **Pre-statements** — SQL statements before the model query
3. **Model query** — the SELECT used for materialization
4. **Post-statements** — SQL statements after the model query
5. **Data tests** — `tests` from front-matter
6. **End hooks** — `hooks.end` from front-matter

### Available State Variables

Hooks can use these template variables:

| Variable           | Description                                                                                                    |
| ------------------ | -------------------------------------------------------------------------------------------------------------- |
| `model.name`       | Model name, for example `fct_orders`                                                                           |
| `model.schema`     | Model schema, for example `marts`                                                                              |
| `model.database`   | Model database. Empty for targets that do not use a database level, for example ClickHouse                     |
| `model.full_name`  | Full table name, for example `marts.core_fct_orders`                                                           |
| `model.mode`       | Execution mode, for example `incremental`                                                                      |
| `model.update_key` | The `update_key` of the model, for example `created_at`. Empty if not set                                      |
| `model.unique_key` | The `unique_key` of the model. A composite key is comma-separated, for example `id, line_no`. Empty if not set |
| `target.name`      | Target connection name                                                                                         |
| `store.*`          | Shared key-value store for communication between hooks                                                         |
| `timestamp.*`      | Date and time fields (`YYYY`, `MM`, `DD`, and others)                                                          |

A `model.*` variable with no value renders as an empty string.

This example uses a start hook to stop old ClickHouse mutations of the model table before the incremental merge:

```sql
/**
mode: incremental
update_key: timestamp
unique_key: event_id
hooks:
  start:
    - type: query
      connection: '{target.name}'
      query: |
        KILL MUTATION WHERE database = '{model.schema}' AND table = '{model.name}'
          AND command LIKE '%_sling_build_tmp_{model.name}_%'
    - type: log
      message: "building {model.full_name} ({model.mode}) on {model.unique_key}"
**/
```

{% hint style="info" %}
The `model.*` variables render in hooks from Sling version 1.6.6. Earlier versions send the placeholders to the database as literal text.
{% endhint %}

## Data Tests

Declare data tests in the `tests` front-matter key. Each test compiles to a query that counts violating rows against the materialized table. A count above 0 fails the model, and its downstream models are skipped.

```sql
/**
mode: full-refresh
tests:
  - not_null: [id, customer_id]
  - unique: id
  - accepted_values:
      column: status
      values: [pending, shipped, delivered]
  - expr: sum(amount) >= 0
**/

SELECT id, customer_id, status, amount
FROM {{ ref('stg_orders') }}
```

### Test Types

| Test              | Syntax                                              | Checks                                            |
| ----------------- | --------------------------------------------------- | ------------------------------------------------- |
| `not_null`        | `not_null: id` or `not_null: [id, name]`            | No listed column is NULL                          |
| `unique`          | `unique: id` or `unique: [a, b]`                    | The column set has no duplicate rows              |
| `accepted_values` | `accepted_values: {column: status, values: [a, b]}` | Non-null values of the column are all in the list |
| `expr`            | `expr: sum(amount) >= 0`                            | The SQL expression is true over the table         |

{% hint style="warning" %}
The `expr` test injects your expression into the query without validation. Use it only with SQL you control.
{% endhint %}

### Running Tests Only

Use `sling build test` to run the data tests and skip materialization:

```bash
sling build test
sling build test -s "tag:critical"
```

In this mode Sling walks the selected DAG, skips all seeds, and runs only the tests. Models with no `tests` are no-ops and report OK.

{% hint style="info" %}
`tests` is a front-matter-only key. You cannot set it in a `config()` block.
{% endhint %}

## Macros

Macros are reusable Jinja blocks that remove repeated SQL patterns across models. Define them in `.macros.sql` files. Sling makes them available to models by directory scope.

### Defining Macros

Create a file that ends in `.macros.sql` with one or more `{% macro %}` definitions.

{% code title="utils.macros.sql" %}

```sql
{% macro cents_to_dollars(column_name) %}
    ({{ column_name }} / 100.0)
{% endmacro %}

{% macro safe_divide(numerator, denominator) %}
    CASE WHEN {{ denominator }} = 0 THEN NULL ELSE {{ numerator }}::float / {{ denominator }} END
{% endmacro %}
```

{% endcode %}

{% hint style="info" %}
Sling treats files that end in `.macros.sql` as macro files, not models. It does not compile or execute them against the database.
{% endhint %}

### Using Macros in Models

Call macros in any model SQL with standard Jinja syntax.

```sql
SELECT
    id,
    {{ cents_to_dollars('amount_cents') }} as amount_dollars,
    {{ safe_divide('revenue', 'num_orders') }} as avg_order_value
FROM {{ ref('stg_orders') }}
```

Compiles to:

```sql
SELECT
    id,
    (amount_cents / 100.0) as amount_dollars,
    CASE WHEN num_orders = 0 THEN NULL ELSE revenue::float / num_orders END as avg_order_value
FROM staging.stg_orders
```

### Scoping Rules

Macros are scoped by directory. A macro file is available to models in the same directory and all child directories.

| Macro File Location                        | Available To                                   |
| ------------------------------------------ | ---------------------------------------------- |
| Root-level, for example `utils.macros.sql` | All models in the project                      |
| `staging/helpers.macros.sql`               | Models in `staging/` and its subdirectories    |
| `marts/core/core_utils.macros.sql`         | Models in `marts/core/` and its subdirectories |

```
my_project/
├── utils.macros.sql                    # global — available everywhere
├── staging/
│   ├── helpers.macros.sql              # scoped — staging/ only
│   ├── stg_orders.sql                  # can use: utils + helpers
│   └── stg_customers.sql               # can use: utils + helpers
└── marts/
    └── core/
        └── fct_orders.sql              # can use: utils only (not helpers)
```

### Macro Name Conflicts

When the same macro name exists at more than one scope level, the **closest scope wins**. Sling prints a warning in debug mode when it finds macro shadowing.

```
WARN: macro 'clean_string' in staging/helpers.macros.sql shadows definition in utils.macros.sql
```

Sling loads all `.macros.sql` files in a directory. It concatenates them root-first, then by directory, then alphabetically by filename, for deterministic behavior.

## Seeds

Seeds are static data files that Sling loads into the target database before models execute. Use them for reference data, lookup tables, and test fixtures.

### Supported Formats

| Format  | Extension  | Notes                                |
| ------- | ---------- | ------------------------------------ |
| CSV     | `.csv`     | Parsed with automatic type inference |
| JSON    | `.json`    | Nested structures are flattened      |
| Parquet | `.parquet` | Schema kept from file metadata       |

Extension matching is not case-sensitive. Compressed and other formats, such as `.csv.gz`, `.tsv`, or `.xlsx`, are not supported as seeds.

### Placement and Naming

Seed files follow the same naming rules as models. The first folder sets the schema. The file name is the table name.

**Flat structure** (default): seeds are together with models in schema folders.

```
staging/
├── stg_orders.sql           # model → staging.stg_orders
└── country_codes.csv        # seed  → staging.country_codes
```

**DBT-compatible structure** (`dbt_project: true`): seeds go in the `seeds/` directory.

```
seeds/
└── staging/
    └── country_codes.csv    # seed → staging.country_codes
```

See [Structure](https://docs.slingdata.io/concepts/build/structure.md) for the full naming rules.

### Loading Behavior

* Seeds always load in **full-refresh** mode. This ignores `defaults.mode`
* Sling uses its task infrastructure to load them, so you get type inference, bulk loading, and all 30+ connectors
* Seeds execute at depth 0 in the DAG, before any models

### Referencing Seeds

Reference seeds in models with `ref()`, the same as any other model.

{% code title="staging/country\_codes.csv" %}

```csv
code,name,region
US,United States,North America
GB,United Kingdom,Europe
JP,Japan,Asia
```

{% endcode %}

{% code title="marts/dim\_countries.sql" %}

```sql
SELECT
    code as country_code,
    name as country_name,
    region
FROM {{ ref('country_codes') }}
```

{% endcode %}

The `ref('country_codes')` resolves to `staging.country_codes` and adds a DAG dependency, so the seed loads before the model executes.

### Skipping Seeds

Use `--no-seeds` to skip seed loading.

```bash
sling build run --no-seeds
```

Seeds show as `SKIP` in the progress output. Downstream models still execute — a skipped seed does **not** cascade as a failure.

### Seeds in the DAG

* Seeds have no dependencies and are always at depth 0
* More than one seed can execute in parallel when `--threads` is above 1
* You can select and exclude seeds with `--select` and `--exclude`, the same as models
* A `tag:` selector never matches a seed, because tags apply to models only

## Complete Example

```sql
/**
mode: incremental
unique_key: [order_id, line_id]
merge_strategy: delete+insert
update_key: updated_at
tags:
  - daily
  - core
tests:
  - not_null: [order_id, line_id]
  - unique: [order_id, line_id]
hooks:
  start:
    - type: query
      connection: '{target.name}'
      query: "DELETE FROM marts.core_fct_orders WHERE is_cancelled = true"
  end:
    - type: log
      message: "Model fct_orders built successfully"
**/

SELECT
    o.id as order_id,
    ol.id as line_id,
    o.customer_id,
    {{ cents_to_dollars('ol.amount_cents') }} as amount_dollars,
    o.updated_at
FROM {{ ref('stg_orders') }} o
JOIN {{ ref('stg_order_lines') }} ol ON o.id = ol.order_id
WHERE {{ incremental_where_cond() }}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.slingdata.io/concepts/build/models.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
