diff --git a/benchmarks/duckshop/README.md b/benchmarks/duckshop/README.md index e478c27800..d237e07504 100644 --- a/benchmarks/duckshop/README.md +++ b/benchmarks/duckshop/README.md @@ -125,7 +125,7 @@ project and does not change it: (`sql/models/intermediate/edge_cases/_sqlbuild/_hooks/sql/`) and SQLBuild does not declare. It has 174 models (13 staging, 144 intermediate, 17 marts), 5 Python functions, a SQL table -function, a hook-created JavaScript function, 200 unit tests and 5 scenarios, in nine groups: +function, a hook-created JavaScript function, 203 unit tests and 5 scenarios, in nine groups: | Group | Covers | |-------|--------| @@ -134,7 +134,7 @@ function, a hook-created JavaScript function, 200 unit tests and 5 scenarios, in | VARIANT comparisons | `ARRAY_MAX`, `ARRAY_MIN` and `ARRAY_REVERSE` over arrays mixing numbers, strings, booleans, JSON nulls and integers past 2^53; `MAX` across kinds and non-ASCII strings; `=` and `EQUAL_NULL` for `1`, `"1"` and `1.0`, reordered keys, JSON null and DATE or TIMESTAMP values held in a `VARIANT` against their text; `MIN_BY` and `MAX_BY` of `VARIANT` values; `PARTITION BY`, `SELECT DISTINCT` and `ARRAY_AGG(DISTINCT)` over `VARIANT`; JSON nulls in `ARRAY_REMOVE`, `ARRAY_DISTINCT` and `ARRAYS_OVERLAP`; decimals with trailing zeros in `ARRAY_CONTAINS` and `ARRAY_POSITION`; `OBJECT_CONSTRUCT(* EXCLUDE ("note"))` | | Dates and times | `TRY_TO_TIMESTAMP_NTZ` and its siblings over free text; epoch milliseconds as numbers and text; daylight-saving gaps and overlaps; fractional offsets; nanosecond truncation and epoch parts after 2242; pre-1970 text with sub-microsecond digits; date-part normalisation; month ends and leap days; week numbering across a year; sentinel timestamps; `DATEADD` past the end of a test's open cursor window, in a chained test whose upstream step lists some of its columns; a cursor window that touches no row, expected as an empty fixture; `TRY_TO_DATE` with numeric and month-name formats over unpadded fields, two-digit years, ISO `T` and `Z`, trailing letters, a long s, mixed separators and runs of spaces; text read as `TIMESTAMP_TZ` and `TIMESTAMP_LTZ` with `T`, `Z`, `+00:00`, `+0000`, `+09:00` and `-05:30`, back as the UTC instant, date, year and day start, and compared with text, `TIMESTAMP_NTZ` and `DATE`; `FIRST_VALUE` of a zoned value as a `DATE`; `DATEADD` and `TIMEADD` on `TIME(3)` and the type they return; `DATEDIFF` across units; `TIME(9)`, `FF3` and bare `FF` formats truncating; `DATE`, `TO_TIME`, `TRY_TO_TIMESTAMP` and `TO_TIMESTAMP_LTZ` of clock text, and `CURRENT_DATE` and `SYSDATE` read only for facts that hold on any day | | Ordering, numbers and text | NULL ordering under `DESC`; ties in ordered aggregates, `MAX_BY`, `MODE` and `ANY_VALUE`; default window frames; `UNION ALL BY NAME`; `ROUND` half-way values, decimal division, `MOD` and 38-digit amounts; integers past 2^53 against `FLOAT`; regular expressions and backslash escapes, and a scoped SQL macro collapsing whitespace whose body opens with a block comment and holds a line comment; a scoped SQL macro, `horner_ratio`, whose body nests polynomials in a subquery item without an alias, which a second `sqb format` leaves unchanged; `LIKE ... ESCAPE` and `ILIKE ANY`; `SPLIT_PART` and `SUBSTR` before the start; `NOT IN` with a NULL; names in many scripts; `JOIN ... USING` between `NUMBER(18,0)`, `NUMBER(38,0)` and text keys, with the types of the merged and qualified keys; NULL arithmetic and the types of NULL, decimal and exponent literals, `COUNT`, `ROW_NUMBER`, `%` and `NULLIF`; `MEDIAN` at scales 0 to 15; `DIV0` by literal zeros; `MODE`, `MEDIAN` and `COUNT_IF` over no rows; aggregates inside window functions and `QUALIFY`; `ROLLUP` totals; `TRUNC` of `FLOAT`; infinity words in other scripts; `CASE` without `ELSE` and `DECODE` over text; regular expressions with a `?` after a lazy quantifier, classes opening with `]`, empty matches and `.` against a carriage return; case-insensitive matches outside ASCII; `ILIKE` with a long s; `JAROWINKLER_SIMILARITY` of accented names in both cases; Base64 text with line feeds; `STARTSWITH`, `ENDSWITH`, `SUBSTRING`, `POSITION` with `IN` and with a comma, `CHARINDEX`, `CHR`, `REGEXP_SUBSTR_ALL`, `::STRING` and `CAST ... AS STRING`; `HEX_ENCODE`, `HEX_DECODE_STRING`, `TRY_HEX_DECODE_STRING` and `TRY_BASE64_DECODE_BINARY`; a comment attached to a text literal; `FLOOR` with and without a scale, `BITAND`, `ZEROIFNULL`, `::BIGINT` and `::DOUBLE`; `IS NOT DISTINCT FROM` and `EQUAL_NULL`; a comma join after an explicit join; `HASH_AGG` read in two row orders | -| Lineage and analysis | clauses whose columns decide rows without being output (`WHERE`, `QUALIFY`, `GROUP BY` by position and `ALL`, `ORDER BY` under `LIMIT`, `EXISTS`, a `FLATTEN` input, `ROLLUP` by position, `EXCEPT` under `LIMIT`); `RIGHT JOIN ... USING`, `NATURAL JOIN`, a `USING` key under a later outer join, and unmatched `ASOF JOIN` rows; `CONNECT BY` beside a column named `level`; a recursive CTE without `RECURSIVE` whose columns shift per iteration; `LAST_DAY` with a date part; positional columns and the names Snowflake gives unaliased expressions; `TEXT(5)` and widened `COUNT` contracts; `LAG` and `LEAD` with one, two and three arguments; a comma-joined `LATERAL` whose nested derived table reads the left item; relations aliased `first` and `last`, one without `AS`, the words of Snowflake's read-order clauses; untyped and typed `FILTER` lambdas over `ARRAY_AGG` in a grouped query; column expression ranges in compiled SQL that SQL and Python macros, a variable and cursor bounds rewrote, and columns qualified by their reference call, whose ranges are dropped | +| Lineage and analysis | clauses whose columns decide rows without being output (`WHERE`, `QUALIFY`, `GROUP BY` by position and `ALL`, `ORDER BY` under `LIMIT`, `EXISTS`, a `FLATTEN` input, `ROLLUP` by position, `EXCEPT` under `LIMIT`); `RIGHT JOIN ... USING`, `NATURAL JOIN`, a `USING` key under a later outer join, and unmatched `ASOF JOIN` rows; `CONNECT BY` beside a column named `level`; a recursive CTE without `RECURSIVE` whose columns shift per iteration; `LAST_DAY` with a date part; positional columns and the names Snowflake gives unaliased expressions; `TEXT(5)` and widened `COUNT` contracts; `LAG` and `LEAD` with one, two and three arguments; a comma-joined `LATERAL` whose nested derived table reads the left item; relations aliased `first` and `last`, one without `AS`, the words of Snowflake's read-order clauses; untyped and typed `FILTER` lambdas over `ARRAY_AGG` in a grouped query; column expression ranges in compiled SQL that SQL and Python macros, a variable and cursor bounds rewrote, and columns qualified by their reference call, whose ranges are dropped; an expected CTE that joins and filters through `__ref()` of the mocked model | | Python functions | volatile tokens and numbers from a column, a constant and no argument, and `DIV0` of a volatile call beside look-alike names, checked by assertions that hold for any values; a handler answering NULL input without `STRICT`; Python `None` as JSON null, and datetimes, Decimals and integers past 2^53 handed to `VARIANT` and `FLOAT` results | | Scenarios and lifecycle | typed values across model boundaries; `VARIANT` expected output; a star under a lower-case contract and a quoted camelCase export; a snapshot keyed and compared on quoted camelCase columns; a timestamp snapshot whose `updated_at` is a `DATE`, so its validity columns are `DATE` too; a cursor-window incremental model over far-apart fixture loads; a rolling-window microbatch model whose full refresh covers its `cursor_start` through the current day; a change log merged across two loads, checked against a full rebuild, a keyed cursor `delete_insert` copy of it whose rows move out of the window between loads, and a cursor `delete_insert` copy of every version that `replace_key` replaces per shipment | | Translation refusals | one model per construct that translation tools refuse or guard, most putting a construct refused only under strict checking before one refused by default, so a model shows both: `FLOAT` values through sums, averages, running totals, arrays, objects, `HASH`, `TO_CHAR` and `::NUMBER(38, 10)`; `VARIANT` dates, decimals and XML; `ARRAY_AGG` without `WITHIN GROUP`, sparse arrays and `ARRAY(NUMBER)` casts; `REDUCE`, `FILTER` and `TRANSFORM` lambdas; patterns and `REGEXP_REPLACE` replacements built from columns, and lazy patterns; `TRY_TO_DATE` with a format from a column; zoned literals, `CONVERT_TIMEZONE` from `CURRENT_TIMESTAMP`, `SEQ8`, `GENERATOR` with an expression `ROWCOUNT`; `PIVOT`, `ANY_VALUE`, `IGNORE NULLS` around `IFF`, unaliased columns read by Snowflake's name, `UNION` branches whose column is always NULL; `TO_NUMBER`, `TO_DECIMAL` and `TRY_BASE64_DECODE_BINARY`; an open (uncontracted) source `edge__supplier_notes`, the table function, read for one basket and after `LATERAL` for every basket, and the hook-created function. `rpt_edge_case_model_keys` and `rpt_edge_case_array_model_keys` read every model in the group, so a refusal there also refuses a downstream model | diff --git a/benchmarks/duckshop/project/tests/unit/intermediate/edge_cases/test_int_edge_check_group_flags_expected_reads.sql b/benchmarks/duckshop/project/tests/unit/intermediate/edge_cases/test_int_edge_check_group_flags_expected_reads.sql new file mode 100644 index 0000000000..eef80d9b87 --- /dev/null +++ b/benchmarks/duckshop/project/tests/unit/intermediate/edge_cases/test_int_edge_check_group_flags_expected_reads.sql @@ -0,0 +1,36 @@ +TEST (name "int_edge_check_group_flags__expected_rows_read_the_mocked_checks"); + +WITH __ref__stg_edge_amount_checks AS ( + SELECT + v.check_id::VARCHAR AS check_id, + v.group_code::VARCHAR AS group_code, + v.narrow_key::NUMBER(18, 0) AS narrow_key, + v.wide_key::NUMBER(38, 0) AS wide_key, + v.key_text::VARCHAR AS key_text, + v.amount::NUMBER(18, 2) AS amount, + v.ratio::FLOAT AS ratio + FROM VALUES + ('AC-01', 'G-1', 7, 7, '101,7', 10.05, 0.1), + ('AC-02', 'G-1', 12, 12, '2026-03-04', -0.55, 0.2), + ('AC-03', 'G-2', 3, NULL, '7', 0.00, 0.3), + ('AC-04', 'G-2', NULL, 40, NULL, NULL, NULL) AS v(check_id, group_code, narrow_key, wide_key, key_text, amount, ratio) +), + +group_flags AS ( + SELECT + v.group_code, + v.is_unpaid_group + FROM VALUES ('G-1', FALSE), ('G-2', TRUE) AS v(group_code, is_unpaid_group) +), + +__expected__int_edge_check_group_flags AS ( + SELECT + c.check_id, + g.is_unpaid_group + FROM __ref("stg_edge_amount_checks") AS c + INNER JOIN group_flags AS g + ON g.group_code = c.group_code + WHERE c.check_id IN ( + SELECT a.check_id FROM __ref("stg_edge_amount_checks") AS a + ) +) diff --git a/crates/sqlbuild-analysis/src/analysis_route/_helpers/dialects/snowflake_dialect.rs b/crates/sqlbuild-analysis/src/analysis_route/_helpers/dialects/snowflake_dialect.rs index e534a1a991..d4389dc1e4 100644 --- a/crates/sqlbuild-analysis/src/analysis_route/_helpers/dialects/snowflake_dialect.rs +++ b/crates/sqlbuild-analysis/src/analysis_route/_helpers/dialects/snowflake_dialect.rs @@ -113,7 +113,11 @@ pub(crate) fn shared_parsed(sql: &str, dialect: Dialect) -> Result { - let offset: usize = error.start().unwrap_or_default(); + let offset: usize = error.start().map_or(0, |characters| { + sql.char_indices() + .nth(characters) + .map_or(sql.len(), |(byte, _)| byte) + }); let message: String = unplaced(error); ParserGap { construct: message.clone(), diff --git a/crates/sqlbuild-analysis/src/analysis_route/tests/test_native_gap.rs b/crates/sqlbuild-analysis/src/analysis_route/tests/test_native_gap.rs index b354bfb34f..bd34845e54 100644 --- a/crates/sqlbuild-analysis/src/analysis_route/tests/test_native_gap.rs +++ b/crates/sqlbuild-analysis/src/analysis_route/tests/test_native_gap.rs @@ -1,7 +1,9 @@ use crate::analysis_route::main::analysis_route::analysis_route; use crate::analysis_route::main::native_gap::native_gap; use crate::analysis_route::main::skipped_analysis::skipped_analysis; -use crate::analysis_route::models::{AnalysisRoute, GapPosition, GapSite, LocatedGap, TsqlDialect}; +use crate::analysis_route::models::{ + AnalysisRoute, GapPosition, GapSite, LocatedGap, SnowflakeDialect, TsqlDialect, +}; use crate::analysis_route::tests::test_types::{ NativeGapTestCase, PivotlessDialect, RouteTestCase, SkippedAnalysisTestCase, TsqlParseTestCase, TsqlTypeTestCase, @@ -192,6 +194,44 @@ fn given_model_sql_when_probing_the_native_parser_then_its_gap_is_located_after_ } } +#[test] +fn given_multibyte_snowflake_text_when_probing_then_the_gap_column_counts_characters() { + let unexpected_eq = |column: usize, source_offset: usize| LocatedGap { + construct: "Unexpected token: Eq".to_owned(), + message: "Unexpected token: Eq".to_owned(), + line: 1, + column, + syntax: false, + source_offset: Some(source_offset), + }; + let test_cases = [ + NativeGapTestCase { + description: "ASCII text before the error", + sql: "SELECT 'grosse' AS label FROM orders WHERE row_key = = 1", + placeholders: &[], + expected_gap: Some(unexpected_eq(54, 53)), + }, + NativeGapTestCase { + description: "multibyte text before the error, one character shorter", + sql: "SELECT 'größé' AS label FROM orders WHERE row_key = = 1", + placeholders: &[], + expected_gap: Some(unexpected_eq(53, 52)), + }, + ]; + for test_case in test_cases { + let check = SyntaxCheck { + sql: test_case.sql.to_owned(), + placeholders: Vec::new(), + }; + assert_eq!( + native_gap(&SnowflakeDialect, &check), + Ok(test_case.expected_gap), + "{}", + test_case.description + ); + } +} + #[test] fn given_a_located_gap_when_skipping_analysis_then_p026_names_the_model_its_site_and_the_gap() { let test_cases = [ diff --git a/crates/sqlbuild-analysis/src/compiler/_helpers/sql_tests/expected_columns.rs b/crates/sqlbuild-analysis/src/compiler/_helpers/sql_tests/expected_columns.rs index 87c9ac1bdc..2db0bf0384 100644 --- a/crates/sqlbuild-analysis/src/compiler/_helpers/sql_tests/expected_columns.rs +++ b/crates/sqlbuild-analysis/src/compiler/_helpers/sql_tests/expected_columns.rs @@ -1,7 +1,9 @@ //! Expected-output column names read syntactically from an `__expected__` CTE body. -use std::collections::HashSet; +use std::collections::{BTreeMap, HashSet}; +use serde_json::json; +use sqlbuild_sqltext::sql_scan::models::LexicalSyntax; use sqlquack_syntax::expressions::names::models::Identifier; use sqlquack_syntax::expressions::queries::models::Select; use sqlquack_syntax::{Expression, Parsed}; @@ -10,46 +12,136 @@ use crate::analysis_route::types::NativeDialect; use crate::compiler::_helpers::sql_tests::extraction::{ empty_fixture_marker_matches, generic_syntax, }; +use crate::sql_tree::main::parseable_sql::parseable_sql; -/// Return the authored output column identifiers of `sql`, or `None` when they are not explicit. -pub(crate) fn expected_columns(sql: &str, parser: &dyn NativeDialect) -> Option> { - let mut statements = match parser.parse(sql) { - Ok(Parsed { statements, gaps }) if gaps.is_empty() => statements, - _ => return None, +/// Prefix of the planner error for an expected CTE whose output columns can't be read. +pub(crate) const UNREADABLE_COLUMNS_ERROR_PREFIX: &str = "sql_test_expected_columns:"; + +/// Why the output columns of an expected body can't be read. +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum UnreadableColumns { + /// The body doesn't parse whole in the dialect: the parser's reason, at a line and column of the authored body. + Unparsed { + reason: String, + line: usize, + column: usize, + }, + /// The body parses, but its output columns aren't each one distinct bare column or alias: why. + Unnamed(String), +} + +/// The authored output column identifiers of `sql`, its relation markers read as plain names. +pub(crate) fn expected_columns( + sql: &str, + parser: &dyn NativeDialect, + lexical: &LexicalSyntax, +) -> Result, UnreadableColumns> { + let (parsed_sql, map) = parseable_sql(sql, parser.name(), lexical).map_err(|error| { + UnreadableColumns::Unnamed(format!("its relation markers can't be read: {error}")) + })?; + let unparsed = |reason: String, offset: usize| { + let characters = parsed_sql + .char_indices() + .take_while(|(byte, _)| *byte < offset) + .count(); + let (line, column) = map.start(characters); + UnreadableColumns::Unparsed { + reason, + line, + column, + } }; - if statements.len() != 1 { - return None; + let mut statements = match parser.parse(&parsed_sql) { + Ok(Parsed { statements, gaps }) => match gaps.first() { + None => statements, + Some(gap) => { + return Err(unparsed( + format!("it can't read {}", gap.construct), + gap.start, + )); + } + }, + Err(gap) => return Err(unparsed(gap.message, gap.offset)), + }; + let statement = match (statements.pop(), statements.is_empty()) { + (Some(statement), true) => statement, + _ => { + return Err(UnreadableColumns::Unnamed("it isn't one query".to_owned())); + } + }; + let columns: Vec = query_columns(&statement, &AuthoredSource::new(&parsed_sql)) + .map_err(UnreadableColumns::Unnamed)?; + if columns.is_empty() { + return Err(UnreadableColumns::Unnamed("it names no columns".to_owned())); } - let statement = statements.pop()?; - let source = AuthoredSource::new(sql); - let columns: Vec = query_columns(&statement, &source)?; let mut seen: HashSet = HashSet::new(); - if columns.is_empty() - || !columns - .iter() - .all(|column| seen.insert(normalized_identifier(column))) + if let Some(repeated) = columns + .iter() + .find(|column| !seen.insert(normalized_identifier(column))) { - return None; + return Err(UnreadableColumns::Unnamed(format!( + "it names column {repeated} twice" + ))); } - Some(columns) + Ok(columns) +} + +/// Each mock table function's columns; a mock whose columns can't be read is left out, so its `PARTITION BY` keeps its authored form. +pub(crate) fn mock_table_function_columns( + mocks: &BTreeMap, + (parser, lexical): (&dyn NativeDialect, &LexicalSyntax), +) -> BTreeMap> { + mocks + .iter() + .filter_map(|(name, sql)| match expected_columns(sql, parser, lexical) { + Ok(columns) => Some((name.clone(), columns)), + Err(UnreadableColumns::Unparsed { .. } | UnreadableColumns::Unnamed(_)) => None, + }) + .collect() } /// The columns one `(test, file, model)` step lists, none for an empty fixture; unreadable ones are an error. pub(crate) fn step_expected_columns( sql: &str, - parser: &dyn NativeDialect, + (parser, lexical): (&dyn NativeDialect, &LexicalSyntax), (test_name, file_label, model): (&str, &str, &str), ) -> Result>, String> { if empty_fixture_marker_matches(sql, &generic_syntax())? { return Ok(None); } - expected_columns(sql, parser).map(Some).ok_or_else(|| { - format!( - "SQL test '{test_name}' in '{file_label}': the columns of __expected__{model} can't \ - be read, so its rows can't be compared with model '{model}' by name; give every \ - column one distinct name, as a bare column or an alias" - ) - }) + expected_columns(sql, parser, lexical) + .map(Some) + .map_err(|unreadable| { + let cte = format!("__expected__{model}"); + let (message, help) = match unreadable { + UnreadableColumns::Unparsed { + reason, + line, + column, + } => ( + format!( + "SQL test '{test_name}' in '{file_label}': {cte} doesn't parse as {} SQL \ + at line {line}, column {column} of its body: {reason}", + parser.name() + ), + format!( + "write {cte} in {} SQL, so its columns can be compared with model \ + '{model}' by name", + parser.name() + ), + ), + UnreadableColumns::Unnamed(why) => ( + format!( + "SQL test '{test_name}' in '{file_label}': the columns of {cte} can't be \ + read, because {why}, so its rows can't be compared with model '{model}' \ + by name" + ), + "give every column one distinct name, as a bare column or an alias".to_owned(), + ), + }; + let payload = json!({"message": message, "help": help}); + format!("{UNREADABLE_COLUMNS_ERROR_PREFIX}{payload}") + }) } /// Fold an authored identifier to the case-insensitive name used for column matching. @@ -95,7 +187,10 @@ impl<'a> AuthoredSource<'a> { } } -fn query_columns(expression: &Expression, source: &AuthoredSource<'_>) -> Option> { +fn query_columns( + expression: &Expression, + source: &AuthoredSource<'_>, +) -> Result, String> { match expression { Expression::Select(select) => select_columns(select, source), Expression::Union(union) => query_columns(&union.left, source), @@ -106,11 +201,11 @@ fn query_columns(expression: &Expression, source: &AuthoredSource<'_>) -> Option query_columns(&subquery.this, source) } Expression::Values(values) => identifiers(&values.column_aliases, source), - _ => None, + _ => Err("it isn't a query".to_owned()), } } -fn select_columns(select: &Select, source: &AuthoredSource<'_>) -> Option> { +fn select_columns(select: &Select, source: &AuthoredSource<'_>) -> Result, String> { if let [Expression::Star(star)] = select.expressions.as_slice() { if star.table.is_some() || star.except.is_some() @@ -118,34 +213,46 @@ fn select_columns(select: &Select, source: &AuthoredSource<'_>) -> Option, -) -> Option> { +) -> Result, String> { match relation { Expression::Subquery(subquery) if matches!(subquery.this, Expression::Values(_)) => { identifiers(&subquery.column_aliases, source) } Expression::Values(values) => identifiers(&values.column_aliases, source), - _ => None, + _ => Err(star_names_none()), } } +fn star_names_none() -> String { + "its SELECT * names no columns".to_owned() +} + fn projection_column(projection: &Expression, source: &AuthoredSource<'_>) -> Option { match projection { Expression::Alias(alias) if alias.column_aliases.is_empty() => { @@ -156,12 +263,19 @@ fn projection_column(projection: &Expression, source: &AuthoredSource<'_>) -> Op } } -fn identifiers(identifiers: &[Identifier], source: &AuthoredSource<'_>) -> Option> { +fn identifiers( + identifiers: &[Identifier], + source: &AuthoredSource<'_>, +) -> Result, String> { if identifiers.is_empty() { - return None; + return Err("its VALUES names no columns".to_owned()); } identifiers .iter() - .map(|identifier| source.identifier(identifier)) + .map(|identifier| { + source + .identifier(identifier) + .ok_or_else(|| format!("its column {} can't be read as written", identifier.name)) + }) .collect() } diff --git a/crates/sqlbuild-analysis/src/compiler/_helpers/sql_tests/planning.rs b/crates/sqlbuild-analysis/src/compiler/_helpers/sql_tests/planning.rs index 29e98c7a4f..3d9514ce6e 100644 --- a/crates/sqlbuild-analysis/src/compiler/_helpers/sql_tests/planning.rs +++ b/crates/sqlbuild-analysis/src/compiler/_helpers/sql_tests/planning.rs @@ -19,7 +19,7 @@ use crate::compiler::_helpers::sql_tests::cte_slices::{SliceDialect, strip_state use crate::compiler::_helpers::sql_tests::cte_sql::{ cte_definition_sql, leading_with_prefix_end, with_leading_ctes, with_unique_ctes, }; -use crate::compiler::_helpers::sql_tests::expected_columns::expected_columns; +use crate::compiler::_helpers::sql_tests::expected_columns::mock_table_function_columns; use crate::compiler::_helpers::sql_tests::expected_columns::step_expected_columns; use crate::compiler::_helpers::sql_tests::helper_names::HELPER_PREFIX; use crate::compiler::_helpers::sql_tests::helper_scope::{ @@ -778,11 +778,10 @@ fn plan_model_test( ) -> Result { let mut fixtures = classify_fixtures(plan.authored_ctes, plan.expected_ctes, plan.assertion_ctes); - fixtures.mock_table_function_columns = fixtures - .mock_table_functions - .iter() - .filter_map(|(name, sql)| Some((name.clone(), expected_columns(sql, context.parser)?))) - .collect(); + fixtures.mock_table_function_columns = mock_table_function_columns( + &fixtures.mock_table_functions, + (context.parser, &context.patterns.lexical), + ); fixtures.scope = ScopeGraph::new(&ScopeRequest { fixtures: &fixtures, patterns: &context.patterns, @@ -933,7 +932,9 @@ fn plan_model_test( model_name: model_name.clone(), resolved_sql, expected_columns: authored_expected - .map(|sql| step_expected_columns(sql, context.parser, label)) + .map(|sql| { + step_expected_columns(sql, (context.parser, &context.patterns.lexical), label) + }) .transpose()? .flatten(), expected_cte_sql: authored_expected diff --git a/crates/sqlbuild-analysis/src/compiler/main/scenario_expected_columns.rs b/crates/sqlbuild-analysis/src/compiler/main/scenario_expected_columns.rs index 7ff60c1550..2dcdb7a878 100644 --- a/crates/sqlbuild-analysis/src/compiler/main/scenario_expected_columns.rs +++ b/crates/sqlbuild-analysis/src/compiler/main/scenario_expected_columns.rs @@ -1,26 +1,37 @@ //! Compare a scenario `__expected__` CTE's listed columns with its model's output columns. +use sqlbuild_sqltext::sql_scan::main::dialect_lexical_syntax::dialect_lexical_syntax; + use crate::compiler::_helpers::sql_tests::expected_columns::{ - expected_columns, normalized_identifier, + UnreadableColumns, expected_columns, normalized_identifier, }; use crate::compiler::_helpers::sql_tests::rendering::sql_test_parser; use crate::compiler::models::ScenarioExpectedColumns; -/// The columns an expected CTE lists and how they differ from the known model output. +/// The columns an expected CTE lists and how they differ from the known model output; none when they can't be read, so the scenario compares rows by position. #[must_use] pub fn scenario_expected_columns( expected_sql: &str, dialect: Option<&str>, model_columns: Option<&[String]>, ) -> ScenarioExpectedColumns { - let listed: Option> = - sql_test_parser(dialect).and_then(|parser| expected_columns(expected_sql, parser)); - let (Some(listed_columns), Some(model_columns)) = (listed.as_deref(), model_columns) else { - return ScenarioExpectedColumns { - listed, - unlisted: Vec::new(), - unknown: Vec::new(), + let only_listed = |listed: Option>| ScenarioExpectedColumns { + listed, + unlisted: Vec::new(), + unknown: Vec::new(), + }; + let Some(parser) = sql_test_parser(dialect) else { + return only_listed(None); + }; + let listed_columns: Vec = + match expected_columns(expected_sql, parser, &dialect_lexical_syntax(parser.name())) { + Ok(columns) => columns, + Err(UnreadableColumns::Unparsed { .. } | UnreadableColumns::Unnamed(_)) => { + return only_listed(None); + } }; + let Some(model_columns) = model_columns else { + return only_listed(Some(listed_columns)); }; let listed_names: Vec = listed_columns .iter() @@ -43,7 +54,7 @@ pub fn scenario_expected_columns( .map(|(column, _)| column.clone()) .collect(); ScenarioExpectedColumns { - listed, + listed: Some(listed_columns), unlisted, unknown, } diff --git a/crates/sqlbuild-analysis/src/compiler/tests/helpers.rs b/crates/sqlbuild-analysis/src/compiler/tests/helpers.rs index 6a407c1c0e..4b83ad5ae8 100644 --- a/crates/sqlbuild-analysis/src/compiler/tests/helpers.rs +++ b/crates/sqlbuild-analysis/src/compiler/tests/helpers.rs @@ -1911,9 +1911,10 @@ pub(crate) fn unreadable_chain_step_expected_columns_are_a_plan_error() -> bool let duplicated: String = plan("SELECT 1 AS order_id, 2 AS ORDER_ID") .expect_err("a step whose columns can't be read doesn't plan"); assert!( - duplicated.contains( - "SQL test 'orders_case' in 'tests/orders.sql': the columns of __expected__stg_orders can't be read" - ), + duplicated.starts_with("sql_test_expected_columns:") + && duplicated.contains( + "SQL test 'orders_case' in 'tests/orders.sql': the columns of __expected__stg_orders can't be read, because it names column ORDER_ID twice" + ), "{duplicated}" ); let empty: String = diff --git a/crates/sqlbuild-analysis/src/compiler/tests/test_sql_test_expected_columns.rs b/crates/sqlbuild-analysis/src/compiler/tests/test_sql_test_expected_columns.rs index b95f97928f..58a42ea0b5 100644 --- a/crates/sqlbuild-analysis/src/compiler/tests/test_sql_test_expected_columns.rs +++ b/crates/sqlbuild-analysis/src/compiler/tests/test_sql_test_expected_columns.rs @@ -1,4 +1,6 @@ -use crate::compiler::_helpers::sql_tests::expected_columns::expected_columns; +use sqlbuild_sqltext::sql_scan::main::dialect_lexical_syntax::dialect_lexical_syntax; + +use crate::compiler::_helpers::sql_tests::expected_columns::{UnreadableColumns, expected_columns}; use crate::compiler::_helpers::sql_tests::rendering::sql_test_parser; use crate::compiler::tests::test_types::ExpectedColumnsTestCase; @@ -9,73 +11,147 @@ fn given_expected_cte_bodies_when_reading_columns_then_authored_names_or_none_ar description: "aliases and bare or qualified columns", dialect: "duckdb", sql: "SELECT 1 AS order_id, o.customer_id, amount FROM orders AS o", - expected_columns: Some(&["order_id", "customer_id", "amount"]), + expected_result: Ok(&["order_id", "customer_id", "amount"]), }, ExpectedColumnsTestCase { description: "quoted identifiers keep authored spelling", dialect: "snowflake", sql: "SELECT 1 AS \"Order Id\", 'paid' AS Status", - expected_columns: Some(&["\"Order Id\"", "Status"]), + expected_result: Ok(&["\"Order Id\"", "Status"]), }, ExpectedColumnsTestCase { description: "bracketed identifiers keep authored spelling", dialect: "tsql", sql: "SELECT 1 AS [Order Id], 2 AS amount", - expected_columns: Some(&["[Order Id]", "amount"]), + expected_result: Ok(&["[Order Id]", "amount"]), }, ExpectedColumnsTestCase { description: "set operations use the first branch", dialect: "duckdb", sql: "SELECT 1 AS order_id, 10 AS amount UNION ALL SELECT 2, 20", - expected_columns: Some(&["order_id", "amount"]), + expected_result: Ok(&["order_id", "amount"]), }, ExpectedColumnsTestCase { description: "star over aliased values uses the alias list", dialect: "duckdb", sql: "SELECT * FROM (VALUES (1, 'paid'), (2, 'open')) AS t(order_id, status)", - expected_columns: Some(&["order_id", "status"]), + expected_result: Ok(&["order_id", "status"]), }, ExpectedColumnsTestCase { description: "leading WITH uses the final projection", dialect: "duckdb", sql: "WITH picked AS (SELECT 1 AS a, 2 AS b) SELECT b FROM picked", - expected_columns: Some(&["b"]), + expected_result: Ok(&["b"]), }, ExpectedColumnsTestCase { description: "non-ASCII text before an identifier keeps its spelling", dialect: "duckdb", sql: "SELECT '订单' AS label, 1 AS \"数量\"", - expected_columns: Some(&["label", "\"数量\""]), + expected_result: Ok(&["label", "\"数量\""]), + }, + ExpectedColumnsTestCase { + description: "a Snowflake reference in a join reads as a relation", + dialect: "snowflake", + sql: "SELECT p.row_key, e.measure_a FROM expected AS e \ + INNER JOIN __ref(\"model_a\") AS p ON p.source_key = e.source_key", + expected_result: Ok(&["row_key", "measure_a"]), + }, + ExpectedColumnsTestCase { + description: "a Snowflake reference in a WHERE subquery reads as a relation", + dialect: "snowflake", + sql: "SELECT e.source_key AS row_key FROM expected AS e \ + WHERE e.source_key IN (SELECT source_key FROM __ref(\"model_a\"))", + expected_result: Ok(&["row_key"]), + }, + ExpectedColumnsTestCase { + description: "a Snowflake table function marker reads inside TABLE()", + dialect: "snowflake", + sql: "SELECT t.order_id FROM __table_fn(\"orders_for\")(1) AS t", + expected_result: Ok(&["order_id"]), + }, + ExpectedColumnsTestCase { + description: "a column after a multi-byte reference keeps its spelling", + dialect: "snowflake", + sql: "SELECT p.\"Größe\" FROM __ref(\"größen\") AS p", + expected_result: Ok(&["\"Größe\""]), + }, + ExpectedColumnsTestCase { + description: "a bare Snowflake table function stops the parse where it stands", + dialect: "snowflake", + sql: "SELECT p.row_key\nFROM orders_for('x') AS p", + expected_result: Err(UnreadableColumns::Unparsed { + reason: "Expected TABLE( ) around a table function".to_owned(), + line: 2, + column: 17, + }), + }, + ExpectedColumnsTestCase { + description: "multibyte text before a Snowflake parse error keeps its column", + dialect: "snowflake", + sql: "SELECT 'größé' AS label FROM orders WHERE row_key = = 1", + expected_result: Err(UnreadableColumns::Unparsed { + reason: "Unexpected token: Eq".to_owned(), + line: 1, + column: 53, + }), + }, + ExpectedColumnsTestCase { + description: "an error inside a Snowflake table function's arguments is placed as written", + dialect: "snowflake", + sql: "SELECT * FROM (SELECT * FROM __table_fn(\"f\")(1, )) AS t", + expected_result: Err(UnreadableColumns::Unparsed { + reason: "Unexpected token: RParen".to_owned(), + line: 1, + column: 49, + }), + }, + ExpectedColumnsTestCase { + description: "a PostgreSQL SELECT with no projection names no columns", + dialect: "postgres", + sql: "SELECT FROM __ref(\"orders\")", + expected_result: Err(UnreadableColumns::Unnamed("it names no columns".to_owned())), }, ExpectedColumnsTestCase { description: "star from another relation is not explicit", dialect: "duckdb", sql: "SELECT * FROM orders", - expected_columns: None, + expected_result: Err(UnreadableColumns::Unnamed( + "its SELECT * names no columns".to_owned(), + )), }, ExpectedColumnsTestCase { description: "star with exclusions is not explicit", dialect: "duckdb", sql: "SELECT * EXCLUDE (amount) FROM (VALUES (1, 2)) AS t(order_id, amount)", - expected_columns: None, + expected_result: Err(UnreadableColumns::Unnamed( + "its SELECT * names no columns".to_owned(), + )), }, ExpectedColumnsTestCase { description: "unaliased expressions are not explicit", dialect: "duckdb", sql: "SELECT 1 AS order_id, amount + 1 FROM orders", - expected_columns: None, + expected_result: Err(UnreadableColumns::Unnamed( + "its output column 2 is neither a bare column nor an alias".to_owned(), + )), }, ExpectedColumnsTestCase { description: "duplicate names keep full-row comparison", dialect: "duckdb", sql: "SELECT 1 AS order_id, 2 AS ORDER_ID", - expected_columns: None, + expected_result: Err(UnreadableColumns::Unnamed( + "it names column ORDER_ID twice".to_owned(), + )), }, ExpectedColumnsTestCase { description: "unparsable SQL is not explicit", dialect: "duckdb", sql: "SELECT FROM WHERE", - expected_columns: None, + expected_result: Err(UnreadableColumns::Unparsed { + reason: "Syntax error at or near 'WHERE'".to_owned(), + line: 1, + column: 13, + }), }, ]; @@ -84,13 +160,15 @@ fn given_expected_cte_bodies_when_reading_columns_then_authored_names_or_none_ar .filter(|test_case| sql_test_parser(Some(test_case.dialect)).is_some()) { let parser = sql_test_parser(Some(test_case.dialect)).expect("native parser"); - let actual: Option> = expected_columns(test_case.sql, parser); - let actual_columns: Option> = actual - .as_ref() - .map(|columns| columns.iter().map(String::as_str).collect()); assert_eq!( - actual_columns.as_deref(), - test_case.expected_columns, + expected_columns( + test_case.sql, + parser, + &dialect_lexical_syntax(test_case.dialect), + ), + test_case + .expected_result + .map(|columns| columns.iter().map(ToString::to_string).collect()), "{}", test_case.description ); diff --git a/crates/sqlbuild-analysis/src/compiler/tests/test_types.rs b/crates/sqlbuild-analysis/src/compiler/tests/test_types.rs index f0553c451b..ae7da44553 100644 --- a/crates/sqlbuild-analysis/src/compiler/tests/test_types.rs +++ b/crates/sqlbuild-analysis/src/compiler/tests/test_types.rs @@ -1,3 +1,4 @@ +use crate::compiler::_helpers::sql_tests::expected_columns::UnreadableColumns; use sqlbuild_sqltext::sql_scan::models::Unclosed; use sqlquack_syntax::Dialect; @@ -23,7 +24,8 @@ pub(crate) struct ExpectedColumnsTestCase { pub(crate) description: &'static str, pub(crate) dialect: &'static str, pub(crate) sql: &'static str, - pub(crate) expected_columns: Option<&'static [&'static str]>, + /// The columns read, or why they can't be: where the body stops parsing, or why its columns aren't named. + pub(crate) expected_result: Result<&'static [&'static str], UnreadableColumns>, } pub(crate) struct TopLevelScanTestCase { diff --git a/crates/sqlbuild-analysis/src/sql_tree/main/mod.rs b/crates/sqlbuild-analysis/src/sql_tree/main/mod.rs index 26be427137..6f7cc52d4c 100644 --- a/crates/sqlbuild-analysis/src/sql_tree/main/mod.rs +++ b/crates/sqlbuild-analysis/src/sql_tree/main/mod.rs @@ -1,5 +1,6 @@ //! Entry points. pub mod deeper_than; +pub(crate) mod parseable_sql; pub mod shared_dialect; pub mod sql_tree_nodes; diff --git a/crates/sqlbuild-analysis/src/sql_tree/main/parseable_sql.rs b/crates/sqlbuild-analysis/src/sql_tree/main/parseable_sql.rs new file mode 100644 index 0000000000..9e6cf0a7c0 --- /dev/null +++ b/crates/sqlbuild-analysis/src/sql_tree/main/parseable_sql.rs @@ -0,0 +1,25 @@ +//! `parseable_sql`: code a dialect's parser can read, with the map of its positions back to the code. + +use sqlbuild_sqltext::sql_scan::models::LexicalSyntax; + +use crate::relation_markers::main::located_markers_as_names::located_markers_as_names; +use crate::sql_tree::_helpers::source_map::SourceMap; +use crate::sql_tree::_helpers::table_wrapped::table_wrapped; +use crate::sql_tree::constants::SNOWFLAKE_DIALECT; + +/// `sql` with each relation marker call as a plain name, and on Snowflake each table function call in `TABLE( )`; an error when its markers can't be read. +pub(crate) fn parseable_sql<'a>( + sql: &'a str, + dialect: &str, + syntax: &LexicalSyntax, +) -> Result<(String, SourceMap<'a>), String> { + let (named, calls, ranges) = located_markers_as_names(sql, syntax)?; + let (wrapped, wrappers) = if dialect == SNOWFLAKE_DIALECT { + let (wrapped, wrappers) = table_wrapped(&named, &calls, syntax); + (Some(wrapped), wrappers) + } else { + (None, Vec::new()) + }; + let map = SourceMap::new(sql, &named, &ranges, wrappers); + Ok((wrapped.unwrap_or(named), map)) +} diff --git a/crates/sqlbuild-analysis/src/sql_tree/main/sql_tree_nodes.rs b/crates/sqlbuild-analysis/src/sql_tree/main/sql_tree_nodes.rs index fed642126f..f94624e1f2 100644 --- a/crates/sqlbuild-analysis/src/sql_tree/main/sql_tree_nodes.rs +++ b/crates/sqlbuild-analysis/src/sql_tree/main/sql_tree_nodes.rs @@ -3,14 +3,12 @@ use sqlbuild_sqltext::sql_scan::main::dialect_lexical_syntax::dialect_lexical_syntax; use sqlquack_syntax::Expression; -use crate::relation_markers::main::located_markers_as_names::located_markers_as_names; use crate::sql_tree::_helpers::parse::parse; use crate::sql_tree::_helpers::rules_tree_parser::rules_tree_parser; -use crate::sql_tree::_helpers::source_map::SourceMap; -use crate::sql_tree::_helpers::table_wrapped::table_wrapped; use crate::sql_tree::_helpers::walk::walk; -use crate::sql_tree::constants::{SNOWFLAKE_DIALECT, TREE_WORKER_STACK_BYTES}; +use crate::sql_tree::constants::TREE_WORKER_STACK_BYTES; use crate::sql_tree::errors::SqlTreeError; +use crate::sql_tree::main::parseable_sql::parseable_sql; use crate::sql_tree::models::SqlTreeNode; use crate::worker_stack::main::run_on_worker_stack::run_on_worker_stack; @@ -26,15 +24,8 @@ fn tree_nodes(sql: &str, dialect: &str) -> Result, SqlTreeError let parser = rules_tree_parser(dialect) .ok_or_else(|| SqlTreeError::UnavailableDialect(dialect.to_owned()))?; let syntax = dialect_lexical_syntax(dialect); - let (named, calls, ranges) = - located_markers_as_names(sql, &syntax).map_err(SqlTreeError::Unanalysable)?; - let (wrapped, wrappers) = if dialect == SNOWFLAKE_DIALECT { - let (wrapped, wrappers) = table_wrapped(&named, &calls, &syntax); - (Some(wrapped), wrappers) - } else { - (None, Vec::new()) - }; - let map = SourceMap::new(sql, &named, &ranges, wrappers); - let statements: Vec = parse(wrapped.as_deref().unwrap_or(&named), parser)?; + let (parseable, map) = + parseable_sql(sql, dialect, &syntax).map_err(SqlTreeError::Unanalysable)?; + let statements: Vec = parse(&parseable, parser)?; walk(&statements, &map) } diff --git a/crates/sqlbuild-python-project/src/sql_test_glue/_helpers/plan/plan_errors.rs b/crates/sqlbuild-python-project/src/sql_test_glue/_helpers/plan/plan_errors.rs index 1d5a35b824..2f5dbc5f9e 100644 --- a/crates/sqlbuild-python-project/src/sql_test_glue/_helpers/plan/plan_errors.rs +++ b/crates/sqlbuild-python-project/src/sql_test_glue/_helpers/plan/plan_errors.rs @@ -1,6 +1,7 @@ //! Project native planning failures into existing located diagnostic exceptions. use crate::sql_test_glue::_helpers::plan::plan_values::string; +use pyo3::exceptions::PyValueError; use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyErr, PyResult, Python}; use pyo3::types::{PyDict, PyDictMethods}; use sqlbuild_analysis::sql_test_attachment::main::sql_test_cte_location::sql_test_cte_location; @@ -83,7 +84,21 @@ pub(crate) fn planning_error( error_class(py, class)?.call((message,), Some(&kwargs))?, )); } - let (class, message) = if let Some(message) = message.strip_prefix("compile_input:") { + let kwargs = PyDict::new(py); + let (class, message) = if let Some(payload) = message.strip_prefix("sql_test_expected_columns:") + { + let payload: serde_json::Value = serde_json::from_str(payload) + .map_err(|error| PyValueError::new_err(error.to_string()))?; + kwargs.set_item("help", payload["help"].as_str())?; + kwargs.set_item( + "code", + crate::sql_test_glue::constants::SQL_TEST_EXPECTED_COLUMNS_CODE, + )?; + let message = payload["message"].as_str().ok_or_else(|| { + PyValueError::new_err("an unreadable expected-columns error carries no message") + })?; + (ErrorId::CompileInput, message.to_owned()) + } else if let Some(message) = message.strip_prefix("compile_input:") { (ErrorId::CompileInput, message.to_owned()) } else if let Some(message) = message.strip_prefix("planner_input:") { (ErrorId::PlannerInput, message.to_owned()) @@ -94,6 +109,6 @@ pub(crate) fn planning_error( ) }; Ok(PyErr::from_value( - error_class(py, class)?.call1((string(py, &message),))?, + error_class(py, class)?.call((string(py, &message),), Some(&kwargs))?, )) } diff --git a/crates/sqlbuild-python-project/src/sql_test_glue/constants.rs b/crates/sqlbuild-python-project/src/sql_test_glue/constants.rs index ae707a6fe0..e6884c89ee 100644 --- a/crates/sqlbuild-python-project/src/sql_test_glue/constants.rs +++ b/crates/sqlbuild-python-project/src/sql_test_glue/constants.rs @@ -44,3 +44,6 @@ pub const SQL_TEST_CTE_SCAN_ALGORITHM: &str = "expanded-sql-test-ctes-v1"; /// The scan store namespace of the models SQL tests expect. pub const SQL_TEST_EXPECTED_MODELS_SCAN_ALGORITHM: &str = "sql-test-expected-models-v1"; + +/// The diagnostic code of an expected CTE whose output columns can't be read. +pub const SQL_TEST_EXPECTED_COLUMNS_CODE: &str = "P028"; diff --git a/scripts/compiler_differential/_helpers/corpus/render_failure_cases.py b/scripts/compiler_differential/_helpers/corpus/render_failure_cases.py index a6a096721f..cfb38e65a9 100644 --- a/scripts/compiler_differential/_helpers/corpus/render_failure_cases.py +++ b/scripts/compiler_differential/_helpers/corpus/render_failure_cases.py @@ -353,6 +353,28 @@ def _reference_cases() -> tuple[FailureCase, ...]: ) }, ), + failure_case( + name="test-expected-columns-repeat-a-name", + expected_code="P028", + expected_message=( + "the columns of __expected__stg_orders can't be read, because it names column " + "ORDER_ID twice" + ), + expected_help="give every column one distinct name, as a bare column or an alias", + files={ + FAILURE_CONFIG_PATH: FAILURE_BASE_CONFIG + + '\n[[rules.rule_ignores]]\nrules = ["SQLCLEAN010"]\n' + + 'paths = ["tests/unit/test_stg_orders.sql"]\n' + + 'reason = "The case repeats a column name in an expected CTE."\n', + "tests/unit/test_stg_orders.sql": ( + "TEST();\n\nWITH\n__source__raw_orders AS (\n" + " SELECT 1 AS order_id, 10 AS customer_id, CAST(5 AS DOUBLE) AS amount," + " 'placed' AS status\n),\n" + "__expected__stg_orders AS (\n SELECT 1 AS order_id, 2 AS ORDER_ID\n)\n" + "SELECT 1\n" + ), + }, + ), failure_case( name="test-helper-reads-unknown-model", expected_code="P013", diff --git a/scripts/compiler_differential/constants.py b/scripts/compiler_differential/constants.py index 798418ba6b..3ffc6c1790 100644 --- a/scripts/compiler_differential/constants.py +++ b/scripts/compiler_differential/constants.py @@ -584,6 +584,7 @@ def short_model_names(*, model: Model, ctx: RuleContext) -> list[Finding]: "P024", "P025", "P027", + "P028", "S026", } ) diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/testing.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/testing.md index 70122f67ad..48222e86fe 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/testing.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/testing.md @@ -255,6 +255,8 @@ SQLBuild reads test CTEs strictly. Other forms are compile errors that name the | A CTE name is an unquoted ASCII identifier: letters, digits and underscores, not starting with a digit | `"recent orders"`, `` `recent orders` ``, names with `$` or non-ASCII characters | | The CTE body follows `AS` directly | `AS MATERIALIZED (...)`, `AS NOT MATERIALIZED (...)` | | Every column of an expected CTE has a name | `amount IS NULL` or `CASE ... END` without an alias | +| Each column name appears once in an expected CTE, in any case | `1 AS order_id, 2 AS ORDER_ID` | +| An expected CTE parses in the project's SQL dialect; the error names the line and column where it stops | On Snowflake, a table function call without `TABLE( )`, such as `FROM order_lookup('x')` | | An expected CTE is a plain `SELECT`, optionally combined with `UNION`, `INTERSECT` or `EXCEPT` | Parenthesized branches, a `WITH` inside the CTE | | An expected CTE lists its columns | `SELECT *`, `SELECT DISTINCT *`, `t.*` | diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/test/_test_types.py b/tests/e2e/src/sqlbuild/cli/commands/main/test/_test_types.py index 0d8a3b5950..8c5097892b 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/test/_test_types.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/test/_test_types.py @@ -783,3 +783,14 @@ class RetiredConversionCacheE2ETestCase: description: str folder: str expected_note_count: int + + +@dataclass(frozen=True) +class ExpectedReferenceShapeE2ETestCase: + """A Snowflake `__expected__` CTE body reading a model through `__ref()`.""" + + description: str + expected_body: str + command: tuple[str, ...] + expected_return_code: int + expected_output_fragment: str diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/test/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/test/helpers.py index bb3218a3d6..58a366c774 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/test/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/test/helpers.py @@ -2812,3 +2812,36 @@ def is_test_row(line: str) -> bool: """Whether a screen line is a test's result row, ` N/M test STATUS ...`.""" return _TEST_ROW.match(line) is not None + + +def build_expected_reference_project_files(*, expected_body: str) -> dict[str, str]: + """A Snowflake project of models `order_keys` and `orders`, which reads a mocked + `order_amounts`, and one test whose `__expected__orders` body is `expected_body`, read with the + `expected` rows CTE.""" + + return { + "sqlbuild_project.toml": ( + 'name = "orders"\nadapter = "snowflake"\n\n' + '[connection]\naccount = "example"\nuser = "builder"\n\n' + '[defaults]\ndatabase = "ANALYTICS"\nschema = "MARTS"\n\n' + "[scopes]\nenforce_placement = false\n" + ), + "sql/models/order_keys.sql": ( + "MODEL (description 'Order keys.', materialized table);\n" + "SELECT 1 AS order_id, 100 AS order_key\n" + ), + "sql/models/order_amounts.sql": ( + "MODEL (description 'Order amounts.', materialized table);\n" + "SELECT 1 AS order_id, 10 AS amount\n" + ), + "sql/models/orders.sql": ( + "MODEL (description 'Orders.', materialized table);\n" + 'SELECT order_id, amount FROM __ref("order_amounts")\n' + ), + "tests/unit/test_orders.sql": ( + 'TEST (name "orders_case");\n\nWITH\n' + "__ref__order_amounts AS (SELECT 1 AS order_id, 10 AS amount),\n" + "expected AS (SELECT 1 AS order_id, 10 AS amount),\n" + f"__expected__orders AS (\n {expected_body}\n)\nSELECT 1\n" + ), + } diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_test.py b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_test.py index 16ca44dbbe..1517223787 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_test.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_test.py @@ -12,6 +12,7 @@ from tests.e2e.src.sqlbuild.cli.commands.main.test._test_types import ( ComplexValuesFixtureE2ETestCase, ExpectedColumnSubsetE2ETestCase, + ExpectedReferenceShapeE2ETestCase, FixtureCompatibilityE2ETestCase, MissingMockCliE2ETestCase, ParameterCaseSelectionE2ETestCase, @@ -40,6 +41,7 @@ build_dynamic_pivot_test_project_files, build_empty_partial_fixture_project_files, build_expected_column_subset_project_files, + build_expected_reference_project_files, build_explicit_typed_null_fixture_project_files, build_incompatible_fixture_type_project_files, build_invalid_partial_fixture_project_files, @@ -116,6 +118,11 @@ "status: expected closed, actual open", ) _UNKNOWN_COLUMN_MESSAGE: str = "expected output 'orders' lists columns that model 'orders'" +_LOCAL_TEST: tuple[str, ...] = ("--no-color", "test", "--run-on", "local") +_JOINED_KEYS: str = ( + "SELECT k.order_id, e.amount FROM expected AS e\n" + ' INNER JOIN __ref("order_keys") AS k ON k.order_id = e.order_id' +) @pytest.mark.parametrize( @@ -1246,3 +1253,74 @@ def test_given_missing_mock_when_testing_and_compiling_then_error_is_reported_un fixed_test_output: str = fixed_test.stdout + fixed_test.stderr assert fixed_test.returncode == 0, fixed_test_output assert "PASS=1 FAIL=0 TOTAL=1" in fixed_test.stdout, fixed_test_output + + +@pytest.mark.parametrize( + "test_case", + [ + ExpectedReferenceShapeE2ETestCase( + description="a Snowflake expected CTE joining __ref() compares its columns", + expected_body=_JOINED_KEYS, + command=_LOCAL_TEST, + expected_return_code=0, + expected_output_fragment="PASS=1 FAIL=0 TOTAL=1", + ), + ExpectedReferenceShapeE2ETestCase( + description="a Snowflake expected CTE reading __ref() in a WHERE subquery compares", + expected_body=( + "SELECT e.order_id, e.amount FROM expected AS e\n" + ' WHERE e.order_id IN (SELECT order_id FROM __ref("order_keys"))' + ), + command=_LOCAL_TEST, + expected_return_code=0, + expected_output_fragment="PASS=1 FAIL=0 TOTAL=1", + ), + ExpectedReferenceShapeE2ETestCase( + description="a Snowflake expected CTE joining the mocked model compares its columns", + expected_body=( + "SELECT e.order_id, a.amount FROM expected AS e\n" + ' INNER JOIN __ref("order_amounts") AS a ON a.order_id = e.order_id' + ), + command=_LOCAL_TEST, + expected_return_code=0, + expected_output_fragment="PASS=1 FAIL=0 TOTAL=1", + ), + ExpectedReferenceShapeE2ETestCase( + description="a Snowflake expected CTE joining __ref() fails on a wrong value", + expected_body=_JOINED_KEYS.replace("e.amount", "e.amount + 1 AS amount"), + command=_LOCAL_TEST, + expected_return_code=1, + expected_output_fragment="PASS=0 FAIL=1 TOTAL=1", + ), + ExpectedReferenceShapeE2ETestCase( + description="a Snowflake expected CTE that doesn't parse names where it stops", + expected_body=( + "SELECT e.order_id, e.amount\n FROM expected AS e, order_lookup('x') AS l" + ), + command=("--no-color", "compile"), + expected_return_code=1, + expected_output_fragment=( + "error[P028]: SQL test 'orders_case' in 'tests/unit/test_orders.sql': " + "__expected__orders doesn't parse as snowflake SQL at line 2, column" + ), + ), + ], + ids=lambda case: case.description, +) +def test_given_an_expected_cte_reading_a_model_when_testing_then_it_compares_its_columns( + test_case: ExpectedReferenceShapeE2ETestCase, + tmp_path: Path, +) -> None: + project_dir: Path = prepare_inline_project( + tmp_path=tmp_path, + project_name="expected_reference_project", + repo_files=build_expected_reference_project_files(expected_body=test_case.expected_body), + ) + + result: subprocess.CompletedProcess[str] = run_sqb( + command=test_case.command, project_dir=project_dir + ) + + output: str = result.stdout + result.stderr + assert result.returncode == test_case.expected_return_code, output + assert test_case.expected_output_fragment in output, output diff --git a/tests/goldens/compiler/failure/test-expected-columns-repeat-a-name.json b/tests/goldens/compiler/failure/test-expected-columns-repeat-a-name.json new file mode 100644 index 0000000000..40c28627d1 --- /dev/null +++ b/tests/goldens/compiler/failure/test-expected-columns-repeat-a-name.json @@ -0,0 +1,31 @@ +{ + "commands": [ + { + "label": "compile", + "exit_code": 1, + "diagnostics": [ + { + "phase": "compile", + "severity": "error", + "code": "P028", + "message": "SQL test 'test_stg_orders' in 'tests/unit/test_stg_orders.sql': the columns of __expected__stg_orders can't be read, because it names column ORDER_ID twice, so its rows can't be compared with model 'stg_orders' by name", + "help": "give every column one distinct name, as a bare column or an alias" + } + ] + } + ], + "compiled": { + "sql/models/marts/customer_totals.sql": [ + "SELECT customer_id, SUM(amount) AS total_amount", + "FROM __ref(\"stg_orders\")", + "GROUP BY customer_id", + "" + ], + "sql/models/staging/stg_orders.sql": [ + "SELECT order_id, customer_id, amount, status", + "FROM __source(\"raw_orders\")", + "" + ] + }, + "manifest": null +} diff --git a/website/src/content/docs/docs/concepts/testing.mdx b/website/src/content/docs/docs/concepts/testing.mdx index d2e88634fe..d5e84369df 100644 --- a/website/src/content/docs/docs/concepts/testing.mdx +++ b/website/src/content/docs/docs/concepts/testing.mdx @@ -236,6 +236,8 @@ SQLBuild reads test CTEs strictly. Other forms are compile errors that name the | A CTE name is an unquoted ASCII identifier: letters, digits and underscores, not starting with a digit | `"recent orders"`, `` `recent orders` ``, names with `$` or non-ASCII characters | | The CTE body follows `AS` directly | `AS MATERIALIZED (...)`, `AS NOT MATERIALIZED (...)` | | Every column of an expected CTE has a name | `amount IS NULL` or `CASE ... END` without an alias | +| Each column name appears once in an expected CTE, in any case | `1 AS order_id, 2 AS ORDER_ID` | +| An expected CTE parses in the project's SQL dialect; the error names the line and column where it stops | On Snowflake, a table function call without `TABLE( )`, such as `FROM order_lookup('x')` | | An expected CTE is a plain `SELECT`, optionally combined with `UNION`, `INTERSECT` or `EXCEPT` | Parenthesized branches, a `WITH` inside the CTE | | An expected CTE lists its columns | `SELECT *`, `SELECT DISTINCT *`, `t.*` |