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

Add functions DT_DATE_NOW and DT_DATE_TODAY #453

Merged
merged 6 commits into from
Apr 1, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
4 changes: 3 additions & 1 deletion docs/references/functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ Available through the _ExpressionConfiguration.StandardFunctionsDictionary_ cons

| Name | Description |
|--------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| DT_DATE_NEW(year, month, day [,hour, minute, second, millis, nanos] [,zoneId]) | Returns a new DATE_TIME value with the given parameters. Any optional time zone (string) can be specified, e.g. "Europe/Berlin", or "GMT+02:00. If no zone id is specified, the configured zone id is used. |
| DT_DATE_NEW(year, month, day [,hour, minute, second, millis, nanos] [,zoneId]) | Returns a new DATE_TIME value with the given parameters. Any optional time zone (string) can be specified, e.g. "Europe/Berlin", or "GMT+02:00". If no zone id is specified, the configured zone id is used. |
| DT_DATE_NEW(millis) | Returns a new DATE_TIME from the epoch of 1970-01-01T00:00:00Z in milliseconds. |
| DT_DATE_PARSE(value [,zoneId] [,format, ...]) | Converts the given string value to a date time value by using the optional time zone and formats. All formats are used until the first matching format. Without a format, the configured formats are used. Time zone can be NULL, the the configured time zone is used. |
| DT_DATE_FORMAT(value, [,format] [,zoneId]) | Formats the given date-time to a string using the given optional format and time zone. Without a format, the first configured format is used. The zone id defaults to the configured zone id. |
Expand All @@ -91,3 +91,5 @@ Available through the _ExpressionConfiguration.StandardFunctionsDictionary_ cons
| DT_DURATION_PARSE(value) | Converts the given ISO-8601 duration string representation to a duration value. E.g. "P2DT3H4M" parses 2 days, 3 hours and 4 minutes. |
| DT_DURATION_FROM_MILLIS(millis) | Returns a new DURATION value with the given milliseconds. |
| DT_DURATION_TO_MILLIS(value) | Converts the given duration to a milliseconds value. |
| DT_DATE_NOW() | Produces a new DATE_TIME that represents the current date and time. |
| DT_DATE_TODAY([zoneId]) | Produces a new DATE_TIME that represents the current date, at midnight (00:00). An optional time zone (string) can be specified, e.g. "America/Sao_Paulo", or "GMT-03:00". If no zone id is specified, the configured zone id is used. |
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,9 @@ public class ExpressionConfiguration {
Map.entry("DT_DURATION_NEW", new DurationNewFunction()),
Map.entry("DT_DURATION_FROM_MILLIS", new DurationFromMillisFunction()),
Map.entry("DT_DURATION_TO_MILLIS", new DurationToMillisFunction()),
Map.entry("DT_DURATION_PARSE", new DurationParseFunction()));
Map.entry("DT_DURATION_PARSE", new DurationParseFunction()),
Map.entry("DT_NOW", new DateTimeNowFunction()),
Map.entry("DT_TODAY", new DateTimeTodayFunction()));

/** The math context to use. */
@Builder.Default @Getter private final MathContext mathContext = DEFAULT_MATH_CONTEXT;
Expand Down
11 changes: 11 additions & 0 deletions src/main/java/com/ezylang/evalex/functions/FunctionIfc.java
Original file line number Diff line number Diff line change
Expand Up @@ -79,4 +79,15 @@ default boolean isParameterLazy(int parameterIndex) {
}
return getFunctionParameterDefinitions().get(parameterIndex).isLazy();
}

/**
* Returns the count of non-var-arg parameters defined by this function. If the function has
* var-args, the the result is the count of parameter definitions - 1.
*
* @return the count of non-var-arg parameters defined by this function.
*/
default int getCountOfNonVarArgParameters() {
int numOfParameters = getFunctionParameterDefinitions().size();
return hasVarArgs() ? numOfParameters - 1 : numOfParameters;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
* format is given, the first format defined in the configured formats is used. Second optional
* parameter is the zone-id to use wit formatting. Default is the configured zone-id.
*/
@FunctionParameter(name = "value")
@FunctionParameter(name = "parameters", isVarArg = true)
public class DateTimeFormatFunction extends AbstractFunction {
@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
Copyright 2012-2024 Udo Klimaschewski

Licensed 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.
*/
package com.ezylang.evalex.functions.datetime;

import com.ezylang.evalex.Expression;
import com.ezylang.evalex.data.EvaluationValue;
import com.ezylang.evalex.functions.AbstractFunction;
import com.ezylang.evalex.parser.Token;
import java.time.Instant;

/**
* Produces a new DATE_TIME that represents the current date and time.
*
* <p>It is useful to calculate a value based on the current date and time. For example, if you know
* the start DATE_TIME of a running process, you might use the following expression to find the
* DURATION that represents the process age:
*
* <blockquote>
*
* {@code DT_DATE_NOW() - startDateTime}
*
* </blockquote>
*
* @author oswaldobapvicjr
*/
public class DateTimeNowFunction extends AbstractFunction {
@Override
public EvaluationValue evaluate(
Expression expression, Token functionToken, EvaluationValue... parameterValues) {
return expression.convertValue(Instant.now());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
* pattern will be used. If <code>NULL</code> is specified for the time zone, the currently
* configured zone is used. If no formatters a
*/
@FunctionParameter(name = "value")
@FunctionParameter(name = "parameters", isVarArg = true)
public class DateTimeParseFunction extends AbstractFunction {

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
Copyright 2012-2024 Udo Klimaschewski

Licensed 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.
*/
package com.ezylang.evalex.functions.datetime;

import com.ezylang.evalex.EvaluationException;
import com.ezylang.evalex.Expression;
import com.ezylang.evalex.config.ExpressionConfiguration;
import com.ezylang.evalex.data.EvaluationValue;
import com.ezylang.evalex.functions.AbstractFunction;
import com.ezylang.evalex.functions.FunctionParameter;
import com.ezylang.evalex.parser.Token;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;

/**
* Produces a new DATE_TIME that represents the current date, at midnight (00:00).
*
* <p>It is useful for DATE_TIME comparison, when the current time must not be considered. For
* example, in the expression:
*
* <blockquote>
*
* {@code IF(expiryDate > DT_DATE_TODAY(), "expired", "valid")}
*
* </blockquote>
*
* <p>This function may accept an optional time zone to be applied. If no zone ID is specified, the
* default zone ID defined at the {@link ExpressionConfiguration} will be used.
*
* @author oswaldobapvicjr
*/
@FunctionParameter(name = "parameters", isVarArg = true)
public class DateTimeTodayFunction extends AbstractFunction {
@Override
public EvaluationValue evaluate(
Expression expression, Token functionToken, EvaluationValue... parameterValues)
throws EvaluationException {
ZoneId zoneId = parseZoneId(expression, functionToken, parameterValues);
Instant today = LocalDate.now().atStartOfDay(zoneId).toInstant();
return expression.convertValue(today);
}

private ZoneId parseZoneId(
Expression expression, Token functionToken, EvaluationValue... parameterValues)
throws EvaluationException {
if (parameterValues.length > 0 && !parameterValues[0].isNullValue()) {
return ZoneIdConverter.convert(functionToken, parameterValues[0].getStringValue());
}
return expression.getConfiguration().getZoneId();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
* All other parameters are optional and specify hours, minutes, seconds, milliseconds and
* nanoseconds.
*/
@FunctionParameter(name = "days")
@FunctionParameter(name = "parameters", isVarArg = true)
public class DurationNewFunction extends AbstractFunction {
@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ private void processBraceClose() throws ParseException {
private void validateFunctionParameters(Token functionToken, ArrayList<ASTNode> parameters)
throws ParseException {
FunctionIfc function = functionToken.getFunctionDefinition();
if (parameters.size() < function.getFunctionParameterDefinitions().size()) {
if (parameters.size() < function.getCountOfNonVarArgParameters()) {
throw new ParseException(functionToken, "Not enough parameters for function");
}
if (!function.hasVarArgs()
Expand Down
5 changes: 5 additions & 0 deletions src/test/java/com/ezylang/evalex/BaseEvaluationTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ protected void assertExpressionHasExpectedResult(
.isEqualTo(expectedResult);
}

protected EvaluationValue evaluate(String expression) throws EvaluationException, ParseException {
return evaluate(
expression, TestConfigurationProvider.StandardConfigurationWithAdditionalTestOperators);
}

private EvaluationValue evaluate(String expressionString, ExpressionConfiguration configuration)
throws EvaluationException, ParseException {
Expression expression = new Expression(expressionString, configuration);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,25 +15,32 @@
*/
package com.ezylang.evalex.functions.datetime;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.within;

import com.ezylang.evalex.BaseEvaluationTest;
import com.ezylang.evalex.EvaluationException;
import com.ezylang.evalex.Expression;
import com.ezylang.evalex.config.ExpressionConfiguration;
import com.ezylang.evalex.config.TestConfigurationProvider;
import com.ezylang.evalex.parser.ParseException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;

class DateTimeFunctionsTest extends BaseEvaluationTest {

private static final ZoneId DEFAULT_ZONE_ID = ZoneId.of("Europe/Berlin");

private static final ExpressionConfiguration DateTimeTestConfiguration =
TestConfigurationProvider.StandardConfigurationWithAdditionalTestOperators.toBuilder()
.zoneId(ZoneId.of("Europe/Berlin"))
.zoneId(DEFAULT_ZONE_ID)
.build();

@ParameterizedTest
Expand Down Expand Up @@ -231,6 +238,27 @@ void testDateTimeToEpoch(String expression, String expectedResult)
assertExpressionHasExpectedResult(expression, expectedResult);
}

@Test
void testDateTimeNow() throws EvaluationException, ParseException {
Instant expectedTime = Instant.now();
Instant actualTime = evaluate("DT_NOW()").getDateTimeValue();
assertThat(actualTime).isCloseTo(expectedTime, within(1, ChronoUnit.SECONDS));
}

@Test
void testDateTimeTodayDefaultTimeZone() throws EvaluationException, ParseException {
Instant expectedTime = LocalDate.now().atStartOfDay(DEFAULT_ZONE_ID).toInstant();
Instant actualTime = evaluate("DT_TODAY()").getDateTimeValue();
assertThat(actualTime).isEqualTo(expectedTime);
}

@Test
void testDateTimeTodayDifferentTimeZone() throws EvaluationException, ParseException {
Instant expectedTime = LocalDate.now().atStartOfDay(ZoneId.of("America/Sao_Paulo")).toInstant();
Instant actualTime = evaluate("DT_TODAY(\"America/Sao_Paulo\")").getDateTimeValue();
assertThat(actualTime).isEqualTo(expectedTime);
}

@ParameterizedTest
@CsvSource(
delimiter = '|',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,8 @@ void testFunctionNotEnoughParameters() {

@Test
void testFunctionNotEnoughParametersForVarArgs() {
Expression expression = new Expression("MIN()");
// The DT_DATE_PARSE() function has a required parameter and var-args
Expression expression = new Expression("DT_DATE_PARSE()");

assertThatThrownBy(expression::evaluate)
.isInstanceOf(ParseException.class)
Expand Down
Loading