diff --git a/sidemantic-rs/src/semantic_input/dialects.rs b/sidemantic-rs/src/semantic_input/dialects.rs index d2b5bd9cc..e0626f370 100644 --- a/sidemantic-rs/src/semantic_input/dialects.rs +++ b/sidemantic-rs/src/semantic_input/dialects.rs @@ -843,6 +843,27 @@ pub(super) fn normalize( mod tests { use super::*; + #[test] + fn authored_full_join_conditions_are_emitted_as_written() { + // Lowering an authored NULL-safe comparison would change its meaning: + // an array-valued operand compares NULL and the empty array as equal + // once wrapped. Only generated combine keys are lowered, at generation. + let source = "SELECT * FROM a FULL OUTER JOIN b \ + ON a.id = b.id AND a.tags IS NOT DISTINCT FROM b.tags"; + for target in [ + DialectType::PostgreSQL, + DialectType::DuckDB, + DialectType::Snowflake, + ] { + let expression = parse(source, DialectType::DuckDB).unwrap(); + let sql = emit(expression, DialectType::DuckDB, target).unwrap(); + assert!( + sql.contains("ON a.id = b.id AND a.tags IS NOT DISTINCT FROM b.tags"), + "{target:?}: {sql}" + ); + } + } + #[test] fn source_transpilation_keeps_seed_alias_and_empty_predicate() { let source = "SELECT amount FROM (SELECT 1 AS amount) seed WHERE FALSE"; diff --git a/sidemantic-rs/src/sql/generator.rs b/sidemantic-rs/src/sql/generator.rs index 53d01d45b..20d3589df 100644 --- a/sidemantic-rs/src/sql/generator.rs +++ b/sidemantic-rs/src/sql/generator.rs @@ -178,6 +178,8 @@ struct RollupFilters { pub struct SqlGenerator<'a> { graph: &'a SemanticGraph, dialect: DialectType, + /// Where a caller re-emits this generator's SQL, when not in `dialect`. + emitted_dialect: Option, timezone: Option, } @@ -186,6 +188,7 @@ impl<'a> SqlGenerator<'a> { Self { graph, dialect: SOURCE_DIALECT, + emitted_dialect: None, timezone: None, } } @@ -195,6 +198,14 @@ impl<'a> SqlGenerator<'a> { self } + /// The semantic SQL rewriter generates leaves in the source dialect and + /// emits the whole statement in another. Constructs that the emitted + /// dialect cannot plan must already be generated in a form it accepts. + pub(crate) fn with_emitted_dialect(mut self, dialect: DialectType) -> Self { + self.emitted_dialect = Some(dialect); + self + } + pub fn with_timezone(mut self, timezone: Option) -> Self { self.timezone = timezone; self @@ -2570,6 +2581,21 @@ impl<'a> SqlGenerator<'a> { Ok(false) } + /// NULL-safe equality that the target can plan as a FULL JOIN condition. + fn full_join_null_safe_equality(&self, left: &str, right: &str) -> String { + if self.emitted_dialect.unwrap_or(self.dialect) == DialectType::PostgreSQL { + // PostgreSQL only plans FULL JOIN on hash- or merge-joinable + // operators, which excludes IS NOT DISTINCT FROM. Array equality + // is both, keeps the column type's own comparison, and treats + // NULL elements as equal. Wrapping an array-valued key turns both + // NULL and the empty array into the empty array, so the keys must + // also agree on being NULL. + format!("ARRAY[{left}] = ARRAY[{right}] AND ({left} IS NULL) = ({right} IS NULL)") + } else { + format!("{left} IS NOT DISTINCT FROM {right}") + } + } + fn generate_with_preaggregation( &self, query: &SemanticQuery, @@ -2711,7 +2737,7 @@ impl<'a> SqlGenerator<'a> { sql.push('\n'); sql.push_str(&format!("FROM {}", cte_names[0])); - for cte_name in cte_names.iter().skip(1) { + for (index, cte_name) in cte_names.iter().enumerate().skip(1) { if dimension_refs.is_empty() { sql.push_str(&format!("\nCROSS JOIN {cte_name}")); } else { @@ -2719,9 +2745,19 @@ impl<'a> SqlGenerator<'a> { .iter() .map(|dim_ref| { let dim_alias = self.quote_identifier(&dim_ref.alias); - format!( - "{}.{} IS NOT DISTINCT FROM {cte_name}.{dim_alias}", - cte_names[0], dim_alias + // A group can first appear in any preceding source. + let previous = cte_names[..index] + .iter() + .map(|previous| format!("{previous}.{dim_alias}")) + .collect::>(); + let previous = if previous.len() == 1 { + previous[0].clone() + } else { + format!("COALESCE({})", previous.join(", ")) + }; + self.full_join_null_safe_equality( + &previous, + &format!("{cte_name}.{dim_alias}"), ) }) .collect::>(); @@ -8473,6 +8509,75 @@ models: assert!(sql.contains("WHERE status = 'completed'")); } + #[test] + fn independent_sources_join_on_null_safe_keys_from_every_preceding_source() { + let mut graph = SemanticGraph::new(); + graph + .add_model( + Model::new("customers", "id") + .with_table("customers") + .with_dimension(Dimension::categorical("country")) + .with_metric(Metric::count("customer_count")), + ) + .unwrap(); + graph + .add_model( + Model::new("orders", "id") + .with_table("orders") + .with_metric(Metric::sum("revenue", "amount")) + .with_relationship(Relationship::many_to_one("customers")), + ) + .unwrap(); + graph + .add_model( + Model::new("order_items", "id") + .with_table("order_items") + .with_metric(Metric::sum("quantity", "qty")) + .with_relationship(Relationship::many_to_one("orders")), + ) + .unwrap(); + let query = SemanticQuery::new() + .with_metrics(vec![ + "orders.revenue".into(), + "order_items.quantity".into(), + "customers.customer_count".into(), + ]) + .with_dimensions(vec!["customers.country".into()]); + + let sql = SqlGenerator::new(&graph).generate(&query).unwrap(); + assert!( + sql.contains( + "FULL OUTER JOIN customers_preagg ON COALESCE(orders_preagg.country, \ + order_items_preagg.country) IS NOT DISTINCT FROM customers_preagg.country" + ), + "{sql}" + ); + + // PostgreSQL rejects FULL JOIN ... ON a IS NOT DISTINCT FROM b. + let sql = SqlGenerator::new(&graph) + .with_dialect(DialectType::PostgreSQL) + .generate(&query) + .unwrap(); + assert!( + sql.contains( + "FULL OUTER JOIN order_items_preagg ON ARRAY[orders_preagg.country] \ + = ARRAY[order_items_preagg.country] \ + AND (orders_preagg.country IS NULL) = (order_items_preagg.country IS NULL)" + ), + "{sql}" + ); + assert!( + sql.contains( + "FULL OUTER JOIN customers_preagg ON ARRAY[COALESCE(orders_preagg.country, \ + order_items_preagg.country)] = ARRAY[customers_preagg.country] \ + AND (COALESCE(orders_preagg.country, order_items_preagg.country) IS NULL) \ + = (customers_preagg.country IS NULL)" + ), + "{sql}" + ); + assert!(!sql.contains("IS NOT DISTINCT FROM"), "{sql}"); + } + #[test] fn test_fan_out_warning() { // Create a graph where customers have metrics and we join to orders diff --git a/sidemantic-rs/src/sql/generator/aggregate_plan.rs b/sidemantic-rs/src/sql/generator/aggregate_plan.rs index 16b2855a1..5a417bf22 100644 --- a/sidemantic-rs/src/sql/generator/aggregate_plan.rs +++ b/sidemantic-rs/src/sql/generator/aggregate_plan.rs @@ -1005,6 +1005,7 @@ pub(super) fn try_generate( } let mut public_names = HashSet::new(); let mut order_names = HashMap::new(); + let mut output_aliases = Vec::new(); let mut selections = Vec::new(); for (reference, dimension) in query.dimensions.iter().zip(&dimensions) { let alias = generator.output_alias(&dimension.model, &dimension.alias, &names); @@ -1020,6 +1021,7 @@ pub(super) fn try_generate( dimension_expressions[reference], generator.quote_identifier(&alias) )); + output_aliases.push(alias); } for (reference, resolved, expression) in outputs { let name = &resolved.metric.name; @@ -1043,6 +1045,7 @@ pub(super) fn try_generate( "{expression} AS {}", generator.quote_identifier(&alias) )); + output_aliases.push(alias); } if query.with_totals && !dimensions.is_empty() { let markers: Vec<_> = plan @@ -1092,7 +1095,7 @@ pub(super) fn try_generate( } else { format!("COALESCE({})", previous.join(", ")) }; - format!("{previous} IS NOT DISTINCT FROM {table}.{name}") + generator.full_join_null_safe_equality(&previous, &format!("{table}.{name}")) }) .collect::>(); if query.with_totals { @@ -1135,9 +1138,18 @@ pub(super) fn try_generate( let mut order = Vec::new(); for item in &query.order_by { let (reference, suffix) = crate::sql::split_order_field(item, &known_names); - let alias = order_names - .get(reference) - .ok_or_else(|| unsupported("unprojected_order_by"))?; + let alias = match order_names.get(reference) { + Some(alias) => alias, + // A position selects an output column, as in a single-source + // query; it is not a field named by that number. + None if reference.bytes().all(|byte| byte.is_ascii_digit()) => reference + .parse::() + .ok() + .and_then(|position| position.checked_sub(1)) + .and_then(|index| output_aliases.get(index)) + .ok_or_else(|| unsupported("unprojected_order_by"))?, + None => return Err(unsupported("unprojected_order_by")), + }; // Source splitting must retain the ordinary query's NULL ordering. let suffix = if suffix.contains("NULLS") { suffix @@ -1621,6 +1633,57 @@ mod tests { assert!(sql.contains("ORDER BY region DESC")); } + #[test] + fn postgres_combines_sources_on_hash_joinable_null_safe_keys() { + let graph = graph(); + let query = SemanticQuery::new() + .with_metrics(vec![ + "orders.revenue".into(), + "customers.customer_count".into(), + ]) + .with_dimensions(vec!["customers.region".into()]); + let generator = SqlGenerator::new(&graph).with_dialect(DialectType::PostgreSQL); + let sql = try_generate(&generator, &query).unwrap().unwrap(); + // PostgreSQL rejects FULL JOIN ... ON a IS NOT DISTINCT FROM b. + assert!( + sql.contains( + "FULL OUTER JOIN customers_preagg ON ARRAY[orders_preagg.__sidemantic_dimension_0] \ + = ARRAY[customers_preagg.__sidemantic_dimension_0] \ + AND (orders_preagg.__sidemantic_dimension_0 IS NULL) \ + = (customers_preagg.__sidemantic_dimension_0 IS NULL)" + ), + "{sql}" + ); + assert!(!sql.contains("IS NOT DISTINCT FROM"), "{sql}"); + } + + #[test] + fn order_position_selects_the_output_column() { + let graph = graph(); + let query = SemanticQuery::new() + .with_metrics(vec![ + "orders.revenue".into(), + "customers.customer_count".into(), + ]) + .with_dimensions(vec!["customers.region".into()]) + .with_order_by(vec!["3 DESC".into(), "1".into()]); + let sql = try_generate(&SqlGenerator::new(&graph), &query) + .unwrap() + .unwrap(); + assert!( + sql.contains("ORDER BY customer_count DESC NULLS LAST, region ASC NULLS FIRST"), + "{sql}" + ); + assert_valid_sql(&sql); + + let query = query.with_order_by(vec!["4".into()]); + assert!(matches!( + try_generate(&SqlGenerator::new(&graph), &query), + Err(SidemanticError::UnsupportedSemanticFeatures { capabilities }) + if capabilities == vec!["aggregation.unprojected_order_by"] + )); + } + #[test] fn single_source_stays_on_existing_path() { let graph = graph(); diff --git a/sidemantic-rs/src/sql/generator/options.rs b/sidemantic-rs/src/sql/generator/options.rs index 290322208..390bc718a 100644 --- a/sidemantic-rs/src/sql/generator/options.rs +++ b/sidemantic-rs/src/sql/generator/options.rs @@ -120,6 +120,7 @@ impl SqlGenerator<'_> { let generator = SqlGenerator { graph: self.graph, dialect: self.dialect, + emitted_dialect: self.emitted_dialect, timezone: query.timezone.clone().or_else(|| self.timezone.clone()), }; let mut inner = query.clone(); diff --git a/sidemantic-rs/src/sql/rewriter.rs b/sidemantic-rs/src/sql/rewriter.rs index 7c0afcb0a..24bef9772 100644 --- a/sidemantic-rs/src/sql/rewriter.rs +++ b/sidemantic-rs/src/sql/rewriter.rs @@ -33,6 +33,8 @@ pub struct QueryRewriter<'a> { qualified_tables_physical: bool, warnings: std::cell::RefCell>, used_preaggregation: std::cell::Cell, + /// Dialect of the statement being emitted, for its generated leaves. + emitted_dialect: std::cell::Cell>, } impl<'a> QueryRewriter<'a> { @@ -46,6 +48,7 @@ impl<'a> QueryRewriter<'a> { qualified_tables_physical: false, warnings: std::cell::RefCell::new(Vec::new()), used_preaggregation: std::cell::Cell::new(false), + emitted_dialect: std::cell::Cell::new(None), } } @@ -105,6 +108,25 @@ impl<'a> QueryRewriter<'a> { sql: &str, input_dialect: DialectType, output_dialect: DialectType, + ) -> Result { + // A nested rewrite (a Yardstick leaf) returns DuckDB for a statement + // that is still emitted in the outermost caller's dialect. + let outermost = self.emitted_dialect.get().is_none(); + if outermost { + self.emitted_dialect.set(Some(output_dialect)); + } + let rewritten = self.rewrite_statements(sql, input_dialect, output_dialect); + if outermost { + self.emitted_dialect.set(None); + } + rewritten + } + + fn rewrite_statements( + &self, + sql: &str, + input_dialect: DialectType, + output_dialect: DialectType, ) -> Result { self.used_preaggregation.set(false); if let Some(rewritten) = self.rewrite_ossie_discovery(sql, input_dialect, output_dialect)? { @@ -303,6 +325,83 @@ mod tests { assert!(sql.contains("retention_pct")); } + fn multi_fact_graph() -> SemanticGraph { + let mut graph = SemanticGraph::new(); + graph + .add_model( + Model::new("customers", "id") + .with_table("customers") + .with_dimension(Dimension::categorical("tags")) + .with_metric(Metric::count("customer_count")), + ) + .unwrap(); + graph + .add_model( + Model::new("orders", "id") + .with_table("orders") + .with_metric(Metric::sum("revenue", "amount")) + .with_relationship(Relationship::many_to_one("customers")), + ) + .unwrap(); + graph + } + + #[test] + fn postgres_lowers_only_generated_combine_keys() { + let graph = multi_fact_graph(); + let rewriter = QueryRewriter::new(&graph); + let authored = "s.tags IS NOT DISTINCT FROM labels.tags"; + let sql = format!( + "SELECT s.tags, s.revenue, s.customer_count, labels.name \ + FROM (SELECT customers.tags, orders.revenue, customers.customer_count FROM orders) AS s \ + FULL OUTER JOIN labels ON s.revenue = labels.revenue AND {authored}" + ); + + let postgres = rewriter + .rewrite_with_dialect(&sql, DialectType::PostgreSQL) + .unwrap(); + // PostgreSQL cannot plan the generated combine's NULL-safe keys as written. + assert!( + postgres.contains( + "FULL OUTER JOIN customers_preagg ON ARRAY[orders_preagg.tags] = \ + ARRAY[customers_preagg.tags] \ + AND (orders_preagg.tags IS NULL) = (customers_preagg.tags IS NULL)" + ), + "{postgres}" + ); + // The authored join is the query's own: wrapping an array-valued + // operand would make NULL and the empty array compare as equal. + assert!( + postgres.contains(&format!("ON s.revenue = labels.revenue AND {authored}")), + "{postgres}" + ); + assert_eq!(postgres.matches("ARRAY[").count(), 2, "{postgres}"); + + let duckdb = rewriter + .rewrite_with_dialect(&sql, DialectType::DuckDB) + .unwrap(); + assert!(!duckdb.contains("ARRAY["), "{duckdb}"); + assert_eq!( + duckdb.matches("IS NOT DISTINCT FROM").count(), + 2, + "{duckdb}" + ); + } + + #[test] + fn postgres_passes_authored_full_join_without_semantic_sources_through() { + let graph = multi_fact_graph(); + let sql = "SELECT a.id, b.id FROM a FULL OUTER JOIN b \ + ON a.id = b.id AND a.tags IS NOT DISTINCT FROM b.tags"; + let rewritten = QueryRewriter::new(&graph) + .rewrite_with_dialect(sql, DialectType::PostgreSQL) + .unwrap(); + assert!( + rewritten.contains("ON a.id = b.id AND a.tags IS NOT DISTINCT FROM b.tags"), + "{rewritten}" + ); + } + #[test] fn test_simple_rewrite() { let graph = create_test_graph(); diff --git a/sidemantic-rs/src/sql/rewriter/binding.rs b/sidemantic-rs/src/sql/rewriter/binding.rs index cd3b2fa78..67f05f55a 100644 --- a/sidemantic-rs/src/sql/rewriter/binding.rs +++ b/sidemantic-rs/src/sql/rewriter/binding.rs @@ -575,7 +575,11 @@ impl QueryRewriter<'_> { prepare(&bindings.graph, &mut bindings.query)?; bindings.query.order_by.clear(); } - let sql = SqlGenerator::new(&bindings.graph).generate(&bindings.query)?; + let mut generator = SqlGenerator::new(&bindings.graph); + if let Some(dialect) = self.emitted_dialect.get() { + generator = generator.with_emitted_dialect(dialect); + } + let sql = generator.generate(&bindings.query)?; // Preserve routing metadata outside the parsed subquery: trailing SQL // comments are discarded by the parser and can consume its closing ')'. let sql = if let Some(inner) = sql.strip_suffix("\n-- used_preagg=true") { diff --git a/sidemantic-rs/src/sql/rewriter/policy.rs b/sidemantic-rs/src/sql/rewriter/policy.rs index d6230006e..cae475250 100644 --- a/sidemantic-rs/src/sql/rewriter/policy.rs +++ b/sidemantic-rs/src/sql/rewriter/policy.rs @@ -126,6 +126,7 @@ impl QueryRewriter<'_> { qualified_tables_physical: false, warnings: std::cell::RefCell::new(Vec::new()), used_preaggregation: std::cell::Cell::new(false), + emitted_dialect: std::cell::Cell::new(None), }; rewriter.rewrite_policy_statement(statement) } diff --git a/sidemantic/sql/generator.py b/sidemantic/sql/generator.py index 0741646d5..a30fcfe0f 100644 --- a/sidemantic/sql/generator.py +++ b/sidemantic/sql/generator.py @@ -3290,6 +3290,29 @@ def _needs_preaggregation_for_fanout(self, metrics: list[str], dimensions: list[ return False + def _full_join_null_safe_equality(self, left: exp.Expression, right: exp.Expression) -> str: + """Render a NULL-safe equality the dialect can plan as a FULL JOIN condition.""" + if self.dialect == "postgres": + # PostgreSQL only plans FULL JOIN on hash- or merge-joinable + # operators, which excludes IS NOT DISTINCT FROM. Array equality + # is both, keeps the column type's own comparison, and treats + # NULL elements as equal. Wrapping an array-valued key turns both + # NULL and the empty array into the empty array, so the keys must + # also agree on being NULL. + condition = exp.and_( + exp.EQ( + this=exp.Array(expressions=[left.copy()]), + expression=exp.Array(expressions=[right.copy()]), + ), + exp.EQ( + this=exp.paren(exp.Is(this=left.copy(), expression=exp.null())), + expression=exp.paren(exp.Is(this=right.copy(), expression=exp.null())), + ), + ) + else: + condition = exp.NullSafeEQ(this=left, expression=right) + return condition.sql(dialect=self._dialect_instance) + def _generate_with_preaggregation( self, metrics: list[str], @@ -3654,7 +3677,7 @@ def dimension_output_name(dim_ref: str, dim_name: str, gran: str | None) -> str: previous[0] if len(previous) == 1 else exp.Coalesce(this=previous[0], expressions=previous[1:]) ) rhs = exp.Column(this=col_name, table=cte_name) - join_conditions.append(exp.NullSafeEQ(this=lhs, expression=rhs).sql(dialect=self._dialect_instance)) + join_conditions.append(self._full_join_null_safe_equality(lhs, rhs)) join_clause = " AND ".join(join_conditions) join_clauses.append(f"FULL OUTER JOIN {cte_name} ON {join_clause}") @@ -3709,9 +3732,15 @@ def dimension_output_name(dim_ref: str, dim_name: str, gran: str | None) -> str: suffix = f"{suffix} NULLS {nulls}".strip() field_name = field_ref.split(".", 1)[1] if "." in field_ref else field_ref output_name = output_names.get(field_ref) or output_names.get(field_name) or field_ref + if field_ref not in output_names and field_ref.isdecimal(): + # A position selects an output column, as in the + # single-model query; it is not a column named "1". + order_target = exp.Literal.number(field_ref) + else: + order_target = exp.column(output_name, quoted=True) order_clauses.append( exp.Ordered( - this=exp.column(output_name, quoted=True), + this=order_target, desc=suffix.startswith("DESC"), nulls_first=suffix.endswith("NULLS FIRST"), ) diff --git a/tests/db/test_postgres_integration.py b/tests/db/test_postgres_integration.py index 4e66a7b2e..497a83d91 100644 --- a/tests/db/test_postgres_integration.py +++ b/tests/db/test_postgres_integration.py @@ -4,6 +4,8 @@ """ import os +from datetime import date +from decimal import Decimal import pytest @@ -613,3 +615,204 @@ def test_semantic_layer_postgres_compile_method(clean_postgres): assert "SELECT" in sql.upper() assert "SUM" in sql.upper() assert layer.dialect == "postgres" + + +def _multi_fact_layer(connection: str) -> SemanticLayer: + """Customers, orders and order items with unmatched and NULL-keyed rows.""" + layer = SemanticLayer(connection=connection) + for statement in ( + "CREATE TABLE mf_customers (id INT PRIMARY KEY, region VARCHAR(20))", + """ + CREATE TABLE mf_orders ( + id INT PRIMARY KEY, customer_id INT, status VARCHAR(20), amount DECIMAL(10, 2), created_at TIMESTAMP + ) + """, + "CREATE TABLE mf_order_items (id INT PRIMARY KEY, order_id INT, qty INT)", + # Customer 4 has no region and customer 5 has no orders. + "INSERT INTO mf_customers VALUES (1, 'EU'), (2, 'US'), (3, 'US'), (4, NULL), (5, 'APAC')", + # Order 5 has no customer and order 4 has no items. + """ + INSERT INTO mf_orders VALUES + (1, 1, 'completed', 100.00, '2024-01-05 10:00:00'), + (2, 1, 'pending', 50.00, '2024-01-20 11:00:00'), + (3, 2, 'completed', 75.50, '2024-02-03 09:30:00'), + (4, 3, 'cancelled', 20.00, '2024-02-10 14:00:00'), + (5, NULL, 'completed', 33.00, '2024-02-15 08:00:00'), + (6, 4, 'completed', 60.00, '2024-03-01 12:00:00') + """, + # Item 7 has no order. + """ + INSERT INTO mf_order_items VALUES + (1, 1, 2), (2, 1, 1), (3, 2, 2), (4, 3, 3), (5, 5, 1), (6, 6, 2), (7, NULL, 4) + """, + ): + layer.adapter.execute(statement) + layer.add_model( + Model( + name="mf_customers", + table="mf_customers", + primary_key="id", + dimensions=[Dimension(name="region", type="categorical")], + metrics=[Metric(name="customer_count", agg="count")], + ) + ) + layer.add_model( + Model( + name="mf_orders", + table="mf_orders", + primary_key="id", + relationships=[Relationship(name="mf_customers", type="many_to_one", foreign_key="customer_id")], + dimensions=[ + Dimension(name="status", type="categorical"), + Dimension(name="created_at", type="time", granularity="day"), + ], + metrics=[Metric(name="total_amount", agg="sum", sql="amount")], + ) + ) + layer.add_model( + Model( + name="mf_order_items", + table="mf_order_items", + primary_key="id", + relationships=[Relationship(name="mf_orders", type="many_to_one", foreign_key="order_id")], + metrics=[Metric(name="total_qty", agg="sum", sql="qty")], + ) + ) + return layer + + +def _comparable_rows(result) -> list[tuple]: + def comparable(value): + if isinstance(value, Decimal): + return float(value) + if isinstance(value, date): + return value.isoformat()[:10] + return value + + return [tuple(comparable(value) for value in row) for row in result.fetchall()] + + +def test_semantic_layer_postgres_multi_fact_shared_dimensions(clean_postgres): + """Metrics from several fact models line up on shared dimensions, as on DuckDB.""" + postgres = _multi_fact_layer(POSTGRES_URL) + duckdb = _multi_fact_layer("duckdb:///:memory:") + try: + by_region = "SELECT mf_customers.region, mf_orders.total_amount, mf_order_items.total_qty FROM mf_orders" + rows = _comparable_rows(postgres.sql(by_region)) + # The NULL region bucket of each source must meet in one row. + assert sorted(rows, key=repr) == sorted([("EU", 150.0, 5), ("US", 95.5, 3), (None, 93.0, 7)], key=repr) + + unordered = [ + by_region, + # Three sources: APAC exists only for customers. + "SELECT mf_customers.region, mf_orders.total_amount, mf_order_items.total_qty," + " mf_customers.customer_count FROM mf_orders", + # Two dimensions, one of them a time grain; item 7 has neither. + "SELECT mf_orders.created_at__month, mf_customers.region, mf_orders.total_amount," + " mf_order_items.total_qty FROM mf_orders", + "SELECT mf_customers.region, mf_orders.status, mf_orders.total_amount, mf_order_items.total_qty," + " mf_customers.customer_count FROM mf_orders", + f"{by_region} WHERE mf_orders.status = 'completed'", + ] + for query in unordered: + expected = sorted(_comparable_rows(duckdb.sql(query)), key=repr) + assert sorted(_comparable_rows(postgres.sql(query)), key=repr) == expected, query + assert len(expected) >= 3, query + + # Positions and select aliases order the combined result. + ordered = { + f"{by_region} ORDER BY 2 DESC": [("EU", 150.0, 5), ("US", 95.5, 3), (None, 93.0, 7)], + "SELECT mf_orders.total_amount AS amt, mf_customers.region AS r, mf_order_items.total_qty AS q" + " FROM mf_orders ORDER BY 3 DESC, amt": [(93.0, None, 7), (150.0, "EU", 5), (95.5, "US", 3)], + f"{by_region} ORDER BY 2 DESC LIMIT 1 OFFSET 1": [("US", 95.5, 3)], + } + for query, expected in ordered.items(): + assert _comparable_rows(postgres.sql(query)) == expected, query + assert _comparable_rows(duckdb.sql(query)) == expected, query + + structured = { + "metrics": ["mf_orders.total_amount", "mf_order_items.total_qty"], + "dimensions": ["mf_customers.region"], + "order_by": ["2 DESC"], + "limit": 2, + } + assert _comparable_rows(postgres.query(**structured)) == [("EU", 150.0, 5), ("US", 95.5, 3)] + assert _comparable_rows(duckdb.query(**structured)) == [("EU", 150.0, 5), ("US", 95.5, 3)] + finally: + postgres.adapter.close() + duckdb.adapter.close() + + +def _array_keyed_layer() -> SemanticLayer: + """Groups keyed by an array column whose values include NULL and the empty array.""" + layer = SemanticLayer(connection=POSTGRES_URL) + for statement in ( + "CREATE TABLE mf_groups (id INT PRIMARY KEY, tags INT[])", + "CREATE TABLE mf_sales (id INT PRIMARY KEY, group_id INT, amount INT)", + "CREATE TABLE mf_returns (id INT PRIMARY KEY, group_id INT, qty INT)", + "CREATE TABLE mf_labels (id INT PRIMARY KEY, tags INT[])", + "INSERT INTO mf_groups VALUES (1, '{1,2}'), (2, NULL), (3, '{}'), (4, '{1}')", + # Sale 4 has no group, and group 4 has no sales. + "INSERT INTO mf_sales VALUES (1, 1, 10), (2, 2, 20), (3, 3, 30), (4, NULL, 5)", + "INSERT INTO mf_returns VALUES (1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 4, 4)", + # Labels 2 and 3 swap the NULL and empty tags of groups 2 and 3. + "INSERT INTO mf_labels VALUES (1, '{1,2}'), (2, '{}'), (3, NULL), (4, '{{1}}')", + ): + layer.adapter.execute(statement) + layer.add_model( + Model( + name="mf_groups", + table="mf_groups", + primary_key="id", + dimensions=[Dimension(name="id", type="categorical"), Dimension(name="tags", type="categorical")], + metrics=[Metric(name="group_count", agg="count")], + ) + ) + for name, column in (("mf_sales", "amount"), ("mf_returns", "qty")): + layer.add_model( + Model( + name=name, + table=name, + primary_key="id", + relationships=[Relationship(name="mf_groups", type="many_to_one", foreign_key="group_id")], + metrics=[Metric(name="total", agg="sum", sql=column)], + ) + ) + return layer + + +def test_semantic_layer_postgres_multi_fact_array_valued_dimension(clean_postgres): + """An array-valued shared dimension keeps its NULL and empty-array groups apart.""" + layer = _array_keyed_layer() + try: + rows = layer.sql("SELECT mf_groups.tags, mf_sales.total, mf_returns.total FROM mf_sales").fetchall() + assert sorted(rows, key=repr) == sorted( + [ + ([1, 2], 10, 1), + # Sales 2 and 4 have NULL tags; only sale 3 has empty tags. + (None, 25, 2), + ([], 30, 3), + ([1], None, 4), + ], + key=repr, + ) + finally: + layer.adapter.close() + + +def test_semantic_layer_postgres_authored_full_join_keeps_array_comparison(clean_postgres): + """A FULL JOIN written in the query is PostgreSQL's to evaluate, not a combine to lower.""" + layer = _array_keyed_layer() + try: + rows = layer.sql( + "SELECT s.id, s.group_count, labels.id AS label_id" + " FROM (SELECT mf_groups.id, mf_groups.tags, mf_groups.group_count FROM mf_groups) AS s" + " FULL OUTER JOIN mf_labels AS labels ON s.id = labels.id AND s.tags IS NOT DISTINCT FROM labels.tags" + ).fetchall() + # NULL tags are distinct from empty tags, and {1} from {{1}}. + assert sorted(rows, key=repr) == sorted( + [(1, 1, 1)] + [(group, 1, None) for group in (2, 3, 4)] + [(None, None, label) for label in (2, 3, 4)], + key=repr, + ) + finally: + layer.adapter.close() diff --git a/tests/queries/test_multi_fact_combine.py b/tests/queries/test_multi_fact_combine.py new file mode 100644 index 000000000..55e299f59 --- /dev/null +++ b/tests/queries/test_multi_fact_combine.py @@ -0,0 +1,260 @@ +"""Independently aggregated fact sources combine on their shared dimensions.""" + +import pytest +import sqlglot +from sqlglot import exp + +from sidemantic import Dimension, Metric, Model, Relationship, SemanticLayer +from tests.utils import fetch_rows + +ENGINES = ["python", "rust"] + + +def _shop_layer(engine: str, dialect: str | None = None) -> SemanticLayer: + if engine == "rust": + pytest.importorskip("sidemantic_rs") + layer = SemanticLayer(engine=engine, fallback=False, auto_register=False, dialect=dialect) + layer.add_model( + Model( + name="customers", + table="customers", + primary_key="id", + dimensions=[Dimension(name="region", type="categorical")], + metrics=[Metric(name="customer_count", agg="count")], + ) + ) + layer.add_model( + Model( + name="orders", + table="orders", + primary_key="id", + relationships=[Relationship(name="customers", type="many_to_one", foreign_key="customer_id")], + dimensions=[ + Dimension(name="status", type="categorical"), + Dimension(name="created_at", type="time", granularity="day"), + ], + metrics=[Metric(name="total_amount", agg="sum", sql="amount")], + ) + ) + layer.add_model( + Model( + name="order_items", + table="order_items", + primary_key="id", + relationships=[Relationship(name="orders", type="many_to_one", foreign_key="order_id")], + metrics=[Metric(name="total_qty", agg="sum", sql="qty")], + ) + ) + return layer + + +def _load_shop(layer: SemanticLayer) -> None: + """One order without a customer, one customer without orders, one item without an order.""" + layer.adapter.execute("CREATE TABLE customers (id INTEGER, region VARCHAR)") + layer.adapter.execute("INSERT INTO customers VALUES (1, 'EU'), (2, 'US'), (3, 'US'), (4, NULL), (5, 'APAC')") + layer.adapter.execute( + "CREATE TABLE orders (id INTEGER, customer_id INTEGER, status VARCHAR, amount INTEGER, created_at TIMESTAMP)" + ) + layer.adapter.execute( + """ + INSERT INTO orders VALUES + (1, 1, 'completed', 100, '2024-01-05 10:00:00'), + (2, 1, 'pending', 50, '2024-01-20 11:00:00'), + (3, 2, 'completed', 75, '2024-02-03 09:30:00'), + (4, 3, 'cancelled', 20, '2024-02-10 14:00:00'), + (5, NULL, 'completed', 33, '2024-02-15 08:00:00'), + (6, 4, 'completed', 60, '2024-03-01 12:00:00') + """ + ) + layer.adapter.execute("CREATE TABLE order_items (id INTEGER, order_id INTEGER, qty INTEGER)") + layer.adapter.execute( + "INSERT INTO order_items VALUES (1, 1, 2), (2, 1, 1), (3, 2, 2), (4, 3, 3), (5, 5, 1), (6, 6, 2), (7, NULL, 4)" + ) + + +@pytest.fixture(params=ENGINES) +def shop(request): + layer = _shop_layer(request.param) + _load_shop(layer) + yield layer + layer.adapter.close() + + +def _full_join_conditions(sql: str, dialect: str) -> dict[str, list[exp.Expression]]: + """Conjuncts of every FULL JOIN condition, keyed by the joined relation.""" + conditions = {} + for join in sqlglot.parse_one(sql, read=dialect).find_all(exp.Join): + if join.side == "FULL": + condition = join.args["on"] + conditions[join.alias_or_name] = ( + list(condition.flatten()) if isinstance(condition, exp.And) else [condition] + ) + return conditions + + +def _is_null_safe_combine_key(conjuncts: list[exp.Expression]) -> bool: + """One generated key: equal as array elements, and equally NULL.""" + if len(conjuncts) != 2 or not all(type(conjunct) is exp.EQ for conjunct in conjuncts): + return False + elements, null_flags = conjuncts + wrapped = [side.expressions[0] for side in (elements.left, elements.right) if isinstance(side, exp.Array)] + flagged = [ + side.unnest().this + for side in (null_flags.left, null_flags.right) + if isinstance(side.unnest(), exp.Is) and isinstance(side.unnest().expression, exp.Null) + ] + return len(wrapped) == 2 and wrapped == flagged + + +@pytest.mark.parametrize("engine", ENGINES) +@pytest.mark.parametrize( + ("metrics", "dimensions", "full_joins"), + [ + (["orders.total_amount", "order_items.total_qty"], ["customers.region"], 1), + ( + ["orders.total_amount", "order_items.total_qty", "customers.customer_count"], + ["customers.region", "orders.created_at__month"], + 2, + ), + ], + ids=["two-sources", "three-sources-two-dimensions"], +) +def test_postgres_full_join_uses_only_equality_conditions(engine, metrics, dimensions, full_joins): + """PostgreSQL rejects FULL JOIN conditions that are not hash- or merge-joinable.""" + layer = _shop_layer(engine, dialect="postgres") + try: + structured = layer.compile(metrics=metrics, dimensions=dimensions) + semantic_sql = f"SELECT {', '.join(dimensions + metrics)} FROM orders" + rewritten = layer.explain_sql(semantic_sql).rewritten_sql + for sql in (structured, rewritten): + joins = _full_join_conditions(sql, "postgres") + assert len(joins) == full_joins, sql + for conjuncts in joins.values(): + assert all(type(conjunct) is exp.EQ for conjunct in conjuncts), sql + # A bare column equality would drop the NULL dimension bucket. + keys = [conjuncts[index : index + 2] for index in range(0, len(conjuncts), 2)] + assert len(keys) == len(dimensions), sql + assert all(_is_null_safe_combine_key(key) for key in keys), sql + finally: + layer.adapter.close() + + +@pytest.mark.parametrize("engine", ENGINES) +@pytest.mark.parametrize("dialect", ["postgres", "duckdb"]) +def test_authored_full_join_condition_is_emitted_as_written(engine, dialect): + """Only generated combine keys are lowered for PostgreSQL, never the query's own joins. + + Wrapping an array-valued operand would make NULL and the empty array compare as equal. + """ + layer = _shop_layer(engine, dialect=dialect) + try: + rewritten = layer.explain_sql( + "SELECT s.region, s.total_amount, s.total_qty, labels.name" + " FROM (SELECT customers.region, orders.total_amount, order_items.total_qty FROM orders) AS s" + " FULL OUTER JOIN labels ON s.total_amount = labels.amount AND s.region IS NOT DISTINCT FROM labels.tags" + ).rewritten_sql + joins = _full_join_conditions(rewritten, dialect) + assert set(joins) == {"labels", "order_items_preagg"}, rewritten + + authored = joins["labels"] + assert [type(conjunct) for conjunct in authored] == [exp.EQ, exp.NullSafeEQ], rewritten + assert authored[1].sql(dialect=dialect) == "s.region IS NOT DISTINCT FROM labels.tags" + assert not list(authored[1].find_all(exp.Array)), rewritten + + generated = joins["order_items_preagg"] + if dialect == "postgres": + assert _is_null_safe_combine_key(generated), rewritten + else: + assert [type(conjunct) for conjunct in generated] == [exp.NullSafeEQ], rewritten + finally: + layer.adapter.close() + + +def test_three_sources_share_null_and_unmatched_dimension_groups(shop): + rows = fetch_rows( + shop.sql( + "SELECT customers.region, orders.total_amount, order_items.total_qty, customers.customer_count FROM orders" + ) + ) + assert sorted(rows, key=repr) == sorted( + [ + # Orders 5 and 6 and the orderless item all have no region. + (None, 93, 7, 1), + ("APAC", None, None, 1), + ("EU", 150, 5, 1), + ("US", 95, 3, 2), + ], + key=repr, + ) + + +def test_two_dimensions_including_time_grain_align_across_sources(shop): + rows = fetch_rows( + shop.sql( + "SELECT orders.created_at__month, customers.region, orders.total_amount, order_items.total_qty FROM orders" + ) + ) + months = [(month.isoformat()[:10] if month else None, region, amount, qty) for month, region, amount, qty in rows] + assert sorted(months, key=repr) == sorted( + [ + ("2024-01-01", "EU", 150, 5), + ("2024-02-01", "US", 95, 3), + # The NULL region is its own group inside each month. + ("2024-02-01", None, 33, 1), + ("2024-03-01", None, 60, 2), + (None, None, None, 4), + ], + key=repr, + ) + + +@pytest.mark.parametrize( + ("query", "expected"), + [ + ( + "SELECT customers.region, orders.total_amount, order_items.total_qty FROM orders ORDER BY 2 DESC", + [("EU", 150, 5), ("US", 95, 3), (None, 93, 7)], + ), + ( + # A position refers to the written projection, not the generated one. + "SELECT orders.total_amount, customers.region, order_items.total_qty FROM orders ORDER BY 1 DESC", + [(150, "EU", 5), (95, "US", 3), (93, None, 7)], + ), + ( + "SELECT customers.region, orders.total_amount, order_items.total_qty FROM orders ORDER BY 3, 2", + [("US", 95, 3), ("EU", 150, 5), (None, 93, 7)], + ), + ( + "SELECT customers.region AS r, orders.total_amount AS amt, order_items.total_qty AS q" + " FROM orders ORDER BY amt DESC", + [("EU", 150, 5), ("US", 95, 3), (None, 93, 7)], + ), + ( + "SELECT customers.region, orders.total_amount, order_items.total_qty FROM orders" + " ORDER BY 2 DESC LIMIT 1 OFFSET 1", + [("US", 95, 3)], + ), + ], + ids=["metric-position", "written-projection-position", "two-positions", "select-alias", "position-with-limit"], +) +def test_multi_fact_sql_orders_by_position_and_alias(shop, query, expected): + assert fetch_rows(shop.sql(query)) == expected + + +def test_multi_fact_sql_orders_dimension_by_position(shop): + rows = fetch_rows( + shop.sql("SELECT customers.region, orders.total_amount, order_items.total_qty FROM orders ORDER BY 1") + ) + # Engines place the NULL bucket differently; the named regions must be sorted. + assert [row for row in rows if row[0] is not None] == [("EU", 150, 5), ("US", 95, 3)] + assert (None, 93, 7) in rows and len(rows) == 3 + + +def test_multi_fact_structured_query_orders_by_position(shop): + result = shop.query( + metrics=["orders.total_amount", "order_items.total_qty"], + dimensions=["customers.region"], + order_by=["2 DESC", "1"], + limit=2, + ) + assert fetch_rows(result) == [("EU", 150, 5), ("US", 95, 3)]