You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by "Fokko (via GitHub)" <gi...@apache.org> on 2023/07/24 14:19:55 UTC
[GitHub] [arrow] Fokko opened a new pull request, #36846: GH-36845: [
Fokko opened a new pull request, #36846:
URL: https://github.com/apache/arrow/pull/36846
Revival of https://github.com/apache/arrow/pull/12000/
<!--
Thanks for opening a pull request!
If this is your first pull request you can find detailed information on how
to contribute here:
* [New Contributor's Guide](https://arrow.apache.org/docs/dev/developers/guide/step_by_step/pr_lifecycle.html#reviews-and-merge-of-the-pull-request)
* [Contributing Overview](https://arrow.apache.org/docs/dev/developers/overview.html)
If this is not a [minor PR](https://github.com/apache/arrow/blob/main/CONTRIBUTING.md#Minor-Fixes). Could you open an issue for this pull request on GitHub? https://github.com/apache/arrow/issues/new/choose
Opening GitHub issues ahead of time contributes to the [Openness](http://theapacheway.com/open/#:~:text=Openness%20allows%20new%20users%20the,must%20happen%20in%20the%20open.) of the Apache Arrow project.
Then could you also rename the pull request title in the following format?
GH-${GITHUB_ISSUE_ID}: [${COMPONENT}] ${SUMMARY}
or
MINOR: [${COMPONENT}] ${SUMMARY}
In the case of PARQUET issues on JIRA the title also supports:
PARQUET-${JIRA_ISSUE_ID}: [${COMPONENT}] ${SUMMARY}
-->
### Rationale for this change
It would be great to be able to do promotions when `concat`'ing a table, such as:
```python
def test_concat_tables_with_promotion_int():
import pyarrow as pa
t1 = pa.Table.from_arrays(
[pa.array([1, 2], type=pa.int64())], ["int"])
t2 = pa.Table.from_arrays(
[pa.array([3, 4], type=pa.int32())], ["int"])
result = pa.concat_tables([t1, t2], promote=True)
assert result.equals(pa.Table.from_arrays([
pa.array([1, 2, 3, 4], type=pa.int64())
], ["int"]))
```
<!--
Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed.
Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes.
-->
### What changes are included in this PR?
<!--
There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR.
-->
### Are these changes tested?
<!--
We typically require tests for all PRs in order to:
1. Prevent the code from being accidentally broken by subsequent changes
2. Serve as another way to document the expected behavior of the code
If tests are not included in your PR, please explain why (for example, are they covered by existing tests)?
-->
### Are there any user-facing changes?
<!--
If there are user-facing changes then we may require documentation to be updated before approving the PR.
-->
<!--
If there are any breaking changes to public APIs, please uncomment the line below and explain which changes are breaking.
-->
<!-- **This PR includes breaking changes to public APIs.** -->
<!--
Please uncomment the line below (and provide explanation) if the changes fix either (a) a security vulnerability, (b) a bug that caused incorrect or invalid data to be produced, or (c) a bug that causes a crash (even when the API contract is upheld). We use this to highlight fixes to issues that may affect users without their knowledge. For this reason, fixing bugs that cause errors don't count, since those are usually obvious.
-->
<!-- **This PR contains a "Critical Fix".** -->
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] jorisvandenbossche commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "jorisvandenbossche (via GitHub)" <gi...@apache.org>.
jorisvandenbossche commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1303020868
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,67 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
+
+ /// Allow a decimal to be promoted to a float. The float type will
+ /// not itself be promoted (e.g. Decimal128 + Float32 = Float32).
+ bool promote_decimal_to_float = false;
+
+ /// Allow an integer to be promoted to a decimal.
+ ///
+ /// May fail if the decimal has insufficient precision to
+ /// accommodate the integer. (See increase_decimal_precision.)
+ bool promote_integer_to_decimal = false;
+
+ /// Allow an integer of a given bit width to be promoted to a
+ /// float; the result will be a float of an equal or greater bit
+ /// width to both of the inputs.
+ bool promote_integer_to_float = false;
Review Comment:
I think for some of those cases, it might be useful to given an example (like "int64 + float32 -> float64").
##########
cpp/src/arrow/type.cc:
##########
@@ -327,6 +315,449 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_list = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_decimal=" << (promote_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_list=" << (promote_list ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_dictionary_ordered="
+ << (promote_dictionary_ordered ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::TypeError(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_temporal_unit) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+
+ if (promoted_type->id() == Type::DURATION && other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(std::max(left.unit(), right.unit()));
+ }
+
+ if (is_time(promoted_type->id()) && is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = std::max(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+ }
+
+ if (promoted_type->id() == Type::TIMESTAMP && other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::TypeError(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::TypeError("Cannot merge timestamps with differing timezones");
+ }
Review Comment:
A potential option could be actually allow promoting timezones, and with the result using UTC (the actual time points will stay the same since we store UTC under the hood, you only loose the information about the specified timezone)
(but this is perfect to discuss for a follow-up issue as well ;))
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,63 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
+
+ /// Allow a decimal to be promoted to a float. The float type will
+ /// not itself be promoted (e.g. Decimal128 + Float32 = Float32).
+ bool promote_decimal_to_float = false;
+
+ /// Allow an integer to be promoted to a decimal.
+ ///
+ /// May fail if the decimal has insufficient precision to
+ /// accommodate the integer. (See increase_decimal_precision.)
+ bool promote_integer_to_decimal = false;
+
+ /// Allow an integer of a given bit width to be promoted to a
+ /// float; the result will be a float of an equal or greater bit
+ /// width to both of the inputs.
+ bool promote_integer_to_float = false;
+
+ /// Allow an unsigned integer of a given bit width to be promoted
+ /// to a signed integer of the equal or greater bit width.
+ bool promote_integer_sign = false;
+
+ /// Allow an integer, float, or decimal of a given bit width to be
+ /// promoted to an equivalent type of a greater bit width.
+ bool promote_numeric_width = false;
+
+ /// Allow strings to be promoted to binary types.
+ bool promote_binary = false;
Review Comment:
Don't know if this has come up before, but would it make sense to have a separate `promote_string_to_binary`? Logically that seems something different from allowing string to become large_string
(there are already many options though ..)
##########
cpp/src/arrow/type.cc:
##########
@@ -327,6 +315,449 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_list = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_decimal=" << (promote_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_list=" << (promote_list ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_dictionary_ordered="
+ << (promote_dictionary_ordered ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::TypeError(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_temporal_unit) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+
+ if (promoted_type->id() == Type::DURATION && other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(std::max(left.unit(), right.unit()));
+ }
+
+ if (is_time(promoted_type->id()) && is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = std::max(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+ }
+
+ if (promoted_type->id() == Type::TIMESTAMP && other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::TypeError(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::TypeError("Cannot merge timestamps with differing timezones");
+ }
+ if (options.promote_temporal_unit) {
+ return timestamp(std::max(left.unit(), right.unit()), left.timezone());
+ }
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-numeric types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_to_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_to_decimal &&
+ ((is_decimal(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_decimal(other_type->id()) && is_integer(promoted_type->id())))) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ // Other type is always the int
+ promoted_type.swap(other_type);
+ }
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(const auto promoted_decimal,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ ARROW_ASSIGN_OR_RAISE(promoted_type,
+ WidenDecimals(promoted_type, promoted_decimal, options));
Review Comment:
~How useful is it to widen the decimal to the biggest possible precision needed to store the largest integer? Because often you have small integers. And you could also keep the existing decimal type, and rely on safe casting to catch errors?~
Actually, it seems our casting kernel has the same logic, so nevermind (it will error anyway)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] jorisvandenbossche commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "jorisvandenbossche (via GitHub)" <gi...@apache.org>.
jorisvandenbossche commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1336833340
##########
cpp/src/arrow/table.h:
##########
@@ -313,16 +314,24 @@ Result<std::shared_ptr<Table>> ConcatenateTables(
ConcatenateTablesOptions options = ConcatenateTablesOptions::Defaults(),
MemoryPool* memory_pool = default_memory_pool());
+namespace compute {
+class CastOptions;
+}
+
/// \brief Promotes a table to conform to the given schema.
///
-/// If a field in the schema does not have a corresponding column in the
-/// table, a column of nulls will be added to the resulting table.
-/// If the corresponding column is of type Null, it will be promoted to
-/// the type specified by schema, with null values filled.
+/// If a field in the schema does not have a corresponding column in
+/// the table, a column of nulls will be added to the resulting table.
+/// If the corresponding column is of type Null, it will be promoted
+/// to the type specified by schema, with null values filled. If Arrow
+/// was built with ARROW_COMPUTE, then the column will be casted to
+/// the type specified by the schema.
Review Comment:
This "if Arrow was built with ARROW_COMPUTE" part is now outdated
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] jorisvandenbossche commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "jorisvandenbossche (via GitHub)" <gi...@apache.org>.
jorisvandenbossche commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1336854098
##########
cpp/src/arrow/type.cc:
##########
@@ -327,6 +315,449 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_list = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_decimal=" << (promote_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_list=" << (promote_list ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_dictionary_ordered="
+ << (promote_dictionary_ordered ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::TypeError(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_temporal_unit) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+
+ if (promoted_type->id() == Type::DURATION && other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(std::max(left.unit(), right.unit()));
+ }
+
+ if (is_time(promoted_type->id()) && is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = std::max(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+ }
+
+ if (promoted_type->id() == Type::TIMESTAMP && other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::TypeError(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::TypeError("Cannot merge timestamps with differing timezones");
+ }
+ if (options.promote_temporal_unit) {
+ return timestamp(std::max(left.unit(), right.unit()), left.timezone());
+ }
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-numeric types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_to_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_to_decimal &&
+ ((is_decimal(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_decimal(other_type->id()) && is_integer(promoted_type->id())))) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ // Other type is always the int
+ promoted_type.swap(other_type);
+ }
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(const auto promoted_decimal,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ ARROW_ASSIGN_OR_RAISE(promoted_type,
+ WidenDecimals(promoted_type, promoted_decimal, options));
+ return promoted_type;
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ ARROW_ASSIGN_OR_RAISE(promoted_type,
+ WidenDecimals(promoted_type, other_type, options));
+ return promoted_type;
+ }
+
+ if (options.promote_integer_sign && ((is_unsigned_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) ||
+ (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())))) {
+ if (!options.promote_numeric_width &&
+ bit_width(promoted_type->id()) != bit_width(other_type->id())) {
+ return Status::TypeError(
+ "Cannot widen (un)signed integers without promote_numeric_width=true");
+ }
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
Review Comment:
Did you address this comment? (`uint32` getting promoted to `int32`)
##########
python/pyarrow/tests/test_table.py:
##########
@@ -1330,6 +1330,22 @@ def test_concat_tables():
assert result.equals(expected)
+def test_concat_tables_permissive():
+ t1 = pa.Table.from_arrays([list(range(10))], names=('a',))
+ t2 = pa.Table.from_arrays([list(range(10, 20))], names=('a',))
+
+ result = pa.concat_tables([t1, t2], field_merge_options="permissive")
Review Comment:
I am not sure this is a perfect test for "permissive", because this specific case would perfectly work as well without specifying `field_merge_options="permissive"` (since the types are the same), and so it doesn't test that the option is properly passed through
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables` [arrow]
Posted by "jorisvandenbossche (via GitHub)" <gi...@apache.org>.
jorisvandenbossche commented on PR #36846:
URL: https://github.com/apache/arrow/pull/36846#issuecomment-1755405449
Thanks @Fokko! (and @lidavidm for the initial PR)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1274917005
##########
python/pyarrow/table.pxi:
##########
@@ -5031,9 +5032,13 @@ def concat_tables(tables, c_bool promote=False, MemoryPool memory_pool=None):
tables : iterable of pyarrow.Table objects
Pyarrow tables to concatenate into a single Table.
promote : bool, default False
- If True, concatenate tables with null-filling and null type promotion.
+ If True, concatenate tables with null-filling and type promotion.
+ See field_merge_options for the type promotion behavior.
memory_pool : MemoryPool, default None
For memory allocations, if required, otherwise use default pool.
+ field_merge_options : FieldMergeOptions, default None
Review Comment:
I like it, added
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1274925653
##########
python/pyarrow/tests/test_schema.py:
##########
@@ -725,6 +725,10 @@ def test_schema_merge():
result = pa.unify_schemas((a, b, c))
assert result.equals(expected)
+ result = pa.unify_schemas(
+ [b, d], options=pa.FieldMergeOptions.permissive())
+ assert result.equals(d)
Review Comment:
I like it, added it!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1274898844
##########
cpp/src/arrow/type_traits.h:
##########
@@ -1187,7 +1202,6 @@ constexpr bool is_var_length_list(Type::type type_id) {
switch (type_id) {
case Type::LIST:
case Type::LARGE_LIST:
- case Type::MAP:
Review Comment:
I was also reluctant to change this, but I think it is correct. This is in line with the original PR: https://github.com/apache/arrow/pull/12000/files#diff-d606ef26a35a58e56fc01c680ea87eaaba5488b63b71fb7ab37930f81ec159b8R980-R989
It is only used for internal methods AFAICT
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1274887090
##########
cpp/src/arrow/type_test.cc:
##########
@@ -983,6 +1091,242 @@ TEST_F(TestUnifySchemas, MoreSchemas) {
utf8_field->WithNullable(true)}));
}
+TEST_F(TestUnifySchemas, Numeric) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ CheckUnify(uint8(),
+ {int8(), uint16(), int16(), uint32(), int32(), uint64(), int64(), float32(),
+ float64()},
+ options);
+ CheckUnify(int8(), {int16(), int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint16(),
+ {int16(), uint32(), int32(), uint64(), int64(), float32(), float64()},
+ options);
+ CheckUnify(int16(), {int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint32(), {int32(), uint64(), int64(), float32(), float64()}, options);
+ CheckUnify(int32(), {int64(), float32(), float64()}, options);
+ CheckUnify(uint64(), {int64(), float64()}, options);
+ CheckUnify(int64(), {float64()}, options);
+ CheckUnify(float16(), {float32(), float64()}, options);
+ CheckUnify(float32(), {float64()}, options);
+ CheckUnify(uint64(), float32(), float64(), options);
+ CheckUnify(int64(), float32(), float64(), options);
+
+ options.promote_integer_sign = false;
+ CheckUnify(uint8(), {uint16(), uint32(), uint64()}, options);
+ CheckUnify(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(uint8(), {int8(), int16(), int32(), int64()}, options);
+ CheckUnify(uint16(), {uint32(), uint64()}, options);
+ CheckUnify(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(uint16(), {int16(), int32(), int64()}, options);
+ CheckUnify(uint32(), {uint64()}, options);
+ CheckUnify(int32(), {int64()}, options);
+ CheckUnifyFails(uint32(), {int32(), int64()}, options);
+ CheckUnifyFails(uint64(), {int64()}, options);
+
+ options.promote_integer_sign = true;
+ options.promote_integer_float = false;
+ CheckUnifyFails(IntTypes(), FloatingPointTypes(), options);
+
+ options.promote_integer_float = true;
+ options.promote_numeric_width = false;
+ CheckUnifyFails(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(int32(), {int64()}, options);
+}
+
+TEST_F(TestUnifySchemas, Decimal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_decimal_float = true;
+ CheckUnify(decimal128(3, 2), {float32(), float64()}, options);
+ CheckUnify(decimal256(3, 2), {float32(), float64()}, options);
+
+ options.promote_integer_decimal = true;
+ CheckUnify(int32(), decimal128(3, 2), decimal128(3, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(3, -2), options);
+
+ options.promote_decimal = true;
+ CheckUnify(decimal128(3, 2), decimal128(5, 2), decimal128(5, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 3), decimal128(5, 3), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 1), decimal128(6, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, -2), decimal128(9, 2), options);
+ CheckUnify(decimal128(3, -2), decimal128(5, -2), decimal128(5, -2), options);
+
+ // int32() is essentially decimal128(10, 0)
+ CheckUnify(int32(), decimal128(3, 2), decimal128(12, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(10, 0), options);
+
+ CheckUnifyFails(decimal256(1, 0), decimal128(1, 0), options);
+ CheckUnifyFails(int64(), decimal128(38, 37), options);
Review Comment:
I think this one should pass right? `int64` is a `decimal(20, 0)`, which is compatible.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1307193186
##########
python/pyarrow/types.pxi:
##########
@@ -2014,6 +2014,48 @@ cpdef KeyValueMetadata ensure_metadata(object meta, c_bool allow_none=False):
return KeyValueMetadata(meta)
+cdef class FieldMergeOptions(_Weakrefable):
+ """
+ Options controlling how to merge the types of two fields.
+
+ By default, types must match exactly, except the null type can be
+ merged with any other type.
+
+ """
+
+ cdef:
+ CField.CMergeOptions c_options
+
+ __slots__ = ()
+
+ def __init__(self, *):
+ self.c_options = CField.CMergeOptions.Defaults()
Review Comment:
I don't know if anyone would use the fine-grained options. Keep in mind that the `concat_tables` will try to match the schema of the first table, so a user could also cast the columns there. For PyIceberg I'll project the requested schema with an empty table, and then concatenate all the tables with data.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables` [arrow]
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on PR #36846:
URL: https://github.com/apache/arrow/pull/36846#issuecomment-1744547621
Thanks @jorisvandenbossche for summarizing the pending issues. I was rebasing to see if the LLVM stuff has been fixed.
> Do we need the pyarrow.FieldMergeOptions class? At the moment it actually doesn't really do anything, since we don't (yet) allow to tweak individual flags, only "permissive"/"default" (and the class itself actually also only exposes "permissive", not "default", as a static method to create that options object). Maybe we can just remove it for now, we can always add it back later if we want to expose individual options.
I don't think it adds much value. Just accepting a string is much clearer to the end-user, and I think the majority of the people don't the fine-grained tuning.
> For concat_tables, I find it confusing that a user still has to specify promote=True when they already specified field_merge_options="permissive" (because the latter only makes sense with promote=True). Essentially the promote=False can be seen as a "no promotion" field merge option?
I think with this new promotion capability, the historically added promote keyword is unfortunately badly chosen. Essentially it means: "unify schemas" (that's also how it is called on the C++ side), and by default it hardly does any promotion (only non-existing fields or null fields to any type). If we keep promote keyword, I would expect that promote=True would do actual, permissive promotion.
To be clear, this is not caused by this PR, but I would still prefer to get a nicer API. One option is to actually rename promote to unify_schemas (which is what it does). We can still keep promote as an alias for now for backwards compatibility.
This is a good point, and I agree that `promote` is poorly chosen. You could have the situation that you don't want to add null fields, but you allow the promotion of the fields. I've added the `none` option as you suggested, and I think this is much cleaner. Also added support for `promote` if people still rely on it. It will emit a warning to let users know that they should switch to `promote_options`.
> The keyword names: pa.concat_tables uses field_merge_options, pa.unify_schemas uses options. Should we try to align those names? I mentioned that I would like promote_options, which I think is more descriptive, but on the other hand deviates from the C++ terminology ..
I like `promote_options` as well. Aligned the names there.
> The last two bullet points are more about the final Python API, and doesn't impact the large part of the changes in the PR (the actual C++ changes), so maybe I shouldn't block the PR on those, and I am also fine with discussing those in a follow-up.
We should not merge anything that we're going to rip out anyway, but I'm happy to help with some of the follow-ups. Getting this one in would be great since it is quite big already.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables` [arrow]
Posted by "conbench-apache-arrow[bot] (via GitHub)" <gi...@apache.org>.
conbench-apache-arrow[bot] commented on PR #36846:
URL: https://github.com/apache/arrow/pull/36846#issuecomment-1759885766
After merging your PR, Conbench analyzed the 6 benchmarking runs that have been run so far on merge-commit 5f57219ec2730d06ffbe0676175c35b234b08d33.
There were 2 benchmark results indicating a performance regression:
- Commit Run on `ursa-i9-9960x` at [2023-10-11 12:25:39Z](https://conbench.ursa.dev/compare/runs/0a40322ac5ad4cc69b1e2da555cc9884...05f2a40424984d62808b6600a7be60e8/)
- [`file-read` (Python) with compression=uncompressed, dataset=fanniemae_2016Q4, file_type=feather, output_type=table](https://conbench.ursa.dev/compare/benchmarks/065267773de7701c8000226a787526bd...065269a2f2437acc80005b5d8187e3cd)
- [`file-read` (Python) with compression=uncompressed, dataset=fanniemae_2016Q4, file_type=feather, output_type=dataframe](https://conbench.ursa.dev/compare/benchmarks/06526778c742767180004c5f01e2abb0...065269a4a1e97722800020313f358435)
The [full Conbench report](https://github.com/apache/arrow/runs/17648150894) has more details. It also includes information about 8 possible false positives for unstable benchmarks that are known to sometimes produce them.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables` [arrow]
Posted by "jorisvandenbossche (via GitHub)" <gi...@apache.org>.
jorisvandenbossche commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1350036999
##########
python/pyarrow/tests/test_table.py:
##########
@@ -1376,6 +1376,28 @@ def test_concat_tables_with_different_schema_metadata():
assert table2.schema.equals(table3.schema)
+def test_concat_tables_with_promote_option():
+ t1 = pa.Table.from_arrays(
+ [pa.array([1, 2], type=pa.int64())], ["int64_field"])
+ t2 = pa.Table.from_arrays(
+ [pa.array([1.0, 2.0], type=pa.float32())], ["float_field"])
+
+ result = pa.concat_tables([t1, t2], promote=True)
Review Comment:
```suggestion
with pytest.warns(FutureWarning):
result = pa.concat_tables([t1, t2], promote=True)
```
This asserts the warning is raised and at the same time also ensures we don't unnecessarily see the warning in the pytest logs
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on PR #36846:
URL: https://github.com/apache/arrow/pull/36846#issuecomment-1728249599
It has been a week, gentle ping @pitrou and @jorisvandenbossche :)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on PR #36846:
URL: https://github.com/apache/arrow/pull/36846#issuecomment-1735580099
I already implemented the logic of combining uints and ints, but there was a bug. I've fixed it and added some tests as well.
> Numpy also seems to go to float when combining uint64 with any signed integer (since uint64 values cannot all be held in int64). Not sure if we should also do that ..
I agree, that's a bit awkward. If it doesn't fit, we'll get an overflow exception.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1339221494
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,76 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
+
+ /// Allow a decimal to be promoted to a float. The float type will
+ /// not itself be promoted (e.g. Decimal128 + Float32 = Float32).
+ bool promote_decimal_to_float = false;
+
+ /// Allow an integer to be promoted to a decimal.
+ ///
+ /// May fail if the decimal has insufficient precision to
+ /// accommodate the integer. (See increase_decimal_precision.)
+ bool promote_integer_to_decimal = false;
+
+ /// Allow an integer of a given bit width to be promoted to a
+ /// float; the result will be a float of an equal or greater bit
+ /// width to both of the inputs. Examples:
+ /// - int8 + float32 = float32
+ /// - int32 + float32 = float64
+ /// - int32 + float64 = float64
+ /// Because an int32 cannot always be represented exactly in the
+ /// 24 bits of a float32 mantissa.
+ bool promote_integer_to_float = false;
+
+ /// Allow an unsigned integer of a given bit width to be promoted
+ /// to a signed integer that fits into the signed type:
+ /// uint + int16 = int16
+ /// When widening is needed, set promote_numeric_width to true:
+ /// uint16 + int16 = int32
Review Comment:
That's correct, and has been fixed now 👍
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,76 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
+
+ /// Allow a decimal to be promoted to a float. The float type will
+ /// not itself be promoted (e.g. Decimal128 + Float32 = Float32).
+ bool promote_decimal_to_float = false;
+
+ /// Allow an integer to be promoted to a decimal.
+ ///
+ /// May fail if the decimal has insufficient precision to
+ /// accommodate the integer. (See increase_decimal_precision.)
+ bool promote_integer_to_decimal = false;
+
+ /// Allow an integer of a given bit width to be promoted to a
+ /// float; the result will be a float of an equal or greater bit
+ /// width to both of the inputs. Examples:
+ /// - int8 + float32 = float32
+ /// - int32 + float32 = float64
+ /// - int32 + float64 = float64
+ /// Because an int32 cannot always be represented exactly in the
+ /// 24 bits of a float32 mantissa.
+ bool promote_integer_to_float = false;
+
+ /// Allow an unsigned integer of a given bit width to be promoted
+ /// to a signed integer that fits into the signed type:
+ /// uint + int16 = int16
+ /// When widening is needed, set promote_numeric_width to true:
+ /// uint16 + int16 = int32
Review Comment:
That's correct, and has been fixed now 👍
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] pitrou commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "pitrou (via GitHub)" <gi...@apache.org>.
pitrou commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1274962828
##########
cpp/src/arrow/type_traits.h:
##########
@@ -1187,7 +1202,6 @@ constexpr bool is_var_length_list(Type::type type_id) {
switch (type_id) {
case Type::LIST:
case Type::LARGE_LIST:
- case Type::MAP:
Review Comment:
Well, 1) It is a public API, so we probably shouldn't change the current semantics, 2) one should review internal uses of it to make sure changing it doesn't break anything that wouldn't be adequately tested.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1302612955
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
Review Comment:
Changed this to a `TypeError` as well
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] jorisvandenbossche commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "jorisvandenbossche (via GitHub)" <gi...@apache.org>.
jorisvandenbossche commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1303024203
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,67 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
+
+ /// Allow a decimal to be promoted to a float. The float type will
+ /// not itself be promoted (e.g. Decimal128 + Float32 = Float32).
+ bool promote_decimal_to_float = false;
+
+ /// Allow an integer to be promoted to a decimal.
+ ///
+ /// May fail if the decimal has insufficient precision to
+ /// accommodate the integer. (See increase_decimal_precision.)
+ bool promote_integer_to_decimal = false;
+
+ /// Allow an integer of a given bit width to be promoted to a
+ /// float; the result will be a float of an equal or greater bit
+ /// width to both of the inputs.
+ bool promote_integer_to_float = false;
+
+ /// Allow an unsigned integer of a given bit width to be promoted
+ /// to a signed integer of the equal or greater bit width.
+ bool promote_integer_sign = false;
Review Comment:
Potentially dubious case from reading the above: uint32 + int8 -> ? (I assume int64, but only if `promote_numeric_width` is also true, because otherwise the int8 needs to stay int8?)
##########
python/pyarrow/table.pxi:
##########
@@ -5042,9 +5043,14 @@ def concat_tables(tables, c_bool promote=False, MemoryPool memory_pool=None):
tables : iterable of pyarrow.Table objects
Pyarrow tables to concatenate into a single Table.
promote : bool, default False
- If True, concatenate tables with null-filling and null type promotion.
+ If True, concatenate tables with null-filling and type promotion.
+ See field_merge_options for the type promotion behavior.
Review Comment:
From a user experience perspective, I find it a bit strange that I still have to specify `promote=True` when I already specified field_merge_options="permissive" (because the latter only makes sense with promote=True). Essentially the `promote=False` can be seen as a "no promotion" field merge option?
I know this is an existing keyword, but maybe going forward we should try to merge `promote` and `field_merge_options` in a single keyword?
(on the naming side, I think I actually like "promote_options" better than "field_merge_options", but that would then deviate from the C++ naming ..)
##########
cpp/src/arrow/type.cc:
##########
@@ -327,6 +315,449 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_list = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_decimal=" << (promote_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_list=" << (promote_list ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_dictionary_ordered="
+ << (promote_dictionary_ordered ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::TypeError(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_temporal_unit) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+
+ if (promoted_type->id() == Type::DURATION && other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(std::max(left.unit(), right.unit()));
+ }
+
+ if (is_time(promoted_type->id()) && is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = std::max(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+ }
+
+ if (promoted_type->id() == Type::TIMESTAMP && other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::TypeError(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::TypeError("Cannot merge timestamps with differing timezones");
+ }
+ if (options.promote_temporal_unit) {
+ return timestamp(std::max(left.unit(), right.unit()), left.timezone());
+ }
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-numeric types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_to_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_to_decimal &&
+ ((is_decimal(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_decimal(other_type->id()) && is_integer(promoted_type->id())))) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ // Other type is always the int
+ promoted_type.swap(other_type);
+ }
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(const auto promoted_decimal,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ ARROW_ASSIGN_OR_RAISE(promoted_type,
+ WidenDecimals(promoted_type, promoted_decimal, options));
+ return promoted_type;
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ ARROW_ASSIGN_OR_RAISE(promoted_type,
+ WidenDecimals(promoted_type, other_type, options));
+ return promoted_type;
+ }
+
+ if (options.promote_integer_sign && ((is_unsigned_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) ||
+ (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())))) {
+ if (!options.promote_numeric_width &&
+ bit_width(promoted_type->id()) != bit_width(other_type->id())) {
+ return Status::TypeError(
+ "Cannot widen (un)signed integers without promote_numeric_width=true");
+ }
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
Review Comment:
This means that `uint32` gets promoted to `int32`? But should that be `int64` instead?
##########
cpp/src/arrow/table.cc:
##########
@@ -502,9 +515,23 @@ Result<std::shared_ptr<Table>> PromoteTableToSchema(const std::shared_ptr<Table>
continue;
}
+#ifdef ARROW_COMPUTE
+ if (!compute::CanCast(*current_field->type(), *field->type())) {
+ return Status::TypeError("Unable to promote field ", field->name(),
+ ": incompatible types: ", field->type()->ToString(),
+ " vs ", current_field->type()->ToString());
+ }
+ compute::ExecContext ctx(pool);
+ ARROW_ASSIGN_OR_RAISE(auto casted, compute::Cast(table->column(field_index),
+ field->type(), *options, &ctx));
+ columns.push_back(casted.chunked_array());
+#else
return Status::Invalid("Unable to promote field ", field->name(),
": incompatible types: ", field->type()->ToString(), " vs ",
Review Comment:
But related question: I thought the core cast kernels were always available, even if ARROW_COMPUTE wasn't enabled? (https://github.com/apache/arrow/pull/34295)
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,67 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
Review Comment:
So this only supports combining decimals of the same width, and thus for example not decimal128 and decimal256?
That sounds a bit strange to me, as we do support casting from decimal128 to decimal256.
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,67 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
+
+ /// Allow a decimal to be promoted to a float. The float type will
+ /// not itself be promoted (e.g. Decimal128 + Float32 = Float32).
+ bool promote_decimal_to_float = false;
+
+ /// Allow an integer to be promoted to a decimal.
+ ///
+ /// May fail if the decimal has insufficient precision to
+ /// accommodate the integer. (See increase_decimal_precision.)
+ bool promote_integer_to_decimal = false;
+
+ /// Allow an integer of a given bit width to be promoted to a
+ /// float; the result will be a float of an equal or greater bit
+ /// width to both of the inputs.
+ bool promote_integer_to_float = false;
Review Comment:
In addition, I think ideally we also document somewhere _exactly_ how our numeric type promotions work (the comment above says "equal or greater" for the resulting bitwidth, but what's the exact logic for deciding this?)
##########
cpp/src/arrow/table.cc:
##########
@@ -502,9 +515,23 @@ Result<std::shared_ptr<Table>> PromoteTableToSchema(const std::shared_ptr<Table>
continue;
}
+#ifdef ARROW_COMPUTE
+ if (!compute::CanCast(*current_field->type(), *field->type())) {
+ return Status::TypeError("Unable to promote field ", field->name(),
+ ": incompatible types: ", field->type()->ToString(),
+ " vs ", current_field->type()->ToString());
+ }
+ compute::ExecContext ctx(pool);
+ ARROW_ASSIGN_OR_RAISE(auto casted, compute::Cast(table->column(field_index),
+ field->type(), *options, &ctx));
+ columns.push_back(casted.chunked_array());
+#else
return Status::Invalid("Unable to promote field ", field->name(),
": incompatible types: ", field->type()->ToString(), " vs ",
Review Comment:
The "incompatible types" here is now a potentially confusing term? (I would consider int32 and int64 as "compatible") Maybe just use "not equal" instead?
##########
python/pyarrow/types.pxi:
##########
@@ -2014,6 +2014,48 @@ cpdef KeyValueMetadata ensure_metadata(object meta, c_bool allow_none=False):
return KeyValueMetadata(meta)
+cdef class FieldMergeOptions(_Weakrefable):
+ """
+ Options controlling how to merge the types of two fields.
+
+ By default, types must match exactly, except the null type can be
+ merged with any other type.
+
+ """
+
+ cdef:
+ CField.CMergeOptions c_options
+
+ __slots__ = ()
+
+ def __init__(self, *):
+ self.c_options = CField.CMergeOptions.Defaults()
Review Comment:
Do we want to expose all fine grained options in Python? (now it's only the "permissive" and "default")
While trying this out, I expected I could do something like `concat_tables(..., field_merge_options=pa.FieldMergeOptions(promote_integer_to_decimal=True)`
If we only allow the two main options, I am not sure it is worth actually exposing this class publicly.
(exposing the fine grained options in python can also be a follow-up)
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,67 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
+
+ /// Allow a decimal to be promoted to a float. The float type will
+ /// not itself be promoted (e.g. Decimal128 + Float32 = Float32).
+ bool promote_decimal_to_float = false;
+
+ /// Allow an integer to be promoted to a decimal.
+ ///
+ /// May fail if the decimal has insufficient precision to
+ /// accommodate the integer. (See increase_decimal_precision.)
+ bool promote_integer_to_decimal = false;
+
+ /// Allow an integer of a given bit width to be promoted to a
+ /// float; the result will be a float of an equal or greater bit
+ /// width to both of the inputs.
+ bool promote_integer_to_float = false;
+
+ /// Allow an unsigned integer of a given bit width to be promoted
+ /// to a signed integer of the equal or greater bit width.
+ bool promote_integer_sign = false;
+
+ /// Allow an integer, float, or decimal of a given bit width to be
+ /// promoted to an equivalent type of a greater bit width.
+ bool promote_numeric_width = false;
+
+ /// Allow strings to be promoted to binary types. Promotion of fixed size
+ /// binary types to variable sized formats, and binary to large binary,
+ /// and string to large string.
+ bool promote_binary = false;
+
+ /// Second to millisecond, Time32 to Time64, Time32(SECOND) to Time32(MILLI), etc
+ bool promote_temporal_unit = false;
+
+ /// Allow promotion from a list to a large-list
+ bool promote_list = false;
Review Comment:
and also from fixed size list to variable sized list?
##########
python/pyarrow/types.pxi:
##########
@@ -3173,6 +3215,9 @@ def unify_schemas(schemas):
----------
schemas : list of Schema
Schemas to merge into a single one.
+ options : FieldMergeOptions or string, optional
Review Comment:
Maybe we should align the keyword name with the other places where we pass this? In `concat_tables`, it's called `field_merge_options`, which is quite long, so another option is something in between (`merge_options`, although that's probably not very descriptive being about the field types, or `promote_options`, but then that deviates from the naming in C++)
##########
python/pyarrow/types.pxi:
##########
@@ -3173,6 +3215,9 @@ def unify_schemas(schemas):
----------
schemas : list of Schema
Schemas to merge into a single one.
+ options : FieldMergeOptions or string, optional
+ Options for merging duplicate fields.
Review Comment:
```suggestion
Options for merging fields with the same name (which type to promote to).
```
("duplicate" is a bit confusing in this context I think)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1302677319
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_temporal_unit) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(std::max(left.unit(), right.unit()));
+ }
+
+ if (options.promote_temporal_unit && is_time(promoted_type->id()) &&
+ is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = std::max(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::TypeError(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::TypeError("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(std::max(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-numeric types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_to_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_to_decimal &&
+ ((is_decimal(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_decimal(other_type->id()) && is_integer(promoted_type->id())))) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ // Other type is always the int
+ promoted_type.swap(other_type);
+ }
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(const auto promoted_decimal,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, promoted_decimal));
+ return promoted_type;
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const DecimalType& left = checked_cast<const DecimalType&>(*promoted_type);
+ const DecimalType& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::TypeError(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, other_type));
+ return promoted_type;
+ }
+
+ if (options.promote_integer_sign && ((is_unsigned_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) ||
+ (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
+ } else if (max_width >= 16) {
+ promoted_type = int16();
+ } else {
+ promoted_type = int8();
+ }
+ return promoted_type;
+ }
+
+ if (options.promote_integer_to_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ }
+
+ if (options.promote_numeric_width) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (is_floating(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
+ } else if (max_width >= 16) {
+ promoted_type = int16();
+ } else {
+ promoted_type = int8();
+ }
+ } else if (is_unsigned_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = uint64();
+ } else if (max_width >= 32) {
+ promoted_type = uint32();
+ } else if (max_width >= 16) {
+ promoted_type = uint16();
+ } else {
+ promoted_type = uint8();
+ }
+ }
+ }
+
+ return promoted ? promoted_type : nullptr;
+}
+
+// Merge temporal types based on options. Returns nullptr for non-binary types.
+Result<std::shared_ptr<DataType>> MaybeMergeBinaryTypes(
+ std::shared_ptr<DataType>& promoted_type, std::shared_ptr<DataType>& other_type,
+ const Field::MergeOptions& options) {
+ if (options.promote_binary) {
+ if (other_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(promoted_type->id())) {
+ return MakeBinary(*promoted_type);
+ } else if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(other_type->id())) {
+ return MakeBinary(*other_type);
+ } else if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ other_type->id() == Type::FIXED_SIZE_BINARY) {
+ return binary();
+ } else if (is_string(promoted_type->id()) && is_binary(other_type->id())) {
+ return MakeBinary(*other_type);
+ } else if (is_binary(promoted_type->id()) && is_string(other_type->id())) {
+ return MakeBinary(*promoted_type);
+ }
+
+ if ((promoted_type->id() == Type::STRING && other_type->id() == Type::LARGE_STRING) ||
+ (promoted_type->id() == Type::LARGE_STRING && other_type->id() == Type::STRING)) {
+ return large_utf8();
+ } else if ((promoted_type->id() == Type::BINARY &&
+ other_type->id() == Type::LARGE_BINARY) ||
+ (promoted_type->id() == Type::LARGE_BINARY &&
+ other_type->id() == Type::BINARY)) {
+ return large_binary();
+ }
+ }
+
+ return nullptr;
+}
+
+// Merge list types based on options. Returns nullptr for non-list types.
+Result<std::shared_ptr<DataType>> MaybeMergeListTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ bool promoted = false;
+
Review Comment:
I think if either of the sides is large, then I would expect large, but I can add this option
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] kou commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "kou (via GitHub)" <gi...@apache.org>.
kou commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1322232396
##########
c_glib/test/dataset/test-file-system-dataset-factory.rb:
##########
@@ -109,9 +109,9 @@ def test_validate_fragments
point: Arrow::Int16DataType.new)
options.validate_fragments = true
message = "[file-system-dataset-factory][finish]: " +
- "Invalid: Unable to merge: " +
+ "Type Error: Unable to merge: " +
"Field point has incompatible types: int16 vs int32"
- error = assert_raise(Arrow::Error::Invalid) do
+ error = assert_raise(Arrow::Error::TypeError) do
Review Comment:
```suggestion
error = assert_raise(Arrow::Error::Type) do
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1295857260
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_temporal_unit) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(std::max(left.unit(), right.unit()));
+ }
+
+ if (options.promote_temporal_unit && is_time(promoted_type->id()) &&
+ is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = std::max(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::TypeError(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::TypeError("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(std::max(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-numeric types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_to_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_to_decimal &&
+ ((is_decimal(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_decimal(other_type->id()) && is_integer(promoted_type->id())))) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ // Other type is always the int
+ promoted_type.swap(other_type);
+ }
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(const auto promoted_decimal,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, promoted_decimal));
+ return promoted_type;
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const DecimalType& left = checked_cast<const DecimalType&>(*promoted_type);
+ const DecimalType& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::TypeError(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, other_type));
+ return promoted_type;
+ }
+
+ if (options.promote_integer_sign && ((is_unsigned_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) ||
+ (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
+ } else if (max_width >= 16) {
+ promoted_type = int16();
+ } else {
+ promoted_type = int8();
+ }
+ return promoted_type;
+ }
+
+ if (options.promote_integer_to_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ }
+
+ if (options.promote_numeric_width) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (is_floating(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
+ } else if (max_width >= 16) {
+ promoted_type = int16();
+ } else {
+ promoted_type = int8();
+ }
+ } else if (is_unsigned_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = uint64();
+ } else if (max_width >= 32) {
+ promoted_type = uint32();
+ } else if (max_width >= 16) {
+ promoted_type = uint16();
+ } else {
+ promoted_type = uint8();
+ }
+ }
+ }
+
+ return promoted ? promoted_type : nullptr;
+}
+
+// Merge temporal types based on options. Returns nullptr for non-binary types.
+Result<std::shared_ptr<DataType>> MaybeMergeBinaryTypes(
+ std::shared_ptr<DataType>& promoted_type, std::shared_ptr<DataType>& other_type,
+ const Field::MergeOptions& options) {
+ if (options.promote_binary) {
+ if (other_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(promoted_type->id())) {
+ return MakeBinary(*promoted_type);
+ } else if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(other_type->id())) {
+ return MakeBinary(*other_type);
+ } else if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ other_type->id() == Type::FIXED_SIZE_BINARY) {
+ return binary();
+ } else if (is_string(promoted_type->id()) && is_binary(other_type->id())) {
+ return MakeBinary(*other_type);
Review Comment:
Should we merge those two together in the first place?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on PR #36846:
URL: https://github.com/apache/arrow/pull/36846#issuecomment-1681277533
@lidavidm Thanks, in PyIceberg we do this by taking the field, casting them accordingly, and then turning it back into a table: https://github.com/apache/iceberg/blob/master/python/pyiceberg/io/pyarrow.py#L952-L1024 It is far from optimal, and the concat operation would be perfect.
> Though I don't believe dataset has any provision for manual casting, so if you do have (say) an int column that became a float column, this would be the only way to support it.
The `pa.concat_tables` is about tables, and not about datasets. There is an option to cast them today: https://arrow.apache.org/docs/python/generated/pyarrow.Table.html#pyarrow.Table.cast
I think having the same safe flag on the `pa.concat_tables` would do the trick as well. WDYT @pitrou ?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1295766364
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
Review Comment:
Moved this to WidenDecimals.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1295863442
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_temporal_unit) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(std::max(left.unit(), right.unit()));
+ }
+
+ if (options.promote_temporal_unit && is_time(promoted_type->id()) &&
+ is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = std::max(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::TypeError(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::TypeError("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(std::max(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-numeric types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_to_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_to_decimal &&
+ ((is_decimal(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_decimal(other_type->id()) && is_integer(promoted_type->id())))) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ // Other type is always the int
+ promoted_type.swap(other_type);
+ }
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(const auto promoted_decimal,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, promoted_decimal));
+ return promoted_type;
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const DecimalType& left = checked_cast<const DecimalType&>(*promoted_type);
+ const DecimalType& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::TypeError(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, other_type));
+ return promoted_type;
+ }
+
+ if (options.promote_integer_sign && ((is_unsigned_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) ||
+ (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
+ } else if (max_width >= 16) {
+ promoted_type = int16();
+ } else {
+ promoted_type = int8();
+ }
+ return promoted_type;
+ }
+
+ if (options.promote_integer_to_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ }
+
+ if (options.promote_numeric_width) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (is_floating(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
+ } else if (max_width >= 16) {
+ promoted_type = int16();
+ } else {
+ promoted_type = int8();
+ }
+ } else if (is_unsigned_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = uint64();
+ } else if (max_width >= 32) {
+ promoted_type = uint32();
+ } else if (max_width >= 16) {
+ promoted_type = uint16();
+ } else {
+ promoted_type = uint8();
+ }
+ }
+ }
+
+ return promoted ? promoted_type : nullptr;
+}
+
+// Merge temporal types based on options. Returns nullptr for non-binary types.
+Result<std::shared_ptr<DataType>> MaybeMergeBinaryTypes(
+ std::shared_ptr<DataType>& promoted_type, std::shared_ptr<DataType>& other_type,
+ const Field::MergeOptions& options) {
+ if (options.promote_binary) {
+ if (other_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(promoted_type->id())) {
+ return MakeBinary(*promoted_type);
+ } else if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(other_type->id())) {
+ return MakeBinary(*other_type);
+ } else if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ other_type->id() == Type::FIXED_SIZE_BINARY) {
+ return binary();
+ } else if (is_string(promoted_type->id()) && is_binary(other_type->id())) {
+ return MakeBinary(*other_type);
+ } else if (is_binary(promoted_type->id()) && is_string(other_type->id())) {
+ return MakeBinary(*promoted_type);
+ }
+
+ if ((promoted_type->id() == Type::STRING && other_type->id() == Type::LARGE_STRING) ||
+ (promoted_type->id() == Type::LARGE_STRING && other_type->id() == Type::STRING)) {
+ return large_utf8();
+ } else if ((promoted_type->id() == Type::BINARY &&
+ other_type->id() == Type::LARGE_BINARY) ||
+ (promoted_type->id() == Type::LARGE_BINARY &&
+ other_type->id() == Type::BINARY)) {
+ return large_binary();
+ }
+ }
+
+ return nullptr;
+}
+
+// Merge list types based on options. Returns nullptr for non-list types.
+Result<std::shared_ptr<DataType>> MaybeMergeListTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ bool promoted = false;
+
+ if (promoted_type->id() == Type::FIXED_SIZE_LIST &&
+ other_type->id() == Type::FIXED_SIZE_LIST) {
+ const auto& left = checked_cast<const FixedSizeListType&>(*promoted_type);
+ const auto& right = checked_cast<const FixedSizeListType&>(*other_type);
+ ARROW_ASSIGN_OR_RAISE(
+ auto value_field,
+ left.value_field()->MergeWith(
+ *right.value_field()->WithName(left.value_field()->name()), options));
+ if (left.list_size() == right.list_size()) {
+ return fixed_size_list(std::move(value_field), left.list_size());
+ }
+ return Status::TypeError("Cannot merge fixed_size_list of different sizes");
+ } else if (promoted_type->id() == Type::MAP && other_type->id() == Type::MAP) {
+ const auto& left = checked_cast<const MapType&>(*promoted_type);
+ const auto& right = checked_cast<const MapType&>(*other_type);
+ ARROW_ASSIGN_OR_RAISE(
+ auto key_field,
+ left.key_field()->MergeWith(
+ *right.key_field()->WithName(left.key_field()->name()), options));
+ ARROW_ASSIGN_OR_RAISE(
+ auto item_field,
+ left.item_field()->MergeWith(
+ *right.item_field()->WithName(left.item_field()->name()), options));
+ return map(std::move(key_field->type()), std::move(item_field),
+ /*keys_sorted=*/left.keys_sorted() && right.keys_sorted());
+ } else if (is_list(promoted_type->id()) && is_list(other_type->id())) {
+ const auto& left = checked_cast<const BaseListType&>(*promoted_type);
+ const auto& right = checked_cast<const BaseListType&>(*other_type);
+ ARROW_ASSIGN_OR_RAISE(
+ auto value_field,
+ left.value_field()->MergeWith(
+ *right.value_field()->WithName(left.value_field()->name()), options));
+ if (promoted_type->id() == Type::LARGE_LIST || other_type->id() == Type::LARGE_LIST) {
+ return large_list(std::move(value_field));
+ } else {
+ return list(std::move(value_field));
+ }
+ } else if (promoted_type->id() == Type::STRUCT && other_type->id() == Type::STRUCT) {
+ SchemaBuilder builder(SchemaBuilder::CONFLICT_APPEND, options);
+ // Add the LHS fields. Duplicates will be preserved.
+ RETURN_NOT_OK(builder.AddFields(promoted_type->fields()));
+
+ // Add the RHS fields. Duplicates will be merged, unless the field was
+ // already a duplicate, in which case we error (since we don't know which
+ // field to merge with).
+ builder.SetPolicy(SchemaBuilder::CONFLICT_MERGE);
+ RETURN_NOT_OK(builder.AddFields(other_type->fields()));
+
+ ARROW_ASSIGN_OR_RAISE(auto schema, builder.Finish());
+ return struct_(schema->fields());
+ }
+
+ return promoted ? promoted_type : nullptr;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ if (promoted_type->Equals(*other_type)) return promoted_type;
+
+ bool promoted = false;
+ if (options.promote_nullability) {
+ if (promoted_type->id() == Type::NA) {
+ return other_type;
+ } else if (other_type->id() == Type::NA) {
+ return promoted_type;
+ }
+ } else if (promoted_type->id() == Type::NA || other_type->id() == Type::NA) {
+ return Status::Invalid("Cannot merge type with null unless promote_nullability=true");
Review Comment:
Yes, that's more appropriate
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] pitrou commented on pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "pitrou (via GitHub)" <gi...@apache.org>.
pitrou commented on PR #36846:
URL: https://github.com/apache/arrow/pull/36846#issuecomment-1680853510
Ahah, I see. @lidavidm Could you take a look at @Fokko 's questions above?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1295859928
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_temporal_unit) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(std::max(left.unit(), right.unit()));
+ }
+
+ if (options.promote_temporal_unit && is_time(promoted_type->id()) &&
+ is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = std::max(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::TypeError(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::TypeError("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(std::max(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-numeric types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_to_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_to_decimal &&
+ ((is_decimal(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_decimal(other_type->id()) && is_integer(promoted_type->id())))) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ // Other type is always the int
+ promoted_type.swap(other_type);
+ }
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(const auto promoted_decimal,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, promoted_decimal));
+ return promoted_type;
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const DecimalType& left = checked_cast<const DecimalType&>(*promoted_type);
+ const DecimalType& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::TypeError(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, other_type));
+ return promoted_type;
+ }
+
+ if (options.promote_integer_sign && ((is_unsigned_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) ||
+ (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
+ } else if (max_width >= 16) {
+ promoted_type = int16();
+ } else {
+ promoted_type = int8();
+ }
+ return promoted_type;
+ }
+
+ if (options.promote_integer_to_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ }
+
+ if (options.promote_numeric_width) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (is_floating(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
+ } else if (max_width >= 16) {
+ promoted_type = int16();
+ } else {
+ promoted_type = int8();
+ }
+ } else if (is_unsigned_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = uint64();
+ } else if (max_width >= 32) {
+ promoted_type = uint32();
+ } else if (max_width >= 16) {
+ promoted_type = uint16();
+ } else {
+ promoted_type = uint8();
+ }
+ }
+ }
+
+ return promoted ? promoted_type : nullptr;
+}
+
+// Merge temporal types based on options. Returns nullptr for non-binary types.
+Result<std::shared_ptr<DataType>> MaybeMergeBinaryTypes(
+ std::shared_ptr<DataType>& promoted_type, std::shared_ptr<DataType>& other_type,
+ const Field::MergeOptions& options) {
+ if (options.promote_binary) {
+ if (other_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(promoted_type->id())) {
+ return MakeBinary(*promoted_type);
+ } else if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(other_type->id())) {
+ return MakeBinary(*other_type);
+ } else if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ other_type->id() == Type::FIXED_SIZE_BINARY) {
+ return binary();
+ } else if (is_string(promoted_type->id()) && is_binary(other_type->id())) {
+ return MakeBinary(*other_type);
+ } else if (is_binary(promoted_type->id()) && is_string(other_type->id())) {
+ return MakeBinary(*promoted_type);
+ }
+
+ if ((promoted_type->id() == Type::STRING && other_type->id() == Type::LARGE_STRING) ||
+ (promoted_type->id() == Type::LARGE_STRING && other_type->id() == Type::STRING)) {
+ return large_utf8();
+ } else if ((promoted_type->id() == Type::BINARY &&
+ other_type->id() == Type::LARGE_BINARY) ||
+ (promoted_type->id() == Type::LARGE_BINARY &&
+ other_type->id() == Type::BINARY)) {
+ return large_binary();
+ }
+ }
+
+ return nullptr;
+}
+
+// Merge list types based on options. Returns nullptr for non-list types.
+Result<std::shared_ptr<DataType>> MaybeMergeListTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ bool promoted = false;
+
+ if (promoted_type->id() == Type::FIXED_SIZE_LIST &&
+ other_type->id() == Type::FIXED_SIZE_LIST) {
+ const auto& left = checked_cast<const FixedSizeListType&>(*promoted_type);
+ const auto& right = checked_cast<const FixedSizeListType&>(*other_type);
+ ARROW_ASSIGN_OR_RAISE(
+ auto value_field,
+ left.value_field()->MergeWith(
+ *right.value_field()->WithName(left.value_field()->name()), options));
+ if (left.list_size() == right.list_size()) {
+ return fixed_size_list(std::move(value_field), left.list_size());
+ }
+ return Status::TypeError("Cannot merge fixed_size_list of different sizes");
Review Comment:
Sounds reasonable, updated
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] lidavidm commented on pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "lidavidm (via GitHub)" <gi...@apache.org>.
lidavidm commented on PR #36846:
URL: https://github.com/apache/arrow/pull/36846#issuecomment-1680879319
It's been long enough that I don't recall any particular reasoning, other than the cast being possible. You could certainly start smaller.
Though I don't believe dataset has any provision for manual casting, so if you do have (say) an int column that became a float column, this would be the only way to support it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] jorisvandenbossche commented on pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "jorisvandenbossche (via GitHub)" <gi...@apache.org>.
jorisvandenbossche commented on PR #36846:
URL: https://github.com/apache/arrow/pull/36846#issuecomment-1690002282
@Fokko I needed this small diff to get pyarrow building locally:
```diff
diff --git a/python/pyarrow/types.pxi b/python/pyarrow/types.pxi
index 68efd1375..53b1fe65b 100644
--- a/python/pyarrow/types.pxi
+++ b/python/pyarrow/types.pxi
@@ -3239,13 +3239,12 @@ def unify_schemas(schemas, *, options=None):
c_schemas.push_back(pyarrow_unwrap_schema(schema))
if isinstance(options, str):
if options == "default":
- options = CField.CMergeOptions.Defaults()
+ c_options = CField.CMergeOptions.Defaults()
elif options == "permissive":
- options = CField.CMergeOptions.Permissive()
+ c_options = CField.CMergeOptions.Permissive()
else:
raise ValueError(f"Invalid merge option: {options}")
-
- if options:
+ elif options is not None:
c_options = (<FieldMergeOptions> options).c_options
else:
c_options = CField.CMergeOptions.Defaults()
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] jorisvandenbossche commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "jorisvandenbossche (via GitHub)" <gi...@apache.org>.
jorisvandenbossche commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1336805745
##########
python/pyarrow/table.pxi:
##########
@@ -5042,9 +5043,14 @@ def concat_tables(tables, c_bool promote=False, MemoryPool memory_pool=None):
tables : iterable of pyarrow.Table objects
Pyarrow tables to concatenate into a single Table.
promote : bool, default False
- If True, concatenate tables with null-filling and null type promotion.
+ If True, concatenate tables with null-filling and type promotion.
+ See field_merge_options for the type promotion behavior.
Review Comment:
> The problem is that the `promote` is only relevant when merging tables, when just upcasting fields, then you don't need this, therefore `merge_options` might not be the best place to put it.
Do you mean with "merging" tables for when the columns don't match? So if a column is not present in one of the tables, it gets filled with all nulls. This specific aspect is not something that you can control with `field_merge_options`? (you can only control whether to upcast null type to the target type, if the nulls where already present)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] jorisvandenbossche commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "jorisvandenbossche (via GitHub)" <gi...@apache.org>.
jorisvandenbossche commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1336812905
##########
python/pyarrow/types.pxi:
##########
@@ -2014,6 +2014,48 @@ cpdef KeyValueMetadata ensure_metadata(object meta, c_bool allow_none=False):
return KeyValueMetadata(meta)
+cdef class FieldMergeOptions(_Weakrefable):
+ """
+ Options controlling how to merge the types of two fields.
+
+ By default, types must match exactly, except the null type can be
+ merged with any other type.
+
+ """
+
+ cdef:
+ CField.CMergeOptions c_options
+
+ __slots__ = ()
+
+ def __init__(self, *):
+ self.c_options = CField.CMergeOptions.Defaults()
Review Comment:
I am certainly fine with not exposing the fine-grained options for this PR. But in that case we maybe also don't need this class? (and just accept the string version in the function that have this option)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] jorisvandenbossche commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "jorisvandenbossche (via GitHub)" <gi...@apache.org>.
jorisvandenbossche commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1336807999
##########
python/pyarrow/types.pxi:
##########
@@ -3173,6 +3215,9 @@ def unify_schemas(schemas):
----------
schemas : list of Schema
Schemas to merge into a single one.
+ options : FieldMergeOptions or string, optional
Review Comment:
Yes, but for the cast example, it are the CastOptions passed to the cast kernel. While here we have options for promoting types that is not tied to a specific function (i.e. it's used both in unify_schema, concat_tables, and potentially others)
(eg also on the C++ side Cast just has `options`, while UnifySchemas takes `field_merge_options`)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] jorisvandenbossche commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "jorisvandenbossche (via GitHub)" <gi...@apache.org>.
jorisvandenbossche commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1336944831
##########
python/pyarrow/types.pxi:
##########
@@ -2014,6 +2014,48 @@ cpdef KeyValueMetadata ensure_metadata(object meta, c_bool allow_none=False):
return KeyValueMetadata(meta)
+cdef class FieldMergeOptions(_Weakrefable):
+ """
+ Options controlling how to merge the types of two fields.
+
+ By default, types must match exactly, except the null type can be
+ merged with any other type.
+
+ """
+
+ cdef:
+ CField.CMergeOptions c_options
+
+ __slots__ = ()
+
+ def __init__(self, *):
+ self.c_options = CField.CMergeOptions.Defaults()
Review Comment:
> Keep in mind that the `concat_tables` will try to match the schema of the first table,
I think when `promote=True` is specified (which translates to `unify_schemas=True` on the C++ side), we actually do unify the schemas of all input tables first, and so not just take the schema of the first input? (the text about the first table is only to determine which schema _metadata_ to use for the return value)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1295576348
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
Review Comment:
Also the decimals we're missing, added those!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1307101413
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,67 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
+
+ /// Allow a decimal to be promoted to a float. The float type will
+ /// not itself be promoted (e.g. Decimal128 + Float32 = Float32).
+ bool promote_decimal_to_float = false;
+
+ /// Allow an integer to be promoted to a decimal.
+ ///
+ /// May fail if the decimal has insufficient precision to
+ /// accommodate the integer. (See increase_decimal_precision.)
+ bool promote_integer_to_decimal = false;
+
+ /// Allow an integer of a given bit width to be promoted to a
+ /// float; the result will be a float of an equal or greater bit
+ /// width to both of the inputs.
+ bool promote_integer_to_float = false;
Review Comment:
Updated the docstring to:
```
/// Allow an integer of a given bit width to be promoted to a
/// float; the result will be a float of an equal or greater bit
/// width to both of the inputs. Examples:
/// - int8 + float32 = float32
/// - int32 + float32 = float64
/// - int32 + float64 = float64
/// Because an int32 cannot always be represented exactly in the
/// 24 bits of a float32 mantissa.
```
Let me know if you had an other place in mind to document this.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1307183313
##########
python/pyarrow/types.pxi:
##########
@@ -3173,6 +3215,9 @@ def unify_schemas(schemas):
----------
schemas : list of Schema
Schemas to merge into a single one.
+ options : FieldMergeOptions or string, optional
Review Comment:
Hmm, maybe this 🚢 has sailed already. It is also called options in `cast(target_schema, safe, options)`, I like the consistency there
##########
python/pyarrow/types.pxi:
##########
@@ -3173,6 +3215,9 @@ def unify_schemas(schemas):
----------
schemas : list of Schema
Schemas to merge into a single one.
+ options : FieldMergeOptions or string, optional
Review Comment:
Hmm, maybe this 🚢 has sailed already. It is also called options in `cast(target_schema, safe, options)`, I like the consistency there
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1307181012
##########
python/pyarrow/types.pxi:
##########
@@ -3173,6 +3215,9 @@ def unify_schemas(schemas):
----------
schemas : list of Schema
Schemas to merge into a single one.
+ options : FieldMergeOptions or string, optional
Review Comment:
I can rename it to `promote_options` everywhere.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] jorisvandenbossche commented on pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "jorisvandenbossche (via GitHub)" <gi...@apache.org>.
jorisvandenbossche commented on PR #36846:
URL: https://github.com/apache/arrow/pull/36846#issuecomment-1741122238
About https://github.com/apache/arrow/pull/36846#issuecomment-1735513388:
> I'm not sure what you're referring to here: [#36846 (comment)](https://github.com/apache/arrow/pull/36846#discussion_r1336872769)
I suggested to add that to the doc comment of `promote_decimal` (like you did in the docstring for `promote_integer_sign`):
> Ah, I see in the code that this can be done with `promote_numeric_width`. Maybe mention that here in the doc comment as well? (I didn't directly think about that)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables` [arrow]
Posted by "jorisvandenbossche (via GitHub)" <gi...@apache.org>.
jorisvandenbossche commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1348635657
##########
python/pyarrow/table.pxi:
##########
@@ -5024,31 +5024,35 @@ def table(data, names=None, schema=None, metadata=None, nthreads=None):
"Expected pandas DataFrame, python dictionary or list of arrays")
-def concat_tables(tables, c_bool promote=False, MemoryPool memory_pool=None):
+def concat_tables(tables, MemoryPool memory_pool=None, str promote_options="none", **kwargs):
"""
Concatenate pyarrow.Table objects.
- If promote==False, a zero-copy concatenation will be performed. The schemas
+ If promote_options=="none", a zero-copy concatenation will be performed. The schemas
Review Comment:
```suggestion
If promote_options="none", a zero-copy concatenation will be performed. The schemas
```
##########
python/pyarrow/types.pxi:
##########
@@ -3174,6 +3174,10 @@ def unify_schemas(schemas):
----------
schemas : list of Schema
Schemas to merge into a single one.
+ promote_options : str, default default
+ Accepts strings "default" and "permissive".
+ Default; null and only null can be unified with another type.
+ Permissive; promotes types to the greater common denominator.
Review Comment:
```suggestion
Default: null and only null can be unified with another type.
Permissive: types are promoted to the greater common denominator.
```
##########
python/pyarrow/table.pxi:
##########
@@ -5078,11 +5082,24 @@ def concat_tables(tables, c_bool promote=False, MemoryPool memory_pool=None):
CConcatenateTablesOptions options = (
CConcatenateTablesOptions.Defaults())
+ if "promote" in kwargs:
+ warnings.warn(
+ "promote has been superseded by mode='default'.", FutureWarning)
Review Comment:
```suggestion
"promote has been superseded by mode='default'.", FutureWarning, stacklevel=2)
```
##########
python/pyarrow/table.pxi:
##########
@@ -5024,31 +5024,35 @@ def table(data, names=None, schema=None, metadata=None, nthreads=None):
"Expected pandas DataFrame, python dictionary or list of arrays")
-def concat_tables(tables, c_bool promote=False, MemoryPool memory_pool=None):
+def concat_tables(tables, MemoryPool memory_pool=None, str promote_options="none", **kwargs):
"""
Concatenate pyarrow.Table objects.
- If promote==False, a zero-copy concatenation will be performed. The schemas
+ If promote_options=="none", a zero-copy concatenation will be performed. The schemas
of all the Tables must be the same (except the metadata), otherwise an
exception will be raised. The result Table will share the metadata with the
first table.
- If promote==True, any null type arrays will be casted to the type of other
+ If promote_options=="default", any null type arrays will be casted to the type of other
Review Comment:
```suggestion
If promote_options="default", any null type arrays will be casted to the type of other
```
##########
python/pyarrow/table.pxi:
##########
@@ -5078,11 +5082,24 @@ def concat_tables(tables, c_bool promote=False, MemoryPool memory_pool=None):
CConcatenateTablesOptions options = (
CConcatenateTablesOptions.Defaults())
+ if "promote" in kwargs:
+ warnings.warn(
+ "promote has been superseded by mode='default'.", FutureWarning)
+ if kwargs['promote'] is True:
+ promote_options = "permissive"
Review Comment:
```suggestion
promote_options = "default"
```
Isn't that needed to preserve the current default behaviour?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1274664355
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +298,431 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_float = true;
+ options.promote_integer_decimal = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_date = true;
+ options.promote_duration = true;
+ options.promote_time = true;
+ options.promote_timestamp = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ options.promote_large = true;
+ options.promote_nested = true;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_float=" << (promote_integer_float ? "true" : "false");
+ ss << ", promote_integer_decimal=" << (promote_integer_decimal ? "true" : "false");
+ ss << ", promote_decimal_float=" << (promote_decimal_float ? "true" : "false");
+ ss << ", promote_date=" << (promote_date ? "true" : "false");
+ ss << ", promote_time=" << (promote_time ? "true" : "false");
+ ss << ", promote_duration=" << (promote_duration ? "true" : "false");
+ ss << ", promote_timestamp=" << (promote_timestamp ? "true" : "false");
+ ss << ", promote_nested=" << (promote_nested ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_large=" << (promote_large ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeSigned(const DataType& type) {
+ switch (type.id()) {
+ case Type::INT8:
+ case Type::UINT8:
+ return int8();
+ case Type::INT16:
+ case Type::UINT16:
+ return int16();
+ case Type::INT32:
+ case Type::UINT32:
+ return int32();
+ case Type::INT64:
+ case Type::UINT64:
+ return int64();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+TimeUnit::type CommonTimeUnit(TimeUnit::type left, TimeUnit::type right) {
+ if (left == TimeUnit::NANO || right == TimeUnit::NANO) {
+ return TimeUnit::NANO;
+ } else if (left == TimeUnit::MICRO || right == TimeUnit::MICRO) {
+ return TimeUnit::MICRO;
+ } else if (left == TimeUnit::MILLI || right == TimeUnit::MILLI) {
+ return TimeUnit::MILLI;
+ }
+ return TimeUnit::SECOND;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::Invalid(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_date) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_duration && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(CommonTimeUnit(left.unit(), right.unit()));
+ }
+
+ if (options.promote_time && is_time(promoted_type->id()) && is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = CommonTimeUnit(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_timestamp && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::Invalid(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::Invalid("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(CommonTimeUnit(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_decimal) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ promoted_type.swap(other_type);
+ }
+
+ if (is_decimal(promoted_type->id()) && is_integer(other_type->id())) {
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(other_type,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ promoted = true;
+ }
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::Invalid(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ (options.promote_numeric_width &&
+ common_precision > BasicDecimal128::kMaxPrecision)) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+ }
+
+ if (options.promote_integer_sign) {
+ if (is_unsigned_integer(promoted_type->id()) && is_signed_integer(other_type->id())) {
+ promoted = bit_width(other_type->id()) >= bit_width(promoted_type->id());
+ promoted_type = MakeSigned(*promoted_type);
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ promoted = bit_width(promoted_type->id()) >= bit_width(other_type->id());
+ other_type = MakeSigned(*other_type);
+ }
+ }
+
+ if (options.promote_integer_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ promoted = true;
+ }
+
+ if (options.promote_numeric_width) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (is_floating(promoted_type->id()) && is_floating(other_type->id())) {
+ if (max_width >= 64) {
+ return float64();
+ } else if (max_width >= 32) {
+ return float32();
+ }
+ return float16();
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return int64();
+ } else if (max_width >= 32) {
+ return int32();
+ } else if (max_width >= 16) {
+ return int16();
+ }
+ return int8();
+ } else if (is_unsigned_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return uint64();
+ } else if (max_width >= 32) {
+ return uint32();
+ } else if (max_width >= 16) {
+ return uint16();
+ }
+ return uint8();
+ }
+ }
+
+ return promoted ? promoted_type : nullptr;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ if (promoted_type->Equals(*other_type)) return promoted_type;
+
+ bool promoted = false;
+ if (options.promote_nullability) {
+ if (promoted_type->id() == Type::NA) {
+ return other_type;
+ } else if (other_type->id() == Type::NA) {
+ return promoted_type;
+ }
+ } else if (promoted_type->id() == Type::NA || other_type->id() == Type::NA) {
+ return Status::Invalid("Cannot merge type with null unless promote_nullability=true");
+ }
+
+ if (options.promote_dictionary && is_dictionary(promoted_type->id()) &&
+ is_dictionary(other_type->id())) {
+ return MergeDictionaryTypes(promoted_type, other_type, options);
+ }
+
+ ARROW_ASSIGN_OR_RAISE(auto maybe_promoted,
+ MaybeMergeTemporalTypes(promoted_type, other_type, options));
+ if (maybe_promoted) return maybe_promoted;
+
+ ARROW_ASSIGN_OR_RAISE(maybe_promoted,
+ MaybeMergeNumericTypes(promoted_type, other_type, options));
+ if (maybe_promoted) return maybe_promoted;
+
+ if (options.promote_large) {
+ if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
Review Comment:
I think we should remove `promote_large`, and replace it with `promote_binary`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1274828067
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +298,431 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_float = true;
+ options.promote_integer_decimal = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_date = true;
+ options.promote_duration = true;
+ options.promote_time = true;
+ options.promote_timestamp = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ options.promote_large = true;
+ options.promote_nested = true;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_float=" << (promote_integer_float ? "true" : "false");
+ ss << ", promote_integer_decimal=" << (promote_integer_decimal ? "true" : "false");
+ ss << ", promote_decimal_float=" << (promote_decimal_float ? "true" : "false");
+ ss << ", promote_date=" << (promote_date ? "true" : "false");
+ ss << ", promote_time=" << (promote_time ? "true" : "false");
+ ss << ", promote_duration=" << (promote_duration ? "true" : "false");
+ ss << ", promote_timestamp=" << (promote_timestamp ? "true" : "false");
+ ss << ", promote_nested=" << (promote_nested ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_large=" << (promote_large ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeSigned(const DataType& type) {
+ switch (type.id()) {
+ case Type::INT8:
+ case Type::UINT8:
+ return int8();
+ case Type::INT16:
+ case Type::UINT16:
+ return int16();
+ case Type::INT32:
+ case Type::UINT32:
+ return int32();
+ case Type::INT64:
+ case Type::UINT64:
+ return int64();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+TimeUnit::type CommonTimeUnit(TimeUnit::type left, TimeUnit::type right) {
+ if (left == TimeUnit::NANO || right == TimeUnit::NANO) {
+ return TimeUnit::NANO;
+ } else if (left == TimeUnit::MICRO || right == TimeUnit::MICRO) {
+ return TimeUnit::MICRO;
+ } else if (left == TimeUnit::MILLI || right == TimeUnit::MILLI) {
+ return TimeUnit::MILLI;
+ }
+ return TimeUnit::SECOND;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::Invalid(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_date) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_duration && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(CommonTimeUnit(left.unit(), right.unit()));
+ }
+
+ if (options.promote_time && is_time(promoted_type->id()) && is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = CommonTimeUnit(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_timestamp && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::Invalid(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::Invalid("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(CommonTimeUnit(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_decimal) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ promoted_type.swap(other_type);
+ }
+
+ if (is_decimal(promoted_type->id()) && is_integer(other_type->id())) {
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(other_type,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ promoted = true;
+ }
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::Invalid(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ (options.promote_numeric_width &&
+ common_precision > BasicDecimal128::kMaxPrecision)) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+ }
+
+ if (options.promote_integer_sign) {
+ if (is_unsigned_integer(promoted_type->id()) && is_signed_integer(other_type->id())) {
+ promoted = bit_width(other_type->id()) >= bit_width(promoted_type->id());
+ promoted_type = MakeSigned(*promoted_type);
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ promoted = bit_width(promoted_type->id()) >= bit_width(other_type->id());
+ other_type = MakeSigned(*other_type);
+ }
+ }
+
+ if (options.promote_integer_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ promoted = true;
+ }
+
+ if (options.promote_numeric_width) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (is_floating(promoted_type->id()) && is_floating(other_type->id())) {
+ if (max_width >= 64) {
+ return float64();
+ } else if (max_width >= 32) {
+ return float32();
+ }
+ return float16();
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return int64();
+ } else if (max_width >= 32) {
+ return int32();
+ } else if (max_width >= 16) {
+ return int16();
+ }
+ return int8();
+ } else if (is_unsigned_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return uint64();
+ } else if (max_width >= 32) {
+ return uint32();
+ } else if (max_width >= 16) {
+ return uint16();
+ }
+ return uint8();
+ }
+ }
+
+ return promoted ? promoted_type : nullptr;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ if (promoted_type->Equals(*other_type)) return promoted_type;
+
+ bool promoted = false;
+ if (options.promote_nullability) {
+ if (promoted_type->id() == Type::NA) {
+ return other_type;
+ } else if (other_type->id() == Type::NA) {
+ return promoted_type;
+ }
+ } else if (promoted_type->id() == Type::NA || other_type->id() == Type::NA) {
+ return Status::Invalid("Cannot merge type with null unless promote_nullability=true");
+ }
+
+ if (options.promote_dictionary && is_dictionary(promoted_type->id()) &&
+ is_dictionary(other_type->id())) {
+ return MergeDictionaryTypes(promoted_type, other_type, options);
+ }
+
+ ARROW_ASSIGN_OR_RAISE(auto maybe_promoted,
+ MaybeMergeTemporalTypes(promoted_type, other_type, options));
+ if (maybe_promoted) return maybe_promoted;
+
+ ARROW_ASSIGN_OR_RAISE(maybe_promoted,
+ MaybeMergeNumericTypes(promoted_type, other_type, options));
+ if (maybe_promoted) return maybe_promoted;
+
+ if (options.promote_large) {
+ if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(other_type->id())) {
+ promoted_type = binary();
+ promoted = other_type->id() == Type::BINARY;
+ }
+ if (other_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(promoted_type->id())) {
+ other_type = binary();
+ promoted = promoted_type->id() == Type::BINARY;
+ }
+
+ if (promoted_type->id() == Type::FIXED_SIZE_LIST &&
+ is_var_length_list(other_type->id())) {
+ promoted_type =
+ list(checked_cast<const BaseListType&>(*promoted_type).value_field());
+ promoted = other_type->Equals(*promoted_type);
+ }
+ if (other_type->id() == Type::FIXED_SIZE_LIST &&
+ is_var_length_list(promoted_type->id())) {
+ other_type = list(checked_cast<const BaseListType&>(*other_type).value_field());
+ promoted = other_type->Equals(*promoted_type);
+ }
+ }
+
+ if (options.promote_binary) {
+ if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ other_type->id() == Type::FIXED_SIZE_BINARY) {
+ return binary();
+ }
+ if (is_string(promoted_type->id()) && is_binary(other_type->id())) {
+ promoted_type = MakeBinary(*promoted_type);
+ promoted =
+ offset_bit_width(promoted_type->id()) == offset_bit_width(other_type->id());
+ } else if (is_binary(promoted_type->id()) && is_string(other_type->id())) {
+ other_type = MakeBinary(*other_type);
+ promoted =
+ offset_bit_width(promoted_type->id()) == offset_bit_width(other_type->id());
+ }
+ }
+
+ if (options.promote_large) {
+ if ((promoted_type->id() == Type::STRING && other_type->id() == Type::LARGE_STRING) ||
+ (promoted_type->id() == Type::LARGE_STRING && other_type->id() == Type::STRING)) {
+ return large_utf8();
+ } else if ((promoted_type->id() == Type::BINARY &&
+ other_type->id() == Type::LARGE_BINARY) ||
+ (promoted_type->id() == Type::LARGE_BINARY &&
+ other_type->id() == Type::BINARY)) {
+ return large_binary();
+ }
+ if ((promoted_type->id() == Type::LIST && other_type->id() == Type::LARGE_LIST) ||
+ (promoted_type->id() == Type::LARGE_LIST && other_type->id() == Type::LIST)) {
+ promoted_type =
+ large_list(checked_cast<const BaseListType&>(*promoted_type).value_field());
+ promoted = true;
Review Comment:
I took the original code from #12000. I would probably implement this using a post-order visitor pattern to traverse the schema. That would simplify the logic quite a bit.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1274924599
##########
python/pyarrow/types.pxi:
##########
@@ -1969,6 +1969,33 @@ cpdef KeyValueMetadata ensure_metadata(object meta, c_bool allow_none=False):
return KeyValueMetadata(meta)
+cdef class FieldMergeOptions(_Weakrefable):
+ """
+ Options controlling how to merge the types of two fields.
+
+ By default, types must match exactly, except the null type can be
+ merged with any other type.
+
+ """
+
+ cdef:
+ CField.CMergeOptions c_options
+
+ __slots__ = ()
+
+ def __init__(self, *):
+ self.c_options = CField.CMergeOptions.Defaults()
+
+ @staticmethod
+ def permissive():
+ """
+ Allow merging generally compatible types (e.g. float64 and int64).
+ """
+ cdef FieldMergeOptions options = FieldMergeOptions()
+ options.c_options = CField.CMergeOptions.Permissive()
+ return options
Review Comment:
That's a great suggestion
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] jorisvandenbossche commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "jorisvandenbossche (via GitHub)" <gi...@apache.org>.
jorisvandenbossche commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1303213849
##########
python/pyarrow/types.pxi:
##########
@@ -3186,12 +3231,26 @@ def unify_schemas(schemas):
"""
cdef:
Schema schema
+ CField.CMergeOptions c_options
vector[shared_ptr[CSchema]] c_schemas
for schema in schemas:
if not isinstance(schema, Schema):
raise TypeError("Expected Schema, got {}".format(type(schema)))
c_schemas.push_back(pyarrow_unwrap_schema(schema))
- return pyarrow_wrap_schema(GetResultValue(UnifySchemas(c_schemas)))
+ if isinstance(options, str):
+ if options == "default":
+ c_options = CField.CMergeOptions.Defaults()
+ elif options == "permissive":
+ c_options = CField.CMergeOptions.Permissive()
+ else:
+ raise ValueError(f"Invalid merge option: {options}")
+
+ elif c_options:
Review Comment:
```suggestion
elif options:
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1322394955
##########
c_glib/test/dataset/test-file-system-dataset-factory.rb:
##########
@@ -109,9 +109,9 @@ def test_validate_fragments
point: Arrow::Int16DataType.new)
options.validate_fragments = true
message = "[file-system-dataset-factory][finish]: " +
- "Invalid: Unable to merge: " +
+ "Type Error: Unable to merge: " +
"Field point has incompatible types: int16 vs int32"
- error = assert_raise(Arrow::Error::Invalid) do
+ error = assert_raise(Arrow::Error::TypeError) do
Review Comment:
Thank you @kou
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1274828067
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +298,431 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_float = true;
+ options.promote_integer_decimal = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_date = true;
+ options.promote_duration = true;
+ options.promote_time = true;
+ options.promote_timestamp = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ options.promote_large = true;
+ options.promote_nested = true;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_float=" << (promote_integer_float ? "true" : "false");
+ ss << ", promote_integer_decimal=" << (promote_integer_decimal ? "true" : "false");
+ ss << ", promote_decimal_float=" << (promote_decimal_float ? "true" : "false");
+ ss << ", promote_date=" << (promote_date ? "true" : "false");
+ ss << ", promote_time=" << (promote_time ? "true" : "false");
+ ss << ", promote_duration=" << (promote_duration ? "true" : "false");
+ ss << ", promote_timestamp=" << (promote_timestamp ? "true" : "false");
+ ss << ", promote_nested=" << (promote_nested ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_large=" << (promote_large ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeSigned(const DataType& type) {
+ switch (type.id()) {
+ case Type::INT8:
+ case Type::UINT8:
+ return int8();
+ case Type::INT16:
+ case Type::UINT16:
+ return int16();
+ case Type::INT32:
+ case Type::UINT32:
+ return int32();
+ case Type::INT64:
+ case Type::UINT64:
+ return int64();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+TimeUnit::type CommonTimeUnit(TimeUnit::type left, TimeUnit::type right) {
+ if (left == TimeUnit::NANO || right == TimeUnit::NANO) {
+ return TimeUnit::NANO;
+ } else if (left == TimeUnit::MICRO || right == TimeUnit::MICRO) {
+ return TimeUnit::MICRO;
+ } else if (left == TimeUnit::MILLI || right == TimeUnit::MILLI) {
+ return TimeUnit::MILLI;
+ }
+ return TimeUnit::SECOND;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::Invalid(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_date) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_duration && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(CommonTimeUnit(left.unit(), right.unit()));
+ }
+
+ if (options.promote_time && is_time(promoted_type->id()) && is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = CommonTimeUnit(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_timestamp && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::Invalid(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::Invalid("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(CommonTimeUnit(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_decimal) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ promoted_type.swap(other_type);
+ }
+
+ if (is_decimal(promoted_type->id()) && is_integer(other_type->id())) {
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(other_type,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ promoted = true;
+ }
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::Invalid(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ (options.promote_numeric_width &&
+ common_precision > BasicDecimal128::kMaxPrecision)) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+ }
+
+ if (options.promote_integer_sign) {
+ if (is_unsigned_integer(promoted_type->id()) && is_signed_integer(other_type->id())) {
+ promoted = bit_width(other_type->id()) >= bit_width(promoted_type->id());
+ promoted_type = MakeSigned(*promoted_type);
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ promoted = bit_width(promoted_type->id()) >= bit_width(other_type->id());
+ other_type = MakeSigned(*other_type);
+ }
+ }
+
+ if (options.promote_integer_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ promoted = true;
+ }
+
+ if (options.promote_numeric_width) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (is_floating(promoted_type->id()) && is_floating(other_type->id())) {
+ if (max_width >= 64) {
+ return float64();
+ } else if (max_width >= 32) {
+ return float32();
+ }
+ return float16();
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return int64();
+ } else if (max_width >= 32) {
+ return int32();
+ } else if (max_width >= 16) {
+ return int16();
+ }
+ return int8();
+ } else if (is_unsigned_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return uint64();
+ } else if (max_width >= 32) {
+ return uint32();
+ } else if (max_width >= 16) {
+ return uint16();
+ }
+ return uint8();
+ }
+ }
+
+ return promoted ? promoted_type : nullptr;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ if (promoted_type->Equals(*other_type)) return promoted_type;
+
+ bool promoted = false;
+ if (options.promote_nullability) {
+ if (promoted_type->id() == Type::NA) {
+ return other_type;
+ } else if (other_type->id() == Type::NA) {
+ return promoted_type;
+ }
+ } else if (promoted_type->id() == Type::NA || other_type->id() == Type::NA) {
+ return Status::Invalid("Cannot merge type with null unless promote_nullability=true");
+ }
+
+ if (options.promote_dictionary && is_dictionary(promoted_type->id()) &&
+ is_dictionary(other_type->id())) {
+ return MergeDictionaryTypes(promoted_type, other_type, options);
+ }
+
+ ARROW_ASSIGN_OR_RAISE(auto maybe_promoted,
+ MaybeMergeTemporalTypes(promoted_type, other_type, options));
+ if (maybe_promoted) return maybe_promoted;
+
+ ARROW_ASSIGN_OR_RAISE(maybe_promoted,
+ MaybeMergeNumericTypes(promoted_type, other_type, options));
+ if (maybe_promoted) return maybe_promoted;
+
+ if (options.promote_large) {
+ if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(other_type->id())) {
+ promoted_type = binary();
+ promoted = other_type->id() == Type::BINARY;
+ }
+ if (other_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(promoted_type->id())) {
+ other_type = binary();
+ promoted = promoted_type->id() == Type::BINARY;
+ }
+
+ if (promoted_type->id() == Type::FIXED_SIZE_LIST &&
+ is_var_length_list(other_type->id())) {
+ promoted_type =
+ list(checked_cast<const BaseListType&>(*promoted_type).value_field());
+ promoted = other_type->Equals(*promoted_type);
+ }
+ if (other_type->id() == Type::FIXED_SIZE_LIST &&
+ is_var_length_list(promoted_type->id())) {
+ other_type = list(checked_cast<const BaseListType&>(*other_type).value_field());
+ promoted = other_type->Equals(*promoted_type);
+ }
+ }
+
+ if (options.promote_binary) {
+ if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ other_type->id() == Type::FIXED_SIZE_BINARY) {
+ return binary();
+ }
+ if (is_string(promoted_type->id()) && is_binary(other_type->id())) {
+ promoted_type = MakeBinary(*promoted_type);
+ promoted =
+ offset_bit_width(promoted_type->id()) == offset_bit_width(other_type->id());
+ } else if (is_binary(promoted_type->id()) && is_string(other_type->id())) {
+ other_type = MakeBinary(*other_type);
+ promoted =
+ offset_bit_width(promoted_type->id()) == offset_bit_width(other_type->id());
+ }
+ }
+
+ if (options.promote_large) {
+ if ((promoted_type->id() == Type::STRING && other_type->id() == Type::LARGE_STRING) ||
+ (promoted_type->id() == Type::LARGE_STRING && other_type->id() == Type::STRING)) {
+ return large_utf8();
+ } else if ((promoted_type->id() == Type::BINARY &&
+ other_type->id() == Type::LARGE_BINARY) ||
+ (promoted_type->id() == Type::LARGE_BINARY &&
+ other_type->id() == Type::BINARY)) {
+ return large_binary();
+ }
+ if ((promoted_type->id() == Type::LIST && other_type->id() == Type::LARGE_LIST) ||
+ (promoted_type->id() == Type::LARGE_LIST && other_type->id() == Type::LIST)) {
+ promoted_type =
+ large_list(checked_cast<const BaseListType&>(*promoted_type).value_field());
+ promoted = true;
Review Comment:
I took the original code from #12000. I would probably implement this using a post-order visitor pattern to traverse the schema. That would simplify the logic quite a bit.
I've updated the code to merge the values as well
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] pitrou commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "pitrou (via GitHub)" <gi...@apache.org>.
pitrou commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1274894812
##########
cpp/src/arrow/type_test.cc:
##########
@@ -983,6 +1091,242 @@ TEST_F(TestUnifySchemas, MoreSchemas) {
utf8_field->WithNullable(true)}));
}
+TEST_F(TestUnifySchemas, Numeric) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ CheckUnify(uint8(),
+ {int8(), uint16(), int16(), uint32(), int32(), uint64(), int64(), float32(),
+ float64()},
+ options);
+ CheckUnify(int8(), {int16(), int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint16(),
+ {int16(), uint32(), int32(), uint64(), int64(), float32(), float64()},
+ options);
+ CheckUnify(int16(), {int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint32(), {int32(), uint64(), int64(), float32(), float64()}, options);
+ CheckUnify(int32(), {int64(), float32(), float64()}, options);
+ CheckUnify(uint64(), {int64(), float64()}, options);
+ CheckUnify(int64(), {float64()}, options);
+ CheckUnify(float16(), {float32(), float64()}, options);
+ CheckUnify(float32(), {float64()}, options);
+ CheckUnify(uint64(), float32(), float64(), options);
+ CheckUnify(int64(), float32(), float64(), options);
+
+ options.promote_integer_sign = false;
+ CheckUnify(uint8(), {uint16(), uint32(), uint64()}, options);
+ CheckUnify(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(uint8(), {int8(), int16(), int32(), int64()}, options);
+ CheckUnify(uint16(), {uint32(), uint64()}, options);
+ CheckUnify(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(uint16(), {int16(), int32(), int64()}, options);
+ CheckUnify(uint32(), {uint64()}, options);
+ CheckUnify(int32(), {int64()}, options);
+ CheckUnifyFails(uint32(), {int32(), int64()}, options);
+ CheckUnifyFails(uint64(), {int64()}, options);
+
+ options.promote_integer_sign = true;
+ options.promote_integer_float = false;
+ CheckUnifyFails(IntTypes(), FloatingPointTypes(), options);
+
+ options.promote_integer_float = true;
+ options.promote_numeric_width = false;
+ CheckUnifyFails(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(int32(), {int64()}, options);
+}
+
+TEST_F(TestUnifySchemas, Decimal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_decimal_float = true;
+ CheckUnify(decimal128(3, 2), {float32(), float64()}, options);
+ CheckUnify(decimal256(3, 2), {float32(), float64()}, options);
+
+ options.promote_integer_decimal = true;
+ CheckUnify(int32(), decimal128(3, 2), decimal128(3, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(3, -2), options);
+
+ options.promote_decimal = true;
+ CheckUnify(decimal128(3, 2), decimal128(5, 2), decimal128(5, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 3), decimal128(5, 3), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 1), decimal128(6, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, -2), decimal128(9, 2), options);
+ CheckUnify(decimal128(3, -2), decimal128(5, -2), decimal128(5, -2), options);
+
+ // int32() is essentially decimal128(10, 0)
+ CheckUnify(int32(), decimal128(3, 2), decimal128(12, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(10, 0), options);
+
+ CheckUnifyFails(decimal256(1, 0), decimal128(1, 0), options);
+ CheckUnifyFails(int64(), decimal128(38, 37), options);
Review Comment:
No, because the required precision (57 = 37+20) would be higher than what decimal128 allows.
However, perhaps it could upcast to decimal256 if the corresponding option is activated.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] github-actions[bot] commented on pull request #36846: GH-36845: [
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #36846:
URL: https://github.com/apache/arrow/pull/36846#issuecomment-1648013027
:warning: GitHub issue #36845 **has been automatically assigned in GitHub** to PR creator.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1307084587
##########
cpp/src/arrow/table.cc:
##########
@@ -502,9 +515,23 @@ Result<std::shared_ptr<Table>> PromoteTableToSchema(const std::shared_ptr<Table>
continue;
}
+#ifdef ARROW_COMPUTE
+ if (!compute::CanCast(*current_field->type(), *field->type())) {
+ return Status::TypeError("Unable to promote field ", field->name(),
+ ": incompatible types: ", field->type()->ToString(),
+ " vs ", current_field->type()->ToString());
+ }
+ compute::ExecContext ctx(pool);
+ ARROW_ASSIGN_OR_RAISE(auto casted, compute::Cast(table->column(field_index),
+ field->type(), *options, &ctx));
+ columns.push_back(casted.chunked_array());
+#else
return Status::Invalid("Unable to promote field ", field->name(),
": incompatible types: ", field->type()->ToString(), " vs ",
Review Comment:
Hmm, interesting. Looking at the PR, I think you're right!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1307151739
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,67 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
+
+ /// Allow a decimal to be promoted to a float. The float type will
+ /// not itself be promoted (e.g. Decimal128 + Float32 = Float32).
+ bool promote_decimal_to_float = false;
+
+ /// Allow an integer to be promoted to a decimal.
+ ///
+ /// May fail if the decimal has insufficient precision to
+ /// accommodate the integer. (See increase_decimal_precision.)
+ bool promote_integer_to_decimal = false;
+
+ /// Allow an integer of a given bit width to be promoted to a
+ /// float; the result will be a float of an equal or greater bit
+ /// width to both of the inputs.
+ bool promote_integer_to_float = false;
+
+ /// Allow an unsigned integer of a given bit width to be promoted
+ /// to a signed integer of the equal or greater bit width.
+ bool promote_integer_sign = false;
Review Comment:
This docstring is actually incorrect, it requires `promote_numeric_width` to be set to widen type type. I've updated the docstring
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on PR #36846:
URL: https://github.com/apache/arrow/pull/36846#issuecomment-1735513388
I'm not sure what you're referring to here: https://github.com/apache/arrow/pull/36846#discussion_r1336872769
This one is being used here:
```cpp
if (options.promote_decimal && is_decimal(promoted_type->id()) &&
is_decimal(other_type->id())) {
ARROW_ASSIGN_OR_RAISE(promoted_type,
WidenDecimals(promoted_type, other_type, options));
return promoted_type;
}
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] jorisvandenbossche commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "jorisvandenbossche (via GitHub)" <gi...@apache.org>.
jorisvandenbossche commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1336835446
##########
cpp/src/arrow/table.h:
##########
@@ -23,6 +23,7 @@
#include <vector>
#include "arrow/chunked_array.h" // IWYU pragma: keep
+#include "arrow/compute/cast.h"
Review Comment:
About including the compute headers here, @pitrou are you fine with the current state, or do you have another suggestion how to avoid it?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] jorisvandenbossche commented on pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "jorisvandenbossche (via GitHub)" <gi...@apache.org>.
jorisvandenbossche commented on PR #36846:
URL: https://github.com/apache/arrow/pull/36846#issuecomment-1741172891
@Fokko thanks for the updates!
Going throught my previous reviews, summarizing here:
Some follow-up ideas that I don't think need to be addressed here:
- Mismatching timezones: a potential option could be to actually allow promoting timezones, and with the result using UTC (the actual time points will stay the same since we store UTC under the hood, you only loose the information about the specified timezone)
- Promoting bools to numeric?
- Exposing the fine-grained options in python (if we actually want to do this?)
- We have some logic around promoting types in kernels (`DispatchBest`, implemented in `CommonNumeric` for numeric types, added in #9294). We should look into consolidating that logic (the kernels can use the "permissive" promotion).
Then there are a few things that I would prefer to resolve here in this PR:
- Do we need the `pyarrow.FieldMergeOptions` class? At the moment it actually doesn't really do anything, since we don't (yet) allow to tweak individual flags, only "permissive"/"default" (and the class itself actually also only exposes "permissive", not "default", as a static method to create that options object). Maybe we can just remove it for now, we can always add it back later if we want to expose individual options.
I just noticed that the repr is also failing, so if we keep it, we should fix and test that.
- For `concat_tables`, I find it confusing that a user still has to specify `promote=True` when they already specified `field_merge_options="permissive"` (because the latter only makes sense with promote=True). Essentially the `promote=False` can be seen as a "no promotion" field merge option?
I think with this new promotion capability, the historically added `promote` keyword is unfortunately badly chosen. Essentially it means: "unify schemas" (that's also how it is called on the C++ side), and by default it hardly does any promotion (only non-existing fields or null fields to any type). If we keep `promote` keyword, I would expect that `promote=True` would do actual, permissive promotion.
To be clear, this is not caused by this PR, but I would still prefer to get a nicer API. One option is to actually rename promote to `unify_schemas` (which is what it does). We can still keep `promote` as an alias for now for backwards compatibility.
And personally, I am also wondering if we shouldn't make "permissive" the default, when schema unification is enabled (in which case the "default" merge option is badly named ..). But that would actually be a change in behaviour.
- The keyword names: `pa.concat_tables` uses `field_merge_options`, `pa.unify_schemas` uses `options`. Should we try to align those names? I mentioned that I would like `promote_options`, which I think is more descriptive, but on the other hand deviates from the C++ termininology ..
The last two bullet points are more about the final Python API, and doesn't impact the large part of the changes in the PR (the actual C++ changes), so maybe I shouldn't block the PR on those, and I am also fine with discussing those in a follow-up.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1302611446
##########
python/pyarrow/table.pxi:
##########
@@ -5066,6 +5073,16 @@ def concat_tables(tables, c_bool promote=False, MemoryPool memory_pool=None):
for table in tables:
c_tables.push_back(table.sp_table)
+ if field_merge_options is not None:
+ if isinstance(field_merge_options, str):
+ if field_merge_options == "permissive":
+ options.field_merge_options = CField.CMergeOptions.Permissive()
+ elif field_merge_options == "default":
+ options.field_merge_options = CField.CMergeOptions.Defaults()
+ else:
+ options.field_merge_options = cython.cast(
+ FieldMergeOptions, field_merge_options).c_options
Review Comment:
Much better indeed, thanks!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1302657996
##########
cpp/src/arrow/type_test.cc:
##########
@@ -983,6 +1127,242 @@ TEST_F(TestUnifySchemas, MoreSchemas) {
utf8_field->WithNullable(true)}));
}
+TEST_F(TestUnifySchemas, Numeric) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ CheckUnify(uint8(),
+ {int8(), uint16(), int16(), uint32(), int32(), uint64(), int64(), float32(),
+ float64()},
+ options);
+ CheckUnify(int8(), {int16(), int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint16(),
+ {int16(), uint32(), int32(), uint64(), int64(), float32(), float64()},
+ options);
+ CheckUnify(int16(), {int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint32(), {int32(), uint64(), int64(), float32(), float64()}, options);
+ CheckUnify(int32(), {int64(), float32(), float64()}, options);
+ CheckUnify(uint64(), {int64(), float64()}, options);
+ CheckUnify(int64(), {float64()}, options);
+ CheckUnify(float16(), {float32(), float64()}, options);
+ CheckUnify(float32(), {float64()}, options);
+ CheckUnify(uint64(), float32(), float64(), options);
+ CheckUnify(int64(), float32(), float64(), options);
+
+ options.promote_integer_sign = false;
+ CheckUnify(uint8(), {uint16(), uint32(), uint64()}, options);
+ CheckUnify(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFailsInvalid(uint8(), {int8(), int16(), int32(), int64()}, options);
+ CheckUnify(uint16(), {uint32(), uint64()}, options);
+ CheckUnify(int16(), {int32(), int64()}, options);
+ CheckUnifyFailsInvalid(uint16(), {int16(), int32(), int64()}, options);
+ CheckUnify(uint32(), {uint64()}, options);
+ CheckUnify(int32(), {int64()}, options);
+ CheckUnifyFailsInvalid(uint32(), {int32(), int64()}, options);
+ CheckUnifyFailsInvalid(uint64(), {int64()}, options);
+
+ options.promote_integer_sign = true;
+ options.promote_integer_to_float = false;
+ CheckUnifyFailsInvalid(IntTypes(), FloatingPointTypes(), options);
+
+ options.promote_integer_to_float = true;
+ options.promote_numeric_width = false;
+ CheckUnifyFailsInvalid(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFailsInvalid(int16(), {int32(), int64()}, options);
+ CheckUnifyFailsInvalid(int32(), {int64()}, options);
+ CheckUnify(int32(), {float32()}, options);
+ CheckUnify(int64(), {float64()}, options);
+ CheckUnify(int32(), float16(), float32(), options);
+}
+
+TEST_F(TestUnifySchemas, Decimal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_decimal_to_float = true;
+ CheckUnify(decimal128(3, 2), {float32(), float64()}, options);
+ CheckUnify(decimal256(3, 2), {float32(), float64()}, options);
+
+ options.promote_integer_to_decimal = true;
+ CheckUnify(int32(), decimal128(3, 2), decimal128(12, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(10, 0), options);
+
+ options.promote_decimal = true;
+ CheckUnify(decimal128(3, 2), decimal128(5, 2), decimal128(5, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 3), decimal128(5, 3), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 1), decimal128(6, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, -2), decimal128(9, 2), options);
+ CheckUnify(decimal128(3, -2), decimal128(5, -2), decimal128(5, -2), options);
+ CheckUnify(decimal128(38, 10), decimal128(38, 5), decimal256(43, 10), options);
+
+ CheckUnify(decimal256(3, 2), decimal256(5, 2), decimal256(5, 2), options);
+ CheckUnify(decimal256(3, 2), decimal256(5, 3), decimal256(5, 3), options);
+ CheckUnify(decimal256(3, 2), decimal256(5, 1), decimal256(6, 2), options);
+ CheckUnify(decimal256(3, 2), decimal256(5, -2), decimal256(9, 2), options);
+ CheckUnify(decimal256(3, -2), decimal256(5, -2), decimal256(5, -2), options);
+
+ // int32() is essentially decimal128(10, 0)
+ CheckUnify(int32(), decimal128(3, 2), decimal128(12, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(10, 0), options);
+ CheckUnify(int64(), decimal128(38, 37), decimal256(56, 37), options);
+
+ CheckUnifyFailsTypeError(decimal256(1, 0), decimal128(1, 0), options);
+
+ options.promote_numeric_width = true;
+ CheckUnify(decimal128(3, 2), decimal256(5, 2), decimal256(5, 2), options);
+ CheckUnify(int32(), decimal128(38, 37), decimal256(47, 37), options);
+ CheckUnifyFailsInvalid(decimal128(38, 10), decimal256(76, 5), options);
+
+ CheckUnifyFailsInvalid(int64(), decimal256(76, 75), options);
+}
+
+TEST_F(TestUnifySchemas, Temporal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_temporal_unit = true;
+ CheckUnify(date32(), {date64()}, options);
+
+ CheckUnify(time32(TimeUnit::SECOND),
+ {time32(TimeUnit::MILLI), time64(TimeUnit::MICRO), time64(TimeUnit::NANO)},
+ options);
+ CheckUnify(time32(TimeUnit::MILLI), {time64(TimeUnit::MICRO), time64(TimeUnit::NANO)},
+ options);
+ CheckUnify(time64(TimeUnit::MICRO), {time64(TimeUnit::NANO)}, options);
+
+ CheckUnify(
+ duration(TimeUnit::SECOND),
+ {duration(TimeUnit::MILLI), duration(TimeUnit::MICRO), duration(TimeUnit::NANO)},
+ options);
+ CheckUnify(duration(TimeUnit::MILLI),
+ {duration(TimeUnit::MICRO), duration(TimeUnit::NANO)}, options);
+ CheckUnify(duration(TimeUnit::MICRO), {duration(TimeUnit::NANO)}, options);
+
+ CheckUnify(
+ timestamp(TimeUnit::SECOND),
+ {timestamp(TimeUnit::MILLI), timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO)},
+ options);
+ CheckUnify(timestamp(TimeUnit::MILLI),
+ {timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO)}, options);
+ CheckUnify(timestamp(TimeUnit::MICRO), {timestamp(TimeUnit::NANO)}, options);
+
+ CheckUnifyFailsTypeError(timestamp(TimeUnit::SECOND),
+ timestamp(TimeUnit::SECOND, "UTC"), options);
+ CheckUnifyFailsTypeError(timestamp(TimeUnit::SECOND, "America/New_York"),
+ timestamp(TimeUnit::SECOND, "UTC"), options);
+
+ options.promote_temporal_unit = false;
+ CheckUnifyFailsInvalid(timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO), options);
Review Comment:
Even with the `promote_temporal_unit = False`?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1295669757
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,63 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
+
+ /// Allow a decimal to be promoted to a float. The float type will
+ /// not itself be promoted (e.g. Decimal128 + Float32 = Float32).
+ bool promote_decimal_to_float = false;
+
+ /// Allow an integer to be promoted to a decimal.
+ ///
+ /// May fail if the decimal has insufficient precision to
+ /// accommodate the integer. (See increase_decimal_precision.)
+ bool promote_integer_to_decimal = false;
+
+ /// Allow an integer of a given bit width to be promoted to a
+ /// float; the result will be a float of an equal or greater bit
+ /// width to both of the inputs.
+ bool promote_integer_to_float = false;
+
+ /// Allow an unsigned integer of a given bit width to be promoted
+ /// to a signed integer of the equal or greater bit width.
+ bool promote_integer_sign = false;
+
+ /// Allow an integer, float, or decimal of a given bit width to be
+ /// promoted to an equivalent type of a greater bit width.
+ bool promote_numeric_width = false;
+
+ /// Allow strings to be promoted to binary types.
+ bool promote_binary = false;
Review Comment:
I've extended the docstring
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1295669757
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,63 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
+
+ /// Allow a decimal to be promoted to a float. The float type will
+ /// not itself be promoted (e.g. Decimal128 + Float32 = Float32).
+ bool promote_decimal_to_float = false;
+
+ /// Allow an integer to be promoted to a decimal.
+ ///
+ /// May fail if the decimal has insufficient precision to
+ /// accommodate the integer. (See increase_decimal_precision.)
+ bool promote_integer_to_decimal = false;
+
+ /// Allow an integer of a given bit width to be promoted to a
+ /// float; the result will be a float of an equal or greater bit
+ /// width to both of the inputs.
+ bool promote_integer_to_float = false;
+
+ /// Allow an unsigned integer of a given bit width to be promoted
+ /// to a signed integer of the equal or greater bit width.
+ bool promote_integer_sign = false;
+
+ /// Allow an integer, float, or decimal of a given bit width to be
+ /// promoted to an equivalent type of a greater bit width.
+ bool promote_numeric_width = false;
+
+ /// Allow strings to be promoted to binary types.
+ bool promote_binary = false;
Review Comment:
I've extended the docstring
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1295843050
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
Review Comment:
You can't have strings as keys in Arrow?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables` [arrow]
Posted by "jorisvandenbossche (via GitHub)" <gi...@apache.org>.
jorisvandenbossche merged PR #36846:
URL: https://github.com/apache/arrow/pull/36846
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] jorisvandenbossche commented on pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "jorisvandenbossche (via GitHub)" <gi...@apache.org>.
jorisvandenbossche commented on PR #36846:
URL: https://github.com/apache/arrow/pull/36846#issuecomment-1689465208
> I'm not interested in these special cases at least, it is just in here because the original author did this, but I'm also fine with only including the obvious and getting rid of all the flags.
Sorry for the slow reply here (holidays/conferences), but one thing to add: while I don't have a strong opinion on whether all fine-grained options are useful, I do think a promotion like int -> float can certainly be useful to allow, even if that's not a typical schema evolution allowed by Iceberg. At least in the pandas world, it's quite common to end up with a mixture (eg because of missing values turning int to float), and then being able to read multiple parquet files with such a difference in schema can help.
Also in general, `pd.concat` of DataFrames follows the numpy promotion rules, and there int/float combinations typically promote to float.
> I think having the same safe flag similar to `Table.cast` on the `pa.concat_tables` would do the trick as well.
I _think_ promotion and safe/unsafe casting can in theory be two distinct questions. For example, you might want to allow promoting int to float, but only it preserves the value (safe casting). Or promote "s" timestamps to "ns", but only it's not out of bounds.
(now, I haven't looked into detail at the PR yet, so not sure that makes sense. But I was planning to take a closer look later today)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on PR #36846:
URL: https://github.com/apache/arrow/pull/36846#issuecomment-1689372348
Alright, doing casts during reads has its [own issues](https://github.com/apache/arrow/issues/36845) (this might be faster, because it reads it right into the correct format?). Also, other folks are [waiting](https://github.com/apache/arrow/issues/37068) on this, so let's push this through. I now got my c++ environment running locally for faster development 👍🏻
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1307100965
##########
cpp/src/arrow/table_test.cc:
##########
@@ -520,6 +523,48 @@ TEST_F(ConcatenateTablesWithPromotionTest, Simple) {
AssertTablesEqualUnorderedFields(*expected, *result);
}
+TEST_F(ConcatenateTablesWithPromotionTest, Unify) {
+ auto t1 = TableFromJSON(schema({field("f0", int32())}), {"[[0], [1]]"});
+ auto t2 = TableFromJSON(schema({field("f0", int64())}), {"[[2], [3]]"});
+ auto t3 = TableFromJSON(schema({field("f0", null())}), {"[[null], [null]]"});
+
+ auto expected_int64 =
+ TableFromJSON(schema({field("f0", int64())}), {"[[0], [1], [2], [3]]"});
+ auto expected_null =
+ TableFromJSON(schema({field("f0", int32())}), {"[[0], [1], [null], [null]]"});
+
+ ConcatenateTablesOptions options;
+ EXPECT_RAISES_WITH_MESSAGE_THAT(Invalid,
+ ::testing::HasSubstr("Schema at index 1 was different"),
+ ConcatenateTables({t1, t2}, options));
+ EXPECT_RAISES_WITH_MESSAGE_THAT(Invalid,
+ ::testing::HasSubstr("Schema at index 1 was different"),
+ ConcatenateTables({t1, t3}, options));
+
+ options.unify_schemas = true;
+ EXPECT_RAISES_WITH_MESSAGE_THAT(Invalid,
+ ::testing::HasSubstr("Field f0 has incompatible types"),
+ ConcatenateTables({t1, t2}, options));
+ ASSERT_OK_AND_ASSIGN(auto actual, ConcatenateTables({t1, t3}, options));
+ AssertTablesEqual(*expected_null, *actual, /*same_chunk_layout=*/false);
+
+ options.field_merge_options.promote_numeric_width = true;
+ ASSERT_OK_AND_ASSIGN(actual, ConcatenateTables({t1, t2}, options));
+ AssertTablesEqual(*expected_int64, *actual, /*same_chunk_layout=*/false);
+}
+
+// TEST_F(ConcatenateTablesWithPromotionTest, Overflow) {
Review Comment:
I've uncommented it. I think it is a good test to have
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1307155011
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,67 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
+
+ /// Allow a decimal to be promoted to a float. The float type will
+ /// not itself be promoted (e.g. Decimal128 + Float32 = Float32).
+ bool promote_decimal_to_float = false;
+
+ /// Allow an integer to be promoted to a decimal.
+ ///
+ /// May fail if the decimal has insufficient precision to
+ /// accommodate the integer. (See increase_decimal_precision.)
+ bool promote_integer_to_decimal = false;
+
+ /// Allow an integer of a given bit width to be promoted to a
+ /// float; the result will be a float of an equal or greater bit
+ /// width to both of the inputs.
+ bool promote_integer_to_float = false;
+
+ /// Allow an unsigned integer of a given bit width to be promoted
+ /// to a signed integer of the equal or greater bit width.
+ bool promote_integer_sign = false;
+
+ /// Allow an integer, float, or decimal of a given bit width to be
+ /// promoted to an equivalent type of a greater bit width.
+ bool promote_numeric_width = false;
+
+ /// Allow strings to be promoted to binary types. Promotion of fixed size
+ /// binary types to variable sized formats, and binary to large binary,
+ /// and string to large string.
+ bool promote_binary = false;
+
+ /// Second to millisecond, Time32 to Time64, Time32(SECOND) to Time32(MILLI), etc
+ bool promote_temporal_unit = false;
+
+ /// Allow promotion from a list to a large-list
+ bool promote_list = false;
Review Comment:
I agree, added!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1307151739
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,67 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
+
+ /// Allow a decimal to be promoted to a float. The float type will
+ /// not itself be promoted (e.g. Decimal128 + Float32 = Float32).
+ bool promote_decimal_to_float = false;
+
+ /// Allow an integer to be promoted to a decimal.
+ ///
+ /// May fail if the decimal has insufficient precision to
+ /// accommodate the integer. (See increase_decimal_precision.)
+ bool promote_integer_to_decimal = false;
+
+ /// Allow an integer of a given bit width to be promoted to a
+ /// float; the result will be a float of an equal or greater bit
+ /// width to both of the inputs.
+ bool promote_integer_to_float = false;
+
+ /// Allow an unsigned integer of a given bit width to be promoted
+ /// to a signed integer of the equal or greater bit width.
+ bool promote_integer_sign = false;
Review Comment:
This docstring is actually incorrect, it requires `promote_numeric_width` to be set to widen type type.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1307176960
##########
cpp/src/arrow/type.cc:
##########
@@ -327,6 +315,449 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_list = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_decimal=" << (promote_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_list=" << (promote_list ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_dictionary_ordered="
+ << (promote_dictionary_ordered ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::TypeError(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_temporal_unit) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+
+ if (promoted_type->id() == Type::DURATION && other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(std::max(left.unit(), right.unit()));
+ }
+
+ if (is_time(promoted_type->id()) && is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = std::max(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+ }
+
+ if (promoted_type->id() == Type::TIMESTAMP && other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::TypeError(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::TypeError("Cannot merge timestamps with differing timezones");
+ }
+ if (options.promote_temporal_unit) {
+ return timestamp(std::max(left.unit(), right.unit()), left.timezone());
+ }
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-numeric types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_to_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_to_decimal &&
+ ((is_decimal(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_decimal(other_type->id()) && is_integer(promoted_type->id())))) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ // Other type is always the int
+ promoted_type.swap(other_type);
+ }
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(const auto promoted_decimal,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ ARROW_ASSIGN_OR_RAISE(promoted_type,
+ WidenDecimals(promoted_type, promoted_decimal, options));
+ return promoted_type;
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ ARROW_ASSIGN_OR_RAISE(promoted_type,
+ WidenDecimals(promoted_type, other_type, options));
+ return promoted_type;
+ }
+
+ if (options.promote_integer_sign && ((is_unsigned_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) ||
+ (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())))) {
+ if (!options.promote_numeric_width &&
+ bit_width(promoted_type->id()) != bit_width(other_type->id())) {
+ return Status::TypeError(
+ "Cannot widen (un)signed integers without promote_numeric_width=true");
+ }
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
Review Comment:
You're right:
```
>>> import pyarrow as pa
>>> pa.array([4294967295], type=pa.uint32())
<pyarrow.lib.UInt32Array object at 0x1542b2f20>
[
4294967295
]
>>> pa.array([4294967295], type=pa.int32())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pyarrow/array.pxi", line 320, in pyarrow.lib.array
File "pyarrow/array.pxi", line 39, in pyarrow.lib._sequence_to_array
File "pyarrow/error.pxi", line 144, in pyarrow.lib.pyarrow_internal_check_status
File "pyarrow/error.pxi", line 100, in pyarrow.lib.check_status
pyarrow.lib.ArrowInvalid: Value 4294967295 too large to fit in C integer type
```
But then again we should also check for negatives:
```
>>> pa.array([-1], type=pa.int32())
<pyarrow.lib.Int32Array object at 0x1542b3220>
[
-1
]
>>> pa.array([-1], type=pa.uint32())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pyarrow/array.pxi", line 320, in pyarrow.lib.array
File "pyarrow/array.pxi", line 39, in pyarrow.lib._sequence_to_array
File "pyarrow/error.pxi", line 144, in pyarrow.lib.pyarrow_internal_check_status
OverflowError: can't convert negative value to unsigned int
```
Otherwise, it will raise an `OverflowError` on runtime
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables` [arrow]
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1348956806
##########
python/pyarrow/table.pxi:
##########
@@ -5078,11 +5082,24 @@ def concat_tables(tables, c_bool promote=False, MemoryPool memory_pool=None):
CConcatenateTablesOptions options = (
CConcatenateTablesOptions.Defaults())
+ if "promote" in kwargs:
+ warnings.warn(
+ "promote has been superseded by mode='default'.", FutureWarning)
+ if kwargs['promote'] is True:
+ promote_options = "permissive"
Review Comment:
I thought we agreed on promoting when `promote=True`, but this also works for me.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1274678188
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +298,431 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_float = true;
+ options.promote_integer_decimal = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_date = true;
+ options.promote_duration = true;
+ options.promote_time = true;
+ options.promote_timestamp = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ options.promote_large = true;
+ options.promote_nested = true;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_float=" << (promote_integer_float ? "true" : "false");
+ ss << ", promote_integer_decimal=" << (promote_integer_decimal ? "true" : "false");
+ ss << ", promote_decimal_float=" << (promote_decimal_float ? "true" : "false");
+ ss << ", promote_date=" << (promote_date ? "true" : "false");
+ ss << ", promote_time=" << (promote_time ? "true" : "false");
+ ss << ", promote_duration=" << (promote_duration ? "true" : "false");
+ ss << ", promote_timestamp=" << (promote_timestamp ? "true" : "false");
+ ss << ", promote_nested=" << (promote_nested ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_large=" << (promote_large ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeSigned(const DataType& type) {
+ switch (type.id()) {
+ case Type::INT8:
+ case Type::UINT8:
+ return int8();
+ case Type::INT16:
+ case Type::UINT16:
+ return int16();
+ case Type::INT32:
+ case Type::UINT32:
+ return int32();
+ case Type::INT64:
+ case Type::UINT64:
+ return int64();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+TimeUnit::type CommonTimeUnit(TimeUnit::type left, TimeUnit::type right) {
+ if (left == TimeUnit::NANO || right == TimeUnit::NANO) {
+ return TimeUnit::NANO;
+ } else if (left == TimeUnit::MICRO || right == TimeUnit::MICRO) {
+ return TimeUnit::MICRO;
+ } else if (left == TimeUnit::MILLI || right == TimeUnit::MILLI) {
+ return TimeUnit::MILLI;
+ }
+ return TimeUnit::SECOND;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::Invalid(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_date) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_duration && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(CommonTimeUnit(left.unit(), right.unit()));
+ }
+
+ if (options.promote_time && is_time(promoted_type->id()) && is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = CommonTimeUnit(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_timestamp && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::Invalid(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::Invalid("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(CommonTimeUnit(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_decimal) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ promoted_type.swap(other_type);
+ }
+
+ if (is_decimal(promoted_type->id()) && is_integer(other_type->id())) {
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(other_type,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ promoted = true;
+ }
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::Invalid(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ (options.promote_numeric_width &&
+ common_precision > BasicDecimal128::kMaxPrecision)) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+ }
+
+ if (options.promote_integer_sign) {
+ if (is_unsigned_integer(promoted_type->id()) && is_signed_integer(other_type->id())) {
+ promoted = bit_width(other_type->id()) >= bit_width(promoted_type->id());
+ promoted_type = MakeSigned(*promoted_type);
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ promoted = bit_width(promoted_type->id()) >= bit_width(other_type->id());
+ other_type = MakeSigned(*other_type);
+ }
+ }
+
+ if (options.promote_integer_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ promoted = true;
+ }
+
+ if (options.promote_numeric_width) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (is_floating(promoted_type->id()) && is_floating(other_type->id())) {
+ if (max_width >= 64) {
+ return float64();
+ } else if (max_width >= 32) {
+ return float32();
+ }
+ return float16();
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return int64();
+ } else if (max_width >= 32) {
+ return int32();
+ } else if (max_width >= 16) {
+ return int16();
+ }
+ return int8();
+ } else if (is_unsigned_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return uint64();
+ } else if (max_width >= 32) {
+ return uint32();
+ } else if (max_width >= 16) {
+ return uint16();
+ }
+ return uint8();
+ }
+ }
+
+ return promoted ? promoted_type : nullptr;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ if (promoted_type->Equals(*other_type)) return promoted_type;
+
+ bool promoted = false;
+ if (options.promote_nullability) {
+ if (promoted_type->id() == Type::NA) {
+ return other_type;
+ } else if (other_type->id() == Type::NA) {
+ return promoted_type;
+ }
+ } else if (promoted_type->id() == Type::NA || other_type->id() == Type::NA) {
+ return Status::Invalid("Cannot merge type with null unless promote_nullability=true");
+ }
+
+ if (options.promote_dictionary && is_dictionary(promoted_type->id()) &&
+ is_dictionary(other_type->id())) {
+ return MergeDictionaryTypes(promoted_type, other_type, options);
+ }
+
+ ARROW_ASSIGN_OR_RAISE(auto maybe_promoted,
+ MaybeMergeTemporalTypes(promoted_type, other_type, options));
+ if (maybe_promoted) return maybe_promoted;
+
+ ARROW_ASSIGN_OR_RAISE(maybe_promoted,
+ MaybeMergeNumericTypes(promoted_type, other_type, options));
+ if (maybe_promoted) return maybe_promoted;
+
+ if (options.promote_large) {
+ if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(other_type->id())) {
+ promoted_type = binary();
+ promoted = other_type->id() == Type::BINARY;
+ }
+ if (other_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(promoted_type->id())) {
+ other_type = binary();
+ promoted = promoted_type->id() == Type::BINARY;
+ }
+
+ if (promoted_type->id() == Type::FIXED_SIZE_LIST &&
Review Comment:
This is for converting a fixed list into a variable-length list.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1295547209
##########
python/pyarrow/tests/test_table.py:
##########
@@ -1373,6 +1373,15 @@ def test_concat_tables_with_promotion():
pa.array([None, None, 1.0, 2.0], type=pa.float32()),
], ["int64_field", "float_field"]))
+ t3 = pa.Table.from_arrays(
+ [pa.array([1, 2], type=pa.int32())], ["int64_field"])
+ result = pa.concat_tables(
+ [t1, t3], promote=True,
+ field_merge_options=pa.FieldMergeOptions.permissive())
Review Comment:
Yes, added a test
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on PR #36846:
URL: https://github.com/apache/arrow/pull/36846#issuecomment-1680587527
@pitrou Thanks for the reviews, I appreciate it. I wonder if we're not making this too big. Casting `int -> float`, `int -> decimal`, etc doesn't make much sense to me, and I don't think people expect much more than widening of the same type, such as `string -> large_string`, instead of also allowing `string -> binary`. I'm not interested in these special cases at least, it is just in here because the original author did this, but I'm also fine with only including the obvious and getting rid of all the flags. This also makes it much simpler, WDYT?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1295957962
##########
cpp/src/arrow/table_test.cc:
##########
@@ -520,6 +522,36 @@ TEST_F(ConcatenateTablesWithPromotionTest, Simple) {
AssertTablesEqualUnorderedFields(*expected, *result);
}
+TEST_F(ConcatenateTablesWithPromotionTest, Unify) {
+ auto t1 = TableFromJSON(schema({field("f0", int32())}), {"[[0], [1]]"});
+ auto t2 = TableFromJSON(schema({field("f0", int64())}), {"[[2], [3]]"});
+ auto t3 = TableFromJSON(schema({field("f0", null())}), {"[[null], [null]]"});
+
+ auto expected_int64 =
+ TableFromJSON(schema({field("f0", int64())}), {"[[0], [1], [2], [3]]"});
+ auto expected_null =
+ TableFromJSON(schema({field("f0", int32())}), {"[[0], [1], [null], [null]]"});
+
+ ConcatenateTablesOptions options;
+ EXPECT_RAISES_WITH_MESSAGE_THAT(Invalid,
+ ::testing::HasSubstr("Schema at index 1 was different"),
+ ConcatenateTables({t1, t2}, options));
+ EXPECT_RAISES_WITH_MESSAGE_THAT(Invalid,
+ ::testing::HasSubstr("Schema at index 1 was different"),
+ ConcatenateTables({t1, t3}, options));
+
+ options.unify_schemas = true;
+ EXPECT_RAISES_WITH_MESSAGE_THAT(Invalid,
+ ::testing::HasSubstr("Field f0 has incompatible types"),
+ ConcatenateTables({t1, t2}, options));
+ ASSERT_OK_AND_ASSIGN(auto actual, ConcatenateTables({t1, t3}, options));
+ AssertTablesEqual(*expected_null, *actual, /*same_chunk_layout=*/false);
+
+ options.field_merge_options.promote_numeric_width = true;
+ ASSERT_OK_AND_ASSIGN(actual, ConcatenateTables({t1, t2}, options));
+ AssertTablesEqual(*expected_int64, *actual, /*same_chunk_layout=*/false);
+}
Review Comment:
I've added a test for combining a `decimal(76, 75)` and a `int64`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1295957962
##########
cpp/src/arrow/table_test.cc:
##########
@@ -520,6 +522,36 @@ TEST_F(ConcatenateTablesWithPromotionTest, Simple) {
AssertTablesEqualUnorderedFields(*expected, *result);
}
+TEST_F(ConcatenateTablesWithPromotionTest, Unify) {
+ auto t1 = TableFromJSON(schema({field("f0", int32())}), {"[[0], [1]]"});
+ auto t2 = TableFromJSON(schema({field("f0", int64())}), {"[[2], [3]]"});
+ auto t3 = TableFromJSON(schema({field("f0", null())}), {"[[null], [null]]"});
+
+ auto expected_int64 =
+ TableFromJSON(schema({field("f0", int64())}), {"[[0], [1], [2], [3]]"});
+ auto expected_null =
+ TableFromJSON(schema({field("f0", int32())}), {"[[0], [1], [null], [null]]"});
+
+ ConcatenateTablesOptions options;
+ EXPECT_RAISES_WITH_MESSAGE_THAT(Invalid,
+ ::testing::HasSubstr("Schema at index 1 was different"),
+ ConcatenateTables({t1, t2}, options));
+ EXPECT_RAISES_WITH_MESSAGE_THAT(Invalid,
+ ::testing::HasSubstr("Schema at index 1 was different"),
+ ConcatenateTables({t1, t3}, options));
+
+ options.unify_schemas = true;
+ EXPECT_RAISES_WITH_MESSAGE_THAT(Invalid,
+ ::testing::HasSubstr("Field f0 has incompatible types"),
+ ConcatenateTables({t1, t2}, options));
+ ASSERT_OK_AND_ASSIGN(auto actual, ConcatenateTables({t1, t3}, options));
+ AssertTablesEqual(*expected_null, *actual, /*same_chunk_layout=*/false);
+
+ options.field_merge_options.promote_numeric_width = true;
+ ASSERT_OK_AND_ASSIGN(actual, ConcatenateTables({t1, t2}, options));
+ AssertTablesEqual(*expected_int64, *actual, /*same_chunk_layout=*/false);
+}
Review Comment:
I wasn't sure what kind of tests you were looking for.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] pitrou commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "pitrou (via GitHub)" <gi...@apache.org>.
pitrou commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1296054101
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
Review Comment:
Dictionaries in Arrow are like categoricals in Pandas. They are mostly for more efficient encoding of columns with many repetitions.
If you want flexible key-value mappings, a Map type should be used instead.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables` [arrow]
Posted by "jorisvandenbossche (via GitHub)" <gi...@apache.org>.
jorisvandenbossche commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1350039458
##########
python/pyarrow/table.pxi:
##########
@@ -5078,11 +5082,24 @@ def concat_tables(tables, c_bool promote=False, MemoryPool memory_pool=None):
CConcatenateTablesOptions options = (
CConcatenateTablesOptions.Defaults())
+ if "promote" in kwargs:
+ warnings.warn(
+ "promote has been superseded by mode='default'.", FutureWarning)
+ if kwargs['promote'] is True:
+ promote_options = "permissive"
Review Comment:
Yeah, I mentioned that I would find a `promote=True` a better default, but now that we deprecated it in favor of `promote_options`, we don't need to change the current behaviour, as it will be removed anyway. And users can now replace it with `promote_options="permissive"` if they prefer that
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables` [arrow]
Posted by "jorisvandenbossche (via GitHub)" <gi...@apache.org>.
jorisvandenbossche commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1350039458
##########
python/pyarrow/table.pxi:
##########
@@ -5078,11 +5082,24 @@ def concat_tables(tables, c_bool promote=False, MemoryPool memory_pool=None):
CConcatenateTablesOptions options = (
CConcatenateTablesOptions.Defaults())
+ if "promote" in kwargs:
+ warnings.warn(
+ "promote has been superseded by mode='default'.", FutureWarning)
+ if kwargs['promote'] is True:
+ promote_options = "permissive"
Review Comment:
Yeah, I mentioned that I would find a `promote=True` a better default, but now that we deprecated it in favor of `promote_options`, we don't need to change the current behaviour, as it will be removed anyway
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1295538126
##########
cpp/src/arrow/table.cc:
##########
@@ -502,9 +504,16 @@ Result<std::shared_ptr<Table>> PromoteTableToSchema(const std::shared_ptr<Table>
continue;
}
- return Status::Invalid("Unable to promote field ", field->name(),
- ": incompatible types: ", field->type()->ToString(), " vs ",
- current_field->type()->ToString());
+ if (!compute::CanCast(*current_field->type(), *field->type())) {
+ return Status::Invalid("Unable to promote field ", field->name(),
Review Comment:
I went a bit back and forth here, but it looks like this one slipped through the cracks. I'm okay with changing the above test, but that will change the previous behavior. (but I think we're okay here)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1295568424
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,63 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
+
+ /// Allow a decimal to be promoted to a float. The float type will
+ /// not itself be promoted (e.g. Decimal128 + Float32 = Float32).
+ bool promote_decimal_to_float = false;
+
+ /// Allow an integer to be promoted to a decimal.
+ ///
+ /// May fail if the decimal has insufficient precision to
+ /// accommodate the integer. (See increase_decimal_precision.)
+ bool promote_integer_to_decimal = false;
+
+ /// Allow an integer of a given bit width to be promoted to a
+ /// float; the result will be a float of an equal or greater bit
+ /// width to both of the inputs.
+ bool promote_integer_to_float = false;
+
+ /// Allow an unsigned integer of a given bit width to be promoted
+ /// to a signed integer of the equal or greater bit width.
+ bool promote_integer_sign = false;
+
+ /// Allow an integer, float, or decimal of a given bit width to be
+ /// promoted to an equivalent type of a greater bit width.
+ bool promote_numeric_width = false;
+
+ /// Allow strings to be promoted to binary types.
+ bool promote_binary = false;
Review Comment:
I've updated the docstring
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] pitrou commented on pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "pitrou (via GitHub)" <gi...@apache.org>.
pitrou commented on PR #36846:
URL: https://github.com/apache/arrow/pull/36846#issuecomment-1680794852
> I'm not interested in these special cases at least, it is just in here because the original author did this, but I'm also fine with only including the obvious and getting rid of all the flags.
Well, we shouldn't get rid of existing functionality. So any cast that is already supported should keep being supported (unless it's a glaring mistake of course!).
As for getting rid of all the flags, I don't know if the options need to be as fine-grained as you made them, I thought you had a use for that :-) That said, it's nice to make things configurable, and it seems you did most of the work anyway?
@westonpace What do you think?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] lidavidm commented on pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "lidavidm (via GitHub)" <gi...@apache.org>.
lidavidm commented on PR #36846:
URL: https://github.com/apache/arrow/pull/36846#issuecomment-1681311609
The underlying function in C++ is used in both contexts, and was my original motivation.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1295571483
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,63 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
+
+ /// Allow a decimal to be promoted to a float. The float type will
+ /// not itself be promoted (e.g. Decimal128 + Float32 = Float32).
+ bool promote_decimal_to_float = false;
+
+ /// Allow an integer to be promoted to a decimal.
+ ///
+ /// May fail if the decimal has insufficient precision to
+ /// accommodate the integer. (See increase_decimal_precision.)
+ bool promote_integer_to_decimal = false;
+
+ /// Allow an integer of a given bit width to be promoted to a
+ /// float; the result will be a float of an equal or greater bit
+ /// width to both of the inputs.
+ bool promote_integer_to_float = false;
+
+ /// Allow an unsigned integer of a given bit width to be promoted
+ /// to a signed integer of the equal or greater bit width.
+ bool promote_integer_sign = false;
+
+ /// Allow an integer, float, or decimal of a given bit width to be
+ /// promoted to an equivalent type of a greater bit width.
+ bool promote_numeric_width = false;
+
+ /// Allow strings to be promoted to binary types.
+ bool promote_binary = false;
+
+ /// Second to millisecond, Time32 to Time64, Time32(SECOND) to Time32(MILLI), etc
+ bool promote_temporal_unit = false;
+
+ /// Promote dictionary index types to a common type, and unify the
+ /// value types.
+ bool promote_dictionary = false;
+
+ /// Allow merging ordered and non-ordered dictionaries, else
+ /// error. The result will be ordered if and only if both inputs
Review Comment:
I agree. Explicit > implicit
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,63 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
+
+ /// Allow a decimal to be promoted to a float. The float type will
+ /// not itself be promoted (e.g. Decimal128 + Float32 = Float32).
+ bool promote_decimal_to_float = false;
+
+ /// Allow an integer to be promoted to a decimal.
+ ///
+ /// May fail if the decimal has insufficient precision to
+ /// accommodate the integer. (See increase_decimal_precision.)
+ bool promote_integer_to_decimal = false;
+
+ /// Allow an integer of a given bit width to be promoted to a
+ /// float; the result will be a float of an equal or greater bit
+ /// width to both of the inputs.
+ bool promote_integer_to_float = false;
+
+ /// Allow an unsigned integer of a given bit width to be promoted
+ /// to a signed integer of the equal or greater bit width.
+ bool promote_integer_sign = false;
+
+ /// Allow an integer, float, or decimal of a given bit width to be
+ /// promoted to an equivalent type of a greater bit width.
+ bool promote_numeric_width = false;
+
+ /// Allow strings to be promoted to binary types.
+ bool promote_binary = false;
+
+ /// Second to millisecond, Time32 to Time64, Time32(SECOND) to Time32(MILLI), etc
+ bool promote_temporal_unit = false;
+
+ /// Promote dictionary index types to a common type, and unify the
+ /// value types.
+ bool promote_dictionary = false;
+
+ /// Allow merging ordered and non-ordered dictionaries, else
+ /// error. The result will be ordered if and only if both inputs
Review Comment:
I agree. Explicit > implicit
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] jorisvandenbossche commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "jorisvandenbossche (via GitHub)" <gi...@apache.org>.
jorisvandenbossche commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1336834165
##########
cpp/src/arrow/table.h:
##########
@@ -333,4 +342,29 @@ Result<std::shared_ptr<Table>> PromoteTableToSchema(
const std::shared_ptr<Table>& table, const std::shared_ptr<Schema>& schema,
MemoryPool* pool = default_memory_pool());
+/// \brief Promotes a table to conform to the given schema.
+///
+/// If a field in the schema does not have a corresponding column in
+/// the table, a column of nulls will be added to the resulting table.
+/// If the corresponding column is of type Null, it will be promoted
+/// to the type specified by schema, with null values filled. If Arrow
+/// was built with ARROW_COMPUTE, then the column will be casted to
Review Comment:
same here
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] pitrou commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "pitrou (via GitHub)" <gi...@apache.org>.
pitrou commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1336837386
##########
cpp/src/arrow/table.h:
##########
@@ -23,6 +23,7 @@
#include <vector>
#include "arrow/chunked_array.h" // IWYU pragma: keep
+#include "arrow/compute/cast.h"
Review Comment:
Still no fine, and the suggestion I made in https://github.com/apache/arrow/pull/36846/files/1c5643c4a855ca7a29fdbc4e3b83acd4e3d2af96#r1290117358 still holds.
##########
cpp/src/arrow/table.h:
##########
@@ -23,6 +23,7 @@
#include <vector>
#include "arrow/chunked_array.h" // IWYU pragma: keep
+#include "arrow/compute/cast.h"
Review Comment:
Still not fine, and the suggestion I made in https://github.com/apache/arrow/pull/36846/files/1c5643c4a855ca7a29fdbc4e3b83acd4e3d2af96#r1290117358 still holds.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] jorisvandenbossche commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "jorisvandenbossche (via GitHub)" <gi...@apache.org>.
jorisvandenbossche commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1336807999
##########
python/pyarrow/types.pxi:
##########
@@ -3173,6 +3215,9 @@ def unify_schemas(schemas):
----------
schemas : list of Schema
Schemas to merge into a single one.
+ options : FieldMergeOptions or string, optional
Review Comment:
Yes, but for the cast example, it are the CastOptions passed to the cast kernel. While here we have options for promoting types that is not tied to a specific function (i.e. it's used both in unify_schema, concat_tables, and potentially others)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1322471331
##########
c_glib/test/dataset/test-file-system-dataset-factory.rb:
##########
@@ -109,9 +109,9 @@ def test_validate_fragments
point: Arrow::Int16DataType.new)
options.validate_fragments = true
message = "[file-system-dataset-factory][finish]: " +
- "Invalid: Unable to merge: " +
+ "Type Error: Unable to merge: " +
Review Comment:
Thank you @kou I'm not very much into the ruby ecosystem or its casing :)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1274894006
##########
cpp/src/arrow/type_traits.h:
##########
@@ -998,6 +998,21 @@ constexpr bool is_run_end_type(Type::type type_id) {
return false;
}
+/// \brief Check for a time type
+///
+/// \param[in] type_id the type-id to check
+/// \return whether type-id is a primitive type one
+constexpr bool is_time(Type::type type_id) {
Review Comment:
1. Yes
2. Yes
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on PR #36846:
URL: https://github.com/apache/arrow/pull/36846#issuecomment-1690040274
@jorisvandenbossche Thanks for letting me know. I've pushed those changes. I'm working on the c++ tests to get them all happy and green
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] jorisvandenbossche commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "jorisvandenbossche (via GitHub)" <gi...@apache.org>.
jorisvandenbossche commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1303038815
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,67 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
Review Comment:
Ah, I see in the code that this can be done with `promote_numeric_width`. Maybe mention that here in the doc comment as well? (I didn't directly think about that)
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,67 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
+
+ /// Allow a decimal to be promoted to a float. The float type will
+ /// not itself be promoted (e.g. Decimal128 + Float32 = Float32).
+ bool promote_decimal_to_float = false;
+
+ /// Allow an integer to be promoted to a decimal.
+ ///
+ /// May fail if the decimal has insufficient precision to
+ /// accommodate the integer. (See increase_decimal_precision.)
+ bool promote_integer_to_decimal = false;
+
+ /// Allow an integer of a given bit width to be promoted to a
+ /// float; the result will be a float of an equal or greater bit
+ /// width to both of the inputs.
+ bool promote_integer_to_float = false;
+
+ /// Allow an unsigned integer of a given bit width to be promoted
+ /// to a signed integer of the equal or greater bit width.
+ bool promote_integer_sign = false;
+
+ /// Allow an integer, float, or decimal of a given bit width to be
+ /// promoted to an equivalent type of a greater bit width.
+ bool promote_numeric_width = false;
+
+ /// Allow strings to be promoted to binary types. Promotion of fixed size
+ /// binary types to variable sized formats, and binary to large binary,
+ /// and string to large string.
+ bool promote_binary = false;
+
+ /// Second to millisecond, Time32 to Time64, Time32(SECOND) to Time32(MILLI), etc
+ bool promote_temporal_unit = false;
+
+ /// Allow promotion from a list to a large-list
+ bool promote_list = false;
Review Comment:
And looking at the code, it also promotes fixed_sized_list of mixed length to variable sized list. That might be worth to mention in the doc comment above.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] jorisvandenbossche commented on pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "jorisvandenbossche (via GitHub)" <gi...@apache.org>.
jorisvandenbossche commented on PR #36846:
URL: https://github.com/apache/arrow/pull/36846#issuecomment-1741175759
And on the `concat_tables` keyword, another idea I mentioned above was to combine the `promote` ("unify_schemas") and `field_merge_options` in a single keyword. This could have options False/"none" (no unification / promotion, only exactly the same schemas are allowed, the default), "default" (unify schemas, with only null to any type promotion) and "permissive" (unify schemas, with permissive type promotion)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1295703070
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_temporal_unit) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(std::max(left.unit(), right.unit()));
+ }
+
+ if (options.promote_temporal_unit && is_time(promoted_type->id()) &&
+ is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = std::max(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::TypeError(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::TypeError("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(std::max(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-numeric types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_to_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_to_decimal &&
+ ((is_decimal(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_decimal(other_type->id()) && is_integer(promoted_type->id())))) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ // Other type is always the int
+ promoted_type.swap(other_type);
+ }
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(const auto promoted_decimal,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, promoted_decimal));
+ return promoted_type;
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const DecimalType& left = checked_cast<const DecimalType&>(*promoted_type);
+ const DecimalType& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::TypeError(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, other_type));
+ return promoted_type;
+ }
+
+ if (options.promote_integer_sign && ((is_unsigned_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) ||
+ (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
Review Comment:
Yes, I agree. I've added the following check:
```c++
if (!options.promote_numeric_width && bit_width(promoted_type->id()) != bit_width(other_type->id())) {
return Status::TypeError(
"Cannot widen (un)signed integers without promote_numeric_width=true");
}
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1295905033
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_temporal_unit) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(std::max(left.unit(), right.unit()));
+ }
+
+ if (options.promote_temporal_unit && is_time(promoted_type->id()) &&
+ is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = std::max(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::TypeError(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::TypeError("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(std::max(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-numeric types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_to_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_to_decimal &&
+ ((is_decimal(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_decimal(other_type->id()) && is_integer(promoted_type->id())))) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ // Other type is always the int
+ promoted_type.swap(other_type);
+ }
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(const auto promoted_decimal,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, promoted_decimal));
+ return promoted_type;
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const DecimalType& left = checked_cast<const DecimalType&>(*promoted_type);
+ const DecimalType& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::TypeError(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, other_type));
+ return promoted_type;
+ }
+
+ if (options.promote_integer_sign && ((is_unsigned_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) ||
+ (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
+ } else if (max_width >= 16) {
+ promoted_type = int16();
+ } else {
+ promoted_type = int8();
+ }
+ return promoted_type;
+ }
+
+ if (options.promote_integer_to_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ }
+
+ if (options.promote_numeric_width) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (is_floating(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
+ } else if (max_width >= 16) {
+ promoted_type = int16();
+ } else {
+ promoted_type = int8();
+ }
+ } else if (is_unsigned_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = uint64();
+ } else if (max_width >= 32) {
+ promoted_type = uint32();
+ } else if (max_width >= 16) {
+ promoted_type = uint16();
+ } else {
+ promoted_type = uint8();
+ }
+ }
+ }
+
+ return promoted ? promoted_type : nullptr;
+}
+
+// Merge temporal types based on options. Returns nullptr for non-binary types.
+Result<std::shared_ptr<DataType>> MaybeMergeBinaryTypes(
+ std::shared_ptr<DataType>& promoted_type, std::shared_ptr<DataType>& other_type,
+ const Field::MergeOptions& options) {
+ if (options.promote_binary) {
+ if (other_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(promoted_type->id())) {
+ return MakeBinary(*promoted_type);
+ } else if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(other_type->id())) {
+ return MakeBinary(*other_type);
+ } else if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ other_type->id() == Type::FIXED_SIZE_BINARY) {
+ return binary();
+ } else if (is_string(promoted_type->id()) && is_binary(other_type->id())) {
+ return MakeBinary(*other_type);
Review Comment:
Removed them for now
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] pitrou commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "pitrou (via GitHub)" <gi...@apache.org>.
pitrou commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1290143821
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
Review Comment:
Looks like this doesn't include all fields? `promote_dictionary_ordered` is missing at least.
##########
cpp/src/arrow/table.h:
##########
@@ -23,6 +23,7 @@
#include <vector>
#include "arrow/chunked_array.h" // IWYU pragma: keep
+#include "arrow/compute/cast.h"
Review Comment:
It would be better to avoid pulling compute headers in this `.h` file.
Perhaps you can forward-declare `CastOptions` and pass it by const-ref:
```c++
namespace compute {
class CastOptions
};
ARROW_EXPORT
Result<std::shared_ptr<Table>> PromoteTableToSchema(
const std::shared_ptr<Table>& table, const std::shared_ptr<Schema>& schema,
MemoryPool* pool = default_memory_pool());
ARROW_EXPORT
Result<std::shared_ptr<Table>> PromoteTableToSchema(
const std::shared_ptr<Table>& table, const std::shared_ptr<Schema>& schema,
const compute::CastOptions&, MemoryPool* pool = default_memory_pool());
```
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
Review Comment:
```suggestion
return Status::TypeError("Could not merge dictionary index types");
```
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_temporal_unit) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(std::max(left.unit(), right.unit()));
+ }
+
+ if (options.promote_temporal_unit && is_time(promoted_type->id()) &&
+ is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = std::max(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::TypeError(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::TypeError("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(std::max(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-numeric types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_to_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_to_decimal &&
+ ((is_decimal(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_decimal(other_type->id()) && is_integer(promoted_type->id())))) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ // Other type is always the int
+ promoted_type.swap(other_type);
+ }
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(const auto promoted_decimal,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, promoted_decimal));
+ return promoted_type;
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const DecimalType& left = checked_cast<const DecimalType&>(*promoted_type);
+ const DecimalType& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::TypeError(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, other_type));
+ return promoted_type;
+ }
+
+ if (options.promote_integer_sign && ((is_unsigned_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) ||
+ (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
+ } else if (max_width >= 16) {
+ promoted_type = int16();
+ } else {
+ promoted_type = int8();
+ }
+ return promoted_type;
+ }
+
+ if (options.promote_integer_to_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
Review Comment:
Same here (`promote_numeric_width`), also, I'm unconvinced by the bit width equivalence between integer and floating.
For example, an int32 cannot always be represented exactly in the 24 bits of a float32 mantissa.
So I would say (assuming `promote_numeric_width` is true)
* int width <= 8 ⇒ promoted float width = max(16, other float width)
* int width <= 16 ⇒ promoted float width = max(32, other float width)
* otherwise ⇒ promoted float width = max(64, other float width)
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
Review Comment:
This could simply call `MaybeMergeNumericTypes`?
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_temporal_unit) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(std::max(left.unit(), right.unit()));
+ }
+
+ if (options.promote_temporal_unit && is_time(promoted_type->id()) &&
+ is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = std::max(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::TypeError(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::TypeError("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(std::max(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-numeric types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_to_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_to_decimal &&
+ ((is_decimal(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_decimal(other_type->id()) && is_integer(promoted_type->id())))) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ // Other type is always the int
+ promoted_type.swap(other_type);
+ }
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(const auto promoted_decimal,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, promoted_decimal));
+ return promoted_type;
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const DecimalType& left = checked_cast<const DecimalType&>(*promoted_type);
+ const DecimalType& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::TypeError(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, other_type));
+ return promoted_type;
+ }
+
+ if (options.promote_integer_sign && ((is_unsigned_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) ||
+ (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
Review Comment:
Shouldn't this be conditioned on `promote_numeric_width`?
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_temporal_unit) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(std::max(left.unit(), right.unit()));
+ }
+
+ if (options.promote_temporal_unit && is_time(promoted_type->id()) &&
+ is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = std::max(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::TypeError(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::TypeError("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(std::max(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-numeric types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_to_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_to_decimal &&
+ ((is_decimal(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_decimal(other_type->id()) && is_integer(promoted_type->id())))) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ // Other type is always the int
+ promoted_type.swap(other_type);
+ }
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(const auto promoted_decimal,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, promoted_decimal));
Review Comment:
Note the `promote_numeric_width` check is missing here, so better factor it out into `WidenDecimals`?
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_temporal_unit) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(std::max(left.unit(), right.unit()));
+ }
+
+ if (options.promote_temporal_unit && is_time(promoted_type->id()) &&
+ is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = std::max(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::TypeError(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::TypeError("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(std::max(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-numeric types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_to_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_to_decimal &&
+ ((is_decimal(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_decimal(other_type->id()) && is_integer(promoted_type->id())))) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ // Other type is always the int
+ promoted_type.swap(other_type);
+ }
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(const auto promoted_decimal,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, promoted_decimal));
+ return promoted_type;
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const DecimalType& left = checked_cast<const DecimalType&>(*promoted_type);
+ const DecimalType& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::TypeError(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, other_type));
+ return promoted_type;
+ }
+
+ if (options.promote_integer_sign && ((is_unsigned_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) ||
+ (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
+ } else if (max_width >= 16) {
+ promoted_type = int16();
+ } else {
+ promoted_type = int8();
+ }
+ return promoted_type;
+ }
+
+ if (options.promote_integer_to_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ }
+
+ if (options.promote_numeric_width) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (is_floating(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
+ } else if (max_width >= 16) {
+ promoted_type = int16();
+ } else {
+ promoted_type = int8();
+ }
+ } else if (is_unsigned_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = uint64();
+ } else if (max_width >= 32) {
+ promoted_type = uint32();
+ } else if (max_width >= 16) {
+ promoted_type = uint16();
+ } else {
+ promoted_type = uint8();
+ }
+ }
+ }
+
+ return promoted ? promoted_type : nullptr;
+}
+
+// Merge temporal types based on options. Returns nullptr for non-binary types.
+Result<std::shared_ptr<DataType>> MaybeMergeBinaryTypes(
+ std::shared_ptr<DataType>& promoted_type, std::shared_ptr<DataType>& other_type,
+ const Field::MergeOptions& options) {
+ if (options.promote_binary) {
+ if (other_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(promoted_type->id())) {
+ return MakeBinary(*promoted_type);
+ } else if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(other_type->id())) {
+ return MakeBinary(*other_type);
+ } else if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ other_type->id() == Type::FIXED_SIZE_BINARY) {
+ return binary();
+ } else if (is_string(promoted_type->id()) && is_binary(other_type->id())) {
+ return MakeBinary(*other_type);
+ } else if (is_binary(promoted_type->id()) && is_string(other_type->id())) {
+ return MakeBinary(*promoted_type);
+ }
+
+ if ((promoted_type->id() == Type::STRING && other_type->id() == Type::LARGE_STRING) ||
+ (promoted_type->id() == Type::LARGE_STRING && other_type->id() == Type::STRING)) {
+ return large_utf8();
+ } else if ((promoted_type->id() == Type::BINARY &&
+ other_type->id() == Type::LARGE_BINARY) ||
+ (promoted_type->id() == Type::LARGE_BINARY &&
+ other_type->id() == Type::BINARY)) {
+ return large_binary();
+ }
+ }
+
+ return nullptr;
+}
+
+// Merge list types based on options. Returns nullptr for non-list types.
+Result<std::shared_ptr<DataType>> MaybeMergeListTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ bool promoted = false;
+
+ if (promoted_type->id() == Type::FIXED_SIZE_LIST &&
+ other_type->id() == Type::FIXED_SIZE_LIST) {
+ const auto& left = checked_cast<const FixedSizeListType&>(*promoted_type);
+ const auto& right = checked_cast<const FixedSizeListType&>(*other_type);
+ ARROW_ASSIGN_OR_RAISE(
+ auto value_field,
+ left.value_field()->MergeWith(
+ *right.value_field()->WithName(left.value_field()->name()), options));
+ if (left.list_size() == right.list_size()) {
+ return fixed_size_list(std::move(value_field), left.list_size());
+ }
+ return Status::TypeError("Cannot merge fixed_size_list of different sizes");
+ } else if (promoted_type->id() == Type::MAP && other_type->id() == Type::MAP) {
+ const auto& left = checked_cast<const MapType&>(*promoted_type);
+ const auto& right = checked_cast<const MapType&>(*other_type);
+ ARROW_ASSIGN_OR_RAISE(
+ auto key_field,
+ left.key_field()->MergeWith(
+ *right.key_field()->WithName(left.key_field()->name()), options));
+ ARROW_ASSIGN_OR_RAISE(
+ auto item_field,
+ left.item_field()->MergeWith(
+ *right.item_field()->WithName(left.item_field()->name()), options));
+ return map(std::move(key_field->type()), std::move(item_field),
+ /*keys_sorted=*/left.keys_sorted() && right.keys_sorted());
+ } else if (is_list(promoted_type->id()) && is_list(other_type->id())) {
+ const auto& left = checked_cast<const BaseListType&>(*promoted_type);
+ const auto& right = checked_cast<const BaseListType&>(*other_type);
+ ARROW_ASSIGN_OR_RAISE(
+ auto value_field,
+ left.value_field()->MergeWith(
+ *right.value_field()->WithName(left.value_field()->name()), options));
+ if (promoted_type->id() == Type::LARGE_LIST || other_type->id() == Type::LARGE_LIST) {
+ return large_list(std::move(value_field));
+ } else {
+ return list(std::move(value_field));
+ }
+ } else if (promoted_type->id() == Type::STRUCT && other_type->id() == Type::STRUCT) {
+ SchemaBuilder builder(SchemaBuilder::CONFLICT_APPEND, options);
+ // Add the LHS fields. Duplicates will be preserved.
+ RETURN_NOT_OK(builder.AddFields(promoted_type->fields()));
+
+ // Add the RHS fields. Duplicates will be merged, unless the field was
+ // already a duplicate, in which case we error (since we don't know which
+ // field to merge with).
+ builder.SetPolicy(SchemaBuilder::CONFLICT_MERGE);
+ RETURN_NOT_OK(builder.AddFields(other_type->fields()));
+
+ ARROW_ASSIGN_OR_RAISE(auto schema, builder.Finish());
+ return struct_(schema->fields());
+ }
+
+ return promoted ? promoted_type : nullptr;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ if (promoted_type->Equals(*other_type)) return promoted_type;
+
+ bool promoted = false;
+ if (options.promote_nullability) {
+ if (promoted_type->id() == Type::NA) {
+ return other_type;
+ } else if (other_type->id() == Type::NA) {
+ return promoted_type;
+ }
+ } else if (promoted_type->id() == Type::NA || other_type->id() == Type::NA) {
+ return Status::Invalid("Cannot merge type with null unless promote_nullability=true");
Review Comment:
`TypeError` here as well?
##########
python/pyarrow/table.pxi:
##########
@@ -5066,6 +5073,16 @@ def concat_tables(tables, c_bool promote=False, MemoryPool memory_pool=None):
for table in tables:
c_tables.push_back(table.sp_table)
+ if field_merge_options is not None:
+ if isinstance(field_merge_options, str):
+ if field_merge_options == "permissive":
+ options.field_merge_options = CField.CMergeOptions.Permissive()
+ elif field_merge_options == "default":
+ options.field_merge_options = CField.CMergeOptions.Defaults()
+ else:
+ options.field_merge_options = cython.cast(
+ FieldMergeOptions, field_merge_options).c_options
Review Comment:
You can simply write:
```suggestion
options.field_merge_options = (<FieldMergeOptions> field_merge_options).c_options
```
... and remove the `import cython` at the top.
##########
cpp/src/arrow/type_test.cc:
##########
@@ -892,6 +892,150 @@ class TestUnifySchemas : public TestSchema {
<< lhs_field->ToString() << " vs " << rhs_field->ToString();
}
}
+
+ void CheckUnifyAsymmetric(
+ const std::shared_ptr<Field>& field1, const std::shared_ptr<Field>& field2,
+ const std::shared_ptr<Field>& expected,
+ const Field::MergeOptions& options = Field::MergeOptions::Defaults()) {
+ ARROW_SCOPED_TRACE("options: ", options);
+ ARROW_SCOPED_TRACE("field2: ", field2->ToString());
+ ARROW_SCOPED_TRACE("field1: ", field1->ToString());
+ ASSERT_OK_AND_ASSIGN(auto merged, field1->MergeWith(field2, options));
+ AssertFieldEqual(merged, expected);
+ }
+
+ void CheckUnify(const std::shared_ptr<Field>& field1,
+ const std::shared_ptr<Field>& field2,
+ const std::shared_ptr<Field>& expected,
+ const Field::MergeOptions& options = Field::MergeOptions::Defaults()) {
+ CheckUnifyAsymmetric(field1, field2, expected, options);
+ CheckUnifyAsymmetric(field2, field1, expected, options);
+ }
+
+ void CheckUnifyFailsInvalid(
+ const std::shared_ptr<Field>& field1, const std::shared_ptr<Field>& field2,
+ const Field::MergeOptions& options = Field::MergeOptions::Defaults()) {
+ ARROW_SCOPED_TRACE("options: ", options);
+ ARROW_SCOPED_TRACE("field2: ", field2->ToString());
+ ARROW_SCOPED_TRACE("field1: ", field1->ToString());
+ ASSERT_RAISES(Invalid, field1->MergeWith(field2, options));
+ ASSERT_RAISES(Invalid, field2->MergeWith(field1, options));
+ }
Review Comment:
I think it would be nicer to also check a part of the error message. For example (untested, but you get the idea):
```suggestion
void CheckUnifyFailsInvalid(
const std::shared_ptr<Field>& field1, const std::shared_ptr<Field>& field2,
const Field::MergeOptions& options = Field::MergeOptions::Defaults(),
const std::string& match_message = "") {
ARROW_SCOPED_TRACE("options: ", options);
ARROW_SCOPED_TRACE("field2: ", field2->ToString());
ARROW_SCOPED_TRACE("field1: ", field1->ToString());
EXPECT_RAISES_WITH_MESSAGE_THAT(
Invalid, ::testing::HasSubstr(match_message), field1->MergeWith(field2, options));
EXPECT_RAISES_WITH_MESSAGE_THAT(
Invalid, ::testing::HasSubstr(match_message), field2->MergeWith(field1, options));
}
```
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,63 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
+
+ /// Allow a decimal to be promoted to a float. The float type will
+ /// not itself be promoted (e.g. Decimal128 + Float32 = Float32).
+ bool promote_decimal_to_float = false;
+
+ /// Allow an integer to be promoted to a decimal.
+ ///
+ /// May fail if the decimal has insufficient precision to
+ /// accommodate the integer. (See increase_decimal_precision.)
+ bool promote_integer_to_decimal = false;
+
+ /// Allow an integer of a given bit width to be promoted to a
+ /// float; the result will be a float of an equal or greater bit
+ /// width to both of the inputs.
+ bool promote_integer_to_float = false;
+
+ /// Allow an unsigned integer of a given bit width to be promoted
+ /// to a signed integer of the equal or greater bit width.
+ bool promote_integer_sign = false;
+
+ /// Allow an integer, float, or decimal of a given bit width to be
+ /// promoted to an equivalent type of a greater bit width.
+ bool promote_numeric_width = false;
+
+ /// Allow strings to be promoted to binary types.
+ bool promote_binary = false;
Review Comment:
Call this `promote_string_to_binary` for clarity?
##########
python/pyarrow/types.pxi:
##########
@@ -1969,6 +1969,48 @@ cpdef KeyValueMetadata ensure_metadata(object meta, c_bool allow_none=False):
return KeyValueMetadata(meta)
+cdef class FieldMergeOptions(_Weakrefable):
+ """
+ Options controlling how to merge the types of two fields.
+
+ By default, types must match exactly, except the null type can be
+ merged with any other type.
+
+ """
+
+ cdef:
+ CField.CMergeOptions c_options
+
+ __slots__ = ()
+
+ def __init__(self, *):
+ self.c_options = CField.CMergeOptions.Defaults()
+
+ @staticmethod
+ def permissive():
+ """
+ Allow merging generally compatible types (e.g. float64 and int64).
+ """
+ cdef FieldMergeOptions options = FieldMergeOptions()
+ options.c_options = CField.CMergeOptions.Permissive()
+ return options
+
+ def __repr__(self) -> str:
+ return 'FieldMergeOptions(promote_nullability={},promote_decimal={},promote_decimal_to_float={},promote_integer_to_decimal={},promote_integer_to_float={},promote_integer_sign={},promote_numeric_width={},promote_binary={},promote_temporal_unit={},promote_dictionary={},promote_dictionary_ordered={})'.format(
Review Comment:
Two things:
1) can you please ensure lines are not too long?
2) you can use a f-string here, for example:
```python
return (
f'FieldMergeOptions(promote_nullability={self.promote_nullability}, '
f'promote_decimal={self.promote_decimal}, '
...)
```
##########
python/pyarrow/types.pxi:
##########
@@ -3128,6 +3170,8 @@ def unify_schemas(schemas):
----------
schemas : list of Schema
Schemas to merge into a single one.
+ options : FieldMergeOptions, optional
Review Comment:
Here as well, it would be nice to be able to pass this as a string ("default" or "permissive").
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
Review Comment:
```suggestion
return Status::Invalid("Could not merge dictionary value types");
```
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
Review Comment:
Should we instead return an error if `options.promote_numeric_width` is false?
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_temporal_unit) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(std::max(left.unit(), right.unit()));
+ }
+
+ if (options.promote_temporal_unit && is_time(promoted_type->id()) &&
+ is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = std::max(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::TypeError(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::TypeError("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(std::max(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-numeric types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_to_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_to_decimal &&
+ ((is_decimal(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_decimal(other_type->id()) && is_integer(promoted_type->id())))) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ // Other type is always the int
+ promoted_type.swap(other_type);
+ }
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(const auto promoted_decimal,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, promoted_decimal));
+ return promoted_type;
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const DecimalType& left = checked_cast<const DecimalType&>(*promoted_type);
+ const DecimalType& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::TypeError(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, other_type));
+ return promoted_type;
+ }
+
+ if (options.promote_integer_sign && ((is_unsigned_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) ||
+ (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
+ } else if (max_width >= 16) {
+ promoted_type = int16();
+ } else {
+ promoted_type = int8();
+ }
+ return promoted_type;
+ }
+
+ if (options.promote_integer_to_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ }
+
+ if (options.promote_numeric_width) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (is_floating(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
+ } else if (max_width >= 16) {
+ promoted_type = int16();
+ } else {
+ promoted_type = int8();
+ }
+ } else if (is_unsigned_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = uint64();
+ } else if (max_width >= 32) {
+ promoted_type = uint32();
+ } else if (max_width >= 16) {
+ promoted_type = uint16();
+ } else {
+ promoted_type = uint8();
+ }
+ }
+ }
+
+ return promoted ? promoted_type : nullptr;
+}
+
+// Merge temporal types based on options. Returns nullptr for non-binary types.
+Result<std::shared_ptr<DataType>> MaybeMergeBinaryTypes(
+ std::shared_ptr<DataType>& promoted_type, std::shared_ptr<DataType>& other_type,
+ const Field::MergeOptions& options) {
+ if (options.promote_binary) {
+ if (other_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(promoted_type->id())) {
+ return MakeBinary(*promoted_type);
+ } else if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(other_type->id())) {
+ return MakeBinary(*other_type);
+ } else if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ other_type->id() == Type::FIXED_SIZE_BINARY) {
+ return binary();
+ } else if (is_string(promoted_type->id()) && is_binary(other_type->id())) {
+ return MakeBinary(*other_type);
+ } else if (is_binary(promoted_type->id()) && is_string(other_type->id())) {
+ return MakeBinary(*promoted_type);
+ }
+
+ if ((promoted_type->id() == Type::STRING && other_type->id() == Type::LARGE_STRING) ||
+ (promoted_type->id() == Type::LARGE_STRING && other_type->id() == Type::STRING)) {
+ return large_utf8();
+ } else if ((promoted_type->id() == Type::BINARY &&
+ other_type->id() == Type::LARGE_BINARY) ||
+ (promoted_type->id() == Type::LARGE_BINARY &&
+ other_type->id() == Type::BINARY)) {
+ return large_binary();
+ }
+ }
+
+ return nullptr;
+}
+
+// Merge list types based on options. Returns nullptr for non-list types.
+Result<std::shared_ptr<DataType>> MaybeMergeListTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ bool promoted = false;
+
Review Comment:
I would suggest a `promote_list` option to enable changing the list kind: for example from list to large_list. Doing it by default would be surprising to users IMHO.
The value type would always be promoted recursively, however.
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_temporal_unit) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(std::max(left.unit(), right.unit()));
+ }
+
+ if (options.promote_temporal_unit && is_time(promoted_type->id()) &&
+ is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = std::max(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::TypeError(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::TypeError("Cannot merge timestamps with differing timezones");
+ }
Review Comment:
Do we want these checks to run even if `options.promote_temporal_unit` is false? This could allow for nicer error messages.
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,63 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
+
+ /// Allow a decimal to be promoted to a float. The float type will
+ /// not itself be promoted (e.g. Decimal128 + Float32 = Float32).
+ bool promote_decimal_to_float = false;
+
+ /// Allow an integer to be promoted to a decimal.
+ ///
+ /// May fail if the decimal has insufficient precision to
+ /// accommodate the integer. (See increase_decimal_precision.)
+ bool promote_integer_to_decimal = false;
+
+ /// Allow an integer of a given bit width to be promoted to a
+ /// float; the result will be a float of an equal or greater bit
+ /// width to both of the inputs.
+ bool promote_integer_to_float = false;
+
+ /// Allow an unsigned integer of a given bit width to be promoted
+ /// to a signed integer of the equal or greater bit width.
+ bool promote_integer_sign = false;
+
+ /// Allow an integer, float, or decimal of a given bit width to be
+ /// promoted to an equivalent type of a greater bit width.
+ bool promote_numeric_width = false;
+
+ /// Allow strings to be promoted to binary types.
+ bool promote_binary = false;
+
+ /// Second to millisecond, Time32 to Time64, Time32(SECOND) to Time32(MILLI), etc
+ bool promote_temporal_unit = false;
+
+ /// Promote dictionary index types to a common type, and unify the
+ /// value types.
Review Comment:
```suggestion
/// Unify dictionary index types and dictionary value types.
```
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,63 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
+
+ /// Allow a decimal to be promoted to a float. The float type will
+ /// not itself be promoted (e.g. Decimal128 + Float32 = Float32).
+ bool promote_decimal_to_float = false;
+
+ /// Allow an integer to be promoted to a decimal.
+ ///
+ /// May fail if the decimal has insufficient precision to
+ /// accommodate the integer. (See increase_decimal_precision.)
+ bool promote_integer_to_decimal = false;
+
+ /// Allow an integer of a given bit width to be promoted to a
+ /// float; the result will be a float of an equal or greater bit
+ /// width to both of the inputs.
+ bool promote_integer_to_float = false;
+
+ /// Allow an unsigned integer of a given bit width to be promoted
+ /// to a signed integer of the equal or greater bit width.
+ bool promote_integer_sign = false;
+
+ /// Allow an integer, float, or decimal of a given bit width to be
+ /// promoted to an equivalent type of a greater bit width.
+ bool promote_numeric_width = false;
+
+ /// Allow strings to be promoted to binary types.
+ bool promote_binary = false;
+
+ /// Second to millisecond, Time32 to Time64, Time32(SECOND) to Time32(MILLI), etc
+ bool promote_temporal_unit = false;
+
+ /// Promote dictionary index types to a common type, and unify the
+ /// value types.
+ bool promote_dictionary = false;
+
+ /// Allow merging ordered and non-ordered dictionaries, else
+ /// error. The result will be ordered if and only if both inputs
Review Comment:
"else error" is implied, isn't it? No need to spell it out explicitly, IMHO.
##########
python/pyarrow/tests/test_table.py:
##########
@@ -1373,6 +1373,15 @@ def test_concat_tables_with_promotion():
pa.array([None, None, 1.0, 2.0], type=pa.float32()),
], ["int64_field", "float_field"]))
+ t3 = pa.Table.from_arrays(
+ [pa.array([1, 2], type=pa.int32())], ["int64_field"])
+ result = pa.concat_tables(
+ [t1, t3], promote=True,
+ field_merge_options=pa.FieldMergeOptions.permissive())
Review Comment:
Can you add a test for it?
##########
cpp/src/arrow/table.cc:
##########
@@ -502,9 +504,16 @@ Result<std::shared_ptr<Table>> PromoteTableToSchema(const std::shared_ptr<Table>
continue;
}
- return Status::Invalid("Unable to promote field ", field->name(),
- ": incompatible types: ", field->type()->ToString(), " vs ",
- current_field->type()->ToString());
+ if (!compute::CanCast(*current_field->type(), *field->type())) {
+ return Status::Invalid("Unable to promote field ", field->name(),
Review Comment:
Did you forget to change this?
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,63 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
+
+ /// Allow a decimal to be promoted to a float. The float type will
+ /// not itself be promoted (e.g. Decimal128 + Float32 = Float32).
+ bool promote_decimal_to_float = false;
+
+ /// Allow an integer to be promoted to a decimal.
+ ///
+ /// May fail if the decimal has insufficient precision to
+ /// accommodate the integer. (See increase_decimal_precision.)
+ bool promote_integer_to_decimal = false;
+
+ /// Allow an integer of a given bit width to be promoted to a
+ /// float; the result will be a float of an equal or greater bit
+ /// width to both of the inputs.
+ bool promote_integer_to_float = false;
+
+ /// Allow an unsigned integer of a given bit width to be promoted
+ /// to a signed integer of the equal or greater bit width.
+ bool promote_integer_sign = false;
+
+ /// Allow an integer, float, or decimal of a given bit width to be
+ /// promoted to an equivalent type of a greater bit width.
+ bool promote_numeric_width = false;
+
+ /// Allow strings to be promoted to binary types.
+ bool promote_binary = false;
Review Comment:
Actually, this seems to be conditioning a lot of other promotions. So the name is fine but the docstring should be fixed, IMHO.
##########
cpp/src/arrow/table_test.cc:
##########
@@ -520,6 +522,36 @@ TEST_F(ConcatenateTablesWithPromotionTest, Simple) {
AssertTablesEqualUnorderedFields(*expected, *result);
}
+TEST_F(ConcatenateTablesWithPromotionTest, Unify) {
+ auto t1 = TableFromJSON(schema({field("f0", int32())}), {"[[0], [1]]"});
+ auto t2 = TableFromJSON(schema({field("f0", int64())}), {"[[2], [3]]"});
+ auto t3 = TableFromJSON(schema({field("f0", null())}), {"[[null], [null]]"});
+
+ auto expected_int64 =
+ TableFromJSON(schema({field("f0", int64())}), {"[[0], [1], [2], [3]]"});
+ auto expected_null =
+ TableFromJSON(schema({field("f0", int32())}), {"[[0], [1], [null], [null]]"});
+
+ ConcatenateTablesOptions options;
+ EXPECT_RAISES_WITH_MESSAGE_THAT(Invalid,
+ ::testing::HasSubstr("Schema at index 1 was different"),
+ ConcatenateTables({t1, t2}, options));
+ EXPECT_RAISES_WITH_MESSAGE_THAT(Invalid,
+ ::testing::HasSubstr("Schema at index 1 was different"),
+ ConcatenateTables({t1, t3}, options));
+
+ options.unify_schemas = true;
+ EXPECT_RAISES_WITH_MESSAGE_THAT(Invalid,
+ ::testing::HasSubstr("Field f0 has incompatible types"),
+ ConcatenateTables({t1, t2}, options));
+ ASSERT_OK_AND_ASSIGN(auto actual, ConcatenateTables({t1, t3}, options));
+ AssertTablesEqual(*expected_null, *actual, /*same_chunk_layout=*/false);
+
+ options.field_merge_options.promote_numeric_width = true;
+ ASSERT_OK_AND_ASSIGN(actual, ConcatenateTables({t1, t2}, options));
+ AssertTablesEqual(*expected_int64, *actual, /*same_chunk_layout=*/false);
+}
Review Comment:
It looks like you haven't addressed this comment?
##########
cpp/src/arrow/type.cc:
##########
@@ -327,14 +709,27 @@ Result<std::shared_ptr<Field>> Field::MergeWith(const Field& other,
return Copy();
}
- if (options.promote_nullability) {
- if (type()->Equals(other.type())) {
- return Copy()->WithNullable(nullable() || other.nullable());
+ auto maybe_promoted_type = MergeTypes(type_, other.type(), options);
+ if (!maybe_promoted_type.ok()) {
+ return maybe_promoted_type.status().WithMessage(
+ "Unable to merge: Field ", name(),
+ " has incompatible types: ", type()->ToString(), " vs ", other.type()->ToString(),
+ ": ", maybe_promoted_type.status().message());
+ }
+ auto promoted_type = *std::move(maybe_promoted_type);
+ if (promoted_type) {
+ bool nullable = nullable_;
+ if (options.promote_nullability) {
+ nullable = nullable || other.nullable() || type_->id() == Type::NA ||
+ other.type()->id() == Type::NA;
+ } else if (nullable_ != other.nullable()) {
+ return Status::Invalid("Unable to merge: Field ", name(),
+ " has incompatible nullability: ", nullable_, " vs ",
+ other.nullable());
Review Comment:
We should probably change these errors to `TypeError`. It may slightly break user code, but for the better (so that one can distinguish between unsupported type casts and invalid value casts).
##########
cpp/src/arrow/type_test.cc:
##########
@@ -983,6 +1127,242 @@ TEST_F(TestUnifySchemas, MoreSchemas) {
utf8_field->WithNullable(true)}));
}
+TEST_F(TestUnifySchemas, Numeric) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ CheckUnify(uint8(),
+ {int8(), uint16(), int16(), uint32(), int32(), uint64(), int64(), float32(),
+ float64()},
+ options);
+ CheckUnify(int8(), {int16(), int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint16(),
+ {int16(), uint32(), int32(), uint64(), int64(), float32(), float64()},
+ options);
+ CheckUnify(int16(), {int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint32(), {int32(), uint64(), int64(), float32(), float64()}, options);
+ CheckUnify(int32(), {int64(), float32(), float64()}, options);
+ CheckUnify(uint64(), {int64(), float64()}, options);
+ CheckUnify(int64(), {float64()}, options);
+ CheckUnify(float16(), {float32(), float64()}, options);
+ CheckUnify(float32(), {float64()}, options);
+ CheckUnify(uint64(), float32(), float64(), options);
+ CheckUnify(int64(), float32(), float64(), options);
+
+ options.promote_integer_sign = false;
+ CheckUnify(uint8(), {uint16(), uint32(), uint64()}, options);
+ CheckUnify(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFailsInvalid(uint8(), {int8(), int16(), int32(), int64()}, options);
+ CheckUnify(uint16(), {uint32(), uint64()}, options);
+ CheckUnify(int16(), {int32(), int64()}, options);
+ CheckUnifyFailsInvalid(uint16(), {int16(), int32(), int64()}, options);
+ CheckUnify(uint32(), {uint64()}, options);
+ CheckUnify(int32(), {int64()}, options);
+ CheckUnifyFailsInvalid(uint32(), {int32(), int64()}, options);
+ CheckUnifyFailsInvalid(uint64(), {int64()}, options);
+
+ options.promote_integer_sign = true;
+ options.promote_integer_to_float = false;
+ CheckUnifyFailsInvalid(IntTypes(), FloatingPointTypes(), options);
+
+ options.promote_integer_to_float = true;
+ options.promote_numeric_width = false;
+ CheckUnifyFailsInvalid(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFailsInvalid(int16(), {int32(), int64()}, options);
+ CheckUnifyFailsInvalid(int32(), {int64()}, options);
+ CheckUnify(int32(), {float32()}, options);
+ CheckUnify(int64(), {float64()}, options);
+ CheckUnify(int32(), float16(), float32(), options);
+}
+
+TEST_F(TestUnifySchemas, Decimal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_decimal_to_float = true;
+ CheckUnify(decimal128(3, 2), {float32(), float64()}, options);
+ CheckUnify(decimal256(3, 2), {float32(), float64()}, options);
+
+ options.promote_integer_to_decimal = true;
+ CheckUnify(int32(), decimal128(3, 2), decimal128(12, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(10, 0), options);
+
+ options.promote_decimal = true;
+ CheckUnify(decimal128(3, 2), decimal128(5, 2), decimal128(5, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 3), decimal128(5, 3), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 1), decimal128(6, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, -2), decimal128(9, 2), options);
+ CheckUnify(decimal128(3, -2), decimal128(5, -2), decimal128(5, -2), options);
+ CheckUnify(decimal128(38, 10), decimal128(38, 5), decimal256(43, 10), options);
+
+ CheckUnify(decimal256(3, 2), decimal256(5, 2), decimal256(5, 2), options);
+ CheckUnify(decimal256(3, 2), decimal256(5, 3), decimal256(5, 3), options);
+ CheckUnify(decimal256(3, 2), decimal256(5, 1), decimal256(6, 2), options);
+ CheckUnify(decimal256(3, 2), decimal256(5, -2), decimal256(9, 2), options);
+ CheckUnify(decimal256(3, -2), decimal256(5, -2), decimal256(5, -2), options);
+
+ // int32() is essentially decimal128(10, 0)
+ CheckUnify(int32(), decimal128(3, 2), decimal128(12, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(10, 0), options);
+ CheckUnify(int64(), decimal128(38, 37), decimal256(56, 37), options);
+
+ CheckUnifyFailsTypeError(decimal256(1, 0), decimal128(1, 0), options);
+
+ options.promote_numeric_width = true;
+ CheckUnify(decimal128(3, 2), decimal256(5, 2), decimal256(5, 2), options);
+ CheckUnify(int32(), decimal128(38, 37), decimal256(47, 37), options);
+ CheckUnifyFailsInvalid(decimal128(38, 10), decimal256(76, 5), options);
+
+ CheckUnifyFailsInvalid(int64(), decimal256(76, 75), options);
+}
+
+TEST_F(TestUnifySchemas, Temporal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_temporal_unit = true;
+ CheckUnify(date32(), {date64()}, options);
+
+ CheckUnify(time32(TimeUnit::SECOND),
+ {time32(TimeUnit::MILLI), time64(TimeUnit::MICRO), time64(TimeUnit::NANO)},
+ options);
+ CheckUnify(time32(TimeUnit::MILLI), {time64(TimeUnit::MICRO), time64(TimeUnit::NANO)},
+ options);
+ CheckUnify(time64(TimeUnit::MICRO), {time64(TimeUnit::NANO)}, options);
+
+ CheckUnify(
+ duration(TimeUnit::SECOND),
+ {duration(TimeUnit::MILLI), duration(TimeUnit::MICRO), duration(TimeUnit::NANO)},
+ options);
+ CheckUnify(duration(TimeUnit::MILLI),
+ {duration(TimeUnit::MICRO), duration(TimeUnit::NANO)}, options);
+ CheckUnify(duration(TimeUnit::MICRO), {duration(TimeUnit::NANO)}, options);
+
+ CheckUnify(
+ timestamp(TimeUnit::SECOND),
+ {timestamp(TimeUnit::MILLI), timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO)},
+ options);
+ CheckUnify(timestamp(TimeUnit::MILLI),
+ {timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO)}, options);
+ CheckUnify(timestamp(TimeUnit::MICRO), {timestamp(TimeUnit::NANO)}, options);
+
+ CheckUnifyFailsTypeError(timestamp(TimeUnit::SECOND),
+ timestamp(TimeUnit::SECOND, "UTC"), options);
+ CheckUnifyFailsTypeError(timestamp(TimeUnit::SECOND, "America/New_York"),
+ timestamp(TimeUnit::SECOND, "UTC"), options);
+
+ options.promote_temporal_unit = false;
+ CheckUnifyFailsInvalid(timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO), options);
Review Comment:
(would expect `TypeError` as well as in all/most instances here)
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_temporal_unit) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(std::max(left.unit(), right.unit()));
+ }
+
+ if (options.promote_temporal_unit && is_time(promoted_type->id()) &&
+ is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = std::max(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::TypeError(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::TypeError("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(std::max(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-numeric types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_to_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_to_decimal &&
+ ((is_decimal(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_decimal(other_type->id()) && is_integer(promoted_type->id())))) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ // Other type is always the int
+ promoted_type.swap(other_type);
+ }
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(const auto promoted_decimal,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, promoted_decimal));
+ return promoted_type;
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const DecimalType& left = checked_cast<const DecimalType&>(*promoted_type);
+ const DecimalType& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::TypeError(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, other_type));
+ return promoted_type;
+ }
+
+ if (options.promote_integer_sign && ((is_unsigned_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) ||
+ (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
+ } else if (max_width >= 16) {
+ promoted_type = int16();
+ } else {
+ promoted_type = int8();
+ }
+ return promoted_type;
+ }
+
+ if (options.promote_integer_to_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
Review Comment:
Same here (`promote_numeric_width`), also, I'm unconvinced by the bit width equivalence between integer and floating.
For example, an int32 cannot always be represented exactly in the 24 bits of a float32 mantissa.
So I would say (assuming `promote_numeric_width` is true)
* int width <= 8 ⇒ promoted float width = max(16, other float width)
* int width <= 16 ⇒ promoted float width = max(32, other float width)
* otherwise ⇒ promoted float width = max(64, other float width)
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_temporal_unit) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(std::max(left.unit(), right.unit()));
+ }
+
+ if (options.promote_temporal_unit && is_time(promoted_type->id()) &&
+ is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = std::max(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::TypeError(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::TypeError("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(std::max(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-numeric types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_to_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_to_decimal &&
+ ((is_decimal(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_decimal(other_type->id()) && is_integer(promoted_type->id())))) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ // Other type is always the int
+ promoted_type.swap(other_type);
+ }
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(const auto promoted_decimal,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, promoted_decimal));
+ return promoted_type;
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const DecimalType& left = checked_cast<const DecimalType&>(*promoted_type);
+ const DecimalType& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::TypeError(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, other_type));
+ return promoted_type;
+ }
+
+ if (options.promote_integer_sign && ((is_unsigned_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) ||
+ (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
+ } else if (max_width >= 16) {
+ promoted_type = int16();
+ } else {
+ promoted_type = int8();
+ }
+ return promoted_type;
+ }
+
+ if (options.promote_integer_to_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ }
+
+ if (options.promote_numeric_width) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (is_floating(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
+ } else if (max_width >= 16) {
+ promoted_type = int16();
+ } else {
+ promoted_type = int8();
+ }
+ } else if (is_unsigned_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = uint64();
+ } else if (max_width >= 32) {
+ promoted_type = uint32();
+ } else if (max_width >= 16) {
+ promoted_type = uint16();
+ } else {
+ promoted_type = uint8();
+ }
+ }
+ }
+
+ return promoted ? promoted_type : nullptr;
+}
+
+// Merge temporal types based on options. Returns nullptr for non-binary types.
+Result<std::shared_ptr<DataType>> MaybeMergeBinaryTypes(
+ std::shared_ptr<DataType>& promoted_type, std::shared_ptr<DataType>& other_type,
+ const Field::MergeOptions& options) {
+ if (options.promote_binary) {
+ if (other_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(promoted_type->id())) {
+ return MakeBinary(*promoted_type);
+ } else if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(other_type->id())) {
+ return MakeBinary(*other_type);
+ } else if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ other_type->id() == Type::FIXED_SIZE_BINARY) {
+ return binary();
+ } else if (is_string(promoted_type->id()) && is_binary(other_type->id())) {
+ return MakeBinary(*other_type);
Review Comment:
Hmm... so, if `promoted_type` is `LARGE_STRING` and `other_type` is `BINARY`, they will be unified into `BINARY`? I would expect `LARGE_BINARY`... I think you have to logically handle utf8-ness and offset width separately, if you want to avoid spelling out all combinations explicitly.
##########
cpp/src/arrow/type_test.cc:
##########
@@ -983,6 +1127,242 @@ TEST_F(TestUnifySchemas, MoreSchemas) {
utf8_field->WithNullable(true)}));
}
+TEST_F(TestUnifySchemas, Numeric) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ CheckUnify(uint8(),
+ {int8(), uint16(), int16(), uint32(), int32(), uint64(), int64(), float32(),
+ float64()},
+ options);
+ CheckUnify(int8(), {int16(), int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint16(),
+ {int16(), uint32(), int32(), uint64(), int64(), float32(), float64()},
+ options);
+ CheckUnify(int16(), {int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint32(), {int32(), uint64(), int64(), float32(), float64()}, options);
+ CheckUnify(int32(), {int64(), float32(), float64()}, options);
+ CheckUnify(uint64(), {int64(), float64()}, options);
+ CheckUnify(int64(), {float64()}, options);
+ CheckUnify(float16(), {float32(), float64()}, options);
+ CheckUnify(float32(), {float64()}, options);
+ CheckUnify(uint64(), float32(), float64(), options);
+ CheckUnify(int64(), float32(), float64(), options);
+
+ options.promote_integer_sign = false;
+ CheckUnify(uint8(), {uint16(), uint32(), uint64()}, options);
+ CheckUnify(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFailsInvalid(uint8(), {int8(), int16(), int32(), int64()}, options);
+ CheckUnify(uint16(), {uint32(), uint64()}, options);
+ CheckUnify(int16(), {int32(), int64()}, options);
+ CheckUnifyFailsInvalid(uint16(), {int16(), int32(), int64()}, options);
+ CheckUnify(uint32(), {uint64()}, options);
+ CheckUnify(int32(), {int64()}, options);
+ CheckUnifyFailsInvalid(uint32(), {int32(), int64()}, options);
+ CheckUnifyFailsInvalid(uint64(), {int64()}, options);
+
+ options.promote_integer_sign = true;
+ options.promote_integer_to_float = false;
+ CheckUnifyFailsInvalid(IntTypes(), FloatingPointTypes(), options);
+
+ options.promote_integer_to_float = true;
+ options.promote_numeric_width = false;
+ CheckUnifyFailsInvalid(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFailsInvalid(int16(), {int32(), int64()}, options);
+ CheckUnifyFailsInvalid(int32(), {int64()}, options);
+ CheckUnify(int32(), {float32()}, options);
+ CheckUnify(int64(), {float64()}, options);
+ CheckUnify(int32(), float16(), float32(), options);
+}
+
+TEST_F(TestUnifySchemas, Decimal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_decimal_to_float = true;
+ CheckUnify(decimal128(3, 2), {float32(), float64()}, options);
+ CheckUnify(decimal256(3, 2), {float32(), float64()}, options);
+
+ options.promote_integer_to_decimal = true;
+ CheckUnify(int32(), decimal128(3, 2), decimal128(12, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(10, 0), options);
+
+ options.promote_decimal = true;
+ CheckUnify(decimal128(3, 2), decimal128(5, 2), decimal128(5, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 3), decimal128(5, 3), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 1), decimal128(6, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, -2), decimal128(9, 2), options);
+ CheckUnify(decimal128(3, -2), decimal128(5, -2), decimal128(5, -2), options);
+ CheckUnify(decimal128(38, 10), decimal128(38, 5), decimal256(43, 10), options);
+
+ CheckUnify(decimal256(3, 2), decimal256(5, 2), decimal256(5, 2), options);
+ CheckUnify(decimal256(3, 2), decimal256(5, 3), decimal256(5, 3), options);
+ CheckUnify(decimal256(3, 2), decimal256(5, 1), decimal256(6, 2), options);
+ CheckUnify(decimal256(3, 2), decimal256(5, -2), decimal256(9, 2), options);
+ CheckUnify(decimal256(3, -2), decimal256(5, -2), decimal256(5, -2), options);
+
+ // int32() is essentially decimal128(10, 0)
+ CheckUnify(int32(), decimal128(3, 2), decimal128(12, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(10, 0), options);
+ CheckUnify(int64(), decimal128(38, 37), decimal256(56, 37), options);
+
+ CheckUnifyFailsTypeError(decimal256(1, 0), decimal128(1, 0), options);
+
+ options.promote_numeric_width = true;
+ CheckUnify(decimal128(3, 2), decimal256(5, 2), decimal256(5, 2), options);
+ CheckUnify(int32(), decimal128(38, 37), decimal256(47, 37), options);
+ CheckUnifyFailsInvalid(decimal128(38, 10), decimal256(76, 5), options);
+
+ CheckUnifyFailsInvalid(int64(), decimal256(76, 75), options);
+}
+
+TEST_F(TestUnifySchemas, Temporal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_temporal_unit = true;
+ CheckUnify(date32(), {date64()}, options);
+
+ CheckUnify(time32(TimeUnit::SECOND),
+ {time32(TimeUnit::MILLI), time64(TimeUnit::MICRO), time64(TimeUnit::NANO)},
+ options);
+ CheckUnify(time32(TimeUnit::MILLI), {time64(TimeUnit::MICRO), time64(TimeUnit::NANO)},
+ options);
+ CheckUnify(time64(TimeUnit::MICRO), {time64(TimeUnit::NANO)}, options);
+
+ CheckUnify(
+ duration(TimeUnit::SECOND),
+ {duration(TimeUnit::MILLI), duration(TimeUnit::MICRO), duration(TimeUnit::NANO)},
+ options);
+ CheckUnify(duration(TimeUnit::MILLI),
+ {duration(TimeUnit::MICRO), duration(TimeUnit::NANO)}, options);
+ CheckUnify(duration(TimeUnit::MICRO), {duration(TimeUnit::NANO)}, options);
+
+ CheckUnify(
+ timestamp(TimeUnit::SECOND),
+ {timestamp(TimeUnit::MILLI), timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO)},
+ options);
+ CheckUnify(timestamp(TimeUnit::MILLI),
+ {timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO)}, options);
+ CheckUnify(timestamp(TimeUnit::MICRO), {timestamp(TimeUnit::NANO)}, options);
+
+ CheckUnifyFailsTypeError(timestamp(TimeUnit::SECOND),
+ timestamp(TimeUnit::SECOND, "UTC"), options);
+ CheckUnifyFailsTypeError(timestamp(TimeUnit::SECOND, "America/New_York"),
+ timestamp(TimeUnit::SECOND, "UTC"), options);
+
+ options.promote_temporal_unit = false;
+ CheckUnifyFailsInvalid(timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO), options);
+}
+
+TEST_F(TestUnifySchemas, Binary) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_binary = true;
+ CheckUnify(utf8(), {large_utf8(), binary(), large_binary()}, options);
+ CheckUnify(binary(), {large_binary()}, options);
+ CheckUnify(fixed_size_binary(2), {fixed_size_binary(2), binary(), large_binary()},
+ options);
+ CheckUnify(fixed_size_binary(2), fixed_size_binary(4), binary(), options);
+
+ options.promote_binary = false;
+ CheckUnifyFailsInvalid({utf8(), binary()}, {large_utf8(), large_binary()});
+ CheckUnifyFailsInvalid(fixed_size_binary(2), BaseBinaryTypes());
+ CheckUnifyFailsInvalid(utf8(), {binary(), large_binary(), fixed_size_binary(2)});
+}
+
+TEST_F(TestUnifySchemas, List) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ CheckUnifyFailsTypeError(fixed_size_list(int8(), 2), {fixed_size_list(int8(), 3)},
+ options);
+
+ options.promote_binary = true;
Review Comment:
I don't understand what `promote_binary` has to do with this?
##########
cpp/src/arrow/type_test.cc:
##########
@@ -892,6 +892,150 @@ class TestUnifySchemas : public TestSchema {
<< lhs_field->ToString() << " vs " << rhs_field->ToString();
}
}
+
+ void CheckUnifyAsymmetric(
+ const std::shared_ptr<Field>& field1, const std::shared_ptr<Field>& field2,
+ const std::shared_ptr<Field>& expected,
+ const Field::MergeOptions& options = Field::MergeOptions::Defaults()) {
+ ARROW_SCOPED_TRACE("options: ", options);
+ ARROW_SCOPED_TRACE("field2: ", field2->ToString());
+ ARROW_SCOPED_TRACE("field1: ", field1->ToString());
+ ASSERT_OK_AND_ASSIGN(auto merged, field1->MergeWith(field2, options));
+ AssertFieldEqual(merged, expected);
+ }
+
+ void CheckUnify(const std::shared_ptr<Field>& field1,
+ const std::shared_ptr<Field>& field2,
+ const std::shared_ptr<Field>& expected,
+ const Field::MergeOptions& options = Field::MergeOptions::Defaults()) {
+ CheckUnifyAsymmetric(field1, field2, expected, options);
+ CheckUnifyAsymmetric(field2, field1, expected, options);
+ }
+
+ void CheckUnifyFailsInvalid(
+ const std::shared_ptr<Field>& field1, const std::shared_ptr<Field>& field2,
+ const Field::MergeOptions& options = Field::MergeOptions::Defaults()) {
+ ARROW_SCOPED_TRACE("options: ", options);
+ ARROW_SCOPED_TRACE("field2: ", field2->ToString());
+ ARROW_SCOPED_TRACE("field1: ", field1->ToString());
+ ASSERT_RAISES(Invalid, field1->MergeWith(field2, options));
+ ASSERT_RAISES(Invalid, field2->MergeWith(field1, options));
+ }
+
+ void CheckUnifyFailsTypeError(
+ const std::shared_ptr<Field>& field1, const std::shared_ptr<Field>& field2,
+ const Field::MergeOptions& options = Field::MergeOptions::Defaults()) {
+ ARROW_SCOPED_TRACE("options: ", options);
+ ARROW_SCOPED_TRACE("field2: ", field2->ToString());
+ ARROW_SCOPED_TRACE("field1: ", field1->ToString());
+ ASSERT_RAISES(TypeError, field1->MergeWith(field2, options));
+ ASSERT_RAISES(TypeError, field2->MergeWith(field1, options));
+ }
+
+ void CheckUnify(const std::shared_ptr<DataType>& left,
+ const std::shared_ptr<DataType>& right,
+ const std::shared_ptr<DataType>& expected,
+ const Field::MergeOptions& options = Field::MergeOptions::Defaults()) {
+ auto field1 = field("a", left);
+ auto field2 = field("a", right);
+ CheckUnify(field1, field2, field("a", expected), options);
+
+ field1 = field("a", left, /*nullable=*/false);
+ field2 = field("a", right, /*nullable=*/false);
+ CheckUnify(field1, field2, field("a", expected, /*nullable=*/false), options);
+
+ field1 = field("a", left);
+ field2 = field("a", right, /*nullable=*/false);
+ CheckUnify(field1, field2, field("a", expected, /*nullable=*/true), options);
+
+ field1 = field("a", left, /*nullable=*/false);
+ field2 = field("a", right);
+ CheckUnify(field1, field2, field("a", expected, /*nullable=*/true), options);
+ }
+
+ void CheckUnifyAsymmetric(
+ const std::shared_ptr<DataType>& left, const std::shared_ptr<DataType>& right,
+ const std::shared_ptr<DataType>& expected,
+ const Field::MergeOptions& options = Field::MergeOptions::Defaults()) {
+ auto field1 = field("a", left);
+ auto field2 = field("a", right);
+ CheckUnifyAsymmetric(field1, field2, field("a", expected), options);
+
+ field1 = field("a", left, /*nullable=*/false);
+ field2 = field("a", right, /*nullable=*/false);
+ CheckUnifyAsymmetric(field1, field2, field("a", expected, /*nullable=*/false),
+ options);
+
+ field1 = field("a", left);
+ field2 = field("a", right, /*nullable=*/false);
+ CheckUnifyAsymmetric(field1, field2, field("a", expected, /*nullable=*/true),
+ options);
+
+ field1 = field("a", left, /*nullable=*/false);
+ field2 = field("a", right);
+ CheckUnifyAsymmetric(field1, field2, field("a", expected, /*nullable=*/true),
+ options);
+ }
+
+ void CheckUnify(const std::shared_ptr<DataType>& from,
+ const std::vector<std::shared_ptr<DataType>>& to,
+ const Field::MergeOptions& options = Field::MergeOptions::Defaults()) {
+ for (const auto& ty : to) {
+ CheckUnify(from, ty, ty, options);
+ }
+ }
+
+ void CheckUnifyFailsInvalid(
+ const std::shared_ptr<DataType>& left, const std::shared_ptr<DataType>& right,
+ const Field::MergeOptions& options = Field::MergeOptions::Defaults()) {
+ auto field1 = field("a", left);
+ auto field2 = field("a", right);
+ CheckUnifyFailsInvalid(field1, field2, options);
+ }
+
+ void CheckUnifyFailsInvalid(
Review Comment:
Not suee this overload is useful since you can just pass both arguments as vectors?
##########
cpp/src/arrow/type_test.cc:
##########
@@ -892,6 +892,150 @@ class TestUnifySchemas : public TestSchema {
<< lhs_field->ToString() << " vs " << rhs_field->ToString();
}
}
+
+ void CheckUnifyAsymmetric(
+ const std::shared_ptr<Field>& field1, const std::shared_ptr<Field>& field2,
+ const std::shared_ptr<Field>& expected,
+ const Field::MergeOptions& options = Field::MergeOptions::Defaults()) {
+ ARROW_SCOPED_TRACE("options: ", options);
+ ARROW_SCOPED_TRACE("field2: ", field2->ToString());
+ ARROW_SCOPED_TRACE("field1: ", field1->ToString());
+ ASSERT_OK_AND_ASSIGN(auto merged, field1->MergeWith(field2, options));
+ AssertFieldEqual(merged, expected);
+ }
+
+ void CheckUnify(const std::shared_ptr<Field>& field1,
+ const std::shared_ptr<Field>& field2,
+ const std::shared_ptr<Field>& expected,
+ const Field::MergeOptions& options = Field::MergeOptions::Defaults()) {
+ CheckUnifyAsymmetric(field1, field2, expected, options);
+ CheckUnifyAsymmetric(field2, field1, expected, options);
+ }
+
+ void CheckUnifyFailsInvalid(
+ const std::shared_ptr<Field>& field1, const std::shared_ptr<Field>& field2,
+ const Field::MergeOptions& options = Field::MergeOptions::Defaults()) {
+ ARROW_SCOPED_TRACE("options: ", options);
+ ARROW_SCOPED_TRACE("field2: ", field2->ToString());
+ ARROW_SCOPED_TRACE("field1: ", field1->ToString());
+ ASSERT_RAISES(Invalid, field1->MergeWith(field2, options));
+ ASSERT_RAISES(Invalid, field2->MergeWith(field1, options));
+ }
+
+ void CheckUnifyFailsTypeError(
+ const std::shared_ptr<Field>& field1, const std::shared_ptr<Field>& field2,
+ const Field::MergeOptions& options = Field::MergeOptions::Defaults()) {
+ ARROW_SCOPED_TRACE("options: ", options);
+ ARROW_SCOPED_TRACE("field2: ", field2->ToString());
+ ARROW_SCOPED_TRACE("field1: ", field1->ToString());
+ ASSERT_RAISES(TypeError, field1->MergeWith(field2, options));
+ ASSERT_RAISES(TypeError, field2->MergeWith(field1, options));
+ }
+
+ void CheckUnify(const std::shared_ptr<DataType>& left,
+ const std::shared_ptr<DataType>& right,
+ const std::shared_ptr<DataType>& expected,
+ const Field::MergeOptions& options = Field::MergeOptions::Defaults()) {
+ auto field1 = field("a", left);
+ auto field2 = field("a", right);
+ CheckUnify(field1, field2, field("a", expected), options);
+
+ field1 = field("a", left, /*nullable=*/false);
+ field2 = field("a", right, /*nullable=*/false);
+ CheckUnify(field1, field2, field("a", expected, /*nullable=*/false), options);
+
+ field1 = field("a", left);
+ field2 = field("a", right, /*nullable=*/false);
+ CheckUnify(field1, field2, field("a", expected, /*nullable=*/true), options);
+
+ field1 = field("a", left, /*nullable=*/false);
+ field2 = field("a", right);
+ CheckUnify(field1, field2, field("a", expected, /*nullable=*/true), options);
+ }
+
+ void CheckUnifyAsymmetric(
+ const std::shared_ptr<DataType>& left, const std::shared_ptr<DataType>& right,
+ const std::shared_ptr<DataType>& expected,
+ const Field::MergeOptions& options = Field::MergeOptions::Defaults()) {
+ auto field1 = field("a", left);
+ auto field2 = field("a", right);
+ CheckUnifyAsymmetric(field1, field2, field("a", expected), options);
+
+ field1 = field("a", left, /*nullable=*/false);
+ field2 = field("a", right, /*nullable=*/false);
+ CheckUnifyAsymmetric(field1, field2, field("a", expected, /*nullable=*/false),
+ options);
+
+ field1 = field("a", left);
+ field2 = field("a", right, /*nullable=*/false);
+ CheckUnifyAsymmetric(field1, field2, field("a", expected, /*nullable=*/true),
+ options);
+
+ field1 = field("a", left, /*nullable=*/false);
+ field2 = field("a", right);
+ CheckUnifyAsymmetric(field1, field2, field("a", expected, /*nullable=*/true),
+ options);
+ }
+
+ void CheckUnify(const std::shared_ptr<DataType>& from,
Review Comment:
For clarity, name it `CheckPromoteTo`? Otherwise it's a bit difficult to understand what happens when reading at the call site.
##########
cpp/src/arrow/type_test.cc:
##########
@@ -892,6 +892,150 @@ class TestUnifySchemas : public TestSchema {
<< lhs_field->ToString() << " vs " << rhs_field->ToString();
}
}
+
+ void CheckUnifyAsymmetric(
+ const std::shared_ptr<Field>& field1, const std::shared_ptr<Field>& field2,
+ const std::shared_ptr<Field>& expected,
+ const Field::MergeOptions& options = Field::MergeOptions::Defaults()) {
+ ARROW_SCOPED_TRACE("options: ", options);
+ ARROW_SCOPED_TRACE("field2: ", field2->ToString());
+ ARROW_SCOPED_TRACE("field1: ", field1->ToString());
+ ASSERT_OK_AND_ASSIGN(auto merged, field1->MergeWith(field2, options));
+ AssertFieldEqual(merged, expected);
+ }
+
+ void CheckUnify(const std::shared_ptr<Field>& field1,
+ const std::shared_ptr<Field>& field2,
+ const std::shared_ptr<Field>& expected,
+ const Field::MergeOptions& options = Field::MergeOptions::Defaults()) {
+ CheckUnifyAsymmetric(field1, field2, expected, options);
+ CheckUnifyAsymmetric(field2, field1, expected, options);
+ }
+
+ void CheckUnifyFailsInvalid(
+ const std::shared_ptr<Field>& field1, const std::shared_ptr<Field>& field2,
+ const Field::MergeOptions& options = Field::MergeOptions::Defaults()) {
+ ARROW_SCOPED_TRACE("options: ", options);
+ ARROW_SCOPED_TRACE("field2: ", field2->ToString());
+ ARROW_SCOPED_TRACE("field1: ", field1->ToString());
+ ASSERT_RAISES(Invalid, field1->MergeWith(field2, options));
+ ASSERT_RAISES(Invalid, field2->MergeWith(field1, options));
+ }
+
+ void CheckUnifyFailsTypeError(
+ const std::shared_ptr<Field>& field1, const std::shared_ptr<Field>& field2,
+ const Field::MergeOptions& options = Field::MergeOptions::Defaults()) {
Review Comment:
Same idea here :-)
##########
cpp/src/arrow/type_test.cc:
##########
@@ -983,6 +1091,242 @@ TEST_F(TestUnifySchemas, MoreSchemas) {
utf8_field->WithNullable(true)}));
}
+TEST_F(TestUnifySchemas, Numeric) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ CheckUnify(uint8(),
+ {int8(), uint16(), int16(), uint32(), int32(), uint64(), int64(), float32(),
+ float64()},
+ options);
+ CheckUnify(int8(), {int16(), int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint16(),
+ {int16(), uint32(), int32(), uint64(), int64(), float32(), float64()},
+ options);
+ CheckUnify(int16(), {int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint32(), {int32(), uint64(), int64(), float32(), float64()}, options);
+ CheckUnify(int32(), {int64(), float32(), float64()}, options);
+ CheckUnify(uint64(), {int64(), float64()}, options);
+ CheckUnify(int64(), {float64()}, options);
+ CheckUnify(float16(), {float32(), float64()}, options);
+ CheckUnify(float32(), {float64()}, options);
+ CheckUnify(uint64(), float32(), float64(), options);
+ CheckUnify(int64(), float32(), float64(), options);
+
+ options.promote_integer_sign = false;
+ CheckUnify(uint8(), {uint16(), uint32(), uint64()}, options);
+ CheckUnify(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(uint8(), {int8(), int16(), int32(), int64()}, options);
+ CheckUnify(uint16(), {uint32(), uint64()}, options);
+ CheckUnify(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(uint16(), {int16(), int32(), int64()}, options);
+ CheckUnify(uint32(), {uint64()}, options);
+ CheckUnify(int32(), {int64()}, options);
+ CheckUnifyFails(uint32(), {int32(), int64()}, options);
+ CheckUnifyFails(uint64(), {int64()}, options);
+
+ options.promote_integer_sign = true;
+ options.promote_integer_float = false;
+ CheckUnifyFails(IntTypes(), FloatingPointTypes(), options);
+
+ options.promote_integer_float = true;
+ options.promote_numeric_width = false;
+ CheckUnifyFails(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(int32(), {int64()}, options);
+}
+
+TEST_F(TestUnifySchemas, Decimal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_decimal_float = true;
+ CheckUnify(decimal128(3, 2), {float32(), float64()}, options);
+ CheckUnify(decimal256(3, 2), {float32(), float64()}, options);
+
+ options.promote_integer_decimal = true;
+ CheckUnify(int32(), decimal128(3, 2), decimal128(3, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(3, -2), options);
+
+ options.promote_decimal = true;
+ CheckUnify(decimal128(3, 2), decimal128(5, 2), decimal128(5, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 3), decimal128(5, 3), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 1), decimal128(6, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, -2), decimal128(9, 2), options);
+ CheckUnify(decimal128(3, -2), decimal128(5, -2), decimal128(5, -2), options);
+
+ // int32() is essentially decimal128(10, 0)
+ CheckUnify(int32(), decimal128(3, 2), decimal128(12, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(10, 0), options);
+
+ CheckUnifyFails(decimal256(1, 0), decimal128(1, 0), options);
+ CheckUnifyFails(int64(), decimal128(38, 37), options);
+
+ options.promote_numeric_width = true;
+ CheckUnify(decimal128(3, 2), decimal256(5, 2), decimal256(5, 2), options);
+ CheckUnify(int32(), decimal128(38, 37), decimal256(47, 37), options);
+
+ CheckUnifyFails(int64(), decimal256(76, 75), options);
+}
+
+TEST_F(TestUnifySchemas, Temporal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_date = true;
+ CheckUnify(date32(), {date64()}, options);
+
+ options.promote_time = true;
+ CheckUnify(time32(TimeUnit::SECOND),
+ {time32(TimeUnit::MILLI), time64(TimeUnit::MICRO), time64(TimeUnit::NANO)},
+ options);
+ CheckUnify(time32(TimeUnit::MILLI), {time64(TimeUnit::MICRO), time64(TimeUnit::NANO)},
+ options);
+ CheckUnify(time64(TimeUnit::MICRO), {time64(TimeUnit::NANO)}, options);
+
+ options.promote_duration = true;
+ CheckUnify(
+ duration(TimeUnit::SECOND),
+ {duration(TimeUnit::MILLI), duration(TimeUnit::MICRO), duration(TimeUnit::NANO)},
+ options);
+ CheckUnify(duration(TimeUnit::MILLI),
+ {duration(TimeUnit::MICRO), duration(TimeUnit::NANO)}, options);
+ CheckUnify(duration(TimeUnit::MICRO), {duration(TimeUnit::NANO)}, options);
+
+ options.promote_timestamp = true;
+ CheckUnify(
+ timestamp(TimeUnit::SECOND),
+ {timestamp(TimeUnit::MILLI), timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO)},
+ options);
+ CheckUnify(timestamp(TimeUnit::MILLI),
+ {timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO)}, options);
+ CheckUnify(timestamp(TimeUnit::MICRO), {timestamp(TimeUnit::NANO)}, options);
+
+ CheckUnifyFails(timestamp(TimeUnit::SECOND), timestamp(TimeUnit::SECOND, "UTC"),
+ options);
+ CheckUnifyFails(timestamp(TimeUnit::SECOND, "America/New_York"),
+ timestamp(TimeUnit::SECOND, "UTC"), options);
+}
+
+TEST_F(TestUnifySchemas, Binary) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_large = true;
+ options.promote_binary = true;
+ CheckUnify(utf8(), {large_utf8(), binary(), large_binary()}, options);
+ CheckUnify(binary(), {large_binary()}, options);
+ CheckUnify(fixed_size_binary(2), {fixed_size_binary(2), binary(), large_binary()},
+ options);
+ CheckUnify(fixed_size_binary(2), fixed_size_binary(4), binary(), options);
+
+ options.promote_large = false;
+ CheckUnifyFails({utf8(), binary()}, {large_utf8(), large_binary()});
+ CheckUnifyFails(fixed_size_binary(2), BaseBinaryTypes());
+
+ options.promote_binary = false;
+ CheckUnifyFails(utf8(), {binary(), large_binary(), fixed_size_binary(2)});
+}
+
+TEST_F(TestUnifySchemas, List) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ CheckUnifyFails(fixed_size_list(int8(), 2),
+ {fixed_size_list(int8(), 3), list(int8()), large_list(int8())},
+ options);
+
+ options.promote_large = true;
+ CheckUnify(list(int8()), {large_list(int8())}, options);
+ CheckUnify(fixed_size_list(int8(), 2), {list(int8()), large_list(int8())}, options);
+
+ options.promote_nested = true;
+ CheckUnify(list(int8()), {list(int16()), list(int32()), list(int64())}, options);
+ CheckUnify(fixed_size_list(int8(), 2),
+ {fixed_size_list(int16(), 2), list(int16()), list(int32()), list(int64())},
+ options);
+
+ auto ty = list(field("foo", int8(), /*nullable=*/false));
+ CheckUnifyAsymmetric(ty, list(int8()), list(field("foo", int8(), /*nullable=*/true)),
+ options);
+ CheckUnifyAsymmetric(ty, list(field("bar", int16(), /*nullable=*/false)),
+ list(field("foo", int16(), /*nullable=*/false)), options);
+}
+
+TEST_F(TestUnifySchemas, Map) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_nested = true;
+ options.promote_numeric_width = true;
+
+ CheckUnify(map(int8(), int32()),
+ {map(int8(), int64()), map(int16(), int32()), map(int64(), int64())},
+ options);
+
+ // Do not test field names, since MapType intentionally ignores them in comparisons
+ // See ARROW-7173, ARROW-14999
+ auto ty = map(field("key", int8(), /*nullable=*/false),
+ field("value", int32(), /*nullable=*/false));
+ CheckUnify(ty, map(int8(), int32()),
+ map(field("key", int8(), /*nullable=*/true),
+ field("value", int32(), /*nullable=*/true)),
+ options);
+ CheckUnify(ty,
+ map(field("key", int16(), /*nullable=*/false),
+ field("value", int64(), /*nullable=*/false)),
+ map(field("key", int16(), /*nullable=*/false),
+ field("value", int64(), /*nullable=*/false)),
+ options);
+}
+
+TEST_F(TestUnifySchemas, Struct) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_nested = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+
+ CheckUnify(struct_({}), struct_({field("a", int8())}), struct_({field("a", int8())}),
+ options);
+
+ CheckUnifyAsymmetric(struct_({field("b", utf8())}), struct_({field("a", int8())}),
+ struct_({field("b", utf8()), field("a", int8())}), options);
+ CheckUnifyAsymmetric(struct_({field("a", int8())}), struct_({field("b", utf8())}),
+ struct_({field("a", int8()), field("b", utf8())}), options);
+
+ CheckUnify(struct_({field("b", utf8())}), struct_({field("b", binary())}),
+ struct_({field("b", binary())}), options);
+
+ CheckUnifyAsymmetric(
+ struct_({field("a", int8()), field("b", utf8()), field("a", int64())}),
+ struct_({field("b", binary())}),
+ struct_({field("a", int8()), field("b", binary()), field("a", int64())}), options);
+
+ ASSERT_RAISES(
+ Invalid,
+ field("foo", struct_({field("a", int8()), field("b", utf8()), field("a", int64())}))
+ ->MergeWith(field("foo", struct_({field("a", int64())})), options));
+}
+
+TEST_F(TestUnifySchemas, Dictionary) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_dictionary = true;
+ options.promote_large = true;
+
+ CheckUnify(dictionary(int8(), utf8()),
+ {
+ dictionary(int64(), utf8()),
+ dictionary(int8(), large_utf8()),
+ },
+ options);
+ CheckUnify(dictionary(int8(), utf8(), /*ordered=*/true),
+ {
+ dictionary(int64(), utf8(), /*ordered=*/true),
+ dictionary(int8(), large_utf8(), /*ordered=*/true),
+ },
+ options);
Review Comment:
Ping on this.
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_temporal_unit) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(std::max(left.unit(), right.unit()));
+ }
+
+ if (options.promote_temporal_unit && is_time(promoted_type->id()) &&
+ is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = std::max(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::TypeError(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::TypeError("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(std::max(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-numeric types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_to_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_to_decimal &&
+ ((is_decimal(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_decimal(other_type->id()) && is_integer(promoted_type->id())))) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ // Other type is always the int
+ promoted_type.swap(other_type);
+ }
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(const auto promoted_decimal,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, promoted_decimal));
+ return promoted_type;
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const DecimalType& left = checked_cast<const DecimalType&>(*promoted_type);
+ const DecimalType& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::TypeError(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, other_type));
+ return promoted_type;
+ }
+
+ if (options.promote_integer_sign && ((is_unsigned_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) ||
+ (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
+ } else if (max_width >= 16) {
+ promoted_type = int16();
+ } else {
+ promoted_type = int8();
+ }
+ return promoted_type;
+ }
+
+ if (options.promote_integer_to_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ }
+
+ if (options.promote_numeric_width) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (is_floating(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
+ } else if (max_width >= 16) {
+ promoted_type = int16();
+ } else {
+ promoted_type = int8();
+ }
+ } else if (is_unsigned_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = uint64();
+ } else if (max_width >= 32) {
+ promoted_type = uint32();
+ } else if (max_width >= 16) {
+ promoted_type = uint16();
+ } else {
+ promoted_type = uint8();
+ }
+ }
+ }
+
+ return promoted ? promoted_type : nullptr;
+}
+
+// Merge temporal types based on options. Returns nullptr for non-binary types.
+Result<std::shared_ptr<DataType>> MaybeMergeBinaryTypes(
+ std::shared_ptr<DataType>& promoted_type, std::shared_ptr<DataType>& other_type,
+ const Field::MergeOptions& options) {
+ if (options.promote_binary) {
+ if (other_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(promoted_type->id())) {
+ return MakeBinary(*promoted_type);
+ } else if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(other_type->id())) {
+ return MakeBinary(*other_type);
+ } else if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ other_type->id() == Type::FIXED_SIZE_BINARY) {
+ return binary();
+ } else if (is_string(promoted_type->id()) && is_binary(other_type->id())) {
+ return MakeBinary(*other_type);
+ } else if (is_binary(promoted_type->id()) && is_string(other_type->id())) {
+ return MakeBinary(*promoted_type);
+ }
+
+ if ((promoted_type->id() == Type::STRING && other_type->id() == Type::LARGE_STRING) ||
+ (promoted_type->id() == Type::LARGE_STRING && other_type->id() == Type::STRING)) {
+ return large_utf8();
+ } else if ((promoted_type->id() == Type::BINARY &&
+ other_type->id() == Type::LARGE_BINARY) ||
+ (promoted_type->id() == Type::LARGE_BINARY &&
+ other_type->id() == Type::BINARY)) {
+ return large_binary();
+ }
+ }
+
+ return nullptr;
+}
+
+// Merge list types based on options. Returns nullptr for non-list types.
+Result<std::shared_ptr<DataType>> MaybeMergeListTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ bool promoted = false;
+
+ if (promoted_type->id() == Type::FIXED_SIZE_LIST &&
+ other_type->id() == Type::FIXED_SIZE_LIST) {
+ const auto& left = checked_cast<const FixedSizeListType&>(*promoted_type);
+ const auto& right = checked_cast<const FixedSizeListType&>(*other_type);
+ ARROW_ASSIGN_OR_RAISE(
+ auto value_field,
+ left.value_field()->MergeWith(
+ *right.value_field()->WithName(left.value_field()->name()), options));
+ if (left.list_size() == right.list_size()) {
+ return fixed_size_list(std::move(value_field), left.list_size());
+ }
+ return Status::TypeError("Cannot merge fixed_size_list of different sizes");
+ } else if (promoted_type->id() == Type::MAP && other_type->id() == Type::MAP) {
+ const auto& left = checked_cast<const MapType&>(*promoted_type);
+ const auto& right = checked_cast<const MapType&>(*other_type);
+ ARROW_ASSIGN_OR_RAISE(
+ auto key_field,
+ left.key_field()->MergeWith(
+ *right.key_field()->WithName(left.key_field()->name()), options));
+ ARROW_ASSIGN_OR_RAISE(
+ auto item_field,
+ left.item_field()->MergeWith(
+ *right.item_field()->WithName(left.item_field()->name()), options));
+ return map(std::move(key_field->type()), std::move(item_field),
+ /*keys_sorted=*/left.keys_sorted() && right.keys_sorted());
+ } else if (is_list(promoted_type->id()) && is_list(other_type->id())) {
+ const auto& left = checked_cast<const BaseListType&>(*promoted_type);
+ const auto& right = checked_cast<const BaseListType&>(*other_type);
+ ARROW_ASSIGN_OR_RAISE(
+ auto value_field,
+ left.value_field()->MergeWith(
+ *right.value_field()->WithName(left.value_field()->name()), options));
+ if (promoted_type->id() == Type::LARGE_LIST || other_type->id() == Type::LARGE_LIST) {
+ return large_list(std::move(value_field));
+ } else {
+ return list(std::move(value_field));
+ }
+ } else if (promoted_type->id() == Type::STRUCT && other_type->id() == Type::STRUCT) {
Review Comment:
I'm surprised that this appears in `MaybeMergeListTypes`. Perhaps a separate helper function is desired for clarity?
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_temporal_unit) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(std::max(left.unit(), right.unit()));
+ }
+
+ if (options.promote_temporal_unit && is_time(promoted_type->id()) &&
+ is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = std::max(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::TypeError(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::TypeError("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(std::max(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-numeric types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_to_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_to_decimal &&
+ ((is_decimal(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_decimal(other_type->id()) && is_integer(promoted_type->id())))) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ // Other type is always the int
+ promoted_type.swap(other_type);
+ }
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(const auto promoted_decimal,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, promoted_decimal));
+ return promoted_type;
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const DecimalType& left = checked_cast<const DecimalType&>(*promoted_type);
+ const DecimalType& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::TypeError(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, other_type));
+ return promoted_type;
+ }
+
+ if (options.promote_integer_sign && ((is_unsigned_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) ||
+ (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
+ } else if (max_width >= 16) {
+ promoted_type = int16();
+ } else {
+ promoted_type = int8();
+ }
+ return promoted_type;
+ }
+
+ if (options.promote_integer_to_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ }
+
+ if (options.promote_numeric_width) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (is_floating(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
+ } else if (max_width >= 16) {
+ promoted_type = int16();
+ } else {
+ promoted_type = int8();
+ }
+ } else if (is_unsigned_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = uint64();
+ } else if (max_width >= 32) {
+ promoted_type = uint32();
+ } else if (max_width >= 16) {
+ promoted_type = uint16();
+ } else {
+ promoted_type = uint8();
+ }
+ }
+ }
+
+ return promoted ? promoted_type : nullptr;
+}
+
+// Merge temporal types based on options. Returns nullptr for non-binary types.
+Result<std::shared_ptr<DataType>> MaybeMergeBinaryTypes(
+ std::shared_ptr<DataType>& promoted_type, std::shared_ptr<DataType>& other_type,
+ const Field::MergeOptions& options) {
+ if (options.promote_binary) {
+ if (other_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(promoted_type->id())) {
+ return MakeBinary(*promoted_type);
+ } else if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(other_type->id())) {
+ return MakeBinary(*other_type);
+ } else if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ other_type->id() == Type::FIXED_SIZE_BINARY) {
+ return binary();
+ } else if (is_string(promoted_type->id()) && is_binary(other_type->id())) {
+ return MakeBinary(*other_type);
+ } else if (is_binary(promoted_type->id()) && is_string(other_type->id())) {
+ return MakeBinary(*promoted_type);
+ }
+
+ if ((promoted_type->id() == Type::STRING && other_type->id() == Type::LARGE_STRING) ||
+ (promoted_type->id() == Type::LARGE_STRING && other_type->id() == Type::STRING)) {
+ return large_utf8();
+ } else if ((promoted_type->id() == Type::BINARY &&
+ other_type->id() == Type::LARGE_BINARY) ||
+ (promoted_type->id() == Type::LARGE_BINARY &&
+ other_type->id() == Type::BINARY)) {
+ return large_binary();
+ }
+ }
+
+ return nullptr;
+}
+
+// Merge list types based on options. Returns nullptr for non-list types.
+Result<std::shared_ptr<DataType>> MaybeMergeListTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ bool promoted = false;
+
+ if (promoted_type->id() == Type::FIXED_SIZE_LIST &&
+ other_type->id() == Type::FIXED_SIZE_LIST) {
+ const auto& left = checked_cast<const FixedSizeListType&>(*promoted_type);
+ const auto& right = checked_cast<const FixedSizeListType&>(*other_type);
+ ARROW_ASSIGN_OR_RAISE(
+ auto value_field,
+ left.value_field()->MergeWith(
+ *right.value_field()->WithName(left.value_field()->name()), options));
+ if (left.list_size() == right.list_size()) {
+ return fixed_size_list(std::move(value_field), left.list_size());
+ }
+ return Status::TypeError("Cannot merge fixed_size_list of different sizes");
Review Comment:
Why not let them promote to a var-size list?
We promote if merging a fixed-size list and a var-size list, AFAICT.
##########
cpp/src/arrow/type_test.cc:
##########
@@ -983,6 +1091,242 @@ TEST_F(TestUnifySchemas, MoreSchemas) {
utf8_field->WithNullable(true)}));
}
+TEST_F(TestUnifySchemas, Numeric) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ CheckUnify(uint8(),
+ {int8(), uint16(), int16(), uint32(), int32(), uint64(), int64(), float32(),
+ float64()},
+ options);
+ CheckUnify(int8(), {int16(), int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint16(),
+ {int16(), uint32(), int32(), uint64(), int64(), float32(), float64()},
+ options);
+ CheckUnify(int16(), {int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint32(), {int32(), uint64(), int64(), float32(), float64()}, options);
+ CheckUnify(int32(), {int64(), float32(), float64()}, options);
+ CheckUnify(uint64(), {int64(), float64()}, options);
+ CheckUnify(int64(), {float64()}, options);
+ CheckUnify(float16(), {float32(), float64()}, options);
+ CheckUnify(float32(), {float64()}, options);
+ CheckUnify(uint64(), float32(), float64(), options);
+ CheckUnify(int64(), float32(), float64(), options);
+
+ options.promote_integer_sign = false;
+ CheckUnify(uint8(), {uint16(), uint32(), uint64()}, options);
+ CheckUnify(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(uint8(), {int8(), int16(), int32(), int64()}, options);
+ CheckUnify(uint16(), {uint32(), uint64()}, options);
+ CheckUnify(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(uint16(), {int16(), int32(), int64()}, options);
+ CheckUnify(uint32(), {uint64()}, options);
+ CheckUnify(int32(), {int64()}, options);
+ CheckUnifyFails(uint32(), {int32(), int64()}, options);
+ CheckUnifyFails(uint64(), {int64()}, options);
+
+ options.promote_integer_sign = true;
+ options.promote_integer_float = false;
+ CheckUnifyFails(IntTypes(), FloatingPointTypes(), options);
+
+ options.promote_integer_float = true;
+ options.promote_numeric_width = false;
+ CheckUnifyFails(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(int32(), {int64()}, options);
+}
+
+TEST_F(TestUnifySchemas, Decimal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_decimal_float = true;
+ CheckUnify(decimal128(3, 2), {float32(), float64()}, options);
+ CheckUnify(decimal256(3, 2), {float32(), float64()}, options);
+
+ options.promote_integer_decimal = true;
+ CheckUnify(int32(), decimal128(3, 2), decimal128(3, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(3, -2), options);
+
+ options.promote_decimal = true;
+ CheckUnify(decimal128(3, 2), decimal128(5, 2), decimal128(5, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 3), decimal128(5, 3), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 1), decimal128(6, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, -2), decimal128(9, 2), options);
+ CheckUnify(decimal128(3, -2), decimal128(5, -2), decimal128(5, -2), options);
+
+ // int32() is essentially decimal128(10, 0)
+ CheckUnify(int32(), decimal128(3, 2), decimal128(12, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(10, 0), options);
+
+ CheckUnifyFails(decimal256(1, 0), decimal128(1, 0), options);
+ CheckUnifyFails(int64(), decimal128(38, 37), options);
+
+ options.promote_numeric_width = true;
+ CheckUnify(decimal128(3, 2), decimal256(5, 2), decimal256(5, 2), options);
+ CheckUnify(int32(), decimal128(38, 37), decimal256(47, 37), options);
+
+ CheckUnifyFails(int64(), decimal256(76, 75), options);
+}
+
+TEST_F(TestUnifySchemas, Temporal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_date = true;
+ CheckUnify(date32(), {date64()}, options);
+
+ options.promote_time = true;
+ CheckUnify(time32(TimeUnit::SECOND),
+ {time32(TimeUnit::MILLI), time64(TimeUnit::MICRO), time64(TimeUnit::NANO)},
+ options);
+ CheckUnify(time32(TimeUnit::MILLI), {time64(TimeUnit::MICRO), time64(TimeUnit::NANO)},
+ options);
+ CheckUnify(time64(TimeUnit::MICRO), {time64(TimeUnit::NANO)}, options);
+
+ options.promote_duration = true;
+ CheckUnify(
+ duration(TimeUnit::SECOND),
+ {duration(TimeUnit::MILLI), duration(TimeUnit::MICRO), duration(TimeUnit::NANO)},
+ options);
+ CheckUnify(duration(TimeUnit::MILLI),
+ {duration(TimeUnit::MICRO), duration(TimeUnit::NANO)}, options);
+ CheckUnify(duration(TimeUnit::MICRO), {duration(TimeUnit::NANO)}, options);
+
+ options.promote_timestamp = true;
+ CheckUnify(
+ timestamp(TimeUnit::SECOND),
+ {timestamp(TimeUnit::MILLI), timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO)},
+ options);
+ CheckUnify(timestamp(TimeUnit::MILLI),
+ {timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO)}, options);
+ CheckUnify(timestamp(TimeUnit::MICRO), {timestamp(TimeUnit::NANO)}, options);
+
+ CheckUnifyFails(timestamp(TimeUnit::SECOND), timestamp(TimeUnit::SECOND, "UTC"),
+ options);
+ CheckUnifyFails(timestamp(TimeUnit::SECOND, "America/New_York"),
+ timestamp(TimeUnit::SECOND, "UTC"), options);
+}
+
+TEST_F(TestUnifySchemas, Binary) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_large = true;
+ options.promote_binary = true;
+ CheckUnify(utf8(), {large_utf8(), binary(), large_binary()}, options);
+ CheckUnify(binary(), {large_binary()}, options);
+ CheckUnify(fixed_size_binary(2), {fixed_size_binary(2), binary(), large_binary()},
+ options);
+ CheckUnify(fixed_size_binary(2), fixed_size_binary(4), binary(), options);
+
+ options.promote_large = false;
+ CheckUnifyFails({utf8(), binary()}, {large_utf8(), large_binary()});
+ CheckUnifyFails(fixed_size_binary(2), BaseBinaryTypes());
+
+ options.promote_binary = false;
+ CheckUnifyFails(utf8(), {binary(), large_binary(), fixed_size_binary(2)});
+}
+
+TEST_F(TestUnifySchemas, List) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ CheckUnifyFails(fixed_size_list(int8(), 2),
+ {fixed_size_list(int8(), 3), list(int8()), large_list(int8())},
+ options);
+
+ options.promote_large = true;
+ CheckUnify(list(int8()), {large_list(int8())}, options);
+ CheckUnify(fixed_size_list(int8(), 2), {list(int8()), large_list(int8())}, options);
+
+ options.promote_nested = true;
+ CheckUnify(list(int8()), {list(int16()), list(int32()), list(int64())}, options);
+ CheckUnify(fixed_size_list(int8(), 2),
+ {fixed_size_list(int16(), 2), list(int16()), list(int32()), list(int64())},
+ options);
+
+ auto ty = list(field("foo", int8(), /*nullable=*/false));
+ CheckUnifyAsymmetric(ty, list(int8()), list(field("foo", int8(), /*nullable=*/true)),
+ options);
+ CheckUnifyAsymmetric(ty, list(field("bar", int16(), /*nullable=*/false)),
+ list(field("foo", int16(), /*nullable=*/false)), options);
+}
+
+TEST_F(TestUnifySchemas, Map) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_nested = true;
+ options.promote_numeric_width = true;
+
+ CheckUnify(map(int8(), int32()),
+ {map(int8(), int64()), map(int16(), int32()), map(int64(), int64())},
+ options);
+
+ // Do not test field names, since MapType intentionally ignores them in comparisons
+ // See ARROW-7173, ARROW-14999
+ auto ty = map(field("key", int8(), /*nullable=*/false),
+ field("value", int32(), /*nullable=*/false));
+ CheckUnify(ty, map(int8(), int32()),
+ map(field("key", int8(), /*nullable=*/true),
+ field("value", int32(), /*nullable=*/true)),
+ options);
+ CheckUnify(ty,
+ map(field("key", int16(), /*nullable=*/false),
+ field("value", int64(), /*nullable=*/false)),
+ map(field("key", int16(), /*nullable=*/false),
+ field("value", int64(), /*nullable=*/false)),
+ options);
+}
+
+TEST_F(TestUnifySchemas, Struct) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_nested = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+
+ CheckUnify(struct_({}), struct_({field("a", int8())}), struct_({field("a", int8())}),
+ options);
+
+ CheckUnifyAsymmetric(struct_({field("b", utf8())}), struct_({field("a", int8())}),
+ struct_({field("b", utf8()), field("a", int8())}), options);
+ CheckUnifyAsymmetric(struct_({field("a", int8())}), struct_({field("b", utf8())}),
+ struct_({field("a", int8()), field("b", utf8())}), options);
+
+ CheckUnify(struct_({field("b", utf8())}), struct_({field("b", binary())}),
+ struct_({field("b", binary())}), options);
+
+ CheckUnifyAsymmetric(
+ struct_({field("a", int8()), field("b", utf8()), field("a", int64())}),
+ struct_({field("b", binary())}),
+ struct_({field("a", int8()), field("b", binary()), field("a", int64())}), options);
+
+ ASSERT_RAISES(
+ Invalid,
+ field("foo", struct_({field("a", int8()), field("b", utf8()), field("a", int64())}))
+ ->MergeWith(field("foo", struct_({field("a", int64())})), options));
Review Comment:
For the record, that PR was merged, so you can use it now.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1295673224
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_temporal_unit) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(std::max(left.unit(), right.unit()));
+ }
+
+ if (options.promote_temporal_unit && is_time(promoted_type->id()) &&
+ is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = std::max(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::TypeError(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::TypeError("Cannot merge timestamps with differing timezones");
+ }
Review Comment:
I think that's a good idea, updated the code 👍🏻
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_temporal_unit) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(std::max(left.unit(), right.unit()));
+ }
+
+ if (options.promote_temporal_unit && is_time(promoted_type->id()) &&
+ is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = std::max(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::TypeError(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::TypeError("Cannot merge timestamps with differing timezones");
+ }
Review Comment:
I think that's a good idea, updated the code 👍🏻
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1295841516
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_temporal_unit) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(std::max(left.unit(), right.unit()));
+ }
+
+ if (options.promote_temporal_unit && is_time(promoted_type->id()) &&
+ is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = std::max(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::TypeError(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::TypeError("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(std::max(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-numeric types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_to_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_to_decimal &&
+ ((is_decimal(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_decimal(other_type->id()) && is_integer(promoted_type->id())))) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ // Other type is always the int
+ promoted_type.swap(other_type);
+ }
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(const auto promoted_decimal,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, promoted_decimal));
+ return promoted_type;
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const DecimalType& left = checked_cast<const DecimalType&>(*promoted_type);
+ const DecimalType& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::TypeError(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, other_type));
+ return promoted_type;
+ }
+
+ if (options.promote_integer_sign && ((is_unsigned_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) ||
+ (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
+ } else if (max_width >= 16) {
+ promoted_type = int16();
+ } else {
+ promoted_type = int8();
+ }
+ return promoted_type;
+ }
+
+ if (options.promote_integer_to_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
Review Comment:
Great catch. I've updated the code.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on PR #36846:
URL: https://github.com/apache/arrow/pull/36846#issuecomment-1680842817
@pitrou I took the existing code from https://github.com/apache/arrow/pull/12000 and went from there. For example, if feels to me that you always want to widen the types.
> Well, we shouldn't get rid of existing functionality. So any cast that is already supported should keep being supported (unless it's a glaring mistake of course!).
Well, many formats are much more restrictive than the first iteration here. Take for example Iceberg:

If you want to do anything special, such as combining a float and integer, you first need to cast it explicitly, which seems reasonable to me.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] jorisvandenbossche commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "jorisvandenbossche (via GitHub)" <gi...@apache.org>.
jorisvandenbossche commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1303010836
##########
cpp/src/arrow/table_test.cc:
##########
@@ -520,6 +523,48 @@ TEST_F(ConcatenateTablesWithPromotionTest, Simple) {
AssertTablesEqualUnorderedFields(*expected, *result);
}
+TEST_F(ConcatenateTablesWithPromotionTest, Unify) {
+ auto t1 = TableFromJSON(schema({field("f0", int32())}), {"[[0], [1]]"});
+ auto t2 = TableFromJSON(schema({field("f0", int64())}), {"[[2], [3]]"});
+ auto t3 = TableFromJSON(schema({field("f0", null())}), {"[[null], [null]]"});
+
+ auto expected_int64 =
+ TableFromJSON(schema({field("f0", int64())}), {"[[0], [1], [2], [3]]"});
+ auto expected_null =
+ TableFromJSON(schema({field("f0", int32())}), {"[[0], [1], [null], [null]]"});
+
+ ConcatenateTablesOptions options;
+ EXPECT_RAISES_WITH_MESSAGE_THAT(Invalid,
+ ::testing::HasSubstr("Schema at index 1 was different"),
+ ConcatenateTables({t1, t2}, options));
+ EXPECT_RAISES_WITH_MESSAGE_THAT(Invalid,
+ ::testing::HasSubstr("Schema at index 1 was different"),
+ ConcatenateTables({t1, t3}, options));
+
+ options.unify_schemas = true;
+ EXPECT_RAISES_WITH_MESSAGE_THAT(Invalid,
+ ::testing::HasSubstr("Field f0 has incompatible types"),
+ ConcatenateTables({t1, t2}, options));
+ ASSERT_OK_AND_ASSIGN(auto actual, ConcatenateTables({t1, t3}, options));
+ AssertTablesEqual(*expected_null, *actual, /*same_chunk_layout=*/false);
+
+ options.field_merge_options.promote_numeric_width = true;
+ ASSERT_OK_AND_ASSIGN(actual, ConcatenateTables({t1, t2}, options));
+ AssertTablesEqual(*expected_int64, *actual, /*same_chunk_layout=*/false);
+}
+
+// TEST_F(ConcatenateTablesWithPromotionTest, Overflow) {
Review Comment:
Just a reminder to clean this up or uncomment
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] jorisvandenbossche commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "jorisvandenbossche (via GitHub)" <gi...@apache.org>.
jorisvandenbossche commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1303183156
##########
cpp/src/arrow/type.cc:
##########
@@ -327,6 +315,449 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_list = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_decimal=" << (promote_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_list=" << (promote_list ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_dictionary_ordered="
+ << (promote_dictionary_ordered ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::TypeError(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_temporal_unit) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+
+ if (promoted_type->id() == Type::DURATION && other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(std::max(left.unit(), right.unit()));
+ }
+
+ if (is_time(promoted_type->id()) && is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = std::max(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+ }
+
+ if (promoted_type->id() == Type::TIMESTAMP && other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::TypeError(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::TypeError("Cannot merge timestamps with differing timezones");
+ }
+ if (options.promote_temporal_unit) {
+ return timestamp(std::max(left.unit(), right.unit()), left.timezone());
+ }
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-numeric types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_to_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_to_decimal &&
+ ((is_decimal(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_decimal(other_type->id()) && is_integer(promoted_type->id())))) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ // Other type is always the int
+ promoted_type.swap(other_type);
+ }
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(const auto promoted_decimal,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ ARROW_ASSIGN_OR_RAISE(promoted_type,
+ WidenDecimals(promoted_type, promoted_decimal, options));
+ return promoted_type;
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ ARROW_ASSIGN_OR_RAISE(promoted_type,
+ WidenDecimals(promoted_type, other_type, options));
+ return promoted_type;
+ }
+
+ if (options.promote_integer_sign && ((is_unsigned_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) ||
+ (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())))) {
+ if (!options.promote_numeric_width &&
+ bit_width(promoted_type->id()) != bit_width(other_type->id())) {
+ return Status::TypeError(
+ "Cannot widen (un)signed integers without promote_numeric_width=true");
+ }
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
Review Comment:
This means that `uint32` gets promoted to `int32`? But should that be `int64` instead? (to ensure it can hold all possible uint32 values, which isn't the case for int32)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] jorisvandenbossche commented on pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "jorisvandenbossche (via GitHub)" <gi...@apache.org>.
jorisvandenbossche commented on PR #36846:
URL: https://github.com/apache/arrow/pull/36846#issuecomment-1735229268
Comparing the current branch with numpy promotion rules:
```python
import itertools
import pyarrow as pa
import numpy as np
types = ["uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "float16", "float32", "float64"]
for t1, t2 in itertools.combinations(types, 2):
np_result = np.result_type(t1, t2)
pa_result = pa.unify_schemas([pa.schema([('a', t1)]), pa.schema([('a', t2)])], options="permissive").field('a').type
pa_result_np = np.dtype(pa_result.to_pandas_dtype())
if np_result != pa_result_np:
print(f"{t1} + {t2}\t:\t{np_result} (numpy), {pa_result_np} (arrow)")
```
```
uint8 + int8 : int16 (numpy), int8 (arrow)
uint16 + int8 : int32 (numpy), int16 (arrow)
uint16 + int16 : int32 (numpy), int16 (arrow)
uint32 + int8 : int64 (numpy), int32 (arrow)
uint32 + int16 : int64 (numpy), int32 (arrow)
uint32 + int32 : int64 (numpy), int32 (arrow)
uint64 + int8 : float64 (numpy), int64 (arrow)
uint64 + int16 : float64 (numpy), int64 (arrow)
uint64 + int32 : float64 (numpy), int64 (arrow)
uint64 + int64 : float64 (numpy), int64 (arrow)
```
That shows the issue of widening the bitwidth for int+uint as commented above.
Numpy also seems to go to float when combining uint64 with any signed integer (since uint64 values cannot all be held in int64). Not sure if we should also do that ..
And comparing with our numeric kernels DispatchBest (implemented in `CommonNumeric`, added in https://github.com/apache/arrow/pull/9294):
```python
for t1, t2 in itertools.combinations(types, 2):
result_merge = pa.unify_schemas([pa.schema([('a', t1)]), pa.schema([('a', t2)])], options="permissive").field('a').type
try:
result_dispatch= pa.compute.add(pa.array([1, 2, 3], t1), pa.array(np.array([1, 2, 3], t2), t2)).type
except:
continue
if result_merge != result_dispatch:
print(f"{t1} + {t2}\t:\t{result_merge} (MergeOptions), {result_dispatch} (DispatchBest)")
```
```
uint8 + int8 : int8 (MergeOptions), int16 (DispatchBest)
uint16 + int8 : int16 (MergeOptions), int32 (DispatchBest)
uint16 + int16 : int16 (MergeOptions), int32 (DispatchBest)
uint32 + int8 : int32 (MergeOptions), int64 (DispatchBest)
uint32 + int16 : int32 (MergeOptions), int64 (DispatchBest)
uint32 + int32 : int32 (MergeOptions), int64 (DispatchBest)
uint32 + float32 : double (MergeOptions), float (DispatchBest)
uint64 + float32 : double (MergeOptions), float (DispatchBest)
int32 + float32 : double (MergeOptions), float (DispatchBest)
int64 + float32 : double (MergeOptions), float (DispatchBest)
```
So the numeric kernels already widen the uint+int case. And they do not widen the float bitwidth in the uint+float case (that's maybe something to change in DispatchBest in a follow-up).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1338209884
##########
python/pyarrow/tests/test_table.py:
##########
@@ -1330,6 +1330,22 @@ def test_concat_tables():
assert result.equals(expected)
+def test_concat_tables_permissive():
+ t1 = pa.Table.from_arrays([list(range(10))], names=('a',))
+ t2 = pa.Table.from_arrays([list(range(10, 20))], names=('a',))
+
+ result = pa.concat_tables([t1, t2], field_merge_options="permissive")
Review Comment:
Fair point, updated it to a rainy day situation
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1307200018
##########
python/pyarrow/table.pxi:
##########
@@ -5042,9 +5043,14 @@ def concat_tables(tables, c_bool promote=False, MemoryPool memory_pool=None):
tables : iterable of pyarrow.Table objects
Pyarrow tables to concatenate into a single Table.
promote : bool, default False
- If True, concatenate tables with null-filling and null type promotion.
+ If True, concatenate tables with null-filling and type promotion.
+ See field_merge_options for the type promotion behavior.
Review Comment:
> Essentially the promote=False can be seen as a "no promotion" field merge option?
This is correct, it will only do null-filling for missing columns.
The problem is that the `promote` is only relevant when merging tables, when just upcasting fields, then you don't need this, therefore `merge_options` might not be the best place to put it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1274870707
##########
cpp/src/arrow/type_test.cc:
##########
@@ -983,6 +1091,242 @@ TEST_F(TestUnifySchemas, MoreSchemas) {
utf8_field->WithNullable(true)}));
}
+TEST_F(TestUnifySchemas, Numeric) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ CheckUnify(uint8(),
+ {int8(), uint16(), int16(), uint32(), int32(), uint64(), int64(), float32(),
+ float64()},
+ options);
+ CheckUnify(int8(), {int16(), int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint16(),
+ {int16(), uint32(), int32(), uint64(), int64(), float32(), float64()},
+ options);
+ CheckUnify(int16(), {int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint32(), {int32(), uint64(), int64(), float32(), float64()}, options);
+ CheckUnify(int32(), {int64(), float32(), float64()}, options);
+ CheckUnify(uint64(), {int64(), float64()}, options);
+ CheckUnify(int64(), {float64()}, options);
+ CheckUnify(float16(), {float32(), float64()}, options);
+ CheckUnify(float32(), {float64()}, options);
+ CheckUnify(uint64(), float32(), float64(), options);
+ CheckUnify(int64(), float32(), float64(), options);
+
+ options.promote_integer_sign = false;
+ CheckUnify(uint8(), {uint16(), uint32(), uint64()}, options);
+ CheckUnify(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(uint8(), {int8(), int16(), int32(), int64()}, options);
+ CheckUnify(uint16(), {uint32(), uint64()}, options);
+ CheckUnify(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(uint16(), {int16(), int32(), int64()}, options);
+ CheckUnify(uint32(), {uint64()}, options);
+ CheckUnify(int32(), {int64()}, options);
+ CheckUnifyFails(uint32(), {int32(), int64()}, options);
+ CheckUnifyFails(uint64(), {int64()}, options);
+
+ options.promote_integer_sign = true;
+ options.promote_integer_float = false;
+ CheckUnifyFails(IntTypes(), FloatingPointTypes(), options);
+
+ options.promote_integer_float = true;
+ options.promote_numeric_width = false;
+ CheckUnifyFails(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(int32(), {int64()}, options);
+}
+
+TEST_F(TestUnifySchemas, Decimal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_decimal_float = true;
+ CheckUnify(decimal128(3, 2), {float32(), float64()}, options);
+ CheckUnify(decimal256(3, 2), {float32(), float64()}, options);
+
+ options.promote_integer_decimal = true;
+ CheckUnify(int32(), decimal128(3, 2), decimal128(3, 2), options);
Review Comment:
This is not correct, and we should not allow truncation. Thanks for catching this!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1295676376
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
Review Comment:
This is already handled around line 515:
```c++
if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
return Status::TypeError(
"Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
}
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1295703070
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_temporal_unit) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(std::max(left.unit(), right.unit()));
+ }
+
+ if (options.promote_temporal_unit && is_time(promoted_type->id()) &&
+ is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = std::max(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::TypeError(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::TypeError("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(std::max(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-numeric types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_to_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_to_decimal &&
+ ((is_decimal(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_decimal(other_type->id()) && is_integer(promoted_type->id())))) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ // Other type is always the int
+ promoted_type.swap(other_type);
+ }
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(const auto promoted_decimal,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, promoted_decimal));
+ return promoted_type;
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const DecimalType& left = checked_cast<const DecimalType&>(*promoted_type);
+ const DecimalType& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::TypeError(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, other_type));
+ return promoted_type;
+ }
+
+ if (options.promote_integer_sign && ((is_unsigned_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) ||
+ (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
Review Comment:
Yes, I agree. I've added the following check:
```c++
if (bit_width(promoted_type->id()) != bit_width(other_type->id())
&& !options.promote_numeric_width) {
return Status::TypeError(
"Cannot widen (un)signed integers without promote_numeric_width=true");
}
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1295767555
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_temporal_unit) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(std::max(left.unit(), right.unit()));
+ }
+
+ if (options.promote_temporal_unit && is_time(promoted_type->id()) &&
+ is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = std::max(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::TypeError(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::TypeError("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(std::max(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-numeric types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_to_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_to_decimal &&
+ ((is_decimal(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_decimal(other_type->id()) && is_integer(promoted_type->id())))) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ // Other type is always the int
+ promoted_type.swap(other_type);
+ }
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(const auto promoted_decimal,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, promoted_decimal));
Review Comment:
Yes, that's the best place to put it, thanks!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1295527632
##########
python/pyarrow/types.pxi:
##########
@@ -1969,6 +1969,48 @@ cpdef KeyValueMetadata ensure_metadata(object meta, c_bool allow_none=False):
return KeyValueMetadata(meta)
+cdef class FieldMergeOptions(_Weakrefable):
+ """
+ Options controlling how to merge the types of two fields.
+
+ By default, types must match exactly, except the null type can be
+ merged with any other type.
+
+ """
+
+ cdef:
+ CField.CMergeOptions c_options
+
+ __slots__ = ()
+
+ def __init__(self, *):
+ self.c_options = CField.CMergeOptions.Defaults()
+
+ @staticmethod
+ def permissive():
+ """
+ Allow merging generally compatible types (e.g. float64 and int64).
+ """
+ cdef FieldMergeOptions options = FieldMergeOptions()
+ options.c_options = CField.CMergeOptions.Permissive()
+ return options
+
+ def __repr__(self) -> str:
+ return 'FieldMergeOptions(promote_nullability={},promote_decimal={},promote_decimal_to_float={},promote_integer_to_decimal={},promote_integer_to_float={},promote_integer_sign={},promote_numeric_width={},promote_binary={},promote_temporal_unit={},promote_dictionary={},promote_dictionary_ordered={})'.format(
Review Comment:
Yes, good call.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1295862739
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_temporal_unit) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(std::max(left.unit(), right.unit()));
+ }
+
+ if (options.promote_temporal_unit && is_time(promoted_type->id()) &&
+ is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = std::max(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::TypeError(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::TypeError("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(std::max(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-numeric types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_to_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_to_decimal &&
+ ((is_decimal(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_decimal(other_type->id()) && is_integer(promoted_type->id())))) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ // Other type is always the int
+ promoted_type.swap(other_type);
+ }
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(const auto promoted_decimal,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, promoted_decimal));
+ return promoted_type;
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const DecimalType& left = checked_cast<const DecimalType&>(*promoted_type);
+ const DecimalType& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::TypeError(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, other_type));
+ return promoted_type;
+ }
+
+ if (options.promote_integer_sign && ((is_unsigned_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) ||
+ (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
+ } else if (max_width >= 16) {
+ promoted_type = int16();
+ } else {
+ promoted_type = int8();
+ }
+ return promoted_type;
+ }
+
+ if (options.promote_integer_to_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ }
+
+ if (options.promote_numeric_width) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (is_floating(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
+ } else if (max_width >= 16) {
+ promoted_type = int16();
+ } else {
+ promoted_type = int8();
+ }
+ } else if (is_unsigned_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = uint64();
+ } else if (max_width >= 32) {
+ promoted_type = uint32();
+ } else if (max_width >= 16) {
+ promoted_type = uint16();
+ } else {
+ promoted_type = uint8();
+ }
+ }
+ }
+
+ return promoted ? promoted_type : nullptr;
+}
+
+// Merge temporal types based on options. Returns nullptr for non-binary types.
+Result<std::shared_ptr<DataType>> MaybeMergeBinaryTypes(
+ std::shared_ptr<DataType>& promoted_type, std::shared_ptr<DataType>& other_type,
+ const Field::MergeOptions& options) {
+ if (options.promote_binary) {
+ if (other_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(promoted_type->id())) {
+ return MakeBinary(*promoted_type);
+ } else if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(other_type->id())) {
+ return MakeBinary(*other_type);
+ } else if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ other_type->id() == Type::FIXED_SIZE_BINARY) {
+ return binary();
+ } else if (is_string(promoted_type->id()) && is_binary(other_type->id())) {
+ return MakeBinary(*other_type);
+ } else if (is_binary(promoted_type->id()) && is_string(other_type->id())) {
+ return MakeBinary(*promoted_type);
+ }
+
+ if ((promoted_type->id() == Type::STRING && other_type->id() == Type::LARGE_STRING) ||
+ (promoted_type->id() == Type::LARGE_STRING && other_type->id() == Type::STRING)) {
+ return large_utf8();
+ } else if ((promoted_type->id() == Type::BINARY &&
+ other_type->id() == Type::LARGE_BINARY) ||
+ (promoted_type->id() == Type::LARGE_BINARY &&
+ other_type->id() == Type::BINARY)) {
+ return large_binary();
+ }
+ }
+
+ return nullptr;
+}
+
+// Merge list types based on options. Returns nullptr for non-list types.
+Result<std::shared_ptr<DataType>> MaybeMergeListTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ bool promoted = false;
+
+ if (promoted_type->id() == Type::FIXED_SIZE_LIST &&
+ other_type->id() == Type::FIXED_SIZE_LIST) {
+ const auto& left = checked_cast<const FixedSizeListType&>(*promoted_type);
+ const auto& right = checked_cast<const FixedSizeListType&>(*other_type);
+ ARROW_ASSIGN_OR_RAISE(
+ auto value_field,
+ left.value_field()->MergeWith(
+ *right.value_field()->WithName(left.value_field()->name()), options));
+ if (left.list_size() == right.list_size()) {
+ return fixed_size_list(std::move(value_field), left.list_size());
+ }
+ return Status::TypeError("Cannot merge fixed_size_list of different sizes");
+ } else if (promoted_type->id() == Type::MAP && other_type->id() == Type::MAP) {
+ const auto& left = checked_cast<const MapType&>(*promoted_type);
+ const auto& right = checked_cast<const MapType&>(*other_type);
+ ARROW_ASSIGN_OR_RAISE(
+ auto key_field,
+ left.key_field()->MergeWith(
+ *right.key_field()->WithName(left.key_field()->name()), options));
+ ARROW_ASSIGN_OR_RAISE(
+ auto item_field,
+ left.item_field()->MergeWith(
+ *right.item_field()->WithName(left.item_field()->name()), options));
+ return map(std::move(key_field->type()), std::move(item_field),
+ /*keys_sorted=*/left.keys_sorted() && right.keys_sorted());
+ } else if (is_list(promoted_type->id()) && is_list(other_type->id())) {
+ const auto& left = checked_cast<const BaseListType&>(*promoted_type);
+ const auto& right = checked_cast<const BaseListType&>(*other_type);
+ ARROW_ASSIGN_OR_RAISE(
+ auto value_field,
+ left.value_field()->MergeWith(
+ *right.value_field()->WithName(left.value_field()->name()), options));
+ if (promoted_type->id() == Type::LARGE_LIST || other_type->id() == Type::LARGE_LIST) {
+ return large_list(std::move(value_field));
+ } else {
+ return list(std::move(value_field));
+ }
+ } else if (promoted_type->id() == Type::STRUCT && other_type->id() == Type::STRUCT) {
Review Comment:
I think splitting that out makes sense.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] pitrou commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "pitrou (via GitHub)" <gi...@apache.org>.
pitrou commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1297287132
##########
cpp/src/arrow/table.h:
##########
@@ -23,6 +23,7 @@
#include <vector>
#include "arrow/chunked_array.h" // IWYU pragma: keep
+#include "arrow/compute/cast.h"
Review Comment:
It's the _function_ `PromoteTableToSchema` that fails linking in your error message above. Meaning you probably didn't implement that particular signature?
> Also, I think it would be nice to set the `CastOptions` to `::Safe()` by default, but I'm not able to get this working with the forward reference.
Yes, this is why I suggested two signatures, one with `CastOptions` and one without.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] pitrou commented on pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "pitrou (via GitHub)" <gi...@apache.org>.
pitrou commented on PR #36846:
URL: https://github.com/apache/arrow/pull/36846#issuecomment-1735231926
Widening int and float types on arithmetic is really a mistake from NumPy, IMHO, so I don't think we should imitate it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1337180673
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,76 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
+
+ /// Allow a decimal to be promoted to a float. The float type will
+ /// not itself be promoted (e.g. Decimal128 + Float32 = Float32).
+ bool promote_decimal_to_float = false;
+
+ /// Allow an integer to be promoted to a decimal.
+ ///
+ /// May fail if the decimal has insufficient precision to
+ /// accommodate the integer. (See increase_decimal_precision.)
Review Comment:
Yes, we've combined these thanks!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1302647081
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_temporal_unit) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(std::max(left.unit(), right.unit()));
+ }
+
+ if (options.promote_temporal_unit && is_time(promoted_type->id()) &&
+ is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = std::max(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::TypeError(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::TypeError("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(std::max(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-numeric types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_to_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_to_decimal &&
+ ((is_decimal(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_decimal(other_type->id()) && is_integer(promoted_type->id())))) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ // Other type is always the int
+ promoted_type.swap(other_type);
+ }
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(const auto promoted_decimal,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, promoted_decimal));
+ return promoted_type;
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const DecimalType& left = checked_cast<const DecimalType&>(*promoted_type);
+ const DecimalType& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::TypeError(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, other_type));
+ return promoted_type;
+ }
+
+ if (options.promote_integer_sign && ((is_unsigned_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) ||
+ (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
+ } else if (max_width >= 16) {
+ promoted_type = int16();
+ } else {
+ promoted_type = int8();
+ }
+ return promoted_type;
+ }
+
+ if (options.promote_integer_to_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ }
+
+ if (options.promote_numeric_width) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (is_floating(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = int64();
+ } else if (max_width >= 32) {
+ promoted_type = int32();
+ } else if (max_width >= 16) {
+ promoted_type = int16();
+ } else {
+ promoted_type = int8();
+ }
+ } else if (is_unsigned_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ promoted = true;
+ if (max_width >= 64) {
+ promoted_type = uint64();
+ } else if (max_width >= 32) {
+ promoted_type = uint32();
+ } else if (max_width >= 16) {
+ promoted_type = uint16();
+ } else {
+ promoted_type = uint8();
+ }
+ }
+ }
+
+ return promoted ? promoted_type : nullptr;
+}
+
+// Merge temporal types based on options. Returns nullptr for non-binary types.
+Result<std::shared_ptr<DataType>> MaybeMergeBinaryTypes(
+ std::shared_ptr<DataType>& promoted_type, std::shared_ptr<DataType>& other_type,
+ const Field::MergeOptions& options) {
+ if (options.promote_binary) {
+ if (other_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(promoted_type->id())) {
+ return MakeBinary(*promoted_type);
+ } else if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(other_type->id())) {
+ return MakeBinary(*other_type);
+ } else if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ other_type->id() == Type::FIXED_SIZE_BINARY) {
+ return binary();
+ } else if (is_string(promoted_type->id()) && is_binary(other_type->id())) {
+ return MakeBinary(*other_type);
Review Comment:
Reinstated this, and added a swap to make sure that the large type is on the lefthand side.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] pitrou commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "pitrou (via GitHub)" <gi...@apache.org>.
pitrou commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1302661741
##########
cpp/src/arrow/type_test.cc:
##########
@@ -983,6 +1127,242 @@ TEST_F(TestUnifySchemas, MoreSchemas) {
utf8_field->WithNullable(true)}));
}
+TEST_F(TestUnifySchemas, Numeric) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ CheckUnify(uint8(),
+ {int8(), uint16(), int16(), uint32(), int32(), uint64(), int64(), float32(),
+ float64()},
+ options);
+ CheckUnify(int8(), {int16(), int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint16(),
+ {int16(), uint32(), int32(), uint64(), int64(), float32(), float64()},
+ options);
+ CheckUnify(int16(), {int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint32(), {int32(), uint64(), int64(), float32(), float64()}, options);
+ CheckUnify(int32(), {int64(), float32(), float64()}, options);
+ CheckUnify(uint64(), {int64(), float64()}, options);
+ CheckUnify(int64(), {float64()}, options);
+ CheckUnify(float16(), {float32(), float64()}, options);
+ CheckUnify(float32(), {float64()}, options);
+ CheckUnify(uint64(), float32(), float64(), options);
+ CheckUnify(int64(), float32(), float64(), options);
+
+ options.promote_integer_sign = false;
+ CheckUnify(uint8(), {uint16(), uint32(), uint64()}, options);
+ CheckUnify(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFailsInvalid(uint8(), {int8(), int16(), int32(), int64()}, options);
+ CheckUnify(uint16(), {uint32(), uint64()}, options);
+ CheckUnify(int16(), {int32(), int64()}, options);
+ CheckUnifyFailsInvalid(uint16(), {int16(), int32(), int64()}, options);
+ CheckUnify(uint32(), {uint64()}, options);
+ CheckUnify(int32(), {int64()}, options);
+ CheckUnifyFailsInvalid(uint32(), {int32(), int64()}, options);
+ CheckUnifyFailsInvalid(uint64(), {int64()}, options);
+
+ options.promote_integer_sign = true;
+ options.promote_integer_to_float = false;
+ CheckUnifyFailsInvalid(IntTypes(), FloatingPointTypes(), options);
+
+ options.promote_integer_to_float = true;
+ options.promote_numeric_width = false;
+ CheckUnifyFailsInvalid(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFailsInvalid(int16(), {int32(), int64()}, options);
+ CheckUnifyFailsInvalid(int32(), {int64()}, options);
+ CheckUnify(int32(), {float32()}, options);
+ CheckUnify(int64(), {float64()}, options);
+ CheckUnify(int32(), float16(), float32(), options);
+}
+
+TEST_F(TestUnifySchemas, Decimal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_decimal_to_float = true;
+ CheckUnify(decimal128(3, 2), {float32(), float64()}, options);
+ CheckUnify(decimal256(3, 2), {float32(), float64()}, options);
+
+ options.promote_integer_to_decimal = true;
+ CheckUnify(int32(), decimal128(3, 2), decimal128(12, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(10, 0), options);
+
+ options.promote_decimal = true;
+ CheckUnify(decimal128(3, 2), decimal128(5, 2), decimal128(5, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 3), decimal128(5, 3), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 1), decimal128(6, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, -2), decimal128(9, 2), options);
+ CheckUnify(decimal128(3, -2), decimal128(5, -2), decimal128(5, -2), options);
+ CheckUnify(decimal128(38, 10), decimal128(38, 5), decimal256(43, 10), options);
+
+ CheckUnify(decimal256(3, 2), decimal256(5, 2), decimal256(5, 2), options);
+ CheckUnify(decimal256(3, 2), decimal256(5, 3), decimal256(5, 3), options);
+ CheckUnify(decimal256(3, 2), decimal256(5, 1), decimal256(6, 2), options);
+ CheckUnify(decimal256(3, 2), decimal256(5, -2), decimal256(9, 2), options);
+ CheckUnify(decimal256(3, -2), decimal256(5, -2), decimal256(5, -2), options);
+
+ // int32() is essentially decimal128(10, 0)
+ CheckUnify(int32(), decimal128(3, 2), decimal128(12, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(10, 0), options);
+ CheckUnify(int64(), decimal128(38, 37), decimal256(56, 37), options);
+
+ CheckUnifyFailsTypeError(decimal256(1, 0), decimal128(1, 0), options);
+
+ options.promote_numeric_width = true;
+ CheckUnify(decimal128(3, 2), decimal256(5, 2), decimal256(5, 2), options);
+ CheckUnify(int32(), decimal128(38, 37), decimal256(47, 37), options);
+ CheckUnifyFailsInvalid(decimal128(38, 10), decimal256(76, 5), options);
+
+ CheckUnifyFailsInvalid(int64(), decimal256(76, 75), options);
+}
+
+TEST_F(TestUnifySchemas, Temporal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_temporal_unit = true;
+ CheckUnify(date32(), {date64()}, options);
+
+ CheckUnify(time32(TimeUnit::SECOND),
+ {time32(TimeUnit::MILLI), time64(TimeUnit::MICRO), time64(TimeUnit::NANO)},
+ options);
+ CheckUnify(time32(TimeUnit::MILLI), {time64(TimeUnit::MICRO), time64(TimeUnit::NANO)},
+ options);
+ CheckUnify(time64(TimeUnit::MICRO), {time64(TimeUnit::NANO)}, options);
+
+ CheckUnify(
+ duration(TimeUnit::SECOND),
+ {duration(TimeUnit::MILLI), duration(TimeUnit::MICRO), duration(TimeUnit::NANO)},
+ options);
+ CheckUnify(duration(TimeUnit::MILLI),
+ {duration(TimeUnit::MICRO), duration(TimeUnit::NANO)}, options);
+ CheckUnify(duration(TimeUnit::MICRO), {duration(TimeUnit::NANO)}, options);
+
+ CheckUnify(
+ timestamp(TimeUnit::SECOND),
+ {timestamp(TimeUnit::MILLI), timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO)},
+ options);
+ CheckUnify(timestamp(TimeUnit::MILLI),
+ {timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO)}, options);
+ CheckUnify(timestamp(TimeUnit::MICRO), {timestamp(TimeUnit::NANO)}, options);
+
+ CheckUnifyFailsTypeError(timestamp(TimeUnit::SECOND),
+ timestamp(TimeUnit::SECOND, "UTC"), options);
+ CheckUnifyFailsTypeError(timestamp(TimeUnit::SECOND, "America/New_York"),
+ timestamp(TimeUnit::SECOND, "UTC"), options);
+
+ options.promote_temporal_unit = false;
+ CheckUnifyFailsInvalid(timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO), options);
Review Comment:
I mean that `Invalid` should be raised when a value fails casting, `TypeError` when we refuse casting from one type to another.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1307092398
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,67 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
Review Comment:
Good one, added that!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on PR #36846:
URL: https://github.com/apache/arrow/pull/36846#issuecomment-1667662889
New week, new chances. Would you have time by any chance @pitrou ? :)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1274660462
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +298,431 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_float = true;
+ options.promote_integer_decimal = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_date = true;
+ options.promote_duration = true;
+ options.promote_time = true;
+ options.promote_timestamp = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ options.promote_large = true;
+ options.promote_nested = true;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_float=" << (promote_integer_float ? "true" : "false");
+ ss << ", promote_integer_decimal=" << (promote_integer_decimal ? "true" : "false");
+ ss << ", promote_decimal_float=" << (promote_decimal_float ? "true" : "false");
+ ss << ", promote_date=" << (promote_date ? "true" : "false");
+ ss << ", promote_time=" << (promote_time ? "true" : "false");
+ ss << ", promote_duration=" << (promote_duration ? "true" : "false");
+ ss << ", promote_timestamp=" << (promote_timestamp ? "true" : "false");
+ ss << ", promote_nested=" << (promote_nested ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_large=" << (promote_large ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeSigned(const DataType& type) {
+ switch (type.id()) {
+ case Type::INT8:
+ case Type::UINT8:
+ return int8();
+ case Type::INT16:
+ case Type::UINT16:
+ return int16();
+ case Type::INT32:
+ case Type::UINT32:
+ return int32();
+ case Type::INT64:
+ case Type::UINT64:
+ return int64();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+TimeUnit::type CommonTimeUnit(TimeUnit::type left, TimeUnit::type right) {
+ if (left == TimeUnit::NANO || right == TimeUnit::NANO) {
+ return TimeUnit::NANO;
+ } else if (left == TimeUnit::MICRO || right == TimeUnit::MICRO) {
+ return TimeUnit::MICRO;
+ } else if (left == TimeUnit::MILLI || right == TimeUnit::MILLI) {
+ return TimeUnit::MILLI;
+ }
+ return TimeUnit::SECOND;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::Invalid(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_date) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_duration && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(CommonTimeUnit(left.unit(), right.unit()));
+ }
+
+ if (options.promote_time && is_time(promoted_type->id()) && is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = CommonTimeUnit(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_timestamp && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::Invalid(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::Invalid("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(CommonTimeUnit(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_decimal) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ promoted_type.swap(other_type);
+ }
+
+ if (is_decimal(promoted_type->id()) && is_integer(other_type->id())) {
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(other_type,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ promoted = true;
+ }
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::Invalid(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ (options.promote_numeric_width &&
+ common_precision > BasicDecimal128::kMaxPrecision)) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+ }
+
+ if (options.promote_integer_sign) {
+ if (is_unsigned_integer(promoted_type->id()) && is_signed_integer(other_type->id())) {
+ promoted = bit_width(other_type->id()) >= bit_width(promoted_type->id());
+ promoted_type = MakeSigned(*promoted_type);
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ promoted = bit_width(promoted_type->id()) >= bit_width(other_type->id());
+ other_type = MakeSigned(*other_type);
+ }
+ }
+
+ if (options.promote_integer_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ promoted = true;
+ }
+
+ if (options.promote_numeric_width) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (is_floating(promoted_type->id()) && is_floating(other_type->id())) {
+ if (max_width >= 64) {
+ return float64();
+ } else if (max_width >= 32) {
+ return float32();
+ }
+ return float16();
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return int64();
+ } else if (max_width >= 32) {
+ return int32();
+ } else if (max_width >= 16) {
+ return int16();
+ }
+ return int8();
+ } else if (is_unsigned_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return uint64();
+ } else if (max_width >= 32) {
+ return uint32();
+ } else if (max_width >= 16) {
+ return uint16();
+ }
+ return uint8();
+ }
Review Comment:
that's happening here:
```cpp
if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
(options.promote_numeric_width &&
common_precision > BasicDecimal128::kMaxPrecision)) {
return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
}
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1274671196
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +298,431 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_float = true;
+ options.promote_integer_decimal = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_date = true;
+ options.promote_duration = true;
+ options.promote_time = true;
+ options.promote_timestamp = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ options.promote_large = true;
+ options.promote_nested = true;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_float=" << (promote_integer_float ? "true" : "false");
+ ss << ", promote_integer_decimal=" << (promote_integer_decimal ? "true" : "false");
+ ss << ", promote_decimal_float=" << (promote_decimal_float ? "true" : "false");
+ ss << ", promote_date=" << (promote_date ? "true" : "false");
+ ss << ", promote_time=" << (promote_time ? "true" : "false");
+ ss << ", promote_duration=" << (promote_duration ? "true" : "false");
+ ss << ", promote_timestamp=" << (promote_timestamp ? "true" : "false");
+ ss << ", promote_nested=" << (promote_nested ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_large=" << (promote_large ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeSigned(const DataType& type) {
+ switch (type.id()) {
+ case Type::INT8:
+ case Type::UINT8:
+ return int8();
+ case Type::INT16:
+ case Type::UINT16:
+ return int16();
+ case Type::INT32:
+ case Type::UINT32:
+ return int32();
+ case Type::INT64:
+ case Type::UINT64:
+ return int64();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+TimeUnit::type CommonTimeUnit(TimeUnit::type left, TimeUnit::type right) {
+ if (left == TimeUnit::NANO || right == TimeUnit::NANO) {
+ return TimeUnit::NANO;
+ } else if (left == TimeUnit::MICRO || right == TimeUnit::MICRO) {
+ return TimeUnit::MICRO;
+ } else if (left == TimeUnit::MILLI || right == TimeUnit::MILLI) {
+ return TimeUnit::MILLI;
+ }
+ return TimeUnit::SECOND;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::Invalid(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_date) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_duration && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(CommonTimeUnit(left.unit(), right.unit()));
+ }
+
+ if (options.promote_time && is_time(promoted_type->id()) && is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = CommonTimeUnit(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_timestamp && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::Invalid(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::Invalid("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(CommonTimeUnit(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_decimal) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ promoted_type.swap(other_type);
+ }
+
+ if (is_decimal(promoted_type->id()) && is_integer(other_type->id())) {
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(other_type,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ promoted = true;
+ }
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::Invalid(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ (options.promote_numeric_width &&
+ common_precision > BasicDecimal128::kMaxPrecision)) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+ }
+
+ if (options.promote_integer_sign) {
+ if (is_unsigned_integer(promoted_type->id()) && is_signed_integer(other_type->id())) {
+ promoted = bit_width(other_type->id()) >= bit_width(promoted_type->id());
+ promoted_type = MakeSigned(*promoted_type);
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ promoted = bit_width(promoted_type->id()) >= bit_width(other_type->id());
+ other_type = MakeSigned(*other_type);
+ }
+ }
+
+ if (options.promote_integer_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ promoted = true;
+ }
+
+ if (options.promote_numeric_width) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (is_floating(promoted_type->id()) && is_floating(other_type->id())) {
+ if (max_width >= 64) {
+ return float64();
+ } else if (max_width >= 32) {
+ return float32();
+ }
+ return float16();
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return int64();
+ } else if (max_width >= 32) {
+ return int32();
+ } else if (max_width >= 16) {
+ return int16();
+ }
+ return int8();
+ } else if (is_unsigned_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return uint64();
+ } else if (max_width >= 32) {
+ return uint32();
+ } else if (max_width >= 16) {
+ return uint16();
+ }
+ return uint8();
+ }
+ }
+
+ return promoted ? promoted_type : nullptr;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ if (promoted_type->Equals(*other_type)) return promoted_type;
+
+ bool promoted = false;
+ if (options.promote_nullability) {
+ if (promoted_type->id() == Type::NA) {
+ return other_type;
+ } else if (other_type->id() == Type::NA) {
+ return promoted_type;
+ }
+ } else if (promoted_type->id() == Type::NA || other_type->id() == Type::NA) {
+ return Status::Invalid("Cannot merge type with null unless promote_nullability=true");
+ }
+
+ if (options.promote_dictionary && is_dictionary(promoted_type->id()) &&
+ is_dictionary(other_type->id())) {
+ return MergeDictionaryTypes(promoted_type, other_type, options);
+ }
+
+ ARROW_ASSIGN_OR_RAISE(auto maybe_promoted,
+ MaybeMergeTemporalTypes(promoted_type, other_type, options));
+ if (maybe_promoted) return maybe_promoted;
+
+ ARROW_ASSIGN_OR_RAISE(maybe_promoted,
+ MaybeMergeNumericTypes(promoted_type, other_type, options));
+ if (maybe_promoted) return maybe_promoted;
+
+ if (options.promote_large) {
+ if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(other_type->id())) {
+ promoted_type = binary();
+ promoted = other_type->id() == Type::BINARY;
Review Comment:
That does not make sense to me, I think it still should promote
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] pitrou commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "pitrou (via GitHub)" <gi...@apache.org>.
pitrou commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1273424096
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,78 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
+
+ /// Allow a decimal to be promoted to a float. The float type will
+ /// not itself be promoted (e.g. Decimal128 + Float32 = Float32).
+ bool promote_decimal_float = false;
Review Comment:
For clarity, call this `promote_decimal_to_float`?
(same for similar options below)
##########
cpp/src/arrow/type_fwd.h:
##########
@@ -516,6 +516,14 @@ std::shared_ptr<DataType> map(std::shared_ptr<DataType> key_type,
std::shared_ptr<Field> item_field,
bool keys_sorted = false);
+/// \brief Create a MapType instance from its key field and value field.
+///
+/// The field override is provided to communicate nullability of the value.
+ARROW_EXPORT
+std::shared_ptr<DataType> map(std::shared_ptr<Field> key_field,
+ std::shared_ptr<Field> item_field,
+ bool keys_sorted = false);
Review Comment:
According to the schema spec:
> Neither the "entries" field nor the "key" field may be nullable.
So I'm not sure this overload is useful.
##########
cpp/src/arrow/table_test.cc:
##########
@@ -34,6 +34,7 @@
#include "arrow/testing/gtest_util.h"
#include "arrow/testing/random.h"
#include "arrow/type.h"
+#include "arrow/util/config.h"
Review Comment:
Do you mean to use this included file?
##########
cpp/src/arrow/table.cc:
##########
@@ -502,9 +504,16 @@ Result<std::shared_ptr<Table>> PromoteTableToSchema(const std::shared_ptr<Table>
continue;
}
- return Status::Invalid("Unable to promote field ", field->name(),
- ": incompatible types: ", field->type()->ToString(), " vs ",
- current_field->type()->ToString());
+ if (!compute::CanCast(*current_field->type(), *field->type())) {
+ return Status::Invalid("Unable to promote field ", field->name(),
Review Comment:
We should make this `TypeError` (and in the nullability test above as well, actually).
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +298,431 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_float = true;
+ options.promote_integer_decimal = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_date = true;
+ options.promote_duration = true;
+ options.promote_time = true;
+ options.promote_timestamp = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ options.promote_large = true;
+ options.promote_nested = true;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_float=" << (promote_integer_float ? "true" : "false");
+ ss << ", promote_integer_decimal=" << (promote_integer_decimal ? "true" : "false");
+ ss << ", promote_decimal_float=" << (promote_decimal_float ? "true" : "false");
+ ss << ", promote_date=" << (promote_date ? "true" : "false");
+ ss << ", promote_time=" << (promote_time ? "true" : "false");
+ ss << ", promote_duration=" << (promote_duration ? "true" : "false");
+ ss << ", promote_timestamp=" << (promote_timestamp ? "true" : "false");
+ ss << ", promote_nested=" << (promote_nested ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_large=" << (promote_large ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeSigned(const DataType& type) {
+ switch (type.id()) {
+ case Type::INT8:
+ case Type::UINT8:
+ return int8();
+ case Type::INT16:
+ case Type::UINT16:
+ return int16();
+ case Type::INT32:
+ case Type::UINT32:
+ return int32();
+ case Type::INT64:
+ case Type::UINT64:
+ return int64();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
Review Comment:
Nit: can simply write `return nullptr`.
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +298,431 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_float = true;
+ options.promote_integer_decimal = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_date = true;
+ options.promote_duration = true;
+ options.promote_time = true;
+ options.promote_timestamp = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ options.promote_large = true;
+ options.promote_nested = true;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_float=" << (promote_integer_float ? "true" : "false");
+ ss << ", promote_integer_decimal=" << (promote_integer_decimal ? "true" : "false");
+ ss << ", promote_decimal_float=" << (promote_decimal_float ? "true" : "false");
+ ss << ", promote_date=" << (promote_date ? "true" : "false");
+ ss << ", promote_time=" << (promote_time ? "true" : "false");
+ ss << ", promote_duration=" << (promote_duration ? "true" : "false");
+ ss << ", promote_timestamp=" << (promote_timestamp ? "true" : "false");
+ ss << ", promote_nested=" << (promote_nested ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_large=" << (promote_large ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeSigned(const DataType& type) {
+ switch (type.id()) {
+ case Type::INT8:
+ case Type::UINT8:
+ return int8();
+ case Type::INT16:
+ case Type::UINT16:
+ return int16();
+ case Type::INT32:
+ case Type::UINT32:
+ return int32();
+ case Type::INT64:
+ case Type::UINT64:
+ return int64();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+TimeUnit::type CommonTimeUnit(TimeUnit::type left, TimeUnit::type right) {
+ if (left == TimeUnit::NANO || right == TimeUnit::NANO) {
+ return TimeUnit::NANO;
+ } else if (left == TimeUnit::MICRO || right == TimeUnit::MICRO) {
+ return TimeUnit::MICRO;
+ } else if (left == TimeUnit::MILLI || right == TimeUnit::MILLI) {
+ return TimeUnit::MILLI;
+ }
+ return TimeUnit::SECOND;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::Invalid(
Review Comment:
Ideally, `MergeTypes` should always return `TypeError`, not `Invalid`?
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +298,431 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_float = true;
+ options.promote_integer_decimal = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_date = true;
+ options.promote_duration = true;
+ options.promote_time = true;
+ options.promote_timestamp = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ options.promote_large = true;
+ options.promote_nested = true;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_float=" << (promote_integer_float ? "true" : "false");
+ ss << ", promote_integer_decimal=" << (promote_integer_decimal ? "true" : "false");
+ ss << ", promote_decimal_float=" << (promote_decimal_float ? "true" : "false");
+ ss << ", promote_date=" << (promote_date ? "true" : "false");
+ ss << ", promote_time=" << (promote_time ? "true" : "false");
+ ss << ", promote_duration=" << (promote_duration ? "true" : "false");
+ ss << ", promote_timestamp=" << (promote_timestamp ? "true" : "false");
+ ss << ", promote_nested=" << (promote_nested ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_large=" << (promote_large ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeSigned(const DataType& type) {
+ switch (type.id()) {
+ case Type::INT8:
+ case Type::UINT8:
+ return int8();
+ case Type::INT16:
+ case Type::UINT16:
+ return int16();
+ case Type::INT32:
+ case Type::UINT32:
+ return int32();
+ case Type::INT64:
+ case Type::UINT64:
+ return int64();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+TimeUnit::type CommonTimeUnit(TimeUnit::type left, TimeUnit::type right) {
+ if (left == TimeUnit::NANO || right == TimeUnit::NANO) {
+ return TimeUnit::NANO;
+ } else if (left == TimeUnit::MICRO || right == TimeUnit::MICRO) {
+ return TimeUnit::MICRO;
+ } else if (left == TimeUnit::MILLI || right == TimeUnit::MILLI) {
+ return TimeUnit::MILLI;
+ }
+ return TimeUnit::SECOND;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::Invalid(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_date) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_duration && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(CommonTimeUnit(left.unit(), right.unit()));
+ }
+
+ if (options.promote_time && is_time(promoted_type->id()) && is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = CommonTimeUnit(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_timestamp && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::Invalid(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::Invalid("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(CommonTimeUnit(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_decimal) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ promoted_type.swap(other_type);
+ }
+
+ if (is_decimal(promoted_type->id()) && is_integer(other_type->id())) {
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(other_type,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ promoted = true;
+ }
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::Invalid(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ (options.promote_numeric_width &&
+ common_precision > BasicDecimal128::kMaxPrecision)) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+ }
+
+ if (options.promote_integer_sign) {
+ if (is_unsigned_integer(promoted_type->id()) && is_signed_integer(other_type->id())) {
+ promoted = bit_width(other_type->id()) >= bit_width(promoted_type->id());
+ promoted_type = MakeSigned(*promoted_type);
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ promoted = bit_width(promoted_type->id()) >= bit_width(other_type->id());
+ other_type = MakeSigned(*other_type);
+ }
+ }
+
+ if (options.promote_integer_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ promoted = true;
+ }
+
+ if (options.promote_numeric_width) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (is_floating(promoted_type->id()) && is_floating(other_type->id())) {
+ if (max_width >= 64) {
+ return float64();
+ } else if (max_width >= 32) {
+ return float32();
+ }
+ return float16();
Review Comment:
Shouldn't you set `promoted_type` instead?
```suggestion
promoted = true;
if (max_width >= 64) {
promoted_type = float64();
} else if (max_width >= 32) {
promoted_type = float32();
} else {
promoted_type = float16();
}
```
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +298,431 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_float = true;
+ options.promote_integer_decimal = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_date = true;
+ options.promote_duration = true;
+ options.promote_time = true;
+ options.promote_timestamp = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ options.promote_large = true;
+ options.promote_nested = true;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_float=" << (promote_integer_float ? "true" : "false");
+ ss << ", promote_integer_decimal=" << (promote_integer_decimal ? "true" : "false");
+ ss << ", promote_decimal_float=" << (promote_decimal_float ? "true" : "false");
+ ss << ", promote_date=" << (promote_date ? "true" : "false");
+ ss << ", promote_time=" << (promote_time ? "true" : "false");
+ ss << ", promote_duration=" << (promote_duration ? "true" : "false");
+ ss << ", promote_timestamp=" << (promote_timestamp ? "true" : "false");
+ ss << ", promote_nested=" << (promote_nested ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_large=" << (promote_large ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeSigned(const DataType& type) {
+ switch (type.id()) {
+ case Type::INT8:
+ case Type::UINT8:
+ return int8();
+ case Type::INT16:
+ case Type::UINT16:
+ return int16();
+ case Type::INT32:
+ case Type::UINT32:
+ return int32();
+ case Type::INT64:
+ case Type::UINT64:
+ return int64();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+TimeUnit::type CommonTimeUnit(TimeUnit::type left, TimeUnit::type right) {
+ if (left == TimeUnit::NANO || right == TimeUnit::NANO) {
+ return TimeUnit::NANO;
+ } else if (left == TimeUnit::MICRO || right == TimeUnit::MICRO) {
+ return TimeUnit::MICRO;
+ } else if (left == TimeUnit::MILLI || right == TimeUnit::MILLI) {
+ return TimeUnit::MILLI;
+ }
+ return TimeUnit::SECOND;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::Invalid(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_date) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_duration && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(CommonTimeUnit(left.unit(), right.unit()));
+ }
+
+ if (options.promote_time && is_time(promoted_type->id()) && is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = CommonTimeUnit(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_timestamp && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::Invalid(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::Invalid("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(CommonTimeUnit(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_decimal) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ promoted_type.swap(other_type);
+ }
+
+ if (is_decimal(promoted_type->id()) && is_integer(other_type->id())) {
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(other_type,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ promoted = true;
+ }
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::Invalid(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ (options.promote_numeric_width &&
+ common_precision > BasicDecimal128::kMaxPrecision)) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+ }
+
+ if (options.promote_integer_sign) {
+ if (is_unsigned_integer(promoted_type->id()) && is_signed_integer(other_type->id())) {
+ promoted = bit_width(other_type->id()) >= bit_width(promoted_type->id());
+ promoted_type = MakeSigned(*promoted_type);
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ promoted = bit_width(promoted_type->id()) >= bit_width(other_type->id());
+ other_type = MakeSigned(*other_type);
+ }
+ }
+
+ if (options.promote_integer_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ promoted = true;
+ }
+
+ if (options.promote_numeric_width) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (is_floating(promoted_type->id()) && is_floating(other_type->id())) {
+ if (max_width >= 64) {
+ return float64();
+ } else if (max_width >= 32) {
+ return float32();
+ }
+ return float16();
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return int64();
+ } else if (max_width >= 32) {
+ return int32();
+ } else if (max_width >= 16) {
+ return int16();
+ }
+ return int8();
+ } else if (is_unsigned_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return uint64();
+ } else if (max_width >= 32) {
+ return uint32();
+ } else if (max_width >= 16) {
+ return uint16();
+ }
+ return uint8();
+ }
+ }
+
+ return promoted ? promoted_type : nullptr;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ if (promoted_type->Equals(*other_type)) return promoted_type;
+
+ bool promoted = false;
+ if (options.promote_nullability) {
+ if (promoted_type->id() == Type::NA) {
+ return other_type;
+ } else if (other_type->id() == Type::NA) {
+ return promoted_type;
+ }
+ } else if (promoted_type->id() == Type::NA || other_type->id() == Type::NA) {
+ return Status::Invalid("Cannot merge type with null unless promote_nullability=true");
+ }
+
+ if (options.promote_dictionary && is_dictionary(promoted_type->id()) &&
+ is_dictionary(other_type->id())) {
+ return MergeDictionaryTypes(promoted_type, other_type, options);
+ }
+
+ ARROW_ASSIGN_OR_RAISE(auto maybe_promoted,
+ MaybeMergeTemporalTypes(promoted_type, other_type, options));
+ if (maybe_promoted) return maybe_promoted;
+
+ ARROW_ASSIGN_OR_RAISE(maybe_promoted,
+ MaybeMergeNumericTypes(promoted_type, other_type, options));
+ if (maybe_promoted) return maybe_promoted;
+
+ if (options.promote_large) {
+ if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(other_type->id())) {
+ promoted_type = binary();
+ promoted = other_type->id() == Type::BINARY;
Review Comment:
Hmm, why? If the other type is a large binary then promotion is refused?
##########
cpp/src/arrow/type.cc:
##########
@@ -327,14 +734,27 @@ Result<std::shared_ptr<Field>> Field::MergeWith(const Field& other,
return Copy();
}
- if (options.promote_nullability) {
- if (type()->Equals(other.type())) {
- return Copy()->WithNullable(nullable() || other.nullable());
+ auto maybe_promoted_type = MergeTypes(type_, other.type(), options);
+ if (!maybe_promoted_type.ok()) {
+ return maybe_promoted_type.status().WithMessage(
+ "Unable to merge: Field ", name(),
+ " has incompatible types: ", type()->ToString(), " vs ", other.type()->ToString(),
+ ": ", maybe_promoted_type.status().message());
+ }
+ auto promoted_type = move(maybe_promoted_type).MoveValueUnsafe();
Review Comment:
```suggestion
auto promoted_type = *std::move(maybe_promoted_type);
```
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +298,431 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_float = true;
+ options.promote_integer_decimal = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_date = true;
+ options.promote_duration = true;
+ options.promote_time = true;
+ options.promote_timestamp = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ options.promote_large = true;
+ options.promote_nested = true;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_float=" << (promote_integer_float ? "true" : "false");
+ ss << ", promote_integer_decimal=" << (promote_integer_decimal ? "true" : "false");
+ ss << ", promote_decimal_float=" << (promote_decimal_float ? "true" : "false");
+ ss << ", promote_date=" << (promote_date ? "true" : "false");
+ ss << ", promote_time=" << (promote_time ? "true" : "false");
+ ss << ", promote_duration=" << (promote_duration ? "true" : "false");
+ ss << ", promote_timestamp=" << (promote_timestamp ? "true" : "false");
+ ss << ", promote_nested=" << (promote_nested ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_large=" << (promote_large ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeSigned(const DataType& type) {
+ switch (type.id()) {
+ case Type::INT8:
+ case Type::UINT8:
+ return int8();
+ case Type::INT16:
+ case Type::UINT16:
+ return int16();
+ case Type::INT32:
+ case Type::UINT32:
+ return int32();
+ case Type::INT64:
+ case Type::UINT64:
+ return int64();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+TimeUnit::type CommonTimeUnit(TimeUnit::type left, TimeUnit::type right) {
+ if (left == TimeUnit::NANO || right == TimeUnit::NANO) {
+ return TimeUnit::NANO;
+ } else if (left == TimeUnit::MICRO || right == TimeUnit::MICRO) {
+ return TimeUnit::MICRO;
+ } else if (left == TimeUnit::MILLI || right == TimeUnit::MILLI) {
+ return TimeUnit::MILLI;
+ }
+ return TimeUnit::SECOND;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::Invalid(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_date) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_duration && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(CommonTimeUnit(left.unit(), right.unit()));
+ }
+
+ if (options.promote_time && is_time(promoted_type->id()) && is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = CommonTimeUnit(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_timestamp && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::Invalid(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::Invalid("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(CommonTimeUnit(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_decimal) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ promoted_type.swap(other_type);
+ }
+
+ if (is_decimal(promoted_type->id()) && is_integer(other_type->id())) {
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(other_type,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ promoted = true;
+ }
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::Invalid(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ (options.promote_numeric_width &&
+ common_precision > BasicDecimal128::kMaxPrecision)) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+ }
+
+ if (options.promote_integer_sign) {
+ if (is_unsigned_integer(promoted_type->id()) && is_signed_integer(other_type->id())) {
+ promoted = bit_width(other_type->id()) >= bit_width(promoted_type->id());
+ promoted_type = MakeSigned(*promoted_type);
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ promoted = bit_width(promoted_type->id()) >= bit_width(other_type->id());
+ other_type = MakeSigned(*other_type);
+ }
+ }
+
+ if (options.promote_integer_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ promoted = true;
+ }
+
+ if (options.promote_numeric_width) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (is_floating(promoted_type->id()) && is_floating(other_type->id())) {
+ if (max_width >= 64) {
+ return float64();
+ } else if (max_width >= 32) {
+ return float32();
+ }
+ return float16();
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return int64();
+ } else if (max_width >= 32) {
+ return int32();
+ } else if (max_width >= 16) {
+ return int16();
+ }
+ return int8();
+ } else if (is_unsigned_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return uint64();
+ } else if (max_width >= 32) {
+ return uint32();
+ } else if (max_width >= 16) {
+ return uint16();
+ }
+ return uint8();
+ }
+ }
+
+ return promoted ? promoted_type : nullptr;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ if (promoted_type->Equals(*other_type)) return promoted_type;
+
+ bool promoted = false;
+ if (options.promote_nullability) {
+ if (promoted_type->id() == Type::NA) {
+ return other_type;
+ } else if (other_type->id() == Type::NA) {
+ return promoted_type;
+ }
+ } else if (promoted_type->id() == Type::NA || other_type->id() == Type::NA) {
+ return Status::Invalid("Cannot merge type with null unless promote_nullability=true");
+ }
+
+ if (options.promote_dictionary && is_dictionary(promoted_type->id()) &&
+ is_dictionary(other_type->id())) {
+ return MergeDictionaryTypes(promoted_type, other_type, options);
+ }
+
+ ARROW_ASSIGN_OR_RAISE(auto maybe_promoted,
+ MaybeMergeTemporalTypes(promoted_type, other_type, options));
+ if (maybe_promoted) return maybe_promoted;
+
+ ARROW_ASSIGN_OR_RAISE(maybe_promoted,
+ MaybeMergeNumericTypes(promoted_type, other_type, options));
+ if (maybe_promoted) return maybe_promoted;
+
+ if (options.promote_large) {
+ if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(other_type->id())) {
+ promoted_type = binary();
+ promoted = other_type->id() == Type::BINARY;
+ }
+ if (other_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(promoted_type->id())) {
+ other_type = binary();
+ promoted = promoted_type->id() == Type::BINARY;
+ }
+
+ if (promoted_type->id() == Type::FIXED_SIZE_LIST &&
+ is_var_length_list(other_type->id())) {
+ promoted_type =
+ list(checked_cast<const BaseListType&>(*promoted_type).value_field());
+ promoted = other_type->Equals(*promoted_type);
+ }
+ if (other_type->id() == Type::FIXED_SIZE_LIST &&
+ is_var_length_list(promoted_type->id())) {
+ other_type = list(checked_cast<const BaseListType&>(*other_type).value_field());
+ promoted = other_type->Equals(*promoted_type);
+ }
+ }
+
+ if (options.promote_binary) {
+ if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ other_type->id() == Type::FIXED_SIZE_BINARY) {
+ return binary();
+ }
+ if (is_string(promoted_type->id()) && is_binary(other_type->id())) {
+ promoted_type = MakeBinary(*promoted_type);
+ promoted =
+ offset_bit_width(promoted_type->id()) == offset_bit_width(other_type->id());
+ } else if (is_binary(promoted_type->id()) && is_string(other_type->id())) {
+ other_type = MakeBinary(*other_type);
+ promoted =
+ offset_bit_width(promoted_type->id()) == offset_bit_width(other_type->id());
+ }
+ }
+
+ if (options.promote_large) {
+ if ((promoted_type->id() == Type::STRING && other_type->id() == Type::LARGE_STRING) ||
+ (promoted_type->id() == Type::LARGE_STRING && other_type->id() == Type::STRING)) {
+ return large_utf8();
+ } else if ((promoted_type->id() == Type::BINARY &&
+ other_type->id() == Type::LARGE_BINARY) ||
+ (promoted_type->id() == Type::LARGE_BINARY &&
+ other_type->id() == Type::BINARY)) {
+ return large_binary();
+ }
+ if ((promoted_type->id() == Type::LIST && other_type->id() == Type::LARGE_LIST) ||
+ (promoted_type->id() == Type::LARGE_LIST && other_type->id() == Type::LIST)) {
+ promoted_type =
+ large_list(checked_cast<const BaseListType&>(*promoted_type).value_field());
+ promoted = true;
+ }
+ }
+
+ if (options.promote_nested) {
+ if ((promoted_type->id() == Type::LIST && other_type->id() == Type::LIST) ||
+ (promoted_type->id() == Type::LARGE_LIST &&
+ other_type->id() == Type::LARGE_LIST) ||
+ (promoted_type->id() == Type::FIXED_SIZE_LIST &&
+ other_type->id() == Type::FIXED_SIZE_LIST)) {
Review Comment:
I think you want a single function or block to handle merging list-like types. Otherwise you're repeating yourself and it also becomes less readable or maintainable.
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,78 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
+
+ /// Allow a decimal to be promoted to a float. The float type will
+ /// not itself be promoted (e.g. Decimal128 + Float32 = Float32).
+ bool promote_decimal_float = false;
+
+ /// Allow an integer to be promoted to a decimal.
+ ///
+ /// May fail if the decimal has insufficient precision to
+ /// accomodate the integer. (See increase_decimal_precision.)
+ bool promote_integer_decimal = false;
+
+ /// Allow an integer of a given bit width to be promoted to a
+ /// float; the result will be a float of an equal or greater bit
+ /// width to both of the inputs.
+ bool promote_integer_float = false;
+
+ /// Allow an unsigned integer of a given bit width to be promoted
+ /// to a signed integer of the equal or greater bit width.
+ bool promote_integer_sign = false;
+
+ /// Allow an integer, float, or decimal of a given bit width to be
+ /// promoted to an equivalent type of a greater bit width.
+ bool promote_numeric_width = false;
+
+ /// Allow strings to be promoted to binary types.
+ bool promote_binary = false;
+
+ /// Promote Date32 to Date64.
+ bool promote_date = false;
+
+ /// Promote second to millisecond, etc.
+ bool promote_duration = false;
+
+ /// Promote Time32 to Time64, or Time32(SECOND) to Time32(MILLI), etc.
+ bool promote_time = false;
+
+ /// Promote second to millisecond, etc.
+ bool promote_timestamp = false;
Review Comment:
Is it useful to have fine-grained options like this? We could have a single `promote_temporal_unit` to allow all of these promotions.
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +298,431 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_float = true;
+ options.promote_integer_decimal = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_date = true;
+ options.promote_duration = true;
+ options.promote_time = true;
+ options.promote_timestamp = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ options.promote_large = true;
+ options.promote_nested = true;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_float=" << (promote_integer_float ? "true" : "false");
+ ss << ", promote_integer_decimal=" << (promote_integer_decimal ? "true" : "false");
+ ss << ", promote_decimal_float=" << (promote_decimal_float ? "true" : "false");
+ ss << ", promote_date=" << (promote_date ? "true" : "false");
+ ss << ", promote_time=" << (promote_time ? "true" : "false");
+ ss << ", promote_duration=" << (promote_duration ? "true" : "false");
+ ss << ", promote_timestamp=" << (promote_timestamp ? "true" : "false");
+ ss << ", promote_nested=" << (promote_nested ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_large=" << (promote_large ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeSigned(const DataType& type) {
+ switch (type.id()) {
+ case Type::INT8:
+ case Type::UINT8:
+ return int8();
+ case Type::INT16:
+ case Type::UINT16:
+ return int16();
+ case Type::INT32:
+ case Type::UINT32:
+ return int32();
+ case Type::INT64:
+ case Type::UINT64:
+ return int64();
+ default:
+ DCHECK(false) << "unreachable";
Review Comment:
Could use `std::unreachable` here, or one of the utilities from `arrow/util/unreachable.h`.
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +298,431 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_float = true;
+ options.promote_integer_decimal = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_date = true;
+ options.promote_duration = true;
+ options.promote_time = true;
+ options.promote_timestamp = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ options.promote_large = true;
+ options.promote_nested = true;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_float=" << (promote_integer_float ? "true" : "false");
+ ss << ", promote_integer_decimal=" << (promote_integer_decimal ? "true" : "false");
+ ss << ", promote_decimal_float=" << (promote_decimal_float ? "true" : "false");
+ ss << ", promote_date=" << (promote_date ? "true" : "false");
+ ss << ", promote_time=" << (promote_time ? "true" : "false");
+ ss << ", promote_duration=" << (promote_duration ? "true" : "false");
+ ss << ", promote_timestamp=" << (promote_timestamp ? "true" : "false");
+ ss << ", promote_nested=" << (promote_nested ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_large=" << (promote_large ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeSigned(const DataType& type) {
+ switch (type.id()) {
+ case Type::INT8:
+ case Type::UINT8:
+ return int8();
+ case Type::INT16:
+ case Type::UINT16:
+ return int16();
+ case Type::INT32:
+ case Type::UINT32:
+ return int32();
+ case Type::INT64:
+ case Type::UINT64:
+ return int64();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+TimeUnit::type CommonTimeUnit(TimeUnit::type left, TimeUnit::type right) {
+ if (left == TimeUnit::NANO || right == TimeUnit::NANO) {
+ return TimeUnit::NANO;
+ } else if (left == TimeUnit::MICRO || right == TimeUnit::MICRO) {
+ return TimeUnit::MICRO;
+ } else if (left == TimeUnit::MILLI || right == TimeUnit::MILLI) {
+ return TimeUnit::MILLI;
+ }
+ return TimeUnit::SECOND;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::Invalid(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_date) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_duration && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(CommonTimeUnit(left.unit(), right.unit()));
+ }
+
+ if (options.promote_time && is_time(promoted_type->id()) && is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = CommonTimeUnit(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_timestamp && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::Invalid(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::Invalid("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(CommonTimeUnit(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_decimal) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ promoted_type.swap(other_type);
+ }
+
+ if (is_decimal(promoted_type->id()) && is_integer(other_type->id())) {
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(other_type,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ promoted = true;
+ }
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::Invalid(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ (options.promote_numeric_width &&
+ common_precision > BasicDecimal128::kMaxPrecision)) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+ }
+
+ if (options.promote_integer_sign) {
+ if (is_unsigned_integer(promoted_type->id()) && is_signed_integer(other_type->id())) {
+ promoted = bit_width(other_type->id()) >= bit_width(promoted_type->id());
+ promoted_type = MakeSigned(*promoted_type);
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ promoted = bit_width(promoted_type->id()) >= bit_width(other_type->id());
+ other_type = MakeSigned(*other_type);
+ }
+ }
+
+ if (options.promote_integer_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ promoted = true;
+ }
+
+ if (options.promote_numeric_width) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (is_floating(promoted_type->id()) && is_floating(other_type->id())) {
+ if (max_width >= 64) {
+ return float64();
+ } else if (max_width >= 32) {
+ return float32();
+ }
+ return float16();
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return int64();
+ } else if (max_width >= 32) {
+ return int32();
+ } else if (max_width >= 16) {
+ return int16();
+ }
+ return int8();
+ } else if (is_unsigned_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return uint64();
+ } else if (max_width >= 32) {
+ return uint32();
+ } else if (max_width >= 16) {
+ return uint16();
+ }
+ return uint8();
+ }
+ }
+
+ return promoted ? promoted_type : nullptr;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ if (promoted_type->Equals(*other_type)) return promoted_type;
+
+ bool promoted = false;
+ if (options.promote_nullability) {
+ if (promoted_type->id() == Type::NA) {
+ return other_type;
+ } else if (other_type->id() == Type::NA) {
+ return promoted_type;
+ }
+ } else if (promoted_type->id() == Type::NA || other_type->id() == Type::NA) {
+ return Status::Invalid("Cannot merge type with null unless promote_nullability=true");
+ }
+
+ if (options.promote_dictionary && is_dictionary(promoted_type->id()) &&
+ is_dictionary(other_type->id())) {
+ return MergeDictionaryTypes(promoted_type, other_type, options);
+ }
+
+ ARROW_ASSIGN_OR_RAISE(auto maybe_promoted,
+ MaybeMergeTemporalTypes(promoted_type, other_type, options));
+ if (maybe_promoted) return maybe_promoted;
+
+ ARROW_ASSIGN_OR_RAISE(maybe_promoted,
+ MaybeMergeNumericTypes(promoted_type, other_type, options));
+ if (maybe_promoted) return maybe_promoted;
+
+ if (options.promote_large) {
+ if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(other_type->id())) {
+ promoted_type = binary();
+ promoted = other_type->id() == Type::BINARY;
+ }
+ if (other_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(promoted_type->id())) {
+ other_type = binary();
+ promoted = promoted_type->id() == Type::BINARY;
+ }
+
+ if (promoted_type->id() == Type::FIXED_SIZE_LIST &&
+ is_var_length_list(other_type->id())) {
+ promoted_type =
+ list(checked_cast<const BaseListType&>(*promoted_type).value_field());
+ promoted = other_type->Equals(*promoted_type);
+ }
+ if (other_type->id() == Type::FIXED_SIZE_LIST &&
+ is_var_length_list(promoted_type->id())) {
+ other_type = list(checked_cast<const BaseListType&>(*other_type).value_field());
+ promoted = other_type->Equals(*promoted_type);
+ }
+ }
+
+ if (options.promote_binary) {
+ if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ other_type->id() == Type::FIXED_SIZE_BINARY) {
+ return binary();
+ }
+ if (is_string(promoted_type->id()) && is_binary(other_type->id())) {
+ promoted_type = MakeBinary(*promoted_type);
+ promoted =
+ offset_bit_width(promoted_type->id()) == offset_bit_width(other_type->id());
+ } else if (is_binary(promoted_type->id()) && is_string(other_type->id())) {
+ other_type = MakeBinary(*other_type);
+ promoted =
+ offset_bit_width(promoted_type->id()) == offset_bit_width(other_type->id());
+ }
+ }
+
+ if (options.promote_large) {
+ if ((promoted_type->id() == Type::STRING && other_type->id() == Type::LARGE_STRING) ||
+ (promoted_type->id() == Type::LARGE_STRING && other_type->id() == Type::STRING)) {
+ return large_utf8();
+ } else if ((promoted_type->id() == Type::BINARY &&
+ other_type->id() == Type::LARGE_BINARY) ||
+ (promoted_type->id() == Type::LARGE_BINARY &&
+ other_type->id() == Type::BINARY)) {
+ return large_binary();
+ }
+ if ((promoted_type->id() == Type::LIST && other_type->id() == Type::LARGE_LIST) ||
+ (promoted_type->id() == Type::LARGE_LIST && other_type->id() == Type::LIST)) {
+ promoted_type =
+ large_list(checked_cast<const BaseListType&>(*promoted_type).value_field());
+ promoted = true;
+ }
+ }
+
+ if (options.promote_nested) {
+ if ((promoted_type->id() == Type::LIST && other_type->id() == Type::LIST) ||
+ (promoted_type->id() == Type::LARGE_LIST &&
+ other_type->id() == Type::LARGE_LIST) ||
+ (promoted_type->id() == Type::FIXED_SIZE_LIST &&
+ other_type->id() == Type::FIXED_SIZE_LIST)) {
+ const auto& left = checked_cast<const BaseListType&>(*promoted_type);
+ const auto& right = checked_cast<const BaseListType&>(*other_type);
+ ARROW_ASSIGN_OR_RAISE(
+ auto value_field,
+ left.value_field()->MergeWith(
+ *right.value_field()->WithName(left.value_field()->name()), options));
+ if (promoted_type->id() == Type::LIST) {
+ return list(std::move(value_field));
+ } else if (promoted_type->id() == Type::LARGE_LIST) {
+ return large_list(std::move(value_field));
+ }
+ const auto left_size =
+ checked_cast<const FixedSizeListType&>(*promoted_type).list_size();
+ const auto right_size =
+ checked_cast<const FixedSizeListType&>(*other_type).list_size();
+ if (left_size == right_size) {
+ return fixed_size_list(std::move(value_field), left_size);
+ }
+ return Status::Invalid("Cannot merge fixed_size_list of different sizes");
+ } else if (promoted_type->id() == Type::MAP && other_type->id() == Type::MAP) {
+ const auto& left = checked_cast<const MapType&>(*promoted_type);
+ const auto& right = checked_cast<const MapType&>(*other_type);
+ // While we try to preserve nonstandard field names here, note that
+ // MapType comparisons ignore field name. See ARROW-7173, ARROW-14999.
Review Comment:
I'm not sure we should care about non-standard field names here?
For lists, we certainly don't seem to care about them.
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +298,431 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_float = true;
+ options.promote_integer_decimal = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_date = true;
+ options.promote_duration = true;
+ options.promote_time = true;
+ options.promote_timestamp = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ options.promote_large = true;
+ options.promote_nested = true;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_float=" << (promote_integer_float ? "true" : "false");
+ ss << ", promote_integer_decimal=" << (promote_integer_decimal ? "true" : "false");
+ ss << ", promote_decimal_float=" << (promote_decimal_float ? "true" : "false");
+ ss << ", promote_date=" << (promote_date ? "true" : "false");
+ ss << ", promote_time=" << (promote_time ? "true" : "false");
+ ss << ", promote_duration=" << (promote_duration ? "true" : "false");
+ ss << ", promote_timestamp=" << (promote_timestamp ? "true" : "false");
+ ss << ", promote_nested=" << (promote_nested ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_large=" << (promote_large ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeSigned(const DataType& type) {
+ switch (type.id()) {
+ case Type::INT8:
+ case Type::UINT8:
+ return int8();
+ case Type::INT16:
+ case Type::UINT16:
+ return int16();
+ case Type::INT32:
+ case Type::UINT32:
+ return int32();
+ case Type::INT64:
+ case Type::UINT64:
+ return int64();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+TimeUnit::type CommonTimeUnit(TimeUnit::type left, TimeUnit::type right) {
+ if (left == TimeUnit::NANO || right == TimeUnit::NANO) {
Review Comment:
Given the way we defined `TimeUnit`, this could simply be `std::max(left, right)`, AFAICT.
##########
cpp/src/arrow/type_test.cc:
##########
@@ -983,6 +1091,242 @@ TEST_F(TestUnifySchemas, MoreSchemas) {
utf8_field->WithNullable(true)}));
}
+TEST_F(TestUnifySchemas, Numeric) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ CheckUnify(uint8(),
+ {int8(), uint16(), int16(), uint32(), int32(), uint64(), int64(), float32(),
+ float64()},
+ options);
+ CheckUnify(int8(), {int16(), int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint16(),
+ {int16(), uint32(), int32(), uint64(), int64(), float32(), float64()},
+ options);
+ CheckUnify(int16(), {int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint32(), {int32(), uint64(), int64(), float32(), float64()}, options);
+ CheckUnify(int32(), {int64(), float32(), float64()}, options);
+ CheckUnify(uint64(), {int64(), float64()}, options);
+ CheckUnify(int64(), {float64()}, options);
+ CheckUnify(float16(), {float32(), float64()}, options);
+ CheckUnify(float32(), {float64()}, options);
+ CheckUnify(uint64(), float32(), float64(), options);
+ CheckUnify(int64(), float32(), float64(), options);
+
+ options.promote_integer_sign = false;
+ CheckUnify(uint8(), {uint16(), uint32(), uint64()}, options);
+ CheckUnify(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(uint8(), {int8(), int16(), int32(), int64()}, options);
+ CheckUnify(uint16(), {uint32(), uint64()}, options);
+ CheckUnify(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(uint16(), {int16(), int32(), int64()}, options);
+ CheckUnify(uint32(), {uint64()}, options);
+ CheckUnify(int32(), {int64()}, options);
+ CheckUnifyFails(uint32(), {int32(), int64()}, options);
+ CheckUnifyFails(uint64(), {int64()}, options);
+
+ options.promote_integer_sign = true;
+ options.promote_integer_float = false;
+ CheckUnifyFails(IntTypes(), FloatingPointTypes(), options);
+
+ options.promote_integer_float = true;
+ options.promote_numeric_width = false;
+ CheckUnifyFails(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(int32(), {int64()}, options);
+}
+
+TEST_F(TestUnifySchemas, Decimal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_decimal_float = true;
+ CheckUnify(decimal128(3, 2), {float32(), float64()}, options);
+ CheckUnify(decimal256(3, 2), {float32(), float64()}, options);
+
+ options.promote_integer_decimal = true;
+ CheckUnify(int32(), decimal128(3, 2), decimal128(3, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(3, -2), options);
+
+ options.promote_decimal = true;
+ CheckUnify(decimal128(3, 2), decimal128(5, 2), decimal128(5, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 3), decimal128(5, 3), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 1), decimal128(6, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, -2), decimal128(9, 2), options);
+ CheckUnify(decimal128(3, -2), decimal128(5, -2), decimal128(5, -2), options);
+
+ // int32() is essentially decimal128(10, 0)
+ CheckUnify(int32(), decimal128(3, 2), decimal128(12, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(10, 0), options);
+
+ CheckUnifyFails(decimal256(1, 0), decimal128(1, 0), options);
+ CheckUnifyFails(int64(), decimal128(38, 37), options);
+
+ options.promote_numeric_width = true;
+ CheckUnify(decimal128(3, 2), decimal256(5, 2), decimal256(5, 2), options);
+ CheckUnify(int32(), decimal128(38, 37), decimal256(47, 37), options);
Review Comment:
What happens if I pass `decimal128(38, 10)` and `decimal256(76, 5)`?
##########
cpp/src/arrow/table.h:
##########
@@ -315,14 +315,18 @@ Result<std::shared_ptr<Table>> ConcatenateTables(
/// \brief Promotes a table to conform to the given schema.
///
-/// If a field in the schema does not have a corresponding column in the
-/// table, a column of nulls will be added to the resulting table.
-/// If the corresponding column is of type Null, it will be promoted to
-/// the type specified by schema, with null values filled.
+/// If a field in the schema does not have a corresponding column in
+/// the table, a column of nulls will be added to the resulting table.
+/// If the corresponding column is of type Null, it will be promoted
+/// to the type specified by schema, with null values filled. If Arrow
+/// was built with ARROW_COMPUTE, then the column will be casted to
+/// the type specified by the schema.
+///
/// Returns an error:
/// - if the corresponding column's type is not compatible with the
/// schema.
/// - if there is a column in the table that does not exist in the schema.
+/// - if the cast fails or casting would be required but is not available.
Review Comment:
We should probably also take an optional `MergeOptions`, to maintain the current semantics, no?
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +298,431 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_float = true;
+ options.promote_integer_decimal = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_date = true;
+ options.promote_duration = true;
+ options.promote_time = true;
+ options.promote_timestamp = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ options.promote_large = true;
+ options.promote_nested = true;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_float=" << (promote_integer_float ? "true" : "false");
+ ss << ", promote_integer_decimal=" << (promote_integer_decimal ? "true" : "false");
+ ss << ", promote_decimal_float=" << (promote_decimal_float ? "true" : "false");
+ ss << ", promote_date=" << (promote_date ? "true" : "false");
+ ss << ", promote_time=" << (promote_time ? "true" : "false");
+ ss << ", promote_duration=" << (promote_duration ? "true" : "false");
+ ss << ", promote_timestamp=" << (promote_timestamp ? "true" : "false");
+ ss << ", promote_nested=" << (promote_nested ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_large=" << (promote_large ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeSigned(const DataType& type) {
+ switch (type.id()) {
+ case Type::INT8:
+ case Type::UINT8:
+ return int8();
+ case Type::INT16:
+ case Type::UINT16:
+ return int16();
+ case Type::INT32:
+ case Type::UINT32:
+ return int32();
+ case Type::INT64:
+ case Type::UINT64:
+ return int64();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+TimeUnit::type CommonTimeUnit(TimeUnit::type left, TimeUnit::type right) {
+ if (left == TimeUnit::NANO || right == TimeUnit::NANO) {
+ return TimeUnit::NANO;
+ } else if (left == TimeUnit::MICRO || right == TimeUnit::MICRO) {
+ return TimeUnit::MICRO;
+ } else if (left == TimeUnit::MILLI || right == TimeUnit::MILLI) {
+ return TimeUnit::MILLI;
+ }
+ return TimeUnit::SECOND;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::Invalid(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_date) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_duration && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(CommonTimeUnit(left.unit(), right.unit()));
+ }
+
+ if (options.promote_time && is_time(promoted_type->id()) && is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = CommonTimeUnit(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_timestamp && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::Invalid(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::Invalid("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(CommonTimeUnit(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-temporal types.
Review Comment:
```suggestion
// Merge numeric types based on options. Returns nullptr for non-numeric types.
```
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,78 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
+
+ /// Allow a decimal to be promoted to a float. The float type will
+ /// not itself be promoted (e.g. Decimal128 + Float32 = Float32).
+ bool promote_decimal_float = false;
+
+ /// Allow an integer to be promoted to a decimal.
+ ///
+ /// May fail if the decimal has insufficient precision to
+ /// accomodate the integer. (See increase_decimal_precision.)
+ bool promote_integer_decimal = false;
+
+ /// Allow an integer of a given bit width to be promoted to a
+ /// float; the result will be a float of an equal or greater bit
+ /// width to both of the inputs.
+ bool promote_integer_float = false;
+
+ /// Allow an unsigned integer of a given bit width to be promoted
+ /// to a signed integer of the equal or greater bit width.
+ bool promote_integer_sign = false;
+
+ /// Allow an integer, float, or decimal of a given bit width to be
+ /// promoted to an equivalent type of a greater bit width.
+ bool promote_numeric_width = false;
+
+ /// Allow strings to be promoted to binary types.
+ bool promote_binary = false;
+
+ /// Promote Date32 to Date64.
+ bool promote_date = false;
+
+ /// Promote second to millisecond, etc.
+ bool promote_duration = false;
+
+ /// Promote Time32 to Time64, or Time32(SECOND) to Time32(MILLI), etc.
+ bool promote_time = false;
+
+ /// Promote second to millisecond, etc.
+ bool promote_timestamp = false;
+
+ /// Promote dictionary index types to a common type, and unify the
+ /// value types.
+ bool promote_dictionary = false;
+
+ /// Allow merging ordered and non-ordered dictionaries, else
+ /// error. The result will be ordered if and only if both inputs
+ /// are ordered.
+ bool promote_dictionary_ordered = false;
+
+ /// Allow a type to be promoted to the Large variant.
+ bool promote_large = false;
+
+ /// Recursively merge nested types.
+ bool promote_nested = false;
Review Comment:
Is it useful? Are there circumstances where nested promotion would need to be disabled?
##########
cpp/src/arrow/table.cc:
##########
@@ -502,9 +504,16 @@ Result<std::shared_ptr<Table>> PromoteTableToSchema(const std::shared_ptr<Table>
continue;
}
- return Status::Invalid("Unable to promote field ", field->name(),
- ": incompatible types: ", field->type()->ToString(), " vs ",
- current_field->type()->ToString());
+ if (!compute::CanCast(*current_field->type(), *field->type())) {
Review Comment:
Do you mean to have a `#ifdef ARROW_COMPUTE` somewhere?
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +298,431 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_float = true;
+ options.promote_integer_decimal = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_date = true;
+ options.promote_duration = true;
+ options.promote_time = true;
+ options.promote_timestamp = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ options.promote_large = true;
+ options.promote_nested = true;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_float=" << (promote_integer_float ? "true" : "false");
+ ss << ", promote_integer_decimal=" << (promote_integer_decimal ? "true" : "false");
+ ss << ", promote_decimal_float=" << (promote_decimal_float ? "true" : "false");
+ ss << ", promote_date=" << (promote_date ? "true" : "false");
+ ss << ", promote_time=" << (promote_time ? "true" : "false");
+ ss << ", promote_duration=" << (promote_duration ? "true" : "false");
+ ss << ", promote_timestamp=" << (promote_timestamp ? "true" : "false");
+ ss << ", promote_nested=" << (promote_nested ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_large=" << (promote_large ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeSigned(const DataType& type) {
+ switch (type.id()) {
+ case Type::INT8:
+ case Type::UINT8:
+ return int8();
+ case Type::INT16:
+ case Type::UINT16:
+ return int16();
+ case Type::INT32:
+ case Type::UINT32:
+ return int32();
+ case Type::INT64:
+ case Type::UINT64:
+ return int64();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+TimeUnit::type CommonTimeUnit(TimeUnit::type left, TimeUnit::type right) {
+ if (left == TimeUnit::NANO || right == TimeUnit::NANO) {
+ return TimeUnit::NANO;
+ } else if (left == TimeUnit::MICRO || right == TimeUnit::MICRO) {
+ return TimeUnit::MICRO;
+ } else if (left == TimeUnit::MILLI || right == TimeUnit::MILLI) {
+ return TimeUnit::MILLI;
+ }
+ return TimeUnit::SECOND;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::Invalid(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_date) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_duration && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(CommonTimeUnit(left.unit(), right.unit()));
+ }
+
+ if (options.promote_time && is_time(promoted_type->id()) && is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = CommonTimeUnit(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_timestamp && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::Invalid(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::Invalid("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(CommonTimeUnit(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_decimal) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ promoted_type.swap(other_type);
+ }
+
+ if (is_decimal(promoted_type->id()) && is_integer(other_type->id())) {
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(other_type,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ promoted = true;
+ }
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::Invalid(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ (options.promote_numeric_width &&
+ common_precision > BasicDecimal128::kMaxPrecision)) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+ }
+
+ if (options.promote_integer_sign) {
+ if (is_unsigned_integer(promoted_type->id()) && is_signed_integer(other_type->id())) {
+ promoted = bit_width(other_type->id()) >= bit_width(promoted_type->id());
+ promoted_type = MakeSigned(*promoted_type);
Review Comment:
Doesn't it make the logic very fragile to change `promoted_type` even if you set `promoted` to false?
##########
python/pyarrow/tests/test_schema.py:
##########
@@ -725,6 +725,10 @@ def test_schema_merge():
result = pa.unify_schemas((a, b, c))
assert result.equals(expected)
+ result = pa.unify_schemas(
+ [b, d], options=pa.FieldMergeOptions.permissive())
+ assert result.equals(d)
Review Comment:
It would be nice if I could also write:
```suggestion
result = pa.unify_schemas(
[b, d], options=pa.FieldMergeOptions.permissive())
assert result.equals(d)
result = pa.unify_schemas([b, d], options="permissive")
assert result.equals(d)
```
@jorisvandenbossche What do you think?
##########
cpp/src/arrow/type_test.cc:
##########
@@ -983,6 +1091,242 @@ TEST_F(TestUnifySchemas, MoreSchemas) {
utf8_field->WithNullable(true)}));
}
+TEST_F(TestUnifySchemas, Numeric) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ CheckUnify(uint8(),
+ {int8(), uint16(), int16(), uint32(), int32(), uint64(), int64(), float32(),
+ float64()},
+ options);
+ CheckUnify(int8(), {int16(), int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint16(),
+ {int16(), uint32(), int32(), uint64(), int64(), float32(), float64()},
+ options);
+ CheckUnify(int16(), {int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint32(), {int32(), uint64(), int64(), float32(), float64()}, options);
+ CheckUnify(int32(), {int64(), float32(), float64()}, options);
+ CheckUnify(uint64(), {int64(), float64()}, options);
+ CheckUnify(int64(), {float64()}, options);
+ CheckUnify(float16(), {float32(), float64()}, options);
+ CheckUnify(float32(), {float64()}, options);
+ CheckUnify(uint64(), float32(), float64(), options);
+ CheckUnify(int64(), float32(), float64(), options);
+
+ options.promote_integer_sign = false;
+ CheckUnify(uint8(), {uint16(), uint32(), uint64()}, options);
+ CheckUnify(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(uint8(), {int8(), int16(), int32(), int64()}, options);
+ CheckUnify(uint16(), {uint32(), uint64()}, options);
+ CheckUnify(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(uint16(), {int16(), int32(), int64()}, options);
+ CheckUnify(uint32(), {uint64()}, options);
+ CheckUnify(int32(), {int64()}, options);
+ CheckUnifyFails(uint32(), {int32(), int64()}, options);
+ CheckUnifyFails(uint64(), {int64()}, options);
+
+ options.promote_integer_sign = true;
+ options.promote_integer_float = false;
+ CheckUnifyFails(IntTypes(), FloatingPointTypes(), options);
+
+ options.promote_integer_float = true;
+ options.promote_numeric_width = false;
+ CheckUnifyFails(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(int32(), {int64()}, options);
+}
+
+TEST_F(TestUnifySchemas, Decimal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_decimal_float = true;
+ CheckUnify(decimal128(3, 2), {float32(), float64()}, options);
+ CheckUnify(decimal256(3, 2), {float32(), float64()}, options);
+
+ options.promote_integer_decimal = true;
+ CheckUnify(int32(), decimal128(3, 2), decimal128(3, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(3, -2), options);
+
+ options.promote_decimal = true;
+ CheckUnify(decimal128(3, 2), decimal128(5, 2), decimal128(5, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 3), decimal128(5, 3), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 1), decimal128(6, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, -2), decimal128(9, 2), options);
+ CheckUnify(decimal128(3, -2), decimal128(5, -2), decimal128(5, -2), options);
+
+ // int32() is essentially decimal128(10, 0)
+ CheckUnify(int32(), decimal128(3, 2), decimal128(12, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(10, 0), options);
+
+ CheckUnifyFails(decimal256(1, 0), decimal128(1, 0), options);
+ CheckUnifyFails(int64(), decimal128(38, 37), options);
+
+ options.promote_numeric_width = true;
+ CheckUnify(decimal128(3, 2), decimal256(5, 2), decimal256(5, 2), options);
+ CheckUnify(int32(), decimal128(38, 37), decimal256(47, 37), options);
+
+ CheckUnifyFails(int64(), decimal256(76, 75), options);
+}
+
+TEST_F(TestUnifySchemas, Temporal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_date = true;
+ CheckUnify(date32(), {date64()}, options);
+
+ options.promote_time = true;
+ CheckUnify(time32(TimeUnit::SECOND),
+ {time32(TimeUnit::MILLI), time64(TimeUnit::MICRO), time64(TimeUnit::NANO)},
+ options);
+ CheckUnify(time32(TimeUnit::MILLI), {time64(TimeUnit::MICRO), time64(TimeUnit::NANO)},
+ options);
+ CheckUnify(time64(TimeUnit::MICRO), {time64(TimeUnit::NANO)}, options);
+
+ options.promote_duration = true;
+ CheckUnify(
+ duration(TimeUnit::SECOND),
+ {duration(TimeUnit::MILLI), duration(TimeUnit::MICRO), duration(TimeUnit::NANO)},
+ options);
+ CheckUnify(duration(TimeUnit::MILLI),
+ {duration(TimeUnit::MICRO), duration(TimeUnit::NANO)}, options);
+ CheckUnify(duration(TimeUnit::MICRO), {duration(TimeUnit::NANO)}, options);
+
+ options.promote_timestamp = true;
+ CheckUnify(
+ timestamp(TimeUnit::SECOND),
+ {timestamp(TimeUnit::MILLI), timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO)},
+ options);
+ CheckUnify(timestamp(TimeUnit::MILLI),
+ {timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO)}, options);
+ CheckUnify(timestamp(TimeUnit::MICRO), {timestamp(TimeUnit::NANO)}, options);
+
+ CheckUnifyFails(timestamp(TimeUnit::SECOND), timestamp(TimeUnit::SECOND, "UTC"),
+ options);
+ CheckUnifyFails(timestamp(TimeUnit::SECOND, "America/New_York"),
+ timestamp(TimeUnit::SECOND, "UTC"), options);
+}
+
+TEST_F(TestUnifySchemas, Binary) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_large = true;
+ options.promote_binary = true;
+ CheckUnify(utf8(), {large_utf8(), binary(), large_binary()}, options);
+ CheckUnify(binary(), {large_binary()}, options);
+ CheckUnify(fixed_size_binary(2), {fixed_size_binary(2), binary(), large_binary()},
+ options);
+ CheckUnify(fixed_size_binary(2), fixed_size_binary(4), binary(), options);
+
+ options.promote_large = false;
+ CheckUnifyFails({utf8(), binary()}, {large_utf8(), large_binary()});
+ CheckUnifyFails(fixed_size_binary(2), BaseBinaryTypes());
+
+ options.promote_binary = false;
+ CheckUnifyFails(utf8(), {binary(), large_binary(), fixed_size_binary(2)});
+}
+
+TEST_F(TestUnifySchemas, List) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ CheckUnifyFails(fixed_size_list(int8(), 2),
+ {fixed_size_list(int8(), 3), list(int8()), large_list(int8())},
+ options);
+
+ options.promote_large = true;
+ CheckUnify(list(int8()), {large_list(int8())}, options);
+ CheckUnify(fixed_size_list(int8(), 2), {list(int8()), large_list(int8())}, options);
+
+ options.promote_nested = true;
+ CheckUnify(list(int8()), {list(int16()), list(int32()), list(int64())}, options);
+ CheckUnify(fixed_size_list(int8(), 2),
+ {fixed_size_list(int16(), 2), list(int16()), list(int32()), list(int64())},
+ options);
+
+ auto ty = list(field("foo", int8(), /*nullable=*/false));
+ CheckUnifyAsymmetric(ty, list(int8()), list(field("foo", int8(), /*nullable=*/true)),
+ options);
+ CheckUnifyAsymmetric(ty, list(field("bar", int16(), /*nullable=*/false)),
+ list(field("foo", int16(), /*nullable=*/false)), options);
+}
+
+TEST_F(TestUnifySchemas, Map) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_nested = true;
+ options.promote_numeric_width = true;
+
+ CheckUnify(map(int8(), int32()),
+ {map(int8(), int64()), map(int16(), int32()), map(int64(), int64())},
+ options);
+
+ // Do not test field names, since MapType intentionally ignores them in comparisons
+ // See ARROW-7173, ARROW-14999
+ auto ty = map(field("key", int8(), /*nullable=*/false),
+ field("value", int32(), /*nullable=*/false));
+ CheckUnify(ty, map(int8(), int32()),
+ map(field("key", int8(), /*nullable=*/true),
+ field("value", int32(), /*nullable=*/true)),
+ options);
+ CheckUnify(ty,
+ map(field("key", int16(), /*nullable=*/false),
+ field("value", int64(), /*nullable=*/false)),
+ map(field("key", int16(), /*nullable=*/false),
+ field("value", int64(), /*nullable=*/false)),
+ options);
+}
+
+TEST_F(TestUnifySchemas, Struct) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_nested = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+
+ CheckUnify(struct_({}), struct_({field("a", int8())}), struct_({field("a", int8())}),
+ options);
+
+ CheckUnifyAsymmetric(struct_({field("b", utf8())}), struct_({field("a", int8())}),
+ struct_({field("b", utf8()), field("a", int8())}), options);
+ CheckUnifyAsymmetric(struct_({field("a", int8())}), struct_({field("b", utf8())}),
+ struct_({field("a", int8()), field("b", utf8())}), options);
+
+ CheckUnify(struct_({field("b", utf8())}), struct_({field("b", binary())}),
+ struct_({field("b", binary())}), options);
+
+ CheckUnifyAsymmetric(
+ struct_({field("a", int8()), field("b", utf8()), field("a", int64())}),
+ struct_({field("b", binary())}),
+ struct_({field("a", int8()), field("b", binary()), field("a", int64())}), options);
+
+ ASSERT_RAISES(
+ Invalid,
+ field("foo", struct_({field("a", int8()), field("b", utf8()), field("a", int64())}))
+ ->MergeWith(field("foo", struct_({field("a", int64())})), options));
+}
+
+TEST_F(TestUnifySchemas, Dictionary) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_dictionary = true;
+ options.promote_large = true;
+
+ CheckUnify(dictionary(int8(), utf8()),
+ {
+ dictionary(int64(), utf8()),
+ dictionary(int8(), large_utf8()),
+ },
+ options);
+ CheckUnify(dictionary(int8(), utf8(), /*ordered=*/true),
+ {
+ dictionary(int64(), utf8(), /*ordered=*/true),
+ dictionary(int8(), large_utf8(), /*ordered=*/true),
+ },
+ options);
Review Comment:
What if I try to unify `dictionary(int64(), utf8())` and `dictionary(int8(), large_utf8())`?
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +298,431 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_float = true;
+ options.promote_integer_decimal = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_date = true;
+ options.promote_duration = true;
+ options.promote_time = true;
+ options.promote_timestamp = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ options.promote_large = true;
+ options.promote_nested = true;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_float=" << (promote_integer_float ? "true" : "false");
+ ss << ", promote_integer_decimal=" << (promote_integer_decimal ? "true" : "false");
+ ss << ", promote_decimal_float=" << (promote_decimal_float ? "true" : "false");
+ ss << ", promote_date=" << (promote_date ? "true" : "false");
+ ss << ", promote_time=" << (promote_time ? "true" : "false");
+ ss << ", promote_duration=" << (promote_duration ? "true" : "false");
+ ss << ", promote_timestamp=" << (promote_timestamp ? "true" : "false");
+ ss << ", promote_nested=" << (promote_nested ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_large=" << (promote_large ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeSigned(const DataType& type) {
+ switch (type.id()) {
+ case Type::INT8:
+ case Type::UINT8:
+ return int8();
+ case Type::INT16:
+ case Type::UINT16:
+ return int16();
+ case Type::INT32:
+ case Type::UINT32:
+ return int32();
+ case Type::INT64:
+ case Type::UINT64:
+ return int64();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+TimeUnit::type CommonTimeUnit(TimeUnit::type left, TimeUnit::type right) {
+ if (left == TimeUnit::NANO || right == TimeUnit::NANO) {
+ return TimeUnit::NANO;
+ } else if (left == TimeUnit::MICRO || right == TimeUnit::MICRO) {
+ return TimeUnit::MICRO;
+ } else if (left == TimeUnit::MILLI || right == TimeUnit::MILLI) {
+ return TimeUnit::MILLI;
+ }
+ return TimeUnit::SECOND;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::Invalid(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_date) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_duration && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(CommonTimeUnit(left.unit(), right.unit()));
+ }
+
+ if (options.promote_time && is_time(promoted_type->id()) && is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = CommonTimeUnit(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_timestamp && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::Invalid(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::Invalid("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(CommonTimeUnit(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_decimal) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ promoted_type.swap(other_type);
+ }
+
+ if (is_decimal(promoted_type->id()) && is_integer(other_type->id())) {
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(other_type,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ promoted = true;
+ }
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::Invalid(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ (options.promote_numeric_width &&
+ common_precision > BasicDecimal128::kMaxPrecision)) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+ }
+
+ if (options.promote_integer_sign) {
+ if (is_unsigned_integer(promoted_type->id()) && is_signed_integer(other_type->id())) {
+ promoted = bit_width(other_type->id()) >= bit_width(promoted_type->id());
+ promoted_type = MakeSigned(*promoted_type);
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ promoted = bit_width(promoted_type->id()) >= bit_width(other_type->id());
+ other_type = MakeSigned(*other_type);
+ }
+ }
+
+ if (options.promote_integer_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ promoted = true;
+ }
+
+ if (options.promote_numeric_width) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (is_floating(promoted_type->id()) && is_floating(other_type->id())) {
+ if (max_width >= 64) {
+ return float64();
+ } else if (max_width >= 32) {
+ return float32();
+ }
+ return float16();
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return int64();
+ } else if (max_width >= 32) {
+ return int32();
+ } else if (max_width >= 16) {
+ return int16();
+ }
+ return int8();
+ } else if (is_unsigned_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return uint64();
+ } else if (max_width >= 32) {
+ return uint32();
+ } else if (max_width >= 16) {
+ return uint16();
+ }
+ return uint8();
+ }
Review Comment:
Aren't you supposed to implement decimal128-to-decimal256 promotion as well?
##########
cpp/src/arrow/type_test.cc:
##########
@@ -983,6 +1091,242 @@ TEST_F(TestUnifySchemas, MoreSchemas) {
utf8_field->WithNullable(true)}));
}
+TEST_F(TestUnifySchemas, Numeric) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ CheckUnify(uint8(),
+ {int8(), uint16(), int16(), uint32(), int32(), uint64(), int64(), float32(),
+ float64()},
+ options);
+ CheckUnify(int8(), {int16(), int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint16(),
+ {int16(), uint32(), int32(), uint64(), int64(), float32(), float64()},
+ options);
+ CheckUnify(int16(), {int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint32(), {int32(), uint64(), int64(), float32(), float64()}, options);
+ CheckUnify(int32(), {int64(), float32(), float64()}, options);
+ CheckUnify(uint64(), {int64(), float64()}, options);
+ CheckUnify(int64(), {float64()}, options);
+ CheckUnify(float16(), {float32(), float64()}, options);
+ CheckUnify(float32(), {float64()}, options);
+ CheckUnify(uint64(), float32(), float64(), options);
+ CheckUnify(int64(), float32(), float64(), options);
+
+ options.promote_integer_sign = false;
+ CheckUnify(uint8(), {uint16(), uint32(), uint64()}, options);
+ CheckUnify(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(uint8(), {int8(), int16(), int32(), int64()}, options);
+ CheckUnify(uint16(), {uint32(), uint64()}, options);
+ CheckUnify(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(uint16(), {int16(), int32(), int64()}, options);
+ CheckUnify(uint32(), {uint64()}, options);
+ CheckUnify(int32(), {int64()}, options);
+ CheckUnifyFails(uint32(), {int32(), int64()}, options);
+ CheckUnifyFails(uint64(), {int64()}, options);
+
+ options.promote_integer_sign = true;
+ options.promote_integer_float = false;
+ CheckUnifyFails(IntTypes(), FloatingPointTypes(), options);
+
+ options.promote_integer_float = true;
+ options.promote_numeric_width = false;
+ CheckUnifyFails(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(int32(), {int64()}, options);
+}
+
+TEST_F(TestUnifySchemas, Decimal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_decimal_float = true;
+ CheckUnify(decimal128(3, 2), {float32(), float64()}, options);
+ CheckUnify(decimal256(3, 2), {float32(), float64()}, options);
+
+ options.promote_integer_decimal = true;
+ CheckUnify(int32(), decimal128(3, 2), decimal128(3, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(3, -2), options);
+
+ options.promote_decimal = true;
+ CheckUnify(decimal128(3, 2), decimal128(5, 2), decimal128(5, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 3), decimal128(5, 3), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 1), decimal128(6, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, -2), decimal128(9, 2), options);
+ CheckUnify(decimal128(3, -2), decimal128(5, -2), decimal128(5, -2), options);
+
+ // int32() is essentially decimal128(10, 0)
+ CheckUnify(int32(), decimal128(3, 2), decimal128(12, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(10, 0), options);
+
+ CheckUnifyFails(decimal256(1, 0), decimal128(1, 0), options);
+ CheckUnifyFails(int64(), decimal128(38, 37), options);
+
+ options.promote_numeric_width = true;
+ CheckUnify(decimal128(3, 2), decimal256(5, 2), decimal256(5, 2), options);
+ CheckUnify(int32(), decimal128(38, 37), decimal256(47, 37), options);
+
+ CheckUnifyFails(int64(), decimal256(76, 75), options);
+}
+
+TEST_F(TestUnifySchemas, Temporal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_date = true;
+ CheckUnify(date32(), {date64()}, options);
+
+ options.promote_time = true;
+ CheckUnify(time32(TimeUnit::SECOND),
+ {time32(TimeUnit::MILLI), time64(TimeUnit::MICRO), time64(TimeUnit::NANO)},
+ options);
+ CheckUnify(time32(TimeUnit::MILLI), {time64(TimeUnit::MICRO), time64(TimeUnit::NANO)},
+ options);
+ CheckUnify(time64(TimeUnit::MICRO), {time64(TimeUnit::NANO)}, options);
+
+ options.promote_duration = true;
+ CheckUnify(
+ duration(TimeUnit::SECOND),
+ {duration(TimeUnit::MILLI), duration(TimeUnit::MICRO), duration(TimeUnit::NANO)},
+ options);
+ CheckUnify(duration(TimeUnit::MILLI),
+ {duration(TimeUnit::MICRO), duration(TimeUnit::NANO)}, options);
+ CheckUnify(duration(TimeUnit::MICRO), {duration(TimeUnit::NANO)}, options);
+
+ options.promote_timestamp = true;
+ CheckUnify(
+ timestamp(TimeUnit::SECOND),
+ {timestamp(TimeUnit::MILLI), timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO)},
+ options);
+ CheckUnify(timestamp(TimeUnit::MILLI),
+ {timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO)}, options);
+ CheckUnify(timestamp(TimeUnit::MICRO), {timestamp(TimeUnit::NANO)}, options);
+
+ CheckUnifyFails(timestamp(TimeUnit::SECOND), timestamp(TimeUnit::SECOND, "UTC"),
+ options);
+ CheckUnifyFails(timestamp(TimeUnit::SECOND, "America/New_York"),
+ timestamp(TimeUnit::SECOND, "UTC"), options);
+}
+
+TEST_F(TestUnifySchemas, Binary) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_large = true;
+ options.promote_binary = true;
+ CheckUnify(utf8(), {large_utf8(), binary(), large_binary()}, options);
+ CheckUnify(binary(), {large_binary()}, options);
+ CheckUnify(fixed_size_binary(2), {fixed_size_binary(2), binary(), large_binary()},
+ options);
+ CheckUnify(fixed_size_binary(2), fixed_size_binary(4), binary(), options);
+
+ options.promote_large = false;
+ CheckUnifyFails({utf8(), binary()}, {large_utf8(), large_binary()});
+ CheckUnifyFails(fixed_size_binary(2), BaseBinaryTypes());
+
+ options.promote_binary = false;
+ CheckUnifyFails(utf8(), {binary(), large_binary(), fixed_size_binary(2)});
+}
+
+TEST_F(TestUnifySchemas, List) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ CheckUnifyFails(fixed_size_list(int8(), 2),
+ {fixed_size_list(int8(), 3), list(int8()), large_list(int8())},
+ options);
+
+ options.promote_large = true;
+ CheckUnify(list(int8()), {large_list(int8())}, options);
+ CheckUnify(fixed_size_list(int8(), 2), {list(int8()), large_list(int8())}, options);
+
+ options.promote_nested = true;
+ CheckUnify(list(int8()), {list(int16()), list(int32()), list(int64())}, options);
+ CheckUnify(fixed_size_list(int8(), 2),
+ {fixed_size_list(int16(), 2), list(int16()), list(int32()), list(int64())},
+ options);
+
+ auto ty = list(field("foo", int8(), /*nullable=*/false));
+ CheckUnifyAsymmetric(ty, list(int8()), list(field("foo", int8(), /*nullable=*/true)),
+ options);
+ CheckUnifyAsymmetric(ty, list(field("bar", int16(), /*nullable=*/false)),
+ list(field("foo", int16(), /*nullable=*/false)), options);
+}
+
+TEST_F(TestUnifySchemas, Map) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_nested = true;
+ options.promote_numeric_width = true;
+
+ CheckUnify(map(int8(), int32()),
+ {map(int8(), int64()), map(int16(), int32()), map(int64(), int64())},
+ options);
+
+ // Do not test field names, since MapType intentionally ignores them in comparisons
+ // See ARROW-7173, ARROW-14999
+ auto ty = map(field("key", int8(), /*nullable=*/false),
+ field("value", int32(), /*nullable=*/false));
+ CheckUnify(ty, map(int8(), int32()),
+ map(field("key", int8(), /*nullable=*/true),
+ field("value", int32(), /*nullable=*/true)),
+ options);
+ CheckUnify(ty,
+ map(field("key", int16(), /*nullable=*/false),
+ field("value", int64(), /*nullable=*/false)),
+ map(field("key", int16(), /*nullable=*/false),
+ field("value", int64(), /*nullable=*/false)),
+ options);
+}
+
+TEST_F(TestUnifySchemas, Struct) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_nested = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+
+ CheckUnify(struct_({}), struct_({field("a", int8())}), struct_({field("a", int8())}),
+ options);
+
+ CheckUnifyAsymmetric(struct_({field("b", utf8())}), struct_({field("a", int8())}),
+ struct_({field("b", utf8()), field("a", int8())}), options);
+ CheckUnifyAsymmetric(struct_({field("a", int8())}), struct_({field("b", utf8())}),
+ struct_({field("a", int8()), field("b", utf8())}), options);
+
+ CheckUnify(struct_({field("b", utf8())}), struct_({field("b", binary())}),
+ struct_({field("b", binary())}), options);
+
+ CheckUnifyAsymmetric(
+ struct_({field("a", int8()), field("b", utf8()), field("a", int64())}),
+ struct_({field("b", binary())}),
+ struct_({field("a", int8()), field("b", binary()), field("a", int64())}), options);
+
+ ASSERT_RAISES(
+ Invalid,
+ field("foo", struct_({field("a", int8()), field("b", utf8()), field("a", int64())}))
+ ->MergeWith(field("foo", struct_({field("a", int64())})), options));
Review Comment:
Since this is always tedious to write, I created https://github.com/apache/arrow/issues/36867
##########
python/pyarrow/table.pxi:
##########
@@ -5031,9 +5032,13 @@ def concat_tables(tables, c_bool promote=False, MemoryPool memory_pool=None):
tables : iterable of pyarrow.Table objects
Pyarrow tables to concatenate into a single Table.
promote : bool, default False
- If True, concatenate tables with null-filling and null type promotion.
+ If True, concatenate tables with null-filling and type promotion.
+ See field_merge_options for the type promotion behavior.
memory_pool : MemoryPool, default None
For memory allocations, if required, otherwise use default pool.
+ field_merge_options : FieldMergeOptions, default None
Review Comment:
Can we also allow passing "default" and "permissive" as strings?
##########
cpp/src/arrow/type_traits.h:
##########
@@ -1187,7 +1202,6 @@ constexpr bool is_var_length_list(Type::type type_id) {
switch (type_id) {
case Type::LIST:
case Type::LARGE_LIST:
- case Type::MAP:
Review Comment:
I don't think we want to change this?
##########
cpp/src/arrow/type_traits.h:
##########
@@ -998,6 +998,21 @@ constexpr bool is_run_end_type(Type::type type_id) {
return false;
}
+/// \brief Check for a time type
+///
+/// \param[in] type_id the type-id to check
+/// \return whether type-id is a primitive type one
+constexpr bool is_time(Type::type type_id) {
Review Comment:
1) can you move this somewhere near `is_temporal`?
2) should we also define `is_date`?
##########
python/pyarrow/types.pxi:
##########
@@ -1969,6 +1969,33 @@ cpdef KeyValueMetadata ensure_metadata(object meta, c_bool allow_none=False):
return KeyValueMetadata(meta)
+cdef class FieldMergeOptions(_Weakrefable):
+ """
+ Options controlling how to merge the types of two fields.
+
+ By default, types must match exactly, except the null type can be
+ merged with any other type.
+
+ """
+
+ cdef:
+ CField.CMergeOptions c_options
+
+ __slots__ = ()
+
+ def __init__(self, *):
+ self.c_options = CField.CMergeOptions.Defaults()
+
+ @staticmethod
+ def permissive():
+ """
+ Allow merging generally compatible types (e.g. float64 and int64).
+ """
+ cdef FieldMergeOptions options = FieldMergeOptions()
+ options.c_options = CField.CMergeOptions.Permissive()
+ return options
Review Comment:
Should at least add a `__repr__` method for printability?
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +298,431 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_float = true;
+ options.promote_integer_decimal = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_date = true;
+ options.promote_duration = true;
+ options.promote_time = true;
+ options.promote_timestamp = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ options.promote_large = true;
+ options.promote_nested = true;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_float=" << (promote_integer_float ? "true" : "false");
+ ss << ", promote_integer_decimal=" << (promote_integer_decimal ? "true" : "false");
+ ss << ", promote_decimal_float=" << (promote_decimal_float ? "true" : "false");
+ ss << ", promote_date=" << (promote_date ? "true" : "false");
+ ss << ", promote_time=" << (promote_time ? "true" : "false");
+ ss << ", promote_duration=" << (promote_duration ? "true" : "false");
+ ss << ", promote_timestamp=" << (promote_timestamp ? "true" : "false");
+ ss << ", promote_nested=" << (promote_nested ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_large=" << (promote_large ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeSigned(const DataType& type) {
+ switch (type.id()) {
+ case Type::INT8:
+ case Type::UINT8:
+ return int8();
+ case Type::INT16:
+ case Type::UINT16:
+ return int16();
+ case Type::INT32:
+ case Type::UINT32:
+ return int32();
+ case Type::INT64:
+ case Type::UINT64:
+ return int64();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+TimeUnit::type CommonTimeUnit(TimeUnit::type left, TimeUnit::type right) {
+ if (left == TimeUnit::NANO || right == TimeUnit::NANO) {
+ return TimeUnit::NANO;
+ } else if (left == TimeUnit::MICRO || right == TimeUnit::MICRO) {
+ return TimeUnit::MICRO;
+ } else if (left == TimeUnit::MILLI || right == TimeUnit::MILLI) {
+ return TimeUnit::MILLI;
+ }
+ return TimeUnit::SECOND;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::Invalid(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_date) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_duration && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(CommonTimeUnit(left.unit(), right.unit()));
+ }
+
+ if (options.promote_time && is_time(promoted_type->id()) && is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = CommonTimeUnit(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_timestamp && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::Invalid(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::Invalid("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(CommonTimeUnit(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_decimal) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ promoted_type.swap(other_type);
+ }
+
+ if (is_decimal(promoted_type->id()) && is_integer(other_type->id())) {
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(other_type,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ promoted = true;
+ }
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::Invalid(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ (options.promote_numeric_width &&
+ common_precision > BasicDecimal128::kMaxPrecision)) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+ }
+
+ if (options.promote_integer_sign) {
+ if (is_unsigned_integer(promoted_type->id()) && is_signed_integer(other_type->id())) {
+ promoted = bit_width(other_type->id()) >= bit_width(promoted_type->id());
+ promoted_type = MakeSigned(*promoted_type);
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ promoted = bit_width(promoted_type->id()) >= bit_width(other_type->id());
+ other_type = MakeSigned(*other_type);
+ }
+ }
+
+ if (options.promote_integer_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ promoted = true;
+ }
+
+ if (options.promote_numeric_width) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (is_floating(promoted_type->id()) && is_floating(other_type->id())) {
+ if (max_width >= 64) {
+ return float64();
+ } else if (max_width >= 32) {
+ return float32();
+ }
+ return float16();
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return int64();
+ } else if (max_width >= 32) {
+ return int32();
+ } else if (max_width >= 16) {
+ return int16();
+ }
+ return int8();
+ } else if (is_unsigned_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return uint64();
+ } else if (max_width >= 32) {
+ return uint32();
+ } else if (max_width >= 16) {
+ return uint16();
+ }
+ return uint8();
+ }
+ }
+
+ return promoted ? promoted_type : nullptr;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ if (promoted_type->Equals(*other_type)) return promoted_type;
+
+ bool promoted = false;
+ if (options.promote_nullability) {
+ if (promoted_type->id() == Type::NA) {
+ return other_type;
+ } else if (other_type->id() == Type::NA) {
+ return promoted_type;
+ }
+ } else if (promoted_type->id() == Type::NA || other_type->id() == Type::NA) {
+ return Status::Invalid("Cannot merge type with null unless promote_nullability=true");
+ }
+
+ if (options.promote_dictionary && is_dictionary(promoted_type->id()) &&
+ is_dictionary(other_type->id())) {
+ return MergeDictionaryTypes(promoted_type, other_type, options);
+ }
+
+ ARROW_ASSIGN_OR_RAISE(auto maybe_promoted,
+ MaybeMergeTemporalTypes(promoted_type, other_type, options));
+ if (maybe_promoted) return maybe_promoted;
+
+ ARROW_ASSIGN_OR_RAISE(maybe_promoted,
+ MaybeMergeNumericTypes(promoted_type, other_type, options));
+ if (maybe_promoted) return maybe_promoted;
+
+ if (options.promote_large) {
+ if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
Review Comment:
Hmm... what does `promote_large` have to do with promoting fixed-size binary to variable-size binary?
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +298,431 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_float = true;
+ options.promote_integer_decimal = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_date = true;
+ options.promote_duration = true;
+ options.promote_time = true;
+ options.promote_timestamp = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ options.promote_large = true;
+ options.promote_nested = true;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_float=" << (promote_integer_float ? "true" : "false");
+ ss << ", promote_integer_decimal=" << (promote_integer_decimal ? "true" : "false");
+ ss << ", promote_decimal_float=" << (promote_decimal_float ? "true" : "false");
+ ss << ", promote_date=" << (promote_date ? "true" : "false");
+ ss << ", promote_time=" << (promote_time ? "true" : "false");
+ ss << ", promote_duration=" << (promote_duration ? "true" : "false");
+ ss << ", promote_timestamp=" << (promote_timestamp ? "true" : "false");
+ ss << ", promote_nested=" << (promote_nested ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_large=" << (promote_large ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeSigned(const DataType& type) {
+ switch (type.id()) {
+ case Type::INT8:
+ case Type::UINT8:
+ return int8();
+ case Type::INT16:
+ case Type::UINT16:
+ return int16();
+ case Type::INT32:
+ case Type::UINT32:
+ return int32();
+ case Type::INT64:
+ case Type::UINT64:
+ return int64();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+TimeUnit::type CommonTimeUnit(TimeUnit::type left, TimeUnit::type right) {
+ if (left == TimeUnit::NANO || right == TimeUnit::NANO) {
+ return TimeUnit::NANO;
+ } else if (left == TimeUnit::MICRO || right == TimeUnit::MICRO) {
+ return TimeUnit::MICRO;
+ } else if (left == TimeUnit::MILLI || right == TimeUnit::MILLI) {
+ return TimeUnit::MILLI;
+ }
+ return TimeUnit::SECOND;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::Invalid(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_date) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_duration && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(CommonTimeUnit(left.unit(), right.unit()));
+ }
+
+ if (options.promote_time && is_time(promoted_type->id()) && is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = CommonTimeUnit(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_timestamp && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::Invalid(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::Invalid("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(CommonTimeUnit(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_decimal) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ promoted_type.swap(other_type);
+ }
+
+ if (is_decimal(promoted_type->id()) && is_integer(other_type->id())) {
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(other_type,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ promoted = true;
+ }
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::Invalid(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ (options.promote_numeric_width &&
+ common_precision > BasicDecimal128::kMaxPrecision)) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+ }
+
+ if (options.promote_integer_sign) {
+ if (is_unsigned_integer(promoted_type->id()) && is_signed_integer(other_type->id())) {
+ promoted = bit_width(other_type->id()) >= bit_width(promoted_type->id());
+ promoted_type = MakeSigned(*promoted_type);
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ promoted = bit_width(promoted_type->id()) >= bit_width(other_type->id());
+ other_type = MakeSigned(*other_type);
+ }
+ }
+
+ if (options.promote_integer_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ promoted = true;
+ }
+
+ if (options.promote_numeric_width) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (is_floating(promoted_type->id()) && is_floating(other_type->id())) {
+ if (max_width >= 64) {
+ return float64();
+ } else if (max_width >= 32) {
+ return float32();
+ }
+ return float16();
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return int64();
+ } else if (max_width >= 32) {
+ return int32();
+ } else if (max_width >= 16) {
+ return int16();
+ }
+ return int8();
+ } else if (is_unsigned_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return uint64();
+ } else if (max_width >= 32) {
+ return uint32();
+ } else if (max_width >= 16) {
+ return uint16();
+ }
+ return uint8();
+ }
+ }
+
+ return promoted ? promoted_type : nullptr;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ if (promoted_type->Equals(*other_type)) return promoted_type;
+
+ bool promoted = false;
+ if (options.promote_nullability) {
+ if (promoted_type->id() == Type::NA) {
+ return other_type;
+ } else if (other_type->id() == Type::NA) {
+ return promoted_type;
+ }
+ } else if (promoted_type->id() == Type::NA || other_type->id() == Type::NA) {
+ return Status::Invalid("Cannot merge type with null unless promote_nullability=true");
+ }
+
+ if (options.promote_dictionary && is_dictionary(promoted_type->id()) &&
+ is_dictionary(other_type->id())) {
+ return MergeDictionaryTypes(promoted_type, other_type, options);
+ }
+
+ ARROW_ASSIGN_OR_RAISE(auto maybe_promoted,
+ MaybeMergeTemporalTypes(promoted_type, other_type, options));
+ if (maybe_promoted) return maybe_promoted;
+
+ ARROW_ASSIGN_OR_RAISE(maybe_promoted,
+ MaybeMergeNumericTypes(promoted_type, other_type, options));
+ if (maybe_promoted) return maybe_promoted;
+
+ if (options.promote_large) {
+ if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(other_type->id())) {
+ promoted_type = binary();
+ promoted = other_type->id() == Type::BINARY;
+ }
+ if (other_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(promoted_type->id())) {
+ other_type = binary();
+ promoted = promoted_type->id() == Type::BINARY;
+ }
+
+ if (promoted_type->id() == Type::FIXED_SIZE_LIST &&
Review Comment:
Same question here. I would expect `promote_large` to unify `list(T)` and `large_list(T)` into `large_list(T)`.
##########
python/pyarrow/tests/test_table.py:
##########
@@ -1373,6 +1373,15 @@ def test_concat_tables_with_promotion():
pa.array([None, None, 1.0, 2.0], type=pa.float32()),
], ["int64_field", "float_field"]))
+ t3 = pa.Table.from_arrays(
+ [pa.array([1, 2], type=pa.int32())], ["int64_field"])
+ result = pa.concat_tables(
+ [t1, t3], promote=True,
+ field_merge_options=pa.FieldMergeOptions.permissive())
Review Comment:
Same here: would be nice to write `field_merge_options="permissive"`
##########
cpp/src/arrow/table_test.cc:
##########
@@ -520,6 +522,36 @@ TEST_F(ConcatenateTablesWithPromotionTest, Simple) {
AssertTablesEqualUnorderedFields(*expected, *result);
}
+TEST_F(ConcatenateTablesWithPromotionTest, Unify) {
+ auto t1 = TableFromJSON(schema({field("f0", int32())}), {"[[0], [1]]"});
+ auto t2 = TableFromJSON(schema({field("f0", int64())}), {"[[2], [3]]"});
+ auto t3 = TableFromJSON(schema({field("f0", null())}), {"[[null], [null]]"});
+
+ auto expected_int64 =
+ TableFromJSON(schema({field("f0", int64())}), {"[[0], [1], [2], [3]]"});
+ auto expected_null =
+ TableFromJSON(schema({field("f0", int32())}), {"[[0], [1], [null], [null]]"});
+
+ ConcatenateTablesOptions options;
+ EXPECT_RAISES_WITH_MESSAGE_THAT(Invalid,
+ ::testing::HasSubstr("Schema at index 1 was different"),
+ ConcatenateTables({t1, t2}, options));
+ EXPECT_RAISES_WITH_MESSAGE_THAT(Invalid,
+ ::testing::HasSubstr("Schema at index 1 was different"),
+ ConcatenateTables({t1, t3}, options));
+
+ options.unify_schemas = true;
+ EXPECT_RAISES_WITH_MESSAGE_THAT(Invalid,
+ ::testing::HasSubstr("Field f0 has incompatible types"),
+ ConcatenateTables({t1, t2}, options));
+ ASSERT_OK_AND_ASSIGN(auto actual, ConcatenateTables({t1, t3}, options));
+ AssertTablesEqual(*expected_null, *actual, /*same_chunk_layout=*/false);
+
+ options.field_merge_options.promote_numeric_width = true;
+ ASSERT_OK_AND_ASSIGN(actual, ConcatenateTables({t1, t2}, options));
+ AssertTablesEqual(*expected_int64, *actual, /*same_chunk_layout=*/false);
+}
Review Comment:
Can you tests for when casting fails because of overflow or other issues?
It would also showcase why the distinction between `TypeError` and `Invalid` is useful.
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +298,431 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_float = true;
+ options.promote_integer_decimal = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_date = true;
+ options.promote_duration = true;
+ options.promote_time = true;
+ options.promote_timestamp = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ options.promote_large = true;
+ options.promote_nested = true;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_float=" << (promote_integer_float ? "true" : "false");
+ ss << ", promote_integer_decimal=" << (promote_integer_decimal ? "true" : "false");
+ ss << ", promote_decimal_float=" << (promote_decimal_float ? "true" : "false");
+ ss << ", promote_date=" << (promote_date ? "true" : "false");
+ ss << ", promote_time=" << (promote_time ? "true" : "false");
+ ss << ", promote_duration=" << (promote_duration ? "true" : "false");
+ ss << ", promote_timestamp=" << (promote_timestamp ? "true" : "false");
+ ss << ", promote_nested=" << (promote_nested ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_large=" << (promote_large ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeSigned(const DataType& type) {
+ switch (type.id()) {
+ case Type::INT8:
+ case Type::UINT8:
+ return int8();
+ case Type::INT16:
+ case Type::UINT16:
+ return int16();
+ case Type::INT32:
+ case Type::UINT32:
+ return int32();
+ case Type::INT64:
+ case Type::UINT64:
+ return int64();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+TimeUnit::type CommonTimeUnit(TimeUnit::type left, TimeUnit::type right) {
+ if (left == TimeUnit::NANO || right == TimeUnit::NANO) {
+ return TimeUnit::NANO;
+ } else if (left == TimeUnit::MICRO || right == TimeUnit::MICRO) {
+ return TimeUnit::MICRO;
+ } else if (left == TimeUnit::MILLI || right == TimeUnit::MILLI) {
+ return TimeUnit::MILLI;
+ }
+ return TimeUnit::SECOND;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::Invalid(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_date) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_duration && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(CommonTimeUnit(left.unit(), right.unit()));
+ }
+
+ if (options.promote_time && is_time(promoted_type->id()) && is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = CommonTimeUnit(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_timestamp && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::Invalid(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::Invalid("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(CommonTimeUnit(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_decimal) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ promoted_type.swap(other_type);
+ }
+
+ if (is_decimal(promoted_type->id()) && is_integer(other_type->id())) {
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(other_type,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ promoted = true;
+ }
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::Invalid(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ (options.promote_numeric_width &&
+ common_precision > BasicDecimal128::kMaxPrecision)) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+ }
+
+ if (options.promote_integer_sign) {
+ if (is_unsigned_integer(promoted_type->id()) && is_signed_integer(other_type->id())) {
+ promoted = bit_width(other_type->id()) >= bit_width(promoted_type->id());
+ promoted_type = MakeSigned(*promoted_type);
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ promoted = bit_width(promoted_type->id()) >= bit_width(other_type->id());
+ other_type = MakeSigned(*other_type);
+ }
+ }
+
+ if (options.promote_integer_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ promoted = true;
+ }
+
+ if (options.promote_numeric_width) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (is_floating(promoted_type->id()) && is_floating(other_type->id())) {
+ if (max_width >= 64) {
+ return float64();
+ } else if (max_width >= 32) {
+ return float32();
+ }
+ return float16();
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return int64();
+ } else if (max_width >= 32) {
+ return int32();
+ } else if (max_width >= 16) {
+ return int16();
+ }
+ return int8();
+ } else if (is_unsigned_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return uint64();
+ } else if (max_width >= 32) {
+ return uint32();
+ } else if (max_width >= 16) {
+ return uint16();
+ }
+ return uint8();
+ }
+ }
+
+ return promoted ? promoted_type : nullptr;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ if (promoted_type->Equals(*other_type)) return promoted_type;
+
+ bool promoted = false;
+ if (options.promote_nullability) {
+ if (promoted_type->id() == Type::NA) {
+ return other_type;
+ } else if (other_type->id() == Type::NA) {
+ return promoted_type;
+ }
+ } else if (promoted_type->id() == Type::NA || other_type->id() == Type::NA) {
+ return Status::Invalid("Cannot merge type with null unless promote_nullability=true");
+ }
+
+ if (options.promote_dictionary && is_dictionary(promoted_type->id()) &&
+ is_dictionary(other_type->id())) {
+ return MergeDictionaryTypes(promoted_type, other_type, options);
+ }
+
+ ARROW_ASSIGN_OR_RAISE(auto maybe_promoted,
+ MaybeMergeTemporalTypes(promoted_type, other_type, options));
+ if (maybe_promoted) return maybe_promoted;
+
+ ARROW_ASSIGN_OR_RAISE(maybe_promoted,
+ MaybeMergeNumericTypes(promoted_type, other_type, options));
+ if (maybe_promoted) return maybe_promoted;
+
Review Comment:
Can we perhaps also have a `MaybeMergeBinaryTypes` and a `MaybeMergeListTypes`? It would make things more readable IMHO.
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +298,431 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_float = true;
+ options.promote_integer_decimal = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_date = true;
+ options.promote_duration = true;
+ options.promote_time = true;
+ options.promote_timestamp = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ options.promote_large = true;
+ options.promote_nested = true;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_float=" << (promote_integer_float ? "true" : "false");
+ ss << ", promote_integer_decimal=" << (promote_integer_decimal ? "true" : "false");
+ ss << ", promote_decimal_float=" << (promote_decimal_float ? "true" : "false");
+ ss << ", promote_date=" << (promote_date ? "true" : "false");
+ ss << ", promote_time=" << (promote_time ? "true" : "false");
+ ss << ", promote_duration=" << (promote_duration ? "true" : "false");
+ ss << ", promote_timestamp=" << (promote_timestamp ? "true" : "false");
+ ss << ", promote_nested=" << (promote_nested ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_large=" << (promote_large ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeSigned(const DataType& type) {
+ switch (type.id()) {
+ case Type::INT8:
+ case Type::UINT8:
+ return int8();
+ case Type::INT16:
+ case Type::UINT16:
+ return int16();
+ case Type::INT32:
+ case Type::UINT32:
+ return int32();
+ case Type::INT64:
+ case Type::UINT64:
+ return int64();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+TimeUnit::type CommonTimeUnit(TimeUnit::type left, TimeUnit::type right) {
+ if (left == TimeUnit::NANO || right == TimeUnit::NANO) {
+ return TimeUnit::NANO;
+ } else if (left == TimeUnit::MICRO || right == TimeUnit::MICRO) {
+ return TimeUnit::MICRO;
+ } else if (left == TimeUnit::MILLI || right == TimeUnit::MILLI) {
+ return TimeUnit::MILLI;
+ }
+ return TimeUnit::SECOND;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::Invalid(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_date) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_duration && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(CommonTimeUnit(left.unit(), right.unit()));
+ }
+
+ if (options.promote_time && is_time(promoted_type->id()) && is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = CommonTimeUnit(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_timestamp && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::Invalid(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::Invalid("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(CommonTimeUnit(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_decimal) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ promoted_type.swap(other_type);
+ }
+
+ if (is_decimal(promoted_type->id()) && is_integer(other_type->id())) {
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(other_type,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ promoted = true;
+ }
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::Invalid(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ (options.promote_numeric_width &&
+ common_precision > BasicDecimal128::kMaxPrecision)) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+ }
+
+ if (options.promote_integer_sign) {
+ if (is_unsigned_integer(promoted_type->id()) && is_signed_integer(other_type->id())) {
+ promoted = bit_width(other_type->id()) >= bit_width(promoted_type->id());
+ promoted_type = MakeSigned(*promoted_type);
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ promoted = bit_width(promoted_type->id()) >= bit_width(other_type->id());
+ other_type = MakeSigned(*other_type);
+ }
+ }
+
+ if (options.promote_integer_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ promoted = true;
+ }
+
+ if (options.promote_numeric_width) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (is_floating(promoted_type->id()) && is_floating(other_type->id())) {
+ if (max_width >= 64) {
+ return float64();
+ } else if (max_width >= 32) {
+ return float32();
+ }
+ return float16();
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return int64();
+ } else if (max_width >= 32) {
+ return int32();
+ } else if (max_width >= 16) {
+ return int16();
+ }
+ return int8();
+ } else if (is_unsigned_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return uint64();
+ } else if (max_width >= 32) {
+ return uint32();
+ } else if (max_width >= 16) {
+ return uint16();
+ }
+ return uint8();
+ }
+ }
+
+ return promoted ? promoted_type : nullptr;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ if (promoted_type->Equals(*other_type)) return promoted_type;
+
+ bool promoted = false;
+ if (options.promote_nullability) {
+ if (promoted_type->id() == Type::NA) {
+ return other_type;
+ } else if (other_type->id() == Type::NA) {
+ return promoted_type;
+ }
+ } else if (promoted_type->id() == Type::NA || other_type->id() == Type::NA) {
+ return Status::Invalid("Cannot merge type with null unless promote_nullability=true");
+ }
+
+ if (options.promote_dictionary && is_dictionary(promoted_type->id()) &&
+ is_dictionary(other_type->id())) {
+ return MergeDictionaryTypes(promoted_type, other_type, options);
+ }
+
+ ARROW_ASSIGN_OR_RAISE(auto maybe_promoted,
+ MaybeMergeTemporalTypes(promoted_type, other_type, options));
+ if (maybe_promoted) return maybe_promoted;
+
+ ARROW_ASSIGN_OR_RAISE(maybe_promoted,
+ MaybeMergeNumericTypes(promoted_type, other_type, options));
+ if (maybe_promoted) return maybe_promoted;
+
+ if (options.promote_large) {
+ if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(other_type->id())) {
+ promoted_type = binary();
+ promoted = other_type->id() == Type::BINARY;
+ }
+ if (other_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(promoted_type->id())) {
+ other_type = binary();
+ promoted = promoted_type->id() == Type::BINARY;
+ }
+
+ if (promoted_type->id() == Type::FIXED_SIZE_LIST &&
+ is_var_length_list(other_type->id())) {
+ promoted_type =
+ list(checked_cast<const BaseListType&>(*promoted_type).value_field());
+ promoted = other_type->Equals(*promoted_type);
+ }
+ if (other_type->id() == Type::FIXED_SIZE_LIST &&
+ is_var_length_list(promoted_type->id())) {
+ other_type = list(checked_cast<const BaseListType&>(*other_type).value_field());
+ promoted = other_type->Equals(*promoted_type);
+ }
+ }
+
+ if (options.promote_binary) {
+ if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ other_type->id() == Type::FIXED_SIZE_BINARY) {
+ return binary();
Review Comment:
Even if both fixed-size binary types have the same width?
##########
cpp/src/arrow/type_test.cc:
##########
@@ -983,6 +1091,242 @@ TEST_F(TestUnifySchemas, MoreSchemas) {
utf8_field->WithNullable(true)}));
}
+TEST_F(TestUnifySchemas, Numeric) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ CheckUnify(uint8(),
+ {int8(), uint16(), int16(), uint32(), int32(), uint64(), int64(), float32(),
+ float64()},
+ options);
+ CheckUnify(int8(), {int16(), int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint16(),
+ {int16(), uint32(), int32(), uint64(), int64(), float32(), float64()},
+ options);
+ CheckUnify(int16(), {int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint32(), {int32(), uint64(), int64(), float32(), float64()}, options);
+ CheckUnify(int32(), {int64(), float32(), float64()}, options);
+ CheckUnify(uint64(), {int64(), float64()}, options);
+ CheckUnify(int64(), {float64()}, options);
+ CheckUnify(float16(), {float32(), float64()}, options);
+ CheckUnify(float32(), {float64()}, options);
+ CheckUnify(uint64(), float32(), float64(), options);
+ CheckUnify(int64(), float32(), float64(), options);
+
+ options.promote_integer_sign = false;
+ CheckUnify(uint8(), {uint16(), uint32(), uint64()}, options);
+ CheckUnify(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(uint8(), {int8(), int16(), int32(), int64()}, options);
+ CheckUnify(uint16(), {uint32(), uint64()}, options);
+ CheckUnify(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(uint16(), {int16(), int32(), int64()}, options);
+ CheckUnify(uint32(), {uint64()}, options);
+ CheckUnify(int32(), {int64()}, options);
+ CheckUnifyFails(uint32(), {int32(), int64()}, options);
+ CheckUnifyFails(uint64(), {int64()}, options);
+
+ options.promote_integer_sign = true;
+ options.promote_integer_float = false;
+ CheckUnifyFails(IntTypes(), FloatingPointTypes(), options);
+
+ options.promote_integer_float = true;
+ options.promote_numeric_width = false;
+ CheckUnifyFails(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(int32(), {int64()}, options);
+}
+
+TEST_F(TestUnifySchemas, Decimal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_decimal_float = true;
+ CheckUnify(decimal128(3, 2), {float32(), float64()}, options);
+ CheckUnify(decimal256(3, 2), {float32(), float64()}, options);
+
+ options.promote_integer_decimal = true;
+ CheckUnify(int32(), decimal128(3, 2), decimal128(3, 2), options);
Review Comment:
Hmm, it's ok to risk truncation here? This is weird, as `int32` to `int16` isn't allowed.
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +298,431 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_float = true;
+ options.promote_integer_decimal = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_date = true;
+ options.promote_duration = true;
+ options.promote_time = true;
+ options.promote_timestamp = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ options.promote_large = true;
+ options.promote_nested = true;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_float=" << (promote_integer_float ? "true" : "false");
+ ss << ", promote_integer_decimal=" << (promote_integer_decimal ? "true" : "false");
+ ss << ", promote_decimal_float=" << (promote_decimal_float ? "true" : "false");
+ ss << ", promote_date=" << (promote_date ? "true" : "false");
+ ss << ", promote_time=" << (promote_time ? "true" : "false");
+ ss << ", promote_duration=" << (promote_duration ? "true" : "false");
+ ss << ", promote_timestamp=" << (promote_timestamp ? "true" : "false");
+ ss << ", promote_nested=" << (promote_nested ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_large=" << (promote_large ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeSigned(const DataType& type) {
+ switch (type.id()) {
+ case Type::INT8:
+ case Type::UINT8:
+ return int8();
+ case Type::INT16:
+ case Type::UINT16:
+ return int16();
+ case Type::INT32:
+ case Type::UINT32:
+ return int32();
+ case Type::INT64:
+ case Type::UINT64:
+ return int64();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+TimeUnit::type CommonTimeUnit(TimeUnit::type left, TimeUnit::type right) {
+ if (left == TimeUnit::NANO || right == TimeUnit::NANO) {
+ return TimeUnit::NANO;
+ } else if (left == TimeUnit::MICRO || right == TimeUnit::MICRO) {
+ return TimeUnit::MICRO;
+ } else if (left == TimeUnit::MILLI || right == TimeUnit::MILLI) {
+ return TimeUnit::MILLI;
+ }
+ return TimeUnit::SECOND;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::Invalid(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_date) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_duration && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(CommonTimeUnit(left.unit(), right.unit()));
+ }
+
+ if (options.promote_time && is_time(promoted_type->id()) && is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = CommonTimeUnit(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_timestamp && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::Invalid(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::Invalid("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(CommonTimeUnit(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_decimal) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ promoted_type.swap(other_type);
+ }
+
+ if (is_decimal(promoted_type->id()) && is_integer(other_type->id())) {
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(other_type,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ promoted = true;
+ }
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::Invalid(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ (options.promote_numeric_width &&
+ common_precision > BasicDecimal128::kMaxPrecision)) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+ }
+
+ if (options.promote_integer_sign) {
+ if (is_unsigned_integer(promoted_type->id()) && is_signed_integer(other_type->id())) {
+ promoted = bit_width(other_type->id()) >= bit_width(promoted_type->id());
+ promoted_type = MakeSigned(*promoted_type);
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ promoted = bit_width(promoted_type->id()) >= bit_width(other_type->id());
+ other_type = MakeSigned(*other_type);
+ }
+ }
+
+ if (options.promote_integer_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ promoted = true;
+ }
+
+ if (options.promote_numeric_width) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (is_floating(promoted_type->id()) && is_floating(other_type->id())) {
+ if (max_width >= 64) {
+ return float64();
+ } else if (max_width >= 32) {
+ return float32();
+ }
+ return float16();
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return int64();
+ } else if (max_width >= 32) {
+ return int32();
+ } else if (max_width >= 16) {
+ return int16();
+ }
+ return int8();
+ } else if (is_unsigned_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return uint64();
+ } else if (max_width >= 32) {
+ return uint32();
+ } else if (max_width >= 16) {
+ return uint16();
+ }
+ return uint8();
+ }
+ }
+
+ return promoted ? promoted_type : nullptr;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ if (promoted_type->Equals(*other_type)) return promoted_type;
+
+ bool promoted = false;
+ if (options.promote_nullability) {
+ if (promoted_type->id() == Type::NA) {
+ return other_type;
+ } else if (other_type->id() == Type::NA) {
+ return promoted_type;
+ }
+ } else if (promoted_type->id() == Type::NA || other_type->id() == Type::NA) {
+ return Status::Invalid("Cannot merge type with null unless promote_nullability=true");
+ }
+
+ if (options.promote_dictionary && is_dictionary(promoted_type->id()) &&
+ is_dictionary(other_type->id())) {
+ return MergeDictionaryTypes(promoted_type, other_type, options);
+ }
+
+ ARROW_ASSIGN_OR_RAISE(auto maybe_promoted,
+ MaybeMergeTemporalTypes(promoted_type, other_type, options));
+ if (maybe_promoted) return maybe_promoted;
+
+ ARROW_ASSIGN_OR_RAISE(maybe_promoted,
+ MaybeMergeNumericTypes(promoted_type, other_type, options));
+ if (maybe_promoted) return maybe_promoted;
+
+ if (options.promote_large) {
+ if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(other_type->id())) {
+ promoted_type = binary();
+ promoted = other_type->id() == Type::BINARY;
+ }
+ if (other_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(promoted_type->id())) {
+ other_type = binary();
+ promoted = promoted_type->id() == Type::BINARY;
+ }
+
+ if (promoted_type->id() == Type::FIXED_SIZE_LIST &&
+ is_var_length_list(other_type->id())) {
+ promoted_type =
+ list(checked_cast<const BaseListType&>(*promoted_type).value_field());
+ promoted = other_type->Equals(*promoted_type);
+ }
+ if (other_type->id() == Type::FIXED_SIZE_LIST &&
+ is_var_length_list(promoted_type->id())) {
+ other_type = list(checked_cast<const BaseListType&>(*other_type).value_field());
+ promoted = other_type->Equals(*promoted_type);
+ }
+ }
+
+ if (options.promote_binary) {
+ if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ other_type->id() == Type::FIXED_SIZE_BINARY) {
+ return binary();
+ }
+ if (is_string(promoted_type->id()) && is_binary(other_type->id())) {
+ promoted_type = MakeBinary(*promoted_type);
+ promoted =
+ offset_bit_width(promoted_type->id()) == offset_bit_width(other_type->id());
+ } else if (is_binary(promoted_type->id()) && is_string(other_type->id())) {
+ other_type = MakeBinary(*other_type);
+ promoted =
+ offset_bit_width(promoted_type->id()) == offset_bit_width(other_type->id());
+ }
+ }
+
+ if (options.promote_large) {
+ if ((promoted_type->id() == Type::STRING && other_type->id() == Type::LARGE_STRING) ||
+ (promoted_type->id() == Type::LARGE_STRING && other_type->id() == Type::STRING)) {
+ return large_utf8();
+ } else if ((promoted_type->id() == Type::BINARY &&
+ other_type->id() == Type::LARGE_BINARY) ||
+ (promoted_type->id() == Type::LARGE_BINARY &&
+ other_type->id() == Type::BINARY)) {
+ return large_binary();
+ }
+ if ((promoted_type->id() == Type::LIST && other_type->id() == Type::LARGE_LIST) ||
+ (promoted_type->id() == Type::LARGE_LIST && other_type->id() == Type::LIST)) {
+ promoted_type =
+ large_list(checked_cast<const BaseListType&>(*promoted_type).value_field());
+ promoted = true;
Review Comment:
Hmm... so if `options.promote_nested` is false, this could successfully promote `list(int16)` and `large_list(int32)` into `large_list(int16)`?
The overall logic looks, again, a bit fragile and error-prone to me. Is it possible to implement this differently?
##########
cpp/src/arrow/type_test.cc:
##########
@@ -983,6 +1091,242 @@ TEST_F(TestUnifySchemas, MoreSchemas) {
utf8_field->WithNullable(true)}));
}
+TEST_F(TestUnifySchemas, Numeric) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ CheckUnify(uint8(),
+ {int8(), uint16(), int16(), uint32(), int32(), uint64(), int64(), float32(),
+ float64()},
+ options);
+ CheckUnify(int8(), {int16(), int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint16(),
+ {int16(), uint32(), int32(), uint64(), int64(), float32(), float64()},
+ options);
+ CheckUnify(int16(), {int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint32(), {int32(), uint64(), int64(), float32(), float64()}, options);
+ CheckUnify(int32(), {int64(), float32(), float64()}, options);
+ CheckUnify(uint64(), {int64(), float64()}, options);
+ CheckUnify(int64(), {float64()}, options);
+ CheckUnify(float16(), {float32(), float64()}, options);
+ CheckUnify(float32(), {float64()}, options);
+ CheckUnify(uint64(), float32(), float64(), options);
+ CheckUnify(int64(), float32(), float64(), options);
+
+ options.promote_integer_sign = false;
+ CheckUnify(uint8(), {uint16(), uint32(), uint64()}, options);
+ CheckUnify(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(uint8(), {int8(), int16(), int32(), int64()}, options);
+ CheckUnify(uint16(), {uint32(), uint64()}, options);
+ CheckUnify(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(uint16(), {int16(), int32(), int64()}, options);
+ CheckUnify(uint32(), {uint64()}, options);
+ CheckUnify(int32(), {int64()}, options);
+ CheckUnifyFails(uint32(), {int32(), int64()}, options);
+ CheckUnifyFails(uint64(), {int64()}, options);
+
+ options.promote_integer_sign = true;
+ options.promote_integer_float = false;
+ CheckUnifyFails(IntTypes(), FloatingPointTypes(), options);
+
+ options.promote_integer_float = true;
+ options.promote_numeric_width = false;
+ CheckUnifyFails(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(int32(), {int64()}, options);
+}
+
+TEST_F(TestUnifySchemas, Decimal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_decimal_float = true;
+ CheckUnify(decimal128(3, 2), {float32(), float64()}, options);
+ CheckUnify(decimal256(3, 2), {float32(), float64()}, options);
+
+ options.promote_integer_decimal = true;
+ CheckUnify(int32(), decimal128(3, 2), decimal128(3, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(3, -2), options);
+
+ options.promote_decimal = true;
+ CheckUnify(decimal128(3, 2), decimal128(5, 2), decimal128(5, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 3), decimal128(5, 3), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 1), decimal128(6, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, -2), decimal128(9, 2), options);
+ CheckUnify(decimal128(3, -2), decimal128(5, -2), decimal128(5, -2), options);
+
+ // int32() is essentially decimal128(10, 0)
+ CheckUnify(int32(), decimal128(3, 2), decimal128(12, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(10, 0), options);
+
+ CheckUnifyFails(decimal256(1, 0), decimal128(1, 0), options);
+ CheckUnifyFails(int64(), decimal128(38, 37), options);
Review Comment:
Add comments explaining why these would fail.
##########
cpp/src/arrow/type_test.cc:
##########
@@ -983,6 +1091,242 @@ TEST_F(TestUnifySchemas, MoreSchemas) {
utf8_field->WithNullable(true)}));
}
+TEST_F(TestUnifySchemas, Numeric) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ CheckUnify(uint8(),
+ {int8(), uint16(), int16(), uint32(), int32(), uint64(), int64(), float32(),
+ float64()},
+ options);
+ CheckUnify(int8(), {int16(), int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint16(),
+ {int16(), uint32(), int32(), uint64(), int64(), float32(), float64()},
+ options);
+ CheckUnify(int16(), {int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint32(), {int32(), uint64(), int64(), float32(), float64()}, options);
+ CheckUnify(int32(), {int64(), float32(), float64()}, options);
+ CheckUnify(uint64(), {int64(), float64()}, options);
+ CheckUnify(int64(), {float64()}, options);
+ CheckUnify(float16(), {float32(), float64()}, options);
+ CheckUnify(float32(), {float64()}, options);
+ CheckUnify(uint64(), float32(), float64(), options);
+ CheckUnify(int64(), float32(), float64(), options);
+
+ options.promote_integer_sign = false;
+ CheckUnify(uint8(), {uint16(), uint32(), uint64()}, options);
+ CheckUnify(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(uint8(), {int8(), int16(), int32(), int64()}, options);
+ CheckUnify(uint16(), {uint32(), uint64()}, options);
+ CheckUnify(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(uint16(), {int16(), int32(), int64()}, options);
+ CheckUnify(uint32(), {uint64()}, options);
+ CheckUnify(int32(), {int64()}, options);
+ CheckUnifyFails(uint32(), {int32(), int64()}, options);
+ CheckUnifyFails(uint64(), {int64()}, options);
+
+ options.promote_integer_sign = true;
+ options.promote_integer_float = false;
+ CheckUnifyFails(IntTypes(), FloatingPointTypes(), options);
+
+ options.promote_integer_float = true;
+ options.promote_numeric_width = false;
+ CheckUnifyFails(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(int32(), {int64()}, options);
+}
+
+TEST_F(TestUnifySchemas, Decimal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_decimal_float = true;
+ CheckUnify(decimal128(3, 2), {float32(), float64()}, options);
+ CheckUnify(decimal256(3, 2), {float32(), float64()}, options);
+
+ options.promote_integer_decimal = true;
+ CheckUnify(int32(), decimal128(3, 2), decimal128(3, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(3, -2), options);
+
+ options.promote_decimal = true;
+ CheckUnify(decimal128(3, 2), decimal128(5, 2), decimal128(5, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 3), decimal128(5, 3), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 1), decimal128(6, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, -2), decimal128(9, 2), options);
+ CheckUnify(decimal128(3, -2), decimal128(5, -2), decimal128(5, -2), options);
+
+ // int32() is essentially decimal128(10, 0)
+ CheckUnify(int32(), decimal128(3, 2), decimal128(12, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(10, 0), options);
+
+ CheckUnifyFails(decimal256(1, 0), decimal128(1, 0), options);
+ CheckUnifyFails(int64(), decimal128(38, 37), options);
+
+ options.promote_numeric_width = true;
+ CheckUnify(decimal128(3, 2), decimal256(5, 2), decimal256(5, 2), options);
+ CheckUnify(int32(), decimal128(38, 37), decimal256(47, 37), options);
+
+ CheckUnifyFails(int64(), decimal256(76, 75), options);
+}
+
+TEST_F(TestUnifySchemas, Temporal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_date = true;
+ CheckUnify(date32(), {date64()}, options);
+
+ options.promote_time = true;
+ CheckUnify(time32(TimeUnit::SECOND),
+ {time32(TimeUnit::MILLI), time64(TimeUnit::MICRO), time64(TimeUnit::NANO)},
+ options);
+ CheckUnify(time32(TimeUnit::MILLI), {time64(TimeUnit::MICRO), time64(TimeUnit::NANO)},
+ options);
+ CheckUnify(time64(TimeUnit::MICRO), {time64(TimeUnit::NANO)}, options);
+
+ options.promote_duration = true;
+ CheckUnify(
+ duration(TimeUnit::SECOND),
+ {duration(TimeUnit::MILLI), duration(TimeUnit::MICRO), duration(TimeUnit::NANO)},
+ options);
+ CheckUnify(duration(TimeUnit::MILLI),
+ {duration(TimeUnit::MICRO), duration(TimeUnit::NANO)}, options);
+ CheckUnify(duration(TimeUnit::MICRO), {duration(TimeUnit::NANO)}, options);
+
+ options.promote_timestamp = true;
+ CheckUnify(
+ timestamp(TimeUnit::SECOND),
+ {timestamp(TimeUnit::MILLI), timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO)},
+ options);
+ CheckUnify(timestamp(TimeUnit::MILLI),
+ {timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO)}, options);
+ CheckUnify(timestamp(TimeUnit::MICRO), {timestamp(TimeUnit::NANO)}, options);
+
+ CheckUnifyFails(timestamp(TimeUnit::SECOND), timestamp(TimeUnit::SECOND, "UTC"),
+ options);
+ CheckUnifyFails(timestamp(TimeUnit::SECOND, "America/New_York"),
+ timestamp(TimeUnit::SECOND, "UTC"), options);
+}
+
+TEST_F(TestUnifySchemas, Binary) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_large = true;
+ options.promote_binary = true;
+ CheckUnify(utf8(), {large_utf8(), binary(), large_binary()}, options);
+ CheckUnify(binary(), {large_binary()}, options);
+ CheckUnify(fixed_size_binary(2), {fixed_size_binary(2), binary(), large_binary()},
+ options);
+ CheckUnify(fixed_size_binary(2), fixed_size_binary(4), binary(), options);
+
+ options.promote_large = false;
+ CheckUnifyFails({utf8(), binary()}, {large_utf8(), large_binary()});
+ CheckUnifyFails(fixed_size_binary(2), BaseBinaryTypes());
+
+ options.promote_binary = false;
+ CheckUnifyFails(utf8(), {binary(), large_binary(), fixed_size_binary(2)});
+}
+
+TEST_F(TestUnifySchemas, List) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ CheckUnifyFails(fixed_size_list(int8(), 2),
+ {fixed_size_list(int8(), 3), list(int8()), large_list(int8())},
+ options);
+
+ options.promote_large = true;
+ CheckUnify(list(int8()), {large_list(int8())}, options);
+ CheckUnify(fixed_size_list(int8(), 2), {list(int8()), large_list(int8())}, options);
+
+ options.promote_nested = true;
+ CheckUnify(list(int8()), {list(int16()), list(int32()), list(int64())}, options);
Review Comment:
Ok, but what if `promote_nested` is disabled?
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +298,431 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_float = true;
+ options.promote_integer_decimal = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_date = true;
+ options.promote_duration = true;
+ options.promote_time = true;
+ options.promote_timestamp = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ options.promote_large = true;
+ options.promote_nested = true;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_float=" << (promote_integer_float ? "true" : "false");
+ ss << ", promote_integer_decimal=" << (promote_integer_decimal ? "true" : "false");
+ ss << ", promote_decimal_float=" << (promote_decimal_float ? "true" : "false");
+ ss << ", promote_date=" << (promote_date ? "true" : "false");
+ ss << ", promote_time=" << (promote_time ? "true" : "false");
+ ss << ", promote_duration=" << (promote_duration ? "true" : "false");
+ ss << ", promote_timestamp=" << (promote_timestamp ? "true" : "false");
+ ss << ", promote_nested=" << (promote_nested ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_large=" << (promote_large ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeSigned(const DataType& type) {
+ switch (type.id()) {
+ case Type::INT8:
+ case Type::UINT8:
+ return int8();
+ case Type::INT16:
+ case Type::UINT16:
+ return int16();
+ case Type::INT32:
+ case Type::UINT32:
+ return int32();
+ case Type::INT64:
+ case Type::UINT64:
+ return int64();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ DCHECK(false) << "unreachable";
+ }
+ return std::shared_ptr<DataType>(nullptr);
+}
+TimeUnit::type CommonTimeUnit(TimeUnit::type left, TimeUnit::type right) {
+ if (left == TimeUnit::NANO || right == TimeUnit::NANO) {
+ return TimeUnit::NANO;
+ } else if (left == TimeUnit::MICRO || right == TimeUnit::MICRO) {
+ return TimeUnit::MICRO;
+ } else if (left == TimeUnit::MILLI || right == TimeUnit::MILLI) {
+ return TimeUnit::MILLI;
+ }
+ return TimeUnit::SECOND;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::Invalid(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_date) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_duration && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(CommonTimeUnit(left.unit(), right.unit()));
+ }
+
+ if (options.promote_time && is_time(promoted_type->id()) && is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = CommonTimeUnit(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_timestamp && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::Invalid(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::Invalid("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(CommonTimeUnit(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_decimal) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ promoted_type.swap(other_type);
+ }
+
+ if (is_decimal(promoted_type->id()) && is_integer(other_type->id())) {
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(other_type,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ promoted = true;
+ }
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::Invalid(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ (options.promote_numeric_width &&
+ common_precision > BasicDecimal128::kMaxPrecision)) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+ }
+
+ if (options.promote_integer_sign) {
+ if (is_unsigned_integer(promoted_type->id()) && is_signed_integer(other_type->id())) {
+ promoted = bit_width(other_type->id()) >= bit_width(promoted_type->id());
+ promoted_type = MakeSigned(*promoted_type);
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ promoted = bit_width(promoted_type->id()) >= bit_width(other_type->id());
+ other_type = MakeSigned(*other_type);
+ }
+ }
+
+ if (options.promote_integer_float &&
+ ((is_floating(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_integer(promoted_type->id()) && is_floating(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (max_width >= 64) {
+ promoted_type = float64();
+ } else if (max_width >= 32) {
+ promoted_type = float32();
+ } else {
+ promoted_type = float16();
+ }
+ promoted = true;
+ }
+
+ if (options.promote_numeric_width) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
+ if (is_floating(promoted_type->id()) && is_floating(other_type->id())) {
+ if (max_width >= 64) {
+ return float64();
+ } else if (max_width >= 32) {
+ return float32();
+ }
+ return float16();
+ } else if (is_signed_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return int64();
+ } else if (max_width >= 32) {
+ return int32();
+ } else if (max_width >= 16) {
+ return int16();
+ }
+ return int8();
+ } else if (is_unsigned_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())) {
+ if (max_width >= 64) {
+ return uint64();
+ } else if (max_width >= 32) {
+ return uint32();
+ } else if (max_width >= 16) {
+ return uint16();
+ }
+ return uint8();
+ }
+ }
+
+ return promoted ? promoted_type : nullptr;
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ if (promoted_type->Equals(*other_type)) return promoted_type;
+
+ bool promoted = false;
+ if (options.promote_nullability) {
+ if (promoted_type->id() == Type::NA) {
+ return other_type;
+ } else if (other_type->id() == Type::NA) {
+ return promoted_type;
+ }
+ } else if (promoted_type->id() == Type::NA || other_type->id() == Type::NA) {
+ return Status::Invalid("Cannot merge type with null unless promote_nullability=true");
+ }
+
+ if (options.promote_dictionary && is_dictionary(promoted_type->id()) &&
+ is_dictionary(other_type->id())) {
+ return MergeDictionaryTypes(promoted_type, other_type, options);
+ }
+
+ ARROW_ASSIGN_OR_RAISE(auto maybe_promoted,
+ MaybeMergeTemporalTypes(promoted_type, other_type, options));
+ if (maybe_promoted) return maybe_promoted;
+
+ ARROW_ASSIGN_OR_RAISE(maybe_promoted,
+ MaybeMergeNumericTypes(promoted_type, other_type, options));
+ if (maybe_promoted) return maybe_promoted;
+
+ if (options.promote_large) {
+ if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(other_type->id())) {
+ promoted_type = binary();
+ promoted = other_type->id() == Type::BINARY;
+ }
+ if (other_type->id() == Type::FIXED_SIZE_BINARY &&
+ is_base_binary_like(promoted_type->id())) {
+ other_type = binary();
+ promoted = promoted_type->id() == Type::BINARY;
+ }
+
+ if (promoted_type->id() == Type::FIXED_SIZE_LIST &&
+ is_var_length_list(other_type->id())) {
+ promoted_type =
+ list(checked_cast<const BaseListType&>(*promoted_type).value_field());
+ promoted = other_type->Equals(*promoted_type);
+ }
+ if (other_type->id() == Type::FIXED_SIZE_LIST &&
+ is_var_length_list(promoted_type->id())) {
+ other_type = list(checked_cast<const BaseListType&>(*other_type).value_field());
+ promoted = other_type->Equals(*promoted_type);
+ }
+ }
+
+ if (options.promote_binary) {
+ if (promoted_type->id() == Type::FIXED_SIZE_BINARY &&
+ other_type->id() == Type::FIXED_SIZE_BINARY) {
+ return binary();
+ }
+ if (is_string(promoted_type->id()) && is_binary(other_type->id())) {
+ promoted_type = MakeBinary(*promoted_type);
+ promoted =
+ offset_bit_width(promoted_type->id()) == offset_bit_width(other_type->id());
+ } else if (is_binary(promoted_type->id()) && is_string(other_type->id())) {
+ other_type = MakeBinary(*other_type);
+ promoted =
+ offset_bit_width(promoted_type->id()) == offset_bit_width(other_type->id());
+ }
+ }
+
+ if (options.promote_large) {
+ if ((promoted_type->id() == Type::STRING && other_type->id() == Type::LARGE_STRING) ||
+ (promoted_type->id() == Type::LARGE_STRING && other_type->id() == Type::STRING)) {
+ return large_utf8();
+ } else if ((promoted_type->id() == Type::BINARY &&
+ other_type->id() == Type::LARGE_BINARY) ||
+ (promoted_type->id() == Type::LARGE_BINARY &&
+ other_type->id() == Type::BINARY)) {
+ return large_binary();
+ }
+ if ((promoted_type->id() == Type::LIST && other_type->id() == Type::LARGE_LIST) ||
+ (promoted_type->id() == Type::LARGE_LIST && other_type->id() == Type::LIST)) {
+ promoted_type =
+ large_list(checked_cast<const BaseListType&>(*promoted_type).value_field());
+ promoted = true;
+ }
+ }
+
+ if (options.promote_nested) {
+ if ((promoted_type->id() == Type::LIST && other_type->id() == Type::LIST) ||
+ (promoted_type->id() == Type::LARGE_LIST &&
+ other_type->id() == Type::LARGE_LIST) ||
+ (promoted_type->id() == Type::FIXED_SIZE_LIST &&
+ other_type->id() == Type::FIXED_SIZE_LIST)) {
+ const auto& left = checked_cast<const BaseListType&>(*promoted_type);
+ const auto& right = checked_cast<const BaseListType&>(*other_type);
+ ARROW_ASSIGN_OR_RAISE(
+ auto value_field,
+ left.value_field()->MergeWith(
+ *right.value_field()->WithName(left.value_field()->name()), options));
+ if (promoted_type->id() == Type::LIST) {
+ return list(std::move(value_field));
+ } else if (promoted_type->id() == Type::LARGE_LIST) {
+ return large_list(std::move(value_field));
+ }
+ const auto left_size =
+ checked_cast<const FixedSizeListType&>(*promoted_type).list_size();
+ const auto right_size =
+ checked_cast<const FixedSizeListType&>(*other_type).list_size();
+ if (left_size == right_size) {
+ return fixed_size_list(std::move(value_field), left_size);
+ }
+ return Status::Invalid("Cannot merge fixed_size_list of different sizes");
+ } else if (promoted_type->id() == Type::MAP && other_type->id() == Type::MAP) {
+ const auto& left = checked_cast<const MapType&>(*promoted_type);
+ const auto& right = checked_cast<const MapType&>(*other_type);
+ // While we try to preserve nonstandard field names here, note that
+ // MapType comparisons ignore field name. See ARROW-7173, ARROW-14999.
+ ARROW_ASSIGN_OR_RAISE(
+ auto key_field,
+ left.key_field()->MergeWith(
+ *right.key_field()->WithName(left.key_field()->name()), options));
+ ARROW_ASSIGN_OR_RAISE(
+ auto item_field,
+ left.item_field()->MergeWith(
+ *right.item_field()->WithName(left.item_field()->name()), options));
+ return map(std::move(key_field), std::move(item_field),
+ /*keys_sorted=*/left.keys_sorted() && right.keys_sorted());
Review Comment:
It's interesting that you added an option for merging different dict orderings, but not different map key sortings. Why?
##########
cpp/src/arrow/type_test.cc:
##########
@@ -983,6 +1091,242 @@ TEST_F(TestUnifySchemas, MoreSchemas) {
utf8_field->WithNullable(true)}));
}
+TEST_F(TestUnifySchemas, Numeric) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ CheckUnify(uint8(),
+ {int8(), uint16(), int16(), uint32(), int32(), uint64(), int64(), float32(),
+ float64()},
+ options);
+ CheckUnify(int8(), {int16(), int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint16(),
+ {int16(), uint32(), int32(), uint64(), int64(), float32(), float64()},
+ options);
+ CheckUnify(int16(), {int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint32(), {int32(), uint64(), int64(), float32(), float64()}, options);
+ CheckUnify(int32(), {int64(), float32(), float64()}, options);
+ CheckUnify(uint64(), {int64(), float64()}, options);
+ CheckUnify(int64(), {float64()}, options);
+ CheckUnify(float16(), {float32(), float64()}, options);
+ CheckUnify(float32(), {float64()}, options);
+ CheckUnify(uint64(), float32(), float64(), options);
+ CheckUnify(int64(), float32(), float64(), options);
+
+ options.promote_integer_sign = false;
+ CheckUnify(uint8(), {uint16(), uint32(), uint64()}, options);
+ CheckUnify(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(uint8(), {int8(), int16(), int32(), int64()}, options);
+ CheckUnify(uint16(), {uint32(), uint64()}, options);
+ CheckUnify(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(uint16(), {int16(), int32(), int64()}, options);
+ CheckUnify(uint32(), {uint64()}, options);
+ CheckUnify(int32(), {int64()}, options);
+ CheckUnifyFails(uint32(), {int32(), int64()}, options);
+ CheckUnifyFails(uint64(), {int64()}, options);
+
+ options.promote_integer_sign = true;
+ options.promote_integer_float = false;
+ CheckUnifyFails(IntTypes(), FloatingPointTypes(), options);
+
+ options.promote_integer_float = true;
+ options.promote_numeric_width = false;
+ CheckUnifyFails(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(int32(), {int64()}, options);
+}
+
+TEST_F(TestUnifySchemas, Decimal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_decimal_float = true;
+ CheckUnify(decimal128(3, 2), {float32(), float64()}, options);
+ CheckUnify(decimal256(3, 2), {float32(), float64()}, options);
+
+ options.promote_integer_decimal = true;
+ CheckUnify(int32(), decimal128(3, 2), decimal128(3, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(3, -2), options);
+
+ options.promote_decimal = true;
+ CheckUnify(decimal128(3, 2), decimal128(5, 2), decimal128(5, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 3), decimal128(5, 3), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 1), decimal128(6, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, -2), decimal128(9, 2), options);
+ CheckUnify(decimal128(3, -2), decimal128(5, -2), decimal128(5, -2), options);
+
+ // int32() is essentially decimal128(10, 0)
+ CheckUnify(int32(), decimal128(3, 2), decimal128(12, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(10, 0), options);
+
+ CheckUnifyFails(decimal256(1, 0), decimal128(1, 0), options);
+ CheckUnifyFails(int64(), decimal128(38, 37), options);
+
+ options.promote_numeric_width = true;
+ CheckUnify(decimal128(3, 2), decimal256(5, 2), decimal256(5, 2), options);
+ CheckUnify(int32(), decimal128(38, 37), decimal256(47, 37), options);
+
+ CheckUnifyFails(int64(), decimal256(76, 75), options);
+}
+
+TEST_F(TestUnifySchemas, Temporal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_date = true;
+ CheckUnify(date32(), {date64()}, options);
+
+ options.promote_time = true;
+ CheckUnify(time32(TimeUnit::SECOND),
+ {time32(TimeUnit::MILLI), time64(TimeUnit::MICRO), time64(TimeUnit::NANO)},
+ options);
+ CheckUnify(time32(TimeUnit::MILLI), {time64(TimeUnit::MICRO), time64(TimeUnit::NANO)},
+ options);
+ CheckUnify(time64(TimeUnit::MICRO), {time64(TimeUnit::NANO)}, options);
Review Comment:
You should also check that unification fails when the relevant option isn't enabled.
##########
cpp/src/arrow/type_test.cc:
##########
@@ -983,6 +1091,242 @@ TEST_F(TestUnifySchemas, MoreSchemas) {
utf8_field->WithNullable(true)}));
}
+TEST_F(TestUnifySchemas, Numeric) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ CheckUnify(uint8(),
+ {int8(), uint16(), int16(), uint32(), int32(), uint64(), int64(), float32(),
+ float64()},
+ options);
+ CheckUnify(int8(), {int16(), int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint16(),
+ {int16(), uint32(), int32(), uint64(), int64(), float32(), float64()},
+ options);
+ CheckUnify(int16(), {int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint32(), {int32(), uint64(), int64(), float32(), float64()}, options);
+ CheckUnify(int32(), {int64(), float32(), float64()}, options);
+ CheckUnify(uint64(), {int64(), float64()}, options);
+ CheckUnify(int64(), {float64()}, options);
+ CheckUnify(float16(), {float32(), float64()}, options);
+ CheckUnify(float32(), {float64()}, options);
+ CheckUnify(uint64(), float32(), float64(), options);
+ CheckUnify(int64(), float32(), float64(), options);
+
+ options.promote_integer_sign = false;
+ CheckUnify(uint8(), {uint16(), uint32(), uint64()}, options);
+ CheckUnify(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(uint8(), {int8(), int16(), int32(), int64()}, options);
+ CheckUnify(uint16(), {uint32(), uint64()}, options);
+ CheckUnify(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(uint16(), {int16(), int32(), int64()}, options);
+ CheckUnify(uint32(), {uint64()}, options);
+ CheckUnify(int32(), {int64()}, options);
+ CheckUnifyFails(uint32(), {int32(), int64()}, options);
+ CheckUnifyFails(uint64(), {int64()}, options);
+
+ options.promote_integer_sign = true;
+ options.promote_integer_float = false;
+ CheckUnifyFails(IntTypes(), FloatingPointTypes(), options);
+
+ options.promote_integer_float = true;
+ options.promote_numeric_width = false;
+ CheckUnifyFails(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(int32(), {int64()}, options);
+}
+
+TEST_F(TestUnifySchemas, Decimal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_decimal_float = true;
+ CheckUnify(decimal128(3, 2), {float32(), float64()}, options);
+ CheckUnify(decimal256(3, 2), {float32(), float64()}, options);
+
+ options.promote_integer_decimal = true;
+ CheckUnify(int32(), decimal128(3, 2), decimal128(3, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(3, -2), options);
+
+ options.promote_decimal = true;
+ CheckUnify(decimal128(3, 2), decimal128(5, 2), decimal128(5, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 3), decimal128(5, 3), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 1), decimal128(6, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, -2), decimal128(9, 2), options);
+ CheckUnify(decimal128(3, -2), decimal128(5, -2), decimal128(5, -2), options);
+
+ // int32() is essentially decimal128(10, 0)
+ CheckUnify(int32(), decimal128(3, 2), decimal128(12, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(10, 0), options);
+
+ CheckUnifyFails(decimal256(1, 0), decimal128(1, 0), options);
+ CheckUnifyFails(int64(), decimal128(38, 37), options);
+
+ options.promote_numeric_width = true;
+ CheckUnify(decimal128(3, 2), decimal256(5, 2), decimal256(5, 2), options);
+ CheckUnify(int32(), decimal128(38, 37), decimal256(47, 37), options);
+
+ CheckUnifyFails(int64(), decimal256(76, 75), options);
+}
+
+TEST_F(TestUnifySchemas, Temporal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_date = true;
+ CheckUnify(date32(), {date64()}, options);
+
+ options.promote_time = true;
+ CheckUnify(time32(TimeUnit::SECOND),
+ {time32(TimeUnit::MILLI), time64(TimeUnit::MICRO), time64(TimeUnit::NANO)},
+ options);
+ CheckUnify(time32(TimeUnit::MILLI), {time64(TimeUnit::MICRO), time64(TimeUnit::NANO)},
+ options);
+ CheckUnify(time64(TimeUnit::MICRO), {time64(TimeUnit::NANO)}, options);
+
+ options.promote_duration = true;
+ CheckUnify(
+ duration(TimeUnit::SECOND),
+ {duration(TimeUnit::MILLI), duration(TimeUnit::MICRO), duration(TimeUnit::NANO)},
+ options);
+ CheckUnify(duration(TimeUnit::MILLI),
+ {duration(TimeUnit::MICRO), duration(TimeUnit::NANO)}, options);
+ CheckUnify(duration(TimeUnit::MICRO), {duration(TimeUnit::NANO)}, options);
+
+ options.promote_timestamp = true;
+ CheckUnify(
+ timestamp(TimeUnit::SECOND),
+ {timestamp(TimeUnit::MILLI), timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO)},
+ options);
+ CheckUnify(timestamp(TimeUnit::MILLI),
+ {timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO)}, options);
+ CheckUnify(timestamp(TimeUnit::MICRO), {timestamp(TimeUnit::NANO)}, options);
+
+ CheckUnifyFails(timestamp(TimeUnit::SECOND), timestamp(TimeUnit::SECOND, "UTC"),
+ options);
+ CheckUnifyFails(timestamp(TimeUnit::SECOND, "America/New_York"),
+ timestamp(TimeUnit::SECOND, "UTC"), options);
+}
+
+TEST_F(TestUnifySchemas, Binary) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_large = true;
+ options.promote_binary = true;
+ CheckUnify(utf8(), {large_utf8(), binary(), large_binary()}, options);
+ CheckUnify(binary(), {large_binary()}, options);
+ CheckUnify(fixed_size_binary(2), {fixed_size_binary(2), binary(), large_binary()},
+ options);
+ CheckUnify(fixed_size_binary(2), fixed_size_binary(4), binary(), options);
+
+ options.promote_large = false;
+ CheckUnifyFails({utf8(), binary()}, {large_utf8(), large_binary()});
+ CheckUnifyFails(fixed_size_binary(2), BaseBinaryTypes());
+
+ options.promote_binary = false;
+ CheckUnifyFails(utf8(), {binary(), large_binary(), fixed_size_binary(2)});
+}
+
+TEST_F(TestUnifySchemas, List) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ CheckUnifyFails(fixed_size_list(int8(), 2),
+ {fixed_size_list(int8(), 3), list(int8()), large_list(int8())},
+ options);
+
+ options.promote_large = true;
+ CheckUnify(list(int8()), {large_list(int8())}, options);
+ CheckUnify(fixed_size_list(int8(), 2), {list(int8()), large_list(int8())}, options);
+
+ options.promote_nested = true;
+ CheckUnify(list(int8()), {list(int16()), list(int32()), list(int64())}, options);
+ CheckUnify(fixed_size_list(int8(), 2),
+ {fixed_size_list(int16(), 2), list(int16()), list(int32()), list(int64())},
+ options);
Review Comment:
What if I try to unify `fixed_size_list(int16, 2)` and `list(int8)`?
##########
cpp/src/arrow/type_test.cc:
##########
@@ -983,6 +1091,242 @@ TEST_F(TestUnifySchemas, MoreSchemas) {
utf8_field->WithNullable(true)}));
}
+TEST_F(TestUnifySchemas, Numeric) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ CheckUnify(uint8(),
+ {int8(), uint16(), int16(), uint32(), int32(), uint64(), int64(), float32(),
+ float64()},
+ options);
+ CheckUnify(int8(), {int16(), int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint16(),
+ {int16(), uint32(), int32(), uint64(), int64(), float32(), float64()},
+ options);
+ CheckUnify(int16(), {int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint32(), {int32(), uint64(), int64(), float32(), float64()}, options);
+ CheckUnify(int32(), {int64(), float32(), float64()}, options);
+ CheckUnify(uint64(), {int64(), float64()}, options);
+ CheckUnify(int64(), {float64()}, options);
+ CheckUnify(float16(), {float32(), float64()}, options);
+ CheckUnify(float32(), {float64()}, options);
+ CheckUnify(uint64(), float32(), float64(), options);
+ CheckUnify(int64(), float32(), float64(), options);
+
+ options.promote_integer_sign = false;
+ CheckUnify(uint8(), {uint16(), uint32(), uint64()}, options);
+ CheckUnify(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(uint8(), {int8(), int16(), int32(), int64()}, options);
+ CheckUnify(uint16(), {uint32(), uint64()}, options);
+ CheckUnify(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(uint16(), {int16(), int32(), int64()}, options);
+ CheckUnify(uint32(), {uint64()}, options);
+ CheckUnify(int32(), {int64()}, options);
+ CheckUnifyFails(uint32(), {int32(), int64()}, options);
+ CheckUnifyFails(uint64(), {int64()}, options);
+
+ options.promote_integer_sign = true;
+ options.promote_integer_float = false;
+ CheckUnifyFails(IntTypes(), FloatingPointTypes(), options);
+
+ options.promote_integer_float = true;
+ options.promote_numeric_width = false;
+ CheckUnifyFails(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(int32(), {int64()}, options);
+}
+
+TEST_F(TestUnifySchemas, Decimal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_decimal_float = true;
+ CheckUnify(decimal128(3, 2), {float32(), float64()}, options);
+ CheckUnify(decimal256(3, 2), {float32(), float64()}, options);
+
+ options.promote_integer_decimal = true;
+ CheckUnify(int32(), decimal128(3, 2), decimal128(3, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(3, -2), options);
+
+ options.promote_decimal = true;
+ CheckUnify(decimal128(3, 2), decimal128(5, 2), decimal128(5, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 3), decimal128(5, 3), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 1), decimal128(6, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, -2), decimal128(9, 2), options);
+ CheckUnify(decimal128(3, -2), decimal128(5, -2), decimal128(5, -2), options);
+
+ // int32() is essentially decimal128(10, 0)
+ CheckUnify(int32(), decimal128(3, 2), decimal128(12, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(10, 0), options);
+
+ CheckUnifyFails(decimal256(1, 0), decimal128(1, 0), options);
+ CheckUnifyFails(int64(), decimal128(38, 37), options);
+
+ options.promote_numeric_width = true;
+ CheckUnify(decimal128(3, 2), decimal256(5, 2), decimal256(5, 2), options);
+ CheckUnify(int32(), decimal128(38, 37), decimal256(47, 37), options);
+
+ CheckUnifyFails(int64(), decimal256(76, 75), options);
+}
+
+TEST_F(TestUnifySchemas, Temporal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_date = true;
+ CheckUnify(date32(), {date64()}, options);
+
+ options.promote_time = true;
+ CheckUnify(time32(TimeUnit::SECOND),
+ {time32(TimeUnit::MILLI), time64(TimeUnit::MICRO), time64(TimeUnit::NANO)},
+ options);
+ CheckUnify(time32(TimeUnit::MILLI), {time64(TimeUnit::MICRO), time64(TimeUnit::NANO)},
+ options);
+ CheckUnify(time64(TimeUnit::MICRO), {time64(TimeUnit::NANO)}, options);
+
+ options.promote_duration = true;
+ CheckUnify(
+ duration(TimeUnit::SECOND),
+ {duration(TimeUnit::MILLI), duration(TimeUnit::MICRO), duration(TimeUnit::NANO)},
+ options);
+ CheckUnify(duration(TimeUnit::MILLI),
+ {duration(TimeUnit::MICRO), duration(TimeUnit::NANO)}, options);
+ CheckUnify(duration(TimeUnit::MICRO), {duration(TimeUnit::NANO)}, options);
+
+ options.promote_timestamp = true;
+ CheckUnify(
+ timestamp(TimeUnit::SECOND),
+ {timestamp(TimeUnit::MILLI), timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO)},
+ options);
+ CheckUnify(timestamp(TimeUnit::MILLI),
+ {timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO)}, options);
+ CheckUnify(timestamp(TimeUnit::MICRO), {timestamp(TimeUnit::NANO)}, options);
+
+ CheckUnifyFails(timestamp(TimeUnit::SECOND), timestamp(TimeUnit::SECOND, "UTC"),
+ options);
+ CheckUnifyFails(timestamp(TimeUnit::SECOND, "America/New_York"),
+ timestamp(TimeUnit::SECOND, "UTC"), options);
+}
+
+TEST_F(TestUnifySchemas, Binary) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_large = true;
+ options.promote_binary = true;
+ CheckUnify(utf8(), {large_utf8(), binary(), large_binary()}, options);
+ CheckUnify(binary(), {large_binary()}, options);
+ CheckUnify(fixed_size_binary(2), {fixed_size_binary(2), binary(), large_binary()},
+ options);
+ CheckUnify(fixed_size_binary(2), fixed_size_binary(4), binary(), options);
+
+ options.promote_large = false;
+ CheckUnifyFails({utf8(), binary()}, {large_utf8(), large_binary()});
+ CheckUnifyFails(fixed_size_binary(2), BaseBinaryTypes());
+
+ options.promote_binary = false;
+ CheckUnifyFails(utf8(), {binary(), large_binary(), fixed_size_binary(2)});
+}
+
+TEST_F(TestUnifySchemas, List) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ CheckUnifyFails(fixed_size_list(int8(), 2),
+ {fixed_size_list(int8(), 3), list(int8()), large_list(int8())},
+ options);
+
+ options.promote_large = true;
+ CheckUnify(list(int8()), {large_list(int8())}, options);
+ CheckUnify(fixed_size_list(int8(), 2), {list(int8()), large_list(int8())}, options);
+
+ options.promote_nested = true;
+ CheckUnify(list(int8()), {list(int16()), list(int32()), list(int64())}, options);
+ CheckUnify(fixed_size_list(int8(), 2),
+ {fixed_size_list(int16(), 2), list(int16()), list(int32()), list(int64())},
+ options);
+
+ auto ty = list(field("foo", int8(), /*nullable=*/false));
+ CheckUnifyAsymmetric(ty, list(int8()), list(field("foo", int8(), /*nullable=*/true)),
+ options);
+ CheckUnifyAsymmetric(ty, list(field("bar", int16(), /*nullable=*/false)),
+ list(field("foo", int16(), /*nullable=*/false)), options);
+}
+
+TEST_F(TestUnifySchemas, Map) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_nested = true;
Review Comment:
Ok, but if `promote_nested` is false, what happens?
##########
cpp/src/arrow/type_test.cc:
##########
@@ -983,6 +1091,242 @@ TEST_F(TestUnifySchemas, MoreSchemas) {
utf8_field->WithNullable(true)}));
}
+TEST_F(TestUnifySchemas, Numeric) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ CheckUnify(uint8(),
+ {int8(), uint16(), int16(), uint32(), int32(), uint64(), int64(), float32(),
+ float64()},
+ options);
+ CheckUnify(int8(), {int16(), int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint16(),
+ {int16(), uint32(), int32(), uint64(), int64(), float32(), float64()},
+ options);
+ CheckUnify(int16(), {int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint32(), {int32(), uint64(), int64(), float32(), float64()}, options);
+ CheckUnify(int32(), {int64(), float32(), float64()}, options);
+ CheckUnify(uint64(), {int64(), float64()}, options);
+ CheckUnify(int64(), {float64()}, options);
+ CheckUnify(float16(), {float32(), float64()}, options);
+ CheckUnify(float32(), {float64()}, options);
+ CheckUnify(uint64(), float32(), float64(), options);
+ CheckUnify(int64(), float32(), float64(), options);
+
+ options.promote_integer_sign = false;
+ CheckUnify(uint8(), {uint16(), uint32(), uint64()}, options);
+ CheckUnify(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(uint8(), {int8(), int16(), int32(), int64()}, options);
+ CheckUnify(uint16(), {uint32(), uint64()}, options);
+ CheckUnify(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(uint16(), {int16(), int32(), int64()}, options);
+ CheckUnify(uint32(), {uint64()}, options);
+ CheckUnify(int32(), {int64()}, options);
+ CheckUnifyFails(uint32(), {int32(), int64()}, options);
+ CheckUnifyFails(uint64(), {int64()}, options);
+
+ options.promote_integer_sign = true;
+ options.promote_integer_float = false;
+ CheckUnifyFails(IntTypes(), FloatingPointTypes(), options);
+
+ options.promote_integer_float = true;
+ options.promote_numeric_width = false;
+ CheckUnifyFails(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(int32(), {int64()}, options);
+}
+
+TEST_F(TestUnifySchemas, Decimal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_decimal_float = true;
+ CheckUnify(decimal128(3, 2), {float32(), float64()}, options);
+ CheckUnify(decimal256(3, 2), {float32(), float64()}, options);
+
+ options.promote_integer_decimal = true;
+ CheckUnify(int32(), decimal128(3, 2), decimal128(3, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(3, -2), options);
+
+ options.promote_decimal = true;
+ CheckUnify(decimal128(3, 2), decimal128(5, 2), decimal128(5, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 3), decimal128(5, 3), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 1), decimal128(6, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, -2), decimal128(9, 2), options);
+ CheckUnify(decimal128(3, -2), decimal128(5, -2), decimal128(5, -2), options);
Review Comment:
What happens if I pass `decimal(38, 10)` and `decimal(38, 5)`. I expect it to fail. Can you add a test?
##########
cpp/src/arrow/type_test.cc:
##########
@@ -983,6 +1091,242 @@ TEST_F(TestUnifySchemas, MoreSchemas) {
utf8_field->WithNullable(true)}));
}
+TEST_F(TestUnifySchemas, Numeric) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ CheckUnify(uint8(),
+ {int8(), uint16(), int16(), uint32(), int32(), uint64(), int64(), float32(),
+ float64()},
+ options);
+ CheckUnify(int8(), {int16(), int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint16(),
+ {int16(), uint32(), int32(), uint64(), int64(), float32(), float64()},
+ options);
+ CheckUnify(int16(), {int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint32(), {int32(), uint64(), int64(), float32(), float64()}, options);
+ CheckUnify(int32(), {int64(), float32(), float64()}, options);
+ CheckUnify(uint64(), {int64(), float64()}, options);
+ CheckUnify(int64(), {float64()}, options);
+ CheckUnify(float16(), {float32(), float64()}, options);
+ CheckUnify(float32(), {float64()}, options);
+ CheckUnify(uint64(), float32(), float64(), options);
+ CheckUnify(int64(), float32(), float64(), options);
+
+ options.promote_integer_sign = false;
+ CheckUnify(uint8(), {uint16(), uint32(), uint64()}, options);
+ CheckUnify(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(uint8(), {int8(), int16(), int32(), int64()}, options);
+ CheckUnify(uint16(), {uint32(), uint64()}, options);
+ CheckUnify(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(uint16(), {int16(), int32(), int64()}, options);
+ CheckUnify(uint32(), {uint64()}, options);
+ CheckUnify(int32(), {int64()}, options);
+ CheckUnifyFails(uint32(), {int32(), int64()}, options);
+ CheckUnifyFails(uint64(), {int64()}, options);
+
+ options.promote_integer_sign = true;
+ options.promote_integer_float = false;
+ CheckUnifyFails(IntTypes(), FloatingPointTypes(), options);
+
+ options.promote_integer_float = true;
+ options.promote_numeric_width = false;
+ CheckUnifyFails(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(int32(), {int64()}, options);
Review Comment:
More tests seem to be missing here?
```suggestion
CheckUnifyFails(int32(), {int64()}, options);
CheckUnify(int32(), {float32()}, options);
CheckUnify(int64(), {float64()}, options);
CheckUnifyFails(int32(), {float16(), float64()}, options);
```
##########
cpp/src/arrow/type_test.cc:
##########
@@ -983,6 +1091,242 @@ TEST_F(TestUnifySchemas, MoreSchemas) {
utf8_field->WithNullable(true)}));
}
+TEST_F(TestUnifySchemas, Numeric) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ CheckUnify(uint8(),
+ {int8(), uint16(), int16(), uint32(), int32(), uint64(), int64(), float32(),
+ float64()},
+ options);
+ CheckUnify(int8(), {int16(), int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint16(),
+ {int16(), uint32(), int32(), uint64(), int64(), float32(), float64()},
+ options);
+ CheckUnify(int16(), {int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint32(), {int32(), uint64(), int64(), float32(), float64()}, options);
+ CheckUnify(int32(), {int64(), float32(), float64()}, options);
+ CheckUnify(uint64(), {int64(), float64()}, options);
+ CheckUnify(int64(), {float64()}, options);
+ CheckUnify(float16(), {float32(), float64()}, options);
+ CheckUnify(float32(), {float64()}, options);
+ CheckUnify(uint64(), float32(), float64(), options);
+ CheckUnify(int64(), float32(), float64(), options);
+
+ options.promote_integer_sign = false;
+ CheckUnify(uint8(), {uint16(), uint32(), uint64()}, options);
+ CheckUnify(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(uint8(), {int8(), int16(), int32(), int64()}, options);
+ CheckUnify(uint16(), {uint32(), uint64()}, options);
+ CheckUnify(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(uint16(), {int16(), int32(), int64()}, options);
+ CheckUnify(uint32(), {uint64()}, options);
+ CheckUnify(int32(), {int64()}, options);
+ CheckUnifyFails(uint32(), {int32(), int64()}, options);
+ CheckUnifyFails(uint64(), {int64()}, options);
+
+ options.promote_integer_sign = true;
+ options.promote_integer_float = false;
+ CheckUnifyFails(IntTypes(), FloatingPointTypes(), options);
+
+ options.promote_integer_float = true;
+ options.promote_numeric_width = false;
+ CheckUnifyFails(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(int32(), {int64()}, options);
+}
+
+TEST_F(TestUnifySchemas, Decimal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_decimal_float = true;
+ CheckUnify(decimal128(3, 2), {float32(), float64()}, options);
+ CheckUnify(decimal256(3, 2), {float32(), float64()}, options);
+
+ options.promote_integer_decimal = true;
+ CheckUnify(int32(), decimal128(3, 2), decimal128(3, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(3, -2), options);
+
+ options.promote_decimal = true;
+ CheckUnify(decimal128(3, 2), decimal128(5, 2), decimal128(5, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 3), decimal128(5, 3), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 1), decimal128(6, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, -2), decimal128(9, 2), options);
+ CheckUnify(decimal128(3, -2), decimal128(5, -2), decimal128(5, -2), options);
Review Comment:
Also, should have similar tests for `decimal256`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1274891472
##########
cpp/src/arrow/type_test.cc:
##########
@@ -983,6 +1091,242 @@ TEST_F(TestUnifySchemas, MoreSchemas) {
utf8_field->WithNullable(true)}));
}
+TEST_F(TestUnifySchemas, Numeric) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ CheckUnify(uint8(),
+ {int8(), uint16(), int16(), uint32(), int32(), uint64(), int64(), float32(),
+ float64()},
+ options);
+ CheckUnify(int8(), {int16(), int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint16(),
+ {int16(), uint32(), int32(), uint64(), int64(), float32(), float64()},
+ options);
+ CheckUnify(int16(), {int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint32(), {int32(), uint64(), int64(), float32(), float64()}, options);
+ CheckUnify(int32(), {int64(), float32(), float64()}, options);
+ CheckUnify(uint64(), {int64(), float64()}, options);
+ CheckUnify(int64(), {float64()}, options);
+ CheckUnify(float16(), {float32(), float64()}, options);
+ CheckUnify(float32(), {float64()}, options);
+ CheckUnify(uint64(), float32(), float64(), options);
+ CheckUnify(int64(), float32(), float64(), options);
+
+ options.promote_integer_sign = false;
+ CheckUnify(uint8(), {uint16(), uint32(), uint64()}, options);
+ CheckUnify(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(uint8(), {int8(), int16(), int32(), int64()}, options);
+ CheckUnify(uint16(), {uint32(), uint64()}, options);
+ CheckUnify(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(uint16(), {int16(), int32(), int64()}, options);
+ CheckUnify(uint32(), {uint64()}, options);
+ CheckUnify(int32(), {int64()}, options);
+ CheckUnifyFails(uint32(), {int32(), int64()}, options);
+ CheckUnifyFails(uint64(), {int64()}, options);
+
+ options.promote_integer_sign = true;
+ options.promote_integer_float = false;
+ CheckUnifyFails(IntTypes(), FloatingPointTypes(), options);
+
+ options.promote_integer_float = true;
+ options.promote_numeric_width = false;
+ CheckUnifyFails(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(int32(), {int64()}, options);
+}
+
+TEST_F(TestUnifySchemas, Decimal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_decimal_float = true;
+ CheckUnify(decimal128(3, 2), {float32(), float64()}, options);
+ CheckUnify(decimal256(3, 2), {float32(), float64()}, options);
+
+ options.promote_integer_decimal = true;
+ CheckUnify(int32(), decimal128(3, 2), decimal128(3, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(3, -2), options);
+
+ options.promote_decimal = true;
+ CheckUnify(decimal128(3, 2), decimal128(5, 2), decimal128(5, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 3), decimal128(5, 3), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 1), decimal128(6, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, -2), decimal128(9, 2), options);
+ CheckUnify(decimal128(3, -2), decimal128(5, -2), decimal128(5, -2), options);
+
+ // int32() is essentially decimal128(10, 0)
+ CheckUnify(int32(), decimal128(3, 2), decimal128(12, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(10, 0), options);
+
+ CheckUnifyFails(decimal256(1, 0), decimal128(1, 0), options);
+ CheckUnifyFails(int64(), decimal128(38, 37), options);
+
+ options.promote_numeric_width = true;
+ CheckUnify(decimal128(3, 2), decimal256(5, 2), decimal256(5, 2), options);
+ CheckUnify(int32(), decimal128(38, 37), decimal256(47, 37), options);
+
+ CheckUnifyFails(int64(), decimal256(76, 75), options);
+}
+
+TEST_F(TestUnifySchemas, Temporal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_date = true;
+ CheckUnify(date32(), {date64()}, options);
+
+ options.promote_time = true;
+ CheckUnify(time32(TimeUnit::SECOND),
+ {time32(TimeUnit::MILLI), time64(TimeUnit::MICRO), time64(TimeUnit::NANO)},
+ options);
+ CheckUnify(time32(TimeUnit::MILLI), {time64(TimeUnit::MICRO), time64(TimeUnit::NANO)},
+ options);
+ CheckUnify(time64(TimeUnit::MICRO), {time64(TimeUnit::NANO)}, options);
+
+ options.promote_duration = true;
+ CheckUnify(
+ duration(TimeUnit::SECOND),
+ {duration(TimeUnit::MILLI), duration(TimeUnit::MICRO), duration(TimeUnit::NANO)},
+ options);
+ CheckUnify(duration(TimeUnit::MILLI),
+ {duration(TimeUnit::MICRO), duration(TimeUnit::NANO)}, options);
+ CheckUnify(duration(TimeUnit::MICRO), {duration(TimeUnit::NANO)}, options);
+
+ options.promote_timestamp = true;
+ CheckUnify(
+ timestamp(TimeUnit::SECOND),
+ {timestamp(TimeUnit::MILLI), timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO)},
+ options);
+ CheckUnify(timestamp(TimeUnit::MILLI),
+ {timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO)}, options);
+ CheckUnify(timestamp(TimeUnit::MICRO), {timestamp(TimeUnit::NANO)}, options);
+
+ CheckUnifyFails(timestamp(TimeUnit::SECOND), timestamp(TimeUnit::SECOND, "UTC"),
+ options);
+ CheckUnifyFails(timestamp(TimeUnit::SECOND, "America/New_York"),
+ timestamp(TimeUnit::SECOND, "UTC"), options);
+}
+
+TEST_F(TestUnifySchemas, Binary) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_large = true;
+ options.promote_binary = true;
+ CheckUnify(utf8(), {large_utf8(), binary(), large_binary()}, options);
+ CheckUnify(binary(), {large_binary()}, options);
+ CheckUnify(fixed_size_binary(2), {fixed_size_binary(2), binary(), large_binary()},
+ options);
+ CheckUnify(fixed_size_binary(2), fixed_size_binary(4), binary(), options);
+
+ options.promote_large = false;
+ CheckUnifyFails({utf8(), binary()}, {large_utf8(), large_binary()});
+ CheckUnifyFails(fixed_size_binary(2), BaseBinaryTypes());
+
+ options.promote_binary = false;
+ CheckUnifyFails(utf8(), {binary(), large_binary(), fixed_size_binary(2)});
+}
+
+TEST_F(TestUnifySchemas, List) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ CheckUnifyFails(fixed_size_list(int8(), 2),
+ {fixed_size_list(int8(), 3), list(int8()), large_list(int8())},
+ options);
+
+ options.promote_large = true;
+ CheckUnify(list(int8()), {large_list(int8())}, options);
+ CheckUnify(fixed_size_list(int8(), 2), {list(int8()), large_list(int8())}, options);
+
+ options.promote_nested = true;
+ CheckUnify(list(int8()), {list(int16()), list(int32()), list(int64())}, options);
+ CheckUnify(fixed_size_list(int8(), 2),
+ {fixed_size_list(int16(), 2), list(int16()), list(int32()), list(int64())},
+ options);
+
+ auto ty = list(field("foo", int8(), /*nullable=*/false));
+ CheckUnifyAsymmetric(ty, list(int8()), list(field("foo", int8(), /*nullable=*/true)),
+ options);
+ CheckUnifyAsymmetric(ty, list(field("bar", int16(), /*nullable=*/false)),
+ list(field("foo", int16(), /*nullable=*/false)), options);
+}
+
+TEST_F(TestUnifySchemas, Map) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_nested = true;
Review Comment:
I've removed promote nested
##########
cpp/src/arrow/type_test.cc:
##########
@@ -983,6 +1091,242 @@ TEST_F(TestUnifySchemas, MoreSchemas) {
utf8_field->WithNullable(true)}));
}
+TEST_F(TestUnifySchemas, Numeric) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ options.promote_integer_float = true;
+ options.promote_integer_sign = true;
+ CheckUnify(uint8(),
+ {int8(), uint16(), int16(), uint32(), int32(), uint64(), int64(), float32(),
+ float64()},
+ options);
+ CheckUnify(int8(), {int16(), int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint16(),
+ {int16(), uint32(), int32(), uint64(), int64(), float32(), float64()},
+ options);
+ CheckUnify(int16(), {int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint32(), {int32(), uint64(), int64(), float32(), float64()}, options);
+ CheckUnify(int32(), {int64(), float32(), float64()}, options);
+ CheckUnify(uint64(), {int64(), float64()}, options);
+ CheckUnify(int64(), {float64()}, options);
+ CheckUnify(float16(), {float32(), float64()}, options);
+ CheckUnify(float32(), {float64()}, options);
+ CheckUnify(uint64(), float32(), float64(), options);
+ CheckUnify(int64(), float32(), float64(), options);
+
+ options.promote_integer_sign = false;
+ CheckUnify(uint8(), {uint16(), uint32(), uint64()}, options);
+ CheckUnify(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(uint8(), {int8(), int16(), int32(), int64()}, options);
+ CheckUnify(uint16(), {uint32(), uint64()}, options);
+ CheckUnify(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(uint16(), {int16(), int32(), int64()}, options);
+ CheckUnify(uint32(), {uint64()}, options);
+ CheckUnify(int32(), {int64()}, options);
+ CheckUnifyFails(uint32(), {int32(), int64()}, options);
+ CheckUnifyFails(uint64(), {int64()}, options);
+
+ options.promote_integer_sign = true;
+ options.promote_integer_float = false;
+ CheckUnifyFails(IntTypes(), FloatingPointTypes(), options);
+
+ options.promote_integer_float = true;
+ options.promote_numeric_width = false;
+ CheckUnifyFails(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFails(int16(), {int32(), int64()}, options);
+ CheckUnifyFails(int32(), {int64()}, options);
+}
+
+TEST_F(TestUnifySchemas, Decimal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_decimal_float = true;
+ CheckUnify(decimal128(3, 2), {float32(), float64()}, options);
+ CheckUnify(decimal256(3, 2), {float32(), float64()}, options);
+
+ options.promote_integer_decimal = true;
+ CheckUnify(int32(), decimal128(3, 2), decimal128(3, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(3, -2), options);
+
+ options.promote_decimal = true;
+ CheckUnify(decimal128(3, 2), decimal128(5, 2), decimal128(5, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 3), decimal128(5, 3), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 1), decimal128(6, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, -2), decimal128(9, 2), options);
+ CheckUnify(decimal128(3, -2), decimal128(5, -2), decimal128(5, -2), options);
+
+ // int32() is essentially decimal128(10, 0)
+ CheckUnify(int32(), decimal128(3, 2), decimal128(12, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(10, 0), options);
+
+ CheckUnifyFails(decimal256(1, 0), decimal128(1, 0), options);
+ CheckUnifyFails(int64(), decimal128(38, 37), options);
+
+ options.promote_numeric_width = true;
+ CheckUnify(decimal128(3, 2), decimal256(5, 2), decimal256(5, 2), options);
+ CheckUnify(int32(), decimal128(38, 37), decimal256(47, 37), options);
+
+ CheckUnifyFails(int64(), decimal256(76, 75), options);
+}
+
+TEST_F(TestUnifySchemas, Temporal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_date = true;
+ CheckUnify(date32(), {date64()}, options);
+
+ options.promote_time = true;
+ CheckUnify(time32(TimeUnit::SECOND),
+ {time32(TimeUnit::MILLI), time64(TimeUnit::MICRO), time64(TimeUnit::NANO)},
+ options);
+ CheckUnify(time32(TimeUnit::MILLI), {time64(TimeUnit::MICRO), time64(TimeUnit::NANO)},
+ options);
+ CheckUnify(time64(TimeUnit::MICRO), {time64(TimeUnit::NANO)}, options);
+
+ options.promote_duration = true;
+ CheckUnify(
+ duration(TimeUnit::SECOND),
+ {duration(TimeUnit::MILLI), duration(TimeUnit::MICRO), duration(TimeUnit::NANO)},
+ options);
+ CheckUnify(duration(TimeUnit::MILLI),
+ {duration(TimeUnit::MICRO), duration(TimeUnit::NANO)}, options);
+ CheckUnify(duration(TimeUnit::MICRO), {duration(TimeUnit::NANO)}, options);
+
+ options.promote_timestamp = true;
+ CheckUnify(
+ timestamp(TimeUnit::SECOND),
+ {timestamp(TimeUnit::MILLI), timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO)},
+ options);
+ CheckUnify(timestamp(TimeUnit::MILLI),
+ {timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO)}, options);
+ CheckUnify(timestamp(TimeUnit::MICRO), {timestamp(TimeUnit::NANO)}, options);
+
+ CheckUnifyFails(timestamp(TimeUnit::SECOND), timestamp(TimeUnit::SECOND, "UTC"),
+ options);
+ CheckUnifyFails(timestamp(TimeUnit::SECOND, "America/New_York"),
+ timestamp(TimeUnit::SECOND, "UTC"), options);
+}
+
+TEST_F(TestUnifySchemas, Binary) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_large = true;
+ options.promote_binary = true;
+ CheckUnify(utf8(), {large_utf8(), binary(), large_binary()}, options);
+ CheckUnify(binary(), {large_binary()}, options);
+ CheckUnify(fixed_size_binary(2), {fixed_size_binary(2), binary(), large_binary()},
+ options);
+ CheckUnify(fixed_size_binary(2), fixed_size_binary(4), binary(), options);
+
+ options.promote_large = false;
+ CheckUnifyFails({utf8(), binary()}, {large_utf8(), large_binary()});
+ CheckUnifyFails(fixed_size_binary(2), BaseBinaryTypes());
+
+ options.promote_binary = false;
+ CheckUnifyFails(utf8(), {binary(), large_binary(), fixed_size_binary(2)});
+}
+
+TEST_F(TestUnifySchemas, List) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ CheckUnifyFails(fixed_size_list(int8(), 2),
+ {fixed_size_list(int8(), 3), list(int8()), large_list(int8())},
+ options);
+
+ options.promote_large = true;
+ CheckUnify(list(int8()), {large_list(int8())}, options);
+ CheckUnify(fixed_size_list(int8(), 2), {list(int8()), large_list(int8())}, options);
+
+ options.promote_nested = true;
+ CheckUnify(list(int8()), {list(int16()), list(int32()), list(int64())}, options);
Review Comment:
I've removed promote nested
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on PR #36846:
URL: https://github.com/apache/arrow/pull/36846#issuecomment-1657267473
@github-actions autotune
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on PR #36846:
URL: https://github.com/apache/arrow/pull/36846#issuecomment-1659706914
@pitrou I addressed your comments. I appreciated your thorough review, would you be able to do another pass?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1277708614
##########
cpp/src/arrow/type.cc:
##########
@@ -327,17 +707,30 @@ Result<std::shared_ptr<Field>> Field::MergeWith(const Field& other,
return Copy();
}
- if (options.promote_nullability) {
- if (type()->Equals(other.type())) {
- return Copy()->WithNullable(nullable() || other.nullable());
+ auto maybe_promoted_type = MergeTypes(type_, other.type(), options);
+ if (!maybe_promoted_type.ok()) {
+ return maybe_promoted_type.status().WithMessage(
+ "Unable to merge: Field ", name(),
+ " has incompatible types: ", type()->ToString(), " vs ", other.type()->ToString(),
+ ": ", maybe_promoted_type.status().message());
+ }
+ auto promoted_type = *std::move(maybe_promoted_type);
+ if (promoted_type) {
+ bool nullable = nullable_;
+ if (options.promote_nullability) {
+ nullable = nullable || other.nullable() || type_->id() == Type::NA ||
+ other.type()->id() == Type::NA;
+ } else if (nullable_ != other.nullable()) {
+ return Status::TypeError("Unable to merge: Field ", name(),
+ " has incompatible nullability: ", nullable_, " vs ",
+ other.nullable());
}
- std::shared_ptr<Field> promoted = MaybePromoteNullTypes(*this, other);
- if (promoted) return promoted;
- }
- return Status::Invalid("Unable to merge: Field ", name(),
- " has incompatible types: ", type()->ToString(), " vs ",
- other.type()->ToString());
+ return std::make_shared<Field>(name_, promoted_type, nullable, metadata_);
+ }
+ return Status::TypeError("Unable to merge: Field ", name(),
Review Comment:
I would argue that this would be a `TypeError`, but I'm afraid we can't just change this.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1295870468
##########
cpp/src/arrow/type_test.cc:
##########
@@ -983,6 +1127,242 @@ TEST_F(TestUnifySchemas, MoreSchemas) {
utf8_field->WithNullable(true)}));
}
+TEST_F(TestUnifySchemas, Numeric) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ CheckUnify(uint8(),
+ {int8(), uint16(), int16(), uint32(), int32(), uint64(), int64(), float32(),
+ float64()},
+ options);
+ CheckUnify(int8(), {int16(), int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint16(),
+ {int16(), uint32(), int32(), uint64(), int64(), float32(), float64()},
+ options);
+ CheckUnify(int16(), {int32(), int64(), float32(), float64()}, options);
+ CheckUnify(uint32(), {int32(), uint64(), int64(), float32(), float64()}, options);
+ CheckUnify(int32(), {int64(), float32(), float64()}, options);
+ CheckUnify(uint64(), {int64(), float64()}, options);
+ CheckUnify(int64(), {float64()}, options);
+ CheckUnify(float16(), {float32(), float64()}, options);
+ CheckUnify(float32(), {float64()}, options);
+ CheckUnify(uint64(), float32(), float64(), options);
+ CheckUnify(int64(), float32(), float64(), options);
+
+ options.promote_integer_sign = false;
+ CheckUnify(uint8(), {uint16(), uint32(), uint64()}, options);
+ CheckUnify(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFailsInvalid(uint8(), {int8(), int16(), int32(), int64()}, options);
+ CheckUnify(uint16(), {uint32(), uint64()}, options);
+ CheckUnify(int16(), {int32(), int64()}, options);
+ CheckUnifyFailsInvalid(uint16(), {int16(), int32(), int64()}, options);
+ CheckUnify(uint32(), {uint64()}, options);
+ CheckUnify(int32(), {int64()}, options);
+ CheckUnifyFailsInvalid(uint32(), {int32(), int64()}, options);
+ CheckUnifyFailsInvalid(uint64(), {int64()}, options);
+
+ options.promote_integer_sign = true;
+ options.promote_integer_to_float = false;
+ CheckUnifyFailsInvalid(IntTypes(), FloatingPointTypes(), options);
+
+ options.promote_integer_to_float = true;
+ options.promote_numeric_width = false;
+ CheckUnifyFailsInvalid(int8(), {int16(), int32(), int64()}, options);
+ CheckUnifyFailsInvalid(int16(), {int32(), int64()}, options);
+ CheckUnifyFailsInvalid(int32(), {int64()}, options);
+ CheckUnify(int32(), {float32()}, options);
+ CheckUnify(int64(), {float64()}, options);
+ CheckUnify(int32(), float16(), float32(), options);
+}
+
+TEST_F(TestUnifySchemas, Decimal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_decimal_to_float = true;
+ CheckUnify(decimal128(3, 2), {float32(), float64()}, options);
+ CheckUnify(decimal256(3, 2), {float32(), float64()}, options);
+
+ options.promote_integer_to_decimal = true;
+ CheckUnify(int32(), decimal128(3, 2), decimal128(12, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(10, 0), options);
+
+ options.promote_decimal = true;
+ CheckUnify(decimal128(3, 2), decimal128(5, 2), decimal128(5, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 3), decimal128(5, 3), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, 1), decimal128(6, 2), options);
+ CheckUnify(decimal128(3, 2), decimal128(5, -2), decimal128(9, 2), options);
+ CheckUnify(decimal128(3, -2), decimal128(5, -2), decimal128(5, -2), options);
+ CheckUnify(decimal128(38, 10), decimal128(38, 5), decimal256(43, 10), options);
+
+ CheckUnify(decimal256(3, 2), decimal256(5, 2), decimal256(5, 2), options);
+ CheckUnify(decimal256(3, 2), decimal256(5, 3), decimal256(5, 3), options);
+ CheckUnify(decimal256(3, 2), decimal256(5, 1), decimal256(6, 2), options);
+ CheckUnify(decimal256(3, 2), decimal256(5, -2), decimal256(9, 2), options);
+ CheckUnify(decimal256(3, -2), decimal256(5, -2), decimal256(5, -2), options);
+
+ // int32() is essentially decimal128(10, 0)
+ CheckUnify(int32(), decimal128(3, 2), decimal128(12, 2), options);
+ CheckUnify(int32(), decimal128(3, -2), decimal128(10, 0), options);
+ CheckUnify(int64(), decimal128(38, 37), decimal256(56, 37), options);
+
+ CheckUnifyFailsTypeError(decimal256(1, 0), decimal128(1, 0), options);
+
+ options.promote_numeric_width = true;
+ CheckUnify(decimal128(3, 2), decimal256(5, 2), decimal256(5, 2), options);
+ CheckUnify(int32(), decimal128(38, 37), decimal256(47, 37), options);
+ CheckUnifyFailsInvalid(decimal128(38, 10), decimal256(76, 5), options);
+
+ CheckUnifyFailsInvalid(int64(), decimal256(76, 75), options);
+}
+
+TEST_F(TestUnifySchemas, Temporal) {
+ auto options = Field::MergeOptions::Defaults();
+
+ options.promote_temporal_unit = true;
+ CheckUnify(date32(), {date64()}, options);
+
+ CheckUnify(time32(TimeUnit::SECOND),
+ {time32(TimeUnit::MILLI), time64(TimeUnit::MICRO), time64(TimeUnit::NANO)},
+ options);
+ CheckUnify(time32(TimeUnit::MILLI), {time64(TimeUnit::MICRO), time64(TimeUnit::NANO)},
+ options);
+ CheckUnify(time64(TimeUnit::MICRO), {time64(TimeUnit::NANO)}, options);
+
+ CheckUnify(
+ duration(TimeUnit::SECOND),
+ {duration(TimeUnit::MILLI), duration(TimeUnit::MICRO), duration(TimeUnit::NANO)},
+ options);
+ CheckUnify(duration(TimeUnit::MILLI),
+ {duration(TimeUnit::MICRO), duration(TimeUnit::NANO)}, options);
+ CheckUnify(duration(TimeUnit::MICRO), {duration(TimeUnit::NANO)}, options);
+
+ CheckUnify(
+ timestamp(TimeUnit::SECOND),
+ {timestamp(TimeUnit::MILLI), timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO)},
+ options);
+ CheckUnify(timestamp(TimeUnit::MILLI),
+ {timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO)}, options);
+ CheckUnify(timestamp(TimeUnit::MICRO), {timestamp(TimeUnit::NANO)}, options);
+
+ CheckUnifyFailsTypeError(timestamp(TimeUnit::SECOND),
+ timestamp(TimeUnit::SECOND, "UTC"), options);
+ CheckUnifyFailsTypeError(timestamp(TimeUnit::SECOND, "America/New_York"),
+ timestamp(TimeUnit::SECOND, "UTC"), options);
+
+ options.promote_temporal_unit = false;
+ CheckUnifyFailsInvalid(timestamp(TimeUnit::MICRO), timestamp(TimeUnit::NANO), options);
+}
+
+TEST_F(TestUnifySchemas, Binary) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_binary = true;
+ CheckUnify(utf8(), {large_utf8(), binary(), large_binary()}, options);
+ CheckUnify(binary(), {large_binary()}, options);
+ CheckUnify(fixed_size_binary(2), {fixed_size_binary(2), binary(), large_binary()},
+ options);
+ CheckUnify(fixed_size_binary(2), fixed_size_binary(4), binary(), options);
+
+ options.promote_binary = false;
+ CheckUnifyFailsInvalid({utf8(), binary()}, {large_utf8(), large_binary()});
+ CheckUnifyFailsInvalid(fixed_size_binary(2), BaseBinaryTypes());
+ CheckUnifyFailsInvalid(utf8(), {binary(), large_binary(), fixed_size_binary(2)});
+}
+
+TEST_F(TestUnifySchemas, List) {
+ auto options = Field::MergeOptions::Defaults();
+ options.promote_numeric_width = true;
+ CheckUnifyFailsTypeError(fixed_size_list(int8(), 2), {fixed_size_list(int8(), 3)},
+ options);
+
+ options.promote_binary = true;
Review Comment:
No idea, removed it
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1296429597
##########
cpp/src/arrow/table.h:
##########
@@ -23,6 +23,7 @@
#include <vector>
#include "arrow/chunked_array.h" // IWYU pragma: keep
+#include "arrow/compute/cast.h"
Review Comment:
It does not seem to find the class when building the tests:
```
/usr/bin/ld: debug/libarrow.so.1300.0.0: undefined reference to `arrow::PromoteTableToSchema(std::shared_ptr<arrow::Table> const&, std::shared_ptr<arrow::Schema> const&, arrow::compute::CastOptions const&, arrow::MemoryPool*)'
collect2: error: ld returned 1 exit status
[319/835] Building CXX object src/arrow/compute/kernels/CMakeFiles/arrow-compute-scalar-if-else-test.dir/scalar_if_else_test.cc.o
ninja: build stopped: subcommand failed.
```
Any pointers?
Also, I think it would be nice to set the `CastOptions` to `::Safe()` by default, but I'm not able to get this working with the forward reference.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1295703070
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
+ ARROW_ASSIGN_OR_RAISE(auto values,
+ MergeTypes(left.value_type(), right.value_type(), options));
+ auto ordered = left.ordered() && right.ordered();
+ if (indices && values) {
+ return dictionary(indices, values, ordered);
+ } else if (values) {
+ return Status::Invalid("Could not merge index types");
+ }
+ return Status::Invalid("Could not merge value types");
+}
+
+// Merge temporal types based on options. Returns nullptr for non-temporal types.
+Result<std::shared_ptr<DataType>> MaybeMergeTemporalTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ if (options.promote_temporal_unit) {
+ if (promoted_type->id() == Type::DATE32 && other_type->id() == Type::DATE64) {
+ return date64();
+ }
+ if (promoted_type->id() == Type::DATE64 && other_type->id() == Type::DATE32) {
+ return date64();
+ }
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::DURATION &&
+ other_type->id() == Type::DURATION) {
+ const auto& left = checked_cast<const DurationType&>(*promoted_type);
+ const auto& right = checked_cast<const DurationType&>(*other_type);
+ return duration(std::max(left.unit(), right.unit()));
+ }
+
+ if (options.promote_temporal_unit && is_time(promoted_type->id()) &&
+ is_time(other_type->id())) {
+ const auto& left = checked_cast<const TimeType&>(*promoted_type);
+ const auto& right = checked_cast<const TimeType&>(*other_type);
+ const auto unit = std::max(left.unit(), right.unit());
+ if (unit == TimeUnit::MICRO || unit == TimeUnit::NANO) {
+ return time64(unit);
+ }
+ return time32(unit);
+ }
+
+ if (options.promote_temporal_unit && promoted_type->id() == Type::TIMESTAMP &&
+ other_type->id() == Type::TIMESTAMP) {
+ const auto& left = checked_cast<const TimestampType&>(*promoted_type);
+ const auto& right = checked_cast<const TimestampType&>(*other_type);
+ if (left.timezone().empty() ^ right.timezone().empty()) {
+ return Status::TypeError(
+ "Cannot merge timestamp with timezone and timestamp without timezone");
+ }
+ if (left.timezone() != right.timezone()) {
+ return Status::TypeError("Cannot merge timestamps with differing timezones");
+ }
+ return timestamp(std::max(left.unit(), right.unit()), left.timezone());
+ }
+
+ return nullptr;
+}
+
+// Merge numeric types based on options. Returns nullptr for non-numeric types.
+Result<std::shared_ptr<DataType>> MaybeMergeNumericTypes(
+ std::shared_ptr<DataType> promoted_type, std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options) {
+ bool promoted = false;
+ if (options.promote_decimal_to_float) {
+ if (is_decimal(promoted_type->id()) && is_floating(other_type->id())) {
+ promoted_type = other_type;
+ promoted = true;
+ } else if (is_floating(promoted_type->id()) && is_decimal(other_type->id())) {
+ other_type = promoted_type;
+ promoted = true;
+ }
+ }
+
+ if (options.promote_integer_to_decimal &&
+ ((is_decimal(promoted_type->id()) && is_integer(other_type->id())) ||
+ (is_decimal(other_type->id()) && is_integer(promoted_type->id())))) {
+ if (is_integer(promoted_type->id()) && is_decimal(other_type->id())) {
+ // Other type is always the int
+ promoted_type.swap(other_type);
+ }
+ ARROW_ASSIGN_OR_RAISE(const int32_t precision,
+ MaxDecimalDigitsForInteger(other_type->id()));
+ ARROW_ASSIGN_OR_RAISE(const auto promoted_decimal,
+ DecimalType::Make(promoted_type->id(), precision, 0));
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, promoted_decimal));
+ return promoted_type;
+ }
+
+ if (options.promote_decimal && is_decimal(promoted_type->id()) &&
+ is_decimal(other_type->id())) {
+ const DecimalType& left = checked_cast<const DecimalType&>(*promoted_type);
+ const DecimalType& right = checked_cast<const DecimalType&>(*other_type);
+ if (!options.promote_numeric_width && left.bit_width() != right.bit_width()) {
+ return Status::TypeError(
+ "Cannot promote decimal128 to decimal256 without promote_numeric_width=true");
+ }
+ ARROW_ASSIGN_OR_RAISE(promoted_type, WidenDecimals(promoted_type, other_type));
+ return promoted_type;
+ }
+
+ if (options.promote_integer_sign && ((is_unsigned_integer(promoted_type->id()) &&
+ is_signed_integer(other_type->id())) ||
+ (is_signed_integer(promoted_type->id()) &&
+ is_unsigned_integer(other_type->id())))) {
+ const int max_width =
+ std::max<int>(bit_width(promoted_type->id()), bit_width(other_type->id()));
Review Comment:
Yes, I agree. I've added the following check:
```c++
if (bit_width(promoted_type->id()) != bit_width(other_type->id())
&& !options.promote_numeric_width) {
return Status::TypeError(
"Cannot widen an (un)signed integer without promote_numeric_width=true");
}
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1302579007
##########
cpp/src/arrow/table.h:
##########
@@ -23,6 +23,7 @@
#include <vector>
#include "arrow/chunked_array.h" // IWYU pragma: keep
+#include "arrow/compute/cast.h"
Review Comment:
Got it, thanks. I changed the `CastOptions` to a pointer because I can't forward declare the `CastOptions::Safe()` afaik. If there is a nullpointer, it will be set to `Safe()` within the `#ifdef ARROW_COMPUTE` block. Let me know what you think
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1302615809
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
Review Comment:
Got it, thanks for the context 👍🏻
##########
cpp/src/arrow/type.cc:
##########
@@ -316,6 +299,405 @@ std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
+Field::MergeOptions Field::MergeOptions::Permissive() {
+ MergeOptions options = Defaults();
+ options.promote_nullability = true;
+ options.promote_decimal = true;
+ options.promote_decimal_to_float = true;
+ options.promote_integer_to_decimal = true;
+ options.promote_integer_to_float = true;
+ options.promote_integer_sign = true;
+ options.promote_numeric_width = true;
+ options.promote_binary = true;
+ options.promote_temporal_unit = true;
+ options.promote_dictionary = true;
+ options.promote_dictionary_ordered = false;
+ return options;
+}
+
+std::string Field::MergeOptions::ToString() const {
+ std::stringstream ss;
+ ss << "MergeOptions{";
+ ss << "promote_nullability=" << (promote_nullability ? "true" : "false");
+ ss << ", promote_numeric_width=" << (promote_numeric_width ? "true" : "false");
+ ss << ", promote_integer_to_float=" << (promote_integer_to_float ? "true" : "false");
+ ss << ", promote_integer_to_decimal="
+ << (promote_integer_to_decimal ? "true" : "false");
+ ss << ", promote_decimal_to_float=" << (promote_decimal_to_float ? "true" : "false");
+ ss << ", promote_temporal_unit=" << (promote_temporal_unit ? "true" : "false");
+ ss << ", promote_dictionary=" << (promote_dictionary ? "true" : "false");
+ ss << ", promote_integer_sign=" << (promote_integer_sign ? "true" : "false");
+ ss << ", promote_binary=" << (promote_binary ? "true" : "false");
+ ss << '}';
+ return ss.str();
+}
+
+namespace {
+// Utilities for Field::MergeWith
+
+std::shared_ptr<DataType> MakeBinary(const DataType& type) {
+ switch (type.id()) {
+ case Type::BINARY:
+ case Type::STRING:
+ return binary();
+ case Type::LARGE_BINARY:
+ case Type::LARGE_STRING:
+ return large_binary();
+ default:
+ Unreachable("Hit an unknown type");
+ }
+ return nullptr;
+}
+
+Result<std::shared_ptr<DataType>> WidenDecimals(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type) {
+ const auto& left = checked_cast<const DecimalType&>(*promoted_type);
+ const auto& right = checked_cast<const DecimalType&>(*other_type);
+ const int32_t max_scale = std::max<int32_t>(left.scale(), right.scale());
+ const int32_t common_precision =
+ std::max<int32_t>(left.precision() + max_scale - left.scale(),
+ right.precision() + max_scale - right.scale());
+ if (left.id() == Type::DECIMAL256 || right.id() == Type::DECIMAL256 ||
+ common_precision > BasicDecimal128::kMaxPrecision) {
+ return DecimalType::Make(Type::DECIMAL256, common_precision, max_scale);
+ }
+ return DecimalType::Make(Type::DECIMAL128, common_precision, max_scale);
+}
+
+Result<std::shared_ptr<DataType>> MergeTypes(std::shared_ptr<DataType> promoted_type,
+ std::shared_ptr<DataType> other_type,
+ const Field::MergeOptions& options);
+
+// Merge two dictionary types, or else give an error.
+Result<std::shared_ptr<DataType>> MergeDictionaryTypes(
+ const std::shared_ptr<DataType>& promoted_type,
+ const std::shared_ptr<DataType>& other_type, const Field::MergeOptions& options) {
+ const auto& left = checked_cast<const DictionaryType&>(*promoted_type);
+ const auto& right = checked_cast<const DictionaryType&>(*other_type);
+ if (!options.promote_dictionary_ordered && left.ordered() != right.ordered()) {
+ return Status::TypeError(
+ "Cannot merge ordered and unordered dictionary unless "
+ "promote_dictionary_ordered=true");
+ }
+ Field::MergeOptions index_options = options;
+ index_options.promote_integer_sign = true;
+ index_options.promote_numeric_width = true;
+ ARROW_ASSIGN_OR_RAISE(auto indices,
+ MergeTypes(left.index_type(), right.index_type(), index_options));
Review Comment:
Got it, thanks for the context 👍🏻
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1295520203
##########
python/pyarrow/types.pxi:
##########
@@ -3128,6 +3170,8 @@ def unify_schemas(schemas):
----------
schemas : list of Schema
Schemas to merge into a single one.
+ options : FieldMergeOptions, optional
Review Comment:
I like it, added it!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1295570141
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,63 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
+
+ /// Allow a decimal to be promoted to a float. The float type will
+ /// not itself be promoted (e.g. Decimal128 + Float32 = Float32).
+ bool promote_decimal_to_float = false;
+
+ /// Allow an integer to be promoted to a decimal.
+ ///
+ /// May fail if the decimal has insufficient precision to
+ /// accommodate the integer. (See increase_decimal_precision.)
+ bool promote_integer_to_decimal = false;
+
+ /// Allow an integer of a given bit width to be promoted to a
+ /// float; the result will be a float of an equal or greater bit
+ /// width to both of the inputs.
+ bool promote_integer_to_float = false;
+
+ /// Allow an unsigned integer of a given bit width to be promoted
+ /// to a signed integer of the equal or greater bit width.
+ bool promote_integer_sign = false;
+
+ /// Allow an integer, float, or decimal of a given bit width to be
+ /// promoted to an equivalent type of a greater bit width.
+ bool promote_numeric_width = false;
+
+ /// Allow strings to be promoted to binary types.
+ bool promote_binary = false;
+
+ /// Second to millisecond, Time32 to Time64, Time32(SECOND) to Time32(MILLI), etc
+ bool promote_temporal_unit = false;
+
+ /// Promote dictionary index types to a common type, and unify the
+ /// value types.
Review Comment:
Thank you, much better indeed
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1295577529
##########
python/pyarrow/types.pxi:
##########
@@ -1969,6 +1969,48 @@ cpdef KeyValueMetadata ensure_metadata(object meta, c_bool allow_none=False):
return KeyValueMetadata(meta)
+cdef class FieldMergeOptions(_Weakrefable):
+ """
+ Options controlling how to merge the types of two fields.
+
+ By default, types must match exactly, except the null type can be
+ merged with any other type.
+
+ """
+
+ cdef:
+ CField.CMergeOptions c_options
+
+ __slots__ = ()
+
+ def __init__(self, *):
+ self.c_options = CField.CMergeOptions.Defaults()
+
+ @staticmethod
+ def permissive():
+ """
+ Allow merging generally compatible types (e.g. float64 and int64).
+ """
+ cdef FieldMergeOptions options = FieldMergeOptions()
+ options.c_options = CField.CMergeOptions.Permissive()
+ return options
+
+ def __repr__(self) -> str:
+ return 'FieldMergeOptions(promote_nullability={},promote_decimal={},promote_decimal_to_float={},promote_integer_to_decimal={},promote_integer_to_float={},promote_integer_sign={},promote_numeric_width={},promote_binary={},promote_temporal_unit={},promote_dictionary={},promote_dictionary_ordered={})'.format(
Review Comment:
Also, `promote_integer_to_float` was missing, added those as well 👍🏻
##########
python/pyarrow/types.pxi:
##########
@@ -1969,6 +1969,48 @@ cpdef KeyValueMetadata ensure_metadata(object meta, c_bool allow_none=False):
return KeyValueMetadata(meta)
+cdef class FieldMergeOptions(_Weakrefable):
+ """
+ Options controlling how to merge the types of two fields.
+
+ By default, types must match exactly, except the null type can be
+ merged with any other type.
+
+ """
+
+ cdef:
+ CField.CMergeOptions c_options
+
+ __slots__ = ()
+
+ def __init__(self, *):
+ self.c_options = CField.CMergeOptions.Defaults()
+
+ @staticmethod
+ def permissive():
+ """
+ Allow merging generally compatible types (e.g. float64 and int64).
+ """
+ cdef FieldMergeOptions options = FieldMergeOptions()
+ options.c_options = CField.CMergeOptions.Permissive()
+ return options
+
+ def __repr__(self) -> str:
+ return 'FieldMergeOptions(promote_nullability={},promote_decimal={},promote_decimal_to_float={},promote_integer_to_decimal={},promote_integer_to_float={},promote_integer_sign={},promote_numeric_width={},promote_binary={},promote_temporal_unit={},promote_dictionary={},promote_dictionary_ordered={})'.format(
Review Comment:
Also, `promote_integer_to_float` was missing, added those as well 👍🏻
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] jorisvandenbossche commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "jorisvandenbossche (via GitHub)" <gi...@apache.org>.
jorisvandenbossche commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1336875237
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,76 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
+
+ /// Allow a decimal to be promoted to a float. The float type will
+ /// not itself be promoted (e.g. Decimal128 + Float32 = Float32).
+ bool promote_decimal_to_float = false;
+
+ /// Allow an integer to be promoted to a decimal.
+ ///
+ /// May fail if the decimal has insufficient precision to
+ /// accommodate the integer. (See increase_decimal_precision.)
Review Comment:
"increase_decimal_precision" doesn't exist? (should that be `promote_numeric_width`?)
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,67 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
Review Comment:
I don't think one was added?
##########
cpp/src/arrow/type.h:
##########
@@ -397,14 +397,76 @@ class ARROW_EXPORT Field : public detail::Fingerprintable,
/// \brief Options that control the behavior of `MergeWith`.
/// Options are to be added to allow type conversions, including integer
/// widening, promotion from integer to float, or conversion to or from boolean.
- struct MergeOptions {
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
/// If true, a Field of NullType can be unified with a Field of another type.
/// The unified field will be of the other type and become nullable.
/// Nullability will be promoted to the looser option (nullable if one is not
/// nullable).
bool promote_nullability = true;
+ /// Allow a decimal to be unified with another decimal of the same
+ /// width, adjusting scale and precision as appropriate. May fail
+ /// if the adjustment is not possible.
+ bool promote_decimal = false;
+
+ /// Allow a decimal to be promoted to a float. The float type will
+ /// not itself be promoted (e.g. Decimal128 + Float32 = Float32).
+ bool promote_decimal_to_float = false;
+
+ /// Allow an integer to be promoted to a decimal.
+ ///
+ /// May fail if the decimal has insufficient precision to
+ /// accommodate the integer. (See increase_decimal_precision.)
+ bool promote_integer_to_decimal = false;
+
+ /// Allow an integer of a given bit width to be promoted to a
+ /// float; the result will be a float of an equal or greater bit
+ /// width to both of the inputs. Examples:
+ /// - int8 + float32 = float32
+ /// - int32 + float32 = float64
+ /// - int32 + float64 = float64
+ /// Because an int32 cannot always be represented exactly in the
+ /// 24 bits of a float32 mantissa.
+ bool promote_integer_to_float = false;
+
+ /// Allow an unsigned integer of a given bit width to be promoted
+ /// to a signed integer that fits into the signed type:
+ /// uint + int16 = int16
+ /// When widening is needed, set promote_numeric_width to true:
+ /// uint16 + int16 = int32
Review Comment:
This doesn't yet seem to be happening (related to an earlier comment), with the current branch:
```
In [37]: pa.unify_schemas([pa.schema([('a', 'uint16')]), pa.schema([('a', 'int16')])], options="permissive")
Out[37]: a: int16
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] jorisvandenbossche commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "jorisvandenbossche (via GitHub)" <gi...@apache.org>.
jorisvandenbossche commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1341538386
##########
python/pyarrow/types.pxi:
##########
@@ -3174,6 +3216,9 @@ def unify_schemas(schemas):
----------
schemas : list of Schema
Schemas to merge into a single one.
+ options : FieldMergeOptions or string, optional
+ Options for merging fields with the same name (which type to promote to).
+ When passing in a string, it should be default or permissive
Review Comment:
```suggestion
When passing in a string, it should be "default" or "permissive".
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1339222000
##########
cpp/src/arrow/table.h:
##########
@@ -23,6 +23,7 @@
#include <vector>
#include "arrow/chunked_array.h" // IWYU pragma: keep
+#include "arrow/compute/cast.h"
Review Comment:
Removed the import 👍 Digging into the failing CI
##########
cpp/src/arrow/table.h:
##########
@@ -23,6 +23,7 @@
#include <vector>
#include "arrow/chunked_array.h" // IWYU pragma: keep
+#include "arrow/compute/cast.h"
Review Comment:
Removed the import 👍 Digging into the failing CI
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] kou commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "kou (via GitHub)" <gi...@apache.org>.
kou commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1322413269
##########
c_glib/test/dataset/test-file-system-dataset-factory.rb:
##########
@@ -109,9 +109,9 @@ def test_validate_fragments
point: Arrow::Int16DataType.new)
options.validate_fragments = true
message = "[file-system-dataset-factory][finish]: " +
- "Invalid: Unable to merge: " +
+ "Type Error: Unable to merge: " +
Review Comment:
```suggestion
"Type error: Unable to merge: " +
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] kou commented on a diff in pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "kou (via GitHub)" <gi...@apache.org>.
kou commented on code in PR #36846:
URL: https://github.com/apache/arrow/pull/36846#discussion_r1322472368
##########
c_glib/test/dataset/test-file-system-dataset-factory.rb:
##########
@@ -109,9 +109,9 @@ def test_validate_fragments
point: Arrow::Int16DataType.new)
options.validate_fragments = true
message = "[file-system-dataset-factory][finish]: " +
- "Invalid: Unable to merge: " +
+ "Type Error: Unable to merge: " +
Review Comment:
Please ask me anything. :-)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] Fokko commented on pull request #36846: GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables`
Posted by "Fokko (via GitHub)" <gi...@apache.org>.
Fokko commented on PR #36846:
URL: https://github.com/apache/arrow/pull/36846#issuecomment-1716386758
Hey @pitrou and @jorisvandenbossche I was off last week, but it is all green again :) I went over all the comments (hope I didn't miss any). I saw the email today on the dev list on the feature freeze of 14.0.0. It would be awesome if we can get it in, do you see any chance?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] GH-36845: [C++][Python] Allow type promotion on `pa.concat_tables` [arrow]
Posted by "jorisvandenbossche (via GitHub)" <gi...@apache.org>.
jorisvandenbossche commented on PR #36846:
URL: https://github.com/apache/arrow/pull/36846#issuecomment-1766399032
FYI, those reported performance regressions were just flakes. The timings are still stable at the same level for later commits.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org