Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions sidemantic-rs/src/semantic_input/dialects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
113 changes: 109 additions & 4 deletions sidemantic-rs/src/sql/generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<DialectType>,
timezone: Option<String>,
}

Expand All @@ -186,6 +188,7 @@ impl<'a> SqlGenerator<'a> {
Self {
graph,
dialect: SOURCE_DIALECT,
emitted_dialect: None,
timezone: None,
}
}
Expand All @@ -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<String>) -> Self {
self.timezone = timezone;
self
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -2711,17 +2737,27 @@ 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 {
let join_conditions = dimension_refs
.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::<Vec<_>>();
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::<Vec<_>>();
Expand Down Expand Up @@ -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
Expand Down
71 changes: 67 additions & 4 deletions sidemantic-rs/src/sql/generator/aggregate_plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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;
Expand All @@ -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
Expand Down Expand Up @@ -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::<Vec<_>>();
if query.with_totals {
Expand Down Expand Up @@ -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::<usize>()
.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
Expand Down Expand Up @@ -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();
Expand Down
1 change: 1 addition & 0 deletions sidemantic-rs/src/sql/generator/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Loading
Loading