| 484 | } |
| 485 | |
| 486 | Status CastDecimalArgs(TypeHolder* begin, size_t count) { |
| 487 | Type::type casted_type_id = Type::DECIMAL128; |
| 488 | TypeHolder* end = begin + count; |
| 489 | |
| 490 | int32_t max_scale = 0; |
| 491 | bool any_floating = false; |
| 492 | for (auto* it = begin; it != end; ++it) { |
| 493 | const auto& ty = *it->type; |
| 494 | if (is_floating(ty.id())) { |
| 495 | // Decimal + float = float |
| 496 | any_floating = true; |
| 497 | } else if (is_integer(ty.id())) { |
| 498 | // Nothing to do here |
| 499 | } else if (is_decimal(ty.id())) { |
| 500 | max_scale = std::max(max_scale, checked_cast<const DecimalType&>(ty).scale()); |
| 501 | if (ty.id() == Type::DECIMAL256) { |
| 502 | casted_type_id = Type::DECIMAL256; |
| 503 | } |
| 504 | } else { |
| 505 | // Non-numeric, can't cast |
| 506 | return Status::OK(); |
| 507 | } |
| 508 | } |
| 509 | if (any_floating) { |
| 510 | ReplaceTypes(float64(), begin, count); |
| 511 | return Status::OK(); |
| 512 | } |
| 513 | |
| 514 | // All integer and decimal, rescale |
| 515 | int32_t common_precision = 0; |
| 516 | for (auto* it = begin; it != end; ++it) { |
| 517 | const auto& ty = *it->type; |
| 518 | if (is_integer(ty.id())) { |
| 519 | ARROW_ASSIGN_OR_RAISE(auto precision, MaxDecimalDigitsForInteger(ty.id())); |
| 520 | precision += max_scale; |
| 521 | common_precision = std::max(common_precision, precision); |
| 522 | } else if (is_decimal(ty.id())) { |
| 523 | const auto& decimal_ty = checked_cast<const DecimalType&>(ty); |
| 524 | auto precision = decimal_ty.precision(); |
| 525 | const auto scale = decimal_ty.scale(); |
| 526 | precision += max_scale - scale; |
| 527 | common_precision = std::max(common_precision, precision); |
| 528 | } |
| 529 | } |
| 530 | |
| 531 | if (common_precision > BasicDecimal256::kMaxPrecision) { |
| 532 | return Status::Invalid("Result precision (", common_precision, |
| 533 | ") exceeds max precision of Decimal256 (", |
| 534 | BasicDecimal256::kMaxPrecision, ")"); |
| 535 | } else if (common_precision > BasicDecimal128::kMaxPrecision) { |
| 536 | casted_type_id = Type::DECIMAL256; |
| 537 | } |
| 538 | |
| 539 | ARROW_ASSIGN_OR_RAISE(auto casted_ty, |
| 540 | DecimalType::Make(casted_type_id, common_precision, max_scale)); |
| 541 | for (auto* it = begin; it != end; ++it) { |
| 542 | *it = casted_ty; |
| 543 | } |