Skip to content

Commit 4e45d58

Browse files
committed
fix: keep macro kind folders when moves carry declaration layouts
Apply group-folder layout rules within a macro's python/ or sql/ folder, migrate the layout and move tests to kind folders and @py. calls, and teach the agent skill SQL macros and kind-prefixed calls.
1 parent 8543bd9 commit 4e45d58

10 files changed

Lines changed: 104 additions & 50 deletions

File tree

‎crates/sqlbuild-scopes/src/placement/_helpers/relocation.rs‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@ use std::collections::{HashMap, HashSet};
55
use crate::placement::_helpers::anchors::{
66
AnchorSets, UsagesByDeclaration, anchor_sets, usages_by_declaration,
77
};
8-
use crate::placement::_helpers::declaration_directory::declaration_directory;
8+
use crate::placement::_helpers::declaration_directory::{
9+
declaration_directory, declaration_file_directory,
10+
};
911
use crate::placement::_helpers::required::required_placement;
1012
use crate::placement::_helpers::role_layout::carried_path;
1113
use crate::placement::models::{PlacementIndex, Relocation, RequiredPlacement};
@@ -82,7 +84,9 @@ fn relocated_record(
8284
resource_kind: None,
8385
},
8486
};
85-
let (carried, requires_group): (String, bool) = carried_path(current, record, &directory);
87+
let file_directory: String =
88+
declaration_file_directory(record.identity.kind, scope, path.as_deref(), &record.path);
89+
let (carried, requires_group): (String, bool) = carried_path(current, record, &file_directory);
8690
let moved = DeclarationRecord {
8791
path: carried,
8892
scope,

‎crates/sqlbuild-scopes/src/placement/_helpers/role_layout.rs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
//! Where a carried declaration file lands inside its destination role folder.
22
3-
use crate::placement::_helpers::declaration_directory::declaration_directory;
3+
use crate::placement::_helpers::declaration_directory::declaration_file_directory;
44
use crate::placement::models::PlacementIndex;
55
use crate::scope_index::models::{DeclarationRecord, ScopeKind};
66
use sqlbuild_core::posix_path::main::posix_name::posix_name;
@@ -21,10 +21,11 @@ pub(crate) fn carried_path(
2121
directory: &str,
2222
) -> (String, bool) {
2323
let name: &str = posix_name(&record.path);
24-
let source: String = declaration_directory(
24+
let source: String = declaration_file_directory(
2525
record.identity.kind,
2626
record.scope,
2727
record.owning_path.as_deref(),
28+
&record.path,
2829
);
2930
let relative: &str = record
3031
.path

‎crates/sqlbuild-scopes/src/placement/tests/helpers.rs‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -128,30 +128,30 @@ fn shared_cents(cents_path: &str, labels_path: Option<&str>) -> PlacementIndex {
128128

129129
/// A grouped `cents` and an empty descendant-public role.
130130
pub(super) fn grouped_cents_empty_role() -> PlacementIndex {
131-
shared_cents("models/sales/_sqlbuild/_macros/money/cents.py", None)
131+
shared_cents("models/sales/_sqlbuild/_macros/python/money/cents.py", None)
132132
}
133133

134134
/// A grouped `cents` and a descendant-public role keeping its files in groups.
135135
pub(super) fn grouped_cents_grouped_role() -> PlacementIndex {
136136
shared_cents(
137-
"models/sales/_sqlbuild/_macros/money/cents.py",
138-
Some("models/sales/_sqlbuild/macros/text/labels.py"),
137+
"models/sales/_sqlbuild/_macros/python/money/cents.py",
138+
Some("models/sales/_sqlbuild/macros/python/text/labels.py"),
139139
)
140140
}
141141

142142
/// A direct `cents` and a descendant-public role keeping its files in groups.
143143
pub(super) fn direct_cents_grouped_role() -> PlacementIndex {
144144
shared_cents(
145-
"models/sales/_sqlbuild/_macros/cents.py",
146-
Some("models/sales/_sqlbuild/macros/text/labels.py"),
145+
"models/sales/_sqlbuild/_macros/python/cents.py",
146+
Some("models/sales/_sqlbuild/macros/python/text/labels.py"),
147147
)
148148
}
149149

150150
/// A grouped `cents` and a descendant-public role keeping its files directly.
151151
pub(super) fn grouped_cents_direct_role() -> PlacementIndex {
152152
shared_cents(
153-
"models/sales/_sqlbuild/_macros/money/cents.py",
154-
Some("models/sales/_sqlbuild/macros/labels.py"),
153+
"models/sales/_sqlbuild/_macros/python/money/cents.py",
154+
Some("models/sales/_sqlbuild/macros/python/labels.py"),
155155
)
156156
}
157157

‎crates/sqlbuild-scopes/src/placement/tests/test_placement.rs‎

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -158,25 +158,33 @@ fn given_destination_role_layout_when_carrying_declaration_then_its_shape_is_mat
158158
description: "an empty destination role keeps the source group",
159159
index: grouped_cents_empty_role,
160160
moves: &[("orders", "models/sales/eu/orders.sql")],
161-
expected_relocations: &[(0, "models/sales/_sqlbuild/macros/money/cents.py", false)],
161+
expected_relocations: &[(
162+
0,
163+
"models/sales/_sqlbuild/macros/python/money/cents.py",
164+
false,
165+
)],
162166
},
163167
CarriedLayoutTestCase {
164168
description: "a grouped destination role keeps the source group",
165169
index: grouped_cents_grouped_role,
166170
moves: &[("orders", "models/sales/eu/orders.sql")],
167-
expected_relocations: &[(0, "models/sales/_sqlbuild/macros/money/cents.py", false)],
171+
expected_relocations: &[(
172+
0,
173+
"models/sales/_sqlbuild/macros/python/money/cents.py",
174+
false,
175+
)],
168176
},
169177
CarriedLayoutTestCase {
170178
description: "a direct source in a grouped destination role needs a group",
171179
index: direct_cents_grouped_role,
172180
moves: &[("orders", "models/sales/eu/orders.sql")],
173-
expected_relocations: &[(0, "models/sales/_sqlbuild/macros/cents.py", true)],
181+
expected_relocations: &[(0, "models/sales/_sqlbuild/macros/python/cents.py", true)],
174182
},
175183
CarriedLayoutTestCase {
176184
description: "a direct destination role drops the source group",
177185
index: grouped_cents_direct_role,
178186
moves: &[("orders", "models/sales/eu/orders.sql")],
179-
expected_relocations: &[(0, "models/sales/_sqlbuild/macros/cents.py", false)],
187+
expected_relocations: &[(0, "models/sales/_sqlbuild/macros/python/cents.py", false)],
180188
},
181189
CarriedLayoutTestCase {
182190
description: "moving every user together places the macro once at their new folder",
@@ -185,7 +193,11 @@ fn given_destination_role_layout_when_carrying_declaration_then_its_shape_is_mat
185193
("orders", "models/sales/eu/orders.sql"),
186194
("refunds", "models/sales/eu/refunds.sql"),
187195
],
188-
expected_relocations: &[(0, "models/sales/eu/_sqlbuild/_macros/money/cents.py", false)],
196+
expected_relocations: &[(
197+
0,
198+
"models/sales/eu/_sqlbuild/_macros/python/money/cents.py",
199+
false,
200+
)],
189201
},
190202
];
191203
for test_case in test_cases {

‎src/sqlbuild/.agents/skills/sqlbuild/SKILL.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@ plan, and ships tools for proving a change is correct. Use those tools; do not s
1414
- Models are SQL files with a `MODEL (...)` header, then one query. No Jinja.
1515
- References are `__ref("model")`, `__source("source_name")`, `__seed("seed")`. Never hardcode a
1616
relation SQLBuild manages.
17-
- Macros are plain Python functions called as `@macro_name("arg")`. Constants and enums are
18-
`@const("name")` and `@enum("name").MEMBER`.
17+
- Macros are typed SQL fragments called as `@sql.name(arg)` or Python functions called as
18+
`@py.name("arg")`. Constants and enums are `@const("name")` and `@enum("name").MEMBER`.
1919
- Config, column schemas, contracts and audits live in the `MODEL()` header, not YAML.
2020
- Every model, scenario, seed, source, function, named hook, Python node and provider needs a
2121
non-empty description (`MODEL (description "...")`, `description:` in YAML, a docstring or
@@ -181,7 +181,9 @@ parameterised cases, scenarios, audits and Rules.
181181
swap for tables, and on each delta before DML for incremental models. Attach built-ins such as
182182
`not_null` and `unique` in the column schema.
183183

184-
**Macros, enums and constants.** Macros are Python functions returning SQL strings; arguments are
184+
**Macros, enums and constants.** SQL macros (`macros/sql/`, one per file, called `@sql.name(...)`)
185+
are typed, logic-free SQL fragments; prefer them when no logic is needed. Python macros
186+
(`macros/python/`, called `@py.name(...)`) are functions returning SQL strings; arguments are
185187
Python literals, and SQL expressions are passed as quoted strings. Public functions become macros;
186188
prefix helpers with `_`. Macros work in model SQL, SQL hooks, tests, scenarios, audits and SQL
187189
functions, but not in ordinary `MODEL()` config fields. Placement decides visibility. Read

‎src/sqlbuild/.agents/skills/sqlbuild/references/macros-and-declarations.md‎

Lines changed: 37 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,30 +11,58 @@
1111

1212
## Macros
1313

14-
Macros are plain Python functions that return final SQL strings. Every public function in a macro
15-
file is callable from SQL as `@name(...)`; prefix helpers, constants and classes with `_`.
14+
Every macro call names its kind: `@sql.name(...)` for a SQL macro, `@py.name(...)` for a Python
15+
macro. A bare `@name(...)` fails with `P014`, and a macro file directly under a `macros/` folder
16+
fails with `D013`.
17+
18+
**SQL macros** live in `macros/sql/`, one per file named after the macro. A `MACRO (...)` header
19+
declares typed arguments; the body is an expression, a `WITH` list of CTEs or a `SELECT` list of
20+
columns. Prefer them whenever no logic is needed: the compiler checks every call's arguments
21+
against the caller's column types.
22+
23+
```sql
24+
-- macros/sql/cents_to_dollars.sql
25+
MACRO (
26+
description "Cents to dollars",
27+
arguments (amount_cents BIGINT, places INT CONST DEFAULT 2),
28+
returns DECIMAL(18, 2),
29+
);
30+
31+
ROUND(CAST(@amount_cents AS DECIMAL(18, 4)) / 100, @places)
32+
```
33+
34+
```sql
35+
SELECT order_id, @sql.cents_to_dollars(amount_cents) AS amount_dollars
36+
FROM __ref("stg_orders")
37+
```
38+
39+
Full reference: [docs/concepts/macros/sql-macros.md](docs/concepts/macros/sql-macros.md).
40+
41+
**Python macros** live in `macros/python/` and are plain Python functions that return final SQL
42+
strings. Every public function in a macro file is callable from SQL as `@py.name(...)`; prefix
43+
helpers, constants and classes with `_`.
1644

1745
```python
18-
# macros/currency.py
46+
# macros/python/currency.py
1947
def cents_to_dollars(expression: str) -> str:
2048
return f"ROUND(CAST({expression} AS DOUBLE) / 100, 2)"
2149
```
2250

2351
```sql
24-
SELECT order_id, @cents_to_dollars("amount_cents") AS amount_dollars
52+
SELECT order_id, @py.cents_to_dollars("amount_cents") AS amount_dollars
2553
FROM __ref("stg_orders")
2654
```
2755

2856
- Arguments are Python literals: strings, numbers, `True`/`False`, lists, dicts, `None`, or another
2957
macro call. Pass SQL expressions and column names as quoted strings. Keyword arguments work:
30-
`@mock_orders(count=5, status="completed")`.
58+
`@py.mock_orders(count=5, status="completed")`.
3159
- Pass the models, sources and seeds a macro reads as typed arguments:
32-
`@union_all([__ref("orders_eu"), __ref("orders_us")])`. The macro receives `SqlResourceRef`
60+
`@py.union_all([__ref("orders_eu"), __ref("orders_us")])`. The macro receives `SqlResourceRef`
3361
values (`sqlbuild.refs`); formatting one into SQL renders the relation, and the dependency
3462
belongs to the calling model.
3563
- A macro used in SQL must return a string, and its output is final SQL. Never return text
36-
containing another `@macro()` call; compose by calling the Python functions directly, including
37-
functions imported from other visible macro files (`from macros.currency import add_tax`).
64+
containing another `@py.macro()` call; compose by calling the Python functions directly, including
65+
functions imported from other visible macro files (`from macros.python.currency import add_tax`).
3866
- Never return `__ref()`, `__source()` or `__seed()` from a macro, including through a quoted
3967
string argument: it fails compile with `P006`. Only `[references] enforce_explicit = false` in
4068
`sqlbuild_project.toml` allows it, as a project-wide migration switch.
@@ -102,7 +130,7 @@ other models or named hooks.
102130

103131
| Location | Visible to |
104132
|---|---|
105-
| Top-level `macros/`, `enums/`, `constants/` | The whole project |
133+
| Top-level `macros/python/`, `macros/sql/`, `enums/`, `constants/` | The whole project |
106134
| `<folder>/_sqlbuild/macros/` (also `enums/`, `constants/`) | That folder and all folders below |
107135
| `<folder>/_sqlbuild/_macros/` (also `_enums/`, `_constants/`) | Files directly in that folder |
108136
| Underscored value in `MODEL()` | That model only |

‎tests/e2e/src/sqlbuild/cli/commands/main/refactor/helpers.py‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -130,11 +130,13 @@ def grouped_role_files(*, cents_path: str, labels_path: str) -> dict[str, str]:
130130

131131
return {
132132
"sqlbuild_project.toml": project_toml() + _LAYOUT_RULES,
133-
cents_path: CENTS_MACRO["models/staging/_sqlbuild/_macros/cents.py"],
133+
cents_path: CENTS_MACRO["models/staging/_sqlbuild/_macros/python/cents.py"],
134134
"models/staging/stg_order_cents.sql": CENTS_MACRO["models/staging/stg_order_cents.sql"],
135135
"models/staging/stg_order_refunds.sql": ORDER_REFUNDS[
136136
"models/staging/stg_order_refunds.sql"
137-
].replace("AS refund_cents\n", "AS refund_cents,\n @upper_label(\"'refund'\") AS label\n"),
137+
].replace(
138+
"AS refund_cents\n", "AS refund_cents,\n @py.upper_label(\"'refund'\") AS label\n"
139+
),
138140
labels_path: _LABEL_MACRO,
139141
"models/staging/eu/stg_order_labels.sql": _label_model("stg_order_labels"),
140142
}
@@ -151,7 +153,7 @@ def shared_cents_with_grouped_global_role() -> dict[str, str]:
151153
"sqlbuild_project.toml": project_toml() + _LAYOUT_RULES,
152154
**CENTS_MACRO,
153155
**ORDER_REFUNDS,
154-
"macros/text/labels.py": _LABEL_MACRO,
156+
"macros/python/text/labels.py": _LABEL_MACRO,
155157
"models/staging/stg_order_labels.sql": _label_model("stg_order_labels"),
156158
"models/marts/order_labels.sql": _label_model("order_labels"),
157159
}
@@ -161,19 +163,19 @@ def same_named_local_macros() -> dict[str, str]:
161163
"""Return two models in different folders, each using its own local ``helpers.py`` macro."""
162164

163165
return {
164-
"models/staging/_sqlbuild/_macros/helpers.py": CENTS_MACRO[
165-
"models/staging/_sqlbuild/_macros/cents.py"
166+
"models/staging/_sqlbuild/_macros/python/helpers.py": CENTS_MACRO[
167+
"models/staging/_sqlbuild/_macros/python/cents.py"
166168
],
167169
"models/staging/stg_order_cents.sql": CENTS_MACRO["models/staging/stg_order_cents.sql"],
168-
"models/marts/_sqlbuild/_macros/helpers.py": _LABEL_MACRO,
170+
"models/marts/_sqlbuild/_macros/python/helpers.py": _LABEL_MACRO,
169171
"models/marts/order_labels.sql": _label_model("order_labels"),
170172
}
171173

172174

173175
def _label_model(name: str) -> str:
174176
return (
175177
f"MODEL (description 'Test model {name}.',\n materialized view,\n);\n\n"
176-
'SELECT\n order_id,\n @upper_label("\'order\'") AS label\nFROM __ref("stg_orders")\n'
178+
'SELECT\n order_id,\n @py.upper_label("\'order\'") AS label\nFROM __ref("stg_orders")\n'
177179
)
178180

179181

‎tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_batch_moves.py‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
write_orders_project,
2828
)
2929

30-
_CENTS: str = "models/staging/_sqlbuild/_macros/cents.py"
30+
_CENTS: str = "models/staging/_sqlbuild/_macros/python/cents.py"
3131
_COMPILE_STARTS: tuple[str, ...] = (
3232
"Compiling project...",
3333
"Verifying the edited project compiles...",
@@ -41,7 +41,7 @@
4141
_EXPECTED_MOVED: dict[str, str] = {
4242
"models/staging/stg_order_cents.sql": "models/finance/stg_order_cents.sql",
4343
"models/staging/stg_order_refunds.sql": "models/finance/stg_order_refunds.sql",
44-
_CENTS: "models/finance/_sqlbuild/_macros/cents.py",
44+
_CENTS: "models/finance/_sqlbuild/_macros/python/cents.py",
4545
}
4646

4747

@@ -105,7 +105,9 @@ def test_given_moves_invalid_one_at_a_time_when_moved_together_then_one_verifica
105105
SingleMoveOfBatchE2ETestCase(
106106
description="moving one user alone needs a group in the top-level role",
107107
move=("stg_order_cents", "models/finance/"),
108-
expected_reason="macro:to_cents must move to macros/, which keeps its files in group",
108+
expected_reason=(
109+
"macro:to_cents must move to macros/python/, which keeps its files in group"
110+
),
109111
),
110112
],
111113
ids=lambda case: case.description,
@@ -178,9 +180,9 @@ def test_given_one_move_of_the_batch_alone_when_moving_then_it_is_refused(
178180
"models/finance/",
179181
),
180182
expected_reason=(
181-
"models/marts/_sqlbuild/_macros/helpers.py and "
182-
"models/staging/_sqlbuild/_macros/helpers.py would both move to "
183-
"models/finance/_sqlbuild/_macros/helpers.py; rename one of them first"
183+
"models/marts/_sqlbuild/_macros/python/helpers.py and "
184+
"models/staging/_sqlbuild/_macros/python/helpers.py would both move to "
185+
"models/finance/_sqlbuild/_macros/python/helpers.py; rename one of them first"
184186
),
185187
),
186188
],
@@ -210,7 +212,7 @@ def test_given_conflicting_moves_when_moved_together_then_batch_is_refused_and_n
210212
"Move 2 models",
211213
"├── stg_order_cents -> models/finance/stg_order_cents.sql",
212214
"└── stg_order_refunds -> models/finance/stg_order_refunds.sql",
213-
f"├── models/finance/_sqlbuild/_macros/cents.py (moved from {_CENTS})",
215+
f"├── models/finance/_sqlbuild/_macros/python/cents.py (moved from {_CENTS})",
214216
"Dry run: compiles, 3 files would change; nothing written",
215217
),
216218
),

‎tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_move_declarations.py‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -71,20 +71,22 @@
7171
model="stg_order_cents",
7272
extra_files=grouped_role_files(
7373
cents_path=_GROUPED_CENTS,
74-
labels_path="models/staging/_sqlbuild/macros/text/labels.py",
74+
labels_path="models/staging/_sqlbuild/macros/python/text/labels.py",
7575
),
7676
destination="models/staging/eu/",
77-
expected_moved={_GROUPED_CENTS: "models/staging/_sqlbuild/macros/money/cents.py"},
77+
expected_moved={
78+
_GROUPED_CENTS: "models/staging/_sqlbuild/macros/python/money/cents.py"
79+
},
7880
),
7981
DeclarationMoveE2ETestCase(
8082
description="a grouped macro drops its group in a direct destination role",
8183
model="stg_order_cents",
8284
extra_files=grouped_role_files(
8385
cents_path=_GROUPED_CENTS,
84-
labels_path="models/staging/_sqlbuild/macros/labels.py",
86+
labels_path="models/staging/_sqlbuild/macros/python/labels.py",
8587
),
8688
destination="models/staging/eu/",
87-
expected_moved={_GROUPED_CENTS: "models/staging/_sqlbuild/macros/cents.py"},
89+
expected_moved={_GROUPED_CENTS: "models/staging/_sqlbuild/macros/python/cents.py"},
8890
),
8991
],
9092
ids=lambda case: case.description,
@@ -119,11 +121,12 @@ def test_given_scoped_declarations_when_moving_model_then_they_follow_placement_
119121
description="a direct macro cannot join a grouped destination role",
120122
model="stg_order_cents",
121123
extra_files=grouped_role_files(
122-
cents_path=_CENTS, labels_path="models/staging/_sqlbuild/macros/text/labels.py"
124+
cents_path=_CENTS,
125+
labels_path="models/staging/_sqlbuild/macros/python/text/labels.py",
123126
),
124127
destination="models/staging/eu/",
125128
expected_message=(
126-
"macro:to_cents must move to models/staging/_sqlbuild/macros/, which keeps its "
129+
"macro:to_cents must move to models/staging/_sqlbuild/macros/python/, which keeps its "
127130
f"files in group folders, but {_CENTS} is not in a group; move it into a group "
128131
"folder of its current role first"
129132
),

‎tests/e2e/src/sqlbuild/cli/commands/main/refactor/test_unit_tests_follow_models.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@
4343
}
4444

4545
_SAMPLE_AMOUNT_MACRO: str = 'def sample_amount() -> str:\n return "{amount}"\n'
46-
_MARTS_MACRO: str = "tests/unit/marts/_sqlbuild/_macros/sample_amount.py"
46+
_MARTS_MACRO: str = "tests/unit/marts/_sqlbuild/_macros/python/sample_amount.py"
4747
_KEPT_NOTE: str = (
4848
"└── tests/unit/marts/test_order_facts__keeps_orders.sql kept in its folder: {declaration} "
4949
"would not resolve to the same declaration from tests/unit/reporting"
@@ -149,7 +149,7 @@ def test_given_dry_run_when_renaming_model_with_unit_test_then_reports_move_and_
149149
ScopedUnitTestMoveE2ETestCase(
150150
description="a folder-scoped test macro keeps the test in its folder",
151151
extra_files={_MARTS_MACRO: _SAMPLE_AMOUNT_MACRO.format(amount=25)},
152-
amount_sql="@sample_amount()",
152+
amount_sql="@py.sample_amount()",
153153
expected_path="tests/unit/marts/test_order_facts__keeps_orders.sql",
154154
expected_notes=(_KEPT_NOTE.format(declaration="macro:sample_amount"),),
155155
),

0 commit comments

Comments
 (0)