This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/dev/pr-12703-a0023f3a2f49ec734f79cbc22ad59bd217c11e41 in repository https://gitbox.apache.org/repos/asf/seatunnel.git
commit 7ce26cca72689b33e3a189ac79004dfc35be9ff8 Author: chovygo <[email protected]> AuthorDate: Sat Nov 7 06:42:38 2026 +0000 [Feature] [Transform-V2] Add UNIX_TIMESTAMP SQL function (#12703) Co-authored-by: zhaowei <[email protected]> --- .../introduction/concepts/incompatible-changes.md | 24 ++ docs/en/transforms/sql-functions.md | 25 ++ .../introduction/concepts/incompatible-changes.md | 16 + docs/zh/transforms/sql-functions.md | 26 ++ .../apache/seatunnel/e2e/transform/TestSQLIT.java | 3 + .../sql_transform/func_unix_timestamp.conf | 101 ++++++ .../transform/sql/zeta/ZetaSQLFunction.java | 3 + .../seatunnel/transform/sql/zeta/ZetaSQLType.java | 1 + .../sql/zeta/functions/DateTimeFunction.java | 131 ++++++- .../transform/sql/SQLDateTimeFunctionsTest.java | 388 +++++++++++++++++++++ 10 files changed, 717 insertions(+), 1 deletion(-) diff --git a/docs/en/introduction/concepts/incompatible-changes.md b/docs/en/introduction/concepts/incompatible-changes.md index afadaa2dc02..61d47aa3e66 100644 --- a/docs/en/introduction/concepts/incompatible-changes.md +++ b/docs/en/introduction/concepts/incompatible-changes.md @@ -415,6 +415,30 @@ The Zeta SQL ARRAY function now declares TINYINT elements as `ARRAY<TINYINT>`, m prefix (a bare key is derived as a passphrase via SHA-256 and is **not** interchangeable with `FieldEncrypt`). See [SQL Functions](../../transforms/sql-functions.md) for the full contract. +### Zeta SQL Transform: built-in UNIX_TIMESTAMP + +- **Behavior change: UNIX_TIMESTAMP is now a built-in function** + - **Affected component**: `seatunnel-transforms-v2` (Zeta SQL transform). + - **Description**: `UNIX_TIMESTAMP()` / `UNIX_TIMESTAMP(string[, pattern])` / + `UNIX_TIMESTAMP(dateTime)` is now a built-in Zeta SQL function, dispatched before + user-registered `ZetaUDF`s, and its output type is resolved as `BIGINT` + (`BasicType.LONG_TYPE`). + - **Impact**: A job that registered a custom `ZetaUDF` named `UNIX_TIMESTAMP` (the + previous workaround for the missing built-in) will, after upgrading, silently start + using this built-in implementation instead of the UDF. The declared output type is + now forced to `BIGINT` regardless of what the UDF's `resultType` returned, which may + break the downstream sink schema if the UDF returned a different type. + - **Migration Guide**: Rename the existing UDF, or switch to the built-in function. + See [SQL Functions](../../transforms/sql-functions.md) for the full contract. + +### Zeta SQL Transform: FROM_UNIXTIME and UNIX_TIMESTAMP text patterns use English locale + +- **Behavior change: text pattern letters are now interpreted in English regardless of the worker JVM locale** + - **Affected component**: `seatunnel-transforms-v2` (Zeta SQL transform). + - **Description**: `getFormatter`, the shared `DateTimeFormatter` factory used by `FROM_UNIXTIME` (format path) and `UNIX_TIMESTAMP` (parse path), now passes `Locale.ENGLISH` to `DateTimeFormatter.ofPattern`. Previously the JVM default FORMAT locale was captured, so text pattern letters such as `MMM` (month name), `EEE` (weekday), or `a` (AM/PM) rendered or parsed in the worker's language. + - **Impact**: On a non-English worker (for example `de-DE`), `FROM_UNIXTIME(epoch, 'dd MMM yyyy')` previously produced `23 Okt 2026` and now produces `23 Oct 2026`; `UNIX_TIMESTAMP('23 Oct 2026', 'dd MMM yyyy')` previously returned `NULL` (parse failure) and now returns the correct epoch. English-locale workers are unaffected. This is consistent with `DAYNAME` and `MONTHNAME`, which already pin English via `DateFormatSymbols.getInstance(Locale.ENGLISH)`. + - **Migration Guide**: No action is needed for correctness — English was always the intended locale for text patterns. If a downstream consumer relied on localized month or weekday names in `FROM_UNIXTIME` output, update it to expect English names. See [SQL Functions](../../transforms/sql-functions.md) for the full pattern reference. + ### RabbitMQ Connector - **Breaking Change: `amqps://` connections now verify broker certificates** diff --git a/docs/en/transforms/sql-functions.md b/docs/en/transforms/sql-functions.md index 0a3d10d52c7..662b8eb5c2d 100644 --- a/docs/en/transforms/sql-functions.md +++ b/docs/en/transforms/sql-functions.md @@ -1112,6 +1112,8 @@ Convert the number of seconds from the UNIX epoch (1970-01-01 00:00:00 UTC) to a The most important format characters are: y year, M month, d day, H hour, m minute, s second. For details of the format, see `java.time.format.DateTimeFormatter`. +Text pattern letters (such as `MMM`, `EEE`) are interpreted in English, independent of the worker JVM locale. + `timeZone` is optional, default value is system's time zone. `timezone` value can be a `UTC+ timezone offset`, for example, `UTC+8` represents the Asia/Shanghai time zone, see https://en.wikipedia.org/wiki/List_of_tz_database_time_zones . @@ -1127,6 +1129,29 @@ or CALL FROM_UNIXTIME(1672502400, 'yyyy-MM-dd HH:mm:ss','UTC+6') +### UNIX_TIMESTAMP + +```UNIX_TIMESTAMP() | UNIX_TIMESTAMP(string[, pattern]) | UNIX_TIMESTAMP(dateTime) -> BIGINT``` + +Convert a datetime to the number of seconds since the UNIX epoch (1970-01-01 00:00:00 UTC). The inverse of `FROM_UNIXTIME`. + +- No argument: current epoch seconds. +- String argument: parsed with the given `pattern` (default `yyyy-MM-dd HH:mm:ss`). For pattern characters see `java.time.format.DateTimeFormatter`. +- `dateTime` argument: a TIMESTAMP / TIMESTAMP WITH TIME ZONE / DATE column. + +`dateTime` and string inputs are resolved against the system's time zone; a TIMESTAMP WITH TIME ZONE value uses its own offset. A string whose pattern carries a zone offset (for example `yyyy-MM-dd HH:mm:ssXXX`) uses that offset rather than the system time zone. Unparseable string input returns NULL rather than raising an error. An explicit NULL pattern or an invalid pattern string returns NULL for all input types. The `pattern` argument is only consulted for string input; it is ignored [...] + +Example: + +select UNIX_TIMESTAMP('2023-01-01 00:00:00') as ts + +select UNIX_TIMESTAMP('2023/01/01 00:00:00', 'yyyy/MM/dd HH:mm:ss') as ts + +select UNIX_TIMESTAMP(dt) as ts + +-- convert a TIMESTAMP in a non-default time zone +select UNIX_TIMESTAMP(dt AT TIME ZONE 'UTC+8') as ts + ### AT TIME ZONE ```dateAndTime AT TIME ZONE 'timeZone' -> TIMESTAMP_TZ``` diff --git a/docs/zh/introduction/concepts/incompatible-changes.md b/docs/zh/introduction/concepts/incompatible-changes.md index 26aadd2b650..a1fd24b43ee 100644 --- a/docs/zh/introduction/concepts/incompatible-changes.md +++ b/docs/zh/introduction/concepts/incompatible-changes.md @@ -352,6 +352,22 @@ Zeta SQL ARRAY 函数现在将 TINYINT 元素声明为 `ARRAY<TINYINT>`,与实 - **影响**:若作业此前注册了名为 `AES_ENCRYPT` 或 `AES_DECRYPT` 的自定义 `ZetaUDF`(此前缺少内置函数时的变通做法),升级后将静默改用此内置实现而非 UDF。若该 UDF 使用了不同的密钥派生、IV 处理或输出编码,则已由 UDF 写入的密文可能无法解密(或在 CBC 填充校验以约 1/256 概率碰巧通过时解出垃圾)。 - **迁移指南**:重命名已有 UDF,或迁移到内置函数。如需与 `FieldEncrypt` 的 `AesCbcEncryptor` 保持线兼容,请使用带 `base64:` 前缀的密钥(裸密钥会按口令经 SHA-256 派生,**不**与 `FieldEncrypt` 互通)。完整契约见 [SQL 函数](../../transforms/sql-functions.md)。 +### Zeta SQL Transform:内置 UNIX_TIMESTAMP + +- **行为变更:UNIX_TIMESTAMP 现为内置函数** + - **影响范围**:`seatunnel-transforms-v2`(Zeta SQL transform)。 + - **变更说明**:`UNIX_TIMESTAMP()` / `UNIX_TIMESTAMP(string[, pattern])` / `UNIX_TIMESTAMP(dateTime)` 现为内置 Zeta SQL 函数,分发顺序在用户注册的 `ZetaUDF` 之前,输出类型解析为 `BIGINT`(`BasicType.LONG_TYPE`)。 + - **影响**:若作业此前注册了名为 `UNIX_TIMESTAMP` 的自定义 `ZetaUDF`(此前缺少内置函数时的变通做法),升级后将静默改用此内置实现而非 UDF。声明的输出类型现在被强制为 `BIGINT`,无视该 UDF 的 `resultType` 返回值,若 UDF 返回不同类型,可能破坏下游 sink 的 schema。 + - **迁移指南**:重命名已有 UDF,或迁移到内置函数。完整契约见 [SQL 函数](../../transforms/sql-functions.md)。 + +### Zeta SQL Transform:FROM_UNIXTIME 与 UNIX_TIMESTAMP 文本 pattern 使用英语 locale + +- **行为变更:文本 pattern 字母现在按英语解释,不受 worker JVM locale 影响** + - **影响范围**:`seatunnel-transforms-v2`(Zeta SQL transform)。 + - **变更说明**:`getFormatter` 是 `FROM_UNIXTIME`(格式化路径)和 `UNIX_TIMESTAMP`(解析路径)共用的 `DateTimeFormatter` 工厂,现在向 `DateTimeFormatter.ofPattern` 传入 `Locale.ENGLISH`。此前捕获的是 JVM 默认 FORMAT locale,导致文本 pattern 字母(如 `MMM` 月份名、`EEE` 星期、`a` 上下午)按 worker 语言渲染或解析。 + - **影响**:在非英语 worker 上(如 `de-DE`),`FROM_UNIXTIME(epoch, 'dd MMM yyyy')` 此前输出 `23 Okt 2026`,现在输出 `23 Oct 2026`;`UNIX_TIMESTAMP('23 Oct 2026', 'dd MMM yyyy')` 此前返回 `NULL`(解析失败),现在返回正确的 epoch 值。英语 locale 的 worker 不受影响。此变更与 `DAYNAME` 和 `MONTHNAME` 一致,后者已通过 `DateFormatSymbols.getInstance(Locale.ENGLISH)` 固定英语。 + - **迁移指南**:无需操作即可保证正确性——文本 pattern 按英语解释始终是预期行为。若下游消费方依赖 `FROM_UNIXTIME` 输出中的本地化月份或星期名称,需更新为预期英语名称。完整 pattern 参考见 [SQL 函数](../../transforms/sql-functions.md)。 + ### RabbitMQ Connector - **破坏性变更:`amqps://` 连接现在会校验 Broker 证书** diff --git a/docs/zh/transforms/sql-functions.md b/docs/zh/transforms/sql-functions.md index c21c958995f..d1f8b85d6d0 100644 --- a/docs/zh/transforms/sql-functions.md +++ b/docs/zh/transforms/sql-functions.md @@ -1111,6 +1111,8 @@ YEAR(CREATED) 最重要的格式字符包括:y(年)、M(月)、d(日)、H(时)、m(分)、s(秒)。有关格式的详细信息,请参阅 `java.time.format.DateTimeFormatter`。 +文本 pattern 字母(如 `MMM`、`EEE`)按英语解释,不受 worker JVM locale 影响。 + `timeZone` 是可选的,默认值为系统的时区。`timezone` 的值可以是一个 `UTC+ 时区偏移`,例如,`UTC+8` 表示亚洲/上海时区,请参阅 https://en.wikipedia.org/wiki/List_of_tz_database_time_zones 。 示例: @@ -1126,6 +1128,30 @@ or CALL FROM_UNIXTIME(1672502400, 'yyyy-MM-dd HH:mm:ss','UTC+6') +### UNIX_TIMESTAMP + +```UNIX_TIMESTAMP() | UNIX_TIMESTAMP(string[, pattern]) | UNIX_TIMESTAMP(dateTime) -> BIGINT``` + +将日期时间转换为自 UNIX 纪元(1970-01-01 00:00:00 UTC)起的秒数。是 `FROM_UNIXTIME` 的逆运算。 + +- 无参数:当前 epoch 秒数。 +- 字符串参数:按给定 `pattern`(默认 `yyyy-MM-dd HH:mm:ss`)解析。格式字符参见 `java.time.format.DateTimeFormatter`。 +- `dateTime` 参数:TIMESTAMP / TIMESTAMP WITH TIME ZONE / DATE 类型的列。 + +`dateTime` 与字符串输入按系统时区折算;TIMESTAMP WITH TIME ZONE 值使用其自身偏移。若字符串的 pattern 携带时区偏移(例如 `yyyy-MM-dd HH:mm:ssXXX`),则使用该偏移而非系统时区。无法解析的字符串输入返回 NULL,而不会抛出错误。显式传入 NULL pattern 或非法 pattern 字符串时,对所有输入类型均返回 NULL。`pattern` 参数仅对字符串输入生效,对 typed datetime 参数会被忽略。不含完整日期的 pattern(例如 `HH:mm:ss` 或 `yyyy-MM`)会导致每行都返回 NULL,因为解析器至少需要日期分量。不支持数值输入,返回 NULL;其他非时间类型(例如 TIME、BOOLEAN、BYTES)会抛出错误。超出范围的日(例如 `2023-02-30`)会被调整为该月最后一天,与本类其他日期函数一致。与 `FROM_UNIXTIME` 不同,`UNIX_TIMESTAMP` 不接受时区参数。如需按指定时区转换 datetime,请先用 `AT TIME [...] + +示例: + +select UNIX_TIMESTAMP('2023-01-01 00:00:00') as ts + +select UNIX_TIMESTAMP('2023/01/01 00:00:00', 'yyyy/MM/dd HH:mm:ss') as ts + +select UNIX_TIMESTAMP(dt) as ts + +-- 按非默认时区转换 TIMESTAMP +select UNIX_TIMESTAMP(dt AT TIME ZONE 'UTC+8') as ts + + ### AT TIME ZONE ```dateAndTime AT TIME ZONE 'timeZone' -> TIMESTAMP_TZ``` diff --git a/seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-2/src/test/java/org/apache/seatunnel/e2e/transform/TestSQLIT.java b/seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-2/src/test/java/org/apache/seatunnel/e2e/transform/TestSQLIT.java index 45b23b356b5..cec6c66d3b9 100644 --- a/seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-2/src/test/java/org/apache/seatunnel/e2e/transform/TestSQLIT.java +++ b/seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-2/src/test/java/org/apache/seatunnel/e2e/transform/TestSQLIT.java @@ -51,6 +51,9 @@ public class TestSQLIT extends TestSuiteBase { Container.ExecResult sqlFuncFromUnixtime = container.executeJob("/sql_transform/func_from_unixtime.conf"); Assertions.assertEquals(0, sqlFuncFromUnixtime.getExitCode()); + Container.ExecResult sqlFuncUnixTimestamp = + container.executeJob("/sql_transform/func_unix_timestamp.conf"); + Assertions.assertEquals(0, sqlFuncUnixTimestamp.getExitCode()); Container.ExecResult sqlCriteriaFilter = container.executeJob("/sql_transform/criteria_filter.conf"); Assertions.assertEquals(0, sqlCriteriaFilter.getExitCode()); diff --git a/seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-2/src/test/resources/sql_transform/func_unix_timestamp.conf b/seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-2/src/test/resources/sql_transform/func_unix_timestamp.conf new file mode 100644 index 00000000000..9afcca26ebd --- /dev/null +++ b/seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-2/src/test/resources/sql_transform/func_unix_timestamp.conf @@ -0,0 +1,101 @@ +# +# 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. +# +###### +###### This config file is a demonstration of streaming processing in seatunnel config +###### + +env { + parallelism = 1 + job.mode = "BATCH" + checkpoint.interval = 10000 +} + +source { + FakeSource { + plugin_output = "fake" + schema = { + fields { + c1 = "timestamp" + c2 = "string" + c3 = "string" + } + } + rows = [ + {fields = ["2023-01-01T00:00:00", "2023-01-01 00:00:00", "2023/01/01 00:00:00"], kind = INSERT} + ] + } +} + +transform { + Sql { + plugin_input = "fake" + plugin_output = "fake1" + query = "select unix_timestamp(c1) as ts1, unix_timestamp(c2) as ts2, unix_timestamp(c3, 'yyyy/MM/dd HH:mm:ss') as ts3, from_unixtime(unix_timestamp(c2), 'yyyy-MM-dd HH:mm:ss') as rt2, unix_timestamp(c1) - unix_timestamp(c2) as diff1, from_unixtime(unix_timestamp(c3, 'yyyy/MM/dd HH:mm:ss'), 'yyyy-MM-dd HH:mm:ss') as rt3 from dual" + } +} + +sink { + Assert { + plugin_input = "fake1" + rules = { + field_rules = [ + { + field_name = "ts1" + field_type = bigint + field_value = [ + {rule_type = NOT_NULL} + ] + } + { + field_name = "ts2" + field_type = bigint + field_value = [ + {rule_type = NOT_NULL} + ] + }, + { + field_name = "ts3" + field_type = bigint + field_value = [ + {rule_type = NOT_NULL} + ] + }, + { + field_name = "rt2" + field_type = string + field_value = [ + {rule_type = NOT_NULL, equals_to = "2023-01-01 00:00:00"} + ] + }, + { + field_name = "diff1" + field_type = bigint + field_value = [ + {rule_type = NOT_NULL, equals_to = "0"} + ] + }, + { + field_name = "rt3" + field_type = string + field_value = [ + {rule_type = NOT_NULL, equals_to = "2023-01-01 00:00:00"} + ] + } + ] + } + } +} diff --git a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/ZetaSQLFunction.java b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/ZetaSQLFunction.java index 2aa82708212..833d015233d 100644 --- a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/ZetaSQLFunction.java +++ b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/ZetaSQLFunction.java @@ -205,6 +205,7 @@ public class ZetaSQLFunction { public static final String WEEK = "WEEK"; public static final String YEAR = "YEAR"; public static final String FROM_UNIXTIME = "FROM_UNIXTIME"; + public static final String UNIX_TIMESTAMP = "UNIX_TIMESTAMP"; // -------------------------lateralView functions---------------------------- public static final String EXPLODE = "EXPLODE"; @@ -644,6 +645,8 @@ public class ZetaSQLFunction { return DateTimeFunction.dayOfYear(args); case FROM_UNIXTIME: return DateTimeFunction.fromUnixTime(args); + case UNIX_TIMESTAMP: + return DateTimeFunction.unixTimestamp(args); case EXTRACT: return DateTimeFunction.extract(args); case FORMATDATETIME: diff --git a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/ZetaSQLType.java b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/ZetaSQLType.java index 5c6a4a7189f..81c2890fbf3 100644 --- a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/ZetaSQLType.java +++ b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/ZetaSQLType.java @@ -387,6 +387,7 @@ public class ZetaSQLType { case ZetaSQLFunction.OCTET_LENGTH: case ZetaSQLFunction.DATEDIFF: case ZetaSQLFunction.MURMUR64: + case ZetaSQLFunction.UNIX_TIMESTAMP: return BasicType.LONG_TYPE; case ZetaSQLFunction.REGEXP_LIKE: case ZetaSQLFunction.IS_DATE: diff --git a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/DateTimeFunction.java b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/DateTimeFunction.java index 70b96dc5944..4b138b707dd 100644 --- a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/DateTimeFunction.java +++ b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/DateTimeFunction.java @@ -24,6 +24,7 @@ import org.apache.seatunnel.transform.sql.zeta.ZetaDateTimeFormat; import org.apache.seatunnel.transform.sql.zeta.ZetaSQLFunction; import java.text.DateFormatSymbols; +import java.time.DateTimeException; import java.time.Duration; import java.time.Instant; import java.time.LocalDate; @@ -33,6 +34,7 @@ import java.time.OffsetDateTime; import java.time.Period; import java.time.ZoneId; import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.time.temporal.Temporal; @@ -40,11 +42,33 @@ import java.time.temporal.TemporalAccessor; import java.time.temporal.WeekFields; import java.util.List; import java.util.Locale; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; public class DateTimeFunction { /** English names of months and week days. */ private static volatile String[][] MONTHS_AND_WEEKS; + // 1024 is far beyond the number of distinct date patterns in real-world SQL + // (typically low tens). The cap bounds retained memory; no eviction needed + // because the cache never fills in practice. + private static final int FORMATTER_CACHE_MAX_SIZE = 1024; + + private static final Map<String, DateTimeFormatter> FORMATTER_CACHE = + new ConcurrentHashMap<>(FORMATTER_CACHE_MAX_SIZE); + + private static DateTimeFormatter getFormatter(String pattern) { + DateTimeFormatter cached = FORMATTER_CACHE.get(pattern); + if (cached != null) { + return cached; + } + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.ENGLISH); + if (FORMATTER_CACHE.size() < FORMATTER_CACHE_MAX_SIZE) { + FORMATTER_CACHE.putIfAbsent(pattern, formatter); + } + return formatter; + } + public static LocalDate currentDate() { return LocalDate.now(); } @@ -796,11 +820,116 @@ public class DateTimeFunction { String timeZone = (String) args.get(2); zoneId = ZoneId.of(timeZone); } - DateTimeFormatter df = DateTimeFormatter.ofPattern(format); + DateTimeFormatter df = getFormatter(format); LocalDateTime datetime = Instant.ofEpochSecond(unixTime).atZone(zoneId).toLocalDateTime(); return df.format(datetime); } + /** + * Converts a datetime to Unix epoch seconds, the inverse of {@link #fromUnixTime}. + * + * <p>Supported forms: + * + * <ul> + * <li>no argument — current epoch seconds ({@code UNIX_TIMESTAMP()}); + * <li>a typed datetime argument ({@code OffsetDateTime} / {@code LocalDateTime} / {@code + * LocalDate}); + * <li>a string parsed with an optional pattern (default {@code yyyy-MM-dd HH:mm:ss}). + * </ul> + * + * <p>{@code LocalDateTime} / {@code LocalDate} and string inputs without a zone offset are + * resolved against the system default time zone (the inverse of {@link #fromUnixTime}); {@code + * OffsetDateTime} and strings whose pattern carries an offset use that offset. Unparseable + * string input returns {@code null} rather than raising. An explicit {@code null} pattern or an + * invalid pattern string returns {@code null} for all input types. The {@code pattern} argument + * is only consulted for string input. Numeric input is not supported and returns {@code null}; + * other non-temporal types (for example {@code LocalTime}, {@code Boolean}, {@code byte[]}) + * raise a {@link TransformException}. An out-of-range day-of-month (for example {@code + * 2023-02-30}) is adjusted to the last valid day of that month by the SMART resolver, + * consistent with the other date functions in this class. + */ + public static Long unixTimestamp(List<Object> args) { + // UNIX_TIMESTAMP() — current epoch seconds + if (args.isEmpty()) { + return Instant.now().getEpochSecond(); + } + Object value = args.get(0); + if (value == null) { + return null; + } + + // Resolve and validate the pattern argument before the type dispatch so that + // an explicit NULL pattern or an invalid pattern returns NULL consistently for + // all input types, not only for string input. + DateTimeFormatter formatter = null; + if (args.size() >= 2) { + Object patternArg = args.get(1); + if (patternArg == null) { + return null; + } + String pattern = patternArg.toString(); + try { + formatter = getFormatter(pattern); + } catch (IllegalArgumentException e) { + // An invalid pattern returns NULL rather than raising, so a bad + // pattern value (including one sourced from a row column) does not + // fail the query. + return null; + } + } + + // UNIX_TIMESTAMP(dateTime) — typed datetime argument; pattern not consulted + if (value instanceof OffsetDateTime) { + return ((OffsetDateTime) value).toEpochSecond(); + } + if (value instanceof LocalDateTime) { + return ((LocalDateTime) value).atZone(ZoneId.systemDefault()).toEpochSecond(); + } + if (value instanceof LocalDate) { + return ((LocalDate) value).atStartOfDay(ZoneId.systemDefault()).toEpochSecond(); + } + + // Numeric input is not supported and returns NULL (documented behaviour); + // other non-temporal types raise so a schema/type mistake is not silent. + if (value instanceof Number) { + return null; + } + if (!(value instanceof String)) { + throw new TransformException( + CommonErrorCodeDeprecated.UNSUPPORTED_OPERATION, + String.format( + "Unsupported type %s for function: UNIX_TIMESTAMP", value.getClass())); + } + + // UNIX_TIMESTAMP(string[, pattern]) — string parsed to epoch seconds + String str = (String) value; + if (formatter == null) { + formatter = getFormatter("yyyy-MM-dd HH:mm:ss"); + } + try { + TemporalAccessor parsed = + formatter.parseBest( + str, + ZonedDateTime::from, + OffsetDateTime::from, + LocalDateTime::from, + LocalDate::from); + if (parsed instanceof ZonedDateTime) { + return ((ZonedDateTime) parsed).toEpochSecond(); + } + if (parsed instanceof OffsetDateTime) { + return ((OffsetDateTime) parsed).toEpochSecond(); + } + if (parsed instanceof LocalDateTime) { + return ((LocalDateTime) parsed).atZone(ZoneId.systemDefault()).toEpochSecond(); + } + return ((LocalDate) parsed).atStartOfDay(ZoneId.systemDefault()).toEpochSecond(); + } catch (DateTimeException e) { + // Unparseable input returns NULL rather than throwing + return null; + } + } + public static OffsetDateTime atTimeZone(TemporalAccessor datetime, Object timeZone) { if (datetime == null) { return null; diff --git a/seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/SQLDateTimeFunctionsTest.java b/seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/SQLDateTimeFunctionsTest.java index e00b9fb0314..dabf452765f 100644 --- a/seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/SQLDateTimeFunctionsTest.java +++ b/seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/SQLDateTimeFunctionsTest.java @@ -30,11 +30,16 @@ import org.apache.seatunnel.transform.exception.TransformException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.OffsetDateTime; import java.time.ZoneId; +import java.time.ZoneOffset; import java.util.Collections; import java.util.List; +import java.util.Locale; import java.util.TimeZone; public class SQLDateTimeFunctionsTest { @@ -324,4 +329,387 @@ public class SQLDateTimeFunctionsTest { Assertions.assertNull(timeRow.getField(0)); Assertions.assertNull(timeRow.getField(1)); } + + @Test + public void testUnixTimestampNoArg() { + SeaTunnelRow noArg = + runSql( + "select UNIX_TIMESTAMP() as ts from dual", + new SeaTunnelRowType( + new String[] {"x"}, + new SeaTunnelDataType[] {BasicType.STRING_TYPE}), + "placeholder"); + long now = Instant.now().getEpochSecond(); + Object noArgTs = noArg.getField(0); + Assertions.assertNotNull(noArgTs); + Assertions.assertTrue( + Math.abs((Long) noArgTs - now) < 60, + "UNIX_TIMESTAMP() should be within 60s of now"); + } + + @Test + public void testUnixTimestampStringPatterns() { + TimeZone originalTz = TimeZone.getDefault(); + TimeZone.setDefault(TimeZone.getTimeZone("UTC")); + try { + SeaTunnelRowType strType = + new SeaTunnelRowType( + new String[] {"s"}, new SeaTunnelDataType[] {BasicType.STRING_TYPE}); + + // default pattern yyyy-MM-dd HH:mm:ss + Assertions.assertEquals( + 1672531200L, + runSql( + "select UNIX_TIMESTAMP(s) as ts from dual", + strType, + "2023-01-01 00:00:00") + .getField(0)); + + // custom pattern + Assertions.assertEquals( + 1672531200L, + runSql( + "select UNIX_TIMESTAMP(s, 'yyyy/MM/dd HH:mm:ss') as ts from dual", + strType, + "2023/01/01 00:00:00") + .getField(0)); + + // date-only pattern -> midnight of that day + Assertions.assertEquals( + 1672531200L, + runSql( + "select UNIX_TIMESTAMP(s, 'yyyy-MM-dd') as ts from dual", + strType, + "2023-01-01") + .getField(0)); + } finally { + TimeZone.setDefault(originalTz); + } + } + + @Test + public void testUnixTimestampNullAndInvalid() { + SeaTunnelRowType strType = + new SeaTunnelRowType( + new String[] {"s"}, new SeaTunnelDataType[] {BasicType.STRING_TYPE}); + + // null input -> null + Assertions.assertNull( + runSql("select UNIX_TIMESTAMP(s) as ts from dual", strType, new Object[] {null}) + .getField(0)); + + // unparseable string -> null (does not raise on bad input) + Assertions.assertNull( + runSql("select UNIX_TIMESTAMP(s) as ts from dual", strType, "not-a-date") + .getField(0)); + + // explicit NULL pattern -> null (propagates, does not fall back to default) + Assertions.assertNull( + runSql( + "select UNIX_TIMESTAMP(s, null) as ts from dual", + strType, + "2023-01-01 00:00:00") + .getField(0)); + + // numeric input is not supported -> null + SeaTunnelRowType longType = + new SeaTunnelRowType( + new String[] {"n"}, new SeaTunnelDataType[] {BasicType.LONG_TYPE}); + Assertions.assertNull( + runSql("select UNIX_TIMESTAMP(n) as ts from dual", longType, 1672531200L) + .getField(0)); + } + + @Test + public void testUnixTimestampTypedInputs() { + TimeZone originalTz = TimeZone.getDefault(); + TimeZone.setDefault(TimeZone.getTimeZone("UTC")); + try { + // typed LocalDateTime argument + SeaTunnelRowType dtType = + new SeaTunnelRowType( + new String[] {"dt"}, + new SeaTunnelDataType[] {LocalTimeType.LOCAL_DATE_TIME_TYPE}); + Assertions.assertEquals( + 1672531200L, + runSql( + "select UNIX_TIMESTAMP(dt) as ts from dual", + dtType, + LocalDateTime.of(2023, 1, 1, 0, 0, 0)) + .getField(0)); + + // typed OffsetDateTime argument (offset-aware, TZ-independent) + SeaTunnelRowType odtType = + new SeaTunnelRowType( + new String[] {"odt"}, + new SeaTunnelDataType[] {LocalTimeType.OFFSET_DATE_TIME_TYPE}); + Assertions.assertEquals( + 1672531200L, + runSql( + "select UNIX_TIMESTAMP(odt) as ts from dual", + odtType, + OffsetDateTime.of(2023, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC)) + .getField(0)); + + // typed LocalDate argument (DATE column, resolved at midnight) + SeaTunnelRowType dateType = + new SeaTunnelRowType( + new String[] {"d"}, + new SeaTunnelDataType[] {LocalTimeType.LOCAL_DATE_TYPE}); + Assertions.assertEquals( + 1672531200L, + runSql( + "select UNIX_TIMESTAMP(d) as ts from dual", + dateType, + LocalDate.of(2023, 1, 1)) + .getField(0)); + } finally { + TimeZone.setDefault(originalTz); + } + } + + @Test + public void testUnixTimestampNonUtcZone() { + // timezone contract: the string overload resolves against the JVM default + // zone, not a hardcoded UTC. Under Asia/Shanghai (UTC+8), 2023-01-01 00:00:00 + // maps to 1672502400 (28800s earlier than UTC's 1672531200). + TimeZone originalTz = TimeZone.getDefault(); + TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai")); + try { + SeaTunnelRowType strType = + new SeaTunnelRowType( + new String[] {"s"}, new SeaTunnelDataType[] {BasicType.STRING_TYPE}); + Assertions.assertEquals( + 1672502400L, + runSql( + "select UNIX_TIMESTAMP(s) as ts from dual", + strType, + "2023-01-01 00:00:00") + .getField(0)); + + // OffsetDateTime is offset-aware, so its epoch is zone-independent. + SeaTunnelRowType odtType = + new SeaTunnelRowType( + new String[] {"odt"}, + new SeaTunnelDataType[] {LocalTimeType.OFFSET_DATE_TIME_TYPE}); + Assertions.assertEquals( + 1672531200L, + runSql( + "select UNIX_TIMESTAMP(odt) as ts from dual", + odtType, + OffsetDateTime.of(2023, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC)) + .getField(0)); + } finally { + TimeZone.setDefault(originalTz); + } + } + + @Test + public void testUnixTimestampDateClamping() { + // impossible date (2023-02-30) is clamped to 2023-02-28 by the SMART + // resolver, consistent with the other date functions in this class. + TimeZone originalTz = TimeZone.getDefault(); + TimeZone.setDefault(TimeZone.getTimeZone("UTC")); + try { + SeaTunnelRowType strType = + new SeaTunnelRowType( + new String[] {"s"}, new SeaTunnelDataType[] {BasicType.STRING_TYPE}); + Assertions.assertEquals( + 1677542400L, + runSql( + "select UNIX_TIMESTAMP(s) as ts from dual", + strType, + "2023-02-30 00:00:00") + .getField(0)); + } finally { + TimeZone.setDefault(originalTz); + } + } + + @Test + public void testFromUnixTimeUnixTimestampRoundTrip() { + // Unit-level round trip: FROM_UNIXTIME(UNIX_TIMESTAMP(s)) under a non-UTC + // zone. Both functions use the same default zone, so the round trip holds. + TimeZone originalTz = TimeZone.getDefault(); + TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai")); + try { + SeaTunnelRowType strType = + new SeaTunnelRowType( + new String[] {"s"}, new SeaTunnelDataType[] {BasicType.STRING_TYPE}); + SeaTunnelRow outRow = + runSql( + "select FROM_UNIXTIME(UNIX_TIMESTAMP(s), 'yyyy-MM-dd HH:mm:ss') as rt from dual", + strType, + "2023-01-01 00:00:00"); + Assertions.assertEquals("2023-01-01 00:00:00", outRow.getField(0)); + } finally { + TimeZone.setDefault(originalTz); + } + } + + @Test + public void testUnixTimestampInvalidPattern() { + // An invalid pattern returns NULL rather than raising, so a bad pattern + // value (including one sourced from a row column) does not fail the query. + SeaTunnelRowType strType = + new SeaTunnelRowType( + new String[] {"s"}, new SeaTunnelDataType[] {BasicType.STRING_TYPE}); + Assertions.assertNull( + runSql( + "select UNIX_TIMESTAMP(s, 'yyyy-MM-dd HHH:mm:ss') as ts from dual", + strType, + "2023-01-01 00:00:00") + .getField(0)); + } + + @Test + public void testUnixTimestampOffsetString() { + // A string whose pattern carries a zone offset uses that offset rather + // than the JVM default zone. Under Asia/Shanghai (UTC+8), the string + // '2023-01-01 00:00:00+00:00' with pattern 'yyyy-MM-dd HH:mm:ssXXX' + // denotes 2023-01-01 00:00:00 UTC = epoch 1672531200. If the offset + // were discarded, the result would be 1672502400 (Shanghai midnight). + TimeZone originalTz = TimeZone.getDefault(); + TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai")); + try { + SeaTunnelRowType strType = + new SeaTunnelRowType( + new String[] {"s"}, new SeaTunnelDataType[] {BasicType.STRING_TYPE}); + Assertions.assertEquals( + 1672531200L, + runSql( + "select UNIX_TIMESTAMP(s, 'yyyy-MM-dd HH:mm:ssXXX') as ts from dual", + strType, + "2023-01-01 00:00:00+00:00") + .getField(0)); + } finally { + TimeZone.setDefault(originalTz); + } + } + + @Test + public void testUnixTimestampNullPatternTypedInput() { + // An explicit NULL pattern returns NULL for all input types, not only + // for string input. UNIX_TIMESTAMP(dt, null) where dt is a typed + // LocalDateTime returns NULL rather than ignoring the pattern. + SeaTunnelRowType dtType = + new SeaTunnelRowType( + new String[] {"dt"}, + new SeaTunnelDataType[] {LocalTimeType.LOCAL_DATE_TIME_TYPE}); + Assertions.assertNull( + runSql( + "select UNIX_TIMESTAMP(dt, null) as ts from dual", + dtType, + LocalDateTime.of(2023, 1, 1, 0, 0, 0)) + .getField(0)); + } + + @Test + public void testUnixTimestampUnsupportedType() { + // Non-temporal, non-string types raise a TransformException so a + // schema/type mistake is not silent. A TIME column (LocalTime) has no + // date component, so converting it to epoch seconds is meaningless. + SeaTunnelRowType timeType = + new SeaTunnelRowType( + new String[] {"t"}, + new SeaTunnelDataType[] {LocalTimeType.LOCAL_TIME_TYPE}); + Assertions.assertThrows( + TransformException.class, + () -> + runSql( + "select UNIX_TIMESTAMP(t) as ts from dual", + timeType, + LocalTime.of(0, 0, 0))); + } + + @Test + public void testUnixTimestampAtTimeZoneExample() { + // Pins the documented example: + // select UNIX_TIMESTAMP(dt AT TIME ZONE 'UTC+8') as ts + // (docs/{en,zh}/transforms/sql-functions.md). Without a time-zone + // argument on UNIX_TIMESTAMP, AT TIME ZONE is the supported way to + // convert a TIMESTAMP in a non-default zone. Under Asia/Shanghai + // (UTC+8), LocalDateTime 2023-01-01 00:00:00 is rebased to + // OffsetDateTime 2023-01-01 00:00:00+08:00, whose epoch is + // 2022-12-31 16:00:00 UTC = 1672502400. If the AT TIME ZONE argument + // were ever ignored, the result would instead be 1672531200 (Shanghai + // midnight 2023-01-01). + TimeZone originalTz = TimeZone.getDefault(); + TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai")); + try { + SeaTunnelRowType dtType = + new SeaTunnelRowType( + new String[] {"dt"}, + new SeaTunnelDataType[] {LocalTimeType.LOCAL_DATE_TIME_TYPE}); + Assertions.assertEquals( + 1672502400L, + runSql( + "select UNIX_TIMESTAMP(dt AT TIME ZONE 'UTC+8') as ts from dual", + dtType, + LocalDateTime.of(2023, 1, 1, 0, 0, 0)) + .getField(0)); + } finally { + TimeZone.setDefault(originalTz); + } + } + + @Test + public void testUnixTimestampTextPatternLocaleIndependent() { + // getFormatter previously used DateTimeFormatter.ofPattern(pattern), which + // captures the JVM default FORMAT locale. A text pattern like 'dd MMM yyyy' + // then failed to parse on a non-English worker (de-DE expects "Okt", not + // "Oct") and the catch block returned NULL. With Locale.ENGLISH in + // getFormatter, parsing is locale-independent. Under Locale.GERMANY this + // test fails without the fix. + Locale originalFormatLocale = Locale.getDefault(Locale.Category.FORMAT); + TimeZone originalTz = TimeZone.getDefault(); + TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai")); + try { + Locale.setDefault(Locale.Category.FORMAT, Locale.GERMANY); + SeaTunnelRowType strType = + new SeaTunnelRowType( + new String[] {"s"}, new SeaTunnelDataType[] {BasicType.STRING_TYPE}); + Object field = + runSql( + "select UNIX_TIMESTAMP(s, 'dd MMM yyyy') as ts from dual", + strType, + "23 Oct 2026") + .getField(0); + Assertions.assertNotNull( + field, "text pattern must not return NULL under a non-English locale"); + // 2026-10-23 00:00:00+08:00 (Asia/Shanghai) = 2026-10-22 16:00:00 UTC + Assertions.assertEquals(1792684800L, field); + } finally { + Locale.setDefault(Locale.Category.FORMAT, originalFormatLocale); + TimeZone.setDefault(originalTz); + } + } + + @Test + public void testFromUnixTimeTextPatternLocaleIndependent() { + // FROM_UNIXTIME rendered text patterns in the worker's locale (de-DE -> + // "Okt"), inconsistent with DAYNAME/MONTHNAME which pin English. With + // Locale.ENGLISH in getFormatter, formatting is locale-independent. Under + // Locale.GERMANY this test fails without the fix. + Locale originalFormatLocale = Locale.getDefault(Locale.Category.FORMAT); + TimeZone originalTz = TimeZone.getDefault(); + TimeZone.setDefault(TimeZone.getTimeZone("UTC")); + try { + Locale.setDefault(Locale.Category.FORMAT, Locale.GERMANY); + long epoch = LocalDate.of(2026, 10, 23).atStartOfDay(ZoneOffset.UTC).toEpochSecond(); + SeaTunnelRowType numType = + new SeaTunnelRowType( + new String[] {"n"}, new SeaTunnelDataType[] {BasicType.LONG_TYPE}); + Object field = + runSql("select FROM_UNIXTIME(n, 'dd MMM yyyy') as d from dual", numType, epoch) + .getField(0); + Assertions.assertNotNull(field); + Assertions.assertTrue( + ((String) field).contains("Oct"), + "FROM_UNIXTIME text pattern must render English month names, got: " + field); + } finally { + Locale.setDefault(Locale.Category.FORMAT, originalFormatLocale); + TimeZone.setDefault(originalTz); + } + } }
