This is an automated email from the ASF dual-hosted git repository.
RussellSpitzer pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/iceberg.git
The following commit(s) were added to refs/heads/main by this push:
new bf00ca292a API: [1/N] Add ReadRestrictions Actions (#16198)
bf00ca292a is described below
commit bf00ca292aa74dca22a959e2a0fc835af19ad889
Author: Prashant Singh <[email protected]>
AuthorDate: Tue Nov 17 18:07:59 2026 -0800
API: [1/N] Add ReadRestrictions Actions (#16198)
---
.../apache/iceberg/functions/IcebergFunction.java | 62 +++
.../apache/iceberg/functions/IcebergFunctions.java | 100 ++++
.../org/apache/iceberg/functions/MaskAlphanum.java | 93 ++++
.../apache/iceberg/functions/MaskToFixedValue.java | 232 +++++++++
.../apache/iceberg/functions/NullSafeFunction.java | 31 ++
.../apache/iceberg/functions/ReplaceWithNull.java | 72 +++
.../iceberg/functions/SerializationProxies.java | 166 ++++++
.../java/org/apache/iceberg/functions/Sha256.java | 146 ++++++
.../org/apache/iceberg/functions/Sha256Global.java | 59 +++
.../apache/iceberg/functions/Sha256QueryLocal.java | 76 +++
.../org/apache/iceberg/functions/ShowFirst4.java | 78 +++
.../org/apache/iceberg/functions/ShowLast4.java | 90 ++++
.../apache/iceberg/functions/TruncateTemporal.java | 99 ++++
.../apache/iceberg/functions/TruncateToMonth.java | 67 +++
.../apache/iceberg/functions/TruncateToYear.java | 67 +++
.../apache/iceberg/functions/UnknownFunction.java | 75 +++
.../functions/TestFunctionSerialization.java | 91 ++++
.../iceberg/functions/TestIcebergFunctions.java | 558 +++++++++++++++++++++
18 files changed, 2162 insertions(+)
diff --git
a/api/src/main/java/org/apache/iceberg/functions/IcebergFunction.java
b/api/src/main/java/org/apache/iceberg/functions/IcebergFunction.java
new file mode 100644
index 0000000000..6d1a06b2e2
--- /dev/null
+++ b/api/src/main/java/org/apache/iceberg/functions/IcebergFunction.java
@@ -0,0 +1,62 @@
+/*
+ * 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.functions;
+
+import java.io.Serializable;
+import org.apache.iceberg.types.Type;
+import org.apache.iceberg.util.SerializableFunction;
+
+/**
+ * A named, type-aware function that can be bound to an Iceberg {@link Type}.
+ *
+ * <p>{@link #bind(Type)} returns a {@link SerializableFunction} that applies
this function's logic
+ * to values of the bound type.
+ *
+ * @param <S> input value type
+ * @param <T> output value type
+ */
+public interface IcebergFunction<S, T> extends Serializable {
+
+ /**
+ * Returns a function that applies this projection to values of the given
{@link Type}.
+ *
+ * @throws IllegalArgumentException if the type is not supported by this
function.
+ * @throws UnsupportedOperationException if this function cannot be bound
with a type alone.
+ */
+ SerializableFunction<S, T> bind(Type type);
+
+ /**
+ * Returns a function that applies this projection to values of the given
{@link Type} using the
+ * given salt.
+ *
+ * @throws IllegalArgumentException if the type is not supported or the salt
is invalid.
+ * @throws UnsupportedOperationException if this function does not accept a
salt.
+ */
+ default SerializableFunction<S, T> bind(Type type, byte[] salt) {
+ throw new UnsupportedOperationException(this + " does not accept a salt");
+ }
+
+ /** Returns true if this function must be bound with a salt using {@link
#bind(Type, byte[])}. */
+ default boolean isSalted() {
+ return false;
+ }
+
+ /** Returns true if this function can be bound to the given {@link Type}. */
+ boolean canBind(Type type);
+}
diff --git
a/api/src/main/java/org/apache/iceberg/functions/IcebergFunctions.java
b/api/src/main/java/org/apache/iceberg/functions/IcebergFunctions.java
new file mode 100644
index 0000000000..21b7ce23ab
--- /dev/null
+++ b/api/src/main/java/org/apache/iceberg/functions/IcebergFunctions.java
@@ -0,0 +1,100 @@
+/*
+ * 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.functions;
+
+import java.util.Locale;
+
+/** Factory for {@link IcebergFunction} implementations. */
+public class IcebergFunctions {
+ private IcebergFunctions() {}
+
+ /**
+ * Returns the function with the given name, such as {@code show-last-4}, or
an {@link
+ * UnknownFunction} if the name is not recognized.
+ */
+ public static IcebergFunction<?, ?> fromString(String function) {
+ switch (function.toLowerCase(Locale.ROOT)) {
+ case MaskAlphanum.NAME:
+ return MaskAlphanum.get();
+ case MaskToFixedValue.NAME:
+ return MaskToFixedValue.get();
+ case ReplaceWithNull.NAME:
+ return ReplaceWithNull.get();
+ case ShowFirst4.NAME:
+ return ShowFirst4.get();
+ case ShowLast4.NAME:
+ return ShowLast4.get();
+ case TruncateToYear.NAME:
+ return TruncateToYear.get();
+ case TruncateToMonth.NAME:
+ return TruncateToMonth.get();
+ case Sha256Global.NAME:
+ return Sha256Global.get();
+ case Sha256QueryLocal.NAME:
+ return Sha256QueryLocal.get();
+ default:
+ return new UnknownFunction(function);
+ }
+ }
+
+ /** Returns a {@code mask-alphanum} {@link IcebergFunction} for string
types. */
+ public static IcebergFunction<CharSequence, CharSequence> maskAlphanum() {
+ return MaskAlphanum.get();
+ }
+
+ /** Returns a {@code mask-to-fixed-value} {@link IcebergFunction}. */
+ public static <T> IcebergFunction<T, T> maskToFixedValue() {
+ return MaskToFixedValue.get();
+ }
+
+ /** Returns a {@code replace-with-null} {@link IcebergFunction} for any
type. */
+ public static <T> IcebergFunction<T, T> replaceWithNull() {
+ return ReplaceWithNull.get();
+ }
+
+ /** Returns a {@code show-first-4} {@link IcebergFunction} for string types.
*/
+ public static IcebergFunction<CharSequence, CharSequence> showFirst4() {
+ return ShowFirst4.get();
+ }
+
+ /** Returns a {@code show-last-4} {@link IcebergFunction} for string types.
*/
+ public static IcebergFunction<CharSequence, CharSequence> showLast4() {
+ return ShowLast4.get();
+ }
+
+ /** Returns a {@code truncate-to-year} {@link IcebergFunction} for date and
timestamp types. */
+ public static <T> IcebergFunction<T, T> truncateToYear() {
+ return TruncateToYear.get();
+ }
+
+ /** Returns a {@code truncate-to-month} {@link IcebergFunction} for date and
timestamp types. */
+ public static <T> IcebergFunction<T, T> truncateToMonth() {
+ return TruncateToMonth.get();
+ }
+
+ /** Returns a {@code sha-256-global} {@link IcebergFunction} for string,
int, long and binary. */
+ public static <T> IcebergFunction<T, T> sha256Global() {
+ return Sha256Global.get();
+ }
+
+ /** Returns a {@code sha-256-query-local} {@link IcebergFunction}, salted
per query. */
+ public static <T> IcebergFunction<T, T> sha256QueryLocal() {
+ return Sha256QueryLocal.get();
+ }
+}
diff --git a/api/src/main/java/org/apache/iceberg/functions/MaskAlphanum.java
b/api/src/main/java/org/apache/iceberg/functions/MaskAlphanum.java
new file mode 100644
index 0000000000..7b341595c6
--- /dev/null
+++ b/api/src/main/java/org/apache/iceberg/functions/MaskAlphanum.java
@@ -0,0 +1,93 @@
+/*
+ * 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.functions;
+
+import java.io.ObjectStreamException;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.types.Type;
+import org.apache.iceberg.util.SerializableFunction;
+
+/** Redacts every Unicode code point in a string per the mask-alphanum rules.
*/
+final class MaskAlphanum implements IcebergFunction<CharSequence,
CharSequence> {
+ static final String NAME = "mask-alphanum";
+
+ private static final MaskAlphanum INSTANCE = new MaskAlphanum();
+
+ static MaskAlphanum get() {
+ return INSTANCE;
+ }
+
+ private MaskAlphanum() {}
+
+ @Override
+ public String toString() {
+ return NAME;
+ }
+
+ Object writeReplace() throws ObjectStreamException {
+ return SerializationProxies.MaskAlphanumProxy.get();
+ }
+
+ @Override
+ public boolean canBind(Type type) {
+ return type.typeId() == Type.TypeID.STRING;
+ }
+
+ @Override
+ public SerializableFunction<CharSequence, CharSequence> bind(Type type) {
+ Preconditions.checkArgument(canBind(type), "mask-alphanum requires STRING
type, got %s", type);
+ return MaskAlphanumFn.INSTANCE;
+ }
+
+ /**
+ * Maps a code point through the mask-alphanum rules; also used by {@link
ShowFirst4} and {@link
+ * ShowLast4} on the code points outside their preserved windows:
+ *
+ * <ul>
+ * <li>ASCII digits (0-9) -> {@code 'n'}
+ * <li>Structural punctuation kept as-is: {@code ( ) , . - @}
+ * <li>Everything else -> {@code 'x'}
+ * </ul>
+ */
+ static int maskCodePoint(int cp) {
+ if (cp >= 0x30 && cp <= 0x39) {
+ return 'n';
+ } else if (cp == '(' || cp == ')' || cp == ',' || cp == '.' || cp == '-'
|| cp == '@') {
+ return cp;
+ } else {
+ return 'x';
+ }
+ }
+
+ private static final class MaskAlphanumFn extends
NullSafeFunction<CharSequence, CharSequence> {
+ static final MaskAlphanumFn INSTANCE = new MaskAlphanumFn();
+
+ @Override
+ protected CharSequence applyNonNull(CharSequence input) {
+ StringBuilder sb = new StringBuilder(input.length());
+ int offset = 0;
+ while (offset < input.length()) {
+ int cp = Character.codePointAt(input, offset);
+ sb.appendCodePoint(maskCodePoint(cp));
+ offset += Character.charCount(cp);
+ }
+ return sb.toString();
+ }
+ }
+}
diff --git
a/api/src/main/java/org/apache/iceberg/functions/MaskToFixedValue.java
b/api/src/main/java/org/apache/iceberg/functions/MaskToFixedValue.java
new file mode 100644
index 0000000000..d39c43a354
--- /dev/null
+++ b/api/src/main/java/org/apache/iceberg/functions/MaskToFixedValue.java
@@ -0,0 +1,232 @@
+/*
+ * 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.functions;
+
+import java.io.ObjectStreamException;
+import java.io.Serializable;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.util.Collections;
+import java.util.List;
+import java.util.UUID;
+import org.apache.iceberg.StructLike;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.types.Type;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.DateTimeUtil;
+import org.apache.iceberg.util.SerializableFunction;
+import org.apache.iceberg.variants.Variant;
+
+/** Returns a spec-defined fixed value for the column's type. */
+final class MaskToFixedValue<T> implements IcebergFunction<T, T> {
+
+ private static final Integer INT_DEFAULT = 0;
+ private static final Long LONG_DEFAULT = 0L;
+ private static final Float FLOAT_DEFAULT = 0.0f;
+ private static final Double DOUBLE_DEFAULT = 0.0d;
+ // Per spec: string uses "XXXXXXXX" (not "") so masked strings stay visually
distinct from
+ // legitimately empty strings. All other types use the zero value of their
representation.
+ private static final String STRING_DEFAULT = "XXXXXXXX";
+ private static final Integer DATE_DEFAULT =
DateTimeUtil.daysFromDate(LocalDate.of(1970, 1, 1));
+ private static final Long TIME_DEFAULT_MICROS = 0L;
+ private static final Long TIMESTAMP_DEFAULT_MICROS =
+ DateTimeUtil.microsFromTimestamp(LocalDateTime.of(1970, 1, 1, 0, 0));
+ private static final Long TIMESTAMP_DEFAULT_NANOS =
+ DateTimeUtil.nanosFromTimestamp(LocalDateTime.of(1970, 1, 1, 0, 0));
+ private static final UUID UUID_DEFAULT =
UUID.fromString("00000000-0000-0000-0000-000000000000");
+ private static final byte[] EMPTY_BYTES = new byte[0];
+
+ // Empty Variant: V1 metadata with no entries + empty object value.
+ private static final Variant EMPTY_VARIANT =
+ Variant.from(
+ ByteBuffer.wrap(new byte[] {0x01, 0x00, 0x00, 0x02, 0x00, 0x00})
+ .order(ByteOrder.LITTLE_ENDIAN));
+
+ static final String NAME = "mask-to-fixed-value";
+
+ private static final MaskToFixedValue<?> INSTANCE = new MaskToFixedValue<>();
+
+ @SuppressWarnings("unchecked")
+ static <T> MaskToFixedValue<T> get() {
+ return (MaskToFixedValue<T>) INSTANCE;
+ }
+
+ private MaskToFixedValue() {}
+
+ @Override
+ public String toString() {
+ return NAME;
+ }
+
+ Object writeReplace() throws ObjectStreamException {
+ return SerializationProxies.MaskToFixedValueProxy.get();
+ }
+
+ @Override
+ public boolean canBind(Type type) {
+ switch (type.typeId()) {
+ case BOOLEAN:
+ case INTEGER:
+ case LONG:
+ case FLOAT:
+ case DOUBLE:
+ case STRING:
+ case DATE:
+ case TIME:
+ case TIMESTAMP:
+ case TIMESTAMP_NANO:
+ case UUID:
+ case FIXED:
+ case BINARY:
+ case DECIMAL:
+ case VARIANT:
+ case LIST:
+ case MAP:
+ return true;
+ case STRUCT:
+ return type.asStructType().fields().stream().allMatch(field ->
canBind(field.type()));
+ default:
+ return false;
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public SerializableFunction<T, T> bind(Type type) {
+ Preconditions.checkArgument(
+ canBind(type), "mask-to-fixed-value is not supported for type: %s",
type);
+ Object defaultValue = defaultValueFor(type);
+ return (SerializableFunction<T, T>)
+ (defaultValue instanceof byte[] bytes
+ ? new ConstantByteBufferFn(bytes)
+ : new ConstantFn(defaultValue));
+ }
+
+ private static Object defaultValueFor(Type type) {
+ switch (type.typeId()) {
+ case BOOLEAN:
+ return Boolean.FALSE;
+ case INTEGER:
+ return INT_DEFAULT;
+ case LONG:
+ return LONG_DEFAULT;
+ case FLOAT:
+ return FLOAT_DEFAULT;
+ case DOUBLE:
+ return DOUBLE_DEFAULT;
+ case STRING:
+ return STRING_DEFAULT;
+ case DATE:
+ return DATE_DEFAULT;
+ case TIME:
+ return TIME_DEFAULT_MICROS;
+ case TIMESTAMP:
+ return TIMESTAMP_DEFAULT_MICROS;
+ case TIMESTAMP_NANO:
+ return TIMESTAMP_DEFAULT_NANOS;
+ case UUID:
+ return UUID_DEFAULT;
+ // ByteBuffer is not serializable, so binary values are held as bytes
and wrapped on access
+ case FIXED:
+ return new byte[((Types.FixedType) type).length()];
+ case BINARY:
+ return EMPTY_BYTES;
+ case DECIMAL:
+ return new BigDecimal(BigInteger.ZERO, ((Types.DecimalType)
type).scale());
+ case VARIANT:
+ return EMPTY_VARIANT;
+ case LIST:
+ return Collections.emptyList();
+ case MAP:
+ return Collections.emptyMap();
+ case STRUCT:
+ return defaultStruct(type.asStructType());
+ default:
+ throw new IllegalStateException("unreachable: canBind should have
rejected " + type);
+ }
+ }
+
+ private static StructLike defaultStruct(Types.StructType structType) {
+ List<Types.NestedField> fields = structType.fields();
+ Object[] values = new Object[fields.size()];
+ for (int i = 0; i < fields.size(); i++) {
+ values[i] = defaultValueFor(fields.get(i).type());
+ }
+ return new DefaultStruct(values);
+ }
+
+ private static final class ConstantFn implements
SerializableFunction<Object, Object> {
+ private final Object constant;
+
+ ConstantFn(Object constant) {
+ this.constant = constant;
+ }
+
+ @Override
+ public Object apply(Object value) {
+ return constant;
+ }
+ }
+
+ private static ByteBuffer toBuffer(byte[] bytes) {
+ return ByteBuffer.wrap(bytes).asReadOnlyBuffer();
+ }
+
+ private static final class ConstantByteBufferFn implements
SerializableFunction<Object, Object> {
+ private final byte[] constant;
+
+ ConstantByteBufferFn(byte[] constant) {
+ this.constant = constant;
+ }
+
+ @Override
+ public Object apply(Object value) {
+ return toBuffer(constant);
+ }
+ }
+
+ private static final class DefaultStruct implements StructLike, Serializable
{
+ private final Object[] values;
+
+ DefaultStruct(Object[] values) {
+ this.values = values;
+ }
+
+ @Override
+ public int size() {
+ return values.length;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public <T> T get(int pos, Class<T> javaClass) {
+ Object value = values[pos];
+ return (T) (value instanceof byte[] bytes ? toBuffer(bytes) : value);
+ }
+
+ @Override
+ public <T> void set(int pos, T value) {
+ throw new UnsupportedOperationException("DefaultStruct is immutable");
+ }
+ }
+}
diff --git
a/api/src/main/java/org/apache/iceberg/functions/NullSafeFunction.java
b/api/src/main/java/org/apache/iceberg/functions/NullSafeFunction.java
new file mode 100644
index 0000000000..0f3f07151b
--- /dev/null
+++ b/api/src/main/java/org/apache/iceberg/functions/NullSafeFunction.java
@@ -0,0 +1,31 @@
+/*
+ * 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.functions;
+
+import org.apache.iceberg.util.SerializableFunction;
+
+/** Base for masking functions that return null for null input. */
+abstract class NullSafeFunction<S, T> implements SerializableFunction<S, T> {
+ @Override
+ public final T apply(S value) {
+ return value == null ? null : applyNonNull(value);
+ }
+
+ protected abstract T applyNonNull(S value);
+}
diff --git
a/api/src/main/java/org/apache/iceberg/functions/ReplaceWithNull.java
b/api/src/main/java/org/apache/iceberg/functions/ReplaceWithNull.java
new file mode 100644
index 0000000000..65148095fc
--- /dev/null
+++ b/api/src/main/java/org/apache/iceberg/functions/ReplaceWithNull.java
@@ -0,0 +1,72 @@
+/*
+ * 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.functions;
+
+import java.io.ObjectStreamException;
+import org.apache.iceberg.types.Type;
+import org.apache.iceberg.util.SerializableFunction;
+
+/**
+ * Returns null for every non-null input. Works for any type.
+ *
+ * <p>Per spec, replace-with-null is only valid for optional (nullable)
fields. Callers must
+ * validate that the target field is optional before binding; this function
cannot check nullability
+ * because {@link org.apache.iceberg.types.Type} does not carry the field's
required/optional flag.
+ */
+final class ReplaceWithNull<T> implements IcebergFunction<T, T> {
+ static final String NAME = "replace-with-null";
+
+ private static final ReplaceWithNull<?> INSTANCE = new ReplaceWithNull<>();
+
+ @SuppressWarnings("unchecked")
+ static <T> ReplaceWithNull<T> get() {
+ return (ReplaceWithNull<T>) INSTANCE;
+ }
+
+ private ReplaceWithNull() {}
+
+ @Override
+ public String toString() {
+ return NAME;
+ }
+
+ Object writeReplace() throws ObjectStreamException {
+ return SerializationProxies.ReplaceWithNullProxy.get();
+ }
+
+ @Override
+ public boolean canBind(Type type) {
+ return true;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public SerializableFunction<T, T> bind(Type type) {
+ return (SerializableFunction<T, T>) ReplaceWithNullFn.INSTANCE;
+ }
+
+ private static final class ReplaceWithNullFn implements
SerializableFunction<Object, Object> {
+ static final ReplaceWithNullFn INSTANCE = new ReplaceWithNullFn();
+
+ @Override
+ public Object apply(Object value) {
+ return null;
+ }
+ }
+}
diff --git
a/api/src/main/java/org/apache/iceberg/functions/SerializationProxies.java
b/api/src/main/java/org/apache/iceberg/functions/SerializationProxies.java
new file mode 100644
index 0000000000..18e62ff7ea
--- /dev/null
+++ b/api/src/main/java/org/apache/iceberg/functions/SerializationProxies.java
@@ -0,0 +1,166 @@
+/*
+ * 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.functions;
+
+import java.io.ObjectStreamException;
+import java.io.Serializable;
+
+/**
+ * Stand-in classes for function classes in Java Serialization.
+ *
+ * <p>These are used so that function classes can be singletons and use
identical equality.
+ */
+class SerializationProxies {
+ private SerializationProxies() {}
+
+ static class MaskAlphanumProxy implements Serializable {
+ private static final MaskAlphanumProxy INSTANCE = new MaskAlphanumProxy();
+
+ static MaskAlphanumProxy get() {
+ return INSTANCE;
+ }
+
+ /** Constructor for Java serialization. */
+ MaskAlphanumProxy() {}
+
+ Object readResolve() throws ObjectStreamException {
+ return MaskAlphanum.get();
+ }
+ }
+
+ static class MaskToFixedValueProxy implements Serializable {
+ private static final MaskToFixedValueProxy INSTANCE = new
MaskToFixedValueProxy();
+
+ static MaskToFixedValueProxy get() {
+ return INSTANCE;
+ }
+
+ /** Constructor for Java serialization. */
+ MaskToFixedValueProxy() {}
+
+ Object readResolve() throws ObjectStreamException {
+ return MaskToFixedValue.get();
+ }
+ }
+
+ static class ReplaceWithNullProxy implements Serializable {
+ private static final ReplaceWithNullProxy INSTANCE = new
ReplaceWithNullProxy();
+
+ static ReplaceWithNullProxy get() {
+ return INSTANCE;
+ }
+
+ /** Constructor for Java serialization. */
+ ReplaceWithNullProxy() {}
+
+ Object readResolve() throws ObjectStreamException {
+ return ReplaceWithNull.get();
+ }
+ }
+
+ static class ShowFirst4Proxy implements Serializable {
+ private static final ShowFirst4Proxy INSTANCE = new ShowFirst4Proxy();
+
+ static ShowFirst4Proxy get() {
+ return INSTANCE;
+ }
+
+ /** Constructor for Java serialization. */
+ ShowFirst4Proxy() {}
+
+ Object readResolve() throws ObjectStreamException {
+ return ShowFirst4.get();
+ }
+ }
+
+ static class ShowLast4Proxy implements Serializable {
+ private static final ShowLast4Proxy INSTANCE = new ShowLast4Proxy();
+
+ static ShowLast4Proxy get() {
+ return INSTANCE;
+ }
+
+ /** Constructor for Java serialization. */
+ ShowLast4Proxy() {}
+
+ Object readResolve() throws ObjectStreamException {
+ return ShowLast4.get();
+ }
+ }
+
+ static class TruncateToYearProxy implements Serializable {
+ private static final TruncateToYearProxy INSTANCE = new
TruncateToYearProxy();
+
+ static TruncateToYearProxy get() {
+ return INSTANCE;
+ }
+
+ /** Constructor for Java serialization. */
+ TruncateToYearProxy() {}
+
+ Object readResolve() throws ObjectStreamException {
+ return TruncateToYear.get();
+ }
+ }
+
+ static class TruncateToMonthProxy implements Serializable {
+ private static final TruncateToMonthProxy INSTANCE = new
TruncateToMonthProxy();
+
+ static TruncateToMonthProxy get() {
+ return INSTANCE;
+ }
+
+ /** Constructor for Java serialization. */
+ TruncateToMonthProxy() {}
+
+ Object readResolve() throws ObjectStreamException {
+ return TruncateToMonth.get();
+ }
+ }
+
+ static class Sha256GlobalProxy implements Serializable {
+ private static final Sha256GlobalProxy INSTANCE = new Sha256GlobalProxy();
+
+ static Sha256GlobalProxy get() {
+ return INSTANCE;
+ }
+
+ /** Constructor for Java serialization. */
+ Sha256GlobalProxy() {}
+
+ Object readResolve() throws ObjectStreamException {
+ return Sha256Global.get();
+ }
+ }
+
+ static class Sha256QueryLocalProxy implements Serializable {
+ private static final Sha256QueryLocalProxy INSTANCE = new
Sha256QueryLocalProxy();
+
+ static Sha256QueryLocalProxy get() {
+ return INSTANCE;
+ }
+
+ /** Constructor for Java serialization. */
+ Sha256QueryLocalProxy() {}
+
+ Object readResolve() throws ObjectStreamException {
+ return Sha256QueryLocal.get();
+ }
+ }
+}
diff --git a/api/src/main/java/org/apache/iceberg/functions/Sha256.java
b/api/src/main/java/org/apache/iceberg/functions/Sha256.java
new file mode 100644
index 0000000000..aaf1753661
--- /dev/null
+++ b/api/src/main/java/org/apache/iceberg/functions/Sha256.java
@@ -0,0 +1,146 @@
+/*
+ * 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.functions;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import org.apache.iceberg.relocated.com.google.common.io.BaseEncoding;
+import org.apache.iceberg.types.Type;
+
+/** Shared SHA-256 masking function. One instance per (type, salt) pair. */
+final class Sha256 extends NullSafeFunction<Object, Object> {
+
+ private static final ThreadLocal<MessageDigest> DIGEST =
+ ThreadLocal.withInitial(
+ () -> {
+ try {
+ return MessageDigest.getInstance("SHA-256");
+ } catch (NoSuchAlgorithmException e) {
+ throw new IllegalStateException("SHA-256 not available", e);
+ }
+ });
+
+ enum Codec {
+ STRING {
+ @Override
+ void update(MessageDigest md, Object value) {
+ md.update(value.toString().getBytes(StandardCharsets.UTF_8));
+ }
+
+ @Override
+ Object encode(byte[] digest) {
+ return BaseEncoding.base16().lowerCase().encode(digest);
+ }
+ },
+ INTEGER {
+ @Override
+ void update(MessageDigest md, Object value) {
+ int intVal = (Integer) value;
+ md.update((byte) intVal);
+ md.update((byte) (intVal >>> 8));
+ md.update((byte) (intVal >>> 16));
+ md.update((byte) (intVal >>> 24));
+ }
+
+ @Override
+ Object encode(byte[] digest) {
+ return ByteBuffer.wrap(digest, 0,
4).order(ByteOrder.LITTLE_ENDIAN).getInt();
+ }
+ },
+ LONG {
+ @Override
+ void update(MessageDigest md, Object value) {
+ long longVal = (Long) value;
+ for (int i = 0; i < 8; i++) {
+ md.update((byte) longVal);
+ longVal >>>= 8;
+ }
+ }
+
+ @Override
+ Object encode(byte[] digest) {
+ return ByteBuffer.wrap(digest, 0,
8).order(ByteOrder.LITTLE_ENDIAN).getLong();
+ }
+ },
+ BINARY {
+ @Override
+ void update(MessageDigest md, Object value) {
+ md.update(((ByteBuffer) value).duplicate());
+ }
+
+ @Override
+ Object encode(byte[] digest) {
+ return ByteBuffer.wrap(digest);
+ }
+ };
+
+ abstract void update(MessageDigest md, Object value);
+
+ abstract Object encode(byte[] digest);
+ }
+
+ static boolean isSupported(Type type) {
+ switch (type.typeId()) {
+ case STRING:
+ case INTEGER:
+ case LONG:
+ case BINARY:
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ static Sha256 forType(Type type, byte[] salt) {
+ switch (type.typeId()) {
+ case STRING:
+ return new Sha256(Codec.STRING, salt);
+ case INTEGER:
+ return new Sha256(Codec.INTEGER, salt);
+ case LONG:
+ return new Sha256(Codec.LONG, salt);
+ case BINARY:
+ return new Sha256(Codec.BINARY, salt);
+ default:
+ throw new IllegalArgumentException("sha-256 is not supported for type:
" + type);
+ }
+ }
+
+ private final Codec codec;
+ private final byte[] salt;
+
+ private Sha256(Codec codec, byte[] salt) {
+ this.codec = codec;
+ this.salt = salt != null ? salt.clone() : null;
+ }
+
+ @Override
+ protected Object applyNonNull(Object value) {
+ MessageDigest md = DIGEST.get();
+ md.reset();
+ if (salt != null) {
+ md.update(salt);
+ }
+ codec.update(md, value);
+ return codec.encode(md.digest());
+ }
+}
diff --git a/api/src/main/java/org/apache/iceberg/functions/Sha256Global.java
b/api/src/main/java/org/apache/iceberg/functions/Sha256Global.java
new file mode 100644
index 0000000000..7a284ab002
--- /dev/null
+++ b/api/src/main/java/org/apache/iceberg/functions/Sha256Global.java
@@ -0,0 +1,59 @@
+/*
+ * 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.functions;
+
+import java.io.ObjectStreamException;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.types.Type;
+import org.apache.iceberg.util.SerializableFunction;
+
+/** Hashes values with SHA-256 using a fixed (unsalted) digest. Output is
deterministic. */
+final class Sha256Global<T> implements IcebergFunction<T, T> {
+ static final String NAME = "sha-256-global";
+
+ private static final Sha256Global<?> INSTANCE = new Sha256Global<>();
+
+ @SuppressWarnings("unchecked")
+ static <T> Sha256Global<T> get() {
+ return (Sha256Global<T>) INSTANCE;
+ }
+
+ private Sha256Global() {}
+
+ @Override
+ public String toString() {
+ return NAME;
+ }
+
+ Object writeReplace() throws ObjectStreamException {
+ return SerializationProxies.Sha256GlobalProxy.get();
+ }
+
+ @Override
+ public boolean canBind(Type type) {
+ return Sha256.isSupported(type);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public SerializableFunction<T, T> bind(Type type) {
+ Preconditions.checkArgument(canBind(type), "sha-256 is not supported for
type: %s", type);
+ return (SerializableFunction<T, T>) Sha256.forType(type, null);
+ }
+}
diff --git
a/api/src/main/java/org/apache/iceberg/functions/Sha256QueryLocal.java
b/api/src/main/java/org/apache/iceberg/functions/Sha256QueryLocal.java
new file mode 100644
index 0000000000..deee797f40
--- /dev/null
+++ b/api/src/main/java/org/apache/iceberg/functions/Sha256QueryLocal.java
@@ -0,0 +1,76 @@
+/*
+ * 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.functions;
+
+import java.io.ObjectStreamException;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.types.Type;
+import org.apache.iceberg.util.SerializableFunction;
+
+/**
+ * Hashes values with SHA-256 using a per-query salt. Binding requires the
salt via {@link
+ * #bind(Type, byte[])}; the no-salt variant fails fast so callers can't
accidentally strip the
+ * query-local randomness.
+ */
+final class Sha256QueryLocal<T> implements IcebergFunction<T, T> {
+ static final String NAME = "sha-256-query-local";
+
+ private static final Sha256QueryLocal<?> INSTANCE = new Sha256QueryLocal<>();
+
+ @SuppressWarnings("unchecked")
+ static <T> Sha256QueryLocal<T> get() {
+ return (Sha256QueryLocal<T>) INSTANCE;
+ }
+
+ private Sha256QueryLocal() {}
+
+ @Override
+ public String toString() {
+ return NAME;
+ }
+
+ Object writeReplace() throws ObjectStreamException {
+ return SerializationProxies.Sha256QueryLocalProxy.get();
+ }
+
+ @Override
+ public boolean isSalted() {
+ return true;
+ }
+
+ @Override
+ public boolean canBind(Type type) {
+ return Sha256.isSupported(type);
+ }
+
+ @Override
+ public SerializableFunction<T, T> bind(Type type) {
+ throw new UnsupportedOperationException(
+ "sha-256-query-local requires a salt; call bind(Type, byte[])
instead");
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public SerializableFunction<T, T> bind(Type type, byte[] salt) {
+ Preconditions.checkArgument(canBind(type), "sha-256 is not supported for
type: %s", type);
+ Preconditions.checkArgument(
+ salt != null && salt.length >= 16, "sha-256-query-local salt must be
>= 16 bytes");
+ return (SerializableFunction<T, T>) Sha256.forType(type, salt);
+ }
+}
diff --git a/api/src/main/java/org/apache/iceberg/functions/ShowFirst4.java
b/api/src/main/java/org/apache/iceberg/functions/ShowFirst4.java
new file mode 100644
index 0000000000..46973d9440
--- /dev/null
+++ b/api/src/main/java/org/apache/iceberg/functions/ShowFirst4.java
@@ -0,0 +1,78 @@
+/*
+ * 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.functions;
+
+import java.io.ObjectStreamException;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.types.Type;
+import org.apache.iceberg.util.SerializableFunction;
+
+/** Preserves the first 4 code points of a string, redacts the rest via
mask-alphanum rules. */
+final class ShowFirst4 implements IcebergFunction<CharSequence, CharSequence> {
+ static final String NAME = "show-first-4";
+
+ private static final ShowFirst4 INSTANCE = new ShowFirst4();
+
+ static ShowFirst4 get() {
+ return INSTANCE;
+ }
+
+ private ShowFirst4() {}
+
+ @Override
+ public String toString() {
+ return NAME;
+ }
+
+ Object writeReplace() throws ObjectStreamException {
+ return SerializationProxies.ShowFirst4Proxy.get();
+ }
+
+ @Override
+ public boolean canBind(Type type) {
+ return type.typeId() == Type.TypeID.STRING;
+ }
+
+ @Override
+ public SerializableFunction<CharSequence, CharSequence> bind(Type type) {
+ Preconditions.checkArgument(canBind(type), "show-first-4 requires STRING
type, got %s", type);
+ return ShowFirst4Fn.INSTANCE;
+ }
+
+ private static final class ShowFirst4Fn extends
NullSafeFunction<CharSequence, CharSequence> {
+ static final ShowFirst4Fn INSTANCE = new ShowFirst4Fn();
+
+ @Override
+ protected CharSequence applyNonNull(CharSequence input) {
+ if (Character.codePointCount(input, 0, input.length()) <= 4) {
+ return input.toString();
+ }
+ StringBuilder sb = new StringBuilder(input.length());
+ int cpIndex = 0;
+ int offset = 0;
+ while (offset < input.length()) {
+ int cp = Character.codePointAt(input, offset);
+ sb.appendCodePoint(cpIndex < 4 ? cp : MaskAlphanum.maskCodePoint(cp));
+ offset += Character.charCount(cp);
+ cpIndex++;
+ }
+ return sb.toString();
+ }
+ }
+}
diff --git a/api/src/main/java/org/apache/iceberg/functions/ShowLast4.java
b/api/src/main/java/org/apache/iceberg/functions/ShowLast4.java
new file mode 100644
index 0000000000..2a334c4832
--- /dev/null
+++ b/api/src/main/java/org/apache/iceberg/functions/ShowLast4.java
@@ -0,0 +1,90 @@
+/*
+ * 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.functions;
+
+import java.io.ObjectStreamException;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.types.Type;
+import org.apache.iceberg.util.SerializableFunction;
+
+/** Redacts all but the last 4 code points of a string via mask-alphanum
rules. */
+final class ShowLast4 implements IcebergFunction<CharSequence, CharSequence> {
+ static final String NAME = "show-last-4";
+
+ private static final ShowLast4 INSTANCE = new ShowLast4();
+
+ static ShowLast4 get() {
+ return INSTANCE;
+ }
+
+ private ShowLast4() {}
+
+ @Override
+ public String toString() {
+ return NAME;
+ }
+
+ Object writeReplace() throws ObjectStreamException {
+ return SerializationProxies.ShowLast4Proxy.get();
+ }
+
+ @Override
+ public boolean canBind(Type type) {
+ return type.typeId() == Type.TypeID.STRING;
+ }
+
+ @Override
+ public SerializableFunction<CharSequence, CharSequence> bind(Type type) {
+ Preconditions.checkArgument(canBind(type), "show-last-4 requires STRING
type, got %s", type);
+ return ShowLast4Fn.INSTANCE;
+ }
+
+ private static final class ShowLast4Fn extends
NullSafeFunction<CharSequence, CharSequence> {
+ static final ShowLast4Fn INSTANCE = new ShowLast4Fn();
+
+ @Override
+ protected CharSequence applyNonNull(CharSequence input) {
+ // Single pass: walk the string while remembering the last 4 code-point
start offsets.
+ // When done, everything before the oldest remembered offset is masked;
everything from
+ // that offset onward is kept verbatim.
+ int[] lastFourStarts = new int[4];
+ int count = 0;
+ int offset = 0;
+ while (offset < input.length()) {
+ lastFourStarts[count % 4] = offset;
+ int cp = Character.codePointAt(input, offset);
+ offset += Character.charCount(cp);
+ count++;
+ }
+ if (count <= 4) {
+ return input.toString();
+ }
+ int keepFromOffset = lastFourStarts[count % 4];
+ StringBuilder sb = new StringBuilder(input.length());
+ int maskOffset = 0;
+ while (maskOffset < keepFromOffset) {
+ int cp = Character.codePointAt(input, maskOffset);
+ sb.appendCodePoint(MaskAlphanum.maskCodePoint(cp));
+ maskOffset += Character.charCount(cp);
+ }
+ sb.append(input, keepFromOffset, input.length());
+ return sb.toString();
+ }
+ }
+}
diff --git
a/api/src/main/java/org/apache/iceberg/functions/TruncateTemporal.java
b/api/src/main/java/org/apache/iceberg/functions/TruncateTemporal.java
new file mode 100644
index 0000000000..e526c8651a
--- /dev/null
+++ b/api/src/main/java/org/apache/iceberg/functions/TruncateTemporal.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.functions;
+
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import org.apache.iceberg.types.Type;
+import org.apache.iceberg.util.DateTimeUtil;
+
+/** Truncates date/timestamp values to the first instant of their year or
month. */
+final class TruncateTemporal extends NullSafeFunction<Object, Object> {
+
+ enum Unit {
+ YEAR,
+ MONTH
+ }
+
+ private enum Storage {
+ DATE_DAYS,
+ TIMESTAMP_MICROS,
+ TIMESTAMP_NANOS
+ }
+
+ static final TruncateTemporal DATE_YEAR = new TruncateTemporal(Unit.YEAR,
Storage.DATE_DAYS);
+ static final TruncateTemporal DATE_MONTH = new TruncateTemporal(Unit.MONTH,
Storage.DATE_DAYS);
+ static final TruncateTemporal TIMESTAMP_YEAR =
+ new TruncateTemporal(Unit.YEAR, Storage.TIMESTAMP_MICROS);
+ static final TruncateTemporal TIMESTAMP_MONTH =
+ new TruncateTemporal(Unit.MONTH, Storage.TIMESTAMP_MICROS);
+ static final TruncateTemporal TIMESTAMP_NANO_YEAR =
+ new TruncateTemporal(Unit.YEAR, Storage.TIMESTAMP_NANOS);
+ static final TruncateTemporal TIMESTAMP_NANO_MONTH =
+ new TruncateTemporal(Unit.MONTH, Storage.TIMESTAMP_NANOS);
+
+ static TruncateTemporal forType(Unit unit, Type type) {
+ switch (type.typeId()) {
+ case DATE:
+ return unit == Unit.YEAR ? DATE_YEAR : DATE_MONTH;
+ case TIMESTAMP:
+ return unit == Unit.YEAR ? TIMESTAMP_YEAR : TIMESTAMP_MONTH;
+ case TIMESTAMP_NANO:
+ return unit == Unit.YEAR ? TIMESTAMP_NANO_YEAR : TIMESTAMP_NANO_MONTH;
+ default:
+ throw new IllegalArgumentException("Unsupported type for truncate: " +
type);
+ }
+ }
+
+ private final Unit unit;
+ private final Storage storage;
+
+ private TruncateTemporal(Unit unit, Storage storage) {
+ this.unit = unit;
+ this.storage = storage;
+ }
+
+ @Override
+ protected Object applyNonNull(Object value) {
+ switch (storage) {
+ case DATE_DAYS:
+ LocalDate date = DateTimeUtil.dateFromDays((Integer) value);
+ return DateTimeUtil.daysFromDate(truncateDate(date));
+ case TIMESTAMP_MICROS:
+ LocalDateTime tsMicros = DateTimeUtil.timestampFromMicros((Long)
value);
+ return DateTimeUtil.microsFromTimestamp(truncateTimestamp(tsMicros));
+ case TIMESTAMP_NANOS:
+ LocalDateTime tsNanos = DateTimeUtil.timestampFromNanos((Long) value);
+ return DateTimeUtil.nanosFromTimestamp(truncateTimestamp(tsNanos));
+ default:
+ throw new IllegalStateException("unreachable: " + storage);
+ }
+ }
+
+ private LocalDate truncateDate(LocalDate date) {
+ return unit == Unit.YEAR ? date.withMonth(1).withDayOfMonth(1) :
date.withDayOfMonth(1);
+ }
+
+ private LocalDateTime truncateTimestamp(LocalDateTime ts) {
+ LocalDateTime truncated =
+ unit == Unit.YEAR ? ts.withMonth(1).withDayOfMonth(1) :
ts.withDayOfMonth(1);
+ return truncated.with(LocalTime.MIDNIGHT);
+ }
+}
diff --git
a/api/src/main/java/org/apache/iceberg/functions/TruncateToMonth.java
b/api/src/main/java/org/apache/iceberg/functions/TruncateToMonth.java
new file mode 100644
index 0000000000..956cca38df
--- /dev/null
+++ b/api/src/main/java/org/apache/iceberg/functions/TruncateToMonth.java
@@ -0,0 +1,67 @@
+/*
+ * 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.functions;
+
+import java.io.ObjectStreamException;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.types.Type;
+import org.apache.iceberg.util.SerializableFunction;
+
+/** Truncates date or timestamp values to the first instant of their month. */
+final class TruncateToMonth<T> implements IcebergFunction<T, T> {
+ static final String NAME = "truncate-to-month";
+
+ private static final TruncateToMonth<?> INSTANCE = new TruncateToMonth<>();
+
+ @SuppressWarnings("unchecked")
+ static <T> TruncateToMonth<T> get() {
+ return (TruncateToMonth<T>) INSTANCE;
+ }
+
+ private TruncateToMonth() {}
+
+ @Override
+ public String toString() {
+ return NAME;
+ }
+
+ Object writeReplace() throws ObjectStreamException {
+ return SerializationProxies.TruncateToMonthProxy.get();
+ }
+
+ @Override
+ public boolean canBind(Type type) {
+ switch (type.typeId()) {
+ case DATE:
+ case TIMESTAMP:
+ case TIMESTAMP_NANO:
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public SerializableFunction<T, T> bind(Type type) {
+ Preconditions.checkArgument(
+ canBind(type), "truncate-to-month is not supported for type: %s",
type);
+ return (SerializableFunction<T, T>)
TruncateTemporal.forType(TruncateTemporal.Unit.MONTH, type);
+ }
+}
diff --git a/api/src/main/java/org/apache/iceberg/functions/TruncateToYear.java
b/api/src/main/java/org/apache/iceberg/functions/TruncateToYear.java
new file mode 100644
index 0000000000..1a63049404
--- /dev/null
+++ b/api/src/main/java/org/apache/iceberg/functions/TruncateToYear.java
@@ -0,0 +1,67 @@
+/*
+ * 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.functions;
+
+import java.io.ObjectStreamException;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.types.Type;
+import org.apache.iceberg.util.SerializableFunction;
+
+/** Truncates date or timestamp values to the first instant of their year. */
+final class TruncateToYear<T> implements IcebergFunction<T, T> {
+ static final String NAME = "truncate-to-year";
+
+ private static final TruncateToYear<?> INSTANCE = new TruncateToYear<>();
+
+ @SuppressWarnings("unchecked")
+ static <T> TruncateToYear<T> get() {
+ return (TruncateToYear<T>) INSTANCE;
+ }
+
+ private TruncateToYear() {}
+
+ @Override
+ public String toString() {
+ return NAME;
+ }
+
+ Object writeReplace() throws ObjectStreamException {
+ return SerializationProxies.TruncateToYearProxy.get();
+ }
+
+ @Override
+ public boolean canBind(Type type) {
+ switch (type.typeId()) {
+ case DATE:
+ case TIMESTAMP:
+ case TIMESTAMP_NANO:
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public SerializableFunction<T, T> bind(Type type) {
+ Preconditions.checkArgument(
+ canBind(type), "truncate-to-year is not supported for type: %s", type);
+ return (SerializableFunction<T, T>)
TruncateTemporal.forType(TruncateTemporal.Unit.YEAR, type);
+ }
+}
diff --git
a/api/src/main/java/org/apache/iceberg/functions/UnknownFunction.java
b/api/src/main/java/org/apache/iceberg/functions/UnknownFunction.java
new file mode 100644
index 0000000000..7a56050721
--- /dev/null
+++ b/api/src/main/java/org/apache/iceberg/functions/UnknownFunction.java
@@ -0,0 +1,75 @@
+/*
+ * 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.functions;
+
+import java.util.Objects;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.types.Type;
+import org.apache.iceberg.util.SerializableFunction;
+
+/**
+ * Preserves a function with a discriminator string this client doesn't
recognize so that newer
+ * server-side function types don't break parsing. Callers that intend to
enforce the function
+ * (engine-side rules) must fail closed when they encounter this â silent
skipping would leak
+ * unmasked data.
+ */
+public final class UnknownFunction implements IcebergFunction<Object, Object> {
+ private final String functionName;
+
+ UnknownFunction(String functionName) {
+ Preconditions.checkArgument(functionName != null, "Invalid function name:
null");
+ this.functionName = functionName;
+ }
+
+ @Override
+ public boolean canBind(Type type) {
+ return false;
+ }
+
+ @Override
+ public SerializableFunction<Object, Object> bind(Type type) {
+ throw new IllegalArgumentException(
+ "Cannot bind unknown function '"
+ + functionName
+ + "': this client does not recognize the function. Upgrade the
client or remove the "
+ + "function from the server-side policy.");
+ }
+
+ @Override
+ public String toString() {
+ return functionName;
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (this == other) {
+ return true;
+ } else if (!(other instanceof UnknownFunction)) {
+ return false;
+ }
+
+ UnknownFunction that = (UnknownFunction) other;
+ return functionName.equals(that.functionName);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hashCode(functionName);
+ }
+}
diff --git
a/api/src/test/java/org/apache/iceberg/functions/TestFunctionSerialization.java
b/api/src/test/java/org/apache/iceberg/functions/TestFunctionSerialization.java
new file mode 100644
index 0000000000..029c830807
--- /dev/null
+++
b/api/src/test/java/org/apache/iceberg/functions/TestFunctionSerialization.java
@@ -0,0 +1,91 @@
+/*
+ * 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.functions;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.apache.iceberg.TestHelpers;
+import org.apache.iceberg.types.Type;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.SerializableFunction;
+import org.junit.jupiter.api.Test;
+
+class TestFunctionSerialization {
+ private static final Type[] TYPES =
+ new Type[] {
+ Types.BooleanType.get(),
+ Types.IntegerType.get(),
+ Types.LongType.get(),
+ Types.FloatType.get(),
+ Types.DoubleType.get(),
+ Types.StringType.get(),
+ Types.DateType.get(),
+ Types.TimeType.get(),
+ Types.TimestampType.withoutZone(),
+ Types.TimestampType.withZone(),
+ Types.TimestampNanoType.withoutZone(),
+ Types.BinaryType.get(),
+ Types.FixedType.ofLength(4),
+ Types.DecimalType.of(9, 4),
+ Types.UUIDType.get(),
+ Types.StructType.of(
+ Types.NestedField.optional(1, "id", Types.IntegerType.get()),
+ Types.NestedField.optional(2, "payload", Types.BinaryType.get())),
+ };
+
+ private static final IcebergFunction<?, ?>[] FUNCTIONS =
+ new IcebergFunction<?, ?>[] {
+ IcebergFunctions.maskAlphanum(),
+ IcebergFunctions.maskToFixedValue(),
+ IcebergFunctions.replaceWithNull(),
+ IcebergFunctions.showFirst4(),
+ IcebergFunctions.showLast4(),
+ IcebergFunctions.truncateToYear(),
+ IcebergFunctions.truncateToMonth(),
+ IcebergFunctions.sha256Global(),
+ IcebergFunctions.sha256QueryLocal()
+ };
+
+ @Test
+ void functionsDeserializeToTheSameInstance() throws Exception {
+ for (IcebergFunction<?, ?> function : FUNCTIONS) {
+ assertThat(TestHelpers.roundTripSerialize(function)).isSameAs(function);
+ }
+ }
+
+ @Test
+ void unknownFunctionDeserializesToAnEqualFunction() throws Exception {
+ IcebergFunction<?, ?> unknown =
IcebergFunctions.fromString("future-mask-v2");
+ assertThat(TestHelpers.roundTripSerialize(unknown)).isEqualTo(unknown);
+ }
+
+ @Test
+ void boundFunctionsAreSerializable() throws Exception {
+ byte[] salt = new byte[16];
+ for (Type type : TYPES) {
+ for (IcebergFunction<?, ?> function : FUNCTIONS) {
+ if (function.canBind(type)) {
+ SerializableFunction<?, ?> func =
+ function.isSalted() ? function.bind(type, salt) :
function.bind(type);
+
assertThat(func).isInstanceOf(TestHelpers.roundTripSerialize(func).getClass());
+ }
+ }
+ }
+ }
+}
diff --git
a/api/src/test/java/org/apache/iceberg/functions/TestIcebergFunctions.java
b/api/src/test/java/org/apache/iceberg/functions/TestIcebergFunctions.java
new file mode 100644
index 0000000000..721cf8e93b
--- /dev/null
+++ b/api/src/test/java/org/apache/iceberg/functions/TestIcebergFunctions.java
@@ -0,0 +1,558 @@
+/*
+ * 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.functions;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.math.BigDecimal;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.ZoneOffset;
+import java.util.Arrays;
+import org.apache.iceberg.StructLike;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.DateTimeUtil;
+import org.apache.iceberg.util.SerializableFunction;
+import org.junit.jupiter.api.Test;
+
+public class TestIcebergFunctions {
+
+ @Test
+ public void maskAlphanumSpecExample() {
+ SerializableFunction<CharSequence, CharSequence> fn =
+ IcebergFunctions.maskAlphanum().bind(Types.StringType.get());
+
assertThat(fn.apply("[email protected]")).isEqualTo("[email protected]");
+ }
+
+ @Test
+ public void maskAlphanumPreservedPunctuation() {
+ SerializableFunction<CharSequence, CharSequence> fn =
+ IcebergFunctions.maskAlphanum().bind(Types.StringType.get());
+ assertThat(fn.apply("(555) 123-4567")).isEqualTo("(nnn)xnnn-nnnn");
+ assertThat(fn.apply("a.b,c")).isEqualTo("x.x,x");
+ }
+
+ @Test
+ public void maskAlphanumSupplementaryCharacter() {
+ SerializableFunction<CharSequence, CharSequence> fn =
+ IcebergFunctions.maskAlphanum().bind(Types.StringType.get());
+ assertThat(fn.apply("ađ1")).isEqualTo("xxn");
+ }
+
+ @Test
+ public void maskAlphanumNullInNullOut() {
+ SerializableFunction<CharSequence, CharSequence> fn =
+ IcebergFunctions.maskAlphanum().bind(Types.StringType.get());
+ assertThat(fn.apply(null)).isNull();
+ }
+
+ @Test
+ public void maskAlphanumEmptyString() {
+ SerializableFunction<CharSequence, CharSequence> fn =
+ IcebergFunctions.maskAlphanum().bind(Types.StringType.get());
+ assertThat(fn.apply("")).isEqualTo("");
+ }
+
+ @Test
+ public void stringFunctionsAcceptAnyCharSequence() {
+ CharSequence email = new StringBuilder("[email protected]");
+
assertThat(IcebergFunctions.maskAlphanum().bind(Types.StringType.get()).apply(email))
+ .hasToString("[email protected]");
+
assertThat(IcebergFunctions.showFirst4().bind(Types.StringType.get()).apply(email))
+ .hasToString("[email protected]");
+
assertThat(IcebergFunctions.showLast4().bind(Types.StringType.get()).apply(email))
+ .hasToString("[email protected]");
+
assertThat(IcebergFunctions.sha256Global().bind(Types.StringType.get()).apply(email))
+ .isEqualTo(
+ IcebergFunctions.sha256Global()
+ .bind(Types.StringType.get())
+ .apply("[email protected]"));
+ }
+
+ @Test
+ public void showFirst4SpecExample() {
+ SerializableFunction<CharSequence, CharSequence> fn =
+ IcebergFunctions.showFirst4().bind(Types.StringType.get());
+
assertThat(fn.apply("[email protected]")).isEqualTo("[email protected]");
+ }
+
+ @Test
+ public void showFirst4FourOrFewerReturnedUnchanged() {
+ SerializableFunction<CharSequence, CharSequence> fn =
+ IcebergFunctions.showFirst4().bind(Types.StringType.get());
+ assertThat(fn.apply("abcd")).isEqualTo("abcd");
+ assertThat(fn.apply("ab")).isEqualTo("ab");
+ assertThat(fn.apply("")).isEqualTo("");
+ }
+
+ @Test
+ public void showFirst4CountsSupplementaryCharactersOnce() {
+ SerializableFunction<CharSequence, CharSequence> fn =
+ IcebergFunctions.showFirst4().bind(Types.StringType.get());
+ assertThat(fn.apply("đbđd1")).isEqualTo("đbđdn");
+ }
+
+ @Test
+ public void showFirst4FourOrFewerReturnsString() {
+ SerializableFunction<CharSequence, CharSequence> fn =
+ IcebergFunctions.showFirst4().bind(Types.StringType.get());
+ assertThat(fn.apply(new
StringBuilder("ab"))).isInstanceOf(String.class).isEqualTo("ab");
+ }
+
+ @Test
+ public void showLast4SpecExample() {
+ SerializableFunction<CharSequence, CharSequence> fn =
+ IcebergFunctions.showLast4().bind(Types.StringType.get());
+
assertThat(fn.apply("4111-1111-1111-4444")).isEqualTo("nnnn-nnnn-nnnn-4444");
+ }
+
+ @Test
+ public void showLast4FourOrFewerReturnedUnchanged() {
+ SerializableFunction<CharSequence, CharSequence> fn =
+ IcebergFunctions.showLast4().bind(Types.StringType.get());
+ assertThat(fn.apply("abcd")).isEqualTo("abcd");
+ assertThat(fn.apply("ab")).isEqualTo("ab");
+ }
+
+ @Test
+ public void showLast4CountsSupplementaryCharactersOnce() {
+ SerializableFunction<CharSequence, CharSequence> fn =
+ IcebergFunctions.showLast4().bind(Types.StringType.get());
+ assertThat(fn.apply("1đbđd")).isEqualTo("nđbđd");
+ }
+
+ @Test
+ public void showLast4FourOrFewerReturnsString() {
+ SerializableFunction<CharSequence, CharSequence> fn =
+ IcebergFunctions.showLast4().bind(Types.StringType.get());
+ assertThat(fn.apply(new
StringBuilder("ab"))).isInstanceOf(String.class).isEqualTo("ab");
+ }
+
+ @Test
+ public void replaceWithNullAlwaysReturnsNull() {
+ SerializableFunction<Object, Object> fn =
+ IcebergFunctions.replaceWithNull().bind(Types.IntegerType.get());
+ assertThat(fn.apply(42)).isNull();
+ assertThat(fn.apply(null)).isNull();
+
+ SerializableFunction<Object, Object> strFn =
+ IcebergFunctions.replaceWithNull().bind(Types.StringType.get());
+ assertThat(strFn.apply("hello")).isNull();
+ }
+
+ @Test
+ public void maskToFixedValueString() {
+ SerializableFunction<Object, Object> fn =
+ IcebergFunctions.maskToFixedValue().bind(Types.StringType.get());
+ assertThat(fn.apply("anything")).isEqualTo("XXXXXXXX");
+ }
+
+ @Test
+ public void maskToFixedValueInt() {
+ SerializableFunction<Object, Object> fn =
+ IcebergFunctions.maskToFixedValue().bind(Types.IntegerType.get());
+ assertThat(fn.apply(42)).isEqualTo(0);
+ }
+
+ @Test
+ public void maskToFixedValueLong() {
+ SerializableFunction<Object, Object> fn =
+ IcebergFunctions.maskToFixedValue().bind(Types.LongType.get());
+ assertThat(fn.apply(42L)).isEqualTo(0L);
+ }
+
+ @Test
+ public void maskToFixedValueDouble() {
+ SerializableFunction<Object, Object> fn =
+ IcebergFunctions.maskToFixedValue().bind(Types.DoubleType.get());
+ assertThat(fn.apply(3.14)).isEqualTo(0.0d);
+ }
+
+ @Test
+ public void maskToFixedValueBoolean() {
+ SerializableFunction<Object, Object> fn =
+ IcebergFunctions.maskToFixedValue().bind(Types.BooleanType.get());
+ assertThat(fn.apply(true)).isEqualTo(false);
+ }
+
+ @Test
+ public void maskToFixedValueDate() {
+ int input = DateTimeUtil.daysFromDate(LocalDate.of(2024, 7, 15));
+ int expected = DateTimeUtil.daysFromDate(LocalDate.of(1970, 1, 1));
+ SerializableFunction<Object, Object> fn =
+ IcebergFunctions.maskToFixedValue().bind(Types.DateType.get());
+ assertThat(fn.apply(input)).isEqualTo(expected);
+ }
+
+ @Test
+ public void maskToFixedValueTimestamp() {
+ long input =
+ LocalDateTime.of(2024, 7, 15, 13, 45,
30).toEpochSecond(ZoneOffset.UTC) * 1_000_000L;
+ long expected = LocalDateTime.of(1970, 1, 1, 0,
0).toEpochSecond(ZoneOffset.UTC) * 1_000_000L;
+ SerializableFunction<Object, Object> fn =
+
IcebergFunctions.maskToFixedValue().bind(Types.TimestampType.withZone());
+ assertThat(fn.apply(input)).isEqualTo(expected);
+ }
+
+ @Test
+ public void maskToFixedValueBinary() {
+ SerializableFunction<Object, Object> fn =
+ IcebergFunctions.maskToFixedValue().bind(Types.BinaryType.get());
+ ByteBuffer result = (ByteBuffer) fn.apply(ByteBuffer.wrap(new byte[] {1,
2, 3}));
+ assertThat(result.remaining()).isEqualTo(0);
+ }
+
+ @Test
+ public void maskToFixedValueStructWithBinaryField() {
+ Types.StructType struct =
+ Types.StructType.of(
+ Types.NestedField.optional(1, "id", Types.IntegerType.get()),
+ Types.NestedField.optional(2, "payload", Types.BinaryType.get()));
+ SerializableFunction<Object, Object> fn =
IcebergFunctions.maskToFixedValue().bind(struct);
+ StructLike result = (StructLike) fn.apply(null);
+ assertThat(result.get(0, Integer.class)).isEqualTo(0);
+ assertThat(result.get(1, ByteBuffer.class).remaining()).isEqualTo(0);
+ }
+
+ @Test
+ public void maskToFixedValueDecimal() {
+ SerializableFunction<Object, Object> fn =
+ IcebergFunctions.maskToFixedValue().bind(Types.DecimalType.of(10, 2));
+ BigDecimal result = (BigDecimal) fn.apply(new BigDecimal("12.34"));
+ assertThat(result.compareTo(BigDecimal.ZERO)).isEqualTo(0);
+ assertThat(result.scale()).isEqualTo(2);
+ }
+
+ @Test
+ public void maskToFixedValueCanBindStructOfSupportedTypes() {
+ Types.StructType struct =
+ Types.StructType.of(
+ Types.NestedField.optional(1, "id", Types.IntegerType.get()),
+ Types.NestedField.optional(
+ 2,
+ "address",
+ Types.StructType.of(
+ Types.NestedField.optional(3, "city",
Types.StringType.get()))));
+ assertThat(IcebergFunctions.maskToFixedValue().canBind(struct)).isTrue();
+ }
+
+ @Test
+ public void maskToFixedValueCannotBindStructWithUnsupportedNestedField() {
+ Types.StructType struct =
+ Types.StructType.of(
+ Types.NestedField.optional(1, "id", Types.IntegerType.get()),
+ Types.NestedField.optional(
+ 2,
+ "address",
+ Types.StructType.of(
+ Types.NestedField.optional(3, "location",
Types.GeometryType.crs84()))));
+ assertThat(IcebergFunctions.maskToFixedValue().canBind(struct)).isFalse();
+ assertThatThrownBy(() -> IcebergFunctions.maskToFixedValue().bind(struct))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("mask-to-fixed-value is not supported for type: " +
struct);
+ }
+
+ @Test
+ public void maskToFixedValueNullReturnsFixedValue() {
+ SerializableFunction<Object, Object> fn =
+ IcebergFunctions.maskToFixedValue().bind(Types.IntegerType.get());
+ assertThat(fn.apply(null)).isEqualTo(0);
+ }
+
+ @Test
+ public void truncateToYearDate() {
+ int input = (int) LocalDate.of(2024, 7, 15).toEpochDay();
+ int expected = (int) LocalDate.of(2024, 1, 1).toEpochDay();
+ SerializableFunction<Object, Object> fn =
+ IcebergFunctions.truncateToYear().bind(Types.DateType.get());
+ assertThat(fn.apply(input)).isEqualTo(expected);
+ }
+
+ @Test
+ public void truncateToMonthDate() {
+ int input = (int) LocalDate.of(2024, 7, 15).toEpochDay();
+ int expected = (int) LocalDate.of(2024, 7, 1).toEpochDay();
+ SerializableFunction<Object, Object> fn =
+ IcebergFunctions.truncateToMonth().bind(Types.DateType.get());
+ assertThat(fn.apply(input)).isEqualTo(expected);
+ }
+
+ @Test
+ public void truncateToYearTimestamp() {
+ long inputMicros =
+ LocalDateTime.of(2024, 7, 15, 13, 45,
30).toEpochSecond(ZoneOffset.UTC) * 1_000_000L;
+ long expectedMicros =
+ LocalDateTime.of(2024, 1, 1, 0, 0, 0).toEpochSecond(ZoneOffset.UTC) *
1_000_000L;
+ SerializableFunction<Object, Object> fn =
+ IcebergFunctions.truncateToYear().bind(Types.TimestampType.withZone());
+ assertThat(fn.apply(inputMicros)).isEqualTo(expectedMicros);
+ }
+
+ @Test
+ public void truncateToMonthTimestamp() {
+ long inputMicros =
+ LocalDateTime.of(2024, 7, 15, 13, 45,
30).toEpochSecond(ZoneOffset.UTC) * 1_000_000L;
+ long expectedMicros =
+ LocalDateTime.of(2024, 7, 1, 0, 0, 0).toEpochSecond(ZoneOffset.UTC) *
1_000_000L;
+ SerializableFunction<Object, Object> fn =
+
IcebergFunctions.truncateToMonth().bind(Types.TimestampType.withZone());
+ assertThat(fn.apply(inputMicros)).isEqualTo(expectedMicros);
+ }
+
+ @Test
+ public void truncateToYearTimestampNanoTz() {
+ long inputNanos =
+ LocalDateTime.of(2024, 7, 15, 13, 45,
30).toEpochSecond(ZoneOffset.UTC) * 1_000_000_000L;
+ long expectedNanos =
+ LocalDateTime.of(2024, 1, 1, 0, 0, 0).toEpochSecond(ZoneOffset.UTC) *
1_000_000_000L;
+ SerializableFunction<Object, Object> fn =
+
IcebergFunctions.truncateToYear().bind(Types.TimestampNanoType.withZone());
+ assertThat(fn.apply(inputNanos)).isEqualTo(expectedNanos);
+ }
+
+ @Test
+ public void truncateToMonthTimestampNanoTz() {
+ long inputNanos =
+ LocalDateTime.of(2024, 7, 15, 13, 45,
30).toEpochSecond(ZoneOffset.UTC) * 1_000_000_000L;
+ long expectedNanos =
+ LocalDateTime.of(2024, 7, 1, 0, 0, 0).toEpochSecond(ZoneOffset.UTC) *
1_000_000_000L;
+ SerializableFunction<Object, Object> fn =
+
IcebergFunctions.truncateToMonth().bind(Types.TimestampNanoType.withZone());
+ assertThat(fn.apply(inputNanos)).isEqualTo(expectedNanos);
+ }
+
+ @Test
+ public void sha256GlobalStringIsDeterministic() {
+ SerializableFunction<Object, Object> fn =
+ IcebergFunctions.sha256Global().bind(Types.StringType.get());
+ String first = (String) fn.apply("hello");
+ String second = (String) fn.apply("hello");
+ assertThat(first).isEqualTo(second);
+
assertThat(first).isEqualTo("2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824");
+ }
+
+ @Test
+ public void sha256GlobalBinaryReturns32Bytes() {
+ SerializableFunction<Object, Object> fn =
+ IcebergFunctions.sha256Global().bind(Types.BinaryType.get());
+ ByteBuffer result = (ByteBuffer) fn.apply(ByteBuffer.wrap(new byte[] {1,
2, 3}));
+ assertThat(result.remaining()).isEqualTo(32);
+ }
+
+ @Test
+ public void sha256GlobalIntegerUsesLittleEndian() throws
NoSuchAlgorithmException {
+ SerializableFunction<Object, Object> fn =
+ IcebergFunctions.sha256Global().bind(Types.IntegerType.get());
+ byte[] input = littleEndian(4).putInt(42).array();
+ assertThat(fn.apply(42)).isEqualTo(sha256LittleEndian(input).getInt());
+ }
+
+ @Test
+ public void sha256GlobalLongUsesLittleEndian() throws
NoSuchAlgorithmException {
+ IcebergFunction<Long, Long> sha256 = IcebergFunctions.sha256Global();
+ SerializableFunction<Long, Long> fn = sha256.bind(Types.LongType.get());
+ byte[] input = littleEndian(8).putLong(42L).array();
+ assertThat(fn.apply(42L)).isEqualTo(sha256LittleEndian(input).getLong());
+ }
+
+ @Test
+ public void sha256QueryLocalPrependsSalt() throws NoSuchAlgorithmException {
+ byte[] salt = new byte[16];
+ Arrays.fill(salt, (byte) 7);
+ SerializableFunction<Object, Object> fn =
+ IcebergFunctions.sha256QueryLocal().bind(Types.LongType.get(), salt);
+ byte[] input = littleEndian(8).putLong(42L).array();
+ assertThat(fn.apply(42L)).isEqualTo(sha256LittleEndian(salt,
input).getLong());
+ }
+
+ @Test
+ public void sha256QueryLocalBindWithoutSaltIsUnsupported() {
+ assertThatThrownBy(() ->
IcebergFunctions.sha256QueryLocal().bind(Types.StringType.get()))
+ .isInstanceOf(UnsupportedOperationException.class)
+ .hasMessageContaining("requires a salt");
+ }
+
+ @Test
+ public void bindWithSaltOnUnsaltedFunctionIsUnsupported() {
+ assertThatThrownBy(
+ () -> IcebergFunctions.sha256Global().bind(Types.StringType.get(),
new byte[16]))
+ .isInstanceOf(UnsupportedOperationException.class)
+ .hasMessageContaining("does not accept a salt");
+ }
+
+ @Test
+ public void sha256QueryLocalDiffersWithDifferentSalt() {
+ byte[] saltA = new byte[16];
+ byte[] saltB = new byte[16];
+ Arrays.fill(saltA, (byte) 1);
+ Arrays.fill(saltB, (byte) 2);
+ SerializableFunction<Object, Object> fnA =
+ IcebergFunctions.sha256QueryLocal().bind(Types.StringType.get(),
saltA);
+ SerializableFunction<Object, Object> fnB =
+ IcebergFunctions.sha256QueryLocal().bind(Types.StringType.get(),
saltB);
+ assertThat(fnA.apply("hello")).isNotEqualTo(fnB.apply("hello"));
+ }
+
+ @Test
+ public void sha256QueryLocalSaltMustBeAtLeast16Bytes() {
+ assertThatThrownBy(
+ () ->
IcebergFunctions.sha256QueryLocal().bind(Types.StringType.get(), new byte[15]))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("16 bytes");
+ }
+
+ @Test
+ public void bindRejectsMaskAlphanumOnNonString() {
+ assertThatThrownBy(() ->
IcebergFunctions.maskAlphanum().bind(Types.IntegerType.get()))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("STRING");
+ }
+
+ @Test
+ public void bindRejectsTruncateOnUnsupportedType() {
+ assertThatThrownBy(() ->
IcebergFunctions.truncateToYear().bind(Types.StringType.get()))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("not supported for type");
+ }
+
+ @Test
+ public void bindFailsClosedOnUnknownFunction() {
+ assertThatThrownBy(() -> new
UnknownFunction("future-mask-v2").bind(Types.StringType.get()))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("future-mask-v2");
+ }
+
+ @Test
+ public void sha256NullInNullOut() {
+ SerializableFunction<Object, Object> fn =
+ IcebergFunctions.sha256Global().bind(Types.StringType.get());
+ assertThat(fn.apply(null)).isNull();
+ }
+
+ @Test
+ public void truncateNullInNullOut() {
+ SerializableFunction<Object, Object> fn =
+ IcebergFunctions.truncateToYear().bind(Types.DateType.get());
+ assertThat(fn.apply(null)).isNull();
+ }
+
+ @Test
+ public void toStringReturnsFunctionName() {
+
assertThat(IcebergFunctions.maskAlphanum().toString()).isEqualTo("mask-alphanum");
+
assertThat(IcebergFunctions.maskToFixedValue().toString()).isEqualTo("mask-to-fixed-value");
+
assertThat(IcebergFunctions.replaceWithNull().toString()).isEqualTo("replace-with-null");
+
assertThat(IcebergFunctions.showFirst4().toString()).isEqualTo("show-first-4");
+
assertThat(IcebergFunctions.showLast4().toString()).isEqualTo("show-last-4");
+
assertThat(IcebergFunctions.truncateToYear().toString()).isEqualTo("truncate-to-year");
+
assertThat(IcebergFunctions.truncateToMonth().toString()).isEqualTo("truncate-to-month");
+
assertThat(IcebergFunctions.sha256Global().toString()).isEqualTo("sha-256-global");
+
assertThat(IcebergFunctions.sha256QueryLocal().toString()).isEqualTo("sha-256-query-local");
+ }
+
+ @Test
+ public void fromStringRoundTripsEveryFunction() {
+ IcebergFunction<?, ?>[] functions =
+ new IcebergFunction<?, ?>[] {
+ IcebergFunctions.maskAlphanum(),
+ IcebergFunctions.maskToFixedValue(),
+ IcebergFunctions.replaceWithNull(),
+ IcebergFunctions.showFirst4(),
+ IcebergFunctions.showLast4(),
+ IcebergFunctions.truncateToYear(),
+ IcebergFunctions.truncateToMonth(),
+ IcebergFunctions.sha256Global(),
+ IcebergFunctions.sha256QueryLocal()
+ };
+
+ for (IcebergFunction<?, ?> expected : functions) {
+
assertThat(IcebergFunctions.fromString(expected.toString())).isSameAs(expected);
+ }
+ }
+
+ @Test
+ public void fromStringIsCaseInsensitive() {
+
assertThat(IcebergFunctions.fromString("SHOW-LAST-4")).isSameAs(IcebergFunctions.showLast4());
+ }
+
+ @Test
+ public void fromStringPreservesUnknownFunction() {
+ IcebergFunction<?, ?> function =
IcebergFunctions.fromString("future-mask-v2");
+ assertThat(function).isInstanceOf(UnknownFunction.class);
+ assertThat(function.toString()).isEqualTo("future-mask-v2");
+ assertThat(function.canBind(Types.StringType.get())).isFalse();
+ }
+
+ @Test
+ public void onlyQueryLocalSha256IsSalted() {
+
assertThat(IcebergFunctions.fromString("sha-256-query-local").isSalted()).isTrue();
+
assertThat(IcebergFunctions.fromString("sha-256-global").isSalted()).isFalse();
+ }
+
+ @Test
+ public void factoryMethodsReturnSingletons() {
+
assertThat(IcebergFunctions.maskAlphanum()).isSameAs(IcebergFunctions.maskAlphanum());
+ }
+
+ @Test
+ public void notEqualIfFunctionDiffers() {
+
assertThat(IcebergFunctions.maskAlphanum()).isNotEqualTo(IcebergFunctions.showLast4());
+ }
+
+ @Test
+ public void equalsIsSymmetricAcrossFunctionTypes() {
+ // An unknown function reporting a known name must not compare equal to
that known function in
+ // either direction: equality is by class, not by the reported name.
+ IcebergFunction<?, ?> known = IcebergFunctions.maskAlphanum();
+ IcebergFunction<?, ?> spoofed = new UnknownFunction(known.toString());
+ assertThat(spoofed.toString()).isEqualTo(known.toString());
+ assertThat(spoofed).isNotEqualTo(known);
+ assertThat(known).isNotEqualTo(spoofed);
+ }
+
+ @Test
+ public void unknownFunctionsWithTheSameNameAreEqual() {
+ assertThat(IcebergFunctions.fromString("future-a"))
+ .isEqualTo(IcebergFunctions.fromString("future-a"))
+ .hasSameHashCodeAs(IcebergFunctions.fromString("future-a"));
+ }
+
+ @Test
+ public void unknownFunctionsDifferByName() {
+ assertThat(IcebergFunctions.fromString("future-a"))
+ .isNotEqualTo(IcebergFunctions.fromString("future-b"));
+ }
+
+ private static ByteBuffer littleEndian(int size) {
+ return ByteBuffer.allocate(size).order(ByteOrder.LITTLE_ENDIAN);
+ }
+
+ private static ByteBuffer sha256LittleEndian(byte[]... parts) throws
NoSuchAlgorithmException {
+ MessageDigest md = MessageDigest.getInstance("SHA-256");
+ for (byte[] part : parts) {
+ md.update(part);
+ }
+
+ return ByteBuffer.wrap(md.digest()).order(ByteOrder.LITTLE_ENDIAN);
+ }
+}