From 16bc30338a9fcc30cad7fde767d40931662fe775 Mon Sep 17 00:00:00 2001 From: Nico Ritschel Date: Mon, 9 Nov 2026 15:42:22 -0800 Subject: [PATCH 1/2] Combine multi-fact sources with join keys PostgreSQL can plan Queries selecting metrics from several models aggregate each model in its own CTE and FULL OUTER JOIN them on the shared dimensions with IS NOT DISTINCT FROM. PostgreSQL only plans FULL JOIN on hash- or merge-joinable operators, so every multi-fact query with a dimension failed with "FULL JOIN is only supported with merge-joinable or hash-joinable join conditions". For PostgreSQL, compare single-element arrays instead: array equality is hash- and merge-joinable, uses the column type's own comparison, and treats NULL elements as equal, so NULL dimension buckets still meet in one row. Other dialects keep IS NOT DISTINCT FROM. The Rust engine gets the same condition in both combine paths, plus a PostgreSQL emission step for semantic SQL, whose leaves are generated as DuckDB before final emission. Its legacy combine path now also matches each source against every preceding source rather than only the first. ORDER BY positions in the same path were quoted as a column named "1". Pass a position through as a position in the Python engine and resolve it to the output column in the Rust aggregate plan. --- sidemantic-rs/src/semantic_input/dialects.rs | 106 +++++++++ sidemantic-rs/src/sql/generator.rs | 97 +++++++- .../src/sql/generator/aggregate_plan.rs | 69 +++++- sidemantic/sql/generator.py | 22 +- tests/db/test_postgres_integration.py | 128 +++++++++++ tests/queries/test_multi_fact_combine.py | 209 ++++++++++++++++++ 6 files changed, 621 insertions(+), 10 deletions(-) create mode 100644 tests/queries/test_multi_fact_combine.py diff --git a/sidemantic-rs/src/semantic_input/dialects.rs b/sidemantic-rs/src/semantic_input/dialects.rs index d2b5bd9cc..c6e09d680 100644 --- a/sidemantic-rs/src/semantic_input/dialects.rs +++ b/sidemantic-rs/src/semantic_input/dialects.rs @@ -206,6 +206,11 @@ fn emit_transformed( target: DialectType, ) -> Result { let expression = super::literals::target_expression(expression, target)?; + let expression = if target == DialectType::PostgreSQL { + postgres_full_join_keys(expression)? + } else { + expression + }; // Generated ASTs can contain target SQL leaves. Keep them as ASTs instead // of reparsing target-quoted identifiers as source SQL. Authored input uses // the complete transpile pipeline below before reaching this boundary. @@ -216,6 +221,72 @@ fn emit_transformed( generate_preserving_null_order(&expression, target, source) } +/// 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, so the NULL-safe +/// key match of independently aggregated sources survives unchanged. +fn postgres_full_join_keys(expression: Expression) -> Result { + use polyglot_sql::expressions::{ArrayConstructor, BinaryOp}; + + fn array(element: Expression) -> Expression { + Expression::ArrayFunc(Box::new(ArrayConstructor { + expressions: vec![element], + bracket_notation: true, + use_list_keyword: false, + })) + } + // Only top-level conjuncts are join keys; anything else keeps its meaning. + fn lower(condition: Expression) -> Expression { + match condition { + Expression::And(operands) => { + let mut operands = *operands; + operands.left = lower(operands.left); + operands.right = lower(operands.right); + Expression::And(Box::new(operands)) + } + Expression::Paren(inner) => { + let mut inner = *inner; + inner.this = lower(inner.this); + Expression::Paren(Box::new(inner)) + } + Expression::NullSafeEq(operands) => Expression::Eq(Box::new(BinaryOp::new( + array(operands.left), + array(operands.right), + ))), + other => other, + } + } + fn visit(value: &mut Value) -> Result<()> { + match value { + Value::Object(fields) => { + for child in fields.values_mut() { + visit(child)?; + } + // Joins are plain structs in the serialized AST, not tagged nodes. + let full_join = fields.get("kind").and_then(Value::as_str) == Some("Full") + && fields.contains_key("using"); + if let Some(on) = fields.get_mut("on").filter(|on| full_join && !on.is_null()) { + let condition: Expression = serde_json::from_value(on.take()) + .map_err(|error| SidemanticError::SqlGeneration(error.to_string()))?; + *on = serde_json::to_value(lower(condition)) + .map_err(|error| SidemanticError::SqlGeneration(error.to_string()))?; + } + } + Value::Array(values) => { + for child in values { + visit(child)?; + } + } + _ => {} + } + Ok(()) + } + let mut value = serde_json::to_value(expression) + .map_err(|error| SidemanticError::SqlGeneration(error.to_string()))?; + visit(&mut value)?; + serde_json::from_value(value).map_err(|error| SidemanticError::SqlGeneration(error.to_string())) +} + /// Preserve explicit NULL placement even when the warehouse's mutable session /// default currently matches it. Polyglot otherwise omits that clause. Render /// only the Ordered leaf as target SQL after transformation, keeping every other @@ -843,6 +914,41 @@ pub(super) fn normalize( mod tests { use super::*; + #[test] + fn postgres_full_join_uses_hash_joinable_null_safe_keys() { + let source = "SELECT * FROM a FULL OUTER JOIN b \ + ON a.x IS NOT DISTINCT FROM b.x AND a.total = b.total \ + FULL OUTER JOIN c ON COALESCE(a.x, b.x) IS NOT DISTINCT FROM c.x \ + LEFT JOIN d ON c.x IS NOT DISTINCT FROM d.x"; + let emitted = |target| { + let expression = parse(source, DialectType::DuckDB).unwrap(); + emit(expression, DialectType::DuckDB, target).unwrap() + }; + let postgres = emitted(DialectType::PostgreSQL); + assert!( + postgres.contains("ON ARRAY[a.x] = ARRAY[b.x] AND a.total = b.total"), + "{postgres}" + ); + assert!( + postgres.contains("ON ARRAY[COALESCE(a.x, b.x)] = ARRAY[c.x]"), + "{postgres}" + ); + // Other join kinds accept the operator as written. + assert!( + postgres.contains("LEFT JOIN d ON c.x IS NOT DISTINCT FROM d.x"), + "{postgres}" + ); + for target in [DialectType::DuckDB, DialectType::Snowflake] { + let sql = emitted(target); + assert!(!sql.contains("ARRAY["), "{target:?}: {sql}"); + assert_eq!( + sql.matches("IS NOT DISTINCT FROM").count(), + 3, + "{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..f93d724e5 100644 --- a/sidemantic-rs/src/sql/generator.rs +++ b/sidemantic-rs/src/sql/generator.rs @@ -2570,6 +2570,19 @@ 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.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. + format!("ARRAY[{left}] = ARRAY[{right}]") + } else { + format!("{left} IS NOT DISTINCT FROM {right}") + } + } + fn generate_with_preaggregation( &self, query: &SemanticQuery, @@ -2711,7 +2724,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 +2732,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 +8496,72 @@ 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]" + ), + "{sql}" + ); + assert!( + sql.contains( + "FULL OUTER JOIN customers_preagg ON ARRAY[COALESCE(orders_preagg.country, \ + order_items_preagg.country)] = ARRAY[customers_preagg.country]" + ), + "{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..e77a6bc9a 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,55 @@ 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]" + ), + "{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/sql/generator.py b/sidemantic/sql/generator.py index 0741646d5..e093a7d0b 100644 --- a/sidemantic/sql/generator.py +++ b/sidemantic/sql/generator.py @@ -3290,6 +3290,18 @@ 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. + condition = exp.EQ(this=exp.Array(expressions=[left]), expression=exp.Array(expressions=[right])) + 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 +3666,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 +3721,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..4f6f54777 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,129 @@ 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() diff --git a/tests/queries/test_multi_fact_combine.py b/tests/queries/test_multi_fact_combine.py new file mode 100644 index 000000000..539d60166 --- /dev/null +++ b/tests/queries/test_multi_fact_combine.py @@ -0,0 +1,209 @@ +"""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) -> list[exp.Expression]: + conditions = [] + for join in sqlglot.parse_one(sql, read=dialect).find_all(exp.Join): + if join.side == "FULL": + condition = join.args["on"] + conditions.extend(condition.flatten() if isinstance(condition, exp.And) else [condition]) + return conditions + + +@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): + conditions = _full_join_conditions(sql, "postgres") + assert len(conditions) == full_joins * len(dimensions), sql + assert all(type(condition) is exp.EQ for condition in conditions), sql + # A bare column equality would drop the NULL dimension bucket. + assert all(isinstance(side, exp.Array) for c in conditions for side in (c.left, c.right)), sql + 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)] From 65f8de5349455ed333cf8a16c12ff12c074af6ea Mon Sep 17 00:00:00 2001 From: Nico Ritschel Date: Mon, 9 Nov 2026 16:26:54 -0800 Subject: [PATCH 2/2] Lower only generated combine keys for PostgreSQL The Rust engine lowered every FULL JOIN ... IS NOT DISTINCT FROM to an array comparison while emitting PostgreSQL, including joins written in the query. For an array-valued operand that changes the result: wrapping turns both NULL and the empty array into the empty array, so `a.tags IS NOT DISTINCT FROM b.tags` started matching NULL tags with empty tags. Remove the emitter rewrite. The semantic SQL rewriter now tells the generator which dialect the statement is emitted in, and the generator writes the PostgreSQL form of its own combine keys; authored joins pass through as written. The same wrapping made the generated combine merge the NULL and empty-array groups of an array-valued dimension. Both engines now also require the keys to agree on being NULL, which keeps the join hash-joinable and is a no-op for scalar keys. --- sidemantic-rs/src/semantic_input/dialects.rs | 111 ++---------------- sidemantic-rs/src/sql/generator.rs | 26 +++- .../src/sql/generator/aggregate_plan.rs | 4 +- sidemantic-rs/src/sql/generator/options.rs | 1 + sidemantic-rs/src/sql/rewriter.rs | 99 ++++++++++++++++ sidemantic-rs/src/sql/rewriter/binding.rs | 6 +- sidemantic-rs/src/sql/rewriter/policy.rs | 1 + sidemantic/sql/generator.py | 15 ++- tests/db/test_postgres_integration.py | 75 ++++++++++++ tests/queries/test_multi_fact_combine.py | 67 +++++++++-- 10 files changed, 290 insertions(+), 115 deletions(-) diff --git a/sidemantic-rs/src/semantic_input/dialects.rs b/sidemantic-rs/src/semantic_input/dialects.rs index c6e09d680..e0626f370 100644 --- a/sidemantic-rs/src/semantic_input/dialects.rs +++ b/sidemantic-rs/src/semantic_input/dialects.rs @@ -206,11 +206,6 @@ fn emit_transformed( target: DialectType, ) -> Result { let expression = super::literals::target_expression(expression, target)?; - let expression = if target == DialectType::PostgreSQL { - postgres_full_join_keys(expression)? - } else { - expression - }; // Generated ASTs can contain target SQL leaves. Keep them as ASTs instead // of reparsing target-quoted identifiers as source SQL. Authored input uses // the complete transpile pipeline below before reaching this boundary. @@ -221,72 +216,6 @@ fn emit_transformed( generate_preserving_null_order(&expression, target, source) } -/// 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, so the NULL-safe -/// key match of independently aggregated sources survives unchanged. -fn postgres_full_join_keys(expression: Expression) -> Result { - use polyglot_sql::expressions::{ArrayConstructor, BinaryOp}; - - fn array(element: Expression) -> Expression { - Expression::ArrayFunc(Box::new(ArrayConstructor { - expressions: vec![element], - bracket_notation: true, - use_list_keyword: false, - })) - } - // Only top-level conjuncts are join keys; anything else keeps its meaning. - fn lower(condition: Expression) -> Expression { - match condition { - Expression::And(operands) => { - let mut operands = *operands; - operands.left = lower(operands.left); - operands.right = lower(operands.right); - Expression::And(Box::new(operands)) - } - Expression::Paren(inner) => { - let mut inner = *inner; - inner.this = lower(inner.this); - Expression::Paren(Box::new(inner)) - } - Expression::NullSafeEq(operands) => Expression::Eq(Box::new(BinaryOp::new( - array(operands.left), - array(operands.right), - ))), - other => other, - } - } - fn visit(value: &mut Value) -> Result<()> { - match value { - Value::Object(fields) => { - for child in fields.values_mut() { - visit(child)?; - } - // Joins are plain structs in the serialized AST, not tagged nodes. - let full_join = fields.get("kind").and_then(Value::as_str) == Some("Full") - && fields.contains_key("using"); - if let Some(on) = fields.get_mut("on").filter(|on| full_join && !on.is_null()) { - let condition: Expression = serde_json::from_value(on.take()) - .map_err(|error| SidemanticError::SqlGeneration(error.to_string()))?; - *on = serde_json::to_value(lower(condition)) - .map_err(|error| SidemanticError::SqlGeneration(error.to_string()))?; - } - } - Value::Array(values) => { - for child in values { - visit(child)?; - } - } - _ => {} - } - Ok(()) - } - let mut value = serde_json::to_value(expression) - .map_err(|error| SidemanticError::SqlGeneration(error.to_string()))?; - visit(&mut value)?; - serde_json::from_value(value).map_err(|error| SidemanticError::SqlGeneration(error.to_string())) -} - /// Preserve explicit NULL placement even when the warehouse's mutable session /// default currently matches it. Polyglot otherwise omits that clause. Render /// only the Ordered leaf as target SQL after transformation, keeping every other @@ -915,35 +844,21 @@ mod tests { use super::*; #[test] - fn postgres_full_join_uses_hash_joinable_null_safe_keys() { + 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.x IS NOT DISTINCT FROM b.x AND a.total = b.total \ - FULL OUTER JOIN c ON COALESCE(a.x, b.x) IS NOT DISTINCT FROM c.x \ - LEFT JOIN d ON c.x IS NOT DISTINCT FROM d.x"; - let emitted = |target| { + 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(); - emit(expression, DialectType::DuckDB, target).unwrap() - }; - let postgres = emitted(DialectType::PostgreSQL); - assert!( - postgres.contains("ON ARRAY[a.x] = ARRAY[b.x] AND a.total = b.total"), - "{postgres}" - ); - assert!( - postgres.contains("ON ARRAY[COALESCE(a.x, b.x)] = ARRAY[c.x]"), - "{postgres}" - ); - // Other join kinds accept the operator as written. - assert!( - postgres.contains("LEFT JOIN d ON c.x IS NOT DISTINCT FROM d.x"), - "{postgres}" - ); - for target in [DialectType::DuckDB, DialectType::Snowflake] { - let sql = emitted(target); - assert!(!sql.contains("ARRAY["), "{target:?}: {sql}"); - assert_eq!( - sql.matches("IS NOT DISTINCT FROM").count(), - 3, + 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}" ); } diff --git a/sidemantic-rs/src/sql/generator.rs b/sidemantic-rs/src/sql/generator.rs index f93d724e5..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 @@ -2572,12 +2583,14 @@ impl<'a> SqlGenerator<'a> { /// 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.dialect == DialectType::PostgreSQL { + 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. - format!("ARRAY[{left}] = ARRAY[{right}]") + // 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}") } @@ -8548,14 +8561,17 @@ models: assert!( sql.contains( "FULL OUTER JOIN order_items_preagg ON ARRAY[orders_preagg.country] \ - = ARRAY[order_items_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]" + 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}" ); diff --git a/sidemantic-rs/src/sql/generator/aggregate_plan.rs b/sidemantic-rs/src/sql/generator/aggregate_plan.rs index e77a6bc9a..5a417bf22 100644 --- a/sidemantic-rs/src/sql/generator/aggregate_plan.rs +++ b/sidemantic-rs/src/sql/generator/aggregate_plan.rs @@ -1648,7 +1648,9 @@ mod tests { assert!( sql.contains( "FULL OUTER JOIN customers_preagg ON ARRAY[orders_preagg.__sidemantic_dimension_0] \ - = ARRAY[customers_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}" ); 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 e093a7d0b..a30fcfe0f 100644 --- a/sidemantic/sql/generator.py +++ b/sidemantic/sql/generator.py @@ -3296,8 +3296,19 @@ def _full_join_null_safe_equality(self, left: exp.Expression, right: exp.Express # 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. - condition = exp.EQ(this=exp.Array(expressions=[left]), expression=exp.Array(expressions=[right])) + # 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) diff --git a/tests/db/test_postgres_integration.py b/tests/db/test_postgres_integration.py index 4f6f54777..497a83d91 100644 --- a/tests/db/test_postgres_integration.py +++ b/tests/db/test_postgres_integration.py @@ -741,3 +741,78 @@ def test_semantic_layer_postgres_multi_fact_shared_dimensions(clean_postgres): 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 index 539d60166..55e299f59 100644 --- a/tests/queries/test_multi_fact_combine.py +++ b/tests/queries/test_multi_fact_combine.py @@ -80,15 +80,32 @@ def shop(request): layer.adapter.close() -def _full_join_conditions(sql: str, dialect: str) -> list[exp.Expression]: - conditions = [] +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.extend(condition.flatten() if isinstance(condition, exp.And) else [condition]) + 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"), @@ -110,11 +127,45 @@ def test_postgres_full_join_uses_only_equality_conditions(engine, metrics, dimen semantic_sql = f"SELECT {', '.join(dimensions + metrics)} FROM orders" rewritten = layer.explain_sql(semantic_sql).rewritten_sql for sql in (structured, rewritten): - conditions = _full_join_conditions(sql, "postgres") - assert len(conditions) == full_joins * len(dimensions), sql - assert all(type(condition) is exp.EQ for condition in conditions), sql - # A bare column equality would drop the NULL dimension bucket. - assert all(isinstance(side, exp.Array) for c in conditions for side in (c.left, c.right)), sql + 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()