You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@avro.apache.org by "clesaec (via GitHub)" <gi...@apache.org> on 2023/06/13 09:51:17 UTC

[GitHub] [avro] clesaec opened a new pull request, #2282: AVRO-3779: [java] any big decimal conversion

clesaec opened a new pull request, #2282:
URL: https://github.com/apache/avro/pull/2282

   <!--
   
   *Thank you very much for contributing to Apache Avro - we are happy that you want to help us improve Avro. To help the community review your contribution in the best possible way, please go through the checklist below, which will get the contribution into a shape in which it can be best reviewed.*
   
   *Please understand that we do not do this to make contributions to Avro a hassle. In order to uphold a high standard of quality for code contributions, while at the same time managing a large number of contributions, we need contributors to prepare the contributions well, and give reviewers enough contextual information for the review. Please also understand that contributions that do not follow this guide will take longer to review and thus typically be picked up with lower priority by the community.*
   
   ## Contribution Checklist
   
     - Make sure that the pull request corresponds to a [JIRA issue](https://issues.apache.org/jira/projects/AVRO/issues). Exceptions are made for typos in JavaDoc or documentation files, which need no JIRA issue.
     
     - Name the pull request in the form "AVRO-XXXX: [component] Title of the pull request", where *AVRO-XXXX* should be replaced by the actual issue number. 
       The *component* is optional, but can help identify the correct reviewers faster: either the language ("java", "python") or subsystem such as "build" or "doc" are good candidates.  
   
     - Fill out the template below to describe the changes contributed by the pull request. That will give reviewers the context they need to do the review.
     
     - Make sure that the change passes the automated tests. You can [build the entire project](https://github.com/apache/avro/blob/master/BUILD.md) or just the [language-specific SDK](https://avro.apache.org/project/how-to-contribute/#unit-tests).
   
     - Each pull request should address only one issue, not mix up code from multiple issues.
     
     - Each commit in the pull request has a meaningful commit message (including the JIRA id)
   
     - Every commit message references Jira issues in their subject lines. In addition, commits follow the guidelines from [How to write a good git commit message](https://chris.beams.io/posts/git-commit/)
       1. Subject is separated from body by a blank line
       1. Subject is limited to 50 characters (not including Jira issue reference)
       1. Subject does not end with a period
       1. Subject uses the imperative mood ("add", not "adding")
       1. Body wraps at 72 characters
       1. Body explains "what" and "why", not "how"
   
   -->
   
   ## What is the purpose of the change
   
   [AVRO-3779](https://issues.apache.org/jira/browse/AVRO-3779) propose a new feature for big decimal conversion. Current decimal conversion require to anticipate precision and scale, and so, to know in advance approximative value of it.
   This conversions, added to existing, allow to deal with completly random big decimal value. Value is store in byte buffer, completly non human readable, but keep the value.
   
   
   ## Verifying this change
   
   This change added tests 'TestBigDecimalConversion' and can be verified as follows:
   Run junit new test, or run all unit test of java module
   
   ## Documentation
   
   - Does this pull request introduce a new feature? yes
   - If yes, how is the feature documented? not documented
   


-- 
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: dev-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-3779: [java] any big decimal conversion [avro]

Posted by "KalleOlaviNiemitalo (via GitHub)" <gi...@apache.org>.
KalleOlaviNiemitalo commented on code in PR #2282:
URL: https://github.com/apache/avro/pull/2282#discussion_r1349457370


##########
doc/content/en/docs/++version++/Specification/_index.md:
##########
@@ -810,6 +810,20 @@ Scale must be zero or a positive integer less than or equal to the precision.
 
 For the purposes of schema resolution, two schemas that are `decimal` logical types _match_ if their scales and precisions match.
 
+**alternative**
+
+As it's not always possible to fix scale and precision in advance for a decimal field, `big-decimal` is another `decimal` logical type restrict to Avro _bytes_.
+
+_only available in Java_
+
+```json
+{
+  "type": "bytes",
+  "logicalType": "big-decimal"
+}
+```
+Here, as scale property is stored in value itself it needs more bytes than preceding `decimal` type, but it allows more flexibility.
+

Review Comment:
   No comments on the Java code, but I'd like to see the specification clarified a bit.
   
   * Separate the "big-decimal" description under its own `### Decimal (variable scale)` heading, for these purposes:
   
     + Gives it an ID in HTML so that it can be linked to.
     + Makes it show up in the table of contents.
     + Makes it clear that the schema-resolution matching rule of "decimal" does not apply.
   
   * Describe how the decimal value is encoded.  AFAICT, it goes like this:
   
     > A `big-decimal` logical type annotates an Avro `bytes` type, which stores the [binary encoding](https://avro.apache.org/docs/1.11.1/specification/#binary-encoding) of the following record:
     >
     > ```JSON
     > {
     >     "type": "record",
     >     "name": "BigDecimal",
     >     "doc": "Avro 'big-decimal' value encoded within 'bytes'",
     >     "fields": [
     >         {
     >             "name": "unscaled",
     >             "type": "bytes",
     >             "doc": "The two’s-complement representation of the unscaled integer value in big-endian byte order"
     >         },
     >         {
     >             "name": "scale",
     >             "type": "int",
     >             "doc": "How many digits of the unscaled value lie at the right side of the decimal point.  Must not be negative."
     >         }
     >     ]
     > }
   
     Or describe it in prose -- as long as the specification is clear enough that the logical type can be implemented without looking at how the Java code does it.
   



##########
doc/content/en/docs/++version++/Specification/_index.md:
##########
@@ -810,6 +810,20 @@ Scale must be zero or a positive integer less than or equal to the precision.
 
 For the purposes of schema resolution, two schemas that are `decimal` logical types _match_ if their scales and precisions match.
 
+**alternative**
+
+As it's not always possible to fix scale and precision in advance for a decimal field, `big-decimal` is another `decimal` logical type restrict to Avro _bytes_.
+
+_only available in Java_
+
+```json
+{
+  "type": "bytes",
+  "logicalType": "big-decimal"
+}
+```
+Here, as scale property is stored in value itself it needs more bytes than preceding `decimal` type, but it allows more flexibility.
+

Review Comment:
   No comments on the Java code, but I'd like to see the specification clarified a bit.
   
   * Separate the "big-decimal" description under its own `### Decimal (variable scale)` heading, for these purposes:
   
     + Gives it an ID in HTML so that it can be linked to.
     + Makes it show up in the table of contents.
     + Makes it clear that the schema-resolution matching rule of "decimal" does not apply.
   
   * Describe how the decimal value is encoded.  AFAICT, it goes like this:
   
     > A `big-decimal` logical type annotates an Avro `bytes` type, which stores the [binary encoding](https://avro.apache.org/docs/1.11.1/specification/#binary-encoding) of the following record:
     >
     > ```JSON
     > {
     >     "type": "record",
     >     "name": "BigDecimal",
     >     "doc": "Avro 'big-decimal' value encoded within 'bytes'",
     >     "fields": [
     >         {
     >             "name": "unscaled",
     >             "type": "bytes",
     >             "doc": "The two’s-complement representation of the unscaled integer value in big-endian byte order"
     >         },
     >         {
     >             "name": "scale",
     >             "type": "int",
     >             "doc": "How many digits of the unscaled value lie at the right side of the decimal point.  Must not be negative."
     >         }
     >     ]
     > }
   
     Or describe it in prose -- as long as the specification is clear enough that the logical type can be implemented without looking at how the Java code does 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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-3779: [java] any big decimal conversion [avro]

Posted by "clesaec (via GitHub)" <gi...@apache.org>.
clesaec merged PR #2282:
URL: https://github.com/apache/avro/pull/2282


-- 
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: dev-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [avro] opwvhk commented on a diff in pull request #2282: AVRO-3779: [java] any big decimal conversion

Posted by "opwvhk (via GitHub)" <gi...@apache.org>.
opwvhk commented on code in PR #2282:
URL: https://github.com/apache/avro/pull/2282#discussion_r1325623771


##########
lang/java/avro/src/main/java/org/apache/avro/Conversions.java:
##########
@@ -146,6 +152,65 @@ private static BigDecimal validate(final LogicalTypes.Decimal decimal, BigDecima
     }
   }
 
+  public static class BigDecimalConversion extends Conversion<BigDecimal> {
+
+    @Override
+    public Class<BigDecimal> getConvertedType() {
+      return BigDecimal.class;
+    }
+
+    @Override
+    public String getLogicalTypeName() {
+      return "bigdecimal";

Review Comment:
   This name does not equals the one in the documentation. Can we please adjust either so they're the same?



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-3779: [java] any big decimal conversion [avro]

Posted by "KalleOlaviNiemitalo (via GitHub)" <gi...@apache.org>.
KalleOlaviNiemitalo commented on PR #2282:
URL: https://github.com/apache/avro/pull/2282#issuecomment-1750450447

   For C#, the Apache.Avro library already defines an AvroDecimal type with a `public AvroDecimal(BigInteger unscaledValue, int scale)` constructor, so it doesn't need a new data type.  AFAICT, the library does not support generating an Avro schema from C# types and thus would not need to recognize an attribute for controlling whether an property with type AvroDecimal maps to the fixed-scale "decimal" logical type or to a variable-scale decimal.


-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-3779: [java] any big decimal conversion [avro]

Posted by "KalleOlaviNiemitalo (via GitHub)" <gi...@apache.org>.
KalleOlaviNiemitalo commented on PR #2282:
URL: https://github.com/apache/avro/pull/2282#issuecomment-1752636768

   > * Con: The value of the "unscaled" field in JSON could lose precision if a library reads it as a `double` (especially in JavaScript).
   
   That would not actually be a problem, because the type of the "unscaled" field would be "bytes", and its value would thus be encoded in JSON as a string rather than a number.


-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [avro] opwvhk commented on a diff in pull request #2282: AVRO-3779: [java] any big decimal conversion

Posted by "opwvhk (via GitHub)" <gi...@apache.org>.
opwvhk commented on code in PR #2282:
URL: https://github.com/apache/avro/pull/2282#discussion_r1325623771


##########
lang/java/avro/src/main/java/org/apache/avro/Conversions.java:
##########
@@ -146,6 +152,65 @@ private static BigDecimal validate(final LogicalTypes.Decimal decimal, BigDecima
     }
   }
 
+  public static class BigDecimalConversion extends Conversion<BigDecimal> {
+
+    @Override
+    public Class<BigDecimal> getConvertedType() {
+      return BigDecimal.class;
+    }
+
+    @Override
+    public String getLogicalTypeName() {
+      return "bigdecimal";

Review Comment:
   This name does not equals the one in the documentation and the tests. Can we please adjust so they're the same?



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-3779: [java] any big decimal conversion [avro]

Posted by "clesaec (via GitHub)" <gi...@apache.org>.
clesaec commented on PR #2282:
URL: https://github.com/apache/avro/pull/2282#issuecomment-1812126833

   [PR](https://github.com/apache/avro/pull/2584) ready to be reviewed @rotilho-bv 


-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [avro] opwvhk commented on a diff in pull request #2282: AVRO-3779: [java] any big decimal conversion

Posted by "opwvhk (via GitHub)" <gi...@apache.org>.
opwvhk commented on code in PR #2282:
URL: https://github.com/apache/avro/pull/2282#discussion_r1232191466


##########
lang/java/avro/src/main/java/org/apache/avro/Conversions.java:
##########
@@ -146,6 +154,65 @@ private static BigDecimal validate(final LogicalTypes.Decimal decimal, BigDecima
     }
   }
 
+  public static class BigDecimalConversion extends Conversion<BigDecimal> {
+
+    @Override
+    public Class<BigDecimal> getConvertedType() {
+      return BigDecimal.class;
+    }
+
+    @Override
+    public String getLogicalTypeName() {
+      return "bigdecimal";
+    }
+
+    @Override
+    public BigDecimal fromBytes(final ByteBuffer value, final Schema schema, final LogicalType type) {
+      BinaryDecoder decoder = DecoderFactory.get().binaryDecoder(value.array(), null);
+
+      try {
+        BigInteger bg = null;
+        ByteBuffer buffer = decoder.readBytes(null);
+        byte[] array = buffer.array();
+        if (array != null && array.length > 0) {
+          bg = new BigInteger(array);
+        }
+
+        int scale = decoder.readInt();
+        return new BigDecimal(bg, scale);
+      } catch (IOException e) {
+        throw new RuntimeException(e);
+      }
+    }
+
+    @Override
+    public ByteBuffer toBytes(final BigDecimal value, final Schema schema, final LogicalType type) {
+      try {
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+        BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(out, null);
+
+        BigInteger unscaledValue = value.unscaledValue();
+        if (unscaledValue != null) {
+          encoder.writeBytes(unscaledValue.toByteArray());
+        } else {
+          encoder.writeBytes(new byte[] {});
+        }
+        encoder.writeInt(value.scale());
+        encoder.flush();
+        return ByteBuffer.wrap(out.toByteArray());
+
+      } catch (IOException e) {
+        throw new RuntimeException(e);
+      }

Review Comment:
   Note that switching the position of the scale and value also saves a byte (or more) in the final result: the converted value no longer has a byte array length indicator.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [avro] clesaec commented on pull request #2282: AVRO-3779: [java] any big decimal conversion

Posted by "clesaec (via GitHub)" <gi...@apache.org>.
clesaec commented on PR #2282:
URL: https://github.com/apache/avro/pull/2282#issuecomment-1594682791

   Doc 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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [avro] clesaec commented on pull request #2282: AVRO-3779: [java] any big decimal conversion

Posted by "clesaec (via GitHub)" <gi...@apache.org>.
clesaec commented on PR #2282:
URL: https://github.com/apache/avro/pull/2282#issuecomment-1597243684

   In rust, this [big decimal](https://docs.diesel.rs/1.4.x/bigdecimal/struct.BigDecimal.html) definition is near the one of Java, as it contains [constructor as](https://docs.diesel.rs/1.4.x/src/bigdecimal/lib.rs.html#149)
   `pub fn new(digits: BigInt, scale: i64) -> BigDecimal {`
   
   In C#, [big rational seems](https://www.extremeoptimization.com/Documentation/Reference/Extreme.Mathematics.BigRational) even better, as it's directly a fraction of 2 big integer (so, support easily 10/3, which is not obvious in Java).
   
   i didn't look in other language, in any case, it should be possible to use the proposed stored format to a defined class (even if i first code it for Java).
   
   For the moment, i didn't see logical type with "java-type" arguments; may be i could add "lang" arg ?
   as `"langs" : ["java", "rust"]`  (adding values when PR integrated) ?


-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [avro] opwvhk commented on a diff in pull request #2282: AVRO-3779: [java] any big decimal conversion

Posted by "opwvhk (via GitHub)" <gi...@apache.org>.
opwvhk commented on code in PR #2282:
URL: https://github.com/apache/avro/pull/2282#discussion_r1232188780


##########
lang/java/avro/src/main/java/org/apache/avro/Conversions.java:
##########
@@ -146,6 +154,65 @@ private static BigDecimal validate(final LogicalTypes.Decimal decimal, BigDecima
     }
   }
 
+  public static class BigDecimalConversion extends Conversion<BigDecimal> {
+
+    @Override
+    public Class<BigDecimal> getConvertedType() {
+      return BigDecimal.class;
+    }
+
+    @Override
+    public String getLogicalTypeName() {
+      return "bigdecimal";
+    }
+
+    @Override
+    public BigDecimal fromBytes(final ByteBuffer value, final Schema schema, final LogicalType type) {
+      BinaryDecoder decoder = DecoderFactory.get().binaryDecoder(value.array(), null);
+
+      try {
+        BigInteger bg = null;
+        ByteBuffer buffer = decoder.readBytes(null);
+        byte[] array = buffer.array();
+        if (array != null && array.length > 0) {
+          bg = new BigInteger(array);
+        }
+
+        int scale = decoder.readInt();
+        return new BigDecimal(bg, scale);
+      } catch (IOException e) {
+        throw new RuntimeException(e);
+      }
+    }
+
+    @Override
+    public ByteBuffer toBytes(final BigDecimal value, final Schema schema, final LogicalType type) {
+      try {
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+        BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(out, null);
+
+        BigInteger unscaledValue = value.unscaledValue();
+        if (unscaledValue != null) {
+          encoder.writeBytes(unscaledValue.toByteArray());
+        } else {
+          encoder.writeBytes(new byte[] {});
+        }
+        encoder.writeInt(value.scale());
+        encoder.flush();
+        return ByteBuffer.wrap(out.toByteArray());
+
+      } catch (IOException e) {
+        throw new RuntimeException(e);
+      }

Review Comment:
   This is overkill: the result is going to be encoded as well...
   
   Given that the scale is usually small, and that we'd like to limit the number of bytes written, this would work as well:
   
   ```
   byte[] unscaled = value.unscaledValue().toByteArray();
   ByteBuffer buffer = ByteBuffer.allocate(unscaled.length + 5);
   int scaleSize = org.apache.avro.io.BinaryData.encodeInt(value.scale(), buffer.array(), buffer.position());
   buffer.position(buffer.position() + scaleSize);
   buffer.put(unscaled);
   buffer.flip();
   return buffer;
   ```
   
   An even better solution would be to add a 2nd version of `org.apache.avro.io.BinaryData#encodeInt` and `org.apache.avro.io.BinaryData#decodeInt` that operate on a ByteBuffer (removing the need to reposition the buffer).



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-3779: [java] any big decimal conversion [avro]

Posted by "KalleOlaviNiemitalo (via GitHub)" <gi...@apache.org>.
KalleOlaviNiemitalo commented on PR #2282:
URL: https://github.com/apache/avro/pull/2282#issuecomment-1751053046

   Yes I think that would be okay.
   
   However, I feel there should be a list of Avro spec features that are not yet supported in all languages.  So that spec changes can be approved and merged without waiting for them to be implemented in all languages, but developers of schemas can avoid using features that might not be supported in languages used by their partners.


-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [avro] clesaec commented on a diff in pull request #2282: AVRO-3779: [java] any big decimal conversion

Posted by "clesaec (via GitHub)" <gi...@apache.org>.
clesaec commented on code in PR #2282:
URL: https://github.com/apache/avro/pull/2282#discussion_r1325873656


##########
lang/java/avro/src/main/java/org/apache/avro/Conversions.java:
##########
@@ -146,6 +152,65 @@ private static BigDecimal validate(final LogicalTypes.Decimal decimal, BigDecima
     }
   }
 
+  public static class BigDecimalConversion extends Conversion<BigDecimal> {
+
+    @Override
+    public Class<BigDecimal> getConvertedType() {
+      return BigDecimal.class;
+    }
+
+    @Override
+    public String getLogicalTypeName() {
+      return "bigdecimal";

Review Comment:
   changed



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-3779: [java] any big decimal conversion [avro]

Posted by "rotilho-bv (via GitHub)" <gi...@apache.org>.
rotilho-bv commented on PR #2282:
URL: https://github.com/apache/avro/pull/2282#issuecomment-1810042575

   Hey guys! Do you have an ETA for the release of this change by 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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [avro] opwvhk commented on pull request #2282: AVRO-3779: [java] any big decimal conversion

Posted by "opwvhk (via GitHub)" <gi...@apache.org>.
opwvhk commented on PR #2282:
URL: https://github.com/apache/avro/pull/2282#issuecomment-1594575027

   What I like: the scale is part of the value, giving greater flexibility when reading (schema resolution does not provide a widening conversion for logical types like `decimal`)
   
   Personally, I would really like this to be documented in this 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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-3779: [java] any big decimal conversion [avro]

Posted by "rotilho-bv (via GitHub)" <gi...@apache.org>.
rotilho-bv commented on PR #2282:
URL: https://github.com/apache/avro/pull/2282#issuecomment-1810528627

   That would be awesome @clesaec !


-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [avro] opwvhk commented on a diff in pull request #2282: AVRO-3779: [java] any big decimal conversion

Posted by "opwvhk (via GitHub)" <gi...@apache.org>.
opwvhk commented on code in PR #2282:
URL: https://github.com/apache/avro/pull/2282#discussion_r1232188780


##########
lang/java/avro/src/main/java/org/apache/avro/Conversions.java:
##########
@@ -146,6 +154,65 @@ private static BigDecimal validate(final LogicalTypes.Decimal decimal, BigDecima
     }
   }
 
+  public static class BigDecimalConversion extends Conversion<BigDecimal> {
+
+    @Override
+    public Class<BigDecimal> getConvertedType() {
+      return BigDecimal.class;
+    }
+
+    @Override
+    public String getLogicalTypeName() {
+      return "bigdecimal";
+    }
+
+    @Override
+    public BigDecimal fromBytes(final ByteBuffer value, final Schema schema, final LogicalType type) {
+      BinaryDecoder decoder = DecoderFactory.get().binaryDecoder(value.array(), null);
+
+      try {
+        BigInteger bg = null;
+        ByteBuffer buffer = decoder.readBytes(null);
+        byte[] array = buffer.array();
+        if (array != null && array.length > 0) {
+          bg = new BigInteger(array);
+        }
+
+        int scale = decoder.readInt();
+        return new BigDecimal(bg, scale);
+      } catch (IOException e) {
+        throw new RuntimeException(e);
+      }
+    }
+
+    @Override
+    public ByteBuffer toBytes(final BigDecimal value, final Schema schema, final LogicalType type) {
+      try {
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+        BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(out, null);
+
+        BigInteger unscaledValue = value.unscaledValue();
+        if (unscaledValue != null) {
+          encoder.writeBytes(unscaledValue.toByteArray());
+        } else {
+          encoder.writeBytes(new byte[] {});
+        }
+        encoder.writeInt(value.scale());
+        encoder.flush();
+        return ByteBuffer.wrap(out.toByteArray());
+
+      } catch (IOException e) {
+        throw new RuntimeException(e);
+      }

Review Comment:
   This is overkill: the result is going to be encoded as well...
   
   Given that the scale is usually small, and that we'd like to limit the number of bytes written, this would work as well:
   
   ```
   byte[] unscaled = value.unscaledValue().toByteArray();
   ByteBuffer buffer = ByteBuffer.allocate(unscaled.length + 5);
   int scaleSize = org.apache.avro.io.BinaryData.encodeInt(value.scale(), buffer.array(), buffer.position());
   buffer.position(buffer.position() + scaleSize);
   buffer.put(unscaled);
   buffer.flip();
   return buffer;
   ```
   
   An even better solution would be to add a 2nd version of `org.apache.avro.io.BinaryData#encodeInt` and `org.apache.avro.io.BinaryData#decodeInt` that operate on a ByteBuffer (removing the need to reposition the buffer).



##########
lang/java/avro/src/main/java/org/apache/avro/Conversions.java:
##########
@@ -146,6 +154,65 @@ private static BigDecimal validate(final LogicalTypes.Decimal decimal, BigDecima
     }
   }
 
+  public static class BigDecimalConversion extends Conversion<BigDecimal> {
+
+    @Override
+    public Class<BigDecimal> getConvertedType() {
+      return BigDecimal.class;
+    }
+
+    @Override
+    public String getLogicalTypeName() {
+      return "bigdecimal";
+    }
+
+    @Override
+    public BigDecimal fromBytes(final ByteBuffer value, final Schema schema, final LogicalType type) {
+      BinaryDecoder decoder = DecoderFactory.get().binaryDecoder(value.array(), null);
+
+      try {
+        BigInteger bg = null;
+        ByteBuffer buffer = decoder.readBytes(null);
+        byte[] array = buffer.array();
+        if (array != null && array.length > 0) {
+          bg = new BigInteger(array);
+        }
+
+        int scale = decoder.readInt();
+        return new BigDecimal(bg, scale);
+      } catch (IOException e) {
+        throw new RuntimeException(e);
+      }
+    }
+
+    @Override
+    public ByteBuffer toBytes(final BigDecimal value, final Schema schema, final LogicalType type) {
+      try {
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+        BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(out, null);
+
+        BigInteger unscaledValue = value.unscaledValue();
+        if (unscaledValue != null) {
+          encoder.writeBytes(unscaledValue.toByteArray());
+        } else {
+          encoder.writeBytes(new byte[] {});
+        }
+        encoder.writeInt(value.scale());
+        encoder.flush();
+        return ByteBuffer.wrap(out.toByteArray());
+
+      } catch (IOException e) {
+        throw new RuntimeException(e);
+      }

Review Comment:
   Note that switching the position of the scale and value also saves a byte (or more) in the final result: the converted value no longer has a byte array length indicator.



-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [avro] clesaec commented on pull request #2282: AVRO-3779: [java] any big decimal conversion

Posted by "clesaec (via GitHub)" <gi...@apache.org>.
clesaec commented on PR #2282:
URL: https://github.com/apache/avro/pull/2282#issuecomment-1600904368

   this [PR](https://github.com/apache/avro/pull/2302) does same for rust BigDecimal


-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-3779: [java] any big decimal conversion [avro]

Posted by "clesaec (via GitHub)" <gi...@apache.org>.
clesaec commented on PR #2282:
URL: https://github.com/apache/avro/pull/2282#issuecomment-1750505410

   So, we can merge this and create a PR for C# that will map this big-decimal type with C# AvroDecimal 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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-3779: [java] any big decimal conversion [avro]

Posted by "clesaec (via GitHub)" <gi...@apache.org>.
clesaec commented on PR #2282:
URL: https://github.com/apache/avro/pull/2282#issuecomment-1810169366

   I don't know when the 1.12.0 is planned for release, i can put this in 1.11 branch for the future 1.11.4 release


-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-3779: [java] any big decimal conversion [avro]

Posted by "KalleOlaviNiemitalo (via GitHub)" <gi...@apache.org>.
KalleOlaviNiemitalo commented on PR #2282:
URL: https://github.com/apache/avro/pull/2282#issuecomment-1751599774

   I don't intend this comment to delay the merging of this pull request.
   
   So far, all Avro logical types annotate `fixed`, `bytes`, `string`, `int`, or `long` types.  From <https://github.com/apache/avro/pull/2282#discussion_r1349457370>, it occurs to me that "big-decimal" might be reasonable to use with a `record` type, similar to a [CBOR decimal fraction (tag number 4)](https://www.rfc-editor.org/rfc/rfc8949.html#fractions):
   
   ``` JSON
   {
       "type": "record",
       "namespace": "apache.avro.test",
       "name": "RecordOfTwoBigDecimals",
       "fields": [
           {
               "name": "dec1",
               "type": {
                   "type": "record",
                   "name": "apache.avro.BigDecimal",
                   "fields": [
                       {
                           "name": "unscaled",
                           "type": "bytes"
                       },
                       {
                           "name": "scale",
                           "type": "int"
                       }
                   ],
                   "logicalType": "big-decimal"
               }
           },
           {
               "name": "dec2",
               "type": "apache.avro.BigDecimal"
           }
       ]
   }
   ```
   
   * Pro: Would make the binary encoding a little smaller, as the length field of the "bytes" value around the "big-decimal" logical value would be omitted.
   * Pro: This would cause the JSON encoding to have "unscaled" and "scale" as separate fields, making it easier to read.
   * Con: The value of the "unscaled" field in JSON could lose precision if a library reads it as a `double` (especially in JavaScript).
   * Con: Schemas using "big-decimal" would become more cumbersome to write, as the underlying record type would have to be defined.  This could be mitigated by having the schema parser define "apache.avro.BigDecimal" implicitly if referenced but not locally defined; but if that causes the "apache.avro.BigDecimal" definition to become embedded in a schema that is uploaded to a schema registry service, then there is a risk that the schema might be considered a derivative work of Avro and require Apache legal notices to be included.
   * Con: Would require larger changes in the implementations.  The C# library does not currently support a named schema having a logical type.
   
   Overall, the difficulties of that approach seem to outweigh the benefits.


-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] AVRO-3779: [java] any big decimal conversion [avro]

Posted by "clesaec (via GitHub)" <gi...@apache.org>.
clesaec commented on PR #2282:
URL: https://github.com/apache/avro/pull/2282#issuecomment-1752613294

   Java accept named schema to have logical type, but, specially with second Con, i agree with you.
   I'll merge this PR and the rust one as there is no major opposition.


-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [avro] martin-g commented on pull request #2282: AVRO-3779: [java] any big decimal conversion

Posted by "martin-g (via GitHub)" <gi...@apache.org>.
martin-g commented on PR #2282:
URL: https://github.com/apache/avro/pull/2282#issuecomment-1597100882

   Just wondering: Could this be done with `"type": "decimal"` + `"java-type": "java.math.BigDecimal` ? Honestly I am not familiar with `java-type`.
   
   I'm asking because the new `"type": "big-decimal"` looks too Java specific to me.
   In Rust the closest I know of is https://crates.io/crates/rust_decimal. In Python I think it is https://docs.python.org/3/library/decimal.html, in C# - BigRational ?!, etc. If we are going to add something new to the Spec then we should try to make it as compatible as possible for most/all of the SDKs.


-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [avro] clesaec commented on pull request #2282: AVRO-3779: [java] any big decimal conversion

Posted by "clesaec (via GitHub)" <gi...@apache.org>.
clesaec commented on PR #2282:
URL: https://github.com/apache/avro/pull/2282#issuecomment-1594654017

   thanks,
   ok, i'll put it doc/content/en/docs/++version++/Specification/_index.md file


-- 
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: issues-unsubscribe@avro.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org