-
Notifications
You must be signed in to change notification settings - Fork 1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add PARSE_DATE and FORMAT_DATE functions (#7733)
* feat: add PARSE_DATE and FORMAT_DATE functions * address review comments * add check for time fields in parser * whitespace
- Loading branch information
Zara Lim
authored
Jul 1, 2021
1 parent
79d14fb
commit 5a64ed7
Showing
16 changed files
with
1,058 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
70 changes: 70 additions & 0 deletions
70
ksqldb-engine/src/main/java/io/confluent/ksql/function/udf/datetime/FormatDate.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
/* | ||
* Copyright 2021 Confluent Inc. | ||
* | ||
* Licensed under the Confluent Community License (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.confluent.io/confluent-community-license | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT | ||
* WARRANTIES OF ANY KIND, either express or implied. See the License for the | ||
* specific language governing permissions and limitations under the License. | ||
*/ | ||
|
||
package io.confluent.ksql.function.udf.datetime; | ||
|
||
import com.google.common.cache.CacheBuilder; | ||
import com.google.common.cache.CacheLoader; | ||
import com.google.common.cache.LoadingCache; | ||
import io.confluent.ksql.function.FunctionCategory; | ||
import io.confluent.ksql.function.KsqlFunctionException; | ||
import io.confluent.ksql.function.udf.Udf; | ||
import io.confluent.ksql.function.udf.UdfDescription; | ||
import io.confluent.ksql.function.udf.UdfParameter; | ||
import io.confluent.ksql.util.KsqlConstants; | ||
import java.sql.Date; | ||
import java.time.LocalDate; | ||
import java.time.format.DateTimeFormatter; | ||
import java.util.concurrent.ExecutionException; | ||
import java.util.concurrent.TimeUnit; | ||
|
||
@UdfDescription( | ||
name = "format_date", | ||
category = FunctionCategory.DATE_TIME, | ||
author = KsqlConstants.CONFLUENT_AUTHOR, | ||
description = "Converts a DATE value to a string" | ||
+ " using the given format pattern. The format pattern should be" | ||
+ " in the format expected by java.time.format.DateTimeFormatter." | ||
) | ||
public class FormatDate { | ||
|
||
private final LoadingCache<String, DateTimeFormatter> formatters = | ||
CacheBuilder.newBuilder() | ||
.maximumSize(1000) | ||
.build(CacheLoader.from(DateTimeFormatter::ofPattern)); | ||
|
||
@Udf(description = "Converts the number of days since 1970-01-01 00:00:00 UTC/GMT to a date " | ||
+ "string using the given format pattern. The format pattern should be in the format" | ||
+ " expected by java.time.format.DateTimeFormatter") | ||
public String formatDate( | ||
@UdfParameter( | ||
description = "The date to convert") final Date date, | ||
@UdfParameter( | ||
description = "The format pattern should be in the format expected by" | ||
+ " java.time.format.DateTimeFormatter.") final String formatPattern) { | ||
if (date == null) { | ||
return null; | ||
} | ||
try { | ||
final DateTimeFormatter formatter = formatters.get(formatPattern); | ||
return LocalDate.ofEpochDay(TimeUnit.MILLISECONDS.toDays(date.getTime())).format(formatter); | ||
} catch (final ExecutionException | RuntimeException e) { | ||
throw new KsqlFunctionException("Failed to format date " + date | ||
+ " with formatter '" + formatPattern | ||
+ "': " + e.getMessage(), e); | ||
} | ||
} | ||
|
||
} |
80 changes: 80 additions & 0 deletions
80
ksqldb-engine/src/main/java/io/confluent/ksql/function/udf/datetime/ParseDate.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
/* | ||
* Copyright 2021 Confluent Inc. | ||
* | ||
* Licensed under the Confluent Community License (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.confluent.io/confluent-community-license | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT | ||
* WARRANTIES OF ANY KIND, either express or implied. See the License for the | ||
* specific language governing permissions and limitations under the License. | ||
*/ | ||
|
||
package io.confluent.ksql.function.udf.datetime; | ||
|
||
import com.google.common.cache.CacheBuilder; | ||
import com.google.common.cache.CacheLoader; | ||
import com.google.common.cache.LoadingCache; | ||
import io.confluent.ksql.function.FunctionCategory; | ||
import io.confluent.ksql.function.KsqlFunctionException; | ||
import io.confluent.ksql.function.udf.Udf; | ||
import io.confluent.ksql.function.udf.UdfDescription; | ||
import io.confluent.ksql.function.udf.UdfParameter; | ||
import io.confluent.ksql.util.KsqlConstants; | ||
import java.sql.Date; | ||
import java.time.LocalDate; | ||
import java.time.format.DateTimeFormatter; | ||
import java.time.temporal.ChronoField; | ||
import java.time.temporal.TemporalAccessor; | ||
import java.util.Arrays; | ||
import java.util.Optional; | ||
import java.util.concurrent.ExecutionException; | ||
import java.util.concurrent.TimeUnit; | ||
|
||
@UdfDescription( | ||
name = "parse_date", | ||
category = FunctionCategory.DATE_TIME, | ||
author = KsqlConstants.CONFLUENT_AUTHOR, | ||
description = "Converts a string representation of a date in the given format" | ||
+ " into a DATE value. The format pattern should be in the format expected by" | ||
+ " java.time.format.DateTimeFormatter" | ||
) | ||
public class ParseDate { | ||
|
||
private final LoadingCache<String, DateTimeFormatter> formatters = | ||
CacheBuilder.newBuilder() | ||
.maximumSize(1000) | ||
.build(CacheLoader.from(DateTimeFormatter::ofPattern)); | ||
|
||
@Udf(description = "Converts a string representation of a date in the given format" | ||
+ " into a DATE value.") | ||
public Date parseDate( | ||
@UdfParameter( | ||
description = "The string representation of a date.") final String formattedDate, | ||
@UdfParameter( | ||
description = "The format pattern should be in the format expected by" | ||
+ " java.time.format.DateTimeFormatter.") final String formatPattern) { | ||
try { | ||
|
||
final TemporalAccessor ta = formatters.get(formatPattern).parse(formattedDate); | ||
final Optional<ChronoField> timeField = Arrays.stream(ChronoField.values()) | ||
.filter(field -> field.isTimeBased()) | ||
.filter(field -> ta.isSupported(field)) | ||
.findFirst(); | ||
|
||
if (timeField.isPresent()) { | ||
throw new KsqlFunctionException("Date format contains time field."); | ||
} | ||
|
||
return new Date( | ||
TimeUnit.DAYS.toMillis(LocalDate.from(ta).toEpochDay())); | ||
} catch (final ExecutionException | RuntimeException e) { | ||
throw new KsqlFunctionException("Failed to parse date '" + formattedDate | ||
+ "' with formatter '" + formatPattern | ||
+ "': " + e.getMessage(), e); | ||
} | ||
} | ||
} |
108 changes: 108 additions & 0 deletions
108
ksqldb-engine/src/test/java/io/confluent/ksql/function/udf/datetime/FormatDateTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,108 @@ | ||
/* | ||
* Copyright 2021 Confluent Inc. | ||
* | ||
* Licensed under the Confluent Community License (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.confluent.io/confluent-community-license | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT | ||
* WARRANTIES OF ANY KIND, either express or implied. See the License for the | ||
* specific language governing permissions and limitations under the License. | ||
*/ | ||
|
||
package io.confluent.ksql.function.udf.datetime; | ||
|
||
import static org.hamcrest.CoreMatchers.is; | ||
import static org.hamcrest.MatcherAssert.assertThat; | ||
import static org.hamcrest.Matchers.containsString; | ||
import static org.junit.Assert.assertThrows; | ||
import static org.junit.Assert.fail; | ||
|
||
import io.confluent.ksql.function.KsqlFunctionException; | ||
import java.sql.Date; | ||
import java.util.stream.IntStream; | ||
import org.junit.Before; | ||
import org.junit.Test; | ||
|
||
public class FormatDateTest { | ||
|
||
private FormatDate udf; | ||
|
||
@Before | ||
public void setUp() { | ||
udf = new FormatDate(); | ||
} | ||
|
||
@Test | ||
public void shouldConvertDateToString() { | ||
// When: | ||
final String result = udf.formatDate(Date.valueOf("2014-11-09"), "yyyy-MM-dd"); | ||
|
||
// Then: | ||
assertThat(result, is("2014-11-09")); | ||
} | ||
|
||
@Test | ||
public void shouldThrowOnUnsupportedFields() { | ||
// When: | ||
final Exception e = assertThrows( | ||
KsqlFunctionException.class, | ||
() -> udf.formatDate(Date.valueOf("2014-11-09"), "yyyy-MM-dd HH:mm")); | ||
|
||
// Then: | ||
assertThat(e.getMessage(), is("Failed to format date 2014-11-09 with formatter 'yyyy-MM-dd HH:mm': Unsupported field: HourOfDay")); | ||
} | ||
|
||
@Test | ||
public void shouldRoundTripWithStringToDate() { | ||
final String format = "dd/MM/yyyy'Freya'"; | ||
final ParseDate parseDate = new ParseDate(); | ||
IntStream.range(-10_000, 20_000) | ||
.parallel() | ||
.forEach(idx -> { | ||
final String result = udf.formatDate(new Date(idx * 86400000L), format); | ||
final Date date = parseDate.parseDate(result, format); | ||
assertThat(date.getTime(), is(idx * 86400000L)); | ||
}); | ||
} | ||
|
||
@Test | ||
public void shouldSupportEmbeddedChars() { | ||
// When: | ||
final Object result = udf.formatDate(Date.valueOf("2014-11-09"), "yyyy-dd-MM'Fred'"); | ||
|
||
// Then: | ||
assertThat(result, is("2014-09-11Fred")); | ||
} | ||
|
||
@Test | ||
public void shouldThrowIfFormatInvalid() { | ||
// When: | ||
final Exception e = assertThrows( | ||
KsqlFunctionException.class, | ||
() -> udf.formatDate(Date.valueOf("2014-11-09"), "invalid") | ||
); | ||
|
||
// Then: | ||
assertThat(e.getMessage(), containsString("Failed to format date 2014-11-09 with formatter 'invalid'")); | ||
} | ||
|
||
@Test | ||
public void shouldByThreadSafeAndWorkWithManyDifferentFormatters() { | ||
IntStream.range(0, 10_000) | ||
.parallel() | ||
.forEach(idx -> { | ||
try { | ||
final String pattern = "yyyy-MM-dd'X" + idx + "'"; | ||
final String result = udf.formatDate(Date.valueOf("2021-05-18"), pattern); | ||
assertThat(result, is("2021-05-18X" + idx)); | ||
} catch (final Exception e) { | ||
fail(e.getMessage()); | ||
} | ||
}); | ||
} | ||
|
||
} |
Oops, something went wrong.