dbt-s-layer 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. dbt_s_layer-1.0.0/PKG-INFO +562 -0
  2. dbt_s_layer-1.0.0/README.md +533 -0
  3. dbt_s_layer-1.0.0/pyproject.toml +99 -0
  4. dbt_s_layer-1.0.0/pyproject.toml.orig +92 -0
  5. dbt_s_layer-1.0.0/src/dbt_s_layer/__init__.py +3 -0
  6. dbt_s_layer-1.0.0/src/dbt_s_layer/__main__.py +8 -0
  7. dbt_s_layer-1.0.0/src/dbt_s_layer/_commands.py +148 -0
  8. dbt_s_layer-1.0.0/src/dbt_s_layer/_doctor.py +314 -0
  9. dbt_s_layer-1.0.0/src/dbt_s_layer/_hook.py +354 -0
  10. dbt_s_layer-1.0.0/src/dbt_s_layer/_paths.py +17 -0
  11. dbt_s_layer-1.0.0/src/dbt_s_layer/_project_yaml.py +297 -0
  12. dbt_s_layer-1.0.0/src/dbt_s_layer/_yaml.py +28 -0
  13. dbt_s_layer-1.0.0/src/dbt_s_layer/artifacts.py +332 -0
  14. dbt_s_layer-1.0.0/src/dbt_s_layer/cli.py +207 -0
  15. dbt_s_layer-1.0.0/src/dbt_s_layer/databricks.py +434 -0
  16. dbt_s_layer-1.0.0/src/dbt_s_layer/duckdb_views.py +547 -0
  17. dbt_s_layer-1.0.0/src/dbt_s_layer/errors.py +69 -0
  18. dbt_s_layer-1.0.0/src/dbt_s_layer/exports.py +433 -0
  19. dbt_s_layer-1.0.0/src/dbt_s_layer/output.py +439 -0
  20. dbt_s_layer-1.0.0/src/dbt_s_layer/profiles.py +85 -0
  21. dbt_s_layer-1.0.0/src/dbt_s_layer/project.py +130 -0
  22. dbt_s_layer-1.0.0/src/dbt_s_layer/py.typed +0 -0
  23. dbt_s_layer-1.0.0/src/dbt_s_layer/quoting.py +239 -0
  24. dbt_s_layer-1.0.0/src/dbt_s_layer/refs.py +104 -0
  25. dbt_s_layer-1.0.0/src/dbt_s_layer/s_layer.py +183 -0
  26. dbt_s_layer-1.0.0/src/dbt_s_layer/semantic_views.py +830 -0
  27. dbt_s_layer-1.0.0/src/dbt_s_layer/sentinels.py +271 -0
  28. dbt_s_layer-1.0.0/src/dbt_s_layer/snowflake.py +590 -0
  29. dbt_s_layer-1.0.0/src/dbt_s_layer/staleness.py +161 -0
@@ -0,0 +1,562 @@
1
+ Metadata-Version: 2.4
2
+ Name: dbt-s-layer
3
+ Version: 1.0.0
4
+ Summary: dbt Cloud semantic-layer features for dbt Core / Fusion users
5
+ Keywords: dbt,semantic-layer,metricflow,snowflake,databricks,duckdb
6
+ Author: Anentropic
7
+ Author-email: Anentropic <ego@anentropic.com>
8
+ License-Expression: Apache-2.0
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: Topic :: Database
17
+ Classifier: Typing :: Typed
18
+ Requires-Dist: typer>=0.26.3
19
+ Requires-Dist: pydantic>=2.7,<3
20
+ Requires-Dist: metricflow==0.213.0
21
+ Requires-Dist: ruamel-yaml>=0.18
22
+ Requires-Dist: s-layer-semantic-formats>=0.2,<0.3
23
+ Requires-Python: >=3.11
24
+ Project-URL: Homepage, https://github.com/s-layer/dbt-s-layer
25
+ Project-URL: Repository, https://github.com/s-layer/dbt-s-layer
26
+ Project-URL: Changelog, https://github.com/s-layer/dbt-s-layer/blob/develop/CHANGELOG.md
27
+ Project-URL: Issues, https://github.com/s-layer/dbt-s-layer/issues
28
+ Description-Content-Type: text/markdown
29
+
30
+ # dbt-s-layer
31
+
32
+ dbt semantic-layer features for dbt Core / Fusion users, no dbt Cloud required.
33
+
34
+ `dbt-s-layer` is a Python package that reads dbt semantic YAML (via `semantic_manifest.json`) and code-generates two families of dbt models:
35
+
36
+ 1. **Warehouse-native semantic views** (`sem__*.sql`) — Snowflake `SEMANTIC VIEW`, Databricks metric views, DuckDB semantic views
37
+ 2. **Pre-aggregated exports** (`exp__*.sql`) — materialised from `saved_query` export blocks using MetricFlow's SQL rendering engine
38
+
39
+ A pre-commit hook keeps generated files in sync with YAML changes automatically.
40
+
41
+ ## Status
42
+
43
+ Version 1.0. Releases follow [Semantic Versioning](https://semver.org/), and
44
+ [CHANGELOG.md](https://github.com/s-layer/dbt-s-layer/blob/develop/CHANGELOG.md) lists what each one changes.
45
+
46
+ ## Quick start
47
+
48
+ Install dbt-s-layer next to the dbt engine and adapter you already use:
49
+
50
+ ```sh
51
+ pip install dbt-s-layer dbt-core dbt-duckdb # or dbt-snowflake, dbt-databricks
52
+ ```
53
+
54
+ In a dbt project whose YAML has `semantic_models:`, `metrics:` and `saved_queries:` with
55
+ `exports:`, parse, generate, commit and build:
56
+
57
+ ```sh
58
+ dbt parse
59
+ dbt-s-layer generate
60
+ git add models/semantic
61
+ dbt build
62
+ ```
63
+
64
+ On Snowflake, the generated semantic views also need the `dbt_semantic_view` package: add it
65
+ to `packages.yml` and run `dbt deps` before `dbt build` (see
66
+ [Install the package](#install-the-package)). On DuckDB they need the `duckdb_semantic_views`
67
+ package and the `semantic_views` extension (see [Semantic views (DuckDB)](#semantic-views-duckdb)).
68
+
69
+ `generate` writes an `exp__<saved_query>__<export>.sql` model for each export and, on
70
+ Snowflake, Databricks and DuckDB, a `sem__<semantic_model>.sql` view for each semantic model, into
71
+ `models/semantic/`. `dbt build` then materialises them like any other model. To keep them in
72
+ step with your YAML, add the [pre-commit hook](#pre-commit-hook); to catch a forgotten
73
+ `generate` in CI, run `dbt-s-layer check`.
74
+
75
+ ## Requirements
76
+
77
+ - Python 3.11+
78
+ - A dbt engine on `PATH` that writes `target/semantic_manifest.json` when you run `dbt parse`, either of:
79
+ - [dbt Core](https://docs.getdbt.com/docs/core/installation-overview) 1.7 or later, which parses both the legacy and the new semantic YAML spec
80
+ - [dbt Fusion](https://docs.getdbt.com/docs/fusion/install-fusion), which parses the new spec only
81
+
82
+ Run `dbt-s-layer doctor` to check what it finds. Add `--project-dir path/to/project` to also check that project's parse artifacts exist and are newer than its semantic YAML, and that the output directory can be written.
83
+
84
+ ## Generating models
85
+
86
+ Run `dbt parse`, then:
87
+
88
+ ```sh
89
+ dbt-s-layer generate --project-dir path/to/project
90
+ ```
91
+
92
+ This writes the generated models and a `_semantic_views.yml` schema file to `models/semantic/`. Commit them alongside your semantic YAML. Running it again with the same inputs leaves the files byte-for-byte unchanged.
93
+
94
+ In CI, `dbt-s-layer check` (same options) exits 1 and lists the changed, missing and stale files when the committed models no longer match a fresh run. It writes nothing.
95
+
96
+ | Option | Default | |
97
+ |---|---|---|
98
+ | `--project-dir` | current directory | The dbt project. Its `target/` must hold fresh `dbt parse` artifacts. |
99
+ | `--output-dir` | `models/semantic` | Relative to `--project-dir`. Keep it under your `model-paths` so dbt builds the models. |
100
+ | `--adapter` | the adapter you parsed with | SQL dialect: `snowflake`, `databricks`, `duckdb`, `bigquery`, `postgres`, `redshift`, `trino` or `athena`. |
101
+ | `--target` | | Use this dbt target's adapter type from `profiles.yml` as the dialect. `--adapter` wins if both are given. |
102
+ | `--profiles-dir` | `DBT_PROFILES_DIR`, the current directory, the project, `~/.dbt` | Where to find `profiles.yml` for `--target`. |
103
+
104
+ In the output directory, dbt-s-layer owns the `exp__*.sql`, `sem__*.sql` and `_semantic_views.yml` files. Each starts with a `Generated by dbt-s-layer` line. Files it no longer generates are deleted. It won't overwrite a file with one of those names that lacks the header, and it leaves every other file alone. New and changed files are staged next to the output directory and moved into place only once all of them are written. A failed run leaves the directory as it was.
105
+
106
+ `generate` also refuses a model that would clash with one of yours, either by name or by building the same table (same custom schema and alias, compared case-insensitively).
107
+
108
+ ## Exports
109
+
110
+ Each `export` of a `saved_query` becomes one model, `exp__<saved_query>__<export>.sql`: MetricFlow's SQL for the saved query, with every table it reads written as a `{{ ref() }}`, so the export sits in your DAG like any other model.
111
+
112
+ - `export_as: table` or `view` sets `materialized` (default `table`). An export without its own `export_as` uses the saved query's `config.export_as`.
113
+ - `alias` defaults to the export name.
114
+ - `schema`, if you set one on the export or the saved query, goes through your project's `generate_schema_name` like any dbt model schema. With dbt's default macro that means `<target schema>_<schema>`, where dbt Cloud would write to the schema exactly as named.
115
+ - The SQL dialect follows the adapter of the target you parsed with, unless you pass `--adapter` or `--target`.
116
+ - The schema file describes each export with its saved query's `description`.
117
+ - An entity, dimension or metric named like a reserved word of the dialect (`order`, `group`, ...) is quoted in the SQL, in the case the warehouse gives an unquoted name (`"ORDER"` on Snowflake), so the column keeps its usual name. MetricFlow itself leaves such names bare ([metricflow#2058](https://github.com/dbt-labs/metricflow/issues/2058)). SQL you write in an `expr` is used as written: quote a reserved word there yourself.
118
+
119
+ ## Semantic views (Snowflake)
120
+
121
+ On a Snowflake target, each semantic model becomes one model, `sem__<semantic_model>.sql`, that
122
+ the Snowflake-Labs [`dbt_semantic_view`](https://github.com/Snowflake-Labs/dbt_semantic_view)
123
+ package builds as a Snowflake `SEMANTIC VIEW`. Databricks targets get metric views instead (see
124
+ [Metric views (Databricks)](#metric-views-databricks)), and DuckDB targets DuckDB semantic views
125
+ (see [Semantic views (DuckDB)](#semantic-views-duckdb)). Other adapters get no `sem__` files and
126
+ one warning; their exports are generated as usual.
127
+
128
+ The model body is the `CREATE SEMANTIC VIEW` clause list. For `orders` it looks like this:
129
+
130
+ ```sql
131
+ -- Generated by dbt-s-layer from semantic model 'orders'. Do not edit: ...
132
+ {{ config(materialized='semantic_view', static_analysis='off') }}
133
+
134
+ TABLES (
135
+ orders AS {{ ref('orders') }}
136
+ PRIMARY KEY (order_id),
137
+ customers AS {{ ref('customers', v=2) }}
138
+ PRIMARY KEY (customer_id)
139
+ )
140
+ RELATIONSHIPS (
141
+ orders_to_customers AS orders (customer_id) REFERENCES customers (customer_id)
142
+ )
143
+ DIMENSIONS (
144
+ orders.customer AS customer_id,
145
+ orders."ORDER" AS order_id,
146
+ orders.ordered_at AS ordered_at,
147
+ customers.country AS country,
148
+ customers.customer AS customer_id
149
+ )
150
+ METRICS (
151
+ orders.order_count AS COUNT(DISTINCT order_id),
152
+ orders.revenue AS SUM(amount),
153
+ average_order_value AS orders.revenue / NULLIF(orders.order_count, 0)
154
+ )
155
+ ```
156
+
157
+ - **Tables.** The semantic model, plus every semantic model MetricFlow could join to it: through
158
+ its primary, unique or foreign entities to a model where that entity is primary or unique, up
159
+ to two hops. Each is a `{{ ref() }}`, so the view sits in your DAG after the models it reads.
160
+ When two join paths reach the same model, the first (in name order) is kept and you get a
161
+ warning.
162
+ - **Keys and relationships.** Primary and unique entities become `PRIMARY KEY` and `UNIQUE`, and
163
+ each join a `RELATIONSHIPS` entry. Snowflake keys must be columns, so an entity whose `expr` is
164
+ an expression is neither a key nor a join (with a warning).
165
+ - **Dimensions.** Every dimension of every table, plus its primary, unique and foreign entities,
166
+ each as `<table>.<name> AS <expr>`.
167
+ - **Metrics.** The semantic model's own simple metrics (`sum`, `min`, `max`, `average`, `count`,
168
+ `count_distinct`, `sum_boolean`, `median` and `percentile`), with `PRIVATE` for private metrics
169
+ and `NON ADDITIVE BY` for a non-additive dimension. Ratio and derived metrics whose inputs are
170
+ all simple metrics of the same semantic model become view-level metrics.
171
+ - **Descriptions** become `COMMENT`s. Names that are Snowflake keywords (`order`, `group`) are
172
+ written as upper-case quoted identifiers, which name the same thing.
173
+
174
+ dbt-s-layer skips the semantic view of a semantic model where Snowflake would read an expression
175
+ differently from MetricFlow: Snowflake resolves a bare name to a dimension or metric of the view
176
+ before a column, so a dimension `amount AS amount * 100` would change a metric `SUM(amount)`.
177
+ `generate` prints a `WARN semantic views: skipped sem__<name>: ...` line saying why, and writes
178
+ the exports and the other views as usual. Rename the dimension, or make its `expr` exactly its
179
+ column. A metric named like a dimension of its semantic model is skipped the same way.
180
+
181
+ ### Install the package
182
+
183
+ Add `dbt_semantic_view` to your `packages.yml` and run `dbt deps`:
184
+
185
+ ```yaml
186
+ packages:
187
+ - package: Snowflake-Labs/dbt_semantic_view
188
+ version: [">=1.0.6", "<1.1.0"]
189
+ ```
190
+
191
+ If your network blocks the hub's GitHub downloads, the `git:` form works too:
192
+
193
+ ```yaml
194
+ packages:
195
+ - git: https://github.com/Snowflake-Labs/dbt_semantic_view.git
196
+ revision: v1.0.6
197
+ ```
198
+
199
+ Without it, `dbt parse` and `dbt compile` still succeed but `dbt run` fails on the `sem__`
200
+ models, so `generate`, `check` and `doctor` warn when it is missing. `static_analysis='off'`
201
+ stops Fusion from parsing the DDL as a query. The generated models compile on dbt Core 1.12 and
202
+ Fusion 2.0.8, and the test project's views, tags included, have been built on a Snowflake
203
+ account with Fusion 2.0.9.
204
+
205
+ ### Snowflake tags
206
+
207
+ A dimension or metric with an [`s_layer` block](#describing-what-a-field-means-s_layer) carries
208
+ it into the view. Its `synonyms` become `WITH SYNONYMS`, and three tags say what it means:
209
+
210
+ | Tag | Value |
211
+ | --------------- | ------------------------------------------------------------------------ |
212
+ | `S_LAYER_KIND` | the block's `value.kind`, such as `currency` |
213
+ | `S_LAYER_LABEL` | the member's dbt `label`, when it has one |
214
+ | `S_LAYER_SPEC` | the rest of the block as compact JSON (left out when there is no rest) |
215
+
216
+ ```sql
217
+ orders.revenue AS SUM(amount) WITH SYNONYMS = ('sales', 'turnover')
218
+ WITH TAG (S_LAYER.DBT.S_LAYER_KIND = 'currency', S_LAYER.DBT.S_LAYER_LABEL = 'Revenue',
219
+ S_LAYER.DBT.S_LAYER_SPEC = '{"value":{"currency":"USD"}}')
220
+ ```
221
+
222
+ Members without a block get no tags, so a project with no blocks needs nothing below. An
223
+ `S_LAYER_LABEL` or `S_LAYER_SPEC` longer than Snowflake's 256-character tag limit is never
224
+ truncated: `generate` stops with an error naming every such member.
225
+
226
+ The tag objects must exist before the views are built. They live in
227
+ `<target database>.<target schema>` unless you set the `s_layer_tag_schema` var to another
228
+ `<database>.<schema>`. Create them with these `on-run-start` hooks in `dbt_project.yml`
229
+ (`generate` warns when a tag name is missing from them; if you create the tags some other way,
230
+ such as with a macro, it keeps warning):
231
+
232
+ ```yaml
233
+ on-run-start:
234
+ - "create schema if not exists {{ var('s_layer_tag_schema', target.database ~ '.' ~ target.schema) }}"
235
+ - "create tag if not exists {{ var('s_layer_tag_schema', target.database ~ '.' ~ target.schema) }}.S_LAYER_KIND"
236
+ - "create tag if not exists {{ var('s_layer_tag_schema', target.database ~ '.' ~ target.schema) }}.S_LAYER_LABEL"
237
+ - "create tag if not exists {{ var('s_layer_tag_schema', target.database ~ '.' ~ target.schema) }}.S_LAYER_SPEC"
238
+ ```
239
+
240
+ Object tagging needs Snowflake Enterprise Edition or higher. Read the tags back with
241
+ `TAG_REFERENCES`, one member at a time: `'<db>.<schema>.<view>!<TABLE>.<MEMBER>'` with the domain
242
+ `'SEMANTIC DIMENSION'` or `'SEMANTIC METRIC'` (`'<view>!<METRIC>'` for a view-level metric).
243
+
244
+ ## Metric views (Databricks)
245
+
246
+ On a Databricks target, each semantic model becomes `sem__<semantic_model>.sql`, which
247
+ dbt-databricks 1.12.0 or later builds as a Unity Catalog
248
+ [metric view](https://docs.databricks.com/aws/en/metric-views/) with its `metric_view`
249
+ materialization. No extra package is needed. The model body is the metric view's YAML
250
+ definition. For `orders` it looks like this:
251
+
252
+ ```yaml
253
+ # Generated by dbt-s-layer from semantic model 'orders'. Do not edit: ...
254
+ {{ config(materialized='metric_view', static_analysis='off') }}
255
+
256
+ version: 1.1
257
+ comment: "One row per order."
258
+ source: "{{ ref('orders') }}"
259
+ joins:
260
+ - name: "customers"
261
+ source: "{{ ref('customers', v=2) }}"
262
+ "on": "source.customer_id = customers.customer_id"
263
+ dimensions:
264
+ - name: "order"
265
+ expr: "source.order_id"
266
+ - name: "ordered_at"
267
+ expr: "source.ordered_at"
268
+ - name: "customer__country"
269
+ expr: "customers.country"
270
+ measures:
271
+ - name: "order_count"
272
+ comment: "Distinct orders."
273
+ expr: "COUNT(DISTINCT source.order_id)"
274
+ - name: "revenue"
275
+ display_name: "Revenue"
276
+ expr: "SUM(source.amount)"
277
+ - name: "average_order_value"
278
+ expr: "MEASURE(`revenue`) / NULLIF(MEASURE(`order_count`), 0)"
279
+ ```
280
+
281
+ It covers the same tables, dimensions and metrics as the Snowflake view, with these
282
+ differences:
283
+
284
+ - **Joins.** The semantic model is the metric view's `source`; the models it joins to are
285
+ `joins`, and a second hop is nested under the first.
286
+ - **Names.** A metric view has one namespace for its dimensions and measures, so a joined
287
+ model's dimensions are named the way MetricFlow names them in a query: `customer__country`,
288
+ or `order__customer__country` two hops away. Two names that differ only in case are an error,
289
+ and that view is skipped with a warning.
290
+ - **Expressions.** A plain column is written `source.<column>` or `<join>.<column>`. Any other
291
+ `expr` on the semantic model itself is copied as written, so write it in Databricks SQL. A
292
+ joined model's dimension whose `expr` is not a plain column is left out with a warning.
293
+ - **Measures.** Ratio and derived metrics use `MEASURE()` on their inputs. A non-additive
294
+ dimension becomes a `window` with `semiadditive: last` (`window_choice: max`) or `first`
295
+ (`min`). Labels become `display_name` and descriptions `comment`.
296
+ - **Private metrics.** Metric views have no hidden measures. A private metric is left out,
297
+ unless a ratio or derived metric uses it: then it is in the view, with a warning saying so.
298
+ - **A semantic model named `source`** cannot be joined, because the root table has that name;
299
+ views that would join it are skipped with a warning.
300
+
301
+ Metric view spec 1.1 needs Unity Catalog and Databricks Runtime 17.3 or later (or a SQL
302
+ warehouse that supports it). With dbt-databricks older than 1.12.0, `dbt parse` and
303
+ `dbt compile` still succeed but `dbt run` fails on the `sem__` models, so `generate`, `check`
304
+ and `doctor` warn. The generated models have been built on a Databricks SQL warehouse with
305
+ dbt Core 1.12.5 + dbt-databricks 1.12.7 and with Fusion 2.0.8, and every measure matched plain
306
+ SQL over the same tables.
307
+
308
+ ### Databricks tags
309
+
310
+ A dimension or metric with an [`s_layer` block](#describing-what-a-field-means-s_layer) gets
311
+ its `synonyms` as the field's `synonyms` (at most 10, each up to 255 characters), and two
312
+ Unity Catalog column tags on the metric view:
313
+
314
+ | Tag | Value |
315
+ | -------------- | ---------------------------------------------------------------------- |
316
+ | `S_LAYER_KIND` | the block's `value.kind`, such as `currency` |
317
+ | `S_LAYER_SPEC` | the rest of the block as compact JSON (left out when there is no rest) |
318
+
319
+ The dbt `label` is already the field's `display_name`, so it has no tag. A metric view cannot
320
+ carry column tags in its definition, so the model sets them in a `post_hook` after every
321
+ build, one `alter table ... alter column ... set tags` per field:
322
+
323
+ ```yaml
324
+ {{ config(
325
+ materialized='metric_view',
326
+ static_analysis='off',
327
+ view_update_via_alter=false,
328
+ post_hook=[
329
+ 'alter table {{ this }} alter column `status` set tags (\'S_LAYER_KIND\' = \'category\')'
330
+ ]
331
+ ) }}
332
+ ```
333
+
334
+ The view is always rebuilt with `create or replace`, which drops every column tag, so a tag a
335
+ block no longer has does not linger. A synonym list or `S_LAYER_SPEC` over the limits stops
336
+ `generate` with an error naming every such member. Members without a block get no tags or
337
+ synonyms. Read the tags back from `<catalog>.information_schema.column_tags`, filtering on
338
+ `schema_name` and `table_name`.
339
+
340
+ ## Semantic views (DuckDB)
341
+
342
+ On a DuckDB target, each semantic model becomes `sem__<semantic_model>.sql`, which the
343
+ [`duckdb_semantic_views`](https://github.com/s-layer/dbt-duckdb-semantic-views) package builds
344
+ as a semantic view of the [`semantic_views`](https://github.com/s-layer/duckdb-semantic-views)
345
+ extension. The body is the `CREATE SEMANTIC VIEW` clause list, as on Snowflake. For `orders`
346
+ it looks like this:
347
+
348
+ ```sql
349
+ -- Generated by dbt-s-layer from semantic model 'orders'. Do not edit: ...
350
+ {{ config(materialized='semantic_view', static_analysis='off') }}
351
+
352
+ TABLES (
353
+ orders AS {{ ref('orders') }}
354
+ PRIMARY KEY (order_id),
355
+ customers AS {{ ref('customers', v=2) }}
356
+ PRIMARY KEY (customer_id)
357
+ )
358
+ RELATIONSHIPS (
359
+ orders_to_customers AS orders (customer_id) REFERENCES customers (customer_id)
360
+ )
361
+ DIMENSIONS (
362
+ orders.order AS orders.order_id,
363
+ orders.order_month AS date_trunc('month', orders.ordered_at),
364
+ orders.status AS orders.status WITH SYNONYMS = ('order status'),
365
+ customers.customer__country AS customers.country
366
+ )
367
+ METRICS (
368
+ orders.order_count AS COUNT(DISTINCT orders.order_id) COMMENT = 'Distinct orders.',
369
+ orders.revenue AS SUM(orders.amount) WITH SYNONYMS = ('sales', 'turnover'),
370
+ average_order_value AS revenue / NULLIF(order_count, 0)
371
+ )
372
+ ```
373
+
374
+ It covers the same tables, dimensions and metrics as the Snowflake view, with these
375
+ differences:
376
+
377
+ - **Names.** Dimensions and metrics share one case-insensitive namespace per view, so a joined
378
+ model's dimensions are named the way MetricFlow names them in a query (`customer__country`),
379
+ as on Databricks. Names are written bare, even reserved words like `order`; only `as` and
380
+ names that are not lower-case letters, digits and underscores are quoted.
381
+ - **Expressions.** In a view of more than one table, DuckDB binds an unqualified column against
382
+ every table, so a column two tables share (`ordered_at`, `order_id`) fails at query time.
383
+ dbt-s-layer therefore qualifies every column an `expr` reads with its table:
384
+ `date_trunc('month', ordered_at)` becomes `date_trunc('month', orders.ordered_at)`. Keywords,
385
+ function names, type names, date parts, `INTERVAL` units and names you qualified yourself are
386
+ left alone. An `expr` with a lambda (`x -> ...`, `lambda x: ...`) or a subquery cannot be read
387
+ that way, so its member is left out with a warning, along with any metric built on it. A view
388
+ of one table keeps every `expr` as written.
389
+ - **Table aliases** are the semantic model names. DuckDB-reserved names get `_t` (a semantic
390
+ model `order` is the table `order_t`), because the extension cannot query a quoted alias. You
391
+ can use the alias in queries, as in `orders.*`.
392
+ - **Metrics.** Ratio and derived metrics name their inputs bare. Labels have no place in a
393
+ DuckDB semantic view and are dropped; descriptions become `COMMENT`s.
394
+ - **S-LAYER.** A member's `s_layer` block becomes `WITH SYNONYMS` and tags, as on Snowflake
395
+ (see [DuckDB tags](#duckdb-tags)).
396
+
397
+ ### DuckDB tags
398
+
399
+ A dimension or metric with an [`s_layer` block](#describing-what-a-field-means-s_layer) gets
400
+ the same three tags as on Snowflake (see [Snowflake tags](#snowflake-tags)), after its comment
401
+ and synonyms:
402
+
403
+ ```sql
404
+ orders.revenue AS SUM(orders.amount) WITH SYNONYMS = ('sales', 'turnover')
405
+ WITH TAG (S_LAYER_KIND = 'currency', S_LAYER_LABEL = 'Revenue',
406
+ S_LAYER_SPEC = '{"value":{"currency":"USD"}}')
407
+ ```
408
+
409
+ DuckDB stores tag names as written, so there are no tag objects to create and no
410
+ `on-run-start` hooks to add. Read the tags back from the `TAGS` rows of
411
+ `describe_semantic_view('sem__orders')`. Values have the same 256-character limit as on
412
+ Snowflake, and `generate` stops with an error naming every member over it.
413
+
414
+ Tags need extension 0.17 or later. An older extension does not reject the clause: it keeps it
415
+ as part of the member's expression, and the member then fails when it is queried. So each model
416
+ asks DuckDB which extension version is loaded when dbt runs it, and writes the tags only on 0.17
417
+ or later. On an older extension you get the synonyms and comments without the tags. `dbt parse`
418
+ runs no query and leaves the tags out.
419
+
420
+ To decide yourself, set the `s_layer_duckdb_tags` var in `dbt_project.yml`. Set it to `true`
421
+ to keep the tags on a local build of the extension, whose version is a commit hash. Set it to
422
+ `false` to never write them:
423
+
424
+ ```yaml
425
+ vars:
426
+ s_layer_duckdb_tags: true
427
+ ```
428
+
429
+ The tag values are checked against the 256-character limit whether or not they end up written.
430
+ A member that is left out of the view (see the differences above) is not checked.
431
+
432
+ ### Install the package and the extension
433
+
434
+ The package is not on dbt hub yet, so add it from GitHub and run `dbt deps`:
435
+
436
+ ```yaml
437
+ packages:
438
+ - git: https://github.com/s-layer/dbt-duckdb-semantic-views.git
439
+ revision: afd0980e70800f630aae32f40ee41bc0812e75f4
440
+ ```
441
+
442
+ Without it, `dbt parse` and `dbt compile` still succeed but `dbt run` fails on the `sem__`
443
+ models, so `generate`, `check` and `doctor` warn when it is missing.
444
+
445
+ The extension has to be loaded in every dbt run. These `on-run-start` hooks in
446
+ `dbt_project.yml` work on dbt Core and Fusion:
447
+
448
+ ```yaml
449
+ on-run-start:
450
+ - "INSTALL semantic_views FROM community"
451
+ - "LOAD semantic_views"
452
+ ```
453
+
454
+ On dbt Core, dbt-duckdb's profile setting `extensions: [{name: semantic_views, repo: community}]`
455
+ does the same. Which extension version you get depends on your DuckDB:
456
+
457
+ | DuckDB | Extension | Notes |
458
+ | ------ | --------- | ----- |
459
+ | 2.0.1 | 0.21 | `SUM` over integers returns `HUGEINT` (`BIGINT` before 0.15). |
460
+ | 2.0.0 | 0.19 | As for 2.0.1. An extension installed earlier may still be 0.16 to 0.18 until you run `UPDATE EXTENSIONS`; member tags need 0.17. |
461
+ | 1.5.6 | 0.13 | The oldest supported with dbt Core. No member tags. |
462
+ | 1.5.4 (inside dbt Fusion 2.0.8 and 2.0.9) | 0.11 | Best effort. No member tags. Creates every view in the default schema, ignoring `+schema`, so keep `sem__` names unique per database. |
463
+
464
+ Query a view with `semantic_view('sem__orders', dimensions := [...], metrics := [...])`. From
465
+ 0.16 on, `SEMANTIC_VIEW(sem__orders DIMENSIONS ... METRICS ...)` works too. A metric with a non-additive
466
+ dimension cannot be queried together with a `COUNT(DISTINCT)` or percentile metric.
467
+
468
+ The generated models have been built with `dbt build` on dbt Core 1.12.6 + dbt-duckdb 1.11.1
469
+ (DuckDB 2.0.0, extension 0.19) and on Fusion 2.0.8 (extension 0.11). Every dimension and metric
470
+ of the test project's views answers on extensions 0.11 and 0.13 (no tags) and on 0.19 and 0.21,
471
+ where `DESCRIBE` returns every tag as written.
472
+
473
+ ## Describing what a field means (`s_layer`)
474
+
475
+ A metric, dimension or entity can say what its values mean in an `s_layer` block under
476
+ `config.meta`: a currency in USD, a fraction to show as a percentage, a duration in seconds.
477
+ The vocabulary is defined by
478
+ [s-layer-semantic-formats](https://github.com/s-layer/semantic-formats), which lists every
479
+ kind and key.
480
+
481
+ ```yaml
482
+ metrics:
483
+ - name: revenue
484
+ label: Revenue
485
+ config:
486
+ meta:
487
+ s_layer:
488
+ value: {kind: currency, currency: USD}
489
+ display: {decimals: {max: 0}}
490
+ synonyms: [sales, turnover]
491
+ ```
492
+
493
+ `generate` and `check` validate every block and stop with an error naming each bad one, so
494
+ nothing reaches the warehouse. Beyond the vocabulary's own rules:
495
+
496
+ - Set the label with dbt's `label:`, not in the block.
497
+ - A time dimension needs kind `date` or `datetime`. Its `time.grain` comes from the
498
+ dimension's `time_granularity`; a different grain in the block is an error.
499
+ - A metric with a `non_additive_dimension` already says how it adds up, so its block leaves
500
+ `aggregation` out.
501
+ - Measures' meta is not read (Fusion copies a metric's meta onto the measure it generates).
502
+ - An entity's block is read from the entity's own `config.meta` only. dbt-s-layer merges
503
+ column meta into dimensions, not entities.
504
+
505
+ ## Left out of semantic and metric views
506
+
507
+ Each of these is skipped with one warning naming it; the rest of the view is still generated.
508
+
509
+ | Left out | Why |
510
+ |---|---|
511
+ | Cumulative metrics | A window metric is partitioned by the queried dimensions, not a time spine. Use an export. |
512
+ | Conversion metrics | No semantic view equivalent. |
513
+ | Metric filters (on a metric or its input) | Would need the `{{ Dimension(...) }}` filter rendered against the view's columns. |
514
+ | Non-additive dimensions with `window_groupings` | The warehouse picks the last rows per queried dimensions, not per entity. |
515
+ | Natural entities (validity windows) | No semantic view equivalent. |
516
+ | Approximate discrete percentiles (Snowflake, DuckDB) | Neither has such a function. |
517
+ | Approximate continuous percentiles (Databricks) | Databricks has no such function. |
518
+ | Ratio and derived metrics with an offset, a filter, or inputs from another semantic model or another derived metric | Only metrics of the same view can be combined without changing their meaning. |
519
+ | `fill_nulls_with`, `join_to_timespine` | Ignored (with a warning); the metric is generated without them. |
520
+ | An `expr` with a lambda or a subquery, in a DuckDB view of more than one table | dbt-s-layer cannot tell which of its names are columns, which DuckDB needs qualified (see [Semantic views (DuckDB)](#semantic-views-duckdb)). Metrics built on such a member are left out too. |
521
+
522
+ ## Pre-commit hook
523
+
524
+ The `dbt-s-layer` hook regenerates the models when you commit a change to your semantic YAML, so the generated files never fall behind. Add it to your repository's `.pre-commit-config.yaml`:
525
+
526
+ ```yaml
527
+ repos:
528
+ - repo: https://github.com/s-layer/dbt-s-layer
529
+ rev: v1.0.0
530
+ hooks:
531
+ - id: dbt-s-layer
532
+ ```
533
+
534
+ Then `pre-commit install` (or `prek install`). On a commit that stages semantic YAML, the hook:
535
+
536
+ 1. finds the dbt project of each staged file: the nearest `dbt_project.yml`, unless a project above it lists that directory as a `local:` package in `packages.yml` or `dependencies.yml`, in which case the installing project (a project in a subdirectory works, and a package that names no `profile` belongs to the nearest project above it that does),
537
+ 2. runs `dbt parse` in it. A project that declares legacy-spec `semantic_models:` (itself, or in a package it installs) is parsed with dbt Core, since Fusion ignores them; the hook stops with an error if `dbtf`/`dbt` on `PATH` offers no dbt Core >= 1.7. Any other project is parsed with `dbtf` if it is on `PATH`, else `dbt`. `--dbt` overrides both,
538
+ 3. runs `dbt-s-layer generate`. If `semantic_manifest.json` lacks a semantic model your YAML declares (a parse with the wrong engine), the hook fails without writing or deleting anything,
539
+ 4. fails the commit if it wrote, changed or deleted anything, and lists the files. Stage them (`git add`) and commit again; the second run changes nothing and passes.
540
+
541
+ Only files that hold a `semantic_models:`, `semantic_model:`, `metrics:`, `saved_queries:` or `time_spine:` key, a `dbt_project.yml`, or a generated file trigger it. A commit without any of them skips the hook in a fraction of a second. A hand edit to a generated file is put back. Deleting a semantic YAML file does not trigger the hook (pre-commit only passes files that exist), so keep `dbt-s-layer check` in CI as well.
542
+
543
+ `dbt parse` needs a profile, as it always does. The hook passes `generate`'s options through `args`, and has two of its own:
544
+
545
+ ```yaml
546
+ - id: dbt-s-layer
547
+ args: [--target, dev, --profiles-dir, analytics/profiles, --dbt, .venv/bin/dbt]
548
+ ```
549
+
550
+ | Option | |
551
+ |---|---|
552
+ | `--dbt` | The executable that parses, for example a dbt Core in a virtualenv that is not activated. Paths are relative to the repository root. |
553
+ | `--no-parse` | Don't run `dbt parse`: something else parses first (another hook). `generate` still refuses artifacts older than the YAML. |
554
+ | `--project-dir`, `--output-dir`, `--target`, `--adapter`, `--profiles-dir` | As for `generate`. `--target` goes to `dbt parse` too. The hook finds `profiles.yml` once (`--profiles-dir`, else `DBT_PROFILES_DIR`, the repository root, the project, `~/.dbt`) and passes that directory to `dbt parse` as `--profiles-dir`, so both read the same file. |
555
+
556
+ pre-commit installs dbt-s-layer in its own environment, so it never touches the dbt you run. Your dbt engine still has to be on `PATH` (or named with `--dbt`).
557
+
558
+ **Speed.** On a generated project with 100 semantic models and 50 exports, on a 4-core Linux machine, the hook takes 4.0 to 4.4 s after a YAML edit with dbt Fusion 2.0.8, whose `dbt parse` takes 0.7 s. dbt Core's own `dbt parse` takes 5.4 to 6.6 s on the same project (more than half of it is dbt's start-up), so with dbt Core the hook takes 10 to 12 s. Saved queries are rendered in parallel on Linux and macOS (in forked processes, and only while dbt-s-layer runs a single thread); set `DBT_S_LAYER_JOBS=1` to use one process. If a worker process dies (out of memory, say), the run fails with an error that suggests that setting.
559
+
560
+ ## License
561
+
562
+ Apache-2.0. See [LICENSE](https://github.com/s-layer/dbt-s-layer/blob/develop/LICENSE).