Feature request: project-wide @DEF macro functions defined in SQL files
メンテナーはふだん 4 日以内に返信
まだ誰も着手していません。
評価
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 初心者へのやさしさ
- 57/100
調査の方向性
Start with _load_scripts in sqlmesh/core/loader.py and the injection path in load_sql_based_model in sqlmesh/core/model/definition.py; also review the existing model-local @DEF parsing and rendering flow. Implement loading of lambda-only @DEF files from macros/, including collision checks and cache invalidation, then inject only referenced shared definitions into each model's pre_statements. Done means shared macros render in models, local definitions override them, collisions fail at load time, and tests cover rendering, transitive dependencies, hashes, and cache invalidation.
索引モデルが issue の本文から書いたものです。
説明
Summary
Let users define @DEF lambda macros in a SQL file under macros/ and call them from any model. Today a @DEF only exists inside the model that declares it, and cannot be made globally available. I immediately preferred the in-model syntax of SQLMesh-native macros, and was genuinely surprised to learn that the current 'native' path for templating relied on Python f-strings. If the approach below sounds good, I'd be happy to open a draft PR!
Current status
| Need | Existing mechanism | Limitation |
|---|---|---|
| Shared values | Global/gateway variables in config |
JSON-like data (scalars, lists, dicts), not SQL expressions |
| Shared macro functions in SQLMesh syntax | — | @DEF is model-local; copying it into every model makes the copies drift apart |
| Shared macro functions in Python | macros/*.py with @macro() |
Requires Python for a one-line SQL expression |
| Shared macro functions in Jinja | {% macro %} blocks in macros/*.sql |
Mixes a second templating system into projects that otherwise use SQLMesh macros |
Python macros can already do this, so my main reason for proposing this feature is consistency and ease of use. Jinja syntax is ugly, and implementing Python macros for templated functions can be verbose. @DEF lambdas are the documented SQLMesh-native way to write a reusable expression, and they compose: @container_volume calls @area in the macro docs. The only missing piece is sharing them across models.
Proposed behavior
A user creates a definitions file, for example macros/finance.sqlm:
@DEF(nrr, (starting_mrr, expansion_mrr, churned_mrr) -> (starting_mrr + expansion_mrr - churned_mrr) / starting_mrr);
@DEF(pct_change, (curr, prev) -> (curr - prev) / NULLIF(prev, 0));
Any model can then call them:
MODEL (name finance.retention, kind FULL);
SELECT
account_id,
@nrr(starting_mrr, expansion_mrr, churned_mrr) AS nrr,
@pct_change(mrr, prev_mrr) AS mrr_growth
FROM finance.mrr
Scope: lambda @DEFs only. Scalar @DEFs whose value is a SQL expression could come later.
Proposal
A user creates a plain SQL definitions file in the macros/ folder, as today. We can then modify _load_scripts to include @DEF macros, using the behavior table below:
| File contents | Current behavior | Proposed behavior |
|---|---|---|
| Jinja only | Jinja macros loaded | Unchanged |
No @DEF or Jinja |
Ignored | Unchanged |
@DEF macros only |
Ignored | Loaded as globally available @DEF macros, with any non-@DEF statement throwing an error |
@DEF macros and Jinja |
@DEF macros silently ignored, Jinja loads normally |
Load time error to keep macro types separate |
This file would be populated with the current lambda syntax, shown below:
@DEF(nrr, (starting_mrr, expansion_mrr, churned_mrr) -> (starting_mrr + expansion_mrr - churned_mrr) / starting_mrr);
@DEF(pct_change, (curr, prev) -> (curr - prev) / NULLIF(prev, 0));
Any model could then call them:
MODEL (name finance.retention, kind FULL);
SELECT
account_id,
@nrr(starting_mrr, expansion_mrr, churned_mrr) AS nrr,
@pct_change(mrr, prev_mrr) AS mrr_growth
FROM finance.mrr
How it works
The loader injects each model's referenced definitions into that model's pre_statements, exactly where model_defaults.pre_statements and model-local @DEFs already go. Rendering, fingerprinting, categorization and state serialization then follow the existing @DEF path unchanged.
- Loading (
_load_scriptsinsqlmesh/core/loader.py): for each macros/*.sql file the loader already reads, classify it by content as in the table. Jinja-only files go to the Jinja extractor as today, @DEF-only files are parsed with d.parse, and mixed files raise an error undermacros/and parse each file withmodel_defaults.dialect. A standalone@DEF(...)already parses to aMacroDef. Raise a load-time error if a name collides with another shared definition, a built-in macro, or a Python macro. Include these files in_macros_max_mtimeso edits invalidate the model cache. Pass the resultingname -> MacroDefmap through the loader the wayjinja_macrosis passed. - Injection (
load_sql_based_modelinsqlmesh/core/model/definition.py): collect the macro names a model calls in its query, pre/post statements andon_virtual_update, minus names the model defines itself. Add any shared definitions that those definitions call. Prepend the result to the model'spre_statements. - Everything else is existing behavior:
- The injected SQL enters the data hash through
_data_hash_values_sql, so only models that use an edited definition get a new version. - Breaking vs. non-breaking is decided by comparing the rendered query.
@VARs and Python macros called inside an injected lambda are picked up by the existingmake_python_envscan, since pre-statements are scanned as data statements.- Shared definitions come first, so a model-local
@DEFwith the same name overrides them.
- The injected SQL enters the data hash through
This mirrors how Python macros already work. A project-wide registry is trimmed to what each model references, and that subset is stored on the model, hashed, and evaluated at render time. Python macros already appear in render_definition and plan diffs as a Python code block. Injected @DEFs would appear the same way, which shows the user every model affected by an edit.
Tests
- A model using a shared definition renders correctly.
- Editing a definition changes the data hash only of the models that use it, directly or through another shared definition.
- A model-local
@DEFoverrides a shared one. - Name collisions raise errors at load time.
- Editing a definitions file invalidates the model cache.
Out of scope for a first version
- Scalar
@DEFs (globalvariablescover most of those cases). - Audits, which evaluate their own
macro_definitions. before_all/after_allenvironment statements.- Python models.
- Using shared lambdas inside the
MODEL (...)block. Model-local@DEFs don't work there either.
- 主要言語
- Python
- スター
- 3.3k
- フォーク
- 471
- 平均マージ
- 6日 7時間
- マージ済み PR(30日)
- 35
環境構築
このプロジェクトの開発コンテナを、あなたの GitHub アカウントでブラウザ上に起動します。
- Dockerfile・Docker Compose ファイルなし
- プルリクエストのテンプレートあり
- コントリビューションガイドを読む
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
SQLMesh/sqlmesh のほかの issue
-
難易度 2/5 1〜3時間 初心者へのやさしさ 86/100
メンテナーはふだん 4 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 68/100
メンテナーはふだん 4 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 67/100
SQLMesh/sqlmesh#6008 · コメント 1 件 ·
メンテナーはふだん 4 日以内に返信
-
VSCode Extension: SQLMesh LSP crashes on startup: ImportError: cannot import name 'WorkspaceDiagnosticRefreshRequest' with lsprotocol 2025.x対応中かも @boomesh11 が 15 日前に担当しました。 オープンBug
難易度 2/5 1〜3時間 初心者へのやさしさ 66/100
メンテナーはふだん 4 日以内に返信
-
Improvement
難易度 1/5 1時間未満 初心者へのやさしさ 85/100
SQLMesh/sqlmesh#5696 · コメント 6 件 ·
メンテナーはふだん 4 日以内に返信
SQLMesh/sqlmesh の issue をすべて見る
似ている issue
-
[BUG][Low–Medium] founder_numbers.py silently reads a SAFE discount or pool target given as a fraction (0.2) as 0.2%対応中かも @sumitkhond111-del が今日担当しました。 オープンbug
難易度 2/5 1〜3時間 初心者へのやさしさ 72/100
bmad-code-org/BMAD-METHOD#3358 · コメント 1 件 ·
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 86/100
open-mmlab/mmcv#3352 ·
-
難易度 1/5 1時間未満 初心者へのやさしさ 68/100
OpenGithubs/weekly#263 ·
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 76/100
メンテナーはふだん 1 日以内に返信
-
comp/cli P3 type/feature
難易度 2/5 1〜3時間 初心者へのやさしさ 76/100
NousResearch/hermes-agent#162784 ·
メンテナーはふだん 1 日以内に返信