World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#14642] fix(jdbc): correct Spark reads and Trino metadata handling (#14643)
Qi Yu7f88982b8462
diff --git a/docs/spark-connector/spark-connector.md b/docs/spark-connector/spark-connector.mdindex 4d1d0f1669..9655d43af4 100644--- a/docs/spark-connector/spark-connector.md+++ b/docs/spark-connector/spark-connector.md@@ -152,3 +152,67 @@ these columns are rejected before JDBC execution, including writes of NULL valueINSERT OVERWRITE. The error identifies the unsupported column. Spark binds these columnsas VARCHAR, which does not preserve the PostgreSQL target type. Use a native PostgreSQLwriter for these tables. Other PostgreSQL column types retain their existing write behavior.++### JDBC query consistency++Spark pushes predicates, aggregates, Top-N, limits, and offsets down to the JDBC source when+the matching `pushDown*` options allow it. Some expressions stay in Spark, because the source+could return different results:++- Expressions on string, char, varchar, binary, UUID, or external-type columns, also inside+ arrays. The source can compare strings with a different collation, and Spark cannot always+ write binary literals in SQL.+- Expressions with a string or binary literal or cast, such as `cast(id AS string) > '9'`.+- Casts to a timestamp type, and casts or date parts such as `hour()` or `year()` of a Spark+ `TIMESTAMP` column. Examples are MySQL `DATETIME`, or PostgreSQL `timestamp` when+ `preferTimestampNTZ` is off. Spark uses the session time zone for these, but the source uses+ its own time zone.+- Date parts other than year, quarter, month, day, hour, and minute, such as `second()` or+ `weekofyear()`. The source can compute them differently.+- Filters with a `TIMESTAMP_NTZ` literal, when the JDBC dialect cannot write it in SQL. The+ PostgreSQL dialect in Spark 3.5 has this limit. Spark 4.0 does not.+- Value-dependent aggregates on timestamp columns whose JDBC reader type differs from the type Spark shows. An+ example is PostgreSQL `timestamptz` on Spark 3.5 with `preferTimestampNTZ=true`.++NULL checks (`IS NULL` and `IS NOT NULL`) and non-distinct `count(column)` on the column itself+can be pushed down when its type does not contain an external type. External types remain in+Spark: for example, PostgreSQL composite NULL checks inspect row fields, while Spark reads a+non-null composite as a string. `count(DISTINCT string_column)` stays in Spark because it+depends on collation.+For PostgreSQL and MySQL, a simple positive string equality or `IN` filter can also be sent+to the source as a prefilter, while Spark rechecks it. This reduces rows transferred to Spark+without trusting the source collation to produce an exact match. These prefilters require+Spark's default binary string comparison. Negated comparisons, casts, compound expressions,+and literals containing a backslash or NUL remain in Spark. Column names differing only by case are excluded from string prefiltering.+Other JDBC sources retain the conservative string policy.++Other expressions are still pushed down, for example `id = 1`, `count(*)`, `LIMIT 10`, or+`ORDER BY id LIMIT 3`. They run with the source semantics. For example, a source `avg()` can+return fewer decimal places than Spark. When a filter stays in Spark, Spark also keeps the+limit and the aggregate of that query in Spark.++#### PostgreSQL timestamps without time zone++By default, a PostgreSQL timestamp without time zone maps to Spark `TIMESTAMP`, as before.+Its value can change with the Spark session time zone. To read the stored wall-clock value,+set `preferTimestampNTZ=true` on the Spark catalog, for example+`spark.sql.catalog.<name>.preferTimestampNTZ=true`. You can also set the Gravitino catalog+property `spark.bypass.preferTimestampNTZ=true`. The Spark catalog option wins when both are+set. This is a catalog-level option: a per-read `spark.read.option("preferTimestampNTZ", ...)`+is ignored so that the reader and the fixed table schema cannot diverge. The option applies to+PostgreSQL catalogs only. Other JDBC catalogs ignore this option and explicitly use+`preferTimestampNTZ=false`, even when `spark.sql.timestampType=TIMESTAMP_NTZ`, to keep their+reader and table schema on `TIMESTAMP`.++With the option on:++- A timestamp without time zone maps to Spark `TIMESTAMP_NTZ`. A timestamp with time zone still+ maps to Spark `TIMESTAMP`.+- Writes store the value from the Spark session time zone instead of the JVM time zone. Jobs+ whose session and JVM time zones differ write different values than before.+- A timestamp column cannot be used as `partitionColumn`. Spark only accepts numeric, date, or+ `TIMESTAMP` partition columns.+- Reading PostgreSQL `infinity` or `-infinity` fails with a `long overflow` error. With the+ option off, Spark reads them as 9999-12-31 and 0001-01-01.+- On Spark 3.5, timestamp array elements still map to `TIMESTAMP`, because the Spark 3.5+ reader does not support `TIMESTAMP_NTZ` array elements.diff --git a/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/jdbc/GravitinoJdbcCatalog.java b/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/jdbc/GravitinoJdbcCatalog.javaindex aef1b5e250..d822f4958e 100644--- a/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/jdbc/GravitinoJdbcCatalog.java+++ b/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/jdbc/GravitinoJdbcCatalog.java@@ -20,6 +20,7 @@package org.apache.gravitino.spark.connector.jdbc;import com.google.common.annotations.VisibleForTesting;+import com.google.common.base.Preconditions;import com.google.common.collect.Maps;import java.util.Map;import org.apache.commons.collections4.MapUtils;@@ -46,6 +47,10 @@ public class GravitinoJdbcCatalog extends BaseCatalog {private static final Logger LOG = LoggerFactory.getLogger(GravitinoJdbcCatalog.class);+ private static final String PREFER_TIMESTAMP_NTZ = "preferTimestampNTZ";++ private boolean useTimestampNtz;+@Overrideprotected TableCatalog createAndInitSparkCatalog(String name, CaseInsensitiveStringMap options, Map<String, String> properties) {@@ -53,6 +58,22 @@ public class GravitinoJdbcCatalog extends BaseCatalog {Map<String, String> all =getPropertiesConverter().toSparkCatalogProperties(options, properties);applyJdbcCredential(gravitinoCatalogClient, all);+ useTimestampNtz = false;+ if ("jdbc-postgresql".equalsIgnoreCase(gravitinoCatalogClient.provider())) {+ String value = preferTimestampNtz(options, properties);+ Preconditions.checkArgument(+ "true".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value),+ "Invalid value '%s' for %s (or %s%s) in catalog %s; use true or false",+ value,+ PREFER_TIMESTAMP_NTZ,+ PropertiesConverter.SPARK_PROPERTY_PREFIX,+ PREFER_TIMESTAMP_NTZ,+ name);+ useTimestampNtz = Boolean.parseBoolean(value);+ }+ // One value drives both the reader and converter for every provider. Explicitly disable NTZ+ // outside PostgreSQL, including when Spark's session timestamp type defaults to NTZ.+ setPreferTimestampNtz(all, useTimestampNtz);jdbcTableCatalog.initialize(name, new CaseInsensitiveStringMap(all));return jdbcTableCatalog;}@@ -115,7 +136,7 @@ public class GravitinoJdbcCatalog extends BaseCatalog {@Overrideprotected SparkTypeConverter getSparkTypeConverter() {- return new SparkJdbcTypeConverter();+ return new SparkJdbcTypeConverter(useTimestampNtz);}@Override@@ -142,4 +163,34 @@ public class GravitinoJdbcCatalog extends BaseCatalog {}super.createNamespace(namespace, properties);}++ @VisibleForTesting+ static void setPreferTimestampNtz(Map<String, String> properties, boolean value) {+ properties.keySet().removeIf(PREFER_TIMESTAMP_NTZ::equalsIgnoreCase);+ properties.put(PREFER_TIMESTAMP_NTZ, String.valueOf(value));+ }++ /**+ * Resolves the opt-in NTZ option. A Spark catalog option wins over a Gravitino catalog property+ * with the {@code spark.bypass.} prefix, as in {@link+ * PropertiesConverter#toSparkCatalogProperties(CaseInsensitiveStringMap, Map)}.+ */+ private static String preferTimestampNtz(+ CaseInsensitiveStringMap options, Map<String, String> properties) {+ if (options != null && options.containsKey(PREFER_TIMESTAMP_NTZ)) {+ return options.get(PREFER_TIMESTAMP_NTZ);+ }+ if (properties != null) {+ for (Map.Entry<String, String> entry : properties.entrySet()) {+ String key = entry.getKey();+ // The prefix is case-sensitive, as in PropertiesConverter; the Spark option name is not.+ if (key.startsWith(PropertiesConverter.SPARK_PROPERTY_PREFIX)+ && PREFER_TIMESTAMP_NTZ.equalsIgnoreCase(+ key.substring(PropertiesConverter.SPARK_PROPERTY_PREFIX.length()))) {+ return entry.getValue();+ }+ }+ }+ return "false";+ }}diff --git a/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/jdbc/JdbcSchemaUtils.java b/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/jdbc/JdbcSchemaUtils.javanew file mode 100644index 0000000000..aa19c9badd--- /dev/null+++ b/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/jdbc/JdbcSchemaUtils.java@@ -0,0 +1,49 @@+/*+ * 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.gravitino.spark.connector.jdbc;++import javax.annotation.Nullable;+import org.apache.spark.sql.types.DataType;+import org.apache.spark.sql.types.StructField;+import org.apache.spark.sql.types.StructType;++/** Column lookup shared by JDBC schema alignment and pushdown checks. */+final class JdbcSchemaUtils {++ private JdbcSchemaUtils() {}++ @Nullable+ static DataType fieldType(StructType schema, String name) {+ DataType candidate = null;+ boolean ambiguous = false;+ for (StructField field : schema.fields()) {+ // PostgreSQL can have distinct quoted columns that differ only in case.+ if (field.name().equals(name)) {+ return field.dataType();+ }+ if (field.name().equalsIgnoreCase(name)) {+ ambiguous |= candidate != null;+ candidate = field.dataType();+ }+ }+ // Preserve case-insensitive lookup only when it identifies a single source column.+ return ambiguous ? null : candidate;+ }+}diff --git a/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/jdbc/SparkJdbcPushDownPolicy.java b/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/jdbc/SparkJdbcPushDownPolicy.javanew file mode 100644index 0000000000..27118dfe02--- /dev/null+++ b/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/jdbc/SparkJdbcPushDownPolicy.java@@ -0,0 +1,379 @@+/*+ * 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.gravitino.spark.connector.jdbc;++import com.google.common.collect.ImmutableSet;+import java.time.LocalDateTime;+import java.util.HashSet;+import java.util.Locale;+import java.util.Set;+import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.types.Type;+import org.apache.gravitino.rel.types.Types;+import org.apache.spark.sql.connector.expressions.Cast;+import org.apache.spark.sql.connector.expressions.Expression;+import org.apache.spark.sql.connector.expressions.Extract;+import org.apache.spark.sql.connector.expressions.Literal;+import org.apache.spark.sql.connector.expressions.NamedReference;+import org.apache.spark.sql.connector.expressions.aggregate.Count;+import org.apache.spark.sql.connector.expressions.filter.Predicate;+import org.apache.spark.sql.jdbc.JdbcDialect;+import org.apache.spark.sql.types.ArrayType;+import org.apache.spark.sql.types.BinaryType;+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.MapType;+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.TimestampNTZType;+import org.apache.spark.sql.types.TimestampType;+import org.apache.spark.sql.types.VarcharType;++/**+ * Decides which expressions a JDBC source may evaluate without changing Spark query results.+ *+ * <p>An expression stays in Spark when it has a known difference from Spark. These are:+ *+ * <ul>+ * <li>string-like or binary columns, also inside arrays, maps, and structs;+ * <li>string or binary literals and casts;+ * <li>casts to a timestamp type, and casts or date parts of a Spark {@code TIMESTAMP} column;+ * <li>date parts other than year, quarter, month, day, hour, and minute;+ * <li>{@code TIMESTAMP_NTZ} literals the dialect cannot write in SQL.+ * </ul>+ *+ * <p>Null checks and non-distinct counts on a column itself are exact unless its type contains an+ * external type, whose source NULL semantics may differ. Simple positive PostgreSQL/MySQL string+ * predicates can prefilter rows while Spark rechecks them; see {@link #canPrefilter(Predicate)}.+ *+ * <p>Value-dependent aggregates also stay in Spark for timestamp columns whose reader type differs+ * from the type Spark sees, because the reader types the pushed aggregate result.+ */+class SparkJdbcPushDownPolicy {++ private static final Set<String> PUSHABLE_EXTRACT_FIELDS =+ ImmutableSet.of("YEAR", "QUARTER", "MONTH", "DAY", "HOUR", "MINUTE");++ private final Set<String> sensitiveColumns;+ private final Set<String> nullPreservingColumns;+ private final Set<String> stringColumns;+ private final boolean stringPrefilterSupported;+ private final Set<String> readerTypeMismatchColumns;+ private final Set<String> zonedTimestampColumns;+ private final boolean ntzLiteralSupported;++ SparkJdbcPushDownPolicy(+ Column[] columns,+ StructType readerSchema,+ StructType sparkSchema,+ JdbcDialect dialect,+ String jdbcUrl) {+ this.sensitiveColumns = new HashSet<>();+ this.nullPreservingColumns = new HashSet<>();+ this.stringColumns = new HashSet<>();+ String url = jdbcUrl.toLowerCase(Locale.ROOT);+ // These sources can return extra collation matches, which Spark removes with a residual.+ // Other JDBC sources retain their existing conservative policy until validated separately.+ this.stringPrefilterSupported =+ url.startsWith("jdbc:postgresql:") || url.startsWith("jdbc:mysql:");+ Set<String> externalColumns = new HashSet<>();+ Set<String> columnNames = new HashSet<>();+ Set<String> ambiguousColumns = new HashSet<>();+ for (Column column : columns) {+ if (!columnNames.add(normalize(column.name()))) {+ ambiguousColumns.add(normalize(column.name()));+ }+ Type type = column.dataType();+ if (containsExternal(type)) {+ externalColumns.add(normalize(column.name()));+ } else {+ nullPreservingColumns.add(normalize(column.name()));+ }+ if ((type instanceof Types.StringType+ || type instanceof Types.VarCharType+ || type instanceof Types.FixedCharType)+ && DataTypes.StringType.equals(JdbcSchemaUtils.fieldType(sparkSchema, column.name()))) {+ stringColumns.add(normalize(column.name()));+ }+ if (isSensitive(column.dataType())) {+ sensitiveColumns.add(normalize(column.name()));+ }+ }+ // Case-insensitive matching must not let a safe column mask a same-spelling external one.+ nullPreservingColumns.removeAll(externalColumns);+ nullPreservingColumns.removeAll(ambiguousColumns);+ stringColumns.removeAll(ambiguousColumns);+ this.readerTypeMismatchColumns = new HashSet<>();+ this.zonedTimestampColumns = new HashSet<>();+ for (StructField field : sparkSchema.fields()) {+ if (field.dataType() instanceof TimestampType) {+ zonedTimestampColumns.add(normalize(field.name()));+ }+ DataType readerType = JdbcSchemaUtils.fieldType(readerSchema, field.name());+ // Only timestamp differences change pushed aggregate results; Spark widens numeric results+ // safely. catalogString ignores nullability, which does not change pushed results.+ if (readerType == null+ || (!readerType.catalogString().equals(field.dataType().catalogString())+ && (containsTimestamp(readerType) || containsTimestamp(field.dataType())))) {+ readerTypeMismatchColumns.add(normalize(field.name()));+ }+ }+ // Spark 3.5 leaves LocalDateTime literals unquoted, while Spark 4 quotes them. Check the+ // dialect itself instead of a Spark version or provider name.+ this.ntzLiteralSupported =+ dialect.compileValue(LocalDateTime.of(2000, 1, 1, 0, 0)) instanceof String;+ }++ /**+ * Returns whether a predicate, sort, or group-by expression may be evaluated by the source.+ *+ * @param expression the expression to check+ * @return true if pushing it keeps Spark results+ */+ boolean canPush(Expression expression) {+ if (expression instanceof Predicate) {+ Predicate predicate = (Predicate) expression;+ Expression[] children = predicate.children();+ if (("IS_NULL".equals(predicate.name()) || "IS_NOT_NULL".equals(predicate.name()))+ && children.length == 1+ && isColumn(children[0], nullPreservingColumns)) {+ // External values may be read as strings but have different source NULL semantics:+ // PostgreSQL composite IS NULL/IS NOT NULL also examines the fields of the row.+ return true;+ }+ }+ if (expression instanceof NamedReference) {+ return !sensitiveColumns.contains(columnName((NamedReference) expression));+ }+ if (expression instanceof Literal) {+ DataType type = ((Literal<?>) expression).dataType();+ return !isSensitive(type) && (ntzLiteralSupported || !containsNtz(type));+ }+ if (expression instanceof Cast) {+ Cast cast = (Cast) expression;+ // Casts to or from TIMESTAMP depend on the time zone: Spark uses the session time zone, and+ // the source uses its own. Casts to TIMESTAMP_NTZ also stay in Spark, which is conservative.+ if (isSensitive(cast.dataType())+ || containsTimestamp(cast.dataType())+ || referencesZonedTimestamp(cast.expression())) {+ return false;+ }+ }+ if (expression instanceof Extract) {+ Extract extract = (Extract) expression;+ // Date parts of a TIMESTAMP depend on the time zone. Other fields, such as SECOND (fractions+ // in PostgreSQL) or WEEK (MySQL week mode on Spark 3.5), can differ from Spark at the source.+ if (!PUSHABLE_EXTRACT_FIELDS.contains(extract.field().toUpperCase(Locale.ROOT))+ || referencesZonedTimestamp(extract.source())) {+ return false;+ }+ }+ for (Expression child : expression.children()) {+ if (!canPush(child)) {+ return false;+ }+ }+ return true;+ }++ /**+ * Returns whether an aggregate function or group-by expression may be evaluated by the source.+ *+ * @param expression the expression to check+ * @return true if pushing it keeps Spark results and result types+ */+ boolean canPushAggregate(Expression expression) {+ if (expression instanceof Count) {+ Count count = (Count) expression;+ // A non-distinct count only uses nullness, not collation or the reader's value type.+ if (!count.isDistinct() && isColumn(count.column(), nullPreservingColumns)) {+ return true;+ }+ }+ if (expression instanceof NamedReference+ && readerTypeMismatchColumns.contains(columnName((NamedReference) expression))) {+ return false;+ }+ if (!canPush(expression)) {+ return false;+ }+ for (Expression child : expression.children()) {+ if (!canPushAggregate(child)) {+ return false;+ }+ }+ return true;+ }++ /**+ * Returns whether a positive string predicate can reduce source rows while Spark rechecks it.+ * Negation and compound expressions are deliberately excluded: a source must not remove a row+ * that Spark would accept. This is a prefilter, never proof that the source result is exact.+ */+ boolean canPrefilter(Predicate predicate) {+ if (!stringPrefilterSupported) {+ return false;+ }+ Expression[] children = predicate.children();+ boolean equality = "=".equals(predicate.name()) && children.length == 2;+ boolean in = "IN".equals(predicate.name()) && children.length >= 2;+ if ((!equality && !in) || !isColumn(children[0], stringColumns)) {+ return false;+ }+ // A non-binary Spark collation could accept rows a stricter source would remove.+ for (int i = 1; i < children.length; i++) {+ if (!(children[i] instanceof Literal)) {+ return false;+ }+ Literal<?> literal = (Literal<?>) children[i];+ if (!DataTypes.StringType.equals(literal.dataType()) || literal.value() == null) {+ return false;+ }+ String value = literal.value().toString();+ // MySQL's dialect does not escape backslashes. PostgreSQL rejects NUL in text literals.+ if (value.indexOf('\\') >= 0 || value.indexOf('\0') >= 0) {+ return false;+ }+ }+ return true;+ }++ private static boolean isColumn(Expression expression, Set<String> names) {+ if (!(expression instanceof NamedReference)) {+ return false;+ }+ NamedReference reference = (NamedReference) expression;+ return reference.fieldNames().length == 1 && names.contains(columnName(reference));+ }++ private boolean referencesZonedTimestamp(Expression expression) {+ if (expression instanceof NamedReference) {+ return zonedTimestampColumns.contains(columnName((NamedReference) expression));+ }+ for (Expression child : expression.children()) {+ if (referencesZonedTimestamp(child)) {+ return true;+ }+ }+ return false;+ }++ private static boolean containsExternal(Type type) {+ if (type instanceof Types.ListType) {+ return containsExternal(((Types.ListType) type).elementType());+ }+ if (type instanceof Types.MapType) {+ return containsExternal(((Types.MapType) type).keyType())+ || containsExternal(((Types.MapType) type).valueType());+ }+ if (type instanceof Types.StructType) {+ for (Types.StructType.Field field : ((Types.StructType) type).fields()) {+ if (containsExternal(field.type())) {+ return true;+ }+ }+ return false;+ }+ return type instanceof Types.ExternalType;+ }++ private static boolean isSensitive(Type type) {+ if (type instanceof Types.ListType) {+ return isSensitive(((Types.ListType) type).elementType());+ }+ if (type instanceof Types.MapType) {+ return isSensitive(((Types.MapType) type).keyType())+ || isSensitive(((Types.MapType) type).valueType());+ }+ if (type instanceof Types.StructType) {+ for (Types.StructType.Field field : ((Types.StructType) type).fields()) {+ if (isSensitive(field.type())) {+ return true;+ }+ }+ return false;+ }+ return type instanceof Types.StringType+ || type instanceof Types.VarCharType+ || type instanceof Types.FixedCharType+ || type instanceof Types.BinaryType+ || type instanceof Types.ExternalType+ || type instanceof Types.UUIDType;+ }++ private static boolean isSensitive(DataType type) {+ if (type instanceof ArrayType) {+ return isSensitive(((ArrayType) type).elementType());+ }+ if (type instanceof MapType) {+ return isSensitive(((MapType) type).keyType()) || isSensitive(((MapType) type).valueType());+ }+ if (type instanceof StructType) {+ for (StructField field : ((StructType) type).fields()) {+ if (isSensitive(field.dataType())) {+ return true;+ }+ }+ return false;+ }+ return type instanceof StringType+ || type instanceof VarcharType+ || type instanceof CharType+ || type instanceof BinaryType;+ }++ private static boolean containsTimestamp(DataType type) {+ return containsNtz(type) || contains(type, TimestampType.class);+ }++ private static boolean containsNtz(DataType type) {+ return contains(type, TimestampNTZType.class);+ }++ private static boolean contains(DataType type, Class<? extends DataType> leaf) {+ if (type instanceof ArrayType) {+ return contains(((ArrayType) type).elementType(), leaf);+ }+ if (type instanceof MapType) {+ return contains(((MapType) type).keyType(), leaf)+ || contains(((MapType) type).valueType(), leaf);+ }+ if (type instanceof StructType) {+ for (StructField field : ((StructType) type).fields()) {+ if (contains(field.dataType(), leaf)) {+ return true;+ }+ }+ return false;+ }+ return leaf.isInstance(type);+ }++ private static String columnName(NamedReference reference) {+ String[] names = reference.fieldNames();+ return names.length == 0 ? "" : normalize(names[0]);+ }++ private static String normalize(String name) {+ return name.toLowerCase(Locale.ROOT);+ }+}diff --git a/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/jdbc/SparkJdbcScanBuilder.java b/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/jdbc/SparkJdbcScanBuilder.javanew file mode 100644index 0000000000..21c6da5d32--- /dev/null+++ b/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/jdbc/SparkJdbcScanBuilder.java@@ -0,0 +1,123 @@+/*+ * 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.gravitino.spark.connector.jdbc;++import java.util.ArrayList;+import java.util.Arrays;+import java.util.LinkedHashSet;+import java.util.List;+import java.util.Set;+import org.apache.spark.sql.connector.expressions.Expression;+import org.apache.spark.sql.connector.expressions.SortOrder;+import org.apache.spark.sql.connector.expressions.aggregate.Aggregation;+import org.apache.spark.sql.connector.expressions.filter.Predicate;+import org.apache.spark.sql.execution.datasources.v2.jdbc.JDBCScanBuilder;++/**+ * A JDBC scan builder that keeps expressions in Spark when the source could evaluate them with+ * different semantics. Other predicates, aggregates, Top-N, limits, and offsets are pushed as+ * usual.+ */+public class SparkJdbcScanBuilder extends JDBCScanBuilder {++ private final transient SparkJdbcPushDownPolicy policy;++ SparkJdbcScanBuilder(JDBCScanBuilder delegate, SparkJdbcPushDownPolicy policy) {+ super(delegate.session(), delegate.schema(), delegate.jdbcOptions());+ this.policy = policy;+ }++ /**+ * Pushes exact predicates and candidate-row prefilters that Spark still evaluates.+ *+ * @param predicates the predicates Spark offers to the source+ * @return the predicates Spark must still evaluate after the scan+ */+ @Override+ public Predicate[] pushPredicates(Predicate[] predicates) {+ Set<Predicate> kept = new LinkedHashSet<>();+ List<Predicate> candidates = new ArrayList<>();+ for (Predicate predicate : predicates) {+ if (policy.canPush(predicate)) {+ candidates.add(predicate);+ } else {+ kept.add(predicate);+ if (policy.canPrefilter(predicate)) {+ candidates.add(predicate);+ }+ }+ }+ kept.addAll(Arrays.asList(super.pushPredicates(candidates.toArray(new Predicate[0]))));+ return kept.toArray(new Predicate[0]);+ }++ /**+ * Checks whether an aggregation can be fully evaluated by the source.+ *+ * @param aggregation the aggregation Spark offers to the source+ * @return false if any part of the aggregation must stay in Spark+ */+ @Override+ public boolean supportCompletePushDown(Aggregation aggregation) {+ return canPush(aggregation) && super.supportCompletePushDown(aggregation);+ }++ /**+ * Pushes an aggregation only when every function and group-by expression is safe.+ *+ * @param aggregation the aggregation Spark offers to the source+ * @return true if the source evaluates the aggregation+ */+ @Override+ public boolean pushAggregation(Aggregation aggregation) {+ return canPush(aggregation) && super.pushAggregation(aggregation);+ }++ /**+ * Pushes Top-N only when every sort expression is safe.+ *+ * @param orders the sort orders+ * @param limit the number of rows to return+ * @return true if the source evaluates the Top-N+ */+ @Override+ public boolean pushTopN(SortOrder[] orders, int limit) {+ for (SortOrder order : orders) {+ if (!policy.canPush(order.expression())) {+ return false;+ }+ }+ return super.pushTopN(orders, limit);+ }++ private boolean canPush(Aggregation aggregation) {+ for (Expression expression : aggregation.aggregateExpressions()) {+ if (!policy.canPushAggregate(expression)) {+ return false;+ }+ }+ for (Expression expression : aggregation.groupByExpressions()) {+ if (!policy.canPushAggregate(expression)) {+ return false;+ }+ }+ return true;+ }+}diff --git a/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/jdbc/SparkJdbcTable.java b/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/jdbc/SparkJdbcTable.javaindex 940cd43cdf..ce62e4d718 100644--- a/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/jdbc/SparkJdbcTable.java+++ b/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/jdbc/SparkJdbcTable.java@@ -19,6 +19,7 @@package org.apache.gravitino.spark.connector.jdbc;+import java.util.HashMap;import java.util.Locale;import java.util.Map;import org.apache.gravitino.rel.Column;@@ -31,14 +32,23 @@ import org.apache.gravitino.spark.connector.utils.GravitinoTableInfoHelper;import org.apache.spark.sql.connector.catalog.Identifier;import org.apache.spark.sql.connector.write.LogicalWriteInfo;import org.apache.spark.sql.connector.write.WriteBuilder;+import org.apache.spark.sql.execution.datasources.v2.jdbc.JDBCScanBuilder;import org.apache.spark.sql.execution.datasources.v2.jdbc.JDBCTable;import org.apache.spark.sql.execution.datasources.v2.jdbc.JDBCTableCatalog;+import org.apache.spark.sql.jdbc.JdbcDialects;+import org.apache.spark.sql.types.ArrayType;+import org.apache.spark.sql.types.DataType;+import org.apache.spark.sql.types.DataTypes;+import org.apache.spark.sql.types.StructField;import org.apache.spark.sql.types.StructType;+import org.apache.spark.sql.util.CaseInsensitiveStringMap;public class SparkJdbcTable extends JDBCTable {private final GravitinoTableInfoHelper gravitinoTableInfoHelper;private final Table gravitinoTable;+ private final StructType sparkSchema;+ private final SparkJdbcPushDownPolicy pushDownPolicy;public SparkJdbcTable(Identifier identifier,@@ -58,6 +68,29 @@ public class SparkJdbcTable extends JDBCTable {propertiesConverter,sparkTransformConverter,sparkTypeConverter);+ this.sparkSchema = alignTimestampArrays(gravitinoTableInfoHelper.schema(), jdbcTable.schema());+ this.pushDownPolicy =+ new SparkJdbcPushDownPolicy(+ gravitinoTable.columns(),+ jdbcTable.schema(),+ sparkSchema,+ JdbcDialects.get(jdbcTable.jdbcOptions().url()),+ jdbcTable.jdbcOptions().url());+ }++ /**+ * Creates a scan builder that keeps unsafe expressions in Spark.+ *+ * @param options the scan options+ * @return the JDBC scan builder+ */+ @Override+ public JDBCScanBuilder newScanBuilder(CaseInsensitiveStringMap options) {+ // Schema and aggregate typing are fixed by the catalog options, not by individual reads.+ Map<String, String> scanOptions = new HashMap<>(options.asCaseSensitiveMap());+ scanOptions.keySet().removeIf("preferTimestampNTZ"::equalsIgnoreCase);+ return new SparkJdbcScanBuilder(+ super.newScanBuilder(new CaseInsensitiveStringMap(scanOptions)), pushDownPolicy);}/**@@ -92,11 +125,40 @@ public class SparkJdbcTable extends JDBCTable {@Override@SuppressWarnings("deprecation")public StructType schema() {- return gravitinoTableInfoHelper.schema();+ return sparkSchema;}@Overridepublic Map<String, String> properties() {return gravitinoTableInfoHelper.properties();}++ /**+ * Uses the reader's element type for timestamp arrays. Spark 3.5 reads PostgreSQL timestamp array+ * elements as TIMESTAMP even when top-level columns use TIMESTAMP_NTZ.+ */+ private static StructType alignTimestampArrays(StructType sparkSchema, StructType readerSchema) {+ StructField[] fields = sparkSchema.fields().clone();+ for (int i = 0; i < fields.length; i++) {+ DataType sparkType = fields[i].dataType();+ DataType readerType = JdbcSchemaUtils.fieldType(readerSchema, fields[i].name());+ if (sparkType instanceof ArrayType+ && readerType instanceof ArrayType+ && isTimestamp(((ArrayType) sparkType).elementType())+ && isTimestamp(((ArrayType) readerType).elementType())) {+ fields[i] =+ new StructField(+ fields[i].name(),+ DataTypes.createArrayType(+ ((ArrayType) readerType).elementType(), ((ArrayType) sparkType).containsNull()),+ fields[i].nullable(),+ fields[i].metadata());+ }+ }+ return new StructType(fields);+ }++ private static boolean isTimestamp(DataType type) {+ return DataTypes.TimestampType.equals(type) || DataTypes.TimestampNTZType.equals(type);+ }}diff --git a/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/jdbc/SparkJdbcTypeConverter.java b/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/jdbc/SparkJdbcTypeConverter.javaindex 737f4fa3d2..cb29c28a8f 100644--- a/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/jdbc/SparkJdbcTypeConverter.java+++ b/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/jdbc/SparkJdbcTypeConverter.java@@ -31,6 +31,26 @@ public class SparkJdbcTypeConverter extends SparkTypeConverter {private static final Logger LOG = LoggerFactory.getLogger(SparkJdbcTypeConverter.class);+ private final boolean useTimestampNtz;++ /** Creates a converter retaining the existing JDBC timestamp mapping. */+ public SparkJdbcTypeConverter() {+ this(false);+ }++ /**+ * Creates a converter with provider-specific timestamp handling.+ *+ * <p>When {@code useTimestampNtz} is true, the Spark JDBC reader of the same catalog must also+ * use {@code preferTimestampNTZ=true}. Otherwise the table schema and the scanned rows use+ * different timestamp types.+ *+ * @param useTimestampNtz whether zone-free timestamps use Spark TimestampNTZType+ */+ public SparkJdbcTypeConverter(boolean useTimestampNtz) {+ this.useTimestampNtz = useTimestampNtz;+ }+@Overridepublic DataType toSparkType(Type gravitinoType) {if (gravitinoType instanceof Types.VarCharType) {@@ -44,7 +64,7 @@ public class SparkJdbcTypeConverter extends SparkTypeConverter {"Reading type {} as a string, Gravitino cannot represent it",((Types.ExternalType) gravitinoType).catalogString());return DataTypes.StringType;- } else if (gravitinoType instanceof Types.TimestampType) {+ } else if (gravitinoType instanceof Types.TimestampType && !useTimestampNtz) {// Both timestamp flavors map to TimestampType, never TimestampNTZType: the MySQL dialect only// pushes TimestampType literals down correctly, and NTZ literals produce invalid SQL.return DataTypes.TimestampType;diff --git a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/jdbc/TestGravitinoJdbcCatalog.java b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/jdbc/TestGravitinoJdbcCatalog.javaindex 6dbff1869a..2512a0fb13 100644--- a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/jdbc/TestGravitinoJdbcCatalog.java+++ b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/jdbc/TestGravitinoJdbcCatalog.java@@ -19,18 +19,38 @@package org.apache.gravitino.spark.connector.jdbc;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.mockStatic;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;+import java.util.Collections;import java.util.HashMap;import java.util.Map;+import java.util.stream.Stream;+import org.apache.commons.lang3.reflect.FieldUtils;import org.apache.gravitino.Audit;import org.apache.gravitino.Catalog;import org.apache.gravitino.credential.Credential;import org.apache.gravitino.credential.JdbcCredential;import org.apache.gravitino.credential.SupportsCredentials;+import org.apache.gravitino.rel.types.Types;+import org.apache.gravitino.spark.connector.catalog.GravitinoCatalogManager;+import org.apache.spark.sql.connector.catalog.TableCatalog;+import org.apache.spark.sql.execution.datasources.jdbc.JDBCOptions;+import org.apache.spark.sql.internal.SQLConf;+import org.apache.spark.sql.types.DataTypes;+import org.apache.spark.sql.util.CaseInsensitiveStringMap;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.Arguments;+import org.junit.jupiter.params.provider.CsvSource;+import org.junit.jupiter.params.provider.MethodSource;+import org.junit.jupiter.params.provider.ValueSource;+import org.mockito.MockedStatic;-/** Unit tests for {@link GravitinoJdbcCatalog#applyJdbcCredential}. */+/** Unit tests for JDBC catalog credentials and timestamp option handling. */public class TestGravitinoJdbcCatalog {/**@@ -90,6 +110,172 @@ public class TestGravitinoJdbcCatalog {}}+ @ParameterizedTest+ @ValueSource(+ strings = {+ "jdbc-postgresql",+ "jdbc-mysql",+ "jdbc-doris",+ "jdbc-starrocks",+ "jdbc-oceanbase",+ "jdbc-oracle"+ })+ void testTimestampMappingIsUnchangedByDefault(String provider) throws Exception {+ try (MockedStatic<GravitinoCatalogManager> global = mockStatic(GravitinoCatalogManager.class)) {+ global.when(GravitinoCatalogManager::get).thenReturn(mock(GravitinoCatalogManager.class));+ SupportsCredentials credentials = mock(SupportsCredentials.class);+ when(credentials.getCredentials())+ .thenReturn(new Credential[] {new JdbcCredential("user", "password")});+ GravitinoJdbcCatalog catalog = catalog(provider, credentials);+ JDBCOptions options = initialize(catalog, Map.of(), Map.of());+ Assertions.assertFalse(options.preferTimestampNTZ());+ Assertions.assertEquals(+ DataTypes.TimestampType,+ catalog.getSparkTypeConverter().toSparkType(Types.TimestampType.withoutTimeZone()));+ Assertions.assertEquals(+ DataTypes.TimestampType,+ catalog.getSparkTypeConverter().toSparkType(Types.TimestampType.withTimeZone()));+ Assertions.assertEquals("password", options.asConnectionProperties().getProperty("password"));+ verify(credentials).getCredentials();+ }+ }++ @ParameterizedTest+ @MethodSource("nonPostgreSqlNtzOptions")+ void testNonPostgreSqlNtzOptionsAreIgnored(+ String provider, Map<String, String> catalogOptions, Map<String, String> properties)+ throws Exception {+ try (MockedStatic<GravitinoCatalogManager> global = mockStatic(GravitinoCatalogManager.class)) {+ global.when(GravitinoCatalogManager::get).thenReturn(mock(GravitinoCatalogManager.class));+ SupportsCredentials credentials = mock(SupportsCredentials.class);+ when(credentials.getCredentials()).thenReturn(new Credential[0]);+ GravitinoJdbcCatalog catalog = catalog(provider, credentials);+ JDBCOptions options = initialize(catalog, catalogOptions, properties);+ Assertions.assertFalse(options.preferTimestampNTZ());+ Assertions.assertEquals(+ DataTypes.TimestampType,+ catalog.getSparkTypeConverter().toSparkType(Types.TimestampType.withoutTimeZone()));+ Assertions.assertEquals(+ 1L,+ options.asProperties().stringPropertyNames().stream()+ .filter("preferTimestampNTZ"::equalsIgnoreCase)+ .count());+ }+ }++ @ParameterizedTest+ @ValueSource(+ strings = {+ "jdbc-postgresql",+ "jdbc-mysql",+ "jdbc-doris",+ "jdbc-starrocks",+ "jdbc-oceanbase",+ "jdbc-oracle"+ })+ void testSessionTimestampTypeDoesNotEnableNtz(String provider) throws Exception {+ SQLConf conf = SQLConf.get();+ String previous = conf.getConfString("spark.sql.timestampType", null);+ try {+ conf.setConfString("spark.sql.timestampType", "TIMESTAMP_NTZ");+ try (MockedStatic<GravitinoCatalogManager> global =+ mockStatic(GravitinoCatalogManager.class)) {+ global.when(GravitinoCatalogManager::get).thenReturn(mock(GravitinoCatalogManager.class));+ SupportsCredentials credentials = mock(SupportsCredentials.class);+ when(credentials.getCredentials()).thenReturn(new Credential[0]);+ GravitinoJdbcCatalog catalog = catalog(provider, credentials);+ Assertions.assertFalse(initialize(catalog, Map.of(), Map.of()).preferTimestampNTZ());+ Assertions.assertEquals(+ DataTypes.TimestampType,+ catalog.getSparkTypeConverter().toSparkType(Types.TimestampType.withoutTimeZone()));+ }+ } finally {+ if (previous == null) {+ conf.unsetConf("spark.sql.timestampType");+ } else {+ conf.setConfString("spark.sql.timestampType", previous);+ }+ }+ }++ @ParameterizedTest+ @CsvSource({+ "preferTimestampNTZ, true, '', true",+ "prefertimestampntz, true, '', true",+ "PREFERTIMESTAMPNTZ, false, '', false",+ "preferTimestampNTZ, '', true, true",+ "prefertimestampntz, '', true, true",+ "PreferTimestampNtz, '', false, false",+ "preferTimestampNTZ, false, true, false",+ "prefertimestampntz, true, false, true",+ "PreferTimestampNtz, true, false, true",+ "PREFERTIMESTAMPNTZ, false, true, false",+ "prefertimestampntz, '', true, true"+ })+ void testPostgreSqlNtzOptionDrivesReaderAndConverter(+ String key, String option, String property, boolean expected) throws Exception {+ try (MockedStatic<GravitinoCatalogManager> global = mockStatic(GravitinoCatalogManager.class)) {+ global.when(GravitinoCatalogManager::get).thenReturn(mock(GravitinoCatalogManager.class));+ SupportsCredentials credentials = mock(SupportsCredentials.class);+ when(credentials.getCredentials()).thenReturn(new Credential[0]);+ GravitinoJdbcCatalog catalog = catalog("jdbc-postgresql", credentials);+ // A Spark catalog option wins over a Gravitino catalog property with the "spark.bypass."+ // prefix.+ JDBCOptions options =+ initialize(+ catalog,+ option.isEmpty() ? Map.of() : Map.of(key, option),+ property.isEmpty() ? Map.of() : Map.of("spark.bypass." + key, property));+ Assertions.assertEquals(expected, options.preferTimestampNTZ());+ Assertions.assertEquals(+ expected ? DataTypes.TimestampNTZType : DataTypes.TimestampType,+ catalog.getSparkTypeConverter().toSparkType(Types.TimestampType.withoutTimeZone()));+ }+ }++ @Test+ void testNtzPropertyNeedsTheBypassPrefix() throws Exception {+ try (MockedStatic<GravitinoCatalogManager> global = mockStatic(GravitinoCatalogManager.class)) {+ global.when(GravitinoCatalogManager::get).thenReturn(mock(GravitinoCatalogManager.class));+ SupportsCredentials credentials = mock(SupportsCredentials.class);+ when(credentials.getCredentials()).thenReturn(new Credential[0]);+ GravitinoJdbcCatalog catalog = catalog("jdbc-postgresql", credentials);+ Assertions.assertFalse(+ initialize(catalog, Map.of(), Map.of("spark.preferTimestampNTZ", "true"))+ .preferTimestampNTZ());+ }+ }++ @Test+ void testInvalidNtzValueIsRejected() throws Exception {+ try (MockedStatic<GravitinoCatalogManager> global = mockStatic(GravitinoCatalogManager.class)) {+ global.when(GravitinoCatalogManager::get).thenReturn(mock(GravitinoCatalogManager.class));+ SupportsCredentials credentials = mock(SupportsCredentials.class);+ when(credentials.getCredentials()).thenReturn(new Credential[0]);+ GravitinoJdbcCatalog catalog = catalog("jdbc-postgresql", credentials);+ IllegalArgumentException error =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> initialize(catalog, Map.of("preferTimestampNTZ", "yes"), Map.of()));+ Assertions.assertTrue(error.getMessage().contains("'yes'"), error.getMessage());+ Assertions.assertTrue(error.getMessage().contains("preferTimestampNTZ"), error.getMessage());+ Assertions.assertTrue(+ error.getMessage().contains("spark.bypass.preferTimestampNTZ"), error.getMessage());+ Assertions.assertTrue(error.getMessage().contains("catalog test"), error.getMessage());+ }+ }++ @Test+ void testNtzOptionKeepsOnlyOneSpelling() {+ Map<String, String> properties = new HashMap<>();+ properties.put("prefertimestampntz", "false");+ properties.put("PreferTimestampNtz", "false");+ properties.put("url", "jdbc:postgresql://localhost/db");+ GravitinoJdbcCatalog.setPreferTimestampNtz(properties, true);+ Assertions.assertEquals(+ Map.of("preferTimestampNTZ", "true", "url", "jdbc:postgresql://localhost/db"), properties);+ }+@Testvoid testCredentialVendingOverridesProperties() {Map<String, String> props = new HashMap<>();@@ -130,4 +316,44 @@ public class TestGravitinoJdbcCatalog {Assertions.assertEquals("prop-password", props.get(JdbcPropertiesConstants.SPARK_JDBC_PASSWORD));}++ private static Stream<Arguments> nonPostgreSqlNtzOptions() {+ return Stream.of("jdbc-mysql", "jdbc-doris", "jdbc-starrocks", "jdbc-oceanbase", "jdbc-oracle")+ .flatMap(+ provider ->+ Stream.of(+ Arguments.of(provider, Map.of("preferTimestampNTZ", "true"), Map.of()),+ Arguments.of(provider, Map.of("PrEfErTiMeStAmPnTz", "true"), Map.of()),+ Arguments.of(+ provider, Map.of(), Map.of("spark.bypass.prefertimestampntz", "true")),+ Arguments.of(+ provider,+ Map.of("PREFERTIMESTAMPNTZ", "true"),+ Map.of("spark.bypass.preferTimestampNTZ", "false")),+ Arguments.of(provider, Map.of("preferTimestampNTZ", "yes"), Map.of())));+ }++ private static GravitinoJdbcCatalog catalog(String provider, SupportsCredentials credentials)+ throws IllegalAccessException {+ Catalog source = mock(Catalog.class);+ when(source.provider()).thenReturn(provider);+ when(source.supportsCredentials()).thenReturn(credentials);+ GravitinoJdbcCatalog catalog = new GravitinoJdbcCatalog();+ FieldUtils.writeField(catalog, "gravitinoCatalogClient", source, true);+ return catalog;+ }++ private static JDBCOptions initialize(+ GravitinoJdbcCatalog catalog, Map<String, String> options, Map<String, String> extra)+ throws IllegalAccessException {+ Map<String, String> properties = new HashMap<>(extra);+ properties.put("jdbc-url", "jdbc:postgresql://localhost/db");+ properties.put("jdbc-driver", "org.postgresql.Driver");+ Map<String, String> originalProperties = new HashMap<>(properties);+ CaseInsensitiveStringMap catalogOptions = new CaseInsensitiveStringMap(options);+ TableCatalog physical = catalog.createAndInitSparkCatalog("test", catalogOptions, properties);+ Assertions.assertEquals(originalProperties, properties);+ Assertions.assertEquals(options, catalogOptions.asCaseSensitiveMap());+ return (JDBCOptions) FieldUtils.readField(physical, "options", true);+ }}diff --git a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/jdbc/TestGravitinoJdbcTimestampRead.java b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/jdbc/TestGravitinoJdbcTimestampRead.javanew file mode 100644index 0000000000..64a716a029--- /dev/null+++ b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/jdbc/TestGravitinoJdbcTimestampRead.java@@ -0,0 +1,174 @@+/*+ * 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.gravitino.spark.connector.jdbc;++import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anySet;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.mockStatic;+import static org.mockito.Mockito.when;++import java.sql.Connection;+import java.sql.DriverManager;+import java.sql.Statement;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.TimeZone;+import org.apache.gravitino.Catalog;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.Table;+import org.apache.gravitino.rel.TableCatalog;+import org.apache.gravitino.rel.types.Types;+import org.apache.gravitino.spark.connector.catalog.GravitinoCatalogManager;+import org.apache.spark.sql.Dataset;+import org.apache.spark.sql.Row;+import org.apache.spark.sql.RowFactory;+import org.apache.spark.sql.SparkSession;+import org.apache.spark.sql.connector.catalog.Identifier;+import org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD;+import org.apache.spark.sql.execution.datasources.v2.jdbc.JDBCTable;+import org.apache.spark.sql.types.DataTypes;+import org.apache.spark.sql.types.StructType;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Tag;+import org.junit.jupiter.api.Test;+import org.mockito.MockedStatic;+import org.testcontainers.containers.GenericContainer;+import org.testcontainers.containers.wait.strategy.Wait;++/** MySQL timestamp options keep the production catalog schema and JDBC reader aligned. */+@Tag("gravitino-docker-test")+public class TestGravitinoJdbcTimestampRead {++ @Test+ void testMySqlIgnoresNtzCatalogBypassAndSessionOptions() throws Exception {+ TimeZone originalTimeZone = TimeZone.getDefault();+ TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));+ try (GenericContainer<?> database =+ new GenericContainer<>("mysql:8.0")+ .withEnv("MYSQL_DATABASE", "test")+ .withEnv("MYSQL_ROOT_PASSWORD", "test")+ .withEnv("MYSQL_ROOT_HOST", "%")+ .withExposedPorts(3306)+ .waitingFor(Wait.forLogMessage(".*mysqld: ready for connections.*\\n", 2))) {+ database.start();+ String url =+ "jdbc:mysql://"+ + database.getHost()+ + ":"+ + database.getMappedPort(3306)+ + "/test?allowPublicKeyRetrieval=true&useSSL=false"+ + "&connectionTimeZone=%2B08:00&forceConnectionTimeZoneToSession=true";+ try (Connection connection = DriverManager.getConnection(url, "root", "test");+ Statement statement = connection.createStatement()) {+ statement.execute("CREATE TABLE timestamps(id int, ts timestamp(6), dt datetime(6))");+ statement.execute(+ "INSERT INTO timestamps VALUES "+ + "(1, '2024-01-02 03:04:05.123456', '2024-01-02 03:04:05.123456'), "+ + "(2, NULL, NULL)");+ }+ GravitinoCatalogManager manager = mock(GravitinoCatalogManager.class);+ try (MockedStatic<GravitinoCatalogManager> managers =+ mockStatic(GravitinoCatalogManager.class);+ SparkSession spark =+ SparkSession.builder()+ .master("local[1]")+ .appName("mysql-timestamp-options")+ .config("spark.ui.enabled", "false")+ .config("spark.sql.session.timeZone", "America/Los_Angeles")+ .getOrCreate()) {+ managers.when(GravitinoCatalogManager::get).thenReturn(manager);+ for (String source : List.of("catalog", "bypass", "session")) {+ String name = "ntz_" + source;+ Map<String, String> properties = new HashMap<>();+ properties.put("jdbc-url", url);+ properties.put("jdbc-driver", "com.mysql.cj.jdbc.Driver");+ properties.put("jdbc-user", "root");+ properties.put("jdbc-password", "test");+ if (source.equals("bypass")) {+ properties.put("spark.bypass.PrEfErTiMeStAmPnTz", "true");+ }+ Catalog catalog = mock(Catalog.class);+ when(catalog.provider()).thenReturn("jdbc-mysql");+ when(catalog.properties()).thenReturn(properties);+ when(catalog.supportsSecrets()).thenThrow(UnsupportedOperationException.class);+ when(catalog.supportsCredentials()).thenThrow(UnsupportedOperationException.class);+ TableCatalog tables = mock(TableCatalog.class);+ when(catalog.asTableCatalog()).thenReturn(tables);+ Table metadata = mock(Table.class);+ when(metadata.columns())+ .thenReturn(+ new Column[] {+ Column.of("id", Types.IntegerType.get()),+ Column.of("ts", Types.TimestampType.withoutTimeZone()),+ Column.of("dt", Types.TimestampType.withoutTimeZone())+ });+ when(tables.loadTable(any(NameIdentifier.class), anySet())).thenReturn(metadata);+ when(manager.getGravitinoCatalogInfo(name)).thenReturn(catalog);+ spark.conf().set("spark.sql.catalog." + name, GravitinoJdbcCatalog.class.getName());+ if (source.equals("catalog")) {+ spark.conf().set("spark.sql.catalog." + name + ".PrEfErTiMeStAmPnTz", "true");+ }+ spark+ .conf()+ .set(+ "spark.sql.timestampType",+ source.equals("session") ? "TIMESTAMP_NTZ" : "TIMESTAMP_LTZ");+ String table = name + ".test.timestamps";+ Dataset<Row> rows = spark.table(table);+ Assertions.assertEquals(DataTypes.TimestampType, rows.schema().apply("ts").dataType());+ Assertions.assertEquals(DataTypes.TimestampType, rows.schema().apply("dt").dataType());+ GravitinoJdbcCatalog initialized =+ (GravitinoJdbcCatalog) spark.sessionState().catalogManager().catalog(name);+ JDBCTable jdbcTable =+ (JDBCTable) initialized.loadTable(Identifier.of(new String[] {"test"}, "timestamps"));+ // Read the source schema with the actual catalog options, before the wrapper replaces it.+ StructType readerSchema = JDBCRDD.resolveTable(jdbcTable.jdbcOptions());+ Assertions.assertEquals(+ DataTypes.TimestampType, readerSchema.apply("ts").dataType(), source);+ Assertions.assertEquals(+ DataTypes.TimestampType, readerSchema.apply("dt").dataType(), source);+ String expected = "2024-01-01 11:04:05.123456";+ Assertions.assertEquals(+ List.of(RowFactory.create(1, expected, expected), RowFactory.create(2, null, null)),+ spark+ .sql(+ "SELECT id, CAST(ts AS STRING), CAST(dt AS STRING) FROM "+ + table+ + " ORDER BY id")+ .collectAsList(),+ source);+ Assertions.assertEquals(+ RowFactory.create(1704135845123456L, 1704135845123456L, 1L, 1L),+ spark+ .sql(+ "SELECT unix_micros(min(ts)), unix_micros(max(dt)), count(ts), count(dt) FROM "+ + table)+ .head(),+ source);+ }+ }+ } finally {+ TimeZone.setDefault(originalTimeZone);+ }+ }+}diff --git a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/jdbc/TestJdbcSchemaUtils.java b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/jdbc/TestJdbcSchemaUtils.javanew file mode 100644index 0000000000..52d7e65ec6--- /dev/null+++ b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/jdbc/TestJdbcSchemaUtils.java@@ -0,0 +1,55 @@+/*+ * 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.gravitino.spark.connector.jdbc;++import org.apache.spark.sql.types.DataTypes;+import org.apache.spark.sql.types.StructType;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++/** JDBC schema lookup preserves distinct case-sensitive source columns. */+public class TestJdbcSchemaUtils {++ @Test+ void testExactColumnNamesWinRegardlessOfOrder() {+ StructType schema =+ new StructType().add("ts", DataTypes.TimestampNTZType).add("TS", DataTypes.TimestampType);+ for (StructType ordered :+ new StructType[] {+ schema, new StructType().add(schema.fields()[1]).add(schema.fields()[0])+ }) {+ Assertions.assertEquals(DataTypes.TimestampNTZType, JdbcSchemaUtils.fieldType(ordered, "ts"));+ Assertions.assertEquals(DataTypes.TimestampType, JdbcSchemaUtils.fieldType(ordered, "TS"));+ }+ // An exact match after multiple case-insensitive candidates must still win.+ Assertions.assertEquals(+ DataTypes.StringType,+ JdbcSchemaUtils.fieldType(schema.add("Ts", DataTypes.StringType), "Ts"));+ }++ @Test+ void testCaseInsensitiveFallbackMustBeUnique() {+ StructType schema = new StructType().add("ts", DataTypes.TimestampNTZType);+ Assertions.assertEquals(DataTypes.TimestampNTZType, JdbcSchemaUtils.fieldType(schema, "TS"));+ Assertions.assertNull(JdbcSchemaUtils.fieldType(schema, "missing"));+ Assertions.assertNull(+ JdbcSchemaUtils.fieldType(schema.add("TS", DataTypes.TimestampType), "Ts"));+ }+}diff --git a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/jdbc/TestSparkJdbcPushDownPolicy.java b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/jdbc/TestSparkJdbcPushDownPolicy.javanew file mode 100644index 0000000000..d20565a174--- /dev/null+++ b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/jdbc/TestSparkJdbcPushDownPolicy.java@@ -0,0 +1,389 @@+/*+ * 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.gravitino.spark.connector.jdbc;++import static org.mockito.Mockito.RETURNS_DEEP_STUBS;+import static org.mockito.Mockito.mock;++import java.time.LocalDateTime;+import java.util.Arrays;+import java.util.List;+import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.types.Type;+import org.apache.gravitino.rel.types.Types;+import org.apache.spark.sql.SparkSession;+import org.apache.spark.sql.connector.expressions.Cast;+import org.apache.spark.sql.connector.expressions.Expression;+import org.apache.spark.sql.connector.expressions.Expressions;+import org.apache.spark.sql.connector.expressions.Extract;+import org.apache.spark.sql.connector.expressions.LiteralValue;+import org.apache.spark.sql.connector.expressions.NullOrdering;+import org.apache.spark.sql.connector.expressions.SortDirection;+import org.apache.spark.sql.connector.expressions.SortOrder;+import org.apache.spark.sql.connector.expressions.aggregate.AggregateFunc;+import org.apache.spark.sql.connector.expressions.aggregate.Aggregation;+import org.apache.spark.sql.connector.expressions.aggregate.Count;+import org.apache.spark.sql.connector.expressions.aggregate.CountStar;+import org.apache.spark.sql.connector.expressions.aggregate.Max;+import org.apache.spark.sql.connector.expressions.filter.And;+import org.apache.spark.sql.connector.expressions.filter.Predicate;+import org.apache.spark.sql.execution.datasources.jdbc.JDBCOptions;+import org.apache.spark.sql.execution.datasources.v2.jdbc.JDBCScanBuilder;+import org.apache.spark.sql.jdbc.JdbcDialect;+import org.apache.spark.sql.jdbc.JdbcDialects;+import org.apache.spark.sql.types.DataType;+import org.apache.spark.sql.types.DataTypes;+import org.apache.spark.sql.types.StructField;+import org.apache.spark.sql.types.StructType;+import org.apache.spark.unsafe.types.UTF8String;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;+import scala.collection.immutable.HashMap;++/** Expression-level pushdown decisions for JDBC tables. */+public class TestSparkJdbcPushDownPolicy {++ private static final String URL = "jdbc:postgresql://localhost/test";+ private static final JdbcDialect DIALECT = JdbcDialects.get(URL);++ @Test+ // Cast(Expression, DataType) is deprecated in Spark 4 but is the only constructor in Spark 3.5.+ @SuppressWarnings("deprecation")+ void testOnlyExpressionsWithSensitiveValuesStayInSpark() {+ SparkJdbcPushDownPolicy policy = policy();+ Assertions.assertTrue(policy.canPush(eq(col("id"), lit(1, DataTypes.IntegerType))));+ Assertions.assertTrue(policy.canPush(eq(col("ID"), lit(1, DataTypes.IntegerType))));+ Assertions.assertFalse(policy.canPush(eq(col("s"), lit("a", DataTypes.StringType))));+ Assertions.assertFalse(policy.canPush(eq(col("v"), lit("a", DataTypes.StringType))));+ Assertions.assertFalse(policy.canPush(eq(col("b"), lit(new byte[] {1}, DataTypes.BinaryType))));+ Assertions.assertFalse(policy.canPush(col("u")));+ Assertions.assertFalse(policy.canPush(col("j")));+ // Array elements compare with the element collation at the source.+ Assertions.assertFalse(policy.canPush(col("tags")));+ // A string cast or literal stays in Spark even over a numeric column.+ Assertions.assertFalse(+ policy.canPush(+ new Predicate(+ ">",+ new Expression[] {+ new Cast(col("id"), DataTypes.StringType), lit("9", DataTypes.StringType)+ })));+ // One unsafe side keeps the whole conjunction in Spark; Spark splits top-level ANDs itself.+ Assertions.assertFalse(+ policy.canPush(+ new And(+ eq(col("id"), lit(1, DataTypes.IntegerType)),+ eq(col("s"), lit("a", DataTypes.StringType)))));+ Assertions.assertTrue(+ policy.canPush(+ eq(col("ts"), lit(LocalDateTime.of(2024, 1, 2, 3, 4), DataTypes.TimestampNTZType)))+ == (DIALECT.compileValue(LocalDateTime.of(2000, 1, 1, 0, 0)) instanceof String));+ Assertions.assertTrue(policy.canPush(col("ts")));+ // Spark converts to TIMESTAMP in the session time zone; the source uses its own time zone.+ Assertions.assertFalse(+ policy.canPush(+ new Predicate(+ ">",+ new Expression[] {+ new Cast(col("ts"), DataTypes.TimestampType), lit(0L, DataTypes.TimestampType)+ })));+ Assertions.assertFalse(policy.canPush(new Cast(col("d"), DataTypes.TimestampType)));+ Assertions.assertTrue(policy.canPush(new Cast(col("id"), DataTypes.LongType)));+ // Date parts and casts of a TIMESTAMP column depend on the session time zone.+ Assertions.assertFalse(policy.canPush(new Extract("HOUR", col("tz"))));+ Assertions.assertFalse(policy.canPush(new Cast(col("tz"), DataTypes.DateType)));+ Assertions.assertTrue(policy.canPush(new Extract("HOUR", col("ts"))));+ Assertions.assertTrue(policy.canPush(new Extract("YEAR", col("d"))));+ // Fields whose source semantics can differ from Spark stay in Spark.+ for (String field :+ new String[] {"SECOND", "WEEK", "DAY_OF_WEEK", "DAY_OF_YEAR", "YEAR_OF_WEEK"}) {+ Assertions.assertFalse(policy.canPush(new Extract(field, col("ts"))), field);+ }+ Assertions.assertTrue(policy.canPush(new Extract("MINUTE", col("ts"))));+ for (String field : new String[] {"QUARTER", "MONTH", "DAY"}) {+ Assertions.assertTrue(policy.canPush(new Extract(field, col("d"))), field);+ }+ }++ @Test+ void testAggregatesStayInSparkWhenReaderTimestampTypeDiffers() {+ SparkJdbcPushDownPolicy policy = policy();+ // "tz" is NTZ for the reader but TIMESTAMP for Spark, as on Spark 3.5 PostgreSQL.+ Assertions.assertTrue(policy.canPush(col("tz")));+ Assertions.assertFalse(policy.canPushAggregate(new Max(col("tz"))));+ Assertions.assertTrue(policy.canPushAggregate(new Max(col("id"))));+ Assertions.assertTrue(policy.canPushAggregate(new CountStar()));+ Assertions.assertFalse(policy.canPushAggregate(new Max(col("s"))));+ // Numeric differences, such as a MySQL SMALLINT read as INT on Spark 3.5, keep pushdown.+ Assertions.assertTrue(policy.canPushAggregate(new Max(col("si"))));+ }++ @Test+ void testScanBuilderKeepsUnsafeExpressionsAndPushesTheRest() {+ SparkJdbcPushDownPolicy policy = policy();+ JDBCOptions options =+ new JDBCOptions(+ new HashMap<String, String>()+ .updated("url", URL)+ .updated("dbtable", "t")+ .updated("driver", "org.postgresql.Driver")+ .updated("pushDownPredicate", "true")+ .updated("pushDownLimit", "true"));+ SparkJdbcScanBuilder builder =+ new SparkJdbcScanBuilder(+ new JDBCScanBuilder(+ mock(SparkSession.class, RETURNS_DEEP_STUBS), sparkSchema(), options),+ policy);+ Predicate safe = eq(col("id"), lit(1, DataTypes.IntegerType));+ Predicate unsafe = eq(col("s"), lit("a", DataTypes.StringType));++ List<Predicate> postScan =+ Arrays.asList(builder.pushPredicates(new Predicate[] {safe, unsafe}));+ Assertions.assertEquals(List.of(unsafe), postScan);+ Assertions.assertEquals(List.of(safe, unsafe), Arrays.asList(builder.pushedPredicates()));+ Assertions.assertFalse(builder.pushTopN(new SortOrder[] {sort(col("s"))}, 1));+ Assertions.assertTrue(builder.pushTopN(new SortOrder[] {sort(col("id"))}, 1));+ Assertions.assertTrue(builder.pushLimit(10));+ Aggregation stringAggregate =+ new Aggregation(new AggregateFunc[] {new Max(col("s"))}, new Expression[0]);+ Assertions.assertFalse(builder.pushAggregation(stringAggregate));+ Assertions.assertFalse(builder.supportCompletePushDown(stringAggregate));+ Aggregation groupByString =+ new Aggregation(new AggregateFunc[] {new CountStar()}, new Expression[] {col("s")});+ Assertions.assertFalse(builder.pushAggregation(groupByString));+ }++ @Test+ @SuppressWarnings("deprecation")+ void testNullChecksAndPositiveStringPrefilters() {+ for (String url : new String[] {URL, "jdbc:mysql://localhost/test"}) {+ SparkJdbcPushDownPolicy policy = policy(url);+ Assertions.assertTrue(policy.canPush(predicate("IS_NULL", col("s"))));+ Assertions.assertTrue(policy.canPush(predicate("IS_NOT_NULL", col("b"))));+ Assertions.assertFalse(+ policy.canPush(predicate("IS_NULL", new Cast(col("id"), DataTypes.StringType))));+ for (String value : new String[] {"a", "A", "a ", "", "é", "O'Reilly"}) {+ Assertions.assertTrue(policy.canPrefilter(eq(col("s"), lit(value, DataTypes.StringType))));+ }+ Assertions.assertTrue(+ policy.canPrefilter(+ predicate(+ "IN", col("v"), lit("a", DataTypes.StringType), lit("B", DataTypes.StringType))));+ for (String operation : new String[] {"<>", "<=>", "NOT IN", ">", "<"}) {+ Assertions.assertFalse(+ policy.canPrefilter(predicate(operation, col("s"), lit("a", DataTypes.StringType))));+ }+ Assertions.assertFalse(+ policy.canPrefilter(predicate("NOT", eq(col("s"), lit("a", DataTypes.StringType)))));+ Assertions.assertFalse(+ policy.canPrefilter(+ predicate(+ "OR",+ eq(col("s"), lit("a", DataTypes.StringType)),+ eq(col("s"), lit("b", DataTypes.StringType)))));+ Assertions.assertFalse(policy.canPrefilter(eq(col("tags"), lit("a", DataTypes.StringType))));+ Assertions.assertFalse(policy.canPrefilter(eq(col("u"), lit("a", DataTypes.StringType))));+ Assertions.assertFalse(policy.canPrefilter(eq(col("j"), lit("a", DataTypes.StringType))));+ Assertions.assertFalse(policy.canPrefilter(eq(col("id"), lit("1", DataTypes.StringType))));+ Assertions.assertFalse(policy.canPrefilter(eq(col("s"), lit(1, DataTypes.IntegerType))));+ Assertions.assertFalse(policy.canPrefilter(eq(col("s"), lit(null, DataTypes.StringType))));+ Assertions.assertFalse(policy.canPrefilter(eq(col("s"), lit("abc\\", DataTypes.StringType))));+ Assertions.assertFalse(policy.canPrefilter(eq(col("s"), lit("a\0b", DataTypes.StringType))));+ Assertions.assertFalse(policy.canPrefilter(predicate("IN", col("s"))));+ Assertions.assertFalse(+ policy.canPrefilter(+ eq(new Cast(col("id"), DataTypes.StringType), lit("1", DataTypes.StringType))));+ }+ Assertions.assertFalse(+ policy("jdbc:h2:mem:test").canPrefilter(eq(col("s"), lit("a", DataTypes.StringType))));+ }++ @Test+ void testDisabledPredicatePushdownKeepsEachResidualOnce() {+ JDBCOptions options =+ new JDBCOptions(+ new HashMap<String, String>()+ .updated("url", URL)+ .updated("dbtable", "t")+ .updated("driver", "org.postgresql.Driver")+ .updated("pushDownPredicate", "false"));+ SparkJdbcScanBuilder builder =+ new SparkJdbcScanBuilder(+ new JDBCScanBuilder(+ mock(SparkSession.class, RETURNS_DEEP_STUBS), sparkSchema(), options),+ policy());+ Predicate prefilter = eq(col("s"), lit("a", DataTypes.StringType));+ Predicate numeric = eq(col("id"), lit(1, DataTypes.IntegerType));+ Predicate[] residual = builder.pushPredicates(new Predicate[] {prefilter, numeric});+ Assertions.assertEquals(List.of(prefilter, numeric), Arrays.asList(residual));+ Assertions.assertEquals(0, builder.pushedPredicates().length);+ }++ @Test+ @SuppressWarnings("deprecation")+ void testNullChecksAndCountsUseOnlyNullPreservingColumns() {+ SparkJdbcPushDownPolicy policy = policy();+ for (String name : new String[] {"s", "v", "b", "u", "tags", "ts", "tz", "id"}) {+ Assertions.assertTrue(policy.canPush(predicate("IS_NULL", col(name))), name);+ Assertions.assertTrue(policy.canPush(predicate("IS_NOT_NULL", col(name))), name);+ Assertions.assertTrue(policy.canPushAggregate(new Count(col(name), false)), name);+ }+ Assertions.assertFalse(policy.canPushAggregate(new Count(col("s"), true)));+ Assertions.assertFalse(policy.canPushAggregate(new Count(col("tags"), true)));+ Assertions.assertFalse(+ policy.canPushAggregate(new Count(new Cast(col("s"), DataTypes.IntegerType), false)));+ Assertions.assertTrue(policy.canPushAggregate(new Count(col("id"), true)));+ for (boolean externalFirst : new boolean[] {true, false}) {+ Column externalColumn = column("VALUE", Types.ExternalType.of("pair"));+ Column stringColumn = column("value", Types.StringType.get());+ Column[] columns =+ externalFirst+ ? new Column[] {externalColumn, stringColumn}+ : new Column[] {stringColumn, externalColumn};+ StructType schema =+ new StructType().add("VALUE", DataTypes.StringType).add("value", DataTypes.StringType);+ SparkJdbcPushDownPolicy collision =+ new SparkJdbcPushDownPolicy(columns, schema, schema, DIALECT, URL);+ Assertions.assertFalse(collision.canPush(predicate("IS_NULL", col("VALUE"))));+ Assertions.assertFalse(collision.canPushAggregate(new Count(col("VALUE"), false)));+ Assertions.assertFalse(+ collision.canPrefilter(eq(col("VALUE"), lit("not-a-composite", DataTypes.StringType))));+ Assertions.assertFalse(+ collision.canPrefilter(eq(col("value"), lit("text", DataTypes.StringType))));+ }+ Type external = Types.ExternalType.of("pair");+ for (Type type :+ new Type[] {+ external,+ Types.ListType.nullable(external),+ Types.MapType.of(external, Types.StringType.get(), true),+ Types.MapType.of(Types.StringType.get(), external, true),+ Types.StructType.of(Types.StructType.Field.of("p", external, true, null)),+ Types.ListType.nullable(+ Types.StructType.of(Types.StructType.Field.of("p", external, true, null)))+ }) {+ StructType schema =+ new StructType().add("value", new SparkJdbcTypeConverter().toSparkType(type));+ SparkJdbcPushDownPolicy externalPolicy =+ new SparkJdbcPushDownPolicy(+ new Column[] {column("value", type)}, schema, schema, DIALECT, URL);+ Assertions.assertFalse(+ externalPolicy.canPush(predicate("IS_NULL", col("value"))), type.simpleString());+ Assertions.assertFalse(+ externalPolicy.canPush(predicate("IS_NOT_NULL", col("value"))), type.simpleString());+ Assertions.assertFalse(+ externalPolicy.canPushAggregate(new Count(col("value"), false)), type.simpleString());+ }+ }++ private static Predicate predicate(String name, Expression... children) {+ return new Predicate(name, children);+ }++ @Test+ void testCaseDistinctTimestampColumnsUseTheirOwnReaderTypes() {+ Column[] columns = {+ column("ts", Types.TimestampType.withoutTimeZone()),+ column("TS", Types.TimestampType.withTimeZone())+ };+ StructType schema =+ new StructType().add("ts", DataTypes.TimestampNTZType).add("TS", DataTypes.TimestampType);+ for (StructType reader :+ new StructType[] {+ schema, new StructType().add(schema.fields()[1]).add(schema.fields()[0])+ }) {+ SparkJdbcPushDownPolicy policy =+ new SparkJdbcPushDownPolicy(columns, reader, schema, DIALECT, URL);+ Assertions.assertTrue(policy.canPushAggregate(new Max(col("ts"))));+ Assertions.assertTrue(policy.canPushAggregate(new Max(col("TS"))));+ }+ }++ private static SparkJdbcPushDownPolicy policy() {+ return policy(URL);+ }++ private static SparkJdbcPushDownPolicy policy(String url) {+ Column[] columns = {+ column("id", Types.IntegerType.get()),+ column("s", Types.StringType.get()),+ column("v", Types.VarCharType.of(10)),+ column("b", Types.BinaryType.get()),+ column("u", Types.UUIDType.get()),+ column("j", Types.ExternalType.of("jsonb")),+ column("tags", Types.ListType.nullable(Types.StringType.get())),+ column("ts", Types.TimestampType.withoutTimeZone()),+ column("tz", Types.TimestampType.withTimeZone()),+ column("d", Types.DateType.get()),+ column("si", Types.ShortType.get())+ };+ // The reader sees timestamptz as NTZ, as Spark 3.5 does under preferTimestampNTZ.+ StructType reader = new StructType();+ for (StructField field : sparkSchema().fields()) {+ if (field.name().equals("tz")) {+ reader = reader.add(field.copy("tz", DataTypes.TimestampNTZType, true, field.metadata()));+ } else if (field.name().equals("si")) {+ reader = reader.add(field.copy("si", DataTypes.IntegerType, true, field.metadata()));+ } else {+ reader = reader.add(field);+ }+ }+ return new SparkJdbcPushDownPolicy(columns, reader, sparkSchema(), JdbcDialects.get(url), url);+ }++ private static StructType sparkSchema() {+ return new StructType()+ .add("id", DataTypes.IntegerType)+ .add("s", DataTypes.StringType)+ .add("v", DataTypes.StringType)+ .add("b", DataTypes.BinaryType)+ .add("u", DataTypes.StringType)+ .add("j", DataTypes.StringType)+ .add("tags", DataTypes.createArrayType(DataTypes.StringType))+ .add("ts", DataTypes.TimestampNTZType)+ .add("tz", DataTypes.TimestampType)+ .add("d", DataTypes.DateType)+ .add("si", DataTypes.ShortType);+ }++ private static Column column(String name, Type type) {+ return Column.of(name, type);+ }++ private static Expression col(String name) {+ return Expressions.column(name);+ }++ private static <T> LiteralValue<?> lit(T value, DataType type) {+ Object internal =+ value instanceof String && DataTypes.StringType.equals(type)+ ? UTF8String.fromString((String) value)+ : value;+ return new LiteralValue<>(internal, type);+ }++ private static Predicate eq(Expression left, Expression right) {+ return new Predicate("=", new Expression[] {left, right});+ }++ private static SortOrder sort(Expression expression) {+ return Expressions.sort(expression, SortDirection.ASCENDING, NullOrdering.NULLS_FIRST);+ }+}diff --git a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/jdbc/TestSparkJdbcReadCorrectness.java b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/jdbc/TestSparkJdbcReadCorrectness.javanew file mode 100644index 0000000000..c509dbbe7c--- /dev/null+++ b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/jdbc/TestSparkJdbcReadCorrectness.java@@ -0,0 +1,418 @@+/*+ * 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.gravitino.spark.connector.jdbc;++import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++import java.sql.Connection;+import java.sql.DriverManager;+import java.sql.Statement;+import java.util.ArrayList;+import java.util.List;+import java.util.Map;+import java.util.TimeZone;+import java.util.regex.Matcher;+import java.util.regex.Pattern;+import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.Table;+import org.apache.gravitino.rel.types.Types;+import org.apache.gravitino.spark.connector.SparkTransformConverter;+import org.apache.spark.sql.Dataset;+import org.apache.spark.sql.Row;+import org.apache.spark.sql.SparkSession;+import org.apache.spark.sql.connector.catalog.Identifier;+import org.apache.spark.sql.execution.datasources.v2.jdbc.JDBCScanBuilder;+import org.apache.spark.sql.execution.datasources.v2.jdbc.JDBCTable;+import org.apache.spark.sql.execution.datasources.v2.jdbc.JDBCTableCatalog;+import org.apache.spark.sql.functions;+import org.apache.spark.sql.types.StructType;+import org.apache.spark.sql.util.CaseInsensitiveStringMap;+import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Tag;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestInstance;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;+import org.testcontainers.containers.GenericContainer;+import org.testcontainers.containers.wait.strategy.Wait;++/**+ * Live Spark scans with the NTZ option on keep string, array, binary, and timestamp semantics,+ * while safe expressions are still pushed down.+ */+@Tag("gravitino-docker-test")+@TestInstance(TestInstance.Lifecycle.PER_CLASS)+public class TestSparkJdbcReadCorrectness {++ private static final String[] ZONES = {"UTC", "America/Los_Angeles", "Asia/Shanghai"};++ private GenericContainer<?> pg;+ private SparkSession spark;++ /** Minimal catalog that installs the production JDBC table wrapper. */+ @SuppressWarnings("overrides")+ public static class SafeCatalog extends JDBCTableCatalog {+ private boolean useTimestampNtz;++ /** {@inheritDoc} */+ @Override+ public void initialize(String name, CaseInsensitiveStringMap options) {+ super.initialize(name, options);+ useTimestampNtz = Boolean.parseBoolean(options.get("preferTimestampNTZ"));+ }++ /** {@inheritDoc} */+ @Override+ public JDBCTable loadTable(Identifier identifier) {+ JDBCTable physical = (JDBCTable) super.loadTable(identifier);+ Table metadata = mock(Table.class);+ when(metadata.columns()).thenReturn(columns(identifier.name()));+ return new SparkJdbcTable(+ identifier,+ metadata,+ physical,+ this,+ JdbcPropertiesConverter.getInstance(),+ new SparkTransformConverter(false),+ new SparkJdbcTypeConverter(useTimestampNtz));+ }++ private static Column[] columns(String table) {+ switch (table) {+ case "timestamp_only":+ return new Column[] {+ Column.of("id", Types.IntegerType.get()),+ Column.of("ts", Types.TimestampType.withoutTimeZone())+ };+ case "timestamp_array_collisions":+ return new Column[] {+ Column.of("ts", Types.ListType.nullable(Types.TimestampType.withoutTimeZone())),+ Column.of("TS", Types.ListType.nullable(Types.TimestampType.withTimeZone()))+ };+ case "zoned_only":+ return new Column[] {+ Column.of("id", Types.IntegerType.get()),+ Column.of("tz", Types.TimestampType.withTimeZone())+ };+ default:+ return new Column[] {+ Column.of("id", Types.IntegerType.get()),+ Column.of("s", Types.StringType.get()),+ Column.of("b", Types.BinaryType.get()),+ Column.of("ts", Types.TimestampType.withoutTimeZone()),+ Column.of("tz", Types.TimestampType.withTimeZone()),+ Column.of("tags", Types.ListType.nullable(Types.StringType.get())),+ Column.of("tss", Types.ListType.nullable(Types.TimestampType.withoutTimeZone()))+ };+ }+ }+ }++ @BeforeAll+ void startPostgreSql() throws Exception {+ pg =+ new GenericContainer<>("postgres:16")+ .withEnv("POSTGRES_DB", "test")+ .withEnv("POSTGRES_PASSWORD", "test")+ .withExposedPorts(5432)+ .waitingFor(+ Wait.forLogMessage(".*database system is ready to accept connections.*\\n", 2));+ pg.start();+ String url = "jdbc:postgresql://" + pg.getHost() + ":" + pg.getMappedPort(5432) + "/test";+ try (Connection connection = DriverManager.getConnection(url, "postgres", "test");+ Statement statement = connection.createStatement()) {+ statement.execute(+ "CREATE TABLE samples(id int, s text COLLATE \"en-US-x-icu\", b bytea, ts timestamp,"+ + " tz timestamptz, tags text[] COLLATE \"en-US-x-icu\", tss timestamp[])");+ statement.execute(+ "INSERT INTO samples VALUES"+ + " (1, 'a', decode('01','hex'), '2026-10-31 12:34:56.123456',"+ + " '2026-10-31 12:34:56.123456+00', '{a}', '{\"2024-01-02 03:04:05\"}'),"+ + " (2, 'B', decode('02','hex'), '0001-01-01 00:00:00',"+ + " '2026-10-31 12:34:56.123456+00', '{B}', null),"+ + " (3, '_x', decode('01','hex'), null, null, '{_x}', null)");+ statement.execute("CREATE TABLE timestamp_only(id int, ts timestamp)");+ statement.execute(+ "INSERT INTO timestamp_only VALUES (1, '2024-01-01 03:04:05'), (2, '2024-01-03 03:04:05')");+ statement.execute("CREATE TABLE zoned_only(id int, tz timestamptz)");+ statement.execute(+ "INSERT INTO zoned_only VALUES (1, '2024-01-01 00:00:00+00'), (2, '2024-01-02 00:00:00+00')");+ statement.execute(+ "CREATE TABLE timestamp_array_collisions(ts timestamp[], \"TS\" timestamptz[])");+ statement.execute(+ "INSERT INTO timestamp_array_collisions VALUES "+ + "(ARRAY[TIMESTAMP '2024-01-02 00:00:00'], "+ + "ARRAY[TIMESTAMPTZ '2024-01-02 00:00:00+00'])");+ }+ spark =+ SparkSession.builder()+ .master("local[1]")+ .appName("jdbc-read-regression")+ .config("spark.ui.enabled", "false")+ .config("spark.sql.catalog.nativejdbc", JDBCTableCatalog.class.getName())+ .config("spark.sql.catalog.nativejdbc.url", url)+ .config("spark.sql.catalog.nativejdbc.user", "postgres")+ .config("spark.sql.catalog.nativejdbc.password", "test")+ .config("spark.sql.catalog.nativejdbc.driver", "org.postgresql.Driver")+ .config("spark.sql.catalog.nativejdbc.preferTimestampNTZ", "true")+ .config("spark.sql.catalog.legacy", SafeCatalog.class.getName())+ .config("spark.sql.catalog.legacy.url", url)+ .config("spark.sql.catalog.legacy.user", "postgres")+ .config("spark.sql.catalog.legacy.password", "test")+ .config("spark.sql.catalog.legacy.driver", "org.postgresql.Driver")+ .config("spark.sql.catalog.legacy.preferTimestampNTZ", "false")+ .config("spark.sql.catalog.safe", SafeCatalog.class.getName())+ .config("spark.sql.catalog.safe.url", url)+ .config("spark.sql.catalog.safe.user", "postgres")+ .config("spark.sql.catalog.safe.password", "test")+ .config("spark.sql.catalog.safe.driver", "org.postgresql.Driver")+ .config("spark.sql.catalog.safe.preferTimestampNTZ", "true")+ .config("spark.sql.catalog.safe.pushDownPredicate", "true")+ .config("spark.sql.catalog.safe.pushDownAggregate", "true")+ .config("spark.sql.catalog.safe.pushDownLimit", "true")+ .config("spark.sql.catalog.safe.pushDownOffset", "true")+ .getOrCreate();+ }++ @AfterAll+ void stop() {+ if (spark != null) {+ spark.stop();+ }+ if (pg != null) {+ pg.stop();+ }+ }++ @Test+ void testSensitiveExpressionsKeepSparkSemantics() {+ for (String zone : ZONES) {+ spark.conf().set("spark.sql.session.timeZone", zone);+ Assertions.assertEquals(+ 1793450096123456L,+ spark+ .sql("SELECT unix_micros(tz) FROM safe.public.samples WHERE id=1")+ .head()+ .getLong(0));+ Row aggregate = spark.sql("SELECT min(s),max(s) FROM safe.public.samples").head();+ Assertions.assertEquals("B", aggregate.getString(0));+ Assertions.assertEquals("a", aggregate.getString(1));+ Assertions.assertEquals(+ "B",+ spark.sql("SELECT s FROM safe.public.samples ORDER BY s LIMIT 1").head().getString(0));+ Assertions.assertEquals(+ List.of(1, 3), ids("SELECT id FROM safe.public.samples WHERE b = X'01' ORDER BY id"));+ // Arrays compare with the element collation in PostgreSQL, so they also stay in Spark.+ Assertions.assertEquals(+ List.of(2), ids("SELECT id FROM safe.public.samples ORDER BY tags LIMIT 1"));+ Assertions.assertEquals(+ "[a]",+ spark.sql("SELECT cast(max(tags) AS string) FROM safe.public.samples").head().get(0));+ Assertions.assertEquals(+ "2026-10-31 12:34:56.123456",+ spark+ .sql("SELECT cast(ts as string) FROM safe.public.samples WHERE id=1")+ .head()+ .getString(0));+ Assertions.assertEquals(+ "0001-01-01 00:00:00",+ spark+ .sql("SELECT cast(ts as string) FROM safe.public.samples WHERE id=2")+ .head()+ .getString(0));+ // PostgreSQL EXTRACT(SECOND) keeps fractions, while Spark second() does not.+ Assertions.assertEquals(+ List.of(1), ids("SELECT id FROM safe.public.samples WHERE second(ts) = 56"));+ // Spark 3.5 reads timestamp array elements as TIMESTAMP; reading them must not fail.+ Assertions.assertEquals(+ 1, spark.sql("SELECT tss FROM safe.public.samples WHERE id=1").head().getList(0).size());+ }+ String stringFilter = pushedFilters("SELECT id FROM safe.public.samples WHERE s = 'a'");+ Assertions.assertTrue(stringFilter.contains("s ="), stringFilter);+ String stringFilterPlan = plan("SELECT id FROM safe.public.samples WHERE s = 'a'");+ Assertions.assertTrue(stringFilterPlan.contains("Filter "), stringFilterPlan);+ // A filter kept in Spark also keeps the limit and the aggregate of the query in Spark.+ String limitAfterStringFilter =+ plan("SELECT id FROM safe.public.samples WHERE s = 'a' LIMIT 1");+ Assertions.assertFalse(limitAfterStringFilter.contains("PushedLimit"), limitAfterStringFilter);+ String countAfterStringFilter = plan("SELECT count(*) FROM safe.public.samples WHERE s = 'a'");+ Assertions.assertFalse(+ countAfterStringFilter.contains("PushedAggregates: [COUNT"), countAfterStringFilter);+ Assertions.assertEquals(+ 1L, spark.sql("SELECT count(*) FROM safe.public.samples WHERE s = 'a'").head().getLong(0));+ String stringTopN = plan("SELECT s FROM safe.public.samples ORDER BY s LIMIT 1");+ Assertions.assertFalse(stringTopN.contains("PushedTopN"), stringTopN);+ }++ @Test+ void testSafeExpressionsArePushedOnTablesWithStringColumns() {+ String filter = pushedFilters("SELECT id FROM safe.public.samples WHERE id = 1");+ Assertions.assertTrue(filter.contains("id = 1"), filter);+ String limit = plan("SELECT id FROM safe.public.samples LIMIT 2");+ Assertions.assertTrue(limit.contains("PushedLimit: LIMIT 2"), limit);+ String count = plan("SELECT count(*) FROM safe.public.samples WHERE id > 0");+ Assertions.assertTrue(count.contains("PushedAggregates: [COUNT(*)]"), count);+ String topN = plan("SELECT id FROM safe.public.samples ORDER BY id LIMIT 2");+ Assertions.assertTrue(topN.contains("PushedTopN"), topN);+ Assertions.assertEquals(+ List.of(1, 2), ids("SELECT id FROM safe.public.samples ORDER BY id LIMIT 2"));+ Assertions.assertEquals(+ 3L, spark.sql("SELECT count(*) FROM safe.public.samples WHERE id > 0").head().getLong(0));+ }++ @Test+ void testTimestampFilterOnTableWithoutStringColumns() {+ boolean ntzLiteralSupported = !spark.version().startsWith("3.5.");+ String query =+ "SELECT id FROM safe.public.timestamp_only"+ + " WHERE ts > TIMESTAMP_NTZ '2024-01-02 03:04:05.123456'";+ String filter = pushedFilters(query);+ Assertions.assertEquals(ntzLiteralSupported, filter.contains("ts >"), filter);+ Assertions.assertTrue(+ pushedFilters("SELECT id FROM safe.public.timestamp_only WHERE id = 1").contains("id = 1"));+ for (String zone : ZONES) {+ spark.conf().set("spark.sql.session.timeZone", zone);+ Assertions.assertEquals(List.of(2), ids(query));+ // A TIMESTAMP literal casts the NTZ column in the session time zone; it must stay in Spark.+ // The literal is 3 hours before row 2, so a pushed cast in another time zone drops it.+ Assertions.assertEquals(+ List.of(2),+ ids(+ "SELECT id FROM safe.public.timestamp_only"+ + " WHERE ts > TIMESTAMP '2024-01-03 00:00:00'"));+ Assertions.assertEquals(+ "2024-01-03 03:04:05",+ spark+ .sql("SELECT cast(max(ts) AS string) FROM safe.public.timestamp_only")+ .head()+ .getString(0));+ }+ }++ @Test+ void testZonedTimestampTableKeepsPushdownAndAggregateTypes() {+ // On Spark 3.5 the reader sees timestamptz as NTZ while Spark sees TIMESTAMP.+ Assertions.assertTrue(+ pushedFilters("SELECT id FROM safe.public.zoned_only WHERE id = 1").contains("id = 1"));+ for (String zone : ZONES) {+ spark.conf().set("spark.sql.session.timeZone", zone);+ Assertions.assertEquals(+ 1704153600000000L,+ spark.sql("SELECT unix_micros(max(tz)) FROM safe.public.zoned_only").head().getLong(0));+ // Date parts and casts of a TIMESTAMP column use the session time zone in Spark.+ boolean utc = zone.equals("UTC");+ Assertions.assertEquals(+ utc ? List.of(1, 2) : List.of(),+ ids("SELECT id FROM safe.public.zoned_only WHERE hour(tz) = 0 ORDER BY id"));+ Assertions.assertEquals(+ zone.equals("America/Los_Angeles") ? List.of(-1, 0) : List.of(0, 1),+ ids(+ "SELECT datediff(d, DATE '2024-01-01') FROM (SELECT cast(tz AS date) AS d, count(*)"+ + " FROM safe.public.zoned_only GROUP BY 1) ORDER BY 1"));+ }+ }++ @ParameterizedTest+ @ValueSource(strings = {"safe", "legacy"})+ void testPerReadTimestampOptionCannotOverrideCatalog(String name) {+ TimeZone original = TimeZone.getDefault();+ String originalSessionZone = spark.conf().get("spark.sql.session.timeZone");+ try {+ TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));+ spark.conf().set("spark.sql.session.timeZone", "UTC");+ boolean ntz = name.equals("safe");+ for (String key :+ new String[] {"preferTimestampNTZ", "prefertimestampntz", "PrEfErTiMeStAmPnTz"}) {+ CaseInsensitiveStringMap options =+ new CaseInsensitiveStringMap(+ Map.of(key, Boolean.toString(!ntz), "pushDownLimit", "false"));+ Map<String, String> originalOptions = Map.copyOf(options.asCaseSensitiveMap());+ JDBCTableCatalog catalog =+ (JDBCTableCatalog) spark.sessionState().catalogManager().catalog(name);+ SparkJdbcTable table =+ (SparkJdbcTable)+ catalog.loadTable(Identifier.of(new String[] {"public"}, "timestamp_only"));+ JDBCScanBuilder builder = table.newScanBuilder(options);+ Assertions.assertEquals(ntz, builder.jdbcOptions().preferTimestampNTZ());+ Assertions.assertFalse(builder.jdbcOptions().pushDownLimit());+ Assertions.assertEquals(originalOptions, options.asCaseSensitiveMap());+ Dataset<Row> read =+ spark.read().option(key, Boolean.toString(!ntz)).table(name + ".public.timestamp_only");+ String expected =+ read.select("ts").collectAsList().stream()+ .map(row -> row.get(0).toString())+ .max(String::compareTo)+ .get();+ Assertions.assertEquals(expected, read.agg(functions.max("ts")).head().get(0).toString());+ }+ } finally {+ spark.conf().set("spark.sql.session.timeZone", originalSessionZone);+ TimeZone.setDefault(original);+ }+ }++ @Test+ void testCaseSensitiveTimestampArraysMatchNativeReader() {+ String originalCaseSensitive = spark.conf().get("spark.sql.caseSensitive");+ String originalSessionZone = spark.conf().get("spark.sql.session.timeZone");+ TimeZone originalJvmZone = TimeZone.getDefault();+ try {+ spark.conf().set("spark.sql.caseSensitive", "true");+ spark.conf().set("spark.sql.session.timeZone", "America/Los_Angeles");+ TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));+ String source = "nativejdbc.public.timestamp_array_collisions";+ String wrapped = "safe.public.timestamp_array_collisions";+ StructType readerSchema = spark.table(source).schema();+ Assertions.assertEquals(+ readerSchema.catalogString(), spark.table(wrapped).schema().catalogString());+ String projection = "SELECT CAST(ts AS STRING), CAST(`TS` AS STRING) FROM ";+ List<Row> expected = spark.sql(projection + source).collectAsList();+ Assertions.assertEquals("[2024-01-01 16:00:00]", expected.get(0).getString(1));+ Assertions.assertEquals(expected, spark.sql(projection + wrapped).collectAsList());+ } finally {+ spark.conf().set("spark.sql.caseSensitive", originalCaseSensitive);+ spark.conf().set("spark.sql.session.timeZone", originalSessionZone);+ TimeZone.setDefault(originalJvmZone);+ }+ }++ private List<Integer> ids(String sql) {+ List<Integer> ids = new ArrayList<>();+ for (Row row : spark.sql(sql).collectAsList()) {+ ids.add(row.getInt(0));+ }+ return ids;+ }++ private String pushedFilters(String sql) {+ String plan = plan(sql);+ Matcher matcher = Pattern.compile("PushedFilters: \\[([^\\]]*)\\]").matcher(plan);+ Assertions.assertTrue(matcher.find(), plan);+ return matcher.group(1);+ }++ private String plan(String sql) {+ Dataset<Row> dataset = spark.sql(sql);+ return dataset.queryExecution().executedPlan().toString();+ }+}diff --git a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/jdbc/TestSparkJdbcStringPushDown.java b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/jdbc/TestSparkJdbcStringPushDown.javanew file mode 100644index 0000000000..27c36453e1--- /dev/null+++ b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/jdbc/TestSparkJdbcStringPushDown.java@@ -0,0 +1,328 @@+/*+ * 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.gravitino.spark.connector.jdbc;++import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++import java.sql.Connection;+import java.sql.DriverManager;+import java.sql.PreparedStatement;+import java.sql.Statement;+import java.util.List;+import java.util.stream.Collectors;+import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.Table;+import org.apache.gravitino.rel.types.Types;+import org.apache.gravitino.spark.connector.SparkTransformConverter;+import org.apache.spark.sql.Dataset;+import org.apache.spark.sql.Row;+import org.apache.spark.sql.SparkSession;+import org.apache.spark.sql.connector.catalog.Identifier;+import org.apache.spark.sql.connector.expressions.Expression;+import org.apache.spark.sql.connector.expressions.Expressions;+import org.apache.spark.sql.connector.expressions.LiteralValue;+import org.apache.spark.sql.connector.expressions.filter.Predicate;+import org.apache.spark.sql.execution.datasources.v2.jdbc.JDBCTable;+import org.apache.spark.sql.execution.datasources.v2.jdbc.JDBCTableCatalog;+import org.apache.spark.sql.jdbc.JdbcDialects;+import org.apache.spark.sql.types.DataType;+import org.apache.spark.sql.types.DataTypes;+import org.apache.spark.sql.types.StructType;+import org.apache.spark.unsafe.types.UTF8String;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Tag;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;+import org.testcontainers.containers.GenericContainer;+import org.testcontainers.containers.wait.strategy.Wait;++/** PostgreSQL and MySQL string prefilters keep Spark semantics and reduce source rows. */+@Tag("gravitino-docker-test")+public class TestSparkJdbcStringPushDown {++ /** A real JDBC reader with the production Gravitino table wrapper. */+ @SuppressWarnings("overrides")+ public static class StringCatalog extends JDBCTableCatalog {+ /** {@inheritDoc} */+ @Override+ public JDBCTable loadTable(Identifier identifier) {+ JDBCTable physical = (JDBCTable) super.loadTable(identifier);+ Table metadata = mock(Table.class);+ Column[] columns;+ if (identifier.name().equals("composites")) {+ columns =+ new Column[] {+ Column.of("id", Types.IntegerType.get()),+ Column.of("p", Types.ExternalType.of("pair"))+ };+ } else if (identifier.name().equals("collisions")) {+ columns =+ new Column[] {+ Column.of("id", Types.IntegerType.get()),+ Column.of("value", Types.StringType.get()),+ Column.of("VALUE", Types.ExternalType.of("pair"))+ };+ } else {+ columns =+ new Column[] {+ Column.of("id", Types.IntegerType.get()), Column.of("s", Types.StringType.get())+ };+ }+ when(metadata.columns()).thenReturn(columns);+ return new SparkJdbcTable(+ identifier,+ metadata,+ physical,+ this,+ JdbcPropertiesConverter.getInstance(),+ new SparkTransformConverter(false),+ new SparkJdbcTypeConverter());+ }+ }++ @ParameterizedTest+ @ValueSource(strings = {"postgres", "mysql"})+ void testStringPredicatesKeepResidualsAndSafePushdown(String backend) throws Exception {+ boolean postgres = backend.equals("postgres");+ int port = postgres ? 5432 : 3306;+ String user = postgres ? "postgres" : "root";+ try (GenericContainer<?> database =+ postgres+ ? new GenericContainer<>("postgres:16")+ .withEnv("POSTGRES_DB", "test")+ .withEnv("POSTGRES_PASSWORD", "test")+ .withExposedPorts(port)+ .waitingFor(+ Wait.forLogMessage(".*database system is ready to accept connections.*\\n", 2))+ : new GenericContainer<>("mysql:8.0")+ .withEnv("MYSQL_DATABASE", "test")+ .withEnv("MYSQL_ROOT_PASSWORD", "test")+ .withEnv("MYSQL_ROOT_HOST", "%")+ .withExposedPorts(port)+ .waitingFor(Wait.forLogMessage(".*mysqld: ready for connections.*\\n", 2))) {+ database.start();+ String url =+ "jdbc:"+ + (postgres ? "postgresql" : "mysql")+ + "://"+ + database.getHost()+ + ":"+ + database.getMappedPort(port)+ + "/test"+ + (postgres ? "" : "?allowPublicKeyRetrieval=true&useSSL=false");+ try (Connection connection = DriverManager.getConnection(url, user, "test");+ Statement statement = connection.createStatement()) {+ statement.execute(+ "CREATE TABLE strings(id int, s "+ + (postgres+ ? "text COLLATE \"en-US-x-icu\""+ : "varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci")+ + ")");+ if (postgres) {+ statement.execute("CREATE TYPE pair AS (x int, y int)");+ statement.execute("CREATE TABLE composites(id int, p pair)");+ statement.execute("CREATE TABLE collisions(id int, value text, \"VALUE\" pair)");+ statement.execute("INSERT INTO collisions VALUES (1, 'text', ROW(1,NULL))");+ statement.execute(+ "INSERT INTO composites VALUES (1, ROW(1,NULL)), (2, ROW(NULL,NULL)), (3, ROW(1,2)), (4, NULL)");+ }+ try (PreparedStatement insert =+ connection.prepareStatement("INSERT INTO strings VALUES (?, ?)")) {+ String[] values = {"v500", "a", "A", "a ", null, "C:\\temp", "abc\\", "O'Reilly"};+ for (int i = 0; i < values.length; i++) {+ insert.setInt(1, i + 1);+ insert.setString(2, values[i]);+ insert.executeUpdate();+ }+ }+ }+ try (SparkSession spark =+ SparkSession.builder()+ .master("local[1]")+ .appName("string-pushdown-regression")+ .config("spark.ui.enabled", "false")+ .config("spark.sql.catalog.strings", StringCatalog.class.getName())+ .config("spark.sql.catalog.strings.url", url)+ .config("spark.sql.catalog.strings.user", user)+ .config("spark.sql.catalog.strings.password", "test")+ .config(+ "spark.sql.catalog.strings.driver",+ postgres ? "org.postgresql.Driver" : "com.mysql.cj.jdbc.Driver")+ .getOrCreate()) {+ if (spark.version().startsWith("4.")) {+ assertNonBinaryCollationIsNotPrefiltered(url);+ }+ String table = "strings." + (postgres ? "public" : "test") + ".strings";+ if (postgres) {+ assertCompositeNullChecksStayInSpark(spark);+ assertCaseSensitiveColumnsDoNotSharePrefilters(spark);+ }+ assertPrefilter(spark, table, "s = 'V500'", List.of());+ assertPrefilter(spark, table, "s = 'a'", List.of(2));+ assertPrefilter(spark, table, "s IN ('a', 'v500')", List.of(1, 2));+ assertPrefilter(spark, table, "s = \"O'Reilly\"", List.of(8));+ assertKept(spark, table, "NOT (s = 'V500')", List.of(1, 2, 3, 4, 6, 7, 8));+ assertKept(spark, table, "s NOT IN ('a', 'v500')", List.of(3, 4, 6, 7, 8));+ assertKept(spark, table, "s = r'C:\\temp'", List.of(6));+ assertKept(spark, table, "s = concat('abc', chr(92))", List.of(7));+ String nullCount = "SELECT count(*) FROM " + table + " WHERE s IS NULL";+ String nullPlan = plan(spark, nullCount);+ Assertions.assertTrue(nullPlan.contains("IS NULL"), nullPlan);+ Assertions.assertTrue(nullPlan.contains("PushedAggregates: [COUNT(*)]"), nullPlan);+ Assertions.assertFalse(nullPlan.contains("Filter "), nullPlan);+ Assertions.assertEquals(1L, spark.sql(nullCount).head().getLong(0));+ Assertions.assertEquals(+ 7L,+ spark.sql("SELECT count(*) FROM " + table + " WHERE s IS NOT NULL").head().getLong(0));+ String columnCount = "SELECT count(s) FROM " + table;+ String columnCountPlan = plan(spark, columnCount);+ Assertions.assertTrue(+ columnCountPlan.contains("PushedAggregates: [COUNT(s)]"), columnCountPlan);+ Assertions.assertEquals(7L, spark.sql(columnCount).head().getLong(0));+ String distinctCount = "SELECT count(DISTINCT s) FROM " + table;+ String distinctPlan = plan(spark, distinctCount);+ Assertions.assertFalse(distinctPlan.contains("PushedAggregates: [COUNT"), distinctPlan);+ Assertions.assertEquals(7L, spark.sql(distinctCount).head().getLong(0));+ String limited = "SELECT id FROM " + table + " WHERE s = 'a' LIMIT 1";+ Assertions.assertFalse(plan(spark, limited).contains("PushedLimit"));+ Assertions.assertEquals(2, spark.sql(limited).head().getInt(0));+ String count = "SELECT count(*) FROM " + table + " WHERE s = 'a'";+ Assertions.assertFalse(plan(spark, count).contains("PushedAggregates: [COUNT"));+ Assertions.assertEquals(1L, spark.sql(count).head().getLong(0));+ }+ }+ }++ private static void assertCompositeNullChecksStayInSpark(SparkSession spark) {+ String table = "strings.public.composites";+ for (String predicate : new String[] {"p IS NULL", "p IS NOT NULL", "p = '(1,)'"}) {+ String sql = "SELECT id FROM " + table + " WHERE " + predicate + " ORDER BY id";+ String actualPlan = plan(spark, sql);+ Assertions.assertTrue(actualPlan.contains("Filter "), actualPlan);+ String pushed = actualPlan.substring(actualPlan.indexOf("PushedFilters:"));+ Assertions.assertFalse(+ pushed.contains("p IS NULL") || pushed.contains("p IS NOT NULL"), pushed);+ List<Integer> expected =+ predicate.equals("p IS NULL")+ ? List.of(4)+ : predicate.equals("p IS NOT NULL") ? List.of(1, 2, 3) : List.of(1);+ Assertions.assertEquals(+ expected,+ spark.sql(sql).collectAsList().stream()+ .map(row -> row.getInt(0))+ .collect(Collectors.toList()));+ }+ String count = "SELECT count(*) FROM " + table + " WHERE p IS NOT NULL";+ String countPlan = plan(spark, count);+ Assertions.assertFalse(countPlan.contains("PushedAggregates: [COUNT"), countPlan);+ Assertions.assertEquals(3L, spark.sql(count).head().getLong(0));+ String columnCount = "SELECT count(p) FROM " + table;+ String columnCountPlan = plan(spark, columnCount);+ Assertions.assertFalse(columnCountPlan.contains("PushedAggregates: [COUNT"), columnCountPlan);+ Assertions.assertEquals(3L, spark.sql(columnCount).head().getLong(0));+ }++ private static void assertCaseSensitiveColumnsDoNotSharePrefilters(SparkSession spark) {+ String original = spark.conf().get("spark.sql.caseSensitive");+ try {+ spark.conf().set("spark.sql.caseSensitive", "true");+ String table = "strings.public.collisions";+ for (String predicate :+ new String[] {"`VALUE` = 'not-a-composite'", "`VALUE` = '(1,)'", "value = 'text'"}) {+ String sql = "SELECT id FROM " + table + " WHERE " + predicate;+ List<Integer> actual =+ spark.sql(sql).collectAsList().stream()+ .map(row -> row.getInt(0))+ .collect(Collectors.toList());+ String actualPlan = plan(spark, sql);+ Assertions.assertTrue(actualPlan.contains("Filter "), actualPlan);+ String pushed = actualPlan.substring(actualPlan.indexOf("PushedFilters:"));+ Assertions.assertFalse(pushed.contains("VALUE =") || pushed.contains("value ="), pushed);+ List<Integer> expected = predicate.contains("not-a-composite") ? List.of() : List.of(1);+ Assertions.assertEquals(expected, actual);+ }+ } finally {+ spark.conf().set("spark.sql.caseSensitive", original);+ }+ }++ private static void assertNonBinaryCollationIsNotPrefiltered(String url) {+ DataType collated = DataType.fromDDL("STRING COLLATE UTF8_LCASE");+ Column[] columns = {Column.of("s", Types.StringType.get())};+ StructType binarySchema = new StructType().add("s", DataTypes.StringType);+ StructType collatedSchema = new StructType().add("s", collated);+ SparkJdbcPushDownPolicy collatedColumn =+ new SparkJdbcPushDownPolicy(+ columns, binarySchema, collatedSchema, JdbcDialects.get(url), url);+ Predicate equality =+ new Predicate(+ "=",+ new Expression[] {+ Expressions.column("s"),+ new LiteralValue<>(UTF8String.fromString("A"), DataTypes.StringType)+ });+ Assertions.assertFalse(collatedColumn.canPrefilter(equality));+ SparkJdbcPushDownPolicy binaryColumn =+ new SparkJdbcPushDownPolicy(+ columns, binarySchema, binarySchema, JdbcDialects.get(url), url);+ Predicate collatedLiteral =+ new Predicate(+ "=",+ new Expression[] {+ Expressions.column("s"), new LiteralValue<>(UTF8String.fromString("A"), collated)+ });+ Assertions.assertFalse(binaryColumn.canPrefilter(collatedLiteral));+ }++ private static void assertPrefilter(+ SparkSession spark, String table, String predicate, List<Integer> expected) {+ String sql = "SELECT id FROM " + table + " WHERE " + predicate + " ORDER BY id";+ String plan = plan(spark, sql);+ Assertions.assertTrue(plan.contains("Filter "), plan);+ String pushed = plan.substring(plan.indexOf("PushedFilters:"));+ Assertions.assertTrue(pushed.contains("s =") || pushed.contains("s IN"), pushed);+ Assertions.assertEquals(+ expected,+ spark.sql(sql).collectAsList().stream()+ .map(row -> row.getInt(0))+ .collect(Collectors.toList()));+ }++ private static void assertKept(+ SparkSession spark, String table, String predicate, List<Integer> expected) {+ String sql = "SELECT id FROM " + table + " WHERE " + predicate + " ORDER BY id";+ String plan = plan(spark, sql);+ Assertions.assertTrue(plan.contains("Filter "), plan);+ String pushed = plan.substring(plan.indexOf("PushedFilters:"));+ Assertions.assertFalse(+ pushed.contains("s =") || pushed.contains("s IN") || pushed.contains("NOT ("), pushed);+ Assertions.assertEquals(+ expected,+ spark.sql(sql).collectAsList().stream()+ .map(row -> row.getInt(0))+ .collect(Collectors.toList()));+ }++ private static String plan(SparkSession spark, String sql) {+ Dataset<Row> result = spark.sql(sql);+ return result.queryExecution().executedPlan().toString();+ }+}diff --git a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/jdbc/TestSparkJdbcTableWriteValidation.java b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/jdbc/TestSparkJdbcTableWriteValidation.javaindex 83eb356876..7a884aa18d 100644--- a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/jdbc/TestSparkJdbcTableWriteValidation.java+++ b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/jdbc/TestSparkJdbcTableWriteValidation.java@@ -33,6 +33,7 @@ import org.apache.spark.sql.connector.write.LogicalWriteInfo;import org.apache.spark.sql.execution.datasources.jdbc.JDBCOptions;import org.apache.spark.sql.execution.datasources.v2.jdbc.JDBCTable;import org.apache.spark.sql.execution.datasources.v2.jdbc.JDBCTableCatalog;+import org.apache.spark.sql.types.DataType;import org.apache.spark.sql.types.DataTypes;import org.apache.spark.sql.types.StructType;import org.apache.spark.sql.util.CaseInsensitiveStringMap;@@ -43,6 +44,48 @@ import scala.collection.immutable.HashMap;/** PostgreSQL write validation before Spark creates or executes a JDBC write. */public class TestSparkJdbcTableWriteValidation {+ @Test+ void testTimestampArraysUseTheReaderElementType() {+ Type timestamps = Types.ListType.nullable(Types.TimestampType.withoutTimeZone());+ // Spark 3.5 reads timestamp array elements as TIMESTAMP even with preferTimestampNTZ.+ SparkJdbcTable spark35 = table(timestamps, DataTypes.createArrayType(DataTypes.TimestampType));+ Assertions.assertEquals(+ DataTypes.createArrayType(DataTypes.TimestampType),+ spark35.schema().fields()[0].dataType());+ SparkJdbcTable spark40 =+ table(timestamps, DataTypes.createArrayType(DataTypes.TimestampNTZType));+ Assertions.assertEquals(+ DataTypes.createArrayType(DataTypes.TimestampNTZType),+ spark40.schema().fields()[0].dataType());+ // Top-level columns keep the converter's type.+ Assertions.assertEquals(+ DataTypes.TimestampNTZType,+ table(Types.TimestampType.withoutTimeZone(), DataTypes.TimestampType)+ .schema()+ .fields()[0]+ .dataType());+ }++ @Test+ void testTimestampArraysKeepCaseDistinctReaderTypes() {+ Column lower = Column.of("ts", Types.ListType.nullable(Types.TimestampType.withoutTimeZone()));+ Column upper = Column.of("TS", Types.ListType.nullable(Types.TimestampType.withTimeZone()));+ DataType ntzArray = DataTypes.createArrayType(DataTypes.TimestampNTZType);+ DataType zonedArray = DataTypes.createArrayType(DataTypes.TimestampType);+ StructType readerSchema = new StructType().add("ts", ntzArray).add("TS", zonedArray);+ for (Column[] columns : new Column[][] {{lower, upper}, {upper, lower}}) {+ for (StructType ordered :+ new StructType[] {+ readerSchema,+ new StructType().add(readerSchema.fields()[1]).add(readerSchema.fields()[0])+ }) {+ SparkJdbcTable table = table(columns, "jdbc:postgresql://localhost/test", ordered);+ Assertions.assertEquals(ntzArray, table.schema().apply("ts").dataType());+ Assertions.assertEquals(zonedArray, table.schema().apply("TS").dataType());+ }+ }+ }+@Testvoid testUnsupportedPostgreSqlColumnsFailBeforeWrite() {for (Type type :@@ -74,9 +117,23 @@ public class TestSparkJdbcTableWriteValidation {}private SparkJdbcTable table(Type type, String url) {+ return table(type, url, new SparkJdbcTypeConverter(true).toSparkType(type));+ }++ private SparkJdbcTable table(Type type, DataType readerType) {+ return table(type, "jdbc:postgresql://localhost/test", readerType);+ }++ private SparkJdbcTable table(Type type, String url, DataType readerType) {+ return table(+ new Column[] {Column.of("special_value", type, null, true, false, null)},+ url,+ new StructType().add("special_value", readerType));+ }++ private SparkJdbcTable table(Column[] columns, String url, StructType readerSchema) {Table metadata = mock(Table.class);- when(metadata.columns())- .thenReturn(new Column[] {Column.of("special_value", type, null, true, false, null)});+ when(metadata.columns()).thenReturn(columns);JDBCOptions options =new JDBCOptions(new HashMap<String, String>()@@ -84,7 +141,7 @@ public class TestSparkJdbcTableWriteValidation {.updated("dbtable", "t").updated("driver", "org.postgresql.Driver"));JDBCTable physical = mock(JDBCTable.class);- when(physical.schema()).thenReturn(new StructType());+ when(physical.schema()).thenReturn(readerSchema);when(physical.jdbcOptions()).thenReturn(options);return new SparkJdbcTable(Identifier.of(new String[] {"public"}, "t"),@@ -93,6 +150,6 @@ public class TestSparkJdbcTableWriteValidation {mock(JDBCTableCatalog.class),JdbcPropertiesConverter.getInstance(),new SparkTransformConverter(false),- new SparkJdbcTypeConverter());+ new SparkJdbcTypeConverter(true));}}diff --git a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/jdbc/TestSparkJdbcTypeConverter.java b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/jdbc/TestSparkJdbcTypeConverter.javaindex 8ead6d53ad..9c66ba95fc 100644--- a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/jdbc/TestSparkJdbcTypeConverter.java+++ b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/jdbc/TestSparkJdbcTypeConverter.java@@ -29,6 +29,15 @@ public class TestSparkJdbcTypeConverter {private final SparkJdbcTypeConverter sparkJdbcTypeConverter = new SparkJdbcTypeConverter();+ @Test+ void testOptInUsesWallClockTimestamps() {+ SparkJdbcTypeConverter converter = new SparkJdbcTypeConverter(true);+ Assertions.assertEquals(+ DataTypes.TimestampNTZType, converter.toSparkType(Types.TimestampType.withoutTimeZone()));+ Assertions.assertEquals(+ DataTypes.TimestampType, converter.toSparkType(Types.TimestampType.withTimeZone()));+ }+@Testvoid testConvertTimestampTypesToSparkTimestamp() {Assertions.assertEquals(diff --git a/trino-connector/src/common/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorMetadata.java b/trino-connector/src/common/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorMetadata.javaindex b72f06a3c5..d1264f04ec 100644--- a/trino-connector/src/common/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorMetadata.java+++ b/trino-connector/src/common/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorMetadata.java@@ -18,6 +18,8 @@*/package org.apache.gravitino.trino.connector.catalog;+import static io.trino.spi.StandardErrorCode.NOT_SUPPORTED;+import com.google.common.base.Preconditions;import com.google.common.base.Strings;import io.airlift.log.Logger;@@ -30,7 +32,6 @@ import java.util.Map;import java.util.Objects;import java.util.Optional;import javax.annotation.Nullable;-import org.apache.commons.lang3.NotImplementedException;import org.apache.gravitino.Catalog;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;@@ -348,7 +349,7 @@ public class CatalogConnectorMetadata {* @param target the name of the target schema*/public void renameSchema(String source, String target) {- throw new NotImplementedException();+ throw new TrinoException(NOT_SUPPORTED, "This connector does not support renaming schemas");}private void applyAlter(SchemaTableName tableName, TableChange... change) {diff --git a/trino-connector/src/common/main/java/org/apache/gravitino/trino/connector/metadata/GravitinoTable.java b/trino-connector/src/common/main/java/org/apache/gravitino/trino/connector/metadata/GravitinoTable.javaindex 8542fe3440..5f5faa7ce9 100644--- a/trino-connector/src/common/main/java/org/apache/gravitino/trino/connector/metadata/GravitinoTable.java+++ b/trino-connector/src/common/main/java/org/apache/gravitino/trino/connector/metadata/GravitinoTable.java@@ -61,8 +61,9 @@ public class GravitinoTable {this.tableName = tableName;ImmutableList.Builder<GravitinoColumn> tableColumns = ImmutableList.builder();- for (int i = 0; i < tableMetadata.columns().length; i++) {- tableColumns.add(new GravitinoColumn(tableMetadata.columns()[i], i));+ Column[] sourceColumns = tableMetadata.columns();+ for (int i = 0; i < sourceColumns.length; i++) {+ tableColumns.add(new GravitinoColumn(sourceColumns[i], i));}this.columns = tableColumns.build();this.comment = tableMetadata.comment();diff --git a/trino-connector/src/common/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorMetadataErrors.java b/trino-connector/src/common/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorMetadataErrors.javaindex b66807b2ac..ddd622d31c 100644--- a/trino-connector/src/common/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorMetadataErrors.java+++ b/trino-connector/src/common/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorMetadataErrors.java@@ -19,13 +19,16 @@package org.apache.gravitino.trino.connector.catalog;import static io.trino.spi.StandardErrorCode.CATALOG_UNAVAILABLE;+import static io.trino.spi.StandardErrorCode.NOT_SUPPORTED;import static io.trino.spi.StandardErrorCode.PERMISSION_DENIED;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.anyBoolean;import static org.mockito.ArgumentMatchers.anyString;import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.verifyNoInteractions;import static org.mockito.Mockito.when;import io.trino.spi.TrinoException;@@ -53,6 +56,18 @@ public class TestCatalogConnectorMetadataErrors {private static final String DENIED_MESSAGE ="User joel is not authorized to perform operation loadTable on metadata m.c.s.t";+ /** Checks schema rename reports an unsupported operation without source mutation. */+ @Test+ public void testSchemaRenameIsExplicitlyUnsupported() {+ TableCatalog catalog = mock(TableCatalog.class);+ CatalogConnectorMetadata metadata = createMetadata(catalog);+ TrinoException error =+ assertThrows(TrinoException.class, () -> metadata.renameSchema("before", "after"));+ assertEquals(NOT_SUPPORTED.toErrorCode(), error.getErrorCode());+ assertTrue(error.getMessage().contains("renaming schemas"));+ verifyNoInteractions(catalog);+ }+@Testpublic void testLoadCatalogDeniedIsPermissionDenied() {GravitinoMetalake metalake = mock(GravitinoMetalake.class);diff --git a/trino-connector/src/common/test/java/org/apache/gravitino/trino/connector/metadata/TestGravitinoTable.java b/trino-connector/src/common/test/java/org/apache/gravitino/trino/connector/metadata/TestGravitinoTable.javaindex f1171ac806..e6006f7554 100644--- a/trino-connector/src/common/test/java/org/apache/gravitino/trino/connector/metadata/TestGravitinoTable.java+++ b/trino-connector/src/common/test/java/org/apache/gravitino/trino/connector/metadata/TestGravitinoTable.java@@ -21,6 +21,8 @@ package org.apache.gravitino.trino.connector.metadata;import static org.apache.gravitino.trino.connector.catalog.jdbc.mysql.MySQLPropertyMeta.TABLE_PRIMARY_KEY;import static org.apache.gravitino.trino.connector.catalog.jdbc.mysql.MySQLPropertyMeta.TABLE_UNIQUE_KEY;import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.times;+import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;import com.google.common.collect.ImmutableList;@@ -48,6 +50,24 @@ import org.junit.jupiter.api.Test;public class TestGravitinoTable {+ /** Checks wide-table construction materializes the source columns once. */+ @Test+ public void testWideTableColumnsAreMaterializedOnce() {+ Column[] columns = new Column[1000];+ for (int i = 0; i < columns.length; i++) {+ columns[i] = Column.of("c" + i, Types.IntegerType.get());+ }+ Table source = mockTable("wide", columns, "comment", Map.of("k", "v"));+ GravitinoTable table = new GravitinoTable("s", "wide", source);+ verify(source, times(1)).columns();+ Assertions.assertEquals(1000, table.getColumns().size());+ for (int i = 0; i < columns.length; i++) {+ Assertions.assertEquals("c" + i, table.getColumns().get(i).getName());+ }+ Assertions.assertEquals("comment", table.getComment());+ Assertions.assertEquals(Map.of("k", "v"), table.getProperties());+ }+@Testpublic void testGravitinoTable() {Column[] columns = {