Skip to content

Commit 8db0f9e

Browse files
committed
fix: pass SQL macro arguments read through untyped sources
Treat a probe as unknown when any FROM or JOIN source in it cannot be typed, so stars over unnest() or table functions no longer report missing columns. Teach kind-prefixed macro calls in the remaining docs.
1 parent a2ee71a commit 8db0f9e

14 files changed

Lines changed: 110 additions & 29 deletions

File tree

‎README.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -167,15 +167,16 @@ SELECT
167167
o.order_id,
168168
o.customer_id,
169169
p.amount_cents AS total_cents,
170-
@cents_to_dollars("p.amount_cents") AS total_dollars
170+
@py.cents_to_dollars("p.amount_cents") AS total_dollars
171171
FROM __ref("stg_orders") o
172172
JOIN __ref("stg_payments") p USING (order_id)
173173
```
174174

175-
Macros are plain Python functions that return SQL, kept next to the models that use them:
175+
Python macros are plain functions that return SQL, kept next to the models that use them; SQL
176+
macros in `macros/sql/` cover logic-free fragments with typed, checked arguments:
176177

177178
```python
178-
# models/marts/_sqlbuild/_macros/currency.py
179+
# models/marts/_sqlbuild/_macros/python/currency.py
179180
def cents_to_dollars(column: str) -> str:
180181
"""Convert a cents integer column to a dollars decimal with two decimal places."""
181182
return f"ROUND(({column}) / 100.0, 2)"

‎crates/sqlbuild-analysis/src/query_analysis/_helpers/compatibility_types.rs‎

Lines changed: 45 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -62,31 +62,57 @@ fn evaluate_outputs(
6262
let mut relations = Relations::new();
6363
if let Some(schema) = schema {
6464
for table in &schema.tables {
65-
relations.insert(
66-
table.name.to_lowercase(),
67-
Rc::new(
68-
table
69-
.columns
70-
.iter()
71-
.map(|column| (column.name.clone(), Some(column.data_type.clone())))
72-
.collect(),
73-
),
74-
);
65+
relations.insert(table.name.to_lowercase(), Rc::new(table_outputs(table)));
7566
}
7667
}
7768
let context = TypeContext {
7869
functions,
7970
dialect,
8071
used_annotations: Cell::new(false),
72+
untyped_source: Cell::new(false),
8173
};
8274
let outputs = context.query(expression, &relations);
8375
(outputs, context.used_annotations.get())
8476
}
8577

78+
/// Outputs only when every `FROM` and `JOIN` source of the query, CTEs included, was typed.
79+
pub(super) fn infer_complete_outputs(
80+
expression: &Expression,
81+
schema: Option<&ValidationSchema>,
82+
functions: &HashMap<String, String>,
83+
dialect: DialectType,
84+
) -> Option<Outputs> {
85+
let mut relations = Relations::new();
86+
if let Some(schema) = schema {
87+
for table in &schema.tables {
88+
relations.insert(table.name.to_lowercase(), Rc::new(table_outputs(table)));
89+
}
90+
}
91+
let context = TypeContext {
92+
functions,
93+
dialect,
94+
used_annotations: Cell::new(false),
95+
untyped_source: Cell::new(false),
96+
};
97+
let outputs = context.query(expression, &relations);
98+
(!context.untyped_source.get()).then_some(outputs)
99+
}
100+
101+
/// A schema table's columns with their declared types.
102+
fn table_outputs(table: &polyglot_sql::SchemaTable) -> Outputs {
103+
table
104+
.columns
105+
.iter()
106+
.map(|column| (column.name.clone(), Some(column.data_type.clone())))
107+
.collect()
108+
}
109+
86110
struct TypeContext<'a> {
87111
functions: &'a HashMap<String, String>,
88112
dialect: DialectType,
89113
used_annotations: Cell<bool>,
114+
/// Whether a `FROM` or `JOIN` source could not be typed, so stars and columns may be missing.
115+
untyped_source: Cell<bool>,
90116
}
91117

92118
impl TypeContext<'_> {
@@ -162,6 +188,15 @@ impl TypeContext<'_> {
162188
.flat_map(|from| &from.expressions)
163189
.chain(select.joins.iter().map(|join| &join.this));
164190
for source in tables {
191+
let typed: bool = match unwrapped(source) {
192+
Expression::Values(_) => true,
193+
Expression::Subquery(subquery) => subquery.alias.is_some(),
194+
Expression::Table(table) => relations.contains_key(&table.name.name.to_lowercase()),
195+
_ => false,
196+
};
197+
if !typed {
198+
self.untyped_source.set(true);
199+
}
165200
if let Expression::Values(values) = unwrapped(source) {
166201
aliases.items.push((
167202
values

‎crates/sqlbuild-analysis/src/query_analysis/main/output_types.rs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@ use std::collections::HashMap;
22

33
use polyglot_sql::{DialectType, Expression, ParseOptions, ValidationSchema};
44

5-
use crate::query_analysis::compatibility_types::{NULL_TYPE, infer_outputs};
5+
use crate::query_analysis::compatibility_types::{NULL_TYPE, infer_complete_outputs};
66

7-
/// The output column names and inferred types of the one query in `sql`, without lineage.
7+
/// The output columns and inferred types of the one query in `sql`; `None` if a source is untyped.
88
#[must_use]
99
pub fn output_types(
1010
sql: &str,
@@ -25,7 +25,8 @@ pub fn output_types(
2525
}
2626
let expression: Expression = statements.pop()?;
2727
let mut outputs: Vec<(String, Option<String>)> = Vec::new();
28-
for (name, data_type) in infer_outputs(&expression, Some(schema), &HashMap::new(), dialect) {
28+
let inferred = infer_complete_outputs(&expression, Some(schema), &HashMap::new(), dialect)?;
29+
for (name, data_type) in inferred {
2930
outputs.push((name, data_type.filter(|value| !is_null_type(value))));
3031
}
3132
Some(outputs)

‎src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/interpolation.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ The rule is simple: if it's any SQL that will be executed, it uses `@`. If it's
3030
|--------|-------|----------|
3131
| `@enum("name").MEMBER` | Executable SQL | Compile time - expands to the validated enum member value |
3232
| `@const("name")` | Executable SQL | Compile time - expands to the named typed scalar, value list, native array, or object expression |
33-
| `@macro(args)` | Model SQL, SQL hooks, tests, audits, inline source expressions | Compile time - expands to macro return value |
33+
| `@sql.name(args)`, `@py.name(args)` | Model SQL, SQL hooks, tests, audits, inline source expressions | Compile time - expands to the macro's SQL |
3434
| `@@name` | Model SQL, SQL hooks, tests, audits, inline source expressions | Compile time - project variable substitution |
3535
| `@@ENV:NAME` | Model SQL, SQL hooks, tests, audits, inline source expressions | Compile time - environment variable |
3636
| `@@CTX:name` | SQL hooks only | Compile time - destination relation, target, run ID |
@@ -184,7 +184,7 @@ Use the quoted form for values rather than SQL identifiers or expressions:
184184
WHERE status = @'expected_status'
185185
```
186186

187-
This is distinct from `@@name` (project variables) and `@macro()` (macro calls), so there is no ambiguity. See [Audits](audits.md) for details on generic audit parameters.
187+
This is distinct from `@@name` (project variables) and `@sql.name()` or `@py.name()` (macro calls), so there is no ambiguity. See [Audits](audits.md) for details on generic audit parameters.
188188

189189
## Named SQL hook parameters
190190

‎src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/macros/composition-and-context.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ or `_macros/`.
7676

7777
## Macro output is final SQL
7878

79-
Do not return SQL containing another `@macro()` call:
79+
Do not return SQL containing another `@py.name()` call:
8080

8181
```python
8282
# Invalid: creates another macro-expansion layer.

‎src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/models/hooks/python.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ MODEL (
105105
SELECT 1 AS id
106106
```
107107

108-
Python hook arguments are ordinary configuration values and are not SQL-expanded. An argument containing `@@CTX:...` or `@macro()` reaches the function unchanged.
108+
Python hook arguments are ordinary configuration values and are not SQL-expanded. An argument containing `@@CTX:...` or `@py.name()` reaches the function unchanged.
109109

110110
## Signature validation
111111

‎src/sqlbuild/.agents/skills/sqlbuild/references/docs/feature-comparison.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ SQLBuild, dbt, and SQLMesh are all SQL pipeline frameworks. They share common gr
5151
| Rules and formatting | Compiler-integrated native and custom diagnostics, reasoned suppressions, and separate canonical formatting | External tools | Built-in formatter plus external linting |
5252
| Compiler-integrated Rules | Native and custom rules over compiler-owned SQL, models, dependencies, contracts, tests, and project paths | Project conventions through packages and external tooling | Built-in audits and external linting |
5353
| SQL transpilation | For local E2E replay into DuckDB | No | For cross-dialect model execution |
54-
| Python macros | `@macro()` syntax | No (Jinja only) | SQLMesh macro syntax |
54+
| Python macros | `@py.name()` syntax | No (Jinja only) | SQLMesh macro syntax |
5555
| Compiler-enforced declaration scopes | Project, descendant-public, exact-owner-private, and model-private tiers with offline `sqb scope` inspection | No lexical declaration scopes | No lexical declaration scopes |
5656
| Jinja support | No (Python macros instead) | Yes (core templating) | Yes |
5757

‎src/sqlbuild/.agents/skills/sqlbuild/references/testing.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ explicit (for example `SELECT *` from another CTE), SQLBuild compares every colu
6767
Helper CTEs can read other helpers and mocks by CTE name (for example `__ref__stg_orders`), so
6868
shared expected rows can live in one helper that both an `__expected__` CTE and an assertion use.
6969

70-
Macros work inside tests, so reusable mock generators such as `@mock_orders(count=5)` are normal.
70+
Macros work inside tests, so reusable mock generators such as `@py.mock_orders(count=5)` are normal.
7171
Tests can also target a macro, UDF or table function directly: defining `__macro_actual__`,
7272
`__udf_actual__` or `__table_fn_actual__` selects that mode without a `mode` header field; see
7373
[docs/concepts/testing.md](docs/concepts/testing.md) for those modes.

‎tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_build.py‎

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,34 @@
286286
query="SELECT order_id, later LIKE '2026-01-01 01:00:00%' FROM orders",
287287
expected_rows=[(2, True)],
288288
),
289+
SqlMacroBuildTestCase(
290+
description="relation_argument_with_a_star_over_unnest_is_not_checked",
291+
files={
292+
**CLEAN_ORDERS,
293+
**orders_model(
294+
"WITH orders_raw AS (\n"
295+
' SELECT o.order_id, o.updated_at, t.* FROM __ref("stg_orders") AS o\n'
296+
" CROSS JOIN unnest([false]) AS t(is_deleted)\n),\n"
297+
"@sql.clean_orders(orders_raw)\nSELECT order_id FROM latest\n"
298+
),
299+
},
300+
query="SELECT order_id FROM orders ORDER BY order_id",
301+
expected_rows=[(1,), (2,), (3,)],
302+
),
303+
SqlMacroBuildTestCase(
304+
description="relation_argument_with_a_star_over_a_table_function_is_not_checked",
305+
files={
306+
**CLEAN_ORDERS,
307+
**orders_model(
308+
"WITH orders_raw AS (\n"
309+
' SELECT o.order_id, o.updated_at, t.* FROM __ref("stg_orders") AS o\n'
310+
" CROSS JOIN range(1) AS t(is_deleted)\n),\n"
311+
"@sql.clean_orders(orders_raw)\nSELECT order_id FROM latest\n"
312+
),
313+
},
314+
query="SELECT order_id FROM orders ORDER BY order_id",
315+
expected_rows=[(1,), (2,), (3,)],
316+
),
289317
SqlMacroBuildTestCase(
290318
description="macro_body_constant_resolves_in_the_macro_folder_for_a_subfolder_caller",
291319
files=_BODY_SCOPED,
@@ -353,7 +381,7 @@ def test_given_any_spelling_of_list_calls_when_building_then_the_model_holds_the
353381
inspected_paths=("target/compiled/models/marts/orders.sql",),
354382
),
355383
SqlMacroCommandTestCase(
356-
description="typed_argument_in_a_later_union_branch_reads_that_branch",
384+
description="typed_argument_in_a_later_union_branch_is_not_checked",
357385
files={
358386
**CENTS_TO_DOLLARS,
359387
**_REFUNDS,
@@ -368,7 +396,7 @@ def test_given_any_spelling_of_list_calls_when_building_then_the_model_holds_the
368396
expected_fragments=("0 errors",),
369397
),
370398
SqlMacroCommandTestCase(
371-
description="typed_argument_in_a_scalar_subquery_reads_the_subquery",
399+
description="typed_argument_in_a_scalar_subquery_is_not_checked",
372400
files={
373401
**CENTS_TO_DOLLARS,
374402
**_REFUNDS,

‎tests/e2e/src/sqlbuild/cli/commands/main/compile/sql_macros/test_sql_macro_errors.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -660,6 +660,22 @@
660660
"pass a relation with these columns: order_id BIGINT, updated_at TIMESTAMP, is_deleted BOOLEAN",
661661
),
662662
),
663+
SqlMacroErrorTestCase(
664+
description="relation_missing_a_column_behind_a_star_over_typed_sources",
665+
files={
666+
**CLEAN_ORDERS,
667+
**orders_model(
668+
"WITH orders_raw AS (\n"
669+
' SELECT o.order_id, o.updated_at, t.* FROM __ref("stg_orders") AS o\n'
670+
" CROSS JOIN (SELECT 1 AS flag) AS t\n),\n"
671+
"@sql.clean_orders(orders_raw)\nSELECT order_id FROM latest\n"
672+
),
673+
},
674+
expected_code="P017",
675+
expected_fragments=(
676+
"argument src of macro clean_orders() needs column is_deleted BOOLEAN; orders_raw has no column is_deleted",
677+
),
678+
),
663679
SqlMacroErrorTestCase(
664680
description="relation_column_of_an_incompatible_type",
665681
files={

0 commit comments

Comments
 (0)