spark-test commented on code in PR #59975:
URL: https://github.com/apache/spark/pull/59975#discussion_r4466697284
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/json/JsonInferSchema.scala:
##########
@@ -180,7 +180,7 @@ class JsonInferSchema(private val options: JSONOptions)
extends Serializable wit
decimalTry.get
} else if (options.inferTimestamp) {
if (isTimeTypeEnabled &&
- (allCatch opt timeFormatter.parse(field)).isDefined) {
+ timeFormatter.parseOptional(field).isDefined) {
Review Comment:
**Non-blocking (P2):** `timeFormatter` is a lazy val, and building it with
`TimeFormatter(options.timeFormatInRead, isParsing = true)` validates the
pattern: a timeFormat it cannot parse with, such as 'EEE HH:mm', throws
INVALID_DATETIME_PATTERN. Before this change the first access happened inside
`allCatch opt timeFormatter.parse(field)`, so such a pattern only meant "not
TIME". Here the access is the receiver of `parseOptional`, outside any catch,
so the error escapes into the per-record handling of inference. The same
applies to `CSVInferSchema` (line 211) and `XmlInferSchema` (line 785).
With `spark.sql.timeType.enabled=true` and `inferTimestamp=true`,
line-delimited JSON in PERMISSIVE mode turns every record holding a string
value into a corrupt record, so those string columns silently disappear from
the inferred schema. Single-line XML behaves the same way. CSV, multi-line
JSON, multi-line XML and `schema_of_json` now fail, where the base branch
inferred a schema without TIME and the read succeeded.
Building the formatter once as an `Option` in each inference class (catching
`NonFatal` around construction in the lazy initializer), and probing only when
it exists, keeps the base-branch behavior and pays the construction failure
once instead of once per value.
**Verification:**
- **Regression:** With TIME enabled and a timeFormat that cannot be built
for parsing, such as 'EEE HH:mm', inference over data with string values
completes for CSV, for line-delimited and multi-line JSON with inferTimestamp
enabled, for single-line and multi-line XML, and for schema_of_json with
inferTimestamp enabled. In PERMISSIVE mode the inferred schema keeps the string
columns, has no corrupt-record column, and no INVALID_DATETIME_PATTERN error is
raised.
- **Behavior:** With TIME enabled, inference with no timeFormat and with a
valid custom timeFormat still infers TIME for matching values, and existing
TIME inference results stay the same.
- **Compatibility:** With TIME disabled, inference behaves exactly as on the
base branch, including when an unusable timeFormat is set.
##########
sql/api/src/main/scala/org/apache/spark/sql/catalyst/util/TimeFormatter.scala:
##########
@@ -17,16 +17,29 @@
package org.apache.spark.sql.catalyst.util
+import java.text.ParsePosition
import java.time.LocalTime
import java.time.format.DateTimeFormatter
import java.util.Locale
+import scala.util.control.NonFatal
+
import org.apache.spark.sql.catalyst.util.SparkDateTimeUtils._
import org.apache.spark.unsafe.types.UTF8String
sealed trait TimeFormatter extends Serializable {
def parse(s: String): Long // returns nanoseconds since midnight
+ // A non-throwing variant of `parse`, returning None instead of throwing
when the input cannot be
+ // parsed. Used by schema inference to probe the time type without paying an
exception per
+ // non-time value; subclasses override it with a more efficient,
exception-free implementation.
Review Comment:
**Nit (P3):** Both overrides still rely on a caught exception for
time-shaped input with out-of-range fields.
`Iso8601TimeFormatter.parseOptional` wraps the conversion in `catch { case
NonFatal(_) => None }`, which is what turns '25:00:00' under 'HH:mm:ss' into
`None`. `DefaultTimeFormatter.parseOptional` calls `stringToTime`, which leaves
out-of-range minutes or seconds such as '10:75:00' to `LocalTime.of` inside its
own `NonFatal` catch. What the overrides avoid is the exception for input that
does not match the time format, so calling them exception-free invites someone
to drop those catches. Suggested wording:
```suggestion
// non-time value. Subclasses override it to return None without throwing
for input that does
// not match the time format; out-of-range fields may still raise an
exception caught internally.
```
**Verification:**
- **Inspection:** The parseOptional comment says the overrides avoid
exceptions for input that does not match the time format, does not call them
exception-free, and is consistent with the internal catch in both overrides.
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/util/TimeFormatterSuite.scala:
##########
@@ -207,4 +207,21 @@ class TimeFormatterSuite extends SparkFunSuite with
SQLHelper {
"targetType" -> "\"TIME(6)\"",
"ansiConfig" -> "\"spark.sql.ansi.enabled\""))
}
+
+ test("parseOptional returns None instead of throwing on unparseable times") {
+ // The default (pattern-less) formatter delegates to stringToTime.
+ val defaultFormatter = new DefaultTimeFormatter(
+ locale = DateFormatter.defaultLocale,
+ isParsing = true)
+
assert(defaultFormatter.parseOptional("01:02:03").contains(defaultFormatter.parse("01:02:03")))
+ assert(defaultFormatter.parseOptional("x123").isEmpty)
+
+ // The Iso8601 formatter uses parseUnresolved and must consume the whole
input.
+ val isoFormatter = new Iso8601TimeFormatter("HH:mm:ss",
DateFormatter.defaultLocale,
Review Comment:
**Nit (P3):** For 'HH:mm:ss', `toLocalTime` reads the hour from
`HOUR_OF_DAY`, where the fields `parseUnresolved` returns and the fields
`parse` resolves are the same. These assertions therefore pass whether or not
`parseOptional` agrees with `parse` on patterns where resolution matters. The
'missing am/pm field' test above already loops over HH, hh, KK and kk;
comparing `parseOptional` with `Try(parse(_)).toOption` over those patterns and
an AM/PM pattern such as 'hh:mm:ss a' would check the exact parity the PR
description promises. The CSV, JSON and XML inference suites also have no case
with a custom clock-hour timeFormat or with a timeFormat that cannot be built,
so the formatter-construction problem in the inference probes passes every
existing test as well.
**Verification:**
- **Regression:** The parity checks fail if parseOptional accepts a value
that parse rejects, rejects a value that parse accepts, or returns a different
time for any covered pattern. The covered inputs include clock hours of 0 and
13 under 'hh' and an out-of-range hour under 'HH'.
- **Behavior:** The custom-pattern inference cases infer TIME only for
columns whose values parse accepts. The unusable-timeFormat cases complete
inference without inferring TIME and without corrupt records.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]