Simplify the `log` function by the relevant rules: 1. Log(a, 1) ===> 0 2. Log(a, Power(a, b)) ===> b 3. Log(a, a) ===> 1
(
&self,
mut args: Vec<Expr>,
info: &SimplifyContext,
)
| 313 | /// 2. Log(a, Power(a, b)) ===> b |
| 314 | /// 3. Log(a, a) ===> 1 |
| 315 | fn simplify( |
| 316 | &self, |
| 317 | mut args: Vec<Expr>, |
| 318 | info: &SimplifyContext, |
| 319 | ) -> Result<ExprSimplifyResult> { |
| 320 | let mut arg_types = args |
| 321 | .iter() |
| 322 | .map(|arg| info.get_data_type(arg)) |
| 323 | .collect::<Result<Vec<_>>>()?; |
| 324 | let return_type = self.return_type(&arg_types)?; |
| 325 | |
| 326 | // Null propagation |
| 327 | if arg_types.iter().any(|dt| dt.is_null()) { |
| 328 | return Ok(ExprSimplifyResult::Simplified(lit( |
| 329 | ScalarValue::Null.cast_to(&return_type)? |
| 330 | ))); |
| 331 | } |
| 332 | |
| 333 | // Args are either |
| 334 | // log(number) |
| 335 | // log(base, number) |
| 336 | let num_args = args.len(); |
| 337 | if num_args != 1 && num_args != 2 { |
| 338 | return plan_err!("Expected log to have 1 or 2 arguments, got {num_args}"); |
| 339 | } |
| 340 | |
| 341 | match arg_types.last().unwrap() { |
| 342 | DataType::Decimal32(_, scale) |
| 343 | | DataType::Decimal64(_, scale) |
| 344 | | DataType::Decimal128(_, scale) |
| 345 | | DataType::Decimal256(_, scale) |
| 346 | if *scale < 0 => |
| 347 | { |
| 348 | return Ok(ExprSimplifyResult::Original(args)); |
| 349 | } |
| 350 | _ => (), |
| 351 | }; |
| 352 | |
| 353 | let number = args.pop().unwrap(); |
| 354 | let number_datatype = arg_types.pop().unwrap(); |
| 355 | // default to base 10 |
| 356 | let base = if let Some(base) = args.pop() { |
| 357 | base |
| 358 | } else { |
| 359 | lit(ScalarValue::new_ten(&number_datatype)?) |
| 360 | }; |
| 361 | |
| 362 | match number { |
| 363 | Expr::Literal(value, _) |
| 364 | if value == ScalarValue::new_one(&number_datatype)? => |
| 365 | { |
| 366 | Ok(ExprSimplifyResult::Simplified(lit(ScalarValue::new_zero( |
| 367 | &info.get_data_type(&base)?, |
| 368 | )?))) |
| 369 | } |
| 370 | Expr::ScalarFunction(ScalarFunction { func, mut args }) |
| 371 | if is_pow(&func) && args.len() == 2 && base == args[0] => |
| 372 | { |