Skip to content

Commit

Permalink
Add unix_seconds
Browse files Browse the repository at this point in the history
  • Loading branch information
acvictor committed Apr 15, 2024
1 parent d796cfc commit a78e19f
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 0 deletions.
5 changes: 5 additions & 0 deletions velox/docs/functions/spark/datetime.rst
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,11 @@ These functions support TIMESTAMP and DATE input types.
SELECT unix_date('1970-01-02'); -- '1'
SELECT unix_date('1969-12-31'); -- '-1'

.. spark:function:: unix_seconds(timestamp) -> bigint
Returns the number of seconds since 1970-01-01 00:00:00 UTC.::

SELECT unix_micros('1970-01-01 00:00:01'); -- 1

.. spark:function:: unix_timestamp() -> integer
Returns the current UNIX timestamp in seconds.
Expand Down
11 changes: 11 additions & 0 deletions velox/functions/sparksql/DateTimeFunctions.h
Original file line number Diff line number Diff line change
Expand Up @@ -731,4 +731,15 @@ struct MakeYMIntervalFunction {
result = totalMonths;
}
};

template <typename T>
struct UnixSecondsFunction {
VELOX_DEFINE_FUNCTION_TYPES(T);

FOLLY_ALWAYS_INLINE void call(
int64_t& result,
const arg_type<Timestamp>& timestamp) {
result = timestamp.getSeconds();
}
};
} // namespace facebook::velox::functions::sparksql
3 changes: 3 additions & 0 deletions velox/functions/sparksql/Register.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,9 @@ void registerFunctions(const std::string& prefix) {

registerFunction<UnixDateFunction, int32_t, Date>({prefix + "unix_date"});

registerFunction<UnixSecondsFunction, int64_t, Timestamp>(
{prefix + "unix_seconds"});

registerFunction<UnixTimestampFunction, int64_t>({prefix + "unix_timestamp"});

registerFunction<UnixTimestampParseFunction, int64_t, Varchar>(
Expand Down
12 changes: 12 additions & 0 deletions velox/functions/sparksql/tests/DateTimeFunctionsTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -968,5 +968,17 @@ TEST_F(DateTimeFunctionsTest, makeYMInterval) {
fromYear(-178956971), "Integer overflow in make_ym_interval(-178956971)");
}

TEST_F(DateTimeFunctionsTest, unixSeconds) {
const auto unixSeconds = [&](const StringView time) {
return evaluateOnce<int64_t, Timestamp>(
"unix_seconds(c0)", util::fromTimestampString(time));
};
EXPECT_EQ(unixSeconds("1970-01-01 00:00:01"), 1);
EXPECT_EQ(unixSeconds("1970-01-01 00:00:00.000127"), 0);
EXPECT_EQ(unixSeconds("1969-12-31 23:59:59.999872"), -1);
EXPECT_EQ(unixSeconds("1970-01-01 00:35:47.483647"), 2147);
EXPECT_EQ(unixSeconds("1971-01-01 00:00:01.483647"), 31536001);
}

} // namespace
} // namespace facebook::velox::functions::sparksql::test

0 comments on commit a78e19f

Please sign in to comment.