-
Notifications
You must be signed in to change notification settings - Fork 1k
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
feat: add PARSE_TIME and FORMAT_TIME functions #7722
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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.Time; | ||
import java.time.LocalTime; | ||
import java.time.format.DateTimeFormatter; | ||
import java.util.concurrent.ExecutionException; | ||
import java.util.concurrent.TimeUnit; | ||
|
||
@UdfDescription( | ||
name = "format_time", | ||
category = FunctionCategory.DATE_TIME, | ||
author = KsqlConstants.CONFLUENT_AUTHOR, | ||
description = "Converts a TIME value into the string representation of the time" | ||
+ " in the given format." | ||
) | ||
public class FormatTime { | ||
|
||
private final LoadingCache<String, DateTimeFormatter> formatters = | ||
CacheBuilder.newBuilder() | ||
.maximumSize(1000) | ||
.build(CacheLoader.from(DateTimeFormatter::ofPattern)); | ||
|
||
@Udf(description = "Converts a TIME value into the" | ||
+ " string representation of the time in the given format." | ||
+ " The format pattern should be in the format expected" | ||
+ " by java.time.format.DateTimeFormatter") | ||
public String formatTime( | ||
@UdfParameter( | ||
description = "TIME value.") final Time time, | ||
@UdfParameter( | ||
description = "The format pattern should be in the format expected by" | ||
+ " java.time.format.DateTimeFormatter.") final String formatPattern) { | ||
if (time == null) { | ||
return null; | ||
} | ||
try { | ||
final DateTimeFormatter formatter = formatters.get(formatPattern); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. No, an exception gets thrown - I'll add a test for that. |
||
return LocalTime.ofNanoOfDay(TimeUnit.MILLISECONDS.toNanos(time.getTime())).format(formatter); | ||
} catch (ExecutionException | RuntimeException e) { | ||
throw new KsqlFunctionException("Failed to format time " | ||
+ LocalTime.ofNanoOfDay(time.getTime() * 1000000) | ||
+ " with formatter '" + formatPattern | ||
+ "': " + e.getMessage(), e); | ||
} | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
/* | ||
* Copyright 2020 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.Time; | ||
import java.time.LocalTime; | ||
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_time", | ||
category = FunctionCategory.DATE_TIME, | ||
author = KsqlConstants.CONFLUENT_AUTHOR, | ||
description = "Converts a string representation of a time in the given format" | ||
+ " into a TIME value." | ||
) | ||
public class ParseTime { | ||
|
||
private final LoadingCache<String, DateTimeFormatter> formatters = | ||
CacheBuilder.newBuilder() | ||
.maximumSize(1000) | ||
.build(CacheLoader.from(DateTimeFormatter::ofPattern)); | ||
|
||
@Udf(description = "Converts a string representation of a time in the given format" | ||
+ " into the TIME value.") | ||
public Time parseTime( | ||
@UdfParameter( | ||
description = "The string representation of a time.") final String formattedTime, | ||
@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(formattedTime); | ||
final Optional<ChronoField> dateField = Arrays.stream(ChronoField.values()) | ||
.filter(field -> field.isDateBased()) | ||
.filter(field -> ta.isSupported(field)) | ||
.findFirst(); | ||
|
||
if (dateField.isPresent()) { | ||
throw new KsqlFunctionException("Time format contains date field."); | ||
} | ||
|
||
return new Time(TimeUnit.NANOSECONDS.toMillis(LocalTime.from(ta).toNanoOfDay())); | ||
} catch (ExecutionException | RuntimeException e) { | ||
throw new KsqlFunctionException("Failed to parse time '" + formattedTime | ||
+ "' with formatter '" + formatPattern | ||
+ "': " + e.getMessage(), e); | ||
} | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,104 @@ | ||
/* | ||
* 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.assertNull; | ||
import static org.junit.Assert.assertThrows; | ||
import static org.junit.Assert.fail; | ||
|
||
import io.confluent.ksql.function.KsqlFunctionException; | ||
import java.sql.Time; | ||
import java.util.stream.IntStream; | ||
import org.junit.Before; | ||
import org.junit.Test; | ||
|
||
public class FormatTimeTest { | ||
|
||
private FormatTime udf; | ||
|
||
@Before | ||
public void setUp() { | ||
udf = new FormatTime(); | ||
} | ||
|
||
@Test | ||
public void shouldConvertTimeToString() { | ||
// When: | ||
final String result = udf.formatTime(new Time(65000), "HHmmss"); | ||
|
||
// Then: | ||
assertThat(result, is("000105")); | ||
} | ||
|
||
@Test | ||
public void shouldRejectUnsupportedFields() { | ||
// When: | ||
final Exception e = assertThrows( | ||
KsqlFunctionException.class, | ||
() -> udf.formatTime(new Time(65000), "yyyy HHmmss")); | ||
|
||
// Then: | ||
assertThat(e.getMessage(), is("Failed to format time 00:01:05 with formatter 'yyyy HHmmss': Unsupported field: YearOfEra")); | ||
} | ||
|
||
@Test | ||
public void shouldSupportEmbeddedChars() { | ||
// When: | ||
final Object result = udf.formatTime(new Time(65000), "HH:mm:ss.SSS'Fred'"); | ||
|
||
// Then: | ||
assertThat(result, is("00:01:05.000Fred")); | ||
} | ||
|
||
@Test | ||
public void shouldThrowIfFormatInvalid() { | ||
// When: | ||
final Exception e = assertThrows( | ||
KsqlFunctionException.class, | ||
() -> udf.formatTime(new Time(65000), "invalid") | ||
); | ||
|
||
// Then: | ||
assertThat(e.getMessage(), containsString("Failed to format time 00:01:05 with formatter 'invalid'")); | ||
} | ||
|
||
@Test | ||
public void shouldByThreadSafeAndWorkWithManyDifferentFormatters() { | ||
IntStream.range(0, 10_000) | ||
.parallel() | ||
.forEach(idx -> { | ||
try { | ||
final String pattern = "HH:mm:ss'X" + idx + "'"; | ||
final String result = udf.formatTime(new Time(65000), pattern); | ||
assertThat(result, is("00:01:05X" + idx)); | ||
} catch (final Exception e) { | ||
fail(e.getMessage()); | ||
} | ||
}); | ||
} | ||
|
||
@Test | ||
public void shoudlReturnNull() { | ||
// When: | ||
final Object result = udf.formatTime(null, "HH:mm:ss.SSS"); | ||
|
||
// Then: | ||
assertNull(result); | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I've been wondering about this cache for a long time and haven't asked. But why do we need it in the time/date/timestamp functions? If a query calls a time UDF with a specific format, then the query will only use 1 format pattern for all rows, won't it? Or if a query calls UDF more than once (one per column) with different formats, doesn't each column have its own instance of
FormatTime
which will end up with one single format pattern for all rows?I haven't checked the above reasoning, but is that the right assumption?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think it's because this function gets called every time there's a new record, so having a cache prevents it from having to recreate the formatter each time.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If it is instantiated once per record, then it probably makes sense. But that magic number of 1000 seems too big. We should dig more into this after 0.20. See if we can get rid of that cache or make it hold the exact # of formatters of the row.