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
6 changes: 6 additions & 0 deletions crates/ddx-ad/src/to_sql/ir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,12 @@ pub(super) enum Expr {
},
Not(Box<Expr>),
Negate(Box<Expr>),
/// `expr BETWEEN low AND high`, which holds both bounds.
Between {
expr: Box<Expr>,
low: Box<Expr>,
high: Box<Expr>,
},
Is {
expr: Box<Expr>,
test: IsTest,
Expand Down
30 changes: 30 additions & 0 deletions crates/ddx-ad/src/to_sql/print.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,15 @@ impl Printer {
self.expr(x);
self.sql.push(')');
}
Expr::Between { expr, low, high } => {
self.sql.push('(');
self.expr(expr);
self.sql.push_str(" BETWEEN ");
self.expr(low);
self.sql.push_str(" AND ");
self.expr(high);
self.sql.push(')');
}
Expr::Is { expr, test } => {
self.sql.push('(');
self.expr(expr);
Expand Down Expand Up @@ -714,4 +723,25 @@ mod tests {
"(CAST(7 AS BIGINT) / CAST(2 AS BIGINT))"
);
}

#[test]
fn between_holds_both_bounds_in_each_dialect() {
let int = |i| Box::new(Expr::Literal(Literal::Int(i, Type::BigInt)));
let e = Expr::Between {
expr: int(1),
low: int(0),
high: int(2),
};
for dialect in [Dialect::DuckDb, Dialect::DataFusion] {
let mut p = Printer {
dialect,
sql: String::new(),
};
p.expr(&e);
assert_eq!(
p.sql,
"(CAST(1 AS BIGINT) BETWEEN CAST(0 AS BIGINT) AND CAST(2 AS BIGINT))"
);
}
}
}
20 changes: 20 additions & 0 deletions crates/ddx-ad/src/to_sql/reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1206,6 +1206,19 @@ impl Reader<'_> {
}
Syntax::Not => Expr::Not(one(&mut args)?),
Syntax::Negate => Expr::Negate(one(&mut args)?),
Syntax::Between => match <[Expr; 3]>::try_from(args) {
Ok([expr, low, high]) => Expr::Between {
expr: Box::new(expr),
low: Box::new(low),
high: Box::new(high),
},
Err(args) => {
return Err(AdError::InvalidPlan(format!(
"`{name}` takes three arguments, not {}",
args.len()
)))
}
},
Syntax::Is(test) => Expr::Is {
expr: one(&mut args)?,
test,
Expand Down Expand Up @@ -1444,6 +1457,7 @@ enum Syntax {
Operator(Op),
Not,
Negate,
Between,
Is(IsTest),
/// The function's argument itself: ddx's stop-gradient, the identity
/// at run time.
Expand Down Expand Up @@ -1476,6 +1490,12 @@ fn syntax(name: &str) -> Option<Syntax> {
"is_not_distinct_from" => Operator(ir::Op::IsNotDistinctFrom),
"not" => Not,
"negate" | "negative" => Negate,
// DuckDB's optimizer derives `between` from a range filter through a
// join's equality, and ANDs it with that filter's comparisons; its
// producer drops whether each bound is held. Read as holding both,
// it is the widest it could mean, and the comparisons beside it
// keep the rows exact.
"between" => Between,
"is_null" => Is(IsTest::Null),
"is_not_null" => Is(IsTest::NotNull),
"is_true" => Is(IsTest::True),
Expand Down
18 changes: 18 additions & 0 deletions python/ddxdb/tests/test_duckdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -997,3 +997,21 @@ def test_in_place_is_refused_on_duckdb(con):

with pytest.raises(ValueError, match="in_place"):
ad.prepare(con, [GRAD], in_place=True)


def test_a_range_duckdb_derives_through_a_join_is_written(ad):
# Through `a.i1 = b.i1`, DuckDB derives `between(i1 - 2, 0, 2)` for `a`
# from `b`'s `i1 >= 0 AND i1 < 2` (#263), beside `a`'s own filter: two
# slices of one table, multiplied, as torch-sql's split.
con = duckdb.connect()
i0, i1 = [i // 6 for i in range(12)], [i % 6 for i in range(12)]
con.register("w", pa.table({"i0": i0, "i1": i1, "v": [float(i) for i in range(12)]}))
loss = """
WITH a AS (SELECT i0, i1 - 2 AS i1, v FROM w WHERE i1 >= 2 AND i1 < 4),
c AS (SELECT i0, i1, v FROM w WHERE i1 >= 0 AND i1 < 2),
p AS (SELECT a.i0, a.i1, a.v * c.v AS v FROM a JOIN c ON a.i0 = c.i0 AND a.i1 = c.i1)
SELECT SUM(v) AS l FROM p"""
rel = ad.sql(con, f"WITH loss AS ({loss}) SELECT i0, i1, grad(loss, v) FROM w")
# d/dv[i0, j] is v[i0, j + 2] for j < 2, and v[i0, j - 2] for j in 2, 3.
expected = [(r, j, float(6 * r + {0: 2, 1: 3, 2: 0, 3: 1}[j]) if j < 4 else 0.0) for r in range(2) for j in range(6)]
assert sorted(rel.fetchall()) == expected
Loading