Skip to content
Open
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
2 changes: 2 additions & 0 deletions coverage/translation-databricks/not-translatable.toml
Original file line number Diff line number Diff line change
Expand Up @@ -504,6 +504,8 @@ reason = "MATCH_RECOGNIZE matches a regular expression of row patterns over orde
forms = [
"db.functions.classifier",
"db.functions.match-number",
"db.functions.match-recognize-next",
"db.functions.match-recognize-prev",
"db.query.select-match-recognize",
"db.query.select-match-recognize-define",
"db.query.select-match-recognize-measures",
Expand Down
12,024 changes: 7,816 additions & 4,208 deletions coverage/translation-databricks/obligations/functions.toml

Large diffs are not rendered by default.

916 changes: 786 additions & 130 deletions coverage/translation-databricks/results-baseline.json

Large diffs are not rendered by default.

46 changes: 44 additions & 2 deletions coverage/translation-databricks/reviews/results.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Sign-offs of the result-matching measure's link map and not-translatable groups. The link map
# in form-links.toml and the function links are unreviewed.
# Sign-offs of the result-matching measure's link map, not-translatable groups and declared-refusal
# groups. The link map in form-links.toml and the function links are unreviewed.

[[signoff]]
subject = "not-translatable:account-context-functions"
Expand Down Expand Up @@ -108,3 +108,45 @@ subject = "grammar-obligations"
sha256 = "384e845fe7e6a8f56a24583d4f30313bfe4461a7e0569e6b4bb21e52e7a7cbae"
scope = "full"
reviewed_utc = "2026-11-29T20:22:01Z"

[[signoff]]
subject = "declared-refusal:collect-list-order"
sha256 = "4fca209f692a8b9df109cee2c4ac2bd7b922ff9e472c4e8d863b2050d58b7f56"
scope = "full"
reviewed_utc = "2026-11-30T16:27:56Z"

[[signoff]]
subject = "declared-refusal:first-last-order"
sha256 = "bacde106ddb39b9f2df7902bc65f824d681e1bfab189ab89dd909662aa87336f"
scope = "full"
reviewed_utc = "2026-11-30T16:27:56Z"

[[signoff]]
subject = "declared-refusal:float-sum-order"
sha256 = "ad0ce4f8124de57a63cd12ca8100047a5d54a2ed4c8cc224f86ef9686a113a2d"
scope = "full"
reviewed_utc = "2026-11-30T16:27:56Z"

[[signoff]]
subject = "declared-refusal:regex-column-pattern"
sha256 = "2c182d829dc09c883af487226cb3263b94273771fe7fd119b6b933038f7442e0"
scope = "full"
reviewed_utc = "2026-11-30T16:27:56Z"

[[signoff]]
subject = "declared-refusal:to-binary-odd-hex"
sha256 = "53088ee55d65e3a5c0cb71ee326e03d7042afeb58b73078eee8e73a21d4db47d"
scope = "full"
reviewed_utc = "2026-11-30T16:27:56Z"

[[signoff]]
subject = "declared-refusal:url-decode-invalid-utf8"
sha256 = "0295b1a8499d1ce8ebed385cb9301f870ac8b4cbfa531b457634a4d1a4b0702b"
scope = "full"
reviewed_utc = "2026-11-30T16:27:56Z"

[[signoff]]
subject = "not-translatable:row-pattern-matching"
sha256 = "298da68122f0eabced829d9b3e0638a6cc8f4e00a2da0988e8d94385476fb2d1"
scope = "full"
reviewed_utc = "2026-11-30T16:27:56Z"
8 changes: 5 additions & 3 deletions crates/sqlbabel-compare/src/comparison/_helpers/rows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ pub(crate) struct RowRules {
pub(crate) float32_ulps: u32,
pub(crate) float64_ulps: u32,
/// Wider 64-bit float limits for single columns, by position.
pub(crate) float64_column_ulps: BTreeMap<usize, u32>,
pub(crate) float64_column_ulps: BTreeMap<usize, u64>,
pub(crate) ignore_zone_labels: bool,
/// Columns holding VARIANT text, compared without the whitespace outside JSON strings.
pub(crate) json_columns: Vec<bool>,
Expand Down Expand Up @@ -124,7 +124,9 @@ fn values_match(
let float64_ulps = rules
.float64_column_ulps
.get(&column)
.map_or(rules.float64_ulps, |limit| (*limit).max(rules.float64_ulps));
.map_or(u64::from(rules.float64_ulps), |limit| {
(*limit).max(u64::from(rules.float64_ulps))
});
match (expected, actual) {
(CanonicalValue::Float32(left), CanonicalValue::Float32(right))
if rules.float32_ulps > 0 =>
Expand All @@ -135,7 +137,7 @@ fn values_match(
(CanonicalValue::Float64(left), CanonicalValue::Float64(right))
if float64_ulps > 0 && comparable_by_ulps(*left, *right) =>
{
ulps_apart(ordered64(*left), ordered64(*right)) <= u64::from(float64_ulps)
ulps_apart(ordered64(*left), ordered64(*right)) <= float64_ulps
}
_ => expected == actual,
}
Expand Down
2 changes: 1 addition & 1 deletion crates/sqlbabel-compare/src/comparison/tests/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ pub(crate) fn replay_mismatch(
pub(crate) fn column_replay_mismatch(
recorded_columns: &[TestColumn],
replayed_columns: &[TestColumn],
tolerated: &[(usize, u32)],
tolerated: &[(usize, u64)],
) -> Option<MismatchKind> {
let mut comparator = comparator(0);
comparator.float64_column_ulps = tolerated.iter().copied().collect();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,18 @@ fn given_a_tolerance_for_one_column_when_comparing_then_every_other_float_column
offsets: [2, 0],
expected_mismatch: Some(MismatchKind::Value),
},
ColumnToleranceTestCase {
description: "a limit beyond 2^32 ulps passes a miss of exactly that many",
tolerated: &[(0, 5_000_000_000)],
offsets: [5_000_000_000, 0],
expected_mismatch: None,
},
ColumnToleranceTestCase {
description: "a limit beyond 2^32 ulps fails a miss one unit past it",
tolerated: &[(0, 5_000_000_000)],
offsets: [5_000_000_001, 0],
expected_mismatch: Some(MismatchKind::Value),
},
];
let values = [0.1_f64, 0.7_f64];
let recorded = || {
Expand Down
2 changes: 1 addition & 1 deletion crates/sqlbabel-compare/src/comparison/tests/test_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub(crate) struct ReplayTestCase {
pub(crate) struct ColumnToleranceTestCase {
pub(crate) description: &'static str,
/// Result column positions with a wider 64-bit float limit, and the limit.
pub(crate) tolerated: &'static [(usize, u32)],
pub(crate) tolerated: &'static [(usize, u64)],
/// How many units in the last place each of the two replayed columns is above its recording.
pub(crate) offsets: [u64; 2],
pub(crate) expected_mismatch: Option<MismatchKind>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,14 @@ use crate::databricks::conversion::_helpers::support::typing::rejected_cast;
use crate::databricks::conversion::constants::{
AGGREGATE_RULE, AGGREGATES, ARRAY_SORT_NAME, BITMAP_BITS, BITMAP_POSITION_ERROR, CASE_RULE,
CAST_FUNCTIONS, CAST_RULE, COALESCE_NAME, COLLECT_ORDER, COLLECT_ORDER_ERROR, CONCAT_RULE,
COUNT_NAME, COUNTER_DIFF_NAME, DECODE_CHARSET_ARGUMENTS, DOUBLE_EXACT_DIGITS,
COUNT_NAME, COUNTER_DIFF_NAME, DECODE_CHARSET_ARGUMENTS, DEVIATIONS, DOUBLE_EXACT_DIGITS,
DOUBLE_EXACT_INTEGERS, EXACT_FRACTION_STEPS, FLOAT_ELEMENTS, IDENTIFIER_NAME, IN_LIST_RULE,
INEXACT_SUM_ERROR, LAMBDA_ELEMENT, LAMBDA_FUNCTIONS, MAX_DECIMAL_PRECISION, MEDIAN_ZERO_ERROR,
MIN_IN_ARGUMENTS, MIN_LIST_ARGUMENTS, MODE_TIES, MODE_TIES_ERROR, NANOS_TIMESTAMP_ERROR,
ORDER_FREE_READERS, ORDERED_PICKS, ORDERING_FUNCTIONS, PERCENTILE_NAME, PICK_COUNT_EMPTY_ERROR,
PICK_ORDER, PICK_ORDER_ERROR, PICK_TIES, PICK_TIES_ERROR, RANGE_NAME, SAME_FUNCTION_RULE,
SAME_FUNCTIONS, STRING_AGG_FUNCTION, TIME_DIFF_NAME, UNIT_ARGUMENTS, UNIT_FUNCTIONS,
INEXACT_SUM_ERROR, LAMBDA_ELEMENT, LAMBDA_FUNCTIONS, LAMBDA_INDEX, LAMBDA_TOTAL,
MAX_DECIMAL_PRECISION, MEDIAN_ZERO_ERROR, MIN_IN_ARGUMENTS, MIN_LIST_ARGUMENTS, MODE_TIES,
MODE_TIES_ERROR, MOMENT_ORDER, MOMENT_SPREAD, NANOS_TIMESTAMP_ERROR, ORDER_FREE_READERS,
ORDERED_PICKS, ORDERING_FUNCTIONS, PERCENTILE_NAME, PICK_COUNT_EMPTY_ERROR, PICK_ORDER,
PICK_ORDER_ERROR, PICK_TIES, PICK_TIES_ERROR, RANGE_NAME, SAME_FUNCTION_RULE, SAME_FUNCTIONS,
SAMPLE_MOMENTS, STRING_AGG_FUNCTION, TIME_DIFF_NAME, UNIT_ARGUMENTS, UNIT_FUNCTIONS,
UNWINDOWED_COUNTER_ERROR, WHOLE_AGGREGATES, WITHIN_GROUP_KIND,
};
use crate::databricks::conversion::models::{DatabricksType, Element, Emitted, Literal, Signature};
Expand Down Expand Up @@ -425,7 +426,8 @@ pub(crate) fn aggregate(call: &Aggregate<'_>, site: Site<'_>) -> Result<Emitted,
None => value,
};
let value = match name {
"SUM" | "TRY_SUM" | "MEDIAN" | "AVG" | "MEAN" | "TRY_AVG" => {
"SUM" | "TRY_SUM" | "MEDIAN" | "AVG" | "MEAN" | "TRY_AVG" | "VAR_POP" | "VAR_SAMP"
| "VARIANCE" | "STDDEV_SAMP" | "STDDEV" | "STD" | "STDDEV_POP" => {
as_number(value, DatabricksType::Double)
}
_ => value,
Expand Down Expand Up @@ -570,6 +572,28 @@ pub(crate) fn aggregate(call: &Aggregate<'_>, site: Site<'_>) -> Result<Emitted,
("BITMAP_OR_AGG" | "BITMAP_AND_AGG", T::Binary) if over.is_none() => {
Some(bitmap_aggregate(function, &value.sql))
}
(
"VAR_POP" | "VAR_SAMP" | "VARIANCE" | "STDDEV_SAMP" | "STDDEV" | "STD" | "STDDEV_POP",
data_type,
) if !distinct
&& over.is_none()
&& match data_type {
T::Decimal { precision, .. } => usize::from(precision) <= DOUBLE_EXACT_DIGITS,
data_type => data_type.is_integral() || matches!(data_type, T::Double | T::Float),
} =>
{
let x = as_type(&value, T::Double);
match name {
"VAR_POP" => {
site.log.divergence(MOMENT_ORDER, "fn:VAR_POP");
Some(var_pop(&x))
}
_ => {
site.log.divergence(MOMENT_SPREAD, &format!("fn:{name}"));
Some(two_pass_moment(name, &x))
}
}
}
("BITMAP_CONSTRUCT_AGG", data_type)
if data_type.is_integral() && over.is_none() && !distinct =>
{
Expand All @@ -592,6 +616,48 @@ pub(crate) fn aggregate(call: &Aggregate<'_>, site: Site<'_>) -> Result<Emitted,
})
}

/// VAR_POP of the DOUBLE `x` as Spark's CentralMomentAgg computes it: the count, mean and second central moment updated row by row with Spark's own arithmetic, in the order DuckDB collects the rows; NULL over no rows.
fn var_pop(x: &str) -> Emitted {
let (s, e, t) = (LAMBDA_TOTAL, LAMBDA_ELEMENT, LAMBDA_INDEX);
let n = format!("({s}[1] + CAST(1 AS DOUBLE))");
let delta = format!("({e} - {s}[2])");
let moments = format!(
"list_reduce(list({x}) FILTER (WHERE {x} IS NOT NULL), lambda {s}, {e}: \
[{n}, {s}[2] + {delta} / {n}, {s}[3] + {delta} * ({delta} - {delta} / {n})], \
CAST([0, 0, 0] AS DOUBLE[]))"
);
typed(
format!(
"list_transform([{moments}], lambda {t}: CASE WHEN {t}[1] <= 0 THEN NULL ELSE {t}[3] / {t}[1] END)[1]"
),
DatabricksType::Double,
)
}

/// VAR_SAMP, STDDEV_SAMP, STDDEV_POP or an alias of the DOUBLE `x`, in two passes over the rows.
fn two_pass_moment(name: &str, x: &str) -> Emitted {
let (rows, mean, e) = (LAMBDA_INDEX, LAMBDA_TOTAL, LAMBDA_ELEMENT);
let (fewest, divisor) = match SAMPLE_MOMENTS.contains(&name) {
true => (1, format!("(len({rows}) - 1)")),
false => (0, format!("len({rows})")),
};
let variance = format!(
"list_sum(list_transform({rows}, lambda {e}: ({e} - {mean}) * ({e} - {mean}))) / {divisor}"
);
let result = match DEVIATIONS.contains(&name) {
true => format!("sqrt({variance})"),
false => variance,
};
typed(
format!(
"list_transform([list({x}) FILTER (WHERE {x} IS NOT NULL)], lambda {rows}: \
list_transform([list_avg({rows})], lambda {mean}: \
CASE WHEN len({rows}) > {fewest} THEN {result} END)[1])[1]"
),
DatabricksType::Double,
)
}

/// `BITMAP_OR_AGG` or `BITMAP_AND_AGG` as DuckDB's `bit_or` or `bit_and` of each BINARY zero-padded or cut to 32768 bits, NULLs skipped; all zero bits, or all one bits for AND, when none remain.
fn bitmap_aggregate(function: &str, x: &str) -> Emitted {
let none = match function {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,12 @@ pub(crate) fn defined_query(
query(node, log, &outer, false)
}

/// The DuckDB SQL and columns of a subquery in an expression, which reads no table or column of the query around it.
/// The DuckDB SQL and columns of a subquery in an expression, which reads no table or column of the query around it; its columns name no result column for a divergence.
pub(crate) fn subquery(
node: &Value,
log: &ProvenanceLog,
) -> Result<(String, Vec<(String, DatabricksType)>), Refusal> {
query(node, log, &[], false)
log.without_column_divergences(|| query(node, log, &[], false))
}

/// A query: one block or a set operation of blocks, reading the common tables `outer` defines; a `top` query's results are written as Databricks returns them, a nested one's kept as DuckDB values.
Expand Down
22 changes: 22 additions & 0 deletions crates/sqlbabel-convert/src/databricks/conversion/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,13 @@ pub const WHOLE_AGGREGATES: &[&str] = &[
"MEDIAN",
"COLLECT_LIST",
"ARRAY_AGG",
"VAR_POP",
"VAR_SAMP",
"VARIANCE",
"STDDEV_SAMP",
"STDDEV",
"STD",
"STDDEV_POP",
];
/// The divergence of COLLECT_LIST and ARRAY_AGG, whose element order neither engine defines.
pub const COLLECT_ORDER: &str = "collect_list_order";
Expand Down Expand Up @@ -1304,7 +1311,22 @@ pub const AGGREGATES: &[(&str, &str)] = &[
("BITMAP_OR_AGG", "bit_or"),
("BITMAP_AND_AGG", "bit_and"),
("BITMAP_CONSTRUCT_AGG", "bitstring_agg"),
("VAR_POP", "var_pop"),
("VAR_SAMP", "var_samp"),
("VARIANCE", "var_samp"),
("STDDEV_SAMP", "stddev_samp"),
("STDDEV", "stddev_samp"),
("STD", "stddev_samp"),
("STDDEV_POP", "stddev_pop"),
];
/// The divergence of VAR_POP, whose result depends on the order rows arrive, as in Databricks.
pub const MOMENT_ORDER: &str = "central_moment_order";
/// The divergence of the two-pass VAR_SAMP, STDDEV_SAMP, STDDEV_POP and their aliases.
pub const MOMENT_SPREAD: &str = "moment_spread";
/// The sample moments, dividing by one less than the count: VAR_SAMP, STDDEV_SAMP and aliases.
pub const SAMPLE_MOMENTS: &[&str] = &["VAR_SAMP", "VARIANCE", "STDDEV_SAMP", "STDDEV", "STD"];
/// The moments whose result is a standard deviation, the square root of the variance.
pub const DEVIATIONS: &[&str] = &["STDDEV_SAMP", "STDDEV", "STD", "STDDEV_POP"];

/// The functions named after a type, which cast their one argument to it.
pub const CAST_FUNCTIONS: &[(&str, DatabricksType)] = &[
Expand Down
2 changes: 2 additions & 0 deletions crates/sqlbabel-convert/src/databricks/conversion/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
mod test_aggregates;
#[path = "tests/test_categories.rs"]
mod test_categories;
#[path = "tests/test_column_divergences.rs"]
mod test_column_divergences;
#[path = "tests/test_convert.rs"]
mod test_convert;
#[path = "tests/test_convert_effect.rs"]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,45 @@ fn given_an_order_dependent_aggregate_when_converted_then_duckdb_orders_or_raise
expected_sql: &["(CASE WHEN count(DISTINCT \"s\") <= 1 THEN min(\"s\") ELSE"],
expected_types: &[DatabricksType::String],
},
ConvertTestCase {
description: "VAR_POP updates Spark's count, mean and second moment row by row, NULL over no rows",
query: "SELECT var_pop(x1) AS v FROM input",
expected_sql: &[
"list_reduce(list(CAST(\"x1\" AS DOUBLE)) FILTER (WHERE CAST(\"x1\" AS DOUBLE) IS NOT NULL), lambda total, element: \
[(total[1] + CAST(1 AS DOUBLE)), total[2] + (element - total[2]) / (total[1] + CAST(1 AS DOUBLE)), \
total[3] + (element - total[2]) * ((element - total[2]) - (element - total[2]) / (total[1] + CAST(1 AS DOUBLE)))]",
"lambda slot: CASE WHEN slot[1] <= 0 THEN NULL ELSE slot[3] / slot[1] END)[1] AS \"v\"",
],
expected_types: &[DatabricksType::Double],
},
ConvertTestCase {
description: "VAR_SAMP sums squared deviations from the mean and divides by one less than the count",
query: "SELECT var_samp(x1) AS v FROM input",
expected_sql: &[
"list_transform([list(CAST(\"x1\" AS DOUBLE)) FILTER (WHERE CAST(\"x1\" AS DOUBLE) IS NOT NULL)], lambda slot: \
list_transform([list_avg(slot)], lambda total: CASE WHEN len(slot) > 1 THEN \
list_sum(list_transform(slot, lambda element: (element - total) * (element - total))) / (len(slot) - 1) END)[1])[1] AS \"v\"",
],
expected_types: &[DatabricksType::Double],
},
ConvertTestCase {
description: "STD, an alias of STDDEV_SAMP, takes the square root of the sample variance",
query: "SELECT std(x1) AS v FROM input",
expected_sql: &[
"CASE WHEN len(slot) > 1 THEN sqrt(list_sum(",
") / (len(slot) - 1)) END",
],
expected_types: &[DatabricksType::Double],
},
ConvertTestCase {
description: "STDDEV_POP divides by the count and is 0 over one row",
query: "SELECT stddev_pop(x1) AS v FROM input",
expected_sql: &[
"CASE WHEN len(slot) > 0 THEN sqrt(list_sum(",
") / len(slot)) END",
],
expected_types: &[DatabricksType::Double],
},
];
for test_case in test_cases {
let converted = analyze(&format!("{FIXTURE}{}", test_case.query))
Expand Down Expand Up @@ -70,6 +109,26 @@ fn given_an_order_dependent_aggregate_no_rule_orders_when_converted_then_it_is_r
query: "SELECT listagg(x1, ',') WITHIN GROUP (ORDER BY x1) AS r FROM input",
expected_reason: "LISTAGG of INT",
},
RefuseTestCase {
description: "VAR_POP with DISTINCT, whose order of distinct values no recording shows",
query: "SELECT var_pop(DISTINCT x1) AS r FROM input",
expected_reason: "no rule converts VAR_POP of INT with DISTINCT",
},
RefuseTestCase {
description: "VAR_POP over a window, which no rule converts",
query: "SELECT var_pop(x1) OVER (ORDER BY ordinal) AS r FROM input",
expected_reason: "as a window function",
},
RefuseTestCase {
description: "STDDEV with DISTINCT, whose two passes over distinct values no recording shows",
query: "SELECT stddev(DISTINCT x1) AS r FROM input",
expected_reason: "no rule converts STDDEV of INT with DISTINCT",
},
RefuseTestCase {
description: "VARIANCE over a window, which no rule converts",
query: "SELECT variance(x1) OVER (ORDER BY ordinal) AS r FROM input",
expected_reason: "as a window function",
},
];
for test_case in test_cases {
let reason = analyze(&format!("{FIXTURE}{}", test_case.query))
Expand Down
Loading
Loading