You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@iceberg.apache.org by GitBox <gi...@apache.org> on 2022/08/04 00:47:37 UTC

[GitHub] [iceberg] kbendick opened a new pull request, #5431: [SPARK] - Add Truncate Function to FunctionCatalog and Break Out Truncate Definition Into Shared Utility Class

kbendick opened a new pull request, #5431:
URL: https://github.com/apache/iceberg/pull/5431

   This is an offshoot of https://github.com/apache/iceberg/pull/5305 and partially closes https://github.com/apache/iceberg/issues/5349.
   
   Adds a `system.truncate` function that can be used in Spark SQL, as well as can be used as a `FunctionCatalog` function that can be turned into a transform for storage partitioned joins.
   
   This also breaks the definition of `Truncate` out into utility functions inside of `TruncateUtil`. Because different usages validate input at different times, all of the functions in `TruncateUtil` do not validate their input and instead assume that the input is validated by the calling code. This allows for the `Truncate` transforms to validate their width one time (on instantiation), and for the Spark `truncate` function to skip input validation for faster generated 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: issues-unsubscribe@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r938333385


##########
spark/v3.3/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkTruncateFunction.java:
##########
@@ -0,0 +1,377 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.sql;
+
+import java.math.BigDecimal;
+import java.nio.charset.StandardCharsets;
+import org.apache.iceberg.AssertHelpers;
+import org.apache.iceberg.relocated.com.google.common.io.BaseEncoding;
+import org.apache.iceberg.spark.SparkTestBaseWithCatalog;
+import org.apache.spark.sql.AnalysisException;
+import org.assertj.core.api.Assertions;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestSparkTruncateFunction extends SparkTestBaseWithCatalog {
+  public TestSparkTruncateFunction() {}
+
+  @Before
+  public void useCatalog() {
+    sql("USE %s", catalogName);
+  }
+
+  @Test
+  public void testTruncateTinyInt() {
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 0Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 1Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 5Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 9Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 10Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 11Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -1Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -5Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -10Y)"));
+    Assert.assertEquals((byte) -20, scalarSql("SELECT system.truncate(10, -11Y)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((byte) -2, scalarSql("SELECT system.truncate(2, -1Y)"));
+
+    // Check that tinyint types are allowed for the width
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(5Y, 1Y)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS tinyint))"));
+  }
+
+  @Test
+  public void testTruncateSmallInt() {
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 0S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 1S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 5S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 9S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 10S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 11S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -1S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -5S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -10S)"));
+    Assert.assertEquals((short) -20, scalarSql("SELECT system.truncate(10, -11S)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((short) -2, scalarSql("SELECT system.truncate(2, -1S)"));
+
+    // Check that short types are allowed for the width
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(5S, 1S)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS smallint))"));
+  }
+
+  @Test
+  public void testTruncateInt() {
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 0));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 1));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 5));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 9));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, %d)", 10));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, %d)", 11));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -1));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -5));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -10));
+    Assert.assertEquals(-20, scalarSql("SELECT system.truncate(10, %d)", -11));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2, scalarSql("SELECT system.truncate(2, %d)", -1));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(300, %d)", 1));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS int))"));
+  }
+
+  @Test
+  public void testTruncateBigInt() {
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 0L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 1L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 5L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 9L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 10L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 11L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -1L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -5L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -10L)"));
+    Assert.assertEquals(-20L, scalarSql("SELECT system.truncate(10, -11L)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2L, scalarSql("SELECT system.truncate(2, -1L)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS bigint))"));
+  }
+
+  @Test
+  public void testTruncateDecimal() {
+    // decimal truncation works by applying the decimal scale to the width: ie 10 scale 2 = 0.10
+    Assert.assertEquals(
+        new BigDecimal("12.30"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 2)))", 12.34));
+
+    Assert.assertEquals(
+        new BigDecimal("12.30"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 2)))", 12.30));
+
+    Assert.assertEquals(
+        new BigDecimal("12.290"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 3)))", 12.299));
+
+    Assert.assertEquals(
+        new BigDecimal("0.03"),
+        scalarSql("SELECT system.truncate(3, CAST(%f as DECIMAL(5, 2)))", 0.05));
+
+    Assert.assertEquals(
+        new BigDecimal("0.00"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 2)))", 0.05));
+
+    Assert.assertEquals(
+        new BigDecimal("-0.10"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 2)))", -0.05));
+
+    Assert.assertEquals(
+        "Implicit decimal scale and precision should be allowed",
+        new BigDecimal("12345.3480"),
+        scalarSql("SELECT system.truncate(10, 12345.3482)"));
+
+    int scale = 4;
+    BigDecimal truncatedDecimal =
+        (BigDecimal) scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(6, 4)))", -0.05);
+    Assert.assertEquals(
+        "Truncating a decimal should return a decimal with the same scale",
+        scale,
+        truncatedDecimal.scale());
+
+    Assert.assertEquals(
+        "Truncating a decimal should return a decimal with the correct scale",
+        BigDecimal.valueOf(-500, 4),
+        truncatedDecimal);
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS decimal))"));
+  }
+
+  @Test
+  public void testInvalidTypesCannotBeUsedForWidth() {
+    AssertHelpers.assertThrows(
+        "Decimal type should not be coercible to the width field",
+        AnalysisException.class,
+        "Expected truncation width to be one of [ByteType, ShortType, IntegerType]",
+        () -> scalarSql("SELECT system.truncate(CAST(12.34 as DECIMAL(9, 2)), 10)", 12.34));
+
+    AssertHelpers.assertThrows(
+        "String type should not be coercible to the width field",
+        AnalysisException.class,
+        "Expected truncation width to be one of [ByteType, ShortType, IntegerType]",
+        () -> scalarSql("SELECT system.truncate('5', 10)"));
+
+    AssertHelpers.assertThrows(
+        "Interval year to month  type should not be coercible to the width field",
+        AnalysisException.class,
+        "Expected truncation width to be one of [ByteType, ShortType, IntegerType]",
+        () -> scalarSql("SELECT system.truncate(INTERVAL '100-00' YEAR TO MONTH, 10)"));
+
+    AssertHelpers.assertThrows(
+        "Interval day-time type should not be coercible to the width field",
+        AnalysisException.class,
+        "Expected truncation width to be one of [ByteType, ShortType, IntegerType]",
+        () -> scalarSql("SELECT system.truncate(CAST('11 23:4:0' AS INTERVAL DAY TO SECOND), 10)"));
+  }
+
+  @Test
+  public void testTruncateString() {
+    Assert.assertEquals(
+        "Should system.truncate strings longer than length",
+        "abcde",
+        scalarSql("SELECT system.truncate(5, 'abcdefg')"));
+    Assert.assertEquals(
+        "Should not pad strings shorter than length",
+        "abc",
+        scalarSql("SELECT system.truncate(5, 'abc')"));
+    Assert.assertEquals(
+        "Should not alter strings equal to length",
+        "abcde",
+        scalarSql("SELECT system.truncate(5, 'abcde')"));
+    Assert.assertEquals(
+        "Should handle three-byte UTF-8 characters appropriately",
+        "测",
+        scalarSql("SELECT system.truncate(1, '测试')"));
+    Assert.assertEquals(
+        "Should handle three-byte UTF-8 characters mixed with two byte utf-8 characters",
+        "测试ra",
+        scalarSql("SELECT system.truncate(4, '测试raul试测')"));
+
+    Assert.assertEquals(
+        "Null input should return null as output",
+        null,
+        scalarSql("SELECT system.truncate(3, CAST(null AS string))"));
+
+    Assert.assertEquals(
+        "Varchar should work like string",
+        "测试ra",
+        scalarSql("SELECT system.truncate(4, CAST('测试raul试测' AS varchar(8)))"));
+
+    Assert.assertEquals(
+        "Char should work like string",
+        "测试ra",
+        scalarSql("SELECT system.truncate(4, CAST('测试raul试测' AS char(8)))"));
+  }
+
+  @Test
+  public void testTruncateBinary() {
+    Assert.assertArrayEquals(
+        new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
+        (byte[]) scalarSql("SELECT system.truncate(10, X'0102030405060708090a0b0c0d0e0f')"));
+    Assert.assertArrayEquals(
+        "Should return the same input when value is equal to truncation width",
+        "abc".getBytes(StandardCharsets.UTF_8),
+        (byte[]) scalarSql("SELECT system.truncate(3, %s)", asBytesLiteral("abcdefg")));
+    Assert.assertArrayEquals(
+        "Should not truncate, pad, or trim the input when its length is less than the width",
+        "abc\0\0".getBytes(StandardCharsets.UTF_8),
+        (byte[]) scalarSql("SELECT system.truncate(10, %s)", asBytesLiteral("abc\0\0")));
+    Assert.assertArrayEquals(
+        "Should not pad the input when its length is equal to the width",
+        "abc".getBytes(StandardCharsets.UTF_8),
+        (byte[]) scalarSql("SELECT system.truncate(3, %s)", asBytesLiteral("abc")));
+    Assert.assertArrayEquals(
+        "Should handle three-byte UTF-8 characters appropriately",
+        "测试".getBytes(StandardCharsets.UTF_8),
+        (byte[]) scalarSql("SELECT system.truncate(6, %s)", asBytesLiteral("测试_")));
+
+    Assert.assertEquals(
+        "Null input should return null as output",
+        null,
+        scalarSql("SELECT system.truncate(3, CAST(null AS binary))"));
+  }
+
+  @Test
+  public void testTruncateUsingDataframeForWidthWithVaryingWidth() {
+    // This situation is atypical but allowed. Typically, width is static as data is partitioned on
+    // one width.
+    long rumRows = 10L;
+    long numNonZero =
+        spark
+            .range(rumRows)
+            .toDF("value")
+            .selectExpr("CAST(value +1 AS INT) AS width", "value")
+            .selectExpr("system.truncate(width, value) as truncated_value")
+            .filter("truncated_value == 0")
+            .count();
+    Assert.assertEquals(
+        "A truncate function with variable widths should be usable on dataframe columns",
+        rumRows,
+        numNonZero);
+  }
+
+  @Test
+  public void testThatMagicFunctionsAreInvoked() {
+    // Magic functions have `staticinvoke` in the explain output.
+    // Non-magic calls have `applyfunctionexpression` instead.
+
+    // TinyInt
+    Assertions.assertThat(scalarSql("EXPLAIN EXTENDED select system.truncate(5, 6Y)"))
+        .asString()
+        .isNotNull()
+        .contains(
+            "staticinvoke(class org.apache.iceberg.spark.functions.TruncateFunction$TruncateTinyInt");
+
+    // SmallInt
+    Assertions.assertThat(scalarSql("EXPLAIN EXTENDED select system.truncate(5, 6S)"))
+        .asString()
+        .isNotNull()
+        .contains(
+            "staticinvoke(class org.apache.iceberg.spark.functions.TruncateFunction$TruncateSmallInt");
+
+    // Int
+    Assertions.assertThat(scalarSql("EXPLAIN EXTENDED select system.truncate(5, 6)"))
+        .asString()
+        .isNotNull()
+        .contains(
+            "staticinvoke(class org.apache.iceberg.spark.functions.TruncateFunction$TruncateInt");
+
+    // Long
+    Assertions.assertThat(scalarSql("EXPLAIN EXTENDED SELECT system.truncate(5, 6L)"))
+        .asString()
+        .isNotNull()
+        .contains(
+            "staticinvoke(class org.apache.iceberg.spark.functions.TruncateFunction$TruncateBigInt");
+
+    // String
+    Assertions.assertThat(scalarSql("EXPLAIN EXTENDED SELECT system.truncate(5, 'abcdefg')"))
+        .asString()
+        .isNotNull()
+        .contains(
+            "staticinvoke(class org.apache.iceberg.spark.functions.TruncateFunction$TruncateString");
+
+    // Decimal
+    Assertions.assertThat(scalarSql("EXPLAIN EXTENDED SELECT system.truncate(5, 12.34)"))
+        .asString()
+        .isNotNull()
+        .contains(
+            "staticinvoke(class org.apache.iceberg.spark.functions.TruncateFunction$TruncateDecimal");
+
+    // Binary
+    Assertions.assertThat(
+            scalarSql("EXPLAIN EXTENDED SELECT system.truncate(4, X'0102030405060708')"))
+        .asString()
+        .isNotNull()
+        .contains(
+            "staticinvoke(class org.apache.iceberg.spark.functions.TruncateFunction$TruncateBinary");
+  }
+
+  @Test
+  public void testMagicFunctionsResolveForTinyIntAndSmallIntWidths() {

Review Comment:
   Can you put this by the negative tests?



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r939220599


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,
+          DataTypes.StringType,
+          DataTypes.BinaryType);
+
+  private static void validateTruncationFieldType(DataType dt) {
+    if (truncateableAtomicTypes.stream().noneMatch(type -> type.sameType(dt))
+        && !(dt instanceof DecimalType)) {
+      String expectedTypes =
+          "[ByteType, ShortType, IntegerType, LongType, StringType, BinaryType, DecimalType]";
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of %s, but found %s",
+              expectedTypes, dt));
+    }
+  }
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type. Expected 2 fields but found %s", inputType.fields().length));

Review Comment:
   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: issues-unsubscribe@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r938304740


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,
+          DataTypes.StringType,
+          DataTypes.BinaryType);
+
+  private static void validateTruncationFieldType(DataType dt) {
+    if (truncateableAtomicTypes.stream().noneMatch(type -> type.sameType(dt))
+        && !(dt instanceof DecimalType)) {
+      String expectedTypes =
+          "[ByteType, ShortType, IntegerType, LongType, StringType, BinaryType, DecimalType]";
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of %s, but found %s",
+              expectedTypes, dt));
+    }
+  }
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type. Expected 2 fields but found %s", inputType.fields().length));

Review Comment:
   It's unlikely that the caller knows what you mean by "input type". While Spark passes `inputType` as a single struct here, the caller's view of the function is `truncate(6, col)`. Instead, I think this should be `Cannot bind truncate: wrong number of inputs (expected width and 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: issues-unsubscribe@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r941731012


##########
spark/v3.3/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkTruncateFunction.java:
##########
@@ -0,0 +1,377 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.sql;
+
+import java.math.BigDecimal;
+import java.nio.charset.StandardCharsets;
+import org.apache.iceberg.AssertHelpers;
+import org.apache.iceberg.relocated.com.google.common.io.BaseEncoding;
+import org.apache.iceberg.spark.SparkTestBaseWithCatalog;
+import org.apache.spark.sql.AnalysisException;
+import org.assertj.core.api.Assertions;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestSparkTruncateFunction extends SparkTestBaseWithCatalog {
+  public TestSparkTruncateFunction() {}
+
+  @Before
+  public void useCatalog() {
+    sql("USE %s", catalogName);
+  }
+
+  @Test
+  public void testTruncateTinyInt() {
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 0Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 1Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 5Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 9Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 10Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 11Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -1Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -5Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -10Y)"));
+    Assert.assertEquals((byte) -20, scalarSql("SELECT system.truncate(10, -11Y)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((byte) -2, scalarSql("SELECT system.truncate(2, -1Y)"));
+
+    // Check that tinyint types are allowed for the width
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(5Y, 1Y)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS tinyint))"));
+  }
+
+  @Test
+  public void testTruncateSmallInt() {
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 0S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 1S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 5S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 9S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 10S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 11S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -1S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -5S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -10S)"));
+    Assert.assertEquals((short) -20, scalarSql("SELECT system.truncate(10, -11S)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((short) -2, scalarSql("SELECT system.truncate(2, -1S)"));
+
+    // Check that short types are allowed for the width
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(5S, 1S)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS smallint))"));
+  }
+
+  @Test
+  public void testTruncateInt() {
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 0));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 1));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 5));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 9));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, %d)", 10));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, %d)", 11));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -1));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -5));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -10));
+    Assert.assertEquals(-20, scalarSql("SELECT system.truncate(10, %d)", -11));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2, scalarSql("SELECT system.truncate(2, %d)", -1));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(300, %d)", 1));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS int))"));
+  }
+
+  @Test
+  public void testTruncateBigInt() {
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 0L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 1L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 5L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 9L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 10L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 11L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -1L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -5L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -10L)"));
+    Assert.assertEquals(-20L, scalarSql("SELECT system.truncate(10, -11L)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2L, scalarSql("SELECT system.truncate(2, -1L)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS bigint))"));
+  }
+
+  @Test
+  public void testTruncateDecimal() {
+    // decimal truncation works by applying the decimal scale to the width: ie 10 scale 2 = 0.10
+    Assert.assertEquals(
+        new BigDecimal("12.30"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 2)))", 12.34));
+
+    Assert.assertEquals(
+        new BigDecimal("12.30"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 2)))", 12.30));
+
+    Assert.assertEquals(
+        new BigDecimal("12.290"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 3)))", 12.299));
+
+    Assert.assertEquals(
+        new BigDecimal("0.03"),
+        scalarSql("SELECT system.truncate(3, CAST(%f as DECIMAL(5, 2)))", 0.05));
+
+    Assert.assertEquals(
+        new BigDecimal("0.00"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 2)))", 0.05));
+
+    Assert.assertEquals(
+        new BigDecimal("-0.10"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 2)))", -0.05));
+
+    Assert.assertEquals(
+        "Implicit decimal scale and precision should be allowed",
+        new BigDecimal("12345.3480"),
+        scalarSql("SELECT system.truncate(10, 12345.3482)"));
+
+    int scale = 4;
+    BigDecimal truncatedDecimal =
+        (BigDecimal) scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(6, 4)))", -0.05);
+    Assert.assertEquals(
+        "Truncating a decimal should return a decimal with the same scale",
+        scale,
+        truncatedDecimal.scale());
+
+    Assert.assertEquals(
+        "Truncating a decimal should return a decimal with the correct scale",
+        BigDecimal.valueOf(-500, 4),
+        truncatedDecimal);
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS decimal))"));
+  }
+
+  @Test
+  public void testInvalidTypesCannotBeUsedForWidth() {

Review Comment:
   Yeah I have tests for that already. But I'll make it more explicit.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r942935489


##########
api/src/main/java/org/apache/iceberg/util/UnicodeUtil.java:
##########
@@ -40,6 +40,17 @@ public static boolean isCharHighSurrogate(char ch) {
    */
   public static CharSequence truncateString(CharSequence input, int length) {
     Preconditions.checkArgument(length > 0, "Truncate length should be positive");
+    return truncateStringUnsafe(length, input);
+  }
+
+  /**
+   * Truncate the input charSequence such that the returned charSequence is a valid unicode string
+   * and the number of unicode characters in the truncated charSequence is lesser than or equal to
+   * length.
+   *
+   * <p>Note that this function does not validate the input

Review Comment:
   Reverted. I might open another PR with these changes as right now the `truncateString` call in the truncate transform validates the input length for every input which is unnecessary.
   
   But it's out of scope for this PR. 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: issues-unsubscribe@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r942959140


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,348 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of [ByteType, ShortType, IntegerType, LongType, "
+                  + "DecimalType, StringType, BinaryType], but found %s",

Review Comment:
   Okay, then we don't need all the context. In that case, just change it to `Expected tinyint, shortint, int, long, decimal, string, or binary: interval year to month `



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r941793922


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,
+          DataTypes.StringType,
+          DataTypes.BinaryType);
+
+  private static void validateTruncationFieldType(DataType dt) {
+    if (truncateableAtomicTypes.stream().noneMatch(type -> type.sameType(dt))
+        && !(dt instanceof DecimalType)) {
+      String expectedTypes =
+          "[ByteType, ShortType, IntegerType, LongType, StringType, BinaryType, DecimalType]";
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of %s, but found %s",
+              expectedTypes, dt));
+    }
+  }
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type. Expected 2 fields but found %s", inputType.fields().length));
+    }
+
+    StructField widthField = inputType.apply(0);
+    StructField toTruncateField = inputType.apply(1);
+
+    validateTruncationFieldType(toTruncateField.dataType());
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType
+        || toTruncateDataType instanceof VarcharType
+        || toTruncateDataType instanceof CharType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException("Cannot truncate type: " + toTruncateDataType);
+    }
+  }
+
+  @Override
+  public String description() {
+    return "Truncate - The Iceberg truncate function used for truncate partition transformations.\n"
+        + "\tCalled with the truncation width as the first argument: e.g. system.truncate(width, col)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Byte toTruncate = !input.isNullAt(1) ? input.getByte(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Short toTruncate = !input.isNullAt(1) ? input.getShort(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateInt extends TruncateBase<Integer> {
+    // magic method used in codegen
+    public static int invoke(int width, int value) {
+      return TruncateUtil.truncateInt(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.IntegerType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.IntegerType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](int)";
+    }
+
+    @Override
+    public Integer produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Integer toTruncate = !input.isNullAt(1) ? input.getInt(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateBigInt extends TruncateBase<Long> {
+    // magic function for usage with codegen
+    public static long invoke(int width, long value) {
+      return TruncateUtil.truncateLong(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.LongType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.LongType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](bigint)";
+    }
+
+    @Override
+    public Long produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Long toTruncate = !input.isNullAt(1) ? input.getLong(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateString extends TruncateBase<UTF8String> {
+    // magic function for usage with codegen
+    // TODO - This can likely be made more efficient, but using existing definition for now.
+    public static UTF8String invoke(int width, UTF8String value) {
+      if (value == null) {
+        return null;
+      }
+
+      ByteBuffer bb = value.getByteBuffer();
+      CharSequence charSequence = StandardCharsets.UTF_8.decode(bb);
+      CharSequence truncated = UnicodeUtil.truncateString(charSequence, width);
+      ByteBuffer truncatedBytes = StandardCharsets.UTF_8.encode(CharBuffer.wrap(truncated));
+      return UTF8String.fromBytes(ByteBuffers.toByteArray(truncatedBytes));
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.StringType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.StringType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](string)";
+    }
+
+    @Override
+    public UTF8String produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      UTF8String toTruncate = !input.isNullAt(1) ? input.getUTF8String(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateBinary extends TruncateBase<byte[]> {
+    // magic method used in codegen
+    public static byte[] invoke(int width, byte[] value) {
+      if (value == null) {
+        return null;
+      }
+
+      return ByteBuffers.toByteArray(
+          TruncateUtil.truncateByteBuffer(width, ByteBuffer.wrap(value)));
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.BinaryType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.BinaryType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](binary)";
+    }
+
+    @Override
+    public byte[] produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      byte[] toTruncate = !input.isNullAt(1) ? input.getBinary(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateDecimal extends TruncateBase<Decimal> {
+    private final int precision;
+    private final int scale;
+
+    public TruncateDecimal(int precision, int scale) {
+      this.precision = precision;
+      this.scale = scale;
+    }
+
+    // magic method used in codegen
+    public static Decimal invoke(int width, Decimal value) {
+      if (value == null) {
+        return null;
+      }
+
+      return Decimal.apply(
+          TruncateUtil.truncateDecimal(BigInteger.valueOf(width), value.toJavaBigDecimal()));
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.createDecimalType(precision, scale)};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.createDecimalType(precision, scale);
+    }
+
+    @Override
+    public String canonicalName() {
+      return String.format("iceberg.truncate[width](decimal(%d,%d))", precision, scale);
+    }
+
+    @Override
+    public Decimal produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Decimal toTruncate = !input.isNullAt(1) ? input.getDecimal(1, precision, scale) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  private static Integer readAndValidateWidth(InternalRow input) {

Review Comment:
   Removed the boxing.
   
   For reference, the magic functions that take in only primitives will return `null` if the input width (an int) is `null`. But I think this is fine as `produceResult` isn't really called 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: issues-unsubscribe@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r941749236


##########
spark/v3.3/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkTruncateFunction.java:
##########
@@ -0,0 +1,377 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.sql;
+
+import java.math.BigDecimal;
+import java.nio.charset.StandardCharsets;
+import org.apache.iceberg.AssertHelpers;
+import org.apache.iceberg.relocated.com.google.common.io.BaseEncoding;
+import org.apache.iceberg.spark.SparkTestBaseWithCatalog;
+import org.apache.spark.sql.AnalysisException;
+import org.assertj.core.api.Assertions;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestSparkTruncateFunction extends SparkTestBaseWithCatalog {
+  public TestSparkTruncateFunction() {}
+
+  @Before
+  public void useCatalog() {
+    sql("USE %s", catalogName);
+  }
+
+  @Test
+  public void testTruncateTinyInt() {
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 0Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 1Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 5Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 9Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 10Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 11Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -1Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -5Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -10Y)"));
+    Assert.assertEquals((byte) -20, scalarSql("SELECT system.truncate(10, -11Y)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((byte) -2, scalarSql("SELECT system.truncate(2, -1Y)"));
+
+    // Check that tinyint types are allowed for the width
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(5Y, 1Y)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS tinyint))"));
+  }
+
+  @Test
+  public void testTruncateSmallInt() {
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 0S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 1S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 5S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 9S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 10S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 11S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -1S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -5S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -10S)"));
+    Assert.assertEquals((short) -20, scalarSql("SELECT system.truncate(10, -11S)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((short) -2, scalarSql("SELECT system.truncate(2, -1S)"));
+
+    // Check that short types are allowed for the width
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(5S, 1S)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS smallint))"));
+  }
+
+  @Test
+  public void testTruncateInt() {
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 0));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 1));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 5));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 9));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, %d)", 10));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, %d)", 11));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -1));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -5));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -10));
+    Assert.assertEquals(-20, scalarSql("SELECT system.truncate(10, %d)", -11));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2, scalarSql("SELECT system.truncate(2, %d)", -1));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(300, %d)", 1));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS int))"));
+  }
+
+  @Test
+  public void testTruncateBigInt() {
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 0L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 1L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 5L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 9L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 10L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 11L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -1L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -5L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -10L)"));
+    Assert.assertEquals(-20L, scalarSql("SELECT system.truncate(10, -11L)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2L, scalarSql("SELECT system.truncate(2, -1L)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS bigint))"));
+  }
+
+  @Test
+  public void testTruncateDecimal() {
+    // decimal truncation works by applying the decimal scale to the width: ie 10 scale 2 = 0.10
+    Assert.assertEquals(
+        new BigDecimal("12.30"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 2)))", 12.34));

Review Comment:
   Good point. Updated to use format strings with string values for the decimal test cases.



##########
spark/v3.3/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkTruncateFunction.java:
##########
@@ -0,0 +1,377 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.sql;
+
+import java.math.BigDecimal;
+import java.nio.charset.StandardCharsets;
+import org.apache.iceberg.AssertHelpers;
+import org.apache.iceberg.relocated.com.google.common.io.BaseEncoding;
+import org.apache.iceberg.spark.SparkTestBaseWithCatalog;
+import org.apache.spark.sql.AnalysisException;
+import org.assertj.core.api.Assertions;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestSparkTruncateFunction extends SparkTestBaseWithCatalog {
+  public TestSparkTruncateFunction() {}
+
+  @Before
+  public void useCatalog() {
+    sql("USE %s", catalogName);
+  }
+
+  @Test
+  public void testTruncateTinyInt() {
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 0Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 1Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 5Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 9Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 10Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 11Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -1Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -5Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -10Y)"));
+    Assert.assertEquals((byte) -20, scalarSql("SELECT system.truncate(10, -11Y)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((byte) -2, scalarSql("SELECT system.truncate(2, -1Y)"));
+
+    // Check that tinyint types are allowed for the width
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(5Y, 1Y)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS tinyint))"));
+  }
+
+  @Test
+  public void testTruncateSmallInt() {
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 0S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 1S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 5S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 9S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 10S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 11S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -1S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -5S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -10S)"));
+    Assert.assertEquals((short) -20, scalarSql("SELECT system.truncate(10, -11S)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((short) -2, scalarSql("SELECT system.truncate(2, -1S)"));
+
+    // Check that short types are allowed for the width
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(5S, 1S)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS smallint))"));
+  }
+
+  @Test
+  public void testTruncateInt() {
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 0));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 1));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 5));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 9));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, %d)", 10));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, %d)", 11));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -1));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -5));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -10));
+    Assert.assertEquals(-20, scalarSql("SELECT system.truncate(10, %d)", -11));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2, scalarSql("SELECT system.truncate(2, %d)", -1));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(300, %d)", 1));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS int))"));
+  }
+
+  @Test
+  public void testTruncateBigInt() {
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 0L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 1L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 5L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 9L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 10L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 11L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -1L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -5L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -10L)"));
+    Assert.assertEquals(-20L, scalarSql("SELECT system.truncate(10, -11L)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2L, scalarSql("SELECT system.truncate(2, -1L)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS bigint))"));
+  }
+
+  @Test
+  public void testTruncateDecimal() {
+    // decimal truncation works by applying the decimal scale to the width: ie 10 scale 2 = 0.10
+    Assert.assertEquals(
+        new BigDecimal("12.30"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 2)))", 12.34));
+
+    Assert.assertEquals(
+        new BigDecimal("12.30"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 2)))", 12.30));
+
+    Assert.assertEquals(
+        new BigDecimal("12.290"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 3)))", 12.299));
+
+    Assert.assertEquals(
+        new BigDecimal("0.03"),
+        scalarSql("SELECT system.truncate(3, CAST(%f as DECIMAL(5, 2)))", 0.05));
+
+    Assert.assertEquals(
+        new BigDecimal("0.00"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 2)))", 0.05));
+
+    Assert.assertEquals(
+        new BigDecimal("-0.10"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 2)))", -0.05));
+
+    Assert.assertEquals(
+        "Implicit decimal scale and precision should be allowed",
+        new BigDecimal("12345.3480"),
+        scalarSql("SELECT system.truncate(10, 12345.3482)"));
+
+    int scale = 4;

Review Comment:
   Removed.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r939171919


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,

Review Comment:
   No, `DataTypes.createDecimalType()` doesn't work as the type generated from that will compare with `precision` and `scale` to the input type to be truncated.
   
   I think we can just remove this function, given that the actual call to bind that this function is used in does type validation already when choosing a specific input type (as follows):
   ```java
       DataType toTruncateDataType = toTruncateField.dataType();
       if (toTruncateDataType instanceof ByteType) {
         return new TruncateTinyInt();
       } else if (toTruncateDataType instanceof ShortType) {
         return new TruncateSmallInt();
       } else if (toTruncateDataType instanceof IntegerType) {
         return new TruncateInt();
       } else if (toTruncateDataType instanceof LongType) {
         return new TruncateBigInt();
       } else if (toTruncateDataType instanceof DecimalType) {
         return new TruncateDecimal(
             ((DecimalType) toTruncateDataType).precision(),
             ((DecimalType) toTruncateDataType).scale());
       } else if (toTruncateDataType instanceof StringType
           || toTruncateDataType instanceof VarcharType
           || toTruncateDataType instanceof CharType) {
         return new TruncateString();
       } else if (toTruncateDataType instanceof BinaryType) {
         return new TruncateBinary();
       } else {
         throw new UnsupportedOperationException("Cannot truncate type: " + toTruncateDataType);
       }
   ```



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r938306652


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,
+          DataTypes.StringType,
+          DataTypes.BinaryType);
+
+  private static void validateTruncationFieldType(DataType dt) {
+    if (truncateableAtomicTypes.stream().noneMatch(type -> type.sameType(dt))
+        && !(dt instanceof DecimalType)) {
+      String expectedTypes =
+          "[ByteType, ShortType, IntegerType, LongType, StringType, BinaryType, DecimalType]";
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of %s, but found %s",
+              expectedTypes, dt));
+    }
+  }
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type. Expected 2 fields but found %s", inputType.fields().length));
+    }
+
+    StructField widthField = inputType.apply(0);
+    StructField toTruncateField = inputType.apply(1);
+
+    validateTruncationFieldType(toTruncateField.dataType());
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType
+        || toTruncateDataType instanceof VarcharType
+        || toTruncateDataType instanceof CharType) {

Review Comment:
   Varchar and Char aren't allowed by `validateTruncationFieldType`. Do these `instanceof` checks work?



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r938306006


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,
+          DataTypes.StringType,
+          DataTypes.BinaryType);
+
+  private static void validateTruncationFieldType(DataType dt) {
+    if (truncateableAtomicTypes.stream().noneMatch(type -> type.sameType(dt))
+        && !(dt instanceof DecimalType)) {
+      String expectedTypes =
+          "[ByteType, ShortType, IntegerType, LongType, StringType, BinaryType, DecimalType]";
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of %s, but found %s",
+              expectedTypes, dt));
+    }
+  }
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type. Expected 2 fields but found %s", inputType.fields().length));
+    }
+
+    StructField widthField = inputType.apply(0);

Review Comment:
   Minor: I'd prefer `inputType.fields()[0]` rather than using `apply` because it isn't clear what `apply` does. It's named `apply` so that Scala syntactic sugar works.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r941785726


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,
+          DataTypes.StringType,
+          DataTypes.BinaryType);
+
+  private static void validateTruncationFieldType(DataType dt) {
+    if (truncateableAtomicTypes.stream().noneMatch(type -> type.sameType(dt))
+        && !(dt instanceof DecimalType)) {
+      String expectedTypes =
+          "[ByteType, ShortType, IntegerType, LongType, StringType, BinaryType, DecimalType]";
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of %s, but found %s",
+              expectedTypes, dt));
+    }
+  }
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type. Expected 2 fields but found %s", inputType.fields().length));
+    }
+
+    StructField widthField = inputType.apply(0);
+    StructField toTruncateField = inputType.apply(1);
+
+    validateTruncationFieldType(toTruncateField.dataType());
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType
+        || toTruncateDataType instanceof VarcharType
+        || toTruncateDataType instanceof CharType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException("Cannot truncate type: " + toTruncateDataType);
+    }
+  }
+
+  @Override
+  public String description() {
+    return "Truncate - The Iceberg truncate function used for truncate partition transformations.\n"
+        + "\tCalled with the truncation width as the first argument: e.g. system.truncate(width, col)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Byte toTruncate = !input.isNullAt(1) ? input.getByte(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Short toTruncate = !input.isNullAt(1) ? input.getShort(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateInt extends TruncateBase<Integer> {
+    // magic method used in codegen
+    public static int invoke(int width, int value) {
+      return TruncateUtil.truncateInt(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.IntegerType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.IntegerType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](int)";
+    }
+
+    @Override
+    public Integer produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Integer toTruncate = !input.isNullAt(1) ? input.getInt(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateBigInt extends TruncateBase<Long> {
+    // magic function for usage with codegen
+    public static long invoke(int width, long value) {
+      return TruncateUtil.truncateLong(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.LongType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.LongType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](bigint)";
+    }
+
+    @Override
+    public Long produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Long toTruncate = !input.isNullAt(1) ? input.getLong(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateString extends TruncateBase<UTF8String> {
+    // magic function for usage with codegen
+    // TODO - This can likely be made more efficient, but using existing definition for now.

Review Comment:
   Javadoc for `UTF8String::substring`
   
   ```
     /**
      * Returns a substring of this.
      * @param start the position of first code point
      * @param until the position after last code point, exclusive.
      */
   ```



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r942942522


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,348 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of [ByteType, ShortType, IntegerType, LongType, "
+                  + "DecimalType, StringType, BinaryType], but found %s",

Review Comment:
   Agree on updating the data types to use the SQL types. But Spark adds some to this error message. Let me show you an example.
   
   When passing `(int, interval year to month)` types, I get the following message now.
   
   ```
    "Function 'truncate' cannot process input: (int, interval year to month): Invalid input type to truncate. Expected one of [ByteType, ShortType, IntegerType, LongType, DecimalType, StringType, BinaryType], but found YearMonthIntervalType(0,1)"
   ```
   
   So I would say that we don't need to repeat the name of the function necessarily as Spark adds it. I'd suggest using 
   `expected truncation col to be tinyint, shortint, int, bigint, decimal, string, or binary`, so that the error message will wind up being:
   
   `" Function 'truncate' cannot process input: (int, interval year to month): expected truncation col to be tinyint, shortint, int, bigint, decimal, string, or 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: issues-unsubscribe@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r943717640


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,348 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of [ByteType, ShortType, IntegerType, LongType, "
+                  + "DecimalType, StringType, BinaryType], but found %s",
+              toTruncateDataType));
+    }
+  }
+
+  @Override
+  public String description() {
+    return name()
+        + "(width, col) - Call Iceberg's truncate transform\n"
+        + "  width :: width for truncation, e.g. truncate(10, 255) -> 250 (must be an integer)\n"
+        + "  col :: column to truncate (must be an integer, decimal, string, or binary)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getByte(1));
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getShort(1));
+    }
+  }
+
+  public static class TruncateInt extends TruncateBase<Integer> {
+    // magic method used in codegen
+    public static int invoke(int width, int value) {
+      return TruncateUtil.truncateInt(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.IntegerType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.IntegerType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(int)";
+    }
+
+    @Override
+    public Integer produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getInt(1));
+    }
+  }
+
+  public static class TruncateBigInt extends TruncateBase<Long> {
+    // magic function for usage with codegen
+    public static long invoke(int width, long value) {
+      return TruncateUtil.truncateLong(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.LongType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.LongType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(bigint)";
+    }
+
+    @Override
+    public Long produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getLong(1));
+    }
+  }
+
+  public static class TruncateString extends TruncateBase<UTF8String> {
+    // magic function for usage with codegen
+    public static UTF8String invoke(int width, UTF8String value) {
+      if (value == null) {
+        return null;
+      }
+
+      return value.substring(0, width);

Review Comment:
   This is a good point. I added a comment here to follow up and add all of our unicode truncation tests: https://github.com/apache/iceberg/pull/5431/files#r943717037



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r943710473


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be tinyint, shortint or int");

Review Comment:
   I think this is handled by Spark. We had a short discussion about error messages in a different thread and if we throw `UnsupportedOperationException` then Spark fills in what failed and the input types.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r943757601


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be tinyint, shortint or int");
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());

Review Comment:
   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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r943855085


##########
spark/v3.3/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkTruncateFunction.java:
##########
@@ -0,0 +1,436 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.sql;
+
+import java.math.BigDecimal;
+import java.nio.charset.StandardCharsets;
+import org.apache.iceberg.AssertHelpers;
+import org.apache.iceberg.relocated.com.google.common.io.BaseEncoding;
+import org.apache.iceberg.spark.SparkTestBaseWithCatalog;
+import org.apache.spark.sql.AnalysisException;
+import org.assertj.core.api.Assertions;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestSparkTruncateFunction extends SparkTestBaseWithCatalog {
+  public TestSparkTruncateFunction() {}
+
+  @Before
+  public void useCatalog() {
+    sql("USE %s", catalogName);
+  }
+
+  @Test
+  public void testTruncateTinyInt() {
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 0Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 1Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 5Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 9Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 10Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 11Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -1Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -5Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -10Y)"));
+    Assert.assertEquals((byte) -20, scalarSql("SELECT system.truncate(10, -11Y)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((byte) -2, scalarSql("SELECT system.truncate(2, -1Y)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS tinyint))"));
+  }
+
+  @Test
+  public void testTruncateSmallInt() {
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 0S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 1S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 5S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 9S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 10S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 11S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -1S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -5S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -10S)"));
+    Assert.assertEquals((short) -20, scalarSql("SELECT system.truncate(10, -11S)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((short) -2, scalarSql("SELECT system.truncate(2, -1S)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS smallint))"));
+  }
+
+  @Test
+  public void testTruncateInt() {
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, 0)"));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, 1)"));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, 5)"));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, 9)"));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, 10)"));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, 11)"));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, -1)"));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, -5)"));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, -10)"));
+    Assert.assertEquals(-20, scalarSql("SELECT system.truncate(10, -11)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2, scalarSql("SELECT system.truncate(2, -1)"));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(300, 1)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS int))"));
+  }
+
+  @Test
+  public void testTruncateBigInt() {
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 0L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 1L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 5L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 9L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 10L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 11L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -1L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -5L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -10L)"));
+    Assert.assertEquals(-20L, scalarSql("SELECT system.truncate(10, -11L)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2L, scalarSql("SELECT system.truncate(2, -1L)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS bigint))"));
+  }
+
+  @Test
+  public void testTruncateDecimal() {
+    // decimal truncation works by applying the decimal scale to the width: ie 10 scale 2 = 0.10
+    Assert.assertEquals(
+        new BigDecimal("12.30"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 2)))", "12.34"));
+
+    Assert.assertEquals(
+        new BigDecimal("12.30"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 2)))", "12.30"));
+
+    Assert.assertEquals(
+        new BigDecimal("12.290"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 3)))", "12.299"));
+
+    Assert.assertEquals(
+        new BigDecimal("0.03"),
+        scalarSql("SELECT system.truncate(3, CAST(%s as DECIMAL(5, 2)))", "0.05"));
+
+    Assert.assertEquals(
+        new BigDecimal("0.00"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 2)))", "0.05"));
+
+    Assert.assertEquals(
+        new BigDecimal("-0.10"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 2)))", "-0.05"));
+
+    Assert.assertEquals(
+        "Implicit decimal scale and precision should be allowed",
+        new BigDecimal("12345.3480"),
+        scalarSql("SELECT system.truncate(10, 12345.3482)"));
+
+    BigDecimal truncatedDecimal =
+        (BigDecimal) scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(6, 4)))", "-0.05");
+    Assert.assertEquals(
+        "Truncating a decimal should return a decimal with the same scale",
+        4,
+        truncatedDecimal.scale());
+
+    Assert.assertEquals(
+        "Truncating a decimal should return a decimal with the correct scale",
+        BigDecimal.valueOf(-500, 4),
+        truncatedDecimal);
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS decimal))"));
+  }
+
+  @Test
+  public void testTruncateString() {
+    Assert.assertEquals(
+        "Should system.truncate strings longer than length",
+        "abcde",
+        scalarSql("SELECT system.truncate(5, 'abcdefg')"));
+
+    Assert.assertEquals(
+        "Should not pad strings shorter than length",
+        "abc",
+        scalarSql("SELECT system.truncate(5, 'abc')"));
+
+    Assert.assertEquals(
+        "Should not alter strings equal to length",
+        "abcde",
+        scalarSql("SELECT system.truncate(5, 'abcde')"));
+
+    Assert.assertEquals(
+        "Should handle three-byte UTF-8 characters appropriately",
+        "测",
+        scalarSql("SELECT system.truncate(1, '测试')"));
+
+    Assert.assertEquals(
+        "Should handle three-byte UTF-8 characters mixed with two byte utf-8 characters",
+        "测试ra",
+        scalarSql("SELECT system.truncate(4, '测试raul试测')"));

Review Comment:
   Looks good.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r943932305


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,348 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of [ByteType, ShortType, IntegerType, LongType, "
+                  + "DecimalType, StringType, BinaryType], but found %s",
+              toTruncateDataType));
+    }
+  }
+
+  @Override
+  public String description() {
+    return name()
+        + "(width, col) - Call Iceberg's truncate transform\n"
+        + "  width :: width for truncation, e.g. truncate(10, 255) -> 250 (must be an integer)\n"
+        + "  col :: column to truncate (must be an integer, decimal, string, or binary)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getByte(1));
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getShort(1));
+    }
+  }
+
+  public static class TruncateInt extends TruncateBase<Integer> {
+    // magic method used in codegen
+    public static int invoke(int width, int value) {
+      return TruncateUtil.truncateInt(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.IntegerType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.IntegerType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(int)";
+    }
+
+    @Override
+    public Integer produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getInt(1));
+    }
+  }
+
+  public static class TruncateBigInt extends TruncateBase<Long> {
+    // magic function for usage with codegen
+    public static long invoke(int width, long value) {
+      return TruncateUtil.truncateLong(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.LongType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.LongType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(bigint)";
+    }
+
+    @Override
+    public Long produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getLong(1));
+    }
+  }
+
+  public static class TruncateString extends TruncateBase<UTF8String> {
+    // magic function for usage with codegen
+    public static UTF8String invoke(int width, UTF8String value) {
+      if (value == null) {
+        return null;
+      }
+
+      return value.substring(0, width);

Review Comment:
   If we want to create a followup task to add more of these tests _back_ to `TestTruncate` or to a `UnicodeUtil` test suite, let me know as I could easily handle that.
   
   At present, this code seems well tested though for using the built-in `UTF8String` tests.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r943911195


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,348 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of [ByteType, ShortType, IntegerType, LongType, "
+                  + "DecimalType, StringType, BinaryType], but found %s",
+              toTruncateDataType));
+    }
+  }
+
+  @Override
+  public String description() {
+    return name()
+        + "(width, col) - Call Iceberg's truncate transform\n"
+        + "  width :: width for truncation, e.g. truncate(10, 255) -> 250 (must be an integer)\n"
+        + "  col :: column to truncate (must be an integer, decimal, string, or binary)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getByte(1));
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getShort(1));
+    }
+  }
+
+  public static class TruncateInt extends TruncateBase<Integer> {
+    // magic method used in codegen
+    public static int invoke(int width, int value) {
+      return TruncateUtil.truncateInt(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.IntegerType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.IntegerType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(int)";
+    }
+
+    @Override
+    public Integer produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getInt(1));
+    }
+  }
+
+  public static class TruncateBigInt extends TruncateBase<Long> {
+    // magic function for usage with codegen
+    public static long invoke(int width, long value) {
+      return TruncateUtil.truncateLong(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.LongType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.LongType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(bigint)";
+    }
+
+    @Override
+    public Long produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getLong(1));
+    }
+  }
+
+  public static class TruncateString extends TruncateBase<UTF8String> {
+    // magic function for usage with codegen
+    public static UTF8String invoke(int width, UTF8String value) {
+      if (value == null) {
+        return null;
+      }
+
+      return value.substring(0, width);

Review Comment:
   I agree with that.
   
   But I took a look and I actually couldn't find any test cases for `UnicodeUtil.truncateString` directly.
   
   I looked up the tests for `TestTruncate`, but `TestTruncate#testTruncateString` has _very few_ tests - all of which are covered here.
   
   https://github.com/apache/iceberg/blob/5a15efc070ab59eeda6343998aa065c0c9892c5c/api/src/test/java/org/apache/iceberg/transforms/TestTruncate.java#L70-L77
   
   I was able to pull more test cases from `TestMetricsTruncation`, and we now cover 2-byte, 3-byte, and 4-byte unicode character truncation (as well as mixed byte alignment).
   
   So I'd say we definitely have enough tests for string truncation now (at least compared to elsewhere).
   



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r941739742


##########
spark/v3.3/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkTruncateFunction.java:
##########
@@ -0,0 +1,377 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.sql;
+
+import java.math.BigDecimal;
+import java.nio.charset.StandardCharsets;
+import org.apache.iceberg.AssertHelpers;
+import org.apache.iceberg.relocated.com.google.common.io.BaseEncoding;
+import org.apache.iceberg.spark.SparkTestBaseWithCatalog;
+import org.apache.spark.sql.AnalysisException;
+import org.assertj.core.api.Assertions;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestSparkTruncateFunction extends SparkTestBaseWithCatalog {
+  public TestSparkTruncateFunction() {}
+
+  @Before
+  public void useCatalog() {
+    sql("USE %s", catalogName);
+  }
+
+  @Test
+  public void testTruncateTinyInt() {
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 0Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 1Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 5Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 9Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 10Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 11Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -1Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -5Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -10Y)"));
+    Assert.assertEquals((byte) -20, scalarSql("SELECT system.truncate(10, -11Y)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((byte) -2, scalarSql("SELECT system.truncate(2, -1Y)"));
+
+    // Check that tinyint types are allowed for the width
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(5Y, 1Y)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS tinyint))"));
+  }
+
+  @Test
+  public void testTruncateSmallInt() {
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 0S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 1S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 5S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 9S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 10S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 11S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -1S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -5S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -10S)"));
+    Assert.assertEquals((short) -20, scalarSql("SELECT system.truncate(10, -11S)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((short) -2, scalarSql("SELECT system.truncate(2, -1S)"));
+
+    // Check that short types are allowed for the width
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(5S, 1S)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS smallint))"));
+  }
+
+  @Test
+  public void testTruncateInt() {
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 0));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 1));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 5));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 9));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, %d)", 10));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, %d)", 11));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -1));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -5));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -10));
+    Assert.assertEquals(-20, scalarSql("SELECT system.truncate(10, %d)", -11));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2, scalarSql("SELECT system.truncate(2, %d)", -1));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(300, %d)", 1));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS int))"));

Review Comment:
   This calls `invoke`. For `invoke`, if any primitive input is `null`, `null` is returned automatically when using the magic functions -- for non-primitives like UTF8String, we still need to check.
   
   Here's the query plan to show it:
   ```
       == Parsed Logical Plan ==
       'Project [unresolvedalias('system.truncate(2, cast(null as bigint)), None)]
       +- OneRowRelation
       == Analyzed Logical Plan ==
       staticinvoke(class org.apache.iceberg.spark.functions.TruncateFunction$TruncateBigInt, LongType, invoke, 2, cast(NULL as bigint), IntegerType, LongType, false, true, true): bigint
       Project [staticinvoke(class org.apache.iceberg.spark.functions.TruncateFunction$TruncateBigInt, LongType, invoke, 2, cast(null as bigint), IntegerType, LongType, false, true, true) AS staticinvoke(class org.apache.iceberg.spark.functions.TruncateFunction$TruncateBigInt, LongType, invoke, 2, cast(NULL as bigint), IntegerType, LongType, false, true, true)#55L]
       +- OneRowRelation
       == Optimized Logical Plan ==
       Project [null AS staticinvoke(class org.apache.iceberg.spark.functions.TruncateFunction$TruncateBigInt, LongType, invoke, 2, cast(NULL as bigint), IntegerType, LongType, false, true, true)#55L]
       +- OneRowRelation
       == Physical Plan ==
       *(1) Project [null AS staticinvoke(class org.apache.iceberg.spark.functions.TruncateFunction$TruncateBigInt, LongType, invoke, 2, cast(NULL as bigint), IntegerType, LongType, false, true, true)#55L]
       +- *(1) Scan OneRowRelation[]
   ```



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] aokolnychyi commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
aokolnychyi commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r943667770


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be tinyint, shortint or int");

Review Comment:
   nit: I'd probably either use `Cannot bind truncate:` prefix in all error messages related to binding or drop it everywhere for consistency.



##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be tinyint, shortint or int");
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {

Review Comment:
   nit: just `inputType.length()` or `inputType.size()`?



##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be tinyint, shortint or int");
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          "Expected truncation col to be tinyint, shortint, int, bigint, decimal, string, or binary");
+    }
+  }
+
+  @Override
+  public String description() {
+    return name()
+        + "(width, col) - Call Iceberg's truncate transform\n"
+        + "  width :: width for truncation, e.g. truncate(10, 255) -> 250 (must be an integer)\n"
+        + "  col :: column to truncate (must be an integer, decimal, string, or binary)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      return input.isNullAt(0) || input.isNullAt(1)

Review Comment:
   What about defining constants for 0 and 1 with some reasonable names to indicate what those are?
   
   ```
   private static final int WIDTH_ORDINAL = 0;
   private static final int VALUE_ORDINAL = 1;
   ```



##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)

Review Comment:
   nit: Since we don't expect an array, struct or map, we don't really need `sameType`. You could define a set and call `contains` on it.
   
   ```
   private static final Set<DataType> SUPPORTED_WIDTH_TYPES =
       ImmutableSet.of(DataTypes.ByteType, DataTypes.ShortType, DataTypes.IntegerType);
   
   ...
   
   if (!SUPPORTED_WIDTH_TYPES.contains(widthField.dataType())) {
     throw new UnsupportedOperationException(...);
   }
   ```



##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be tinyint, shortint or int");
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];

Review Comment:
   nit: Do we call it `value` in most other places?



##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be tinyint, shortint or int");
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          "Expected truncation col to be tinyint, shortint, int, bigint, decimal, string, or binary");
+    }
+  }
+
+  @Override
+  public String description() {
+    return name()
+        + "(width, col) - Call Iceberg's truncate transform\n"
+        + "  width :: width for truncation, e.g. truncate(10, 255) -> 250 (must be an integer)\n"
+        + "  col :: column to truncate (must be an integer, decimal, string, or binary)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      return input.isNullAt(0) || input.isNullAt(1)
+          ? null
+          : invoke(input.getInt(0), input.getByte(1));
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      return input.isNullAt(0) || input.isNullAt(1)

Review Comment:
   Do we actually allow nullable width?



##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be tinyint, shortint or int");
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());

Review Comment:
   Do we have to validate width nullability?



##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be tinyint, shortint or int");
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());

Review Comment:
   What do you think about adding an empty line before this call to separate the block that instantiates the fields from the validation?



##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be tinyint, shortint or int");
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          "Expected truncation col to be tinyint, shortint, int, bigint, decimal, string, or binary");
+    }
+  }
+
+  @Override
+  public String description() {
+    return name()
+        + "(width, col) - Call Iceberg's truncate transform\n"
+        + "  width :: width for truncation, e.g. truncate(10, 255) -> 250 (must be an integer)\n"
+        + "  col :: column to truncate (must be an integer, decimal, string, or binary)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      return input.isNullAt(0) || input.isNullAt(1)
+          ? null
+          : invoke(input.getInt(0), input.getByte(1));
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      return input.isNullAt(0) || input.isNullAt(1)
+          ? null
+          : invoke(input.getInt(0), input.getShort(1));
+    }
+  }
+
+  public static class TruncateInt extends TruncateBase<Integer> {
+    // magic method used in codegen
+    public static int invoke(int width, int value) {
+      return TruncateUtil.truncateInt(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.IntegerType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.IntegerType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(int)";
+    }
+
+    @Override
+    public Integer produceResult(InternalRow input) {
+      return input.isNullAt(0) || input.isNullAt(1)
+          ? null
+          : invoke(input.getInt(0), input.getInt(1));
+    }
+  }
+
+  public static class TruncateBigInt extends TruncateBase<Long> {
+    // magic function for usage with codegen
+    public static long invoke(int width, long value) {
+      return TruncateUtil.truncateLong(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.LongType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.LongType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(bigint)";
+    }
+
+    @Override
+    public Long produceResult(InternalRow input) {
+      return input.isNullAt(0) || input.isNullAt(1)

Review Comment:
   I wonder whether explicit if statements would be more readable given that we have to split the ternary operation onto multiple lines.



##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,348 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of [ByteType, ShortType, IntegerType, LongType, "
+                  + "DecimalType, StringType, BinaryType], but found %s",
+              toTruncateDataType));
+    }
+  }
+
+  @Override
+  public String description() {
+    return name()
+        + "(width, col) - Call Iceberg's truncate transform\n"
+        + "  width :: width for truncation, e.g. truncate(10, 255) -> 250 (must be an integer)\n"
+        + "  col :: column to truncate (must be an integer, decimal, string, or binary)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getByte(1));
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getShort(1));
+    }
+  }
+
+  public static class TruncateInt extends TruncateBase<Integer> {
+    // magic method used in codegen
+    public static int invoke(int width, int value) {
+      return TruncateUtil.truncateInt(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.IntegerType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.IntegerType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(int)";
+    }
+
+    @Override
+    public Integer produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getInt(1));
+    }
+  }
+
+  public static class TruncateBigInt extends TruncateBase<Long> {
+    // magic function for usage with codegen
+    public static long invoke(int width, long value) {
+      return TruncateUtil.truncateLong(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.LongType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.LongType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(bigint)";
+    }
+
+    @Override
+    public Long produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getLong(1));
+    }
+  }
+
+  public static class TruncateString extends TruncateBase<UTF8String> {
+    // magic function for usage with codegen
+    public static UTF8String invoke(int width, UTF8String value) {
+      if (value == null) {
+        return null;
+      }
+
+      return value.substring(0, width);

Review Comment:
   I'd be up to using UTF8String directly. Do we have enough tests to verify the bevahior of the Spark function will match the behavior of Iceberg transform?



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] aokolnychyi commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
aokolnychyi commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r943693066


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,348 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of [ByteType, ShortType, IntegerType, LongType, "
+                  + "DecimalType, StringType, BinaryType], but found %s",
+              toTruncateDataType));
+    }
+  }
+
+  @Override
+  public String description() {
+    return name()
+        + "(width, col) - Call Iceberg's truncate transform\n"
+        + "  width :: width for truncation, e.g. truncate(10, 255) -> 250 (must be an integer)\n"
+        + "  col :: column to truncate (must be an integer, decimal, string, or binary)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getByte(1));
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getShort(1));
+    }
+  }
+
+  public static class TruncateInt extends TruncateBase<Integer> {
+    // magic method used in codegen
+    public static int invoke(int width, int value) {
+      return TruncateUtil.truncateInt(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.IntegerType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.IntegerType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(int)";
+    }
+
+    @Override
+    public Integer produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getInt(1));
+    }
+  }
+
+  public static class TruncateBigInt extends TruncateBase<Long> {
+    // magic function for usage with codegen
+    public static long invoke(int width, long value) {
+      return TruncateUtil.truncateLong(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.LongType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.LongType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(bigint)";
+    }
+
+    @Override
+    public Long produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getLong(1));
+    }
+  }
+
+  public static class TruncateString extends TruncateBase<UTF8String> {
+    // magic function for usage with codegen
+    public static UTF8String invoke(int width, UTF8String value) {
+      if (value == null) {
+        return null;
+      }
+
+      return value.substring(0, width);

Review Comment:
   I'd be up to using UTF8String directly. Do we have enough tests to verify the bevahior of the Spark function will match the behavior of the Iceberg transform?



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r940634710


##########
api/src/main/java/org/apache/iceberg/util/TruncateUtil.java:
##########
@@ -0,0 +1,80 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.util;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+
+/**
+ * Contains the logic for various {@code truncate} transformations for various types.
+ *
+ * <p>This utility class allows for the logic to be reused in different scenarios where input
+ * validation is done at different times either in org.apache.iceberg.transforms.Truncate and within
+ * defined SQL functions for different compute engines for usage in SQL.
+ *
+ * <p>In general, the inputs to the functions should have already been validated by the calling
+ * code, as different classes use truncate with different preprocessing. This generally means that
+ * the truncation width is positive and the value to truncate is non-null.
+ *
+ * <p>Thus, <b>none</b> of these utility functions validate their input. <i>It is the responsibility
+ * of the calling code to validate input.</i>
+ *
+ * <p>See also {@linkplain UnicodeUtil#truncateString(CharSequence, int)} and {@link
+ * BinaryUtil#truncateBinary(ByteBuffer, int)}
+ */
+public class TruncateUtil {
+
+  private TruncateUtil() {}
+
+  public static ByteBuffer truncateByteBuffer(int width, ByteBuffer value) {
+    ByteBuffer ret = value.duplicate();
+    ret.limit(Math.min(value.limit(), value.position() + width));
+    return ret;
+  }

Review Comment:
   Moved over to `BinaryUtil#truncateBinaryUnsafe`.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r941792970


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,
+          DataTypes.StringType,
+          DataTypes.BinaryType);
+
+  private static void validateTruncationFieldType(DataType dt) {
+    if (truncateableAtomicTypes.stream().noneMatch(type -> type.sameType(dt))
+        && !(dt instanceof DecimalType)) {
+      String expectedTypes =
+          "[ByteType, ShortType, IntegerType, LongType, StringType, BinaryType, DecimalType]";
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of %s, but found %s",
+              expectedTypes, dt));
+    }
+  }
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type. Expected 2 fields but found %s", inputType.fields().length));
+    }
+
+    StructField widthField = inputType.apply(0);
+    StructField toTruncateField = inputType.apply(1);
+
+    validateTruncationFieldType(toTruncateField.dataType());
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType
+        || toTruncateDataType instanceof VarcharType
+        || toTruncateDataType instanceof CharType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException("Cannot truncate type: " + toTruncateDataType);
+    }
+  }
+
+  @Override
+  public String description() {
+    return "Truncate - The Iceberg truncate function used for truncate partition transformations.\n"
+        + "\tCalled with the truncation width as the first argument: e.g. system.truncate(width, col)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Byte toTruncate = !input.isNullAt(1) ? input.getByte(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;

Review Comment:
   Changed to 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: issues-unsubscribe@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r941794928


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,
+          DataTypes.StringType,
+          DataTypes.BinaryType);
+
+  private static void validateTruncationFieldType(DataType dt) {
+    if (truncateableAtomicTypes.stream().noneMatch(type -> type.sameType(dt))
+        && !(dt instanceof DecimalType)) {
+      String expectedTypes =
+          "[ByteType, ShortType, IntegerType, LongType, StringType, BinaryType, DecimalType]";
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of %s, but found %s",
+              expectedTypes, dt));
+    }
+  }
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type. Expected 2 fields but found %s", inputType.fields().length));
+    }
+
+    StructField widthField = inputType.apply(0);
+    StructField toTruncateField = inputType.apply(1);
+
+    validateTruncationFieldType(toTruncateField.dataType());
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType
+        || toTruncateDataType instanceof VarcharType
+        || toTruncateDataType instanceof CharType) {

Review Comment:
   Removed the method.
   
   I'm going to remove `varchartype` and `chartype` as Spark prints a warning saying that it casts these two aliases for `UTF8String` to string already and that neither type can be used for functions etc.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r938302293


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,

Review Comment:
   What about `DecimalType`?



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r938332611


##########
spark/v3.3/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkTruncateFunction.java:
##########
@@ -0,0 +1,377 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.sql;
+
+import java.math.BigDecimal;
+import java.nio.charset.StandardCharsets;
+import org.apache.iceberg.AssertHelpers;
+import org.apache.iceberg.relocated.com.google.common.io.BaseEncoding;
+import org.apache.iceberg.spark.SparkTestBaseWithCatalog;
+import org.apache.spark.sql.AnalysisException;
+import org.assertj.core.api.Assertions;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestSparkTruncateFunction extends SparkTestBaseWithCatalog {
+  public TestSparkTruncateFunction() {}
+
+  @Before
+  public void useCatalog() {
+    sql("USE %s", catalogName);
+  }
+
+  @Test
+  public void testTruncateTinyInt() {
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 0Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 1Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 5Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 9Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 10Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 11Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -1Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -5Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -10Y)"));
+    Assert.assertEquals((byte) -20, scalarSql("SELECT system.truncate(10, -11Y)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((byte) -2, scalarSql("SELECT system.truncate(2, -1Y)"));
+
+    // Check that tinyint types are allowed for the width
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(5Y, 1Y)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS tinyint))"));
+  }
+
+  @Test
+  public void testTruncateSmallInt() {
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 0S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 1S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 5S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 9S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 10S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 11S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -1S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -5S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -10S)"));
+    Assert.assertEquals((short) -20, scalarSql("SELECT system.truncate(10, -11S)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((short) -2, scalarSql("SELECT system.truncate(2, -1S)"));
+
+    // Check that short types are allowed for the width
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(5S, 1S)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS smallint))"));
+  }
+
+  @Test
+  public void testTruncateInt() {
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 0));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 1));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 5));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 9));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, %d)", 10));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, %d)", 11));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -1));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -5));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -10));
+    Assert.assertEquals(-20, scalarSql("SELECT system.truncate(10, %d)", -11));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2, scalarSql("SELECT system.truncate(2, %d)", -1));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(300, %d)", 1));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS int))"));
+  }
+
+  @Test
+  public void testTruncateBigInt() {
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 0L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 1L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 5L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 9L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 10L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 11L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -1L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -5L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -10L)"));
+    Assert.assertEquals(-20L, scalarSql("SELECT system.truncate(10, -11L)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2L, scalarSql("SELECT system.truncate(2, -1L)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS bigint))"));
+  }
+
+  @Test
+  public void testTruncateDecimal() {
+    // decimal truncation works by applying the decimal scale to the width: ie 10 scale 2 = 0.10
+    Assert.assertEquals(
+        new BigDecimal("12.30"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 2)))", 12.34));
+
+    Assert.assertEquals(
+        new BigDecimal("12.30"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 2)))", 12.30));
+
+    Assert.assertEquals(
+        new BigDecimal("12.290"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 3)))", 12.299));
+
+    Assert.assertEquals(
+        new BigDecimal("0.03"),
+        scalarSql("SELECT system.truncate(3, CAST(%f as DECIMAL(5, 2)))", 0.05));
+
+    Assert.assertEquals(
+        new BigDecimal("0.00"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 2)))", 0.05));
+
+    Assert.assertEquals(
+        new BigDecimal("-0.10"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 2)))", -0.05));
+
+    Assert.assertEquals(
+        "Implicit decimal scale and precision should be allowed",
+        new BigDecimal("12345.3480"),
+        scalarSql("SELECT system.truncate(10, 12345.3482)"));
+
+    int scale = 4;

Review Comment:
   Why have a variable for this if it isn't used 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: issues-unsubscribe@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] aokolnychyi commented on pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
aokolnychyi commented on PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#issuecomment-1212127251

   I'd love to take a look as well 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: issues-unsubscribe@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r943744566


##########
spark/v3.3/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkTruncateFunction.java:
##########
@@ -0,0 +1,436 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.sql;
+
+import java.math.BigDecimal;
+import java.nio.charset.StandardCharsets;
+import org.apache.iceberg.AssertHelpers;
+import org.apache.iceberg.relocated.com.google.common.io.BaseEncoding;
+import org.apache.iceberg.spark.SparkTestBaseWithCatalog;
+import org.apache.spark.sql.AnalysisException;
+import org.assertj.core.api.Assertions;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestSparkTruncateFunction extends SparkTestBaseWithCatalog {
+  public TestSparkTruncateFunction() {}
+
+  @Before
+  public void useCatalog() {
+    sql("USE %s", catalogName);
+  }
+
+  @Test
+  public void testTruncateTinyInt() {
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 0Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 1Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 5Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 9Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 10Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 11Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -1Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -5Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -10Y)"));
+    Assert.assertEquals((byte) -20, scalarSql("SELECT system.truncate(10, -11Y)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((byte) -2, scalarSql("SELECT system.truncate(2, -1Y)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS tinyint))"));
+  }
+
+  @Test
+  public void testTruncateSmallInt() {
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 0S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 1S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 5S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 9S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 10S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 11S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -1S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -5S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -10S)"));
+    Assert.assertEquals((short) -20, scalarSql("SELECT system.truncate(10, -11S)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((short) -2, scalarSql("SELECT system.truncate(2, -1S)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS smallint))"));
+  }
+
+  @Test
+  public void testTruncateInt() {
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, 0)"));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, 1)"));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, 5)"));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, 9)"));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, 10)"));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, 11)"));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, -1)"));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, -5)"));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, -10)"));
+    Assert.assertEquals(-20, scalarSql("SELECT system.truncate(10, -11)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2, scalarSql("SELECT system.truncate(2, -1)"));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(300, 1)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS int))"));
+  }
+
+  @Test
+  public void testTruncateBigInt() {
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 0L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 1L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 5L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 9L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 10L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 11L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -1L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -5L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -10L)"));
+    Assert.assertEquals(-20L, scalarSql("SELECT system.truncate(10, -11L)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2L, scalarSql("SELECT system.truncate(2, -1L)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS bigint))"));
+  }
+
+  @Test
+  public void testTruncateDecimal() {
+    // decimal truncation works by applying the decimal scale to the width: ie 10 scale 2 = 0.10
+    Assert.assertEquals(
+        new BigDecimal("12.30"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 2)))", "12.34"));
+
+    Assert.assertEquals(
+        new BigDecimal("12.30"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 2)))", "12.30"));
+
+    Assert.assertEquals(
+        new BigDecimal("12.290"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 3)))", "12.299"));
+
+    Assert.assertEquals(
+        new BigDecimal("0.03"),
+        scalarSql("SELECT system.truncate(3, CAST(%s as DECIMAL(5, 2)))", "0.05"));
+
+    Assert.assertEquals(
+        new BigDecimal("0.00"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 2)))", "0.05"));
+
+    Assert.assertEquals(
+        new BigDecimal("-0.10"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 2)))", "-0.05"));
+
+    Assert.assertEquals(
+        "Implicit decimal scale and precision should be allowed",
+        new BigDecimal("12345.3480"),
+        scalarSql("SELECT system.truncate(10, 12345.3482)"));
+
+    BigDecimal truncatedDecimal =
+        (BigDecimal) scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(6, 4)))", "-0.05");
+    Assert.assertEquals(
+        "Truncating a decimal should return a decimal with the same scale",
+        4,
+        truncatedDecimal.scale());
+
+    Assert.assertEquals(
+        "Truncating a decimal should return a decimal with the correct scale",
+        BigDecimal.valueOf(-500, 4),
+        truncatedDecimal);
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS decimal))"));
+  }
+
+  @Test
+  public void testTruncateString() {
+    Assert.assertEquals(
+        "Should system.truncate strings longer than length",
+        "abcde",
+        scalarSql("SELECT system.truncate(5, 'abcdefg')"));
+
+    Assert.assertEquals(
+        "Should not pad strings shorter than length",
+        "abc",
+        scalarSql("SELECT system.truncate(5, 'abc')"));
+
+    Assert.assertEquals(
+        "Should not alter strings equal to length",
+        "abcde",
+        scalarSql("SELECT system.truncate(5, 'abcde')"));
+
+    Assert.assertEquals(
+        "Should handle three-byte UTF-8 characters appropriately",
+        "测",
+        scalarSql("SELECT system.truncate(1, '测试')"));
+
+    Assert.assertEquals(
+        "Should handle three-byte UTF-8 characters mixed with two byte utf-8 characters",
+        "测试ra",
+        scalarSql("SELECT system.truncate(4, '测试raul试测')"));

Review Comment:
   `TestMetricsTruncation` has more test cases, though they're specifically for `testTruncateMin` and `testTruncateMax`.
   
   But I can reuse those as they do cover more situations: https://github.com/apache/iceberg/blob/5a15efc070ab59eeda6343998aa065c0c9892c5c/core/src/test/java/org/apache/iceberg/TestMetricsTruncation.java#L132-L264



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r943832064


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be tinyint, shortint or int");

Review Comment:
   Yeah. I'll remove it from the length check.
   
   Let me check what Spark adds for length itself. We might not even need a check at all (just a unit test) for length.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r938253826


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,
+          DataTypes.StringType,
+          DataTypes.BinaryType);
+
+  private static void validateTruncationFieldType(DataType dt) {
+    if (truncateableAtomicTypes.stream().noneMatch(type -> type.sameType(dt))
+        && !(dt instanceof DecimalType)) {
+      String expectedTypes =
+          "[ByteType, ShortType, IntegerType, LongType, StringType, BinaryType, DecimalType]";
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of %s, but found %s",
+              expectedTypes, dt));
+    }
+  }
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type. Expected 2 fields but found %s", inputType.fields().length));
+    }
+
+    StructField widthField = inputType.apply(0);
+    StructField toTruncateField = inputType.apply(1);
+
+    validateTruncationFieldType(toTruncateField.dataType());
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType
+        || toTruncateDataType instanceof VarcharType
+        || toTruncateDataType instanceof CharType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException("Cannot truncate type: " + toTruncateDataType);
+    }
+  }
+
+  @Override
+  public String description() {
+    return "Truncate - The Iceberg truncate function used for truncate partition transformations.\n"
+        + "\tCalled with the truncation width as the first argument: e.g. system.truncate(width, col)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](tinyint)";

Review Comment:
   Actually, we need to remove `[width]` since the width is passed in.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r938329257


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,
+          DataTypes.StringType,
+          DataTypes.BinaryType);
+
+  private static void validateTruncationFieldType(DataType dt) {
+    if (truncateableAtomicTypes.stream().noneMatch(type -> type.sameType(dt))
+        && !(dt instanceof DecimalType)) {
+      String expectedTypes =
+          "[ByteType, ShortType, IntegerType, LongType, StringType, BinaryType, DecimalType]";
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of %s, but found %s",
+              expectedTypes, dt));
+    }
+  }
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type. Expected 2 fields but found %s", inputType.fields().length));
+    }
+
+    StructField widthField = inputType.apply(0);
+    StructField toTruncateField = inputType.apply(1);
+
+    validateTruncationFieldType(toTruncateField.dataType());
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType
+        || toTruncateDataType instanceof VarcharType
+        || toTruncateDataType instanceof CharType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException("Cannot truncate type: " + toTruncateDataType);
+    }
+  }
+
+  @Override
+  public String description() {
+    return "Truncate - The Iceberg truncate function used for truncate partition transformations.\n"
+        + "\tCalled with the truncation width as the first argument: e.g. system.truncate(width, col)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Byte toTruncate = !input.isNullAt(1) ? input.getByte(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Short toTruncate = !input.isNullAt(1) ? input.getShort(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateInt extends TruncateBase<Integer> {
+    // magic method used in codegen
+    public static int invoke(int width, int value) {
+      return TruncateUtil.truncateInt(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.IntegerType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.IntegerType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](int)";
+    }
+
+    @Override
+    public Integer produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Integer toTruncate = !input.isNullAt(1) ? input.getInt(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateBigInt extends TruncateBase<Long> {
+    // magic function for usage with codegen
+    public static long invoke(int width, long value) {
+      return TruncateUtil.truncateLong(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.LongType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.LongType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](bigint)";
+    }
+
+    @Override
+    public Long produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Long toTruncate = !input.isNullAt(1) ? input.getLong(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateString extends TruncateBase<UTF8String> {
+    // magic function for usage with codegen
+    // TODO - This can likely be made more efficient, but using existing definition for now.
+    public static UTF8String invoke(int width, UTF8String value) {
+      if (value == null) {
+        return null;
+      }
+
+      ByteBuffer bb = value.getByteBuffer();
+      CharSequence charSequence = StandardCharsets.UTF_8.decode(bb);
+      CharSequence truncated = UnicodeUtil.truncateString(charSequence, width);
+      ByteBuffer truncatedBytes = StandardCharsets.UTF_8.encode(CharBuffer.wrap(truncated));
+      return UTF8String.fromBytes(ByteBuffers.toByteArray(truncatedBytes));
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.StringType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.StringType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](string)";
+    }
+
+    @Override
+    public UTF8String produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      UTF8String toTruncate = !input.isNullAt(1) ? input.getUTF8String(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateBinary extends TruncateBase<byte[]> {
+    // magic method used in codegen
+    public static byte[] invoke(int width, byte[] value) {
+      if (value == null) {
+        return null;
+      }
+
+      return ByteBuffers.toByteArray(
+          TruncateUtil.truncateByteBuffer(width, ByteBuffer.wrap(value)));
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.BinaryType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.BinaryType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](binary)";
+    }
+
+    @Override
+    public byte[] produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      byte[] toTruncate = !input.isNullAt(1) ? input.getBinary(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateDecimal extends TruncateBase<Decimal> {
+    private final int precision;
+    private final int scale;
+
+    public TruncateDecimal(int precision, int scale) {
+      this.precision = precision;
+      this.scale = scale;
+    }
+
+    // magic method used in codegen
+    public static Decimal invoke(int width, Decimal value) {
+      if (value == null) {
+        return null;
+      }
+
+      return Decimal.apply(
+          TruncateUtil.truncateDecimal(BigInteger.valueOf(width), value.toJavaBigDecimal()));
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.createDecimalType(precision, scale)};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.createDecimalType(precision, scale);
+    }
+
+    @Override
+    public String canonicalName() {
+      return String.format("iceberg.truncate[width](decimal(%d,%d))", precision, scale);
+    }
+
+    @Override
+    public Decimal produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Decimal toTruncate = !input.isNullAt(1) ? input.getDecimal(1, precision, scale) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  private static Integer readAndValidateWidth(InternalRow input) {

Review Comment:
   The logic here is odd. Why call `isNullAt` to box the value only to check whether it is null and throw an exception? I'd expect something like this:
   
   ```java
     if (input.isNullAt(0)) {
       throw IllegalArgumentException("Invalid truncation width: null");
     }
   
     return width;
   ```
   
   I left out checking whether width is negative. I don't think we care through `produceResult` if we don't care through `invoke`.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r939405701


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,

Review Comment:
   I guess just the name is misleading. I wrote this before I saw how it was used. This isn't a complete list of truncateable types, it's just the ones that can be checked using `sameType`.
   
   A better name would help. Also, `static final` constants should use names that are ALL_UPPER_CASE.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r938301592


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.

Review Comment:
   I think this should be `A Spark function implementation for the Iceberg truncate transform.`



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r938332412


##########
spark/v3.3/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkTruncateFunction.java:
##########
@@ -0,0 +1,377 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.sql;
+
+import java.math.BigDecimal;
+import java.nio.charset.StandardCharsets;
+import org.apache.iceberg.AssertHelpers;
+import org.apache.iceberg.relocated.com.google.common.io.BaseEncoding;
+import org.apache.iceberg.spark.SparkTestBaseWithCatalog;
+import org.apache.spark.sql.AnalysisException;
+import org.assertj.core.api.Assertions;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestSparkTruncateFunction extends SparkTestBaseWithCatalog {
+  public TestSparkTruncateFunction() {}
+
+  @Before
+  public void useCatalog() {
+    sql("USE %s", catalogName);
+  }
+
+  @Test
+  public void testTruncateTinyInt() {
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 0Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 1Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 5Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 9Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 10Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 11Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -1Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -5Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -10Y)"));
+    Assert.assertEquals((byte) -20, scalarSql("SELECT system.truncate(10, -11Y)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((byte) -2, scalarSql("SELECT system.truncate(2, -1Y)"));
+
+    // Check that tinyint types are allowed for the width
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(5Y, 1Y)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS tinyint))"));
+  }
+
+  @Test
+  public void testTruncateSmallInt() {
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 0S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 1S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 5S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 9S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 10S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 11S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -1S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -5S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -10S)"));
+    Assert.assertEquals((short) -20, scalarSql("SELECT system.truncate(10, -11S)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((short) -2, scalarSql("SELECT system.truncate(2, -1S)"));
+
+    // Check that short types are allowed for the width
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(5S, 1S)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS smallint))"));
+  }
+
+  @Test
+  public void testTruncateInt() {
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 0));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 1));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 5));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 9));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, %d)", 10));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, %d)", 11));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -1));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -5));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -10));
+    Assert.assertEquals(-20, scalarSql("SELECT system.truncate(10, %d)", -11));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2, scalarSql("SELECT system.truncate(2, %d)", -1));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(300, %d)", 1));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS int))"));
+  }
+
+  @Test
+  public void testTruncateBigInt() {
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 0L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 1L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 5L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 9L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 10L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 11L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -1L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -5L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -10L)"));
+    Assert.assertEquals(-20L, scalarSql("SELECT system.truncate(10, -11L)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2L, scalarSql("SELECT system.truncate(2, -1L)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS bigint))"));
+  }
+
+  @Test
+  public void testTruncateDecimal() {
+    // decimal truncation works by applying the decimal scale to the width: ie 10 scale 2 = 0.10
+    Assert.assertEquals(
+        new BigDecimal("12.30"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 2)))", 12.34));

Review Comment:
   When working with decimals, you want to prefer strings. Formatting a decimal may give a different value and it looks like this assumes the value will be what was given as a float.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r941746178


##########
spark/v3.3/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkTruncateFunction.java:
##########
@@ -0,0 +1,377 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.sql;
+
+import java.math.BigDecimal;
+import java.nio.charset.StandardCharsets;
+import org.apache.iceberg.AssertHelpers;
+import org.apache.iceberg.relocated.com.google.common.io.BaseEncoding;
+import org.apache.iceberg.spark.SparkTestBaseWithCatalog;
+import org.apache.spark.sql.AnalysisException;
+import org.assertj.core.api.Assertions;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestSparkTruncateFunction extends SparkTestBaseWithCatalog {
+  public TestSparkTruncateFunction() {}
+
+  @Before
+  public void useCatalog() {
+    sql("USE %s", catalogName);
+  }
+
+  @Test
+  public void testTruncateTinyInt() {
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 0Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 1Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 5Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 9Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 10Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 11Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -1Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -5Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -10Y)"));
+    Assert.assertEquals((byte) -20, scalarSql("SELECT system.truncate(10, -11Y)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((byte) -2, scalarSql("SELECT system.truncate(2, -1Y)"));
+
+    // Check that tinyint types are allowed for the width
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(5Y, 1Y)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS tinyint))"));
+  }
+
+  @Test
+  public void testTruncateSmallInt() {
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 0S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 1S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 5S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 9S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 10S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 11S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -1S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -5S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -10S)"));
+    Assert.assertEquals((short) -20, scalarSql("SELECT system.truncate(10, -11S)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((short) -2, scalarSql("SELECT system.truncate(2, -1S)"));
+
+    // Check that short types are allowed for the width
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(5S, 1S)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS smallint))"));
+  }
+
+  @Test
+  public void testTruncateInt() {
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 0));

Review Comment:
   Hold over from a previous version. 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: issues-unsubscribe@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r942843224


##########
api/src/main/java/org/apache/iceberg/util/BinaryUtil.java:
##########
@@ -50,6 +50,22 @@ public static ByteBuffer truncateBinary(ByteBuffer input, int length) {
     return ByteBuffer.wrap(array);
   }
 
+  /**
+   * Truncates the input byte buffer to the given length.
+   *
+   * <p>This skips input validation, and avoids copying the backing bytes if possible for efficiency

Review Comment:
   Why does this say "if possible"? This always returns a duplicate of the original buffer.
   
   The distinction between this and `truncateBinary` is that this doesn't copy the data. You can remove any wording about efficiency or input validation. The buffer handles validation and will throw IllegalArgumentException if needed.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r942942890


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,348 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of [ByteType, ShortType, IntegerType, LongType, "
+                  + "DecimalType, StringType, BinaryType], but found %s",

Review Comment:
   TLDR - Spark prepends `Function 'truncate' cannot process input: (int, interval year to month): ` to the error message from the analysis 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: issues-unsubscribe@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r942953404


##########
api/src/main/java/org/apache/iceberg/transforms/Truncate.java:
##########
@@ -252,7 +254,7 @@ public CharSequence apply(CharSequence value) {
         return null;
       }
 
-      return UnicodeUtil.truncateString(value, length);
+      return UnicodeUtil.truncateStringUnsafe(length, value);

Review Comment:
   This wound up being removed anyway. In a separate PR, I'll update this `Transform` path to not validate the input width on every call but it's out of scope for 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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r939161764


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,

Review Comment:
   This is just the atomic types, as `DataTypes.DecimalType` cannot be used (a precision and scale is needed).
   
   In the validation for the truncation field, we include DecimalType the following way.
   
   ```java
     private static void validateTruncationFieldType(DataType dt) {
       if (truncateableAtomicTypes.stream().noneMatch(type -> type.sameType(dt))
           && !(dt instanceof DecimalType)) {
   ```
   
   Let me see if `DataTypes.createDecimalType()` will work and ignore the precision / scale so they can all be kept in one set.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r939224208


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,
+          DataTypes.StringType,
+          DataTypes.BinaryType);
+
+  private static void validateTruncationFieldType(DataType dt) {
+    if (truncateableAtomicTypes.stream().noneMatch(type -> type.sameType(dt))
+        && !(dt instanceof DecimalType)) {
+      String expectedTypes =
+          "[ByteType, ShortType, IntegerType, LongType, StringType, BinaryType, DecimalType]";
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of %s, but found %s",
+              expectedTypes, dt));
+    }
+  }
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type. Expected 2 fields but found %s", inputType.fields().length));
+    }
+
+    StructField widthField = inputType.apply(0);
+    StructField toTruncateField = inputType.apply(1);
+
+    validateTruncationFieldType(toTruncateField.dataType());
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType
+        || toTruncateDataType instanceof VarcharType
+        || toTruncateDataType instanceof CharType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException("Cannot truncate type: " + toTruncateDataType);
+    }
+  }
+
+  @Override
+  public String description() {
+    return "Truncate - The Iceberg truncate function used for truncate partition transformations.\n"
+        + "\tCalled with the truncation width as the first argument: e.g. system.truncate(width, col)";

Review Comment:
   Good call. That looks much cleaner. Updated to use `name()` and changed to this documentation 👍 



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r942015570


##########
api/src/main/java/org/apache/iceberg/transforms/Truncate.java:
##########
@@ -252,7 +254,7 @@ public CharSequence apply(CharSequence value) {
         return null;
       }
 
-      return UnicodeUtil.truncateString(value, length);
+      return UnicodeUtil.truncateStringUnsafe(length, value);

Review Comment:
   This change keeps the same logic but avoids checking the `width` in a precondition for every string.
   
   The width is already validated in the constructor and this is a hot code path.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r942933519


##########
api/src/main/java/org/apache/iceberg/util/BinaryUtil.java:
##########
@@ -50,6 +50,22 @@ public static ByteBuffer truncateBinary(ByteBuffer input, int length) {
     return ByteBuffer.wrap(array);
   }
 
+  /**
+   * Truncates the input byte buffer to the given length.
+   *
+   * <p>This skips input validation, and avoids copying the backing bytes if possible for efficiency
+   * reasons. This function should only be used if the input doesn't need validation. Likely {@link
+   * #truncateBinary(ByteBuffer, int)} is preferred.
+   *
+   * @param width The non-negative length to truncate input to
+   * @param value The ByteBuffer to be truncated
+   */
+  public static ByteBuffer truncateBinaryUnsafe(int width, ByteBuffer value) {

Review Comment:
   Sure. They were ordered this way to match the spark functions ordering and the ordering of the arguments of the `TruncateUtil`, but I agree it's confusing to have them in a different order within the same 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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r943859079


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be tinyint, shortint or int");
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());

Review Comment:
   So it looks like the `bucket` transform in Spark creartes a non-null integer field. So we can check that here too and it seems to reject correctly. Updating!
   
   https://github.com/apache/spark/blob/126870eddc57fff7408942897dd59a2c19c91c4a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/V2ExpressionUtils.scala#L90-L100



##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be tinyint, shortint or int");
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());

Review Comment:
   So it looks like the `bucket` transform in Spark creartes a non-null integer field called `numBuckets`. So we can check that here too and it seems to reject correctly. Updating!
   
   https://github.com/apache/spark/blob/126870eddc57fff7408942897dd59a2c19c91c4a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/V2ExpressionUtils.scala#L90-L100



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r941810030


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,348 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of [ByteType, ShortType, IntegerType, LongType, "
+                  + "DecimalType, StringType, BinaryType], but found %s",
+              toTruncateDataType));
+    }
+  }
+
+  @Override
+  public String description() {
+    return name()
+        + "(width, col) - Call Iceberg's truncate transform\n"
+        + "  width :: width for truncation, e.g. truncate(10, 255) -> 250 (must be an integer)\n"
+        + "  col :: column to truncate (must be an integer, decimal, string, or binary)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getByte(1));
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getShort(1));
+    }
+  }
+
+  public static class TruncateInt extends TruncateBase<Integer> {
+    // magic method used in codegen
+    public static int invoke(int width, int value) {
+      return TruncateUtil.truncateInt(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.IntegerType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.IntegerType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(int)";
+    }
+
+    @Override
+    public Integer produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getInt(1));
+    }
+  }
+
+  public static class TruncateBigInt extends TruncateBase<Long> {
+    // magic function for usage with codegen
+    public static long invoke(int width, long value) {
+      return TruncateUtil.truncateLong(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.LongType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.LongType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(bigint)";
+    }
+
+    @Override
+    public Long produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getLong(1));
+    }
+  }
+
+  public static class TruncateString extends TruncateBase<UTF8String> {
+    // magic function for usage with codegen
+    public static UTF8String invoke(int width, UTF8String value) {
+      if (value == null) {
+        return null;
+      }
+
+      return value.substring(0, width);

Review Comment:
   The built-in `substring` function of UTF8String is unicode point aware.
   
   It's almost certainly faster than converting to `ByteBuffer` and then `CharSequence` so we can use the existing `StringBuilder` based `UnicodeUtil` method for unicode code-point aware truncation.
   
   There's an existing function in `UTF8String`, called `toTitleCaseSlow` which uses a similar form as our `StringBuilder` based approach in `UnicodeUtil`, so I assume that the methods which rely on the bytes themselves and are code-point aware are faster than doing all of those conversions.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r942846908


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,348 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of [ByteType, ShortType, IntegerType, LongType, "
+                  + "DecimalType, StringType, BinaryType], but found %s",
+              toTruncateDataType));
+    }
+  }
+
+  @Override
+  public String description() {
+    return name()
+        + "(width, col) - Call Iceberg's truncate transform\n"
+        + "  width :: width for truncation, e.g. truncate(10, 255) -> 250 (must be an integer)\n"
+        + "  col :: column to truncate (must be an integer, decimal, string, or binary)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getByte(1));
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getShort(1));
+    }
+  }
+
+  public static class TruncateInt extends TruncateBase<Integer> {
+    // magic method used in codegen
+    public static int invoke(int width, int value) {
+      return TruncateUtil.truncateInt(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.IntegerType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.IntegerType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(int)";
+    }
+
+    @Override
+    public Integer produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getInt(1));
+    }
+  }
+
+  public static class TruncateBigInt extends TruncateBase<Long> {
+    // magic function for usage with codegen
+    public static long invoke(int width, long value) {
+      return TruncateUtil.truncateLong(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.LongType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.LongType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(bigint)";
+    }
+
+    @Override
+    public Long produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getLong(1));
+    }
+  }
+
+  public static class TruncateString extends TruncateBase<UTF8String> {
+    // magic function for usage with codegen
+    public static UTF8String invoke(int width, UTF8String value) {
+      if (value == null) {
+        return null;
+      }
+
+      return value.substring(0, width);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.StringType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.StringType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(string)";
+    }
+
+    @Override
+    public UTF8String produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getUTF8String(1));
+    }
+  }
+
+  public static class TruncateBinary extends TruncateBase<byte[]> {
+    // magic method used in codegen
+    public static byte[] invoke(int width, byte[] value) {
+      if (value == null) {
+        return null;
+      }
+
+      return ByteBuffers.toByteArray(
+          BinaryUtil.truncateBinaryUnsafe(width, ByteBuffer.wrap(value)));
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.BinaryType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.BinaryType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(binary)";
+    }
+
+    @Override
+    public byte[] produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getBinary(1));

Review Comment:
   Let's get rid of `width` and update these to `input.isNullAt(0) || input.isNullAt(1) ? null : invoke(input.getInt(0), input.getBinary(1))`



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r942960417


##########
api/src/main/java/org/apache/iceberg/util/UnicodeUtil.java:
##########
@@ -40,6 +40,17 @@ public static boolean isCharHighSurrogate(char ch) {
    */
   public static CharSequence truncateString(CharSequence input, int length) {
     Preconditions.checkArgument(length > 0, "Truncate length should be positive");
+    return truncateStringUnsafe(length, input);
+  }
+
+  /**
+   * Truncate the input charSequence such that the returned charSequence is a valid unicode string
+   * and the number of unicode characters in the truncated charSequence is lesser than or equal to
+   * length.
+   *
+   * <p>Note that this function does not validate the input

Review Comment:
   Opened https://github.com/apache/iceberg/pull/5496 to avoid validating the input on every record in the CharSequence Truncate transform.
   
   But it's out of scope for this PR so removed from 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: issues-unsubscribe@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r943907354


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be tinyint, shortint or int");
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());

Review Comment:
   I was able to get failure when the `width` field is explicitly non-null. I added two tests for it as well.
   
   I'm not sure if we should remove the checks for null in `produceResult` as Spark isn't great at tracking null vs not null. But it seems that if the schema is `nullable` that function binding will fail, so I personally think that's sufficient to remove the check for `result.isNullAt(WIDTH_ORDINAL)`. 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: issues-unsubscribe@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r938332811


##########
spark/v3.3/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkTruncateFunction.java:
##########
@@ -0,0 +1,377 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.sql;
+
+import java.math.BigDecimal;
+import java.nio.charset.StandardCharsets;
+import org.apache.iceberg.AssertHelpers;
+import org.apache.iceberg.relocated.com.google.common.io.BaseEncoding;
+import org.apache.iceberg.spark.SparkTestBaseWithCatalog;
+import org.apache.spark.sql.AnalysisException;
+import org.assertj.core.api.Assertions;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestSparkTruncateFunction extends SparkTestBaseWithCatalog {
+  public TestSparkTruncateFunction() {}
+
+  @Before
+  public void useCatalog() {
+    sql("USE %s", catalogName);
+  }
+
+  @Test
+  public void testTruncateTinyInt() {
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 0Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 1Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 5Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 9Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 10Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 11Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -1Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -5Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -10Y)"));
+    Assert.assertEquals((byte) -20, scalarSql("SELECT system.truncate(10, -11Y)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((byte) -2, scalarSql("SELECT system.truncate(2, -1Y)"));
+
+    // Check that tinyint types are allowed for the width
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(5Y, 1Y)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS tinyint))"));
+  }
+
+  @Test
+  public void testTruncateSmallInt() {
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 0S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 1S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 5S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 9S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 10S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 11S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -1S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -5S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -10S)"));
+    Assert.assertEquals((short) -20, scalarSql("SELECT system.truncate(10, -11S)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((short) -2, scalarSql("SELECT system.truncate(2, -1S)"));
+
+    // Check that short types are allowed for the width
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(5S, 1S)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS smallint))"));
+  }
+
+  @Test
+  public void testTruncateInt() {
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 0));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 1));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 5));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 9));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, %d)", 10));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, %d)", 11));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -1));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -5));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -10));
+    Assert.assertEquals(-20, scalarSql("SELECT system.truncate(10, %d)", -11));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2, scalarSql("SELECT system.truncate(2, %d)", -1));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(300, %d)", 1));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS int))"));
+  }
+
+  @Test
+  public void testTruncateBigInt() {
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 0L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 1L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 5L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 9L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 10L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 11L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -1L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -5L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -10L)"));
+    Assert.assertEquals(-20L, scalarSql("SELECT system.truncate(10, -11L)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2L, scalarSql("SELECT system.truncate(2, -1L)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS bigint))"));
+  }
+
+  @Test
+  public void testTruncateDecimal() {
+    // decimal truncation works by applying the decimal scale to the width: ie 10 scale 2 = 0.10
+    Assert.assertEquals(
+        new BigDecimal("12.30"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 2)))", 12.34));
+
+    Assert.assertEquals(
+        new BigDecimal("12.30"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 2)))", 12.30));
+
+    Assert.assertEquals(
+        new BigDecimal("12.290"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 3)))", 12.299));
+
+    Assert.assertEquals(
+        new BigDecimal("0.03"),
+        scalarSql("SELECT system.truncate(3, CAST(%f as DECIMAL(5, 2)))", 0.05));
+
+    Assert.assertEquals(
+        new BigDecimal("0.00"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 2)))", 0.05));
+
+    Assert.assertEquals(
+        new BigDecimal("-0.10"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 2)))", -0.05));
+
+    Assert.assertEquals(
+        "Implicit decimal scale and precision should be allowed",
+        new BigDecimal("12345.3480"),
+        scalarSql("SELECT system.truncate(10, 12345.3482)"));
+
+    int scale = 4;
+    BigDecimal truncatedDecimal =
+        (BigDecimal) scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(6, 4)))", -0.05);
+    Assert.assertEquals(
+        "Truncating a decimal should return a decimal with the same scale",
+        scale,
+        truncatedDecimal.scale());
+
+    Assert.assertEquals(
+        "Truncating a decimal should return a decimal with the correct scale",
+        BigDecimal.valueOf(-500, 4),
+        truncatedDecimal);
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS decimal))"));
+  }
+
+  @Test
+  public void testInvalidTypesCannotBeUsedForWidth() {

Review Comment:
   Is there a test that a short or byte can be used as a width?



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r938329257


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,
+          DataTypes.StringType,
+          DataTypes.BinaryType);
+
+  private static void validateTruncationFieldType(DataType dt) {
+    if (truncateableAtomicTypes.stream().noneMatch(type -> type.sameType(dt))
+        && !(dt instanceof DecimalType)) {
+      String expectedTypes =
+          "[ByteType, ShortType, IntegerType, LongType, StringType, BinaryType, DecimalType]";
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of %s, but found %s",
+              expectedTypes, dt));
+    }
+  }
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type. Expected 2 fields but found %s", inputType.fields().length));
+    }
+
+    StructField widthField = inputType.apply(0);
+    StructField toTruncateField = inputType.apply(1);
+
+    validateTruncationFieldType(toTruncateField.dataType());
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType
+        || toTruncateDataType instanceof VarcharType
+        || toTruncateDataType instanceof CharType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException("Cannot truncate type: " + toTruncateDataType);
+    }
+  }
+
+  @Override
+  public String description() {
+    return "Truncate - The Iceberg truncate function used for truncate partition transformations.\n"
+        + "\tCalled with the truncation width as the first argument: e.g. system.truncate(width, col)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Byte toTruncate = !input.isNullAt(1) ? input.getByte(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Short toTruncate = !input.isNullAt(1) ? input.getShort(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateInt extends TruncateBase<Integer> {
+    // magic method used in codegen
+    public static int invoke(int width, int value) {
+      return TruncateUtil.truncateInt(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.IntegerType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.IntegerType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](int)";
+    }
+
+    @Override
+    public Integer produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Integer toTruncate = !input.isNullAt(1) ? input.getInt(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateBigInt extends TruncateBase<Long> {
+    // magic function for usage with codegen
+    public static long invoke(int width, long value) {
+      return TruncateUtil.truncateLong(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.LongType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.LongType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](bigint)";
+    }
+
+    @Override
+    public Long produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Long toTruncate = !input.isNullAt(1) ? input.getLong(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateString extends TruncateBase<UTF8String> {
+    // magic function for usage with codegen
+    // TODO - This can likely be made more efficient, but using existing definition for now.
+    public static UTF8String invoke(int width, UTF8String value) {
+      if (value == null) {
+        return null;
+      }
+
+      ByteBuffer bb = value.getByteBuffer();
+      CharSequence charSequence = StandardCharsets.UTF_8.decode(bb);
+      CharSequence truncated = UnicodeUtil.truncateString(charSequence, width);
+      ByteBuffer truncatedBytes = StandardCharsets.UTF_8.encode(CharBuffer.wrap(truncated));
+      return UTF8String.fromBytes(ByteBuffers.toByteArray(truncatedBytes));
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.StringType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.StringType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](string)";
+    }
+
+    @Override
+    public UTF8String produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      UTF8String toTruncate = !input.isNullAt(1) ? input.getUTF8String(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateBinary extends TruncateBase<byte[]> {
+    // magic method used in codegen
+    public static byte[] invoke(int width, byte[] value) {
+      if (value == null) {
+        return null;
+      }
+
+      return ByteBuffers.toByteArray(
+          TruncateUtil.truncateByteBuffer(width, ByteBuffer.wrap(value)));
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.BinaryType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.BinaryType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](binary)";
+    }
+
+    @Override
+    public byte[] produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      byte[] toTruncate = !input.isNullAt(1) ? input.getBinary(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateDecimal extends TruncateBase<Decimal> {
+    private final int precision;
+    private final int scale;
+
+    public TruncateDecimal(int precision, int scale) {
+      this.precision = precision;
+      this.scale = scale;
+    }
+
+    // magic method used in codegen
+    public static Decimal invoke(int width, Decimal value) {
+      if (value == null) {
+        return null;
+      }
+
+      return Decimal.apply(
+          TruncateUtil.truncateDecimal(BigInteger.valueOf(width), value.toJavaBigDecimal()));
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.createDecimalType(precision, scale)};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.createDecimalType(precision, scale);
+    }
+
+    @Override
+    public String canonicalName() {
+      return String.format("iceberg.truncate[width](decimal(%d,%d))", precision, scale);
+    }
+
+    @Override
+    public Decimal produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Decimal toTruncate = !input.isNullAt(1) ? input.getDecimal(1, precision, scale) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  private static Integer readAndValidateWidth(InternalRow input) {

Review Comment:
   The logic here is odd. Why call `isNullAt` to box the value only to check whether it is null and throw an exception? I'd expect something like this:
   
   ```java
     if (input.isNullAt(0)) {
       throw IllegalArgumentException("Invalid truncation width: null");
     }
   
     return width;
   ```
   
   I left out checking whether width is negative. I don't think we care.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r939156271


##########
core/src/test/java/org/apache/iceberg/util/TestTruncateUtil.java:
##########
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.util;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.assertj.core.api.Assertions;
+import org.junit.Assert;
+import org.junit.jupiter.api.Test;
+
+class TestTruncateUtil {
+  @Test
+  public void testTruncateByteBuffer() throws Exception {
+    Assert.assertEquals(
+        "Should truncate binary longer than length",
+        ByteBuffer.wrap("abcd".getBytes("UTF-8")),
+        TruncateUtil.truncateByteBuffer(4, ByteBuffer.wrap("abcdefg".getBytes("UTF-8"))));
+    Assert.assertEquals(
+        "Should not pad binary shorter than length",
+        ByteBuffer.wrap("abc".getBytes("UTF-8")),
+        TruncateUtil.truncateByteBuffer(4, ByteBuffer.wrap("abc".getBytes("UTF-8"))));
+  }
+
+  @Test
+  public void testTruncateByte() {
+    Assert.assertEquals(
+        "Should return a byte value vs some other numeric type",
+        (byte) (Byte.MAX_VALUE - 1),
+        TruncateUtil.truncateByte(Byte.MAX_VALUE - 1, Byte.MAX_VALUE));
+  }
+
+  @Test
+  public void testTruncateShort() {
+    Assert.assertEquals(
+        "Should truncate a short and return a short",
+        (short) 0,
+        TruncateUtil.truncateShort(Short.MAX_VALUE + 1, Short.MAX_VALUE));
+  }
+
+  @Test
+  public void testTruncateInt() {
+    Assert.assertEquals(
+        "Should correctly truncate integer values and return an integer back",
+        Integer.MAX_VALUE - 1,
+        TruncateUtil.truncateInt(Integer.MAX_VALUE - 1, Integer.MAX_VALUE));
+  }
+
+  @Test
+  public void testTruncateLong() {
+    Assert.assertEquals(
+        "Should correctly truncate long values given a positive width and a long",
+        2147483647L,
+        TruncateUtil.truncateLong(Integer.MAX_VALUE, ((long) Integer.MAX_VALUE) + 1));
+  }
+
+  @Test
+  public void testTruncateDecimal() {
+    int width = 10;
+    Assert.assertEquals(
+        "Should return a decimal with the correct truncated value",
+        BigDecimal.valueOf(1230L, 2),
+        TruncateUtil.truncateDecimal(BigInteger.valueOf(width), BigDecimal.valueOf(1234L, 2)));
+
+    int scale = 2;
+    BigDecimal input = BigDecimal.valueOf(1234L, scale);

Review Comment:
   Removed.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r938293147


##########
api/src/main/java/org/apache/iceberg/util/TruncateUtil.java:
##########
@@ -0,0 +1,80 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.util;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+
+/**
+ * Contains the logic for various {@code truncate} transformations for various types.
+ *
+ * <p>This utility class allows for the logic to be reused in different scenarios where input
+ * validation is done at different times either in org.apache.iceberg.transforms.Truncate and within
+ * defined SQL functions for different compute engines for usage in SQL.
+ *
+ * <p>In general, the inputs to the functions should have already been validated by the calling
+ * code, as different classes use truncate with different preprocessing. This generally means that
+ * the truncation width is positive and the value to truncate is non-null.
+ *
+ * <p>Thus, <b>none</b> of these utility functions validate their input. <i>It is the responsibility
+ * of the calling code to validate input.</i>
+ *
+ * <p>See also {@linkplain UnicodeUtil#truncateString(CharSequence, int)} and {@link
+ * BinaryUtil#truncateBinary(ByteBuffer, int)}
+ */
+public class TruncateUtil {
+
+  private TruncateUtil() {}
+
+  public static ByteBuffer truncateByteBuffer(int width, ByteBuffer value) {
+    ByteBuffer ret = value.duplicate();
+    ret.limit(Math.min(value.limit(), value.position() + width));
+    return ret;
+  }

Review Comment:
   I think it's a bit confusing to have this as well as `BinaryUtil.truncateBinary`. The javadoc links to `truncateBinary`, but doesn't give any guidance about why there is a nearly identical method here.
   
   I think the motivation for this method is to avoid copying the backing bytes, which seems like a good idea. Instead of adding this here, I would like to see it move to `BinaryUtil` and given a name that distinguishes it from the behavior of `truncateBinary`. Maybe `truncateBinaryUnsafe` or something.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r942844824


##########
api/src/main/java/org/apache/iceberg/util/UnicodeUtil.java:
##########
@@ -40,6 +40,17 @@ public static boolean isCharHighSurrogate(char ch) {
    */
   public static CharSequence truncateString(CharSequence input, int length) {
     Preconditions.checkArgument(length > 0, "Truncate length should be positive");
+    return truncateStringUnsafe(length, input);
+  }
+
+  /**
+   * Truncate the input charSequence such that the returned charSequence is a valid unicode string
+   * and the number of unicode characters in the truncated charSequence is lesser than or equal to
+   * length.
+   *
+   * <p>Note that this function does not validate the input

Review Comment:
   Because this uses `UTF8String.substring`, this new method is not called. Can you please revert the changes here and in `Truncate`?



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r942931808


##########
api/src/main/java/org/apache/iceberg/util/BinaryUtil.java:
##########
@@ -50,6 +50,22 @@ public static ByteBuffer truncateBinary(ByteBuffer input, int length) {
     return ByteBuffer.wrap(array);
   }
 
+  /**
+   * Truncates the input byte buffer to the given length.
+   *
+   * <p>This skips input validation, and avoids copying the backing bytes if possible for efficiency

Review Comment:
   The main part remaining about skipping input validation is that `width` isn't validated to be non-negative. I can leave that out though if desired.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r942960511


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,348 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of [ByteType, ShortType, IntegerType, LongType, "
+                  + "DecimalType, StringType, BinaryType], but found %s",
+              toTruncateDataType));
+    }
+  }
+
+  @Override
+  public String description() {
+    return name()
+        + "(width, col) - Call Iceberg's truncate transform\n"
+        + "  width :: width for truncation, e.g. truncate(10, 255) -> 250 (must be an integer)\n"
+        + "  col :: column to truncate (must be an integer, decimal, string, or binary)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getByte(1));
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getShort(1));
+    }
+  }
+
+  public static class TruncateInt extends TruncateBase<Integer> {
+    // magic method used in codegen
+    public static int invoke(int width, int value) {
+      return TruncateUtil.truncateInt(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.IntegerType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.IntegerType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(int)";
+    }
+
+    @Override
+    public Integer produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getInt(1));
+    }
+  }
+
+  public static class TruncateBigInt extends TruncateBase<Long> {
+    // magic function for usage with codegen
+    public static long invoke(int width, long value) {
+      return TruncateUtil.truncateLong(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.LongType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.LongType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(bigint)";
+    }
+
+    @Override
+    public Long produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getLong(1));
+    }
+  }
+
+  public static class TruncateString extends TruncateBase<UTF8String> {
+    // magic function for usage with codegen
+    public static UTF8String invoke(int width, UTF8String value) {
+      if (value == null) {
+        return null;
+      }
+
+      return value.substring(0, width);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.StringType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.StringType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(string)";
+    }
+
+    @Override
+    public UTF8String produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getUTF8String(1));
+    }
+  }
+
+  public static class TruncateBinary extends TruncateBase<byte[]> {
+    // magic method used in codegen
+    public static byte[] invoke(int width, byte[] value) {
+      if (value == null) {
+        return null;
+      }
+
+      return ByteBuffers.toByteArray(
+          BinaryUtil.truncateBinaryUnsafe(width, ByteBuffer.wrap(value)));
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.BinaryType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.BinaryType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(binary)";
+    }
+
+    @Override
+    public byte[] produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getBinary(1));
+    }
+  }
+
+  public static class TruncateDecimal extends TruncateBase<Decimal> {
+    private final int precision;
+    private final int scale;
+
+    public TruncateDecimal(int precision, int scale) {
+      this.precision = precision;
+      this.scale = scale;
+    }
+
+    // magic method used in codegen
+    public static Decimal invoke(int width, Decimal value) {
+      if (value == null) {
+        return null;
+      }
+
+      return Decimal.apply(
+          TruncateUtil.truncateDecimal(BigInteger.valueOf(width), value.toJavaBigDecimal()));
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.createDecimalType(precision, scale)};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.createDecimalType(precision, scale);
+    }
+
+    @Override
+    public String canonicalName() {
+      return String.format("iceberg.truncate(decimal(%d,%d))", precision, scale);
+    }
+
+    @Override
+    public Decimal produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getDecimal(1, precision, scale));
+    }
+  }
+
+  // Not identical behavior to magic methods used in codegen,
+  // This function throws on a `null` width, to avoid boxing.
+  // The magic method in Spark's codegen will return `null` for a `null` width.

Review Comment:
   Updated and removed.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r942959901


##########
api/src/main/java/org/apache/iceberg/transforms/Truncate.java:
##########
@@ -252,7 +254,7 @@ public CharSequence apply(CharSequence value) {
         return null;
       }
 
-      return UnicodeUtil.truncateString(value, length);
+      return UnicodeUtil.truncateStringUnsafe(length, value);

Review Comment:
   I opened https://github.com/apache/iceberg/pull/5496 to skip validating the input `length` for CharSequence Truncate on every record.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r943741861


##########
spark/v3.3/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkTruncateFunction.java:
##########
@@ -0,0 +1,436 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.sql;
+
+import java.math.BigDecimal;
+import java.nio.charset.StandardCharsets;
+import org.apache.iceberg.AssertHelpers;
+import org.apache.iceberg.relocated.com.google.common.io.BaseEncoding;
+import org.apache.iceberg.spark.SparkTestBaseWithCatalog;
+import org.apache.spark.sql.AnalysisException;
+import org.assertj.core.api.Assertions;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestSparkTruncateFunction extends SparkTestBaseWithCatalog {
+  public TestSparkTruncateFunction() {}
+
+  @Before
+  public void useCatalog() {
+    sql("USE %s", catalogName);
+  }
+
+  @Test
+  public void testTruncateTinyInt() {
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 0Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 1Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 5Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 9Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 10Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 11Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -1Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -5Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -10Y)"));
+    Assert.assertEquals((byte) -20, scalarSql("SELECT system.truncate(10, -11Y)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((byte) -2, scalarSql("SELECT system.truncate(2, -1Y)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS tinyint))"));
+  }
+
+  @Test
+  public void testTruncateSmallInt() {
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 0S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 1S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 5S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 9S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 10S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 11S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -1S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -5S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -10S)"));
+    Assert.assertEquals((short) -20, scalarSql("SELECT system.truncate(10, -11S)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((short) -2, scalarSql("SELECT system.truncate(2, -1S)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS smallint))"));
+  }
+
+  @Test
+  public void testTruncateInt() {
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, 0)"));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, 1)"));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, 5)"));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, 9)"));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, 10)"));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, 11)"));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, -1)"));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, -5)"));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, -10)"));
+    Assert.assertEquals(-20, scalarSql("SELECT system.truncate(10, -11)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2, scalarSql("SELECT system.truncate(2, -1)"));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(300, 1)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS int))"));
+  }
+
+  @Test
+  public void testTruncateBigInt() {
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 0L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 1L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 5L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 9L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 10L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 11L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -1L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -5L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -10L)"));
+    Assert.assertEquals(-20L, scalarSql("SELECT system.truncate(10, -11L)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2L, scalarSql("SELECT system.truncate(2, -1L)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS bigint))"));
+  }
+
+  @Test
+  public void testTruncateDecimal() {
+    // decimal truncation works by applying the decimal scale to the width: ie 10 scale 2 = 0.10
+    Assert.assertEquals(
+        new BigDecimal("12.30"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 2)))", "12.34"));
+
+    Assert.assertEquals(
+        new BigDecimal("12.30"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 2)))", "12.30"));
+
+    Assert.assertEquals(
+        new BigDecimal("12.290"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 3)))", "12.299"));
+
+    Assert.assertEquals(
+        new BigDecimal("0.03"),
+        scalarSql("SELECT system.truncate(3, CAST(%s as DECIMAL(5, 2)))", "0.05"));
+
+    Assert.assertEquals(
+        new BigDecimal("0.00"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 2)))", "0.05"));
+
+    Assert.assertEquals(
+        new BigDecimal("-0.10"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 2)))", "-0.05"));
+
+    Assert.assertEquals(
+        "Implicit decimal scale and precision should be allowed",
+        new BigDecimal("12345.3480"),
+        scalarSql("SELECT system.truncate(10, 12345.3482)"));
+
+    BigDecimal truncatedDecimal =
+        (BigDecimal) scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(6, 4)))", "-0.05");
+    Assert.assertEquals(
+        "Truncating a decimal should return a decimal with the same scale",
+        4,
+        truncatedDecimal.scale());
+
+    Assert.assertEquals(
+        "Truncating a decimal should return a decimal with the correct scale",
+        BigDecimal.valueOf(-500, 4),
+        truncatedDecimal);
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS decimal))"));
+  }
+
+  @Test
+  public void testTruncateString() {
+    Assert.assertEquals(
+        "Should system.truncate strings longer than length",
+        "abcde",
+        scalarSql("SELECT system.truncate(5, 'abcdefg')"));
+
+    Assert.assertEquals(
+        "Should not pad strings shorter than length",
+        "abc",
+        scalarSql("SELECT system.truncate(5, 'abc')"));
+
+    Assert.assertEquals(
+        "Should not alter strings equal to length",
+        "abcde",
+        scalarSql("SELECT system.truncate(5, 'abcde')"));
+
+    Assert.assertEquals(
+        "Should handle three-byte UTF-8 characters appropriately",
+        "测",
+        scalarSql("SELECT system.truncate(1, '测试')"));
+
+    Assert.assertEquals(
+        "Should handle three-byte UTF-8 characters mixed with two byte utf-8 characters",
+        "测试ra",
+        scalarSql("SELECT system.truncate(4, '测试raul试测')"));

Review Comment:
   Let me see if I can find more test cases somewhere 🙂 



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r943914954


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be tinyint, shortint or int");
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          "Expected truncation col to be tinyint, shortint, int, bigint, decimal, string, or binary");
+    }
+  }
+
+  @Override
+  public String description() {
+    return name()
+        + "(width, col) - Call Iceberg's truncate transform\n"
+        + "  width :: width for truncation, e.g. truncate(10, 255) -> 250 (must be an integer)\n"
+        + "  col :: column to truncate (must be an integer, decimal, string, or binary)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      return input.isNullAt(0) || input.isNullAt(1)
+          ? null
+          : invoke(input.getInt(0), input.getByte(1));
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      return input.isNullAt(0) || input.isNullAt(1)

Review Comment:
   I reverted the check for `width` field nullability and the associated tests.
   
   I think this is the right choice as Spark is notoriously not great at tracking whether a field is non-null or not. But here's the commit that has the check and tests in case you're curious: https://github.com/apache/iceberg/pull/5431/commits/ad5343facb561750f24e59e8cdba4da882b0313c



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#issuecomment-1212481879

   @aokolnychyi @rdblue I addressed all of your feedback.
   
   Please take a look when you get a chance. Also, on the subject of nullability for the `width` column, I was able to make it work but reverted it based on this comment thread: https://github.com/apache/iceberg/pull/5431#discussion_r943914954
   
   Knowing that Spark isn't the best at keeping track of nullability, I think this is better and adheres to the contract laid out in `ScalarFunction` as quoted by @aokolnychyi.
   
   But take a look at the commit that added nullability-checking on the width field if you'd like: https://github.com/apache/iceberg/pull/5431/commits/ad5343facb561750f24e59e8cdba4da882b0313c


-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#issuecomment-1212599724

   Looks good to me. @aokolnychyi, do you want to take another look?


-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#issuecomment-1210158609

   cc @nastra and @aokolnychyi as well as you reviewed the FunctionCatalog PR itself 🙂 


-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r940664454


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,
+          DataTypes.StringType,
+          DataTypes.BinaryType);
+
+  private static void validateTruncationFieldType(DataType dt) {
+    if (truncateableAtomicTypes.stream().noneMatch(type -> type.sameType(dt))
+        && !(dt instanceof DecimalType)) {
+      String expectedTypes =
+          "[ByteType, ShortType, IntegerType, LongType, StringType, BinaryType, DecimalType]";
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of %s, but found %s",
+              expectedTypes, dt));
+    }
+  }
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type. Expected 2 fields but found %s", inputType.fields().length));
+    }
+
+    StructField widthField = inputType.apply(0);
+    StructField toTruncateField = inputType.apply(1);
+
+    validateTruncationFieldType(toTruncateField.dataType());
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType
+        || toTruncateDataType instanceof VarcharType
+        || toTruncateDataType instanceof CharType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException("Cannot truncate type: " + toTruncateDataType);
+    }
+  }
+
+  @Override
+  public String description() {
+    return "Truncate - The Iceberg truncate function used for truncate partition transformations.\n"
+        + "\tCalled with the truncation width as the first argument: e.g. system.truncate(width, col)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](tinyint)";

Review Comment:
   Ok. Should we use `iceberg.truncate(int, tinyint)` or just leave it out entirely?



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r941810030


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,348 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of [ByteType, ShortType, IntegerType, LongType, "
+                  + "DecimalType, StringType, BinaryType], but found %s",
+              toTruncateDataType));
+    }
+  }
+
+  @Override
+  public String description() {
+    return name()
+        + "(width, col) - Call Iceberg's truncate transform\n"
+        + "  width :: width for truncation, e.g. truncate(10, 255) -> 250 (must be an integer)\n"
+        + "  col :: column to truncate (must be an integer, decimal, string, or binary)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getByte(1));
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getShort(1));
+    }
+  }
+
+  public static class TruncateInt extends TruncateBase<Integer> {
+    // magic method used in codegen
+    public static int invoke(int width, int value) {
+      return TruncateUtil.truncateInt(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.IntegerType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.IntegerType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(int)";
+    }
+
+    @Override
+    public Integer produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getInt(1));
+    }
+  }
+
+  public static class TruncateBigInt extends TruncateBase<Long> {
+    // magic function for usage with codegen
+    public static long invoke(int width, long value) {
+      return TruncateUtil.truncateLong(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.LongType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.LongType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(bigint)";
+    }
+
+    @Override
+    public Long produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getLong(1));
+    }
+  }
+
+  public static class TruncateString extends TruncateBase<UTF8String> {
+    // magic function for usage with codegen
+    public static UTF8String invoke(int width, UTF8String value) {
+      if (value == null) {
+        return null;
+      }
+
+      return value.substring(0, width);

Review Comment:
   The built-in `substring` function of UTF8String is almost certainly faster than converting to `ByteBuffer` and then `CharSequence` so we can use the existing `StringBuilder` based `UnicodeUtil` method for code-point based truncation, so using that.
   
   There's an existing function in `UTF8String`, called `toTitleCaseSlow` which uses our StringBuilder based approach, so I assume that the methods which rely on the bytes themselves and are code-point aware are faster than doing all of those conversions.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r943122405


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,348 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of [ByteType, ShortType, IntegerType, LongType, "
+                  + "DecimalType, StringType, BinaryType], but found %s",
+              toTruncateDataType));
+    }
+  }
+
+  @Override
+  public String description() {
+    return name()
+        + "(width, col) - Call Iceberg's truncate transform\n"
+        + "  width :: width for truncation, e.g. truncate(10, 255) -> 250 (must be an integer)\n"
+        + "  col :: column to truncate (must be an integer, decimal, string, or binary)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getByte(1));
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getShort(1));
+    }
+  }
+
+  public static class TruncateInt extends TruncateBase<Integer> {
+    // magic method used in codegen
+    public static int invoke(int width, int value) {
+      return TruncateUtil.truncateInt(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.IntegerType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.IntegerType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(int)";
+    }
+
+    @Override
+    public Integer produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getInt(1));
+    }
+  }
+
+  public static class TruncateBigInt extends TruncateBase<Long> {
+    // magic function for usage with codegen
+    public static long invoke(int width, long value) {
+      return TruncateUtil.truncateLong(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.LongType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.LongType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(bigint)";
+    }
+
+    @Override
+    public Long produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getLong(1));
+    }
+  }
+
+  public static class TruncateString extends TruncateBase<UTF8String> {
+    // magic function for usage with codegen
+    public static UTF8String invoke(int width, UTF8String value) {
+      if (value == null) {
+        return null;
+      }
+
+      return value.substring(0, width);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.StringType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.StringType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(string)";
+    }
+
+    @Override
+    public UTF8String produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getUTF8String(1));
+    }
+  }
+
+  public static class TruncateBinary extends TruncateBase<byte[]> {
+    // magic method used in codegen
+    public static byte[] invoke(int width, byte[] value) {
+      if (value == null) {
+        return null;
+      }
+
+      return ByteBuffers.toByteArray(
+          BinaryUtil.truncateBinaryUnsafe(width, ByteBuffer.wrap(value)));
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.BinaryType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.BinaryType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(binary)";
+    }
+
+    @Override
+    public byte[] produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getBinary(1));

Review Comment:
   Actually added the null check back in, as certain specialized accessors might throw instead of returning null if the underlying value is null.
   
   Figured it was safer to just keep the implementation consistent.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r943820942


##########
spark/v3.3/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkTruncateFunction.java:
##########
@@ -0,0 +1,436 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.sql;
+
+import java.math.BigDecimal;
+import java.nio.charset.StandardCharsets;
+import org.apache.iceberg.AssertHelpers;
+import org.apache.iceberg.relocated.com.google.common.io.BaseEncoding;
+import org.apache.iceberg.spark.SparkTestBaseWithCatalog;
+import org.apache.spark.sql.AnalysisException;
+import org.assertj.core.api.Assertions;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestSparkTruncateFunction extends SparkTestBaseWithCatalog {
+  public TestSparkTruncateFunction() {}
+
+  @Before
+  public void useCatalog() {
+    sql("USE %s", catalogName);
+  }
+
+  @Test
+  public void testTruncateTinyInt() {
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 0Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 1Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 5Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 9Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 10Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 11Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -1Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -5Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -10Y)"));
+    Assert.assertEquals((byte) -20, scalarSql("SELECT system.truncate(10, -11Y)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((byte) -2, scalarSql("SELECT system.truncate(2, -1Y)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS tinyint))"));
+  }
+
+  @Test
+  public void testTruncateSmallInt() {
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 0S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 1S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 5S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 9S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 10S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 11S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -1S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -5S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -10S)"));
+    Assert.assertEquals((short) -20, scalarSql("SELECT system.truncate(10, -11S)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((short) -2, scalarSql("SELECT system.truncate(2, -1S)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS smallint))"));
+  }
+
+  @Test
+  public void testTruncateInt() {
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, 0)"));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, 1)"));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, 5)"));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, 9)"));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, 10)"));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, 11)"));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, -1)"));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, -5)"));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, -10)"));
+    Assert.assertEquals(-20, scalarSql("SELECT system.truncate(10, -11)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2, scalarSql("SELECT system.truncate(2, -1)"));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(300, 1)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS int))"));
+  }
+
+  @Test
+  public void testTruncateBigInt() {
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 0L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 1L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 5L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 9L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 10L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 11L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -1L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -5L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -10L)"));
+    Assert.assertEquals(-20L, scalarSql("SELECT system.truncate(10, -11L)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2L, scalarSql("SELECT system.truncate(2, -1L)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS bigint))"));
+  }
+
+  @Test
+  public void testTruncateDecimal() {
+    // decimal truncation works by applying the decimal scale to the width: ie 10 scale 2 = 0.10
+    Assert.assertEquals(
+        new BigDecimal("12.30"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 2)))", "12.34"));
+
+    Assert.assertEquals(
+        new BigDecimal("12.30"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 2)))", "12.30"));
+
+    Assert.assertEquals(
+        new BigDecimal("12.290"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 3)))", "12.299"));
+
+    Assert.assertEquals(
+        new BigDecimal("0.03"),
+        scalarSql("SELECT system.truncate(3, CAST(%s as DECIMAL(5, 2)))", "0.05"));
+
+    Assert.assertEquals(
+        new BigDecimal("0.00"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 2)))", "0.05"));
+
+    Assert.assertEquals(
+        new BigDecimal("-0.10"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 2)))", "-0.05"));
+
+    Assert.assertEquals(
+        "Implicit decimal scale and precision should be allowed",
+        new BigDecimal("12345.3480"),
+        scalarSql("SELECT system.truncate(10, 12345.3482)"));
+
+    BigDecimal truncatedDecimal =
+        (BigDecimal) scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(6, 4)))", "-0.05");
+    Assert.assertEquals(
+        "Truncating a decimal should return a decimal with the same scale",
+        4,
+        truncatedDecimal.scale());
+
+    Assert.assertEquals(
+        "Truncating a decimal should return a decimal with the correct scale",
+        BigDecimal.valueOf(-500, 4),
+        truncatedDecimal);
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS decimal))"));
+  }
+
+  @Test
+  public void testTruncateString() {
+    Assert.assertEquals(
+        "Should system.truncate strings longer than length",
+        "abcde",
+        scalarSql("SELECT system.truncate(5, 'abcdefg')"));
+
+    Assert.assertEquals(
+        "Should not pad strings shorter than length",
+        "abc",
+        scalarSql("SELECT system.truncate(5, 'abc')"));
+
+    Assert.assertEquals(
+        "Should not alter strings equal to length",
+        "abcde",
+        scalarSql("SELECT system.truncate(5, 'abcde')"));
+
+    Assert.assertEquals(
+        "Should handle three-byte UTF-8 characters appropriately",
+        "测",
+        scalarSql("SELECT system.truncate(1, '测试')"));
+
+    Assert.assertEquals(
+        "Should handle three-byte UTF-8 characters mixed with two byte utf-8 characters",
+        "测试ra",
+        scalarSql("SELECT system.truncate(4, '测试raul试测')"));

Review Comment:
   I copied over the tests from `TestmetricsTruncation` to ensure that 2-byte, 3-byte, and 4-byt UTF-8 codepoints were all covered.
   
   So we should be fully covered in terms of testing truncate String (at least as covered as we are elsewhere).



##########
spark/v3.3/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkTruncateFunction.java:
##########
@@ -0,0 +1,436 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.sql;
+
+import java.math.BigDecimal;
+import java.nio.charset.StandardCharsets;
+import org.apache.iceberg.AssertHelpers;
+import org.apache.iceberg.relocated.com.google.common.io.BaseEncoding;
+import org.apache.iceberg.spark.SparkTestBaseWithCatalog;
+import org.apache.spark.sql.AnalysisException;
+import org.assertj.core.api.Assertions;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestSparkTruncateFunction extends SparkTestBaseWithCatalog {
+  public TestSparkTruncateFunction() {}
+
+  @Before
+  public void useCatalog() {
+    sql("USE %s", catalogName);
+  }
+
+  @Test
+  public void testTruncateTinyInt() {
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 0Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 1Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 5Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 9Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 10Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 11Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -1Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -5Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -10Y)"));
+    Assert.assertEquals((byte) -20, scalarSql("SELECT system.truncate(10, -11Y)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((byte) -2, scalarSql("SELECT system.truncate(2, -1Y)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS tinyint))"));
+  }
+
+  @Test
+  public void testTruncateSmallInt() {
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 0S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 1S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 5S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 9S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 10S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 11S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -1S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -5S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -10S)"));
+    Assert.assertEquals((short) -20, scalarSql("SELECT system.truncate(10, -11S)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((short) -2, scalarSql("SELECT system.truncate(2, -1S)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS smallint))"));
+  }
+
+  @Test
+  public void testTruncateInt() {
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, 0)"));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, 1)"));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, 5)"));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, 9)"));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, 10)"));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, 11)"));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, -1)"));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, -5)"));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, -10)"));
+    Assert.assertEquals(-20, scalarSql("SELECT system.truncate(10, -11)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2, scalarSql("SELECT system.truncate(2, -1)"));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(300, 1)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS int))"));
+  }
+
+  @Test
+  public void testTruncateBigInt() {
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 0L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 1L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 5L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 9L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 10L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 11L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -1L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -5L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -10L)"));
+    Assert.assertEquals(-20L, scalarSql("SELECT system.truncate(10, -11L)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2L, scalarSql("SELECT system.truncate(2, -1L)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS bigint))"));
+  }
+
+  @Test
+  public void testTruncateDecimal() {
+    // decimal truncation works by applying the decimal scale to the width: ie 10 scale 2 = 0.10
+    Assert.assertEquals(
+        new BigDecimal("12.30"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 2)))", "12.34"));
+
+    Assert.assertEquals(
+        new BigDecimal("12.30"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 2)))", "12.30"));
+
+    Assert.assertEquals(
+        new BigDecimal("12.290"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 3)))", "12.299"));
+
+    Assert.assertEquals(
+        new BigDecimal("0.03"),
+        scalarSql("SELECT system.truncate(3, CAST(%s as DECIMAL(5, 2)))", "0.05"));
+
+    Assert.assertEquals(
+        new BigDecimal("0.00"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 2)))", "0.05"));
+
+    Assert.assertEquals(
+        new BigDecimal("-0.10"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 2)))", "-0.05"));
+
+    Assert.assertEquals(
+        "Implicit decimal scale and precision should be allowed",
+        new BigDecimal("12345.3480"),
+        scalarSql("SELECT system.truncate(10, 12345.3482)"));
+
+    BigDecimal truncatedDecimal =
+        (BigDecimal) scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(6, 4)))", "-0.05");
+    Assert.assertEquals(
+        "Truncating a decimal should return a decimal with the same scale",
+        4,
+        truncatedDecimal.scale());
+
+    Assert.assertEquals(
+        "Truncating a decimal should return a decimal with the correct scale",
+        BigDecimal.valueOf(-500, 4),
+        truncatedDecimal);
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS decimal))"));
+  }
+
+  @Test
+  public void testTruncateString() {
+    Assert.assertEquals(
+        "Should system.truncate strings longer than length",
+        "abcde",
+        scalarSql("SELECT system.truncate(5, 'abcdefg')"));
+
+    Assert.assertEquals(
+        "Should not pad strings shorter than length",
+        "abc",
+        scalarSql("SELECT system.truncate(5, 'abc')"));
+
+    Assert.assertEquals(
+        "Should not alter strings equal to length",
+        "abcde",
+        scalarSql("SELECT system.truncate(5, 'abcde')"));
+
+    Assert.assertEquals(
+        "Should handle three-byte UTF-8 characters appropriately",
+        "测",
+        scalarSql("SELECT system.truncate(1, '测试')"));
+
+    Assert.assertEquals(
+        "Should handle three-byte UTF-8 characters mixed with two byte utf-8 characters",
+        "测试ra",
+        scalarSql("SELECT system.truncate(4, '测试raul试测')"));

Review Comment:
   I copied over the tests from `TestmetricsTruncation` to ensure that 2-byte, 3-byte, and 4-byte UTF-8 codepoints were all covered.
   
   So we should be fully covered in terms of testing truncate String (at least as covered as we are elsewhere).



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r943717037


##########
spark/v3.3/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkTruncateFunction.java:
##########
@@ -0,0 +1,436 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.sql;
+
+import java.math.BigDecimal;
+import java.nio.charset.StandardCharsets;
+import org.apache.iceberg.AssertHelpers;
+import org.apache.iceberg.relocated.com.google.common.io.BaseEncoding;
+import org.apache.iceberg.spark.SparkTestBaseWithCatalog;
+import org.apache.spark.sql.AnalysisException;
+import org.assertj.core.api.Assertions;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestSparkTruncateFunction extends SparkTestBaseWithCatalog {
+  public TestSparkTruncateFunction() {}
+
+  @Before
+  public void useCatalog() {
+    sql("USE %s", catalogName);
+  }
+
+  @Test
+  public void testTruncateTinyInt() {
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 0Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 1Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 5Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 9Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 10Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 11Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -1Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -5Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -10Y)"));
+    Assert.assertEquals((byte) -20, scalarSql("SELECT system.truncate(10, -11Y)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((byte) -2, scalarSql("SELECT system.truncate(2, -1Y)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS tinyint))"));
+  }
+
+  @Test
+  public void testTruncateSmallInt() {
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 0S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 1S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 5S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 9S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 10S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 11S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -1S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -5S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -10S)"));
+    Assert.assertEquals((short) -20, scalarSql("SELECT system.truncate(10, -11S)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((short) -2, scalarSql("SELECT system.truncate(2, -1S)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS smallint))"));
+  }
+
+  @Test
+  public void testTruncateInt() {
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, 0)"));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, 1)"));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, 5)"));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, 9)"));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, 10)"));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, 11)"));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, -1)"));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, -5)"));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, -10)"));
+    Assert.assertEquals(-20, scalarSql("SELECT system.truncate(10, -11)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2, scalarSql("SELECT system.truncate(2, -1)"));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(300, 1)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS int))"));
+  }
+
+  @Test
+  public void testTruncateBigInt() {
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 0L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 1L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 5L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 9L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 10L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 11L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -1L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -5L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -10L)"));
+    Assert.assertEquals(-20L, scalarSql("SELECT system.truncate(10, -11L)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2L, scalarSql("SELECT system.truncate(2, -1L)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS bigint))"));
+  }
+
+  @Test
+  public void testTruncateDecimal() {
+    // decimal truncation works by applying the decimal scale to the width: ie 10 scale 2 = 0.10
+    Assert.assertEquals(
+        new BigDecimal("12.30"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 2)))", "12.34"));
+
+    Assert.assertEquals(
+        new BigDecimal("12.30"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 2)))", "12.30"));
+
+    Assert.assertEquals(
+        new BigDecimal("12.290"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 3)))", "12.299"));
+
+    Assert.assertEquals(
+        new BigDecimal("0.03"),
+        scalarSql("SELECT system.truncate(3, CAST(%s as DECIMAL(5, 2)))", "0.05"));
+
+    Assert.assertEquals(
+        new BigDecimal("0.00"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 2)))", "0.05"));
+
+    Assert.assertEquals(
+        new BigDecimal("-0.10"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 2)))", "-0.05"));
+
+    Assert.assertEquals(
+        "Implicit decimal scale and precision should be allowed",
+        new BigDecimal("12345.3480"),
+        scalarSql("SELECT system.truncate(10, 12345.3482)"));
+
+    BigDecimal truncatedDecimal =
+        (BigDecimal) scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(6, 4)))", "-0.05");
+    Assert.assertEquals(
+        "Truncating a decimal should return a decimal with the same scale",
+        4,
+        truncatedDecimal.scale());
+
+    Assert.assertEquals(
+        "Truncating a decimal should return a decimal with the correct scale",
+        BigDecimal.valueOf(-500, 4),
+        truncatedDecimal);
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS decimal))"));
+  }
+
+  @Test
+  public void testTruncateString() {
+    Assert.assertEquals(
+        "Should system.truncate strings longer than length",
+        "abcde",
+        scalarSql("SELECT system.truncate(5, 'abcdefg')"));
+
+    Assert.assertEquals(
+        "Should not pad strings shorter than length",
+        "abc",
+        scalarSql("SELECT system.truncate(5, 'abc')"));
+
+    Assert.assertEquals(
+        "Should not alter strings equal to length",
+        "abcde",
+        scalarSql("SELECT system.truncate(5, 'abcde')"));
+
+    Assert.assertEquals(
+        "Should handle three-byte UTF-8 characters appropriately",
+        "测",
+        scalarSql("SELECT system.truncate(1, '测试')"));
+
+    Assert.assertEquals(
+        "Should handle three-byte UTF-8 characters mixed with two byte utf-8 characters",
+        "测试ra",
+        scalarSql("SELECT system.truncate(4, '测试raul试测')"));

Review Comment:
   Because we are using Spark's truncate function, I think this needs to run through all of the test cases for Iceberg's `UnicodeUtil.truncateString` and make sure we get the expected output.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r941736160


##########
spark/v3.3/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkTruncateFunction.java:
##########
@@ -0,0 +1,377 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.sql;
+
+import java.math.BigDecimal;
+import java.nio.charset.StandardCharsets;
+import org.apache.iceberg.AssertHelpers;
+import org.apache.iceberg.relocated.com.google.common.io.BaseEncoding;
+import org.apache.iceberg.spark.SparkTestBaseWithCatalog;
+import org.apache.spark.sql.AnalysisException;
+import org.assertj.core.api.Assertions;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestSparkTruncateFunction extends SparkTestBaseWithCatalog {
+  public TestSparkTruncateFunction() {}
+
+  @Before
+  public void useCatalog() {
+    sql("USE %s", catalogName);
+  }
+
+  @Test
+  public void testTruncateTinyInt() {
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 0Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 1Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 5Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 9Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 10Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 11Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -1Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -5Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -10Y)"));
+    Assert.assertEquals((byte) -20, scalarSql("SELECT system.truncate(10, -11Y)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((byte) -2, scalarSql("SELECT system.truncate(2, -1Y)"));
+
+    // Check that tinyint types are allowed for the width
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(5Y, 1Y)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS tinyint))"));
+  }
+
+  @Test
+  public void testTruncateSmallInt() {
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 0S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 1S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 5S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 9S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 10S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 11S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -1S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -5S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -10S)"));
+    Assert.assertEquals((short) -20, scalarSql("SELECT system.truncate(10, -11S)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((short) -2, scalarSql("SELECT system.truncate(2, -1S)"));
+
+    // Check that short types are allowed for the width
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(5S, 1S)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS smallint))"));
+  }
+
+  @Test
+  public void testTruncateInt() {
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 0));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 1));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 5));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 9));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, %d)", 10));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, %d)", 11));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -1));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -5));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -10));
+    Assert.assertEquals(-20, scalarSql("SELECT system.truncate(10, %d)", -11));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2, scalarSql("SELECT system.truncate(2, %d)", -1));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(300, %d)", 1));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS int))"));
+  }
+
+  @Test
+  public void testTruncateBigInt() {
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 0L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 1L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 5L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 9L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 10L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 11L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -1L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -5L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -10L)"));
+    Assert.assertEquals(-20L, scalarSql("SELECT system.truncate(10, -11L)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2L, scalarSql("SELECT system.truncate(2, -1L)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS bigint))"));
+  }
+
+  @Test
+  public void testTruncateDecimal() {
+    // decimal truncation works by applying the decimal scale to the width: ie 10 scale 2 = 0.10
+    Assert.assertEquals(
+        new BigDecimal("12.30"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 2)))", 12.34));
+
+    Assert.assertEquals(
+        new BigDecimal("12.30"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 2)))", 12.30));
+
+    Assert.assertEquals(
+        new BigDecimal("12.290"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 3)))", 12.299));
+
+    Assert.assertEquals(
+        new BigDecimal("0.03"),
+        scalarSql("SELECT system.truncate(3, CAST(%f as DECIMAL(5, 2)))", 0.05));
+
+    Assert.assertEquals(
+        new BigDecimal("0.00"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 2)))", 0.05));
+
+    Assert.assertEquals(
+        new BigDecimal("-0.10"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 2)))", -0.05));
+
+    Assert.assertEquals(
+        "Implicit decimal scale and precision should be allowed",
+        new BigDecimal("12345.3480"),
+        scalarSql("SELECT system.truncate(10, 12345.3482)"));
+
+    int scale = 4;
+    BigDecimal truncatedDecimal =
+        (BigDecimal) scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(6, 4)))", -0.05);
+    Assert.assertEquals(
+        "Truncating a decimal should return a decimal with the same scale",
+        scale,
+        truncatedDecimal.scale());
+
+    Assert.assertEquals(
+        "Truncating a decimal should return a decimal with the correct scale",
+        BigDecimal.valueOf(-500, 4),
+        truncatedDecimal);
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS decimal))"));
+  }
+
+  @Test
+  public void testInvalidTypesCannotBeUsedForWidth() {

Review Comment:
   Added `testWidthAcceptsShortAndByte`



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r941801024


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,

Review Comment:
   Got rid of the function and am now depending on this input block.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r943854193


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be tinyint, shortint or int");
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());

Review Comment:
   Let me see if the logic added for storage-partitioned joins creates a`bucket` function that uses a non-null integer type.
   
   I know this is `truncate`, but that can inform the decision here.



##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be tinyint, shortint or int");
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];

Review Comment:
   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: issues-unsubscribe@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r942843698


##########
api/src/main/java/org/apache/iceberg/util/BinaryUtil.java:
##########
@@ -50,6 +50,22 @@ public static ByteBuffer truncateBinary(ByteBuffer input, int length) {
     return ByteBuffer.wrap(array);
   }
 
+  /**
+   * Truncates the input byte buffer to the given length.
+   *
+   * <p>This skips input validation, and avoids copying the backing bytes if possible for efficiency
+   * reasons. This function should only be used if the input doesn't need validation. Likely {@link
+   * #truncateBinary(ByteBuffer, int)} is preferred.
+   *
+   * @param width The non-negative length to truncate input to
+   * @param value The ByteBuffer to be truncated
+   */
+  public static ByteBuffer truncateBinaryUnsafe(int width, ByteBuffer value) {

Review Comment:
   Can you order arguments to match the `truncateBinary` function? It is confusing to have them in a different order.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] aokolnychyi commented on pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
aokolnychyi commented on PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#issuecomment-1213236871

   Thanks, @kbendick! Could you cherry-pick this to 3.2?


-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r938300094


##########
core/src/test/java/org/apache/iceberg/util/TestTruncateUtil.java:
##########
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.util;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.assertj.core.api.Assertions;
+import org.junit.Assert;
+import org.junit.jupiter.api.Test;
+
+class TestTruncateUtil {
+  @Test
+  public void testTruncateByteBuffer() throws Exception {
+    Assert.assertEquals(
+        "Should truncate binary longer than length",
+        ByteBuffer.wrap("abcd".getBytes("UTF-8")),
+        TruncateUtil.truncateByteBuffer(4, ByteBuffer.wrap("abcdefg".getBytes("UTF-8"))));
+    Assert.assertEquals(
+        "Should not pad binary shorter than length",
+        ByteBuffer.wrap("abc".getBytes("UTF-8")),
+        TruncateUtil.truncateByteBuffer(4, ByteBuffer.wrap("abc".getBytes("UTF-8"))));
+  }
+
+  @Test
+  public void testTruncateByte() {
+    Assert.assertEquals(
+        "Should return a byte value vs some other numeric type",
+        (byte) (Byte.MAX_VALUE - 1),
+        TruncateUtil.truncateByte(Byte.MAX_VALUE - 1, Byte.MAX_VALUE));
+  }
+
+  @Test
+  public void testTruncateShort() {
+    Assert.assertEquals(
+        "Should truncate a short and return a short",
+        (short) 0,
+        TruncateUtil.truncateShort(Short.MAX_VALUE + 1, Short.MAX_VALUE));
+  }
+
+  @Test
+  public void testTruncateInt() {
+    Assert.assertEquals(
+        "Should correctly truncate integer values and return an integer back",
+        Integer.MAX_VALUE - 1,
+        TruncateUtil.truncateInt(Integer.MAX_VALUE - 1, Integer.MAX_VALUE));
+  }
+
+  @Test
+  public void testTruncateLong() {
+    Assert.assertEquals(
+        "Should correctly truncate long values given a positive width and a long",
+        2147483647L,
+        TruncateUtil.truncateLong(Integer.MAX_VALUE, ((long) Integer.MAX_VALUE) + 1));
+  }
+
+  @Test
+  public void testTruncateDecimal() {
+    int width = 10;
+    Assert.assertEquals(
+        "Should return a decimal with the correct truncated value",
+        BigDecimal.valueOf(1230L, 2),
+        TruncateUtil.truncateDecimal(BigInteger.valueOf(width), BigDecimal.valueOf(1234L, 2)));
+
+    int scale = 2;
+    BigDecimal input = BigDecimal.valueOf(1234L, scale);

Review Comment:
   Why use a local variable for `scale` here, but not above? It isn't referenced anywhere because the expected value is `input.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: issues-unsubscribe@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r938332919


##########
spark/v3.3/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkTruncateFunction.java:
##########
@@ -0,0 +1,377 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.sql;
+
+import java.math.BigDecimal;
+import java.nio.charset.StandardCharsets;
+import org.apache.iceberg.AssertHelpers;
+import org.apache.iceberg.relocated.com.google.common.io.BaseEncoding;
+import org.apache.iceberg.spark.SparkTestBaseWithCatalog;
+import org.apache.spark.sql.AnalysisException;
+import org.assertj.core.api.Assertions;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestSparkTruncateFunction extends SparkTestBaseWithCatalog {
+  public TestSparkTruncateFunction() {}
+
+  @Before
+  public void useCatalog() {
+    sql("USE %s", catalogName);
+  }
+
+  @Test
+  public void testTruncateTinyInt() {
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 0Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 1Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 5Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 9Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 10Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 11Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -1Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -5Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -10Y)"));
+    Assert.assertEquals((byte) -20, scalarSql("SELECT system.truncate(10, -11Y)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((byte) -2, scalarSql("SELECT system.truncate(2, -1Y)"));
+
+    // Check that tinyint types are allowed for the width
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(5Y, 1Y)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS tinyint))"));
+  }
+
+  @Test
+  public void testTruncateSmallInt() {
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 0S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 1S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 5S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 9S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 10S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 11S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -1S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -5S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -10S)"));
+    Assert.assertEquals((short) -20, scalarSql("SELECT system.truncate(10, -11S)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((short) -2, scalarSql("SELECT system.truncate(2, -1S)"));
+
+    // Check that short types are allowed for the width
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(5S, 1S)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS smallint))"));
+  }
+
+  @Test
+  public void testTruncateInt() {
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 0));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 1));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 5));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 9));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, %d)", 10));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, %d)", 11));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -1));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -5));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -10));
+    Assert.assertEquals(-20, scalarSql("SELECT system.truncate(10, %d)", -11));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2, scalarSql("SELECT system.truncate(2, %d)", -1));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(300, %d)", 1));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS int))"));

Review Comment:
   Does this call `produceResult` or `invoke`?



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r939160247


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.

Review Comment:
   I like that as well.
   
   Updated to that phrasing, while keeping the example SELECT statement code. I can remove that as well, though I think it provides benefit.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r938331002


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,
+          DataTypes.StringType,
+          DataTypes.BinaryType);
+
+  private static void validateTruncationFieldType(DataType dt) {
+    if (truncateableAtomicTypes.stream().noneMatch(type -> type.sameType(dt))
+        && !(dt instanceof DecimalType)) {
+      String expectedTypes =
+          "[ByteType, ShortType, IntegerType, LongType, StringType, BinaryType, DecimalType]";
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of %s, but found %s",
+              expectedTypes, dt));
+    }
+  }
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type. Expected 2 fields but found %s", inputType.fields().length));
+    }
+
+    StructField widthField = inputType.apply(0);
+    StructField toTruncateField = inputType.apply(1);
+
+    validateTruncationFieldType(toTruncateField.dataType());
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType
+        || toTruncateDataType instanceof VarcharType
+        || toTruncateDataType instanceof CharType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException("Cannot truncate type: " + toTruncateDataType);
+    }
+  }
+
+  @Override
+  public String description() {
+    return "Truncate - The Iceberg truncate function used for truncate partition transformations.\n"
+        + "\tCalled with the truncation width as the first argument: e.g. system.truncate(width, col)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Byte toTruncate = !input.isNullAt(1) ? input.getByte(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Short toTruncate = !input.isNullAt(1) ? input.getShort(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateInt extends TruncateBase<Integer> {
+    // magic method used in codegen
+    public static int invoke(int width, int value) {
+      return TruncateUtil.truncateInt(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.IntegerType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.IntegerType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](int)";
+    }
+
+    @Override
+    public Integer produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Integer toTruncate = !input.isNullAt(1) ? input.getInt(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateBigInt extends TruncateBase<Long> {
+    // magic function for usage with codegen
+    public static long invoke(int width, long value) {
+      return TruncateUtil.truncateLong(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.LongType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.LongType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](bigint)";
+    }
+
+    @Override
+    public Long produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Long toTruncate = !input.isNullAt(1) ? input.getLong(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateString extends TruncateBase<UTF8String> {
+    // magic function for usage with codegen
+    // TODO - This can likely be made more efficient, but using existing definition for now.

Review Comment:
   How would you make this more efficient?



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r938328146


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,
+          DataTypes.StringType,
+          DataTypes.BinaryType);
+
+  private static void validateTruncationFieldType(DataType dt) {
+    if (truncateableAtomicTypes.stream().noneMatch(type -> type.sameType(dt))
+        && !(dt instanceof DecimalType)) {
+      String expectedTypes =
+          "[ByteType, ShortType, IntegerType, LongType, StringType, BinaryType, DecimalType]";
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of %s, but found %s",
+              expectedTypes, dt));
+    }
+  }
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type. Expected 2 fields but found %s", inputType.fields().length));
+    }
+
+    StructField widthField = inputType.apply(0);
+    StructField toTruncateField = inputType.apply(1);
+
+    validateTruncationFieldType(toTruncateField.dataType());
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType
+        || toTruncateDataType instanceof VarcharType
+        || toTruncateDataType instanceof CharType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException("Cannot truncate type: " + toTruncateDataType);
+    }
+  }
+
+  @Override
+  public String description() {
+    return "Truncate - The Iceberg truncate function used for truncate partition transformations.\n"
+        + "\tCalled with the truncation width as the first argument: e.g. system.truncate(width, col)";

Review Comment:
   I thought this previously used `name()`? I think it should use `name()` to ensure the name is consistent. I would also make this more like docs, where the call is documented:
   
   ```
   truncate(width, col) - Call Iceberg's truncate transform
     width :: width for truncation, e.g. truncate(10, 255) -> 250 (must be an integer)
     col :: column to truncate (must be an integer, decimal, string, or 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: issues-unsubscribe@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r938301218


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the

Review Comment:
   I think I already pointed out that "for use in SQL" isn't quite accurate and is not helping the reader understand. Can you remove 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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r938303104


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,
+          DataTypes.StringType,
+          DataTypes.BinaryType);
+
+  private static void validateTruncationFieldType(DataType dt) {
+    if (truncateableAtomicTypes.stream().noneMatch(type -> type.sameType(dt))
+        && !(dt instanceof DecimalType)) {
+      String expectedTypes =
+          "[ByteType, ShortType, IntegerType, LongType, StringType, BinaryType, DecimalType]";

Review Comment:
   We generally avoid local variables to hold static strings, especially when the string is going to be passed to `format`.
   
   Can you embed this in the format string 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: issues-unsubscribe@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r941791980


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,
+          DataTypes.StringType,
+          DataTypes.BinaryType);
+
+  private static void validateTruncationFieldType(DataType dt) {
+    if (truncateableAtomicTypes.stream().noneMatch(type -> type.sameType(dt))
+        && !(dt instanceof DecimalType)) {
+      String expectedTypes =
+          "[ByteType, ShortType, IntegerType, LongType, StringType, BinaryType, DecimalType]";
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of %s, but found %s",
+              expectedTypes, dt));
+    }
+  }
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type. Expected 2 fields but found %s", inputType.fields().length));
+    }
+
+    StructField widthField = inputType.apply(0);
+    StructField toTruncateField = inputType.apply(1);
+
+    validateTruncationFieldType(toTruncateField.dataType());
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType
+        || toTruncateDataType instanceof VarcharType
+        || toTruncateDataType instanceof CharType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException("Cannot truncate type: " + toTruncateDataType);
+    }
+  }
+
+  @Override
+  public String description() {
+    return "Truncate - The Iceberg truncate function used for truncate partition transformations.\n"
+        + "\tCalled with the truncation width as the first argument: e.g. system.truncate(width, col)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Byte toTruncate = !input.isNullAt(1) ? input.getByte(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Short toTruncate = !input.isNullAt(1) ? input.getShort(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateInt extends TruncateBase<Integer> {
+    // magic method used in codegen
+    public static int invoke(int width, int value) {
+      return TruncateUtil.truncateInt(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.IntegerType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.IntegerType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](int)";
+    }
+
+    @Override
+    public Integer produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Integer toTruncate = !input.isNullAt(1) ? input.getInt(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateBigInt extends TruncateBase<Long> {
+    // magic function for usage with codegen
+    public static long invoke(int width, long value) {
+      return TruncateUtil.truncateLong(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.LongType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.LongType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](bigint)";
+    }
+
+    @Override
+    public Long produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Long toTruncate = !input.isNullAt(1) ? input.getLong(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateString extends TruncateBase<UTF8String> {
+    // magic function for usage with codegen
+    // TODO - This can likely be made more efficient, but using existing definition for now.

Review Comment:
   Tried it with `substring` and it passes all of the tests, including utf-8 unicode character aware truncation tests.
   
   Updated to use that method and reverting the other previous changes.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r941801380


##########
core/src/test/java/org/apache/iceberg/util/TestTruncateUtil.java:
##########
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.util;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.assertj.core.api.Assertions;
+import org.junit.Assert;
+import org.junit.jupiter.api.Test;
+
+class TestTruncateUtil {
+  @Test
+  public void testTruncateByteBuffer() throws Exception {
+    Assert.assertEquals(
+        "Should truncate binary longer than length",
+        ByteBuffer.wrap("abcd".getBytes("UTF-8")),
+        TruncateUtil.truncateByteBuffer(4, ByteBuffer.wrap("abcdefg".getBytes("UTF-8"))));
+    Assert.assertEquals(
+        "Should not pad binary shorter than length",
+        ByteBuffer.wrap("abc".getBytes("UTF-8")),
+        TruncateUtil.truncateByteBuffer(4, ByteBuffer.wrap("abc".getBytes("UTF-8"))));
+  }
+
+  @Test
+  public void testTruncateByte() {

Review Comment:
   Removed all of these and left just the test that shows it may or may not throw an exception for invalid input.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r941743483


##########
spark/v3.3/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkTruncateFunction.java:
##########
@@ -0,0 +1,377 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.sql;
+
+import java.math.BigDecimal;
+import java.nio.charset.StandardCharsets;
+import org.apache.iceberg.AssertHelpers;
+import org.apache.iceberg.relocated.com.google.common.io.BaseEncoding;
+import org.apache.iceberg.spark.SparkTestBaseWithCatalog;
+import org.apache.spark.sql.AnalysisException;
+import org.assertj.core.api.Assertions;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestSparkTruncateFunction extends SparkTestBaseWithCatalog {
+  public TestSparkTruncateFunction() {}
+
+  @Before
+  public void useCatalog() {
+    sql("USE %s", catalogName);
+  }
+
+  @Test
+  public void testTruncateTinyInt() {
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 0Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 1Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 5Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 9Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 10Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 11Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -1Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -5Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -10Y)"));
+    Assert.assertEquals((byte) -20, scalarSql("SELECT system.truncate(10, -11Y)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((byte) -2, scalarSql("SELECT system.truncate(2, -1Y)"));
+
+    // Check that tinyint types are allowed for the width
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(5Y, 1Y)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS tinyint))"));
+  }
+
+  @Test
+  public void testTruncateSmallInt() {
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 0S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 1S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 5S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 9S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 10S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 11S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -1S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -5S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -10S)"));
+    Assert.assertEquals((short) -20, scalarSql("SELECT system.truncate(10, -11S)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((short) -2, scalarSql("SELECT system.truncate(2, -1S)"));
+
+    // Check that short types are allowed for the width
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(5S, 1S)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS smallint))"));
+  }
+
+  @Test
+  public void testTruncateInt() {
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 0));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 1));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 5));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 9));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, %d)", 10));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, %d)", 11));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -1));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -5));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, %d)", -10));
+    Assert.assertEquals(-20, scalarSql("SELECT system.truncate(10, %d)", -11));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2, scalarSql("SELECT system.truncate(2, %d)", -1));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(300, %d)", 1));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS int))"));
+  }
+
+  @Test
+  public void testTruncateBigInt() {
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 0L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 1L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 5L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 9L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 10L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 11L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -1L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -5L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -10L)"));
+    Assert.assertEquals(-20L, scalarSql("SELECT system.truncate(10, -11L)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2L, scalarSql("SELECT system.truncate(2, -1L)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS bigint))"));
+  }
+
+  @Test
+  public void testTruncateDecimal() {
+    // decimal truncation works by applying the decimal scale to the width: ie 10 scale 2 = 0.10
+    Assert.assertEquals(
+        new BigDecimal("12.30"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 2)))", 12.34));
+
+    Assert.assertEquals(
+        new BigDecimal("12.30"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 2)))", 12.30));
+
+    Assert.assertEquals(
+        new BigDecimal("12.290"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 3)))", 12.299));
+
+    Assert.assertEquals(
+        new BigDecimal("0.03"),
+        scalarSql("SELECT system.truncate(3, CAST(%f as DECIMAL(5, 2)))", 0.05));
+
+    Assert.assertEquals(
+        new BigDecimal("0.00"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 2)))", 0.05));
+
+    Assert.assertEquals(
+        new BigDecimal("-0.10"),
+        scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(9, 2)))", -0.05));
+
+    Assert.assertEquals(
+        "Implicit decimal scale and precision should be allowed",
+        new BigDecimal("12345.3480"),
+        scalarSql("SELECT system.truncate(10, 12345.3482)"));
+
+    int scale = 4;
+    BigDecimal truncatedDecimal =
+        (BigDecimal) scalarSql("SELECT system.truncate(10, CAST(%f as DECIMAL(6, 4)))", -0.05);
+    Assert.assertEquals(
+        "Truncating a decimal should return a decimal with the same scale",
+        scale,
+        truncatedDecimal.scale());
+
+    Assert.assertEquals(
+        "Truncating a decimal should return a decimal with the correct scale",
+        BigDecimal.valueOf(-500, 4),
+        truncatedDecimal);
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS decimal))"));
+  }
+
+  @Test
+  public void testInvalidTypesCannotBeUsedForWidth() {
+    AssertHelpers.assertThrows(
+        "Decimal type should not be coercible to the width field",
+        AnalysisException.class,
+        "Expected truncation width to be one of [ByteType, ShortType, IntegerType]",
+        () -> scalarSql("SELECT system.truncate(CAST(12.34 as DECIMAL(9, 2)), 10)", 12.34));
+
+    AssertHelpers.assertThrows(
+        "String type should not be coercible to the width field",
+        AnalysisException.class,
+        "Expected truncation width to be one of [ByteType, ShortType, IntegerType]",
+        () -> scalarSql("SELECT system.truncate('5', 10)"));
+
+    AssertHelpers.assertThrows(
+        "Interval year to month  type should not be coercible to the width field",
+        AnalysisException.class,
+        "Expected truncation width to be one of [ByteType, ShortType, IntegerType]",
+        () -> scalarSql("SELECT system.truncate(INTERVAL '100-00' YEAR TO MONTH, 10)"));
+
+    AssertHelpers.assertThrows(
+        "Interval day-time type should not be coercible to the width field",
+        AnalysisException.class,
+        "Expected truncation width to be one of [ByteType, ShortType, IntegerType]",
+        () -> scalarSql("SELECT system.truncate(CAST('11 23:4:0' AS INTERVAL DAY TO SECOND), 10)"));
+  }
+
+  @Test
+  public void testTruncateString() {
+    Assert.assertEquals(
+        "Should system.truncate strings longer than length",
+        "abcde",
+        scalarSql("SELECT system.truncate(5, 'abcdefg')"));
+    Assert.assertEquals(
+        "Should not pad strings shorter than length",
+        "abc",
+        scalarSql("SELECT system.truncate(5, 'abc')"));
+    Assert.assertEquals(
+        "Should not alter strings equal to length",
+        "abcde",
+        scalarSql("SELECT system.truncate(5, 'abcde')"));
+    Assert.assertEquals(
+        "Should handle three-byte UTF-8 characters appropriately",
+        "测",
+        scalarSql("SELECT system.truncate(1, '测试')"));
+    Assert.assertEquals(
+        "Should handle three-byte UTF-8 characters mixed with two byte utf-8 characters",
+        "测试ra",
+        scalarSql("SELECT system.truncate(4, '测试raul试测')"));
+
+    Assert.assertEquals(
+        "Null input should return null as output",
+        null,
+        scalarSql("SELECT system.truncate(3, CAST(null AS string))"));
+
+    Assert.assertEquals(
+        "Varchar should work like string",
+        "测试ra",
+        scalarSql("SELECT system.truncate(4, CAST('测试raul试测' AS varchar(8)))"));
+
+    Assert.assertEquals(
+        "Char should work like string",
+        "测试ra",
+        scalarSql("SELECT system.truncate(4, CAST('测试raul试测' AS char(8)))"));
+  }
+
+  @Test
+  public void testTruncateBinary() {
+    Assert.assertArrayEquals(
+        new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
+        (byte[]) scalarSql("SELECT system.truncate(10, X'0102030405060708090a0b0c0d0e0f')"));
+    Assert.assertArrayEquals(
+        "Should return the same input when value is equal to truncation width",
+        "abc".getBytes(StandardCharsets.UTF_8),
+        (byte[]) scalarSql("SELECT system.truncate(3, %s)", asBytesLiteral("abcdefg")));
+    Assert.assertArrayEquals(
+        "Should not truncate, pad, or trim the input when its length is less than the width",
+        "abc\0\0".getBytes(StandardCharsets.UTF_8),
+        (byte[]) scalarSql("SELECT system.truncate(10, %s)", asBytesLiteral("abc\0\0")));
+    Assert.assertArrayEquals(
+        "Should not pad the input when its length is equal to the width",
+        "abc".getBytes(StandardCharsets.UTF_8),
+        (byte[]) scalarSql("SELECT system.truncate(3, %s)", asBytesLiteral("abc")));
+    Assert.assertArrayEquals(
+        "Should handle three-byte UTF-8 characters appropriately",
+        "测试".getBytes(StandardCharsets.UTF_8),
+        (byte[]) scalarSql("SELECT system.truncate(6, %s)", asBytesLiteral("测试_")));
+
+    Assert.assertEquals(
+        "Null input should return null as output",
+        null,
+        scalarSql("SELECT system.truncate(3, CAST(null AS binary))"));
+  }
+
+  @Test
+  public void testTruncateUsingDataframeForWidthWithVaryingWidth() {
+    // This situation is atypical but allowed. Typically, width is static as data is partitioned on
+    // one width.
+    long rumRows = 10L;
+    long numNonZero =
+        spark
+            .range(rumRows)
+            .toDF("value")
+            .selectExpr("CAST(value +1 AS INT) AS width", "value")
+            .selectExpr("system.truncate(width, value) as truncated_value")
+            .filter("truncated_value == 0")
+            .count();
+    Assert.assertEquals(
+        "A truncate function with variable widths should be usable on dataframe columns",
+        rumRows,
+        numNonZero);
+  }
+
+  @Test
+  public void testThatMagicFunctionsAreInvoked() {
+    // Magic functions have `staticinvoke` in the explain output.
+    // Non-magic calls have `applyfunctionexpression` instead.
+
+    // TinyInt
+    Assertions.assertThat(scalarSql("EXPLAIN EXTENDED select system.truncate(5, 6Y)"))
+        .asString()
+        .isNotNull()
+        .contains(
+            "staticinvoke(class org.apache.iceberg.spark.functions.TruncateFunction$TruncateTinyInt");
+
+    // SmallInt
+    Assertions.assertThat(scalarSql("EXPLAIN EXTENDED select system.truncate(5, 6S)"))
+        .asString()
+        .isNotNull()
+        .contains(
+            "staticinvoke(class org.apache.iceberg.spark.functions.TruncateFunction$TruncateSmallInt");
+
+    // Int
+    Assertions.assertThat(scalarSql("EXPLAIN EXTENDED select system.truncate(5, 6)"))
+        .asString()
+        .isNotNull()
+        .contains(
+            "staticinvoke(class org.apache.iceberg.spark.functions.TruncateFunction$TruncateInt");
+
+    // Long
+    Assertions.assertThat(scalarSql("EXPLAIN EXTENDED SELECT system.truncate(5, 6L)"))
+        .asString()
+        .isNotNull()
+        .contains(
+            "staticinvoke(class org.apache.iceberg.spark.functions.TruncateFunction$TruncateBigInt");
+
+    // String
+    Assertions.assertThat(scalarSql("EXPLAIN EXTENDED SELECT system.truncate(5, 'abcdefg')"))
+        .asString()
+        .isNotNull()
+        .contains(
+            "staticinvoke(class org.apache.iceberg.spark.functions.TruncateFunction$TruncateString");
+
+    // Decimal
+    Assertions.assertThat(scalarSql("EXPLAIN EXTENDED SELECT system.truncate(5, 12.34)"))
+        .asString()
+        .isNotNull()
+        .contains(
+            "staticinvoke(class org.apache.iceberg.spark.functions.TruncateFunction$TruncateDecimal");
+
+    // Binary
+    Assertions.assertThat(
+            scalarSql("EXPLAIN EXTENDED SELECT system.truncate(4, X'0102030405060708')"))
+        .asString()
+        .isNotNull()
+        .contains(
+            "staticinvoke(class org.apache.iceberg.spark.functions.TruncateFunction$TruncateBinary");
+  }
+
+  @Test
+  public void testMagicFunctionsResolveForTinyIntAndSmallIntWidths() {

Review Comment:
   Done. Moved all of the `width` related tests to be in one block towards the end -- or more specifically after the test suites for each individual type to be truncated.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r940638612


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,

Review Comment:
   We might need to normalize the Varchar / Char types, but otherwise I'll get rid of the function and just leave what is 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: issues-unsubscribe@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r943741645


##########
spark/v3.3/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkTruncateFunction.java:
##########
@@ -0,0 +1,436 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.sql;
+
+import java.math.BigDecimal;
+import java.nio.charset.StandardCharsets;
+import org.apache.iceberg.AssertHelpers;
+import org.apache.iceberg.relocated.com.google.common.io.BaseEncoding;
+import org.apache.iceberg.spark.SparkTestBaseWithCatalog;
+import org.apache.spark.sql.AnalysisException;
+import org.assertj.core.api.Assertions;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestSparkTruncateFunction extends SparkTestBaseWithCatalog {
+  public TestSparkTruncateFunction() {}
+
+  @Before
+  public void useCatalog() {
+    sql("USE %s", catalogName);
+  }
+
+  @Test
+  public void testTruncateTinyInt() {
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 0Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 1Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 5Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 9Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 10Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 11Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -1Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -5Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -10Y)"));
+    Assert.assertEquals((byte) -20, scalarSql("SELECT system.truncate(10, -11Y)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((byte) -2, scalarSql("SELECT system.truncate(2, -1Y)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS tinyint))"));
+  }
+
+  @Test
+  public void testTruncateSmallInt() {
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 0S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 1S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 5S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 9S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 10S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 11S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -1S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -5S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -10S)"));
+    Assert.assertEquals((short) -20, scalarSql("SELECT system.truncate(10, -11S)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((short) -2, scalarSql("SELECT system.truncate(2, -1S)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS smallint))"));
+  }
+
+  @Test
+  public void testTruncateInt() {
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, 0)"));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, 1)"));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, 5)"));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, 9)"));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, 10)"));
+    Assert.assertEquals(10, scalarSql("SELECT system.truncate(10, 11)"));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, -1)"));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, -5)"));
+    Assert.assertEquals(-10, scalarSql("SELECT system.truncate(10, -10)"));
+    Assert.assertEquals(-20, scalarSql("SELECT system.truncate(10, -11)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2, scalarSql("SELECT system.truncate(2, -1)"));
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(300, 1)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS int))"));
+  }
+
+  @Test
+  public void testTruncateBigInt() {
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 0L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 1L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 5L)"));
+    Assert.assertEquals(0L, scalarSql("SELECT system.truncate(10, 9L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 10L)"));
+    Assert.assertEquals(10L, scalarSql("SELECT system.truncate(10, 11L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -1L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -5L)"));
+    Assert.assertEquals(-10L, scalarSql("SELECT system.truncate(10, -10L)"));
+    Assert.assertEquals(-20L, scalarSql("SELECT system.truncate(10, -11L)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals(-2L, scalarSql("SELECT system.truncate(2, -1L)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS bigint))"));
+  }
+
+  @Test
+  public void testTruncateDecimal() {
+    // decimal truncation works by applying the decimal scale to the width: ie 10 scale 2 = 0.10
+    Assert.assertEquals(
+        new BigDecimal("12.30"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 2)))", "12.34"));
+
+    Assert.assertEquals(
+        new BigDecimal("12.30"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 2)))", "12.30"));
+
+    Assert.assertEquals(
+        new BigDecimal("12.290"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 3)))", "12.299"));
+
+    Assert.assertEquals(
+        new BigDecimal("0.03"),
+        scalarSql("SELECT system.truncate(3, CAST(%s as DECIMAL(5, 2)))", "0.05"));
+
+    Assert.assertEquals(
+        new BigDecimal("0.00"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 2)))", "0.05"));
+
+    Assert.assertEquals(
+        new BigDecimal("-0.10"),
+        scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(9, 2)))", "-0.05"));
+
+    Assert.assertEquals(
+        "Implicit decimal scale and precision should be allowed",
+        new BigDecimal("12345.3480"),
+        scalarSql("SELECT system.truncate(10, 12345.3482)"));
+
+    BigDecimal truncatedDecimal =
+        (BigDecimal) scalarSql("SELECT system.truncate(10, CAST(%s as DECIMAL(6, 4)))", "-0.05");
+    Assert.assertEquals(
+        "Truncating a decimal should return a decimal with the same scale",
+        4,
+        truncatedDecimal.scale());
+
+    Assert.assertEquals(
+        "Truncating a decimal should return a decimal with the correct scale",
+        BigDecimal.valueOf(-500, 4),
+        truncatedDecimal);
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS decimal))"));
+  }
+
+  @Test
+  public void testTruncateString() {
+    Assert.assertEquals(
+        "Should system.truncate strings longer than length",
+        "abcde",
+        scalarSql("SELECT system.truncate(5, 'abcdefg')"));
+
+    Assert.assertEquals(
+        "Should not pad strings shorter than length",
+        "abc",
+        scalarSql("SELECT system.truncate(5, 'abc')"));
+
+    Assert.assertEquals(
+        "Should not alter strings equal to length",
+        "abcde",
+        scalarSql("SELECT system.truncate(5, 'abcde')"));
+
+    Assert.assertEquals(
+        "Should handle three-byte UTF-8 characters appropriately",
+        "测",
+        scalarSql("SELECT system.truncate(1, '测试')"));
+
+    Assert.assertEquals(
+        "Should handle three-byte UTF-8 characters mixed with two byte utf-8 characters",
+        "测试ra",
+        scalarSql("SELECT system.truncate(4, '测试raul试测')"));

Review Comment:
   I agree with that.
   
   But I took a look and I actually couldn't find any test cases for `UnicodeUtil.truncateString` directly.
   
   I looked up the tests for `TestTruncate`, but `TestTruncate#testTruncateString` has _very few_ tests - all of which are covered here.
   
   https://github.com/apache/iceberg/blob/5a15efc070ab59eeda6343998aa065c0c9892c5c/api/src/test/java/org/apache/iceberg/transforms/TestTruncate.java#L70-L77
   
   



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r943908773


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be tinyint, shortint or int");
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          "Expected truncation col to be tinyint, shortint, int, bigint, decimal, string, or binary");
+    }
+  }
+
+  @Override
+  public String description() {
+    return name()
+        + "(width, col) - Call Iceberg's truncate transform\n"
+        + "  width :: width for truncation, e.g. truncate(10, 255) -> 250 (must be an integer)\n"
+        + "  col :: column to truncate (must be an integer, decimal, string, or binary)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      return input.isNullAt(0) || input.isNullAt(1)
+          ? null
+          : invoke(input.getInt(0), input.getByte(1));
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      return input.isNullAt(0) || input.isNullAt(1)

Review Comment:
   I was able to get failure when the width field is explicitly non-null. I added two tests for it as well.
   
   But Spark isn't great at tracking null vs not null.
   
   So I'm ok either way. It's also arguably a bit harder on the user if they're going to pull `width` from a column, as Spark tends to make things nullable pretty often. So I'm good either way. I can revert the changes I made.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] aokolnychyi commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
aokolnychyi commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r943727680


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be tinyint, shortint or int");
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          "Expected truncation col to be tinyint, shortint, int, bigint, decimal, string, or binary");
+    }
+  }
+
+  @Override
+  public String description() {
+    return name()
+        + "(width, col) - Call Iceberg's truncate transform\n"
+        + "  width :: width for truncation, e.g. truncate(10, 255) -> 250 (must be an integer)\n"
+        + "  col :: column to truncate (must be an integer, decimal, string, or binary)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      return input.isNullAt(0) || input.isNullAt(1)
+          ? null
+          : invoke(input.getInt(0), input.getByte(1));
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      return input.isNullAt(0) || input.isNullAt(1)

Review Comment:
   I know but I think this will be a constant, right? I am talking about width only. My point is that we don't normally allow nullable width in regular truncate transforms so diverging from that seems a bit odd.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r942846252


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,348 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of [ByteType, ShortType, IntegerType, LongType, "
+                  + "DecimalType, StringType, BinaryType], but found %s",
+              toTruncateDataType));
+    }
+  }
+
+  @Override
+  public String description() {
+    return name()
+        + "(width, col) - Call Iceberg's truncate transform\n"
+        + "  width :: width for truncation, e.g. truncate(10, 255) -> 250 (must be an integer)\n"
+        + "  col :: column to truncate (must be an integer, decimal, string, or binary)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getByte(1));
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getShort(1));
+    }
+  }
+
+  public static class TruncateInt extends TruncateBase<Integer> {
+    // magic method used in codegen
+    public static int invoke(int width, int value) {
+      return TruncateUtil.truncateInt(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.IntegerType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.IntegerType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(int)";
+    }
+
+    @Override
+    public Integer produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getInt(1));
+    }
+  }
+
+  public static class TruncateBigInt extends TruncateBase<Long> {
+    // magic function for usage with codegen
+    public static long invoke(int width, long value) {
+      return TruncateUtil.truncateLong(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.LongType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.LongType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(bigint)";
+    }
+
+    @Override
+    public Long produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getLong(1));
+    }
+  }
+
+  public static class TruncateString extends TruncateBase<UTF8String> {
+    // magic function for usage with codegen
+    public static UTF8String invoke(int width, UTF8String value) {
+      if (value == null) {
+        return null;
+      }
+
+      return value.substring(0, width);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.StringType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.StringType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(string)";
+    }
+
+    @Override
+    public UTF8String produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getUTF8String(1));
+    }
+  }
+
+  public static class TruncateBinary extends TruncateBase<byte[]> {
+    // magic method used in codegen
+    public static byte[] invoke(int width, byte[] value) {
+      if (value == null) {
+        return null;
+      }
+
+      return ByteBuffers.toByteArray(
+          BinaryUtil.truncateBinaryUnsafe(width, ByteBuffer.wrap(value)));
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.BinaryType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.BinaryType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(binary)";
+    }
+
+    @Override
+    public byte[] produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getBinary(1));
+    }
+  }
+
+  public static class TruncateDecimal extends TruncateBase<Decimal> {
+    private final int precision;
+    private final int scale;
+
+    public TruncateDecimal(int precision, int scale) {
+      this.precision = precision;
+      this.scale = scale;
+    }
+
+    // magic method used in codegen
+    public static Decimal invoke(int width, Decimal value) {
+      if (value == null) {
+        return null;
+      }
+
+      return Decimal.apply(
+          TruncateUtil.truncateDecimal(BigInteger.valueOf(width), value.toJavaBigDecimal()));
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.createDecimalType(precision, scale)};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.createDecimalType(precision, scale);
+    }
+
+    @Override
+    public String canonicalName() {
+      return String.format("iceberg.truncate(decimal(%d,%d))", precision, scale);
+    }
+
+    @Override
+    public Decimal produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getDecimal(1, precision, scale));
+    }
+  }
+
+  // Not identical behavior to magic methods used in codegen,
+  // This function throws on a `null` width, to avoid boxing.
+  // The magic method in Spark's codegen will return `null` for a `null` width.

Review Comment:
   What's the value of different behavior? We could also return `null` rather than throwing an exception. That seems more reasonable to me. Otherwise, you get different behavior depending on how Spark decided to call this function.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#issuecomment-1213389791

   > Thanks, @kbendick! Could you cherry-pick this to 3.2?
   
   Sure thing!


-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#issuecomment-1209899727

   cc @rdblue PTAL when you have time. I've addressed all of your feedback. 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: issues-unsubscribe@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#issuecomment-1213389715

   Here's the PR for bucket. All the feedback from this PR was more or less applied there as well - https://github.com/apache/iceberg/pull/5513


-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r941785151


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,
+          DataTypes.StringType,
+          DataTypes.BinaryType);
+
+  private static void validateTruncationFieldType(DataType dt) {
+    if (truncateableAtomicTypes.stream().noneMatch(type -> type.sameType(dt))
+        && !(dt instanceof DecimalType)) {
+      String expectedTypes =
+          "[ByteType, ShortType, IntegerType, LongType, StringType, BinaryType, DecimalType]";
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of %s, but found %s",
+              expectedTypes, dt));
+    }
+  }
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type. Expected 2 fields but found %s", inputType.fields().length));
+    }
+
+    StructField widthField = inputType.apply(0);
+    StructField toTruncateField = inputType.apply(1);
+
+    validateTruncationFieldType(toTruncateField.dataType());
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType
+        || toTruncateDataType instanceof VarcharType
+        || toTruncateDataType instanceof CharType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException("Cannot truncate type: " + toTruncateDataType);
+    }
+  }
+
+  @Override
+  public String description() {
+    return "Truncate - The Iceberg truncate function used for truncate partition transformations.\n"
+        + "\tCalled with the truncation width as the first argument: e.g. system.truncate(width, col)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Byte toTruncate = !input.isNullAt(1) ? input.getByte(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Short toTruncate = !input.isNullAt(1) ? input.getShort(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateInt extends TruncateBase<Integer> {
+    // magic method used in codegen
+    public static int invoke(int width, int value) {
+      return TruncateUtil.truncateInt(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.IntegerType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.IntegerType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](int)";
+    }
+
+    @Override
+    public Integer produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Integer toTruncate = !input.isNullAt(1) ? input.getInt(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateBigInt extends TruncateBase<Long> {
+    // magic function for usage with codegen
+    public static long invoke(int width, long value) {
+      return TruncateUtil.truncateLong(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.LongType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.LongType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](bigint)";
+    }
+
+    @Override
+    public Long produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Long toTruncate = !input.isNullAt(1) ? input.getLong(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;
+    }
+  }
+
+  public static class TruncateString extends TruncateBase<UTF8String> {
+    // magic function for usage with codegen
+    // TODO - This can likely be made more efficient, but using existing definition for now.

Review Comment:
   I think we could use the built-in `substring` method or `substringSQL`, which both seem to take into account the logic of `numChars()` method.
   
   `substring`  specifically mentions that it works by code-point: https://github.com/apache/spark/blob/d77bc7027675b9823bcee96589eb0dddee3cfaa0/common/unsafe/src/main/java/org/apache/spark/unsafe/types/UTF8String.java#L264-L294



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r942850531


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,348 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of [ByteType, ShortType, IntegerType, LongType, "
+                  + "DecimalType, StringType, BinaryType], but found %s",
+              toTruncateDataType));
+    }
+  }
+
+  @Override
+  public String description() {
+    return name()
+        + "(width, col) - Call Iceberg's truncate transform\n"
+        + "  width :: width for truncation, e.g. truncate(10, 255) -> 250 (must be an integer)\n"
+        + "  col :: column to truncate (must be an integer, decimal, string, or binary)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getByte(1));
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getShort(1));
+    }
+  }
+
+  public static class TruncateInt extends TruncateBase<Integer> {
+    // magic method used in codegen
+    public static int invoke(int width, int value) {
+      return TruncateUtil.truncateInt(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.IntegerType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.IntegerType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(int)";
+    }
+
+    @Override
+    public Integer produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getInt(1));
+    }
+  }
+
+  public static class TruncateBigInt extends TruncateBase<Long> {
+    // magic function for usage with codegen
+    public static long invoke(int width, long value) {
+      return TruncateUtil.truncateLong(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.LongType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.LongType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(bigint)";
+    }
+
+    @Override
+    public Long produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getLong(1));
+    }
+  }
+
+  public static class TruncateString extends TruncateBase<UTF8String> {
+    // magic function for usage with codegen
+    public static UTF8String invoke(int width, UTF8String value) {
+      if (value == null) {
+        return null;
+      }
+
+      return value.substring(0, width);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.StringType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.StringType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(string)";
+    }
+
+    @Override
+    public UTF8String produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getUTF8String(1));
+    }
+  }
+
+  public static class TruncateBinary extends TruncateBase<byte[]> {
+    // magic method used in codegen
+    public static byte[] invoke(int width, byte[] value) {
+      if (value == null) {
+        return null;
+      }
+
+      return ByteBuffers.toByteArray(
+          BinaryUtil.truncateBinaryUnsafe(width, ByteBuffer.wrap(value)));
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.BinaryType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.BinaryType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(binary)";
+    }
+
+    @Override
+    public byte[] produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getBinary(1));

Review Comment:
   Actually, I made this comment in the wrong place. That should be for the primitive `invoke` functions. Here, we can pass `input.getBinary(1)` through to `invoke` without checking it because invoke checks for null.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r942849226


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,348 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of [ByteType, ShortType, IntegerType, LongType, "
+                  + "DecimalType, StringType, BinaryType], but found %s",

Review Comment:
   These names are internal Spark names for types. I think we should use the SQL names instead:
   
   ```
   Invalid input types: truncate(width=%s, col=%s), expected col to be tinyint, shortint, int, bigint, decimal, string, or 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: issues-unsubscribe@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r943831081


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)

Review Comment:
   Good call. I had a similar setup before for the truncation type, but it required that I have `DecimalType` so the pattern became less helpful.
   
   This works well though! 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: issues-unsubscribe@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] aokolnychyi commented on pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
aokolnychyi commented on PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#issuecomment-1213225387

   @rdblue, let me take a quick 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: issues-unsubscribe@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] aokolnychyi commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
aokolnychyi commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r943727680


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be tinyint, shortint or int");
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          "Expected truncation col to be tinyint, shortint, int, bigint, decimal, string, or binary");
+    }
+  }
+
+  @Override
+  public String description() {
+    return name()
+        + "(width, col) - Call Iceberg's truncate transform\n"
+        + "  width :: width for truncation, e.g. truncate(10, 255) -> 250 (must be an integer)\n"
+        + "  col :: column to truncate (must be an integer, decimal, string, or binary)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      return input.isNullAt(0) || input.isNullAt(1)
+          ? null
+          : invoke(input.getInt(0), input.getByte(1));
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      return input.isNullAt(0) || input.isNullAt(1)

Review Comment:
   I know but I think this will be a constant, right? I am talking about width only.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r942932016


##########
api/src/main/java/org/apache/iceberg/transforms/Truncate.java:
##########
@@ -252,7 +254,7 @@ public CharSequence apply(CharSequence value) {
         return null;
       }
 
-      return UnicodeUtil.truncateString(value, length);
+      return UnicodeUtil.truncateStringUnsafe(length, value);

Review Comment:
   The arguments were transposed to match the other ones from `TruncateUtil`. But I'll update it as it is somewhat odd to be transposed within `UnicodeUtil`.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r943714637


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be tinyint, shortint or int");
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          "Expected truncation col to be tinyint, shortint, int, bigint, decimal, string, or binary");
+    }
+  }
+
+  @Override
+  public String description() {
+    return name()
+        + "(width, col) - Call Iceberg's truncate transform\n"
+        + "  width :: width for truncation, e.g. truncate(10, 255) -> 250 (must be an integer)\n"
+        + "  col :: column to truncate (must be an integer, decimal, string, or binary)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      return input.isNullAt(0) || input.isNullAt(1)
+          ? null
+          : invoke(input.getInt(0), input.getByte(1));
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      return input.isNullAt(0) || input.isNullAt(1)

Review Comment:
   I think it is better if we do because Spark doesn't do a very good job of tracking whether a value is nullable. Lots of values are apparently nullable even though they aren't really.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r939406673


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,
+          DataTypes.StringType,
+          DataTypes.BinaryType);
+
+  private static void validateTruncationFieldType(DataType dt) {
+    if (truncateableAtomicTypes.stream().noneMatch(type -> type.sameType(dt))
+        && !(dt instanceof DecimalType)) {
+      String expectedTypes =
+          "[ByteType, ShortType, IntegerType, LongType, StringType, BinaryType, DecimalType]";
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of %s, but found %s",
+              expectedTypes, dt));
+    }
+  }
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type. Expected 2 fields but found %s", inputType.fields().length));
+    }
+
+    StructField widthField = inputType.apply(0);
+    StructField toTruncateField = inputType.apply(1);
+
+    validateTruncationFieldType(toTruncateField.dataType());
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType
+        || toTruncateDataType instanceof VarcharType
+        || toTruncateDataType instanceof CharType) {

Review Comment:
   Yeah, I don't think that method is necessary. Let's remove 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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r938252617


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,
+          DataTypes.StringType,
+          DataTypes.BinaryType);
+
+  private static void validateTruncationFieldType(DataType dt) {
+    if (truncateableAtomicTypes.stream().noneMatch(type -> type.sameType(dt))
+        && !(dt instanceof DecimalType)) {
+      String expectedTypes =
+          "[ByteType, ShortType, IntegerType, LongType, StringType, BinaryType, DecimalType]";
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of %s, but found %s",
+              expectedTypes, dt));
+    }
+  }
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type. Expected 2 fields but found %s", inputType.fields().length));
+    }
+
+    StructField widthField = inputType.apply(0);
+    StructField toTruncateField = inputType.apply(1);
+
+    validateTruncationFieldType(toTruncateField.dataType());
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType
+        || toTruncateDataType instanceof VarcharType
+        || toTruncateDataType instanceof CharType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException("Cannot truncate type: " + toTruncateDataType);
+    }
+  }
+
+  @Override
+  public String description() {
+    return "Truncate - The Iceberg truncate function used for truncate partition transformations.\n"
+        + "\tCalled with the truncation width as the first argument: e.g. system.truncate(width, col)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](tinyint)";

Review Comment:
   Looks like you forgot to actually embed width in the name.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r938300843


##########
core/src/test/java/org/apache/iceberg/util/TestTruncateUtil.java:
##########
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.util;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.assertj.core.api.Assertions;
+import org.junit.Assert;
+import org.junit.jupiter.api.Test;
+
+class TestTruncateUtil {
+  @Test
+  public void testTruncateByteBuffer() throws Exception {
+    Assert.assertEquals(
+        "Should truncate binary longer than length",
+        ByteBuffer.wrap("abcd".getBytes("UTF-8")),
+        TruncateUtil.truncateByteBuffer(4, ByteBuffer.wrap("abcdefg".getBytes("UTF-8"))));
+    Assert.assertEquals(
+        "Should not pad binary shorter than length",
+        ByteBuffer.wrap("abc".getBytes("UTF-8")),
+        TruncateUtil.truncateByteBuffer(4, ByteBuffer.wrap("abc".getBytes("UTF-8"))));
+  }
+
+  @Test
+  public void testTruncateByte() {

Review Comment:
   I don't find these test cases very useful. They're difficult to read because you're using `MAX_VALUE` to pass both width and value, so it isn't clear which one is which (`truncateByte(10, 244)` is much more clear).
   
   I also think there are already tests for most of these cases, so I'd probably remove these and make sure the other paths are covered.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r938331691


##########
spark/v3.3/spark/src/test/java/org/apache/iceberg/spark/sql/TestSparkTruncateFunction.java:
##########
@@ -0,0 +1,377 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.sql;
+
+import java.math.BigDecimal;
+import java.nio.charset.StandardCharsets;
+import org.apache.iceberg.AssertHelpers;
+import org.apache.iceberg.relocated.com.google.common.io.BaseEncoding;
+import org.apache.iceberg.spark.SparkTestBaseWithCatalog;
+import org.apache.spark.sql.AnalysisException;
+import org.assertj.core.api.Assertions;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestSparkTruncateFunction extends SparkTestBaseWithCatalog {
+  public TestSparkTruncateFunction() {}
+
+  @Before
+  public void useCatalog() {
+    sql("USE %s", catalogName);
+  }
+
+  @Test
+  public void testTruncateTinyInt() {
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 0Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 1Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 5Y)"));
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(10, 9Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 10Y)"));
+    Assert.assertEquals((byte) 10, scalarSql("SELECT system.truncate(10, 11Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -1Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -5Y)"));
+    Assert.assertEquals((byte) -10, scalarSql("SELECT system.truncate(10, -10Y)"));
+    Assert.assertEquals((byte) -20, scalarSql("SELECT system.truncate(10, -11Y)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((byte) -2, scalarSql("SELECT system.truncate(2, -1Y)"));
+
+    // Check that tinyint types are allowed for the width
+    Assert.assertEquals((byte) 0, scalarSql("SELECT system.truncate(5Y, 1Y)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS tinyint))"));
+  }
+
+  @Test
+  public void testTruncateSmallInt() {
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 0S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 1S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 5S)"));
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(10, 9S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 10S)"));
+    Assert.assertEquals((short) 10, scalarSql("SELECT system.truncate(10, 11S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -1S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -5S)"));
+    Assert.assertEquals((short) -10, scalarSql("SELECT system.truncate(10, -10S)"));
+    Assert.assertEquals((short) -20, scalarSql("SELECT system.truncate(10, -11S)"));
+
+    // Check that different widths can be used
+    Assert.assertEquals((short) -2, scalarSql("SELECT system.truncate(2, -1S)"));
+
+    // Check that short types are allowed for the width
+    Assert.assertEquals((short) 0, scalarSql("SELECT system.truncate(5S, 1S)"));
+
+    Assert.assertEquals(
+        "Null input should return null",
+        null,
+        scalarSql("SELECT system.truncate(2, CAST(null AS smallint))"));
+  }
+
+  @Test
+  public void testTruncateInt() {
+    Assert.assertEquals(0, scalarSql("SELECT system.truncate(10, %d)", 0));

Review Comment:
   Why are the ints put into SQL using a format string? None of the other tests do 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: issues-unsubscribe@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r940626280


##########
api/src/main/java/org/apache/iceberg/util/TruncateUtil.java:
##########
@@ -0,0 +1,80 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.util;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+
+/**
+ * Contains the logic for various {@code truncate} transformations for various types.
+ *
+ * <p>This utility class allows for the logic to be reused in different scenarios where input
+ * validation is done at different times either in org.apache.iceberg.transforms.Truncate and within
+ * defined SQL functions for different compute engines for usage in SQL.
+ *
+ * <p>In general, the inputs to the functions should have already been validated by the calling
+ * code, as different classes use truncate with different preprocessing. This generally means that
+ * the truncation width is positive and the value to truncate is non-null.
+ *
+ * <p>Thus, <b>none</b> of these utility functions validate their input. <i>It is the responsibility
+ * of the calling code to validate input.</i>
+ *
+ * <p>See also {@linkplain UnicodeUtil#truncateString(CharSequence, int)} and {@link
+ * BinaryUtil#truncateBinary(ByteBuffer, int)}
+ */
+public class TruncateUtil {
+
+  private TruncateUtil() {}
+
+  public static ByteBuffer truncateByteBuffer(int width, ByteBuffer value) {
+    ByteBuffer ret = value.duplicate();
+    ret.limit(Math.min(value.limit(), value.position() + width));
+    return ret;
+  }

Review Comment:
   I had thought about using the `truncateBinaryUnsafe` idea (even with that name). I'll give that a go.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r939215242


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,
+          DataTypes.StringType,
+          DataTypes.BinaryType);
+
+  private static void validateTruncationFieldType(DataType dt) {
+    if (truncateableAtomicTypes.stream().noneMatch(type -> type.sameType(dt))
+        && !(dt instanceof DecimalType)) {
+      String expectedTypes =
+          "[ByteType, ShortType, IntegerType, LongType, StringType, BinaryType, DecimalType]";

Review Comment:
   Sure thing.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r938295055


##########
api/src/main/java/org/apache/iceberg/util/TruncateUtil.java:
##########
@@ -0,0 +1,80 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.util;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+
+/**
+ * Contains the logic for various {@code truncate} transformations for various types.
+ *
+ * <p>This utility class allows for the logic to be reused in different scenarios where input
+ * validation is done at different times either in org.apache.iceberg.transforms.Truncate and within
+ * defined SQL functions for different compute engines for usage in SQL.
+ *
+ * <p>In general, the inputs to the functions should have already been validated by the calling
+ * code, as different classes use truncate with different preprocessing. This generally means that
+ * the truncation width is positive and the value to truncate is non-null.
+ *
+ * <p>Thus, <b>none</b> of these utility functions validate their input. <i>It is the responsibility
+ * of the calling code to validate input.</i>
+ *
+ * <p>See also {@linkplain UnicodeUtil#truncateString(CharSequence, int)} and {@link
+ * BinaryUtil#truncateBinary(ByteBuffer, int)}
+ */
+public class TruncateUtil {
+
+  private TruncateUtil() {}
+
+  public static ByteBuffer truncateByteBuffer(int width, ByteBuffer value) {
+    ByteBuffer ret = value.duplicate();
+    ret.limit(Math.min(value.limit(), value.position() + width));
+    return ret;
+  }
+
+  public static byte truncateByte(int width, byte value) {
+    return (byte) (value - (((value % width) + width) % width));
+  }
+
+  public static short truncateShort(int width, short value) {
+    return (short) (value - (((value % width) + width) % width));
+  }
+
+  public static int truncateInt(int width, int value) {
+    return value - (((value % width) + width) % width);
+  }
+
+  public static long truncateLong(int width, long value) {

Review Comment:
   Shouldn't this `width` be a long?



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r939157273


##########
core/src/test/java/org/apache/iceberg/util/TestTruncateUtil.java:
##########
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.util;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.assertj.core.api.Assertions;
+import org.junit.Assert;
+import org.junit.jupiter.api.Test;
+
+class TestTruncateUtil {
+  @Test
+  public void testTruncateByteBuffer() throws Exception {
+    Assert.assertEquals(
+        "Should truncate binary longer than length",
+        ByteBuffer.wrap("abcd".getBytes("UTF-8")),
+        TruncateUtil.truncateByteBuffer(4, ByteBuffer.wrap("abcdefg".getBytes("UTF-8"))));
+    Assert.assertEquals(
+        "Should not pad binary shorter than length",
+        ByteBuffer.wrap("abc".getBytes("UTF-8")),
+        TruncateUtil.truncateByteBuffer(4, ByteBuffer.wrap("abc".getBytes("UTF-8"))));
+  }
+
+  @Test
+  public void testTruncateByte() {

Review Comment:
   Will remove. The pathway is already covered by `TestSparkTruncateFunction`.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r938330105


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,
+          DataTypes.StringType,
+          DataTypes.BinaryType);
+
+  private static void validateTruncationFieldType(DataType dt) {
+    if (truncateableAtomicTypes.stream().noneMatch(type -> type.sameType(dt))
+        && !(dt instanceof DecimalType)) {
+      String expectedTypes =
+          "[ByteType, ShortType, IntegerType, LongType, StringType, BinaryType, DecimalType]";
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of %s, but found %s",
+              expectedTypes, dt));
+    }
+  }
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type. Expected 2 fields but found %s", inputType.fields().length));
+    }
+
+    StructField widthField = inputType.apply(0);
+    StructField toTruncateField = inputType.apply(1);
+
+    validateTruncationFieldType(toTruncateField.dataType());
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType
+        || toTruncateDataType instanceof VarcharType
+        || toTruncateDataType instanceof CharType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException("Cannot truncate type: " + toTruncateDataType);
+    }
+  }
+
+  @Override
+  public String description() {
+    return "Truncate - The Iceberg truncate function used for truncate partition transformations.\n"
+        + "\tCalled with the truncation width as the first argument: e.g. system.truncate(width, col)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      Integer width = readAndValidateWidth(input);
+
+      Byte toTruncate = !input.isNullAt(1) ? input.getByte(1) : null;
+      return toTruncate != null ? invoke(width, toTruncate) : null;

Review Comment:
   This does an identical null check twice. I think this should be:
   
   ```java
   return `input.isNullAt(1) ? null : invoke(width, input.getByte(1));`
   ```



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r939222271


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,
+          DataTypes.StringType,
+          DataTypes.BinaryType);
+
+  private static void validateTruncationFieldType(DataType dt) {
+    if (truncateableAtomicTypes.stream().noneMatch(type -> type.sameType(dt))
+        && !(dt instanceof DecimalType)) {
+      String expectedTypes =
+          "[ByteType, ShortType, IntegerType, LongType, StringType, BinaryType, DecimalType]";
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of %s, but found %s",
+              expectedTypes, dt));
+    }
+  }
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type. Expected 2 fields but found %s", inputType.fields().length));
+    }
+
+    StructField widthField = inputType.apply(0);
+    StructField toTruncateField = inputType.apply(1);
+
+    validateTruncationFieldType(toTruncateField.dataType());
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType
+        || toTruncateDataType instanceof VarcharType
+        || toTruncateDataType instanceof CharType) {

Review Comment:
   Yes these `instanceof` checks work the same way that that `instanceof DecimalType` works (because `VarcharType` and `CharType` both have a size / length field so they cannot be compared directly).
   
   I can update `validateTruncationFieldType`. However, I think that `validateTruncationFieldType` is somewhat unnecesssary given that this whole block basically does the same thing. Let me try moving it around 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: issues-unsubscribe@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r942840165


##########
api/src/main/java/org/apache/iceberg/transforms/Truncate.java:
##########
@@ -252,7 +254,7 @@ public CharSequence apply(CharSequence value) {
         return null;
       }
 
-      return UnicodeUtil.truncateString(value, length);
+      return UnicodeUtil.truncateStringUnsafe(length, value);

Review Comment:
   Why are the arguments transposed? I think the new method should use the same argument order that the other `UnicodeUtil` method does.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r941810030


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,348 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of [ByteType, ShortType, IntegerType, LongType, "
+                  + "DecimalType, StringType, BinaryType], but found %s",
+              toTruncateDataType));
+    }
+  }
+
+  @Override
+  public String description() {
+    return name()
+        + "(width, col) - Call Iceberg's truncate transform\n"
+        + "  width :: width for truncation, e.g. truncate(10, 255) -> 250 (must be an integer)\n"
+        + "  col :: column to truncate (must be an integer, decimal, string, or binary)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getByte(1));
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getShort(1));
+    }
+  }
+
+  public static class TruncateInt extends TruncateBase<Integer> {
+    // magic method used in codegen
+    public static int invoke(int width, int value) {
+      return TruncateUtil.truncateInt(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.IntegerType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.IntegerType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(int)";
+    }
+
+    @Override
+    public Integer produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getInt(1));
+    }
+  }
+
+  public static class TruncateBigInt extends TruncateBase<Long> {
+    // magic function for usage with codegen
+    public static long invoke(int width, long value) {
+      return TruncateUtil.truncateLong(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.LongType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.LongType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(bigint)";
+    }
+
+    @Override
+    public Long produceResult(InternalRow input) {
+      int width = readWidth(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getLong(1));
+    }
+  }
+
+  public static class TruncateString extends TruncateBase<UTF8String> {
+    // magic function for usage with codegen
+    public static UTF8String invoke(int width, UTF8String value) {
+      if (value == null) {
+        return null;
+      }
+
+      return value.substring(0, width);

Review Comment:
   The built-in `substring` function of UTF8String is already unicode code-point aware.
   
   It's almost certainly faster than converting to `ByteBuffer` and then `CharSequence` so we can use the existing `StringBuilder` based `UnicodeUtil` method for unicode code-point aware truncation.
   
   There's an existing function in `UTF8String`, called `toTitleCaseSlow` which uses a similar form as our `StringBuilder` based approach in `UnicodeUtil`, so I assume that the methods which rely on the bytes themselves and are code-point aware almost have to be faster than doing all of those conversions.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r941802803


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,
+          DataTypes.StringType,
+          DataTypes.BinaryType);
+
+  private static void validateTruncationFieldType(DataType dt) {
+    if (truncateableAtomicTypes.stream().noneMatch(type -> type.sameType(dt))
+        && !(dt instanceof DecimalType)) {
+      String expectedTypes =
+          "[ByteType, ShortType, IntegerType, LongType, StringType, BinaryType, DecimalType]";
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of %s, but found %s",
+              expectedTypes, dt));
+    }
+  }
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type. Expected 2 fields but found %s", inputType.fields().length));
+    }
+
+    StructField widthField = inputType.apply(0);
+    StructField toTruncateField = inputType.apply(1);
+
+    validateTruncationFieldType(toTruncateField.dataType());
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType
+        || toTruncateDataType instanceof VarcharType
+        || toTruncateDataType instanceof CharType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException("Cannot truncate type: " + toTruncateDataType);
+    }
+  }
+
+  @Override
+  public String description() {
+    return "Truncate - The Iceberg truncate function used for truncate partition transformations.\n"
+        + "\tCalled with the truncation width as the first argument: e.g. system.truncate(width, col)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate[width](tinyint)";

Review Comment:
   As `canonicalName` is used by Spark to compare if two functions are the same (as function namespacing could be different), leaving the `int` for width isn't necessary.
   
   All functions use `int` for width, so the `canonicalName` functions still correctly identify if a function is equivalent to another.
   
   The actual function's documentation includes `width`, which should be sufficient.
   
   Let me know if you feel differently!



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r941800706


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.iceberg.util.UnicodeUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.CharType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.sql.types.VarcharType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A function for use in SQL that truncates input to a given width according to the rules of the
+ * existing Truncate partition transform, e.g. {@code SELECT system.truncate(1, 'abc')} will return
+ * the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+  private static final List<DataType> truncateableAtomicTypes =
+      ImmutableList.of(
+          DataTypes.ByteType,
+          DataTypes.ShortType,
+          DataTypes.IntegerType,
+          DataTypes.LongType,
+          DataTypes.StringType,
+          DataTypes.BinaryType);
+
+  private static void validateTruncationFieldType(DataType dt) {
+    if (truncateableAtomicTypes.stream().noneMatch(type -> type.sameType(dt))
+        && !(dt instanceof DecimalType)) {
+      String expectedTypes =
+          "[ByteType, ShortType, IntegerType, LongType, StringType, BinaryType, DecimalType]";
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of %s, but found %s",
+              expectedTypes, dt));
+    }
+  }
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type. Expected 2 fields but found %s", inputType.fields().length));
+    }
+
+    StructField widthField = inputType.apply(0);
+    StructField toTruncateField = inputType.apply(1);
+
+    validateTruncationFieldType(toTruncateField.dataType());
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType
+        || toTruncateDataType instanceof VarcharType
+        || toTruncateDataType instanceof CharType) {

Review Comment:
   Yep. Removed the check for `VarcharType` and `CharType` as they're not necessary.
   
   There are unit tests to verify this behavior and it also matches the Spark docs.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r942960802


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,348 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of [ByteType, ShortType, IntegerType, LongType, "
+                  + "DecimalType, StringType, BinaryType], but found %s",
+              toTruncateDataType));
+    }
+  }
+
+  @Override
+  public String description() {
+    return name()
+        + "(width, col) - Call Iceberg's truncate transform\n"
+        + "  width :: width for truncation, e.g. truncate(10, 255) -> 250 (must be an integer)\n"
+        + "  col :: column to truncate (must be an integer, decimal, string, or binary)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getByte(1));
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getShort(1));
+    }
+  }
+
+  public static class TruncateInt extends TruncateBase<Integer> {
+    // magic method used in codegen
+    public static int invoke(int width, int value) {
+      return TruncateUtil.truncateInt(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.IntegerType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.IntegerType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(int)";
+    }
+
+    @Override
+    public Integer produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getInt(1));
+    }
+  }
+
+  public static class TruncateBigInt extends TruncateBase<Long> {
+    // magic function for usage with codegen
+    public static long invoke(int width, long value) {
+      return TruncateUtil.truncateLong(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.LongType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.LongType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(bigint)";
+    }
+
+    @Override
+    public Long produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getLong(1));
+    }
+  }
+
+  public static class TruncateString extends TruncateBase<UTF8String> {
+    // magic function for usage with codegen
+    public static UTF8String invoke(int width, UTF8String value) {
+      if (value == null) {
+        return null;
+      }
+
+      return value.substring(0, width);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.StringType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.StringType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(string)";
+    }
+
+    @Override
+    public UTF8String produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getUTF8String(1));
+    }
+  }
+
+  public static class TruncateBinary extends TruncateBase<byte[]> {
+    // magic method used in codegen
+    public static byte[] invoke(int width, byte[] value) {
+      if (value == null) {
+        return null;
+      }
+
+      return ByteBuffers.toByteArray(
+          BinaryUtil.truncateBinaryUnsafe(width, ByteBuffer.wrap(value)));
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.BinaryType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.BinaryType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(binary)";
+    }
+
+    @Override
+    public byte[] produceResult(InternalRow input) {
+      int width = width(input);
+      return input.isNullAt(1) ? null : invoke(width, input.getBinary(1));

Review Comment:
   Will skip the null checks for the ones that `invoke` checks for null.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r942961036


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,348 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be one of [ByteType, ShortType, IntegerType], but found "
+              + widthType);
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          String.format(
+              "Invalid input type to truncate. Expected one of [ByteType, ShortType, IntegerType, LongType, "
+                  + "DecimalType, StringType, BinaryType], but found %s",

Review Comment:
   I updated the test error messages to show the full message that spark adds (which is very similar to the one you proposed).



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r942958063


##########
api/src/main/java/org/apache/iceberg/util/BinaryUtil.java:
##########
@@ -50,6 +50,22 @@ public static ByteBuffer truncateBinary(ByteBuffer input, int length) {
     return ByteBuffer.wrap(array);
   }
 
+  /**
+   * Truncates the input byte buffer to the given length.
+   *
+   * <p>This skips input validation, and avoids copying the backing bytes if possible for efficiency

Review Comment:
   Yep. The buffer handles validation.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r943755147


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be tinyint, shortint or int");
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          "Expected truncation col to be tinyint, shortint, int, bigint, decimal, string, or binary");
+    }
+  }
+
+  @Override
+  public String description() {
+    return name()
+        + "(width, col) - Call Iceberg's truncate transform\n"
+        + "  width :: width for truncation, e.g. truncate(10, 255) -> 250 (must be an integer)\n"
+        + "  col :: column to truncate (must be an integer, decimal, string, or binary)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      return input.isNullAt(0) || input.isNullAt(1)
+          ? null
+          : invoke(input.getInt(0), input.getByte(1));
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      return input.isNullAt(0) || input.isNullAt(1)
+          ? null
+          : invoke(input.getInt(0), input.getShort(1));
+    }
+  }
+
+  public static class TruncateInt extends TruncateBase<Integer> {
+    // magic method used in codegen
+    public static int invoke(int width, int value) {
+      return TruncateUtil.truncateInt(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.IntegerType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.IntegerType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(int)";
+    }
+
+    @Override
+    public Integer produceResult(InternalRow input) {
+      return input.isNullAt(0) || input.isNullAt(1)
+          ? null
+          : invoke(input.getInt(0), input.getInt(1));
+    }
+  }
+
+  public static class TruncateBigInt extends TruncateBase<Long> {
+    // magic function for usage with codegen
+    public static long invoke(int width, long value) {
+      return TruncateUtil.truncateLong(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.LongType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.LongType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(bigint)";
+    }
+
+    @Override
+    public Long produceResult(InternalRow input) {
+      return input.isNullAt(0) || input.isNullAt(1)

Review Comment:
   Good call. I'm not a fan of the ternary style that spotless adds.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] aokolnychyi commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
aokolnychyi commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r943851751


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be tinyint, shortint or int");
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          "Expected truncation col to be tinyint, shortint, int, bigint, decimal, string, or binary");
+    }
+  }
+
+  @Override
+  public String description() {
+    return name()
+        + "(width, col) - Call Iceberg's truncate transform\n"
+        + "  width :: width for truncation, e.g. truncate(10, 255) -> 250 (must be an integer)\n"
+        + "  col :: column to truncate (must be an integer, decimal, string, or binary)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      return input.isNullAt(0) || input.isNullAt(1)
+          ? null
+          : invoke(input.getInt(0), input.getByte(1));
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      return input.isNullAt(0) || input.isNullAt(1)

Review Comment:
   Okay, I took a look at `ScalarFunction`.
   
   ```
    * <h2> Handling of nullable primitive arguments </h2>
    * The handling of null primitive arguments is different between the magic method approach and
    * the {@link #produceResult} approach. With the former, whenever any of the method arguments meet
    * the following conditions:
    * <ol>
    *   <li>the argument is of primitive type</li>
    *   <li>the argument is nullable</li>
    *   <li>the value of the argument is null</li>
    * </ol>
    * Spark will return null directly instead of calling the magic method. On the other hand, Spark
    * will pass null primitive arguments to {@link #produceResult} and it is user's responsibility to
    * handle them in the function implementation.
   ```
   
   Then the existing approach makes more sense to me. At least, it is in line with `invoke`. Let's keep it as-is.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r943911934


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be tinyint, shortint or int");

Review Comment:
   We did need a length check, but the error message didnd't need to include the `Cannot bind truncate:`.
   
   I simplified it and added tests.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] aokolnychyi merged pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
aokolnychyi merged PR #5431:
URL: https://github.com/apache/iceberg/pull/5431


-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] aokolnychyi commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
aokolnychyi commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r943688439


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be tinyint, shortint or int");
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          "Expected truncation col to be tinyint, shortint, int, bigint, decimal, string, or binary");
+    }
+  }
+
+  @Override
+  public String description() {
+    return name()
+        + "(width, col) - Call Iceberg's truncate transform\n"
+        + "  width :: width for truncation, e.g. truncate(10, 255) -> 250 (must be an integer)\n"
+        + "  col :: column to truncate (must be an integer, decimal, string, or binary)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      return input.isNullAt(0) || input.isNullAt(1)

Review Comment:
   What about defining constants for 0 and 1 with some reasonable names to indicate what those are?
   
   ```
   private static final int WIDTH_ORDINAL = 0;
   private static final int VALUE_ORDINAL = 1;
   ```
   
   It is easy to forget what is 0 and what is 1 once you scroll below.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kbendick commented on a diff in pull request #5431: Spark: Support truncate in FunctionCatalog

Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5431:
URL: https://github.com/apache/iceberg/pull/5431#discussion_r943748796


##########
spark/v3.3/spark/src/main/java/org/apache/iceberg/spark/functions/TruncateFunction.java:
##########
@@ -0,0 +1,340 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.spark.functions;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import org.apache.iceberg.util.BinaryUtil;
+import org.apache.iceberg.util.ByteBuffers;
+import org.apache.iceberg.util.TruncateUtil;
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.functions.BoundFunction;
+import org.apache.spark.sql.connector.catalog.functions.ScalarFunction;
+import org.apache.spark.sql.connector.catalog.functions.UnboundFunction;
+import org.apache.spark.sql.types.BinaryType;
+import org.apache.spark.sql.types.ByteType;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.types.DecimalType;
+import org.apache.spark.sql.types.IntegerType;
+import org.apache.spark.sql.types.LongType;
+import org.apache.spark.sql.types.ShortType;
+import org.apache.spark.sql.types.StringType;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * A Spark function implementation for the Iceberg truncate transform.
+ *
+ * <p>Example usage: {@code SELECT system.truncate(1, 'abc')}, which returns the String 'a'.
+ *
+ * <p>Note that for performance reasons, the given input width is not validated in the
+ * implementations used in code-gen. The width must remain non-negative to give meaningful results.
+ */
+public class TruncateFunction implements UnboundFunction {
+
+  private static void validateTruncationWidthType(DataType widthType) {
+    if (!DataTypes.IntegerType.sameType(widthType)
+        && !DataTypes.ShortType.sameType(widthType)
+        && !DataTypes.ByteType.sameType(widthType)) {
+      throw new UnsupportedOperationException(
+          "Expected truncation width to be tinyint, shortint or int");
+    }
+  }
+
+  @Override
+  public BoundFunction bind(StructType inputType) {
+    if (inputType.fields().length != 2) {
+      throw new UnsupportedOperationException(
+          "Cannot bind truncate: wrong number of inputs (expected width and value)");
+    }
+
+    StructField widthField = inputType.fields()[0];
+    StructField toTruncateField = inputType.fields()[1];
+    validateTruncationWidthType(widthField.dataType());
+
+    DataType toTruncateDataType = toTruncateField.dataType();
+    if (toTruncateDataType instanceof ByteType) {
+      return new TruncateTinyInt();
+    } else if (toTruncateDataType instanceof ShortType) {
+      return new TruncateSmallInt();
+    } else if (toTruncateDataType instanceof IntegerType) {
+      return new TruncateInt();
+    } else if (toTruncateDataType instanceof LongType) {
+      return new TruncateBigInt();
+    } else if (toTruncateDataType instanceof DecimalType) {
+      return new TruncateDecimal(
+          ((DecimalType) toTruncateDataType).precision(),
+          ((DecimalType) toTruncateDataType).scale());
+    } else if (toTruncateDataType instanceof StringType) {
+      return new TruncateString();
+    } else if (toTruncateDataType instanceof BinaryType) {
+      return new TruncateBinary();
+    } else {
+      throw new UnsupportedOperationException(
+          "Expected truncation col to be tinyint, shortint, int, bigint, decimal, string, or binary");
+    }
+  }
+
+  @Override
+  public String description() {
+    return name()
+        + "(width, col) - Call Iceberg's truncate transform\n"
+        + "  width :: width for truncation, e.g. truncate(10, 255) -> 250 (must be an integer)\n"
+        + "  col :: column to truncate (must be an integer, decimal, string, or binary)";
+  }
+
+  @Override
+  public String name() {
+    return "truncate";
+  }
+
+  public abstract static class TruncateBase<T> implements ScalarFunction<T> {
+    @Override
+    public String name() {
+      return "truncate";
+    }
+  }
+
+  public static class TruncateTinyInt extends TruncateBase<Byte> {
+    public static byte invoke(int width, byte value) {
+      return TruncateUtil.truncateByte(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ByteType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ByteType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(tinyint)";
+    }
+
+    @Override
+    public Byte produceResult(InternalRow input) {
+      return input.isNullAt(0) || input.isNullAt(1)
+          ? null
+          : invoke(input.getInt(0), input.getByte(1));
+    }
+  }
+
+  public static class TruncateSmallInt extends TruncateBase<Short> {
+    // magic method used in codegen
+    public static short invoke(int width, short value) {
+      return TruncateUtil.truncateShort(width, value);
+    }
+
+    @Override
+    public DataType[] inputTypes() {
+      return new DataType[] {DataTypes.IntegerType, DataTypes.ShortType};
+    }
+
+    @Override
+    public DataType resultType() {
+      return DataTypes.ShortType;
+    }
+
+    @Override
+    public String canonicalName() {
+      return "iceberg.truncate(smallint)";
+    }
+
+    @Override
+    public Short produceResult(InternalRow input) {
+      return input.isNullAt(0) || input.isNullAt(1)

Review Comment:
   The reason for this is that Spark will return `null` for the code-generated code with `null` input. And we don't have much control over that.
   
   I can try setting the input schema that's used for binding and see if requiring that to be non-null will be tracked and throw on a `null` input. But in that case we'd require the user to cast the `width` column (if one is used) to a non-null integer.
   
   We've already taken the standpoint that bad input on the width will lead to undefined results somewhat (in that we aren't testing the width). Technically, the width can be variable and allow for a different value for each column - though in practice we don't expect to use it this way.
   
   This two argument set up is also how the `bucket` v2 function is expected to work.
   
   Let me check if Spark will respect declaring the input schema as non-null.



-- 
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@iceberg.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org