use super::*;
use datafusion::arrow::array::types::{
Decimal128Type, Decimal256Type, DecimalType, validate_decimal_precision_and_scale,
};
use datafusion::arrow::datatypes::{DataType, TimeUnit};
use datafusion::arrow::error::ArrowError;
use datafusion::common::ScalarValue;
use datafusion::common::tree_node::{TreeNode, TreeNodeRecursion};
use datafusion::logical_expr::binary::BinaryTypeCoercer;
use datafusion::logical_expr::{Expr, Operator};
pub fn validate_decimal_scalar_value(value: &ScalarValue) -> Result<(), ArrowError> {
match value {
ScalarValue::Decimal128(value, precision, scale) => {
validate_decimal_precision_and_scale::<Decimal128Type>(*precision, *scale)?;
if let Some(value) = value {
Decimal128Type::validate_decimal_precision(*value, *precision, *scale)?;
}
}
ScalarValue::Decimal256(value, precision, scale) => {
validate_decimal_precision_and_scale::<Decimal256Type>(*precision, *scale)?;
if let Some(value) = value {
Decimal256Type::validate_decimal_precision(*value, *precision, *scale)?;
}
}
_ => {}
}
Ok(())
}
pub fn vm_type_from_data_type(ty: &DataType, nullable: bool) -> Option<VmType> {
use VmScalarType as V;
let scalar = match ty {
DataType::Boolean => V::Bool,
DataType::Int8 => V::Int8,
DataType::Int16 => V::Int16,
DataType::Int32 => V::Int32,
DataType::Int64 => V::Int64,
DataType::UInt8 => V::UInt8,
DataType::UInt16 => V::UInt16,
DataType::UInt32 => V::UInt32,
DataType::UInt64 => V::UInt64,
DataType::Float32 => V::Float32,
DataType::Float64 => V::Float64,
DataType::Utf8 => V::Utf8,
DataType::LargeUtf8 => V::LargeUtf8,
DataType::Utf8View => V::Utf8View,
DataType::Date32 => V::Date32,
DataType::Date64 => V::Date64,
DataType::Time32(u @ (TimeUnit::Second | TimeUnit::Millisecond)) => V::Time32(*u),
DataType::Time64(u @ (TimeUnit::Microsecond | TimeUnit::Nanosecond)) => {
V::Time64(*u)
}
DataType::Duration(u) => V::Duration(*u),
DataType::Timestamp(unit, zone) => V::Timestamp {
unit: *unit,
timezone_aware: zone.is_some(),
},
DataType::Decimal128(p, s) => {
validate_decimal_precision_and_scale::<Decimal128Type>(*p, *s).ok()?;
V::Decimal128 {
precision: *p,
scale: *s,
}
}
DataType::Decimal256(p, s) => {
validate_decimal_precision_and_scale::<Decimal256Type>(*p, *s).ok()?;
V::Decimal256 {
precision: *p,
scale: *s,
}
}
DataType::FixedSizeBinary(width @ 1..=16) => V::FixedSizeBinary(*width as u8),
_ => return None,
};
Some(VmType { scalar, nullable })
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum VmMetadataComparisonColumn {
MatchNumber,
MatchSequenceNumber,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum VmPredicateInputRole {
RowValue,
StaticPredicate { bool_idx: usize },
StaticScalar { scalar_idx: usize },
Classifier,
Metadata(VmMetadataComparisonColumn),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct VmManagedPredicateColumn {
slot_idx: usize,
column_name: String,
scalar_type: Option<VmScalarType>,
}
impl VmManagedPredicateColumn {
pub fn new(
slot_idx: usize,
column_name: String,
scalar_type: Option<VmScalarType>,
) -> Self {
Self {
slot_idx,
column_name,
scalar_type,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct VmPredicateInputColumn {
column_name: String,
ty: Option<VmType>,
role: VmPredicateInputRole,
}
impl VmPredicateInputColumn {
pub fn new(
column_name: String,
ty: Option<VmType>,
role: VmPredicateInputRole,
) -> Self {
Self {
column_name,
ty,
role,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct VmCompileContext {
managed: Vec<VmManagedPredicateColumn>,
inputs: Vec<VmPredicateInputColumn>,
limits: VmCompileLimits,
program_limits: PredicateProgramLimits,
}
impl VmCompileContext {
pub fn try_new(
managed: Vec<VmManagedPredicateColumn>,
inputs: Vec<VmPredicateInputColumn>,
limits: VmCompileLimits,
) -> Result<Self, VmCompileError> {
use VmCompileError::*;
let mut names = std::collections::HashSet::new();
let mut previous = None;
for c in &managed {
u16::try_from(c.slot_idx).map_err(|_| ProgramTooLarge)?;
if !names.insert(&c.column_name) || previous.is_some_and(|p| p >= c.slot_idx)
{
return Err(BindingFailure);
}
previous = Some(c.slot_idx);
}
let (mut bools, mut scalars) = (0, 0);
for c in &inputs {
if !names.insert(&c.column_name) {
return Err(BindingFailure);
}
let (next, index) = match c.role {
VmPredicateInputRole::StaticPredicate { bool_idx } => {
(&mut bools, bool_idx)
}
VmPredicateInputRole::StaticScalar { scalar_idx } => {
(&mut scalars, scalar_idx)
}
_ => continue,
};
u16::try_from(index).map_err(|_| ProgramTooLarge)?;
if index != *next {
return Err(BindingFailure);
}
*next += 1;
}
Ok(Self {
managed,
inputs,
limits: limits.bounded(),
program_limits: Default::default(),
})
}
#[cfg(test)]
pub fn with_program_limits(mut self, limits: PredicateProgramLimits) -> Self {
self.program_limits = limits.bounded();
self
}
}
pub fn compile_direct_predicate(
expr: &Expr,
context: &VmCompileContext,
) -> Result<DirectPredicatePlan, VmCompileError> {
let (mut size, mut literals) = (0, 0);
expr.apply(|e| {
size += 1;
literals += usize::from(matches!(e, Expr::Literal(..)));
Ok(
if size > context.limits.max_ir_nodes
|| literals > context.limits.max_constants
{
TreeNodeRecursion::Stop
} else {
TreeNodeRecursion::Continue
},
)
})
.map_err(|_| VmCompileError::EmissionFailure)?;
if size > context.limits.max_ir_nodes || literals > context.limits.max_constants {
return Err(VmCompileError::ExpressionTooLarge);
}
let mut compiler = Compiler {
context,
nodes: vec![],
rows: vec![],
};
let (root, ty, slots, work, _) = compiler.lower(expr)?;
if ty.scalar != VmScalarType::Bool {
return Err(VmCompileError::TypeResolutionFailure);
}
if work + 1 > context.program_limits.max_operations {
return Err(VmCompileError::ProgramTooLarge);
}
if slots > context.program_limits.max_eval_stack {
return Err(VmCompileError::StackDepthExceeded);
}
Ok(DirectPredicatePlan {
nodes: compiler.nodes,
root,
value_slots: slots as u16,
row_columns: compiler.rows,
})
}
type Value = (u16, VmType, usize, usize, bool);
struct Compiler<'a> {
context: &'a VmCompileContext,
nodes: Vec<PredicateNode>,
rows: Vec<String>,
}
impl Compiler<'_> {
fn lower(&mut self, expr: &Expr) -> Result<Value, VmCompileError> {
use PredicateNode as N;
use VmCompileError::*;
use VmScalarType as T;
let unsupported = UnsupportedNumericTypeCombination;
let (node, ty, slots, work, literal) = match expr {
Expr::Alias(a) => return self.lower(&a.expr),
Expr::Literal(value, _) => {
let ty = vm_type_from_data_type(&value.data_type(), value.is_null())
.ok_or(UnsupportedSourceDomain)?;
validate_decimal_scalar_value(value)
.map_err(|_| UnsupportedSourceDomain)?;
(
N::Source(VmSourceRef::Literal(value.clone())),
ty,
1,
1,
true,
)
}
Expr::Column(c) => {
let source = if let Some(c) = self
.context
.managed
.iter()
.find(|x| x.column_name == c.name)
{
let scalar = c.scalar_type.ok_or(UnsupportedSourceDomain)?;
vm_type_from_data_type(&scalar.arrow_type(), true)
.ok_or(UnsupportedSourceDomain)?;
VmSourceRef::ManagedSlot {
slot_idx: c.slot_idx as u16,
ty: VmType::nullable(scalar),
}
} else {
let c = self
.context
.inputs
.iter()
.find(|x| x.column_name == c.name)
.ok_or(BindingFailure)?;
match c.role {
VmPredicateInputRole::Metadata(
VmMetadataComparisonColumn::MatchNumber,
) => VmSourceRef::MatchNumber,
VmPredicateInputRole::Metadata(_) => {
VmSourceRef::MatchSequenceNumber
}
VmPredicateInputRole::StaticPredicate { bool_idx } => {
VmSourceRef::StaticPredicate {
bool_idx: bool_idx as u16,
}
}
VmPredicateInputRole::Classifier => {
return Err(UnsupportedSourceDomain);
}
role => {
let ty = c.ty.ok_or(UnsupportedSourceDomain)?;
vm_type_from_data_type(&ty.scalar.arrow_type(), ty.nullable)
.ok_or(UnsupportedSourceDomain)?;
if let VmPredicateInputRole::StaticScalar { scalar_idx } =
role
{
VmSourceRef::StaticScalar {
scalar_idx: scalar_idx as u16,
ty,
}
} else {
let id = self
.rows
.iter()
.position(|n| n == &c.column_name)
.unwrap_or_else(|| {
self.rows.push(c.column_name.clone());
self.rows.len() - 1
});
VmSourceRef::RowValue {
column_ref: id as u16,
ty,
}
}
}
}
};
let ty = source.output_type();
(N::Source(source), ty, 1, 1, false)
}
Expr::Case(case)
if case.expr.is_none()
&& case.when_then_expr.len() == 1
&& case.else_expr.is_some() =>
{
let (when, then) = &case.when_then_expr[0];
if !matches!(when.as_ref(), Expr::IsNotNull(x) if x == then) {
return Err(EmissionFailure);
}
let else_expr = case.else_expr.as_deref().expect("checked above");
self.lower_coalesce(then, else_expr)?
}
Expr::Not(e)
| Expr::Negative(e)
| Expr::IsNull(e)
| Expr::IsNotNull(e)
| Expr::Cast(datafusion::logical_expr::expr::Cast { expr: e, .. }) => {
let (input, mut ty, slots, work, literal) = self.lower(e)?;
let node = match expr {
Expr::IsNull(_) => {
ty = VmType::non_null(T::Bool);
N::IsNull { input }
}
Expr::IsNotNull(_) => {
ty = VmType::non_null(T::Bool);
N::IsNotNull { input }
}
Expr::Cast(c) => {
if ty.scalar.arrow_type() == *c.field.data_type() {
return Ok((input, ty, slots, work, literal));
}
let target =
vm_type_from_data_type(c.field.data_type(), ty.nullable)
.ok_or(UnsupportedCast)?;
if !safe_cast(ty.scalar, target.scalar) {
return Err(UnsupportedCast);
}
ty = target;
N::Cast {
target_ty: ty,
input,
}
}
_ => {
let op = if matches!(expr, Expr::Not(_)) {
if ty.scalar != T::Bool {
return Err(unsupported);
}
VmUnaryOp::Not
} else {
if !matches!(
ty.scalar,
T::Int8
| T::Int16
| T::Int32
| T::Int64
| T::MetadataI64
| T::Float64
| T::Decimal128 { .. }
) {
return Err(unsupported);
}
if literal {
VmUnaryOp::CheckedNeg
} else {
VmUnaryOp::Neg
}
};
N::Unary {
op,
out_ty: ty,
input,
}
}
};
(node, ty, slots, work + 1, literal)
}
Expr::BinaryExpr(b) => {
if matches!(b.op, Operator::Plus | Operator::Minus)
&& let Some((base_expr, interval_lit)) =
match (b.left.as_ref(), b.right.as_ref()) {
(lhs, Expr::Literal(lit, _))
if is_fixed_interval_literal(lit) =>
{
Some((lhs, lit))
}
(Expr::Literal(lit, _), rhs)
if b.op == Operator::Plus
&& is_fixed_interval_literal(lit) =>
{
Some((rhs, lit))
}
_ => None,
}
{
let (left, l, ls, lw, ll) = self.lower(base_expr)?;
let delta = fixed_temporal_interval_delta(l.scalar, interval_lit)
.ok_or(unsupported)?;
if self.nodes.len() >= self.context.limits.max_ir_nodes {
return Err(ExpressionTooLarge);
}
let right = self.nodes.len() as u16;
let nullable = l.nullable || delta.is_null();
self.nodes.push(N::Source(VmSourceRef::Literal(delta)));
let out_ty = VmType {
scalar: l.scalar,
nullable,
};
let op = if b.op == Operator::Plus {
VmBinaryOp::AddInterval
} else {
VmBinaryOp::SubInterval
};
(
N::Binary {
op,
out_ty,
left,
right,
},
out_ty,
ls.max(2),
lw + 2,
ll,
)
} else {
let (left, l, ls, lw, ll) = self.lower(&b.left)?;
let (right, r, rs, rw, rl) = self.lower(&b.right)?;
let (op, scalar) =
binary_type(b.op, l.scalar, r.scalar).ok_or(unsupported)?;
let nullable = if matches!(
op,
VmBinaryOp::IsDistinctFrom | VmBinaryOp::IsNotDistinctFrom
) {
false
} else {
l.nullable || r.nullable
};
let out_ty = VmType { scalar, nullable };
(
N::Binary {
op,
out_ty,
left,
right,
},
out_ty,
ls.max(rs + 1),
lw + rw
+ 1
+ usize::from(matches!(op, VmBinaryOp::And | VmBinaryOp::Or)),
ll && rl,
)
}
}
Expr::TryCast(_) => return Err(UnsupportedCast),
Expr::ScalarFunction(func)
if func.func == datafusion::functions::core::coalesce()
&& func.args.len() == 2 =>
{
self.lower_coalesce(&func.args[0], &func.args[1])?
}
Expr::ScalarFunction(func)
if func.func == datafusion::functions::math::abs()
&& func.args.len() == 1 =>
{
let (input, ty, slots, work, literal) = self.lower(&func.args[0])?;
if !matches!(
ty.scalar,
T::Int8
| T::Int16
| T::Int32
| T::Int64
| T::MetadataI64
| T::Float64
| T::Decimal128 { .. }
) {
return Err(unsupported);
}
(
N::Unary {
op: VmUnaryOp::Abs,
out_ty: ty,
input,
},
ty,
slots,
work + 1,
literal,
)
}
Expr::ScalarFunction(_) => return Err(UnsupportedFunctionSignature),
_ => return Err(EmissionFailure),
};
if matches!(ty.scalar, T::Decimal256 { .. } | T::FixedSizeBinary(_)) {
return Err(UnsupportedSourceDomain);
}
if self.nodes.len() >= self.context.limits.max_ir_nodes {
return Err(ExpressionTooLarge);
}
let id = self.nodes.len() as u16;
self.nodes.push(node);
Ok((id, ty, slots, work, literal))
}
fn lower_coalesce(
&mut self,
first: &Expr,
second: &Expr,
) -> Result<(PredicateNode, VmType, usize, usize, bool), VmCompileError> {
use PredicateNode as N;
use VmScalarType as T;
if matches!(second, Expr::Literal(ScalarValue::Boolean(Some(false)), _)) {
let (input, ty, slots, work, literal) = self.lower(first)?;
if ty.scalar != T::Bool {
return Err(VmCompileError::UnsupportedFunctionSignature);
}
let out_ty = VmType::non_null(T::Bool);
return Ok((
N::Unary {
op: VmUnaryOp::IsTrue,
out_ty,
input,
},
out_ty,
slots,
work + 1,
literal,
));
}
let (left, l, ls, lw, ll) = self.lower(first)?;
let (right, r, rs, rw, rl) = self.lower(second)?;
let scalar = coalesce_scalar_type(l.scalar, r.scalar)
.ok_or(VmCompileError::UnsupportedFunctionSignature)?;
let out_ty = VmType {
scalar,
nullable: l.nullable && r.nullable,
};
Ok((
N::Coalesce {
left,
right,
out_ty,
},
out_ty,
ls.max(rs),
lw + rw + 2,
ll && rl,
))
}
}
fn is_fixed_interval_literal(value: &ScalarValue) -> bool {
matches!(
value,
ScalarValue::IntervalMonthDayNano(_) | ScalarValue::IntervalDayTime(_)
)
}
fn fixed_temporal_interval_delta(
target: VmScalarType,
interval: &ScalarValue,
) -> Option<ScalarValue> {
use datafusion::arrow::temporal_conversions::{
MICROSECONDS_IN_DAY, MILLISECONDS_IN_DAY, NANOSECONDS_IN_DAY, SECONDS_IN_DAY,
};
let (days, nanos) = match interval {
ScalarValue::IntervalMonthDayNano(None) | ScalarValue::IntervalDayTime(None) => {
return Some(match target {
VmScalarType::Date32 => ScalarValue::Date32(None),
VmScalarType::Date64 => ScalarValue::Date64(None),
VmScalarType::Timestamp {
unit: TimeUnit::Second,
timezone_aware: false,
} => ScalarValue::TimestampSecond(None, None),
VmScalarType::Timestamp {
unit: TimeUnit::Millisecond,
timezone_aware: false,
} => ScalarValue::TimestampMillisecond(None, None),
VmScalarType::Timestamp {
unit: TimeUnit::Microsecond,
timezone_aware: false,
} => ScalarValue::TimestampMicrosecond(None, None),
VmScalarType::Timestamp {
unit: TimeUnit::Nanosecond,
timezone_aware: false,
} => ScalarValue::TimestampNanosecond(None, None),
_ => return None,
});
}
ScalarValue::IntervalMonthDayNano(Some(iv))
if iv.months == 0
&& ((iv.days >= 0 && iv.nanoseconds >= 0)
|| (iv.days <= 0 && iv.nanoseconds <= 0)) =>
{
(iv.days, iv.nanoseconds)
}
ScalarValue::IntervalDayTime(Some(iv))
if (iv.days >= 0 && iv.milliseconds >= 0)
|| (iv.days <= 0 && iv.milliseconds <= 0) =>
{
(iv.days, i64::from(iv.milliseconds).checked_mul(1_000_000)?)
}
_ => return None,
};
let scaled_ticks = |ticks_per_day: i64, nanos_per_tick: i64| -> Option<i64> {
if nanos % nanos_per_tick != 0 {
return None;
}
i64::from(days)
.checked_mul(ticks_per_day)?
.checked_add(nanos / nanos_per_tick)
};
match target {
VmScalarType::Date32 if nanos == 0 => Some(ScalarValue::Date32(Some(days))),
VmScalarType::Date64 if nanos == 0 => Some(ScalarValue::Date64(Some(
i64::from(days).checked_mul(MILLISECONDS_IN_DAY)?,
))),
VmScalarType::Timestamp {
unit: TimeUnit::Second,
timezone_aware: false,
} => Some(ScalarValue::TimestampSecond(
Some(scaled_ticks(SECONDS_IN_DAY, 1_000_000_000)?),
None,
)),
VmScalarType::Timestamp {
unit: TimeUnit::Millisecond,
timezone_aware: false,
} => Some(ScalarValue::TimestampMillisecond(
Some(scaled_ticks(MILLISECONDS_IN_DAY, 1_000_000)?),
None,
)),
VmScalarType::Timestamp {
unit: TimeUnit::Microsecond,
timezone_aware: false,
} => Some(ScalarValue::TimestampMicrosecond(
Some(scaled_ticks(MICROSECONDS_IN_DAY, 1_000)?),
None,
)),
VmScalarType::Timestamp {
unit: TimeUnit::Nanosecond,
timezone_aware: false,
} => Some(ScalarValue::TimestampNanosecond(
Some(scaled_ticks(NANOSECONDS_IN_DAY, 1)?),
None,
)),
_ => None,
}
}
fn normalize(t: VmScalarType) -> VmScalarType {
if t == VmScalarType::MetadataI64 {
VmScalarType::Int64
} else {
t
}
}
fn signed_rank(t: VmScalarType) -> Option<u8> {
use VmScalarType as T;
match t {
T::Int8 => Some(0),
T::Int16 => Some(1),
T::Int32 => Some(2),
T::Int64 => Some(3),
_ => None,
}
}
fn unsigned_rank(t: VmScalarType) -> Option<u8> {
use VmScalarType as T;
match t {
T::UInt8 => Some(0),
T::UInt16 => Some(1),
T::UInt32 => Some(2),
T::UInt64 => Some(3),
_ => None,
}
}
fn widen_signed(a: VmScalarType, b: VmScalarType) -> Option<VmScalarType> {
let (ra, rb) = (signed_rank(a)?, signed_rank(b)?);
Some(if ra >= rb { a } else { b })
}
fn widen_unsigned(a: VmScalarType, b: VmScalarType) -> Option<VmScalarType> {
let (ra, rb) = (unsigned_rank(a)?, unsigned_rank(b)?);
Some(if ra >= rb { a } else { b })
}
fn coalesce_scalar_type(a: VmScalarType, b: VmScalarType) -> Option<VmScalarType> {
use VmScalarType as T;
let na = normalize(a);
let nb = normalize(b);
if na == nb {
return Some(if a == b { a } else { na });
}
if let (
T::Decimal128 {
precision: p1,
scale: s1,
},
T::Decimal128 {
precision: p2,
scale: s2,
},
) = (na, nb)
&& s1 == s2
{
return Some(T::Decimal128 {
precision: p1.max(p2),
scale: s1,
});
}
if let Some(widened) = widen_signed(na, nb).or_else(|| widen_unsigned(na, nb)) {
return Some(widened);
}
if na.is_string() && nb.is_string() {
return Some(na);
}
None
}
fn safe_cast(a: VmScalarType, b: VmScalarType) -> bool {
use VmScalarType::*;
let a = normalize(a);
let b = normalize(b);
a == b
|| signed_rank(a)
.zip(signed_rank(b))
.is_some_and(|(ra, rb)| ra <= rb)
|| unsigned_rank(a)
.zip(unsigned_rank(b))
.is_some_and(|(ra, rb)| ra <= rb)
|| matches!(
(a, b),
(
Int8 | Int16
| Int32
| Int64
| UInt8
| UInt16
| UInt32
| UInt64
| Float32
| Decimal128 { .. },
Float64
) | (Float64, Decimal128 { .. })
)
|| matches!((a,b),(Decimal128 {scale:a,..},Decimal128 {scale:b,..}) if b>=a && i16::from(b) - i16::from(a) <= 38)
}
fn binary_type(
op: Operator,
a: VmScalarType,
b: VmScalarType,
) -> Option<(VmBinaryOp, VmScalarType)> {
use VmBinaryOp as O;
use VmScalarType as T;
let a = normalize(a);
let b = normalize(b);
let cmp = match op {
Operator::Eq => Some(O::Eq),
Operator::NotEq => Some(O::Ne),
Operator::Lt => Some(O::Lt),
Operator::LtEq => Some(O::Le),
Operator::Gt => Some(O::Gt),
Operator::GtEq => Some(O::Ge),
Operator::IsDistinctFrom => Some(O::IsDistinctFrom),
Operator::IsNotDistinctFrom => Some(O::IsNotDistinctFrom),
_ => None,
};
let same_decimal =
matches!((a,b),(T::Decimal128 {scale:a,..},T::Decimal128 {scale:b,..}) if a==b);
if let Some(cmp) = cmp {
let same = a == b
|| same_decimal
|| (signed_rank(a).is_some() && signed_rank(b).is_some())
|| (unsigned_rank(a).is_some() && unsigned_rank(b).is_some());
if (same && !a.is_string()) || (a.is_string() && b.is_string()) {
return Some((cmp, T::Bool));
}
return None;
}
if a == T::Bool && b == T::Bool {
return match op {
Operator::And => Some((O::And, T::Bool)),
Operator::Or => Some((O::Or, T::Bool)),
_ => None,
};
}
let binary = match op {
Operator::Plus => O::Add,
Operator::Minus => O::Sub,
Operator::Multiply => O::Mul,
_ => return None,
};
if let Some(widened) = widen_signed(a, b).or_else(|| widen_unsigned(a, b)) {
return Some((binary, widened));
}
if a == b && a == T::Float64 {
return Some((binary, a));
}
if binary != O::Mul {
match (a, b, binary) {
(T::Duration(u1), T::Duration(u2), _) if u1 == u2 => {
return Some((binary, T::Duration(u1)));
}
(
T::Timestamp {
unit: u1,
timezone_aware: false,
},
T::Timestamp {
unit: u2,
timezone_aware: false,
},
O::Sub,
) if u1 == u2 => {
return Some((O::Sub, T::Duration(u1)));
}
(
ts @ T::Timestamp {
unit: u1,
timezone_aware: false,
},
T::Duration(u2),
_,
) if u1 == u2 => {
return Some((binary, ts));
}
(
T::Duration(u1),
ts @ T::Timestamp {
unit: u2,
timezone_aware: false,
},
O::Add,
) if u1 == u2 => {
return Some((O::Add, ts));
}
_ => {}
}
}
if let (T::Decimal128 { scale: s1, .. }, T::Decimal128 { scale: s2, .. }) = (a, b) {
let result = BinaryTypeCoercer::new(&a.arrow_type(), &op, &b.arrow_type())
.get_result_type()
.ok()?;
let result = vm_type_from_data_type(&result, true)?.scalar;
let T::Decimal128 { scale: s_out, .. } = result else {
return None;
};
if binary == O::Mul {
if i16::from(s_out) != i16::from(s1) + i16::from(s2) {
return None;
}
} else if s_out != s1.max(s2) {
return None;
}
return Some((binary, result));
}
None
}