Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce simple date time formatter #10966

Closed
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions velox/core/QueryConfig.h
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,11 @@ class QueryConfig {
/// The current spark partition id.
static constexpr const char* kSparkPartitionId = "spark.partition_id";

/// If true, simple date formatter is used for time formatting and parsing.
rui-mo marked this conversation as resolved.
Show resolved Hide resolved
/// False by default.
rui-mo marked this conversation as resolved.
Show resolved Hide resolved
static constexpr const char* kSparkLegacyTimeParser =
"spark.legacy_time_parser_policy";

/// The number of local parallel table writer operators per task.
static constexpr const char* kTaskWriterCount = "task_writer_count";

Expand Down Expand Up @@ -677,6 +682,10 @@ class QueryConfig {
return value;
}

bool sparkLegacyTimeParser() const {
return get<bool>(kSparkLegacyTimeParser, false);
}

bool exprTrackCpuUsage() const {
return get<bool>(kExprTrackCpuUsage, false);
}
Expand Down
4 changes: 4 additions & 0 deletions velox/docs/configs.rst
Original file line number Diff line number Diff line change
Expand Up @@ -697,6 +697,10 @@ Spark-specific Configuration
- integer
-
- The current task's Spark partition ID. It's set by the query engine (Spark) prior to task execution.
* - spark.legacy_time_parser_policy
NEUpanning marked this conversation as resolved.
Show resolved Hide resolved
- bool
- false
- If true, simple date formatter is used for time formatting and parsing. False by default.
rui-mo marked this conversation as resolved.
Show resolved Hide resolved

Tracing
--------
Expand Down
125 changes: 125 additions & 0 deletions velox/functions/lib/DateTimeFormatter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1697,4 +1697,129 @@ std::shared_ptr<DateTimeFormatter> buildJodaDateTimeFormatter(
return builder.setType(DateTimeFormatterType::JODA).build();
}

std::shared_ptr<DateTimeFormatter> buildSimpleDateTimeFormatter(
const std::string_view& format,
bool lenient) {
VELOX_USER_CHECK(!format.empty(), "Format pattern should not be empty.");

DateTimeFormatterBuilder builder(format.size());
const char* cur = format.data();
const char* end = cur + format.size();

while (cur < end) {
const char* startTokenPtr = cur;

// For literal case, literal should be quoted using single quotes ('). If
// there is no quotes, it is interpreted as pattern letters. If there is
// only single quote, a user error will be thrown.
if (*startTokenPtr == '\'') {
// Append single literal quote for 2 consecutive single quote.
if (cur + 1 < end && *(cur + 1) == '\'') {
builder.appendLiteral("'");
cur += 2;
} else {
// Append literal characters from the start until the next closing
// literal sequence single quote.
int64_t count = numLiteralChars(startTokenPtr + 1, end);
VELOX_USER_CHECK_NE(count, -1, "No closing single quote for literal");
for (int64_t i = 1; i <= count; i++) {
builder.appendLiteral(startTokenPtr + i, 1);
if (*(startTokenPtr + i) == '\'') {
i += 1;
}
}
cur += count + 2;
}
} else {
// Append format specifier according to pattern letters. If pattern letter
// is not supported, a user error will be thrown.
int count = 1;
rui-mo marked this conversation as resolved.
Show resolved Hide resolved
++cur;
while (cur < end && *startTokenPtr == *cur) {
++count;
++cur;
}
switch (*startTokenPtr) {
case 'a':
builder.appendHalfDayOfDay();
break;
case 'C':
builder.appendCenturyOfEra(count);
break;
case 'd':
builder.appendDayOfMonth(count);
break;
case 'D':
builder.appendDayOfYear(count);
break;
case 'e':
builder.appendDayOfWeek1Based(count);
break;
case 'E':
builder.appendDayOfWeekText(count);
break;
case 'G':
builder.appendEra();
break;
case 'h':
builder.appendClockHourOfHalfDay(count);
break;
case 'H':
builder.appendHourOfDay(count);
break;
case 'K':
builder.appendHourOfHalfDay(count);
break;
case 'k':
builder.appendClockHourOfDay(count);
break;
case 'm':
builder.appendMinuteOfHour(count);
break;
case 'M':
if (count <= 2) {
builder.appendMonthOfYear(count);
} else {
builder.appendMonthOfYearText(count);
}
break;
case 's':
builder.appendSecondOfMinute(count);
break;
case 'S':
builder.appendFractionOfSecond(count);
break;
case 'w':
builder.appendWeekOfWeekYear(count);
break;
case 'x':
builder.appendWeekYear(count);
break;
case 'y':
builder.appendYear(count);
break;
case 'Y':
builder.appendYearOfEra(count);
break;
case 'z':
builder.appendTimeZone(count);
break;
case 'Z':
builder.appendTimeZoneOffsetId(count);
break;
default:
if (isalpha(*startTokenPtr)) {
VELOX_UNSUPPORTED("Specifier {} is not supported.", *startTokenPtr);
} else {
builder.appendLiteral(startTokenPtr, cur - startTokenPtr);
}
break;
}
}
}
DateTimeFormatterType type = lenient ? DateTimeFormatterType::LENIENT_SIMPLE
: DateTimeFormatterType::STRICT_SIMPLE;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wondering where the LENIENT_SIMPLE and STRICT_SIMPLE will be used. I only find their definitions in this PR but no usage.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It will be used when lenient and non-lenient modes have different code branches. For example, if DateTimeFormatterType is LENIENT_SIMPLE, the helper function "daysSinceEpochFromWeekOfMonthDate" will be called with "lenient=true" otherwise with "lenient=false"

return builder.setType(type).build();
}

} // namespace facebook::velox::functions
14 changes: 13 additions & 1 deletion velox/functions/lib/DateTimeFormatter.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,15 @@

namespace facebook::velox::functions {

enum class DateTimeFormatterType { JODA, MYSQL, UNKNOWN };
enum class DateTimeFormatterType {
JODA,
MYSQL,
// Corresponding to java.text.SimpleDateFormat in lenient mode.
LENIENT_SIMPLE,
rui-mo marked this conversation as resolved.
Show resolved Hide resolved
NEUpanning marked this conversation as resolved.
Show resolved Hide resolved
// Corresponding to java.text.SimpleDateFormat in strict(lenient=false) mode
rui-mo marked this conversation as resolved.
Show resolved Hide resolved
STRICT_SIMPLE,
rui-mo marked this conversation as resolved.
Show resolved Hide resolved
UNKNOWN
};

enum class DateTimeFormatSpecifier : uint8_t {
// Era, e.g: "AD"
Expand Down Expand Up @@ -209,6 +217,10 @@ std::shared_ptr<DateTimeFormatter> buildMysqlDateTimeFormatter(
std::shared_ptr<DateTimeFormatter> buildJodaDateTimeFormatter(
const std::string_view& format);

std::shared_ptr<DateTimeFormatter> buildSimpleDateTimeFormatter(
const std::string_view& format,
bool lenient);

} // namespace facebook::velox::functions

template <>
Expand Down
53 changes: 41 additions & 12 deletions velox/functions/sparksql/DateTimeFunctions.h
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,18 @@

namespace facebook::velox::functions::sparksql {

std::shared_ptr<DateTimeFormatter> getDateTimeFormatter(
NEUpanning marked this conversation as resolved.
Show resolved Hide resolved
const bool legacyTimeParser,
rui-mo marked this conversation as resolved.
Show resolved Hide resolved
const std::string_view& format,
bool lenient) {
if (legacyTimeParser) {
return buildSimpleDateTimeFormatter(format, lenient);
} else {
rui-mo marked this conversation as resolved.
Show resolved Hide resolved
return buildJodaDateTimeFormatter(
std::string_view(format.data(), format.size()));
}
}

template <typename T>
struct YearFunction : public InitSessionTimezone<T> {
VELOX_DEFINE_FUNCTION_TYPES(T);
Expand Down Expand Up @@ -156,7 +168,8 @@ struct UnixTimestampParseFunction {
const std::vector<TypePtr>& /*inputTypes*/,
const core::QueryConfig& config,
const arg_type<Varchar>* /*input*/) {
format_ = buildJodaDateTimeFormatter(kDefaultFormat_);
format_ = getDateTimeFormatter(
config.sparkLegacyTimeParser(), kDefaultFormat_, false);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How does Spark decide lenient or not? Is it through another configuration?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is no configuration to decide lenient or not. It's just uses lenient mode or strict mode . See this Spark issue

SimpleDateFormat - is used in JDBC datasource, in partitions parsing.
SimpleDateFormat in strong mode (lenient = false). It is used by the date_format, from_unixtime, unix_timestamp and to_unix_timestamp functions.

Copy link
Contributor Author

@NEUpanning NEUpanning Sep 13, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI:
Functions using strict mode(lenient=false):
'from_unixtime', 'unix_timestamp', 'make_date', 'to_unix_timestamp', 'date_format'

Functions using lenient mode:
cast date to string

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI: Functions using strict mode(lenient=false): 'from_unixtime', 'unix_timestamp', 'make_date', 'to_unix_timestamp', 'date_format'

Functions using lenient mode: cast date to string

Thanks for the clarify. This is much clearer to me. Would you add this comment to the PR description?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure. Updated.

setTimezone(config);
}

Expand Down Expand Up @@ -205,10 +218,13 @@ struct UnixTimestampParseWithFormatFunction
const core::QueryConfig& config,
const arg_type<Varchar>* /*input*/,
const arg_type<Varchar>* format) {
legacyTimeParser_ = config.sparkLegacyTimeParser();
if (format != nullptr) {
try {
this->format_ = buildJodaDateTimeFormatter(
std::string_view(format->data(), format->size()));
this->format_ = getDateTimeFormatter(
legacyTimeParser_,
std::string_view(format->data(), format->size()),
false);
} catch (const VeloxUserError&) {
invalidFormat_ = true;
}
Expand All @@ -228,8 +244,10 @@ struct UnixTimestampParseWithFormatFunction
// Format error returns null.
try {
if (!isConstFormat_) {
this->format_ = buildJodaDateTimeFormatter(
std::string_view(format.data(), format.size()));
this->format_ = getDateTimeFormatter(
legacyTimeParser_,
std::string_view(format.data(), format.size()),
false);
}
} catch (const VeloxUserError&) {
return false;
Expand All @@ -248,6 +266,7 @@ struct UnixTimestampParseWithFormatFunction
private:
bool isConstFormat_{false};
bool invalidFormat_{false};
bool legacyTimeParser_{false};
NEUpanning marked this conversation as resolved.
Show resolved Hide resolved
};

// Parses unix time in seconds to a formatted string.
Expand All @@ -260,9 +279,10 @@ struct FromUnixtimeFunction {
const core::QueryConfig& config,
const arg_type<int64_t>* /*unixtime*/,
const arg_type<Varchar>* format) {
legacyTimeParser_ = config.sparkLegacyTimeParser();
sessionTimeZone_ = getTimeZoneFromConfig(config);
if (format != nullptr) {
setFormatter(*format);
setFormatter(*format, legacyTimeParser_);
NEUpanning marked this conversation as resolved.
Show resolved Hide resolved
isConstantTimeFormat_ = true;
}
}
Expand All @@ -272,7 +292,7 @@ struct FromUnixtimeFunction {
const arg_type<int64_t>& second,
const arg_type<Varchar>& format) {
if (!isConstantTimeFormat_) {
setFormatter(format);
setFormatter(format, legacyTimeParser_);
}
const Timestamp timestamp{second, 0};
result.reserve(maxResultSize_);
Expand All @@ -283,16 +303,21 @@ struct FromUnixtimeFunction {
}

private:
FOLLY_ALWAYS_INLINE void setFormatter(const arg_type<Varchar>& format) {
formatter_ = buildJodaDateTimeFormatter(
std::string_view(format.data(), format.size()));
FOLLY_ALWAYS_INLINE void setFormatter(
const arg_type<Varchar>& format,
bool legacyTimeParser) {
formatter_ = getDateTimeFormatter(
legacyTimeParser,
std::string_view(format.data(), format.size()),
false);
maxResultSize_ = formatter_->maxResultSize(sessionTimeZone_);
}

const tz::TimeZone* sessionTimeZone_{nullptr};
std::shared_ptr<DateTimeFormatter> formatter_;
uint32_t maxResultSize_;
bool isConstantTimeFormat_{false};
bool legacyTimeParser_{false};
};

template <typename T>
Expand Down Expand Up @@ -366,12 +391,14 @@ struct GetTimestampFunction {
const core::QueryConfig& config,
const arg_type<Varchar>* /*input*/,
const arg_type<Varchar>* format) {
legacyTimeParser_ = config.sparkLegacyTimeParser();
auto sessionTimezoneName = config.sessionTimezone();
if (!sessionTimezoneName.empty()) {
sessionTimeZone_ = tz::locateZone(sessionTimezoneName);
}
if (format != nullptr) {
formatter_ = buildJodaDateTimeFormatter(std::string_view(*format));
formatter_ = getDateTimeFormatter(
legacyTimeParser_, std::string_view(*format), false);
isConstantTimeFormat_ = true;
}
}
Expand All @@ -381,7 +408,8 @@ struct GetTimestampFunction {
const arg_type<Varchar>& input,
const arg_type<Varchar>& format) {
if (!isConstantTimeFormat_) {
formatter_ = buildJodaDateTimeFormatter(std::string_view(format));
formatter_ = getDateTimeFormatter(
legacyTimeParser_, std::string_view(format), false);
}
auto dateTimeResult = formatter_->parse(std::string_view(input));
// Null as result for parsing error.
Expand All @@ -404,6 +432,7 @@ struct GetTimestampFunction {
std::shared_ptr<DateTimeFormatter> formatter_{nullptr};
bool isConstantTimeFormat_{false};
const tz::TimeZone* sessionTimeZone_{tz::locateZone(0)}; // default to GMT.
bool legacyTimeParser_{false};
};

template <typename T>
Expand Down
Loading