diff --git a/build.gradle b/build.gradle index bad33f6bac..9cc1e6cdaa 100644 --- a/build.gradle +++ b/build.gradle @@ -84,21 +84,7 @@ repositories { spotless { java { target fileTree('.') { - include 'core/src/main/java/org/opensearch/sql/analysis/**/*.java', - 'core/src/test/java/org/opensearch/sql/data/**/*.java', - 'core/src/test/java/org/opensearch/sql/datasource/**/*.java', - 'core/src/test/java/org/opensearch/sql/ast/**/*.java', - 'core/src/main/java/org/opensearch/sql/monitor/**/*.java', - 'core/src/main/java/org/opensearch/sql/expression/**/*.java', - 'core/src/main/java/org/opensearch/sql/executor/**/*.java', - 'core/src/main/java/org/opensearch/sql/exception/**/*.java', - 'core/src/main/java/org/opensearch/sql/planner/**/*.java', - 'core/src/main/java/org/opensearch/sql/storage/**/*.java', - 'core/src/main/java/org/opensearch/sql/utils/**/*.java', - 'core/src/main/java/org/opensearch/sql/DataSourceSchemaName.java', - 'core/src/test/java/org/opensearch/sql/data/**/*.java', - 'core/src/test/java/org/opensearch/sql/config/**/*.java', - 'core/src/test/java/org/opensearch/sql/analysis/**/*.java' + include 'core/**/*.java' exclude '**/build/**', '**/build-*/**' } // importOrder() diff --git a/core/build.gradle b/core/build.gradle index cf7f0b7a1c..5d67740a28 100644 --- a/core/build.gradle +++ b/core/build.gradle @@ -66,6 +66,9 @@ dependencies { testImplementation group: 'org.mockito', name: 'mockito-junit-jupiter', version: '3.12.4' } +checkstyleMain.ignoreFailures = true +checkstyleTest.ignoreFailures = true + test { useJUnitPlatform() testLogging { diff --git a/core/src/main/java/org/opensearch/sql/ast/dsl/AstDSL.java b/core/src/main/java/org/opensearch/sql/ast/dsl/AstDSL.java index da018f7b20..95dfc41360 100644 --- a/core/src/main/java/org/opensearch/sql/ast/dsl/AstDSL.java +++ b/core/src/main/java/org/opensearch/sql/ast/dsl/AstDSL.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.ast.dsl; import java.util.Arrays; @@ -63,9 +62,7 @@ import org.opensearch.sql.ast.tree.UnresolvedPlan; import org.opensearch.sql.ast.tree.Values; -/** - * Class of static methods to create specific node instances. - */ +/** Class of static methods to create specific node instances. */ @UtilityClass public class AstDSL { @@ -132,8 +129,9 @@ public static UnresolvedPlan rename(UnresolvedPlan input, Map... maps) { /** * Initialize Values node by rows of literals. - * @param values rows in which each row is a list of literal values - * @return Values node + * + * @param values rows in which each row is a list of literal values + * @return Values node */ @SafeVarargs public UnresolvedPlan values(List... values) { @@ -255,21 +253,23 @@ public static Function function(String funcName, UnresolvedExpression... funcArg *   [ELSE result_expr]
* END */ - public UnresolvedExpression caseWhen(UnresolvedExpression elseClause, - When... whenClauses) { + public UnresolvedExpression caseWhen(UnresolvedExpression elseClause, When... whenClauses) { return caseWhen(null, elseClause, whenClauses); } /** + * + * + *
    * CASE case_value_expr
    *     WHEN compare_expr THEN result_expr
    *     [WHEN compare_expr THEN result_expr] ...
    *     [ELSE result_expr]
    * END
+   * 
*/ - public UnresolvedExpression caseWhen(UnresolvedExpression caseValueExpr, - UnresolvedExpression elseClause, - When... whenClauses) { + public UnresolvedExpression caseWhen( + UnresolvedExpression caseValueExpr, UnresolvedExpression elseClause, When... whenClauses) { return new Case(caseValueExpr, Arrays.asList(whenClauses), elseClause); } @@ -281,19 +281,20 @@ public When when(UnresolvedExpression condition, UnresolvedExpression result) { return new When(condition, result); } - public UnresolvedExpression highlight(UnresolvedExpression fieldName, - java.util.Map arguments) { + public UnresolvedExpression highlight( + UnresolvedExpression fieldName, java.util.Map arguments) { return new HighlightFunction(fieldName, arguments); } - public UnresolvedExpression score(UnresolvedExpression relevanceQuery, - Literal relevanceFieldWeight) { + public UnresolvedExpression score( + UnresolvedExpression relevanceQuery, Literal relevanceFieldWeight) { return new ScoreFunction(relevanceQuery, relevanceFieldWeight); } - public UnresolvedExpression window(UnresolvedExpression function, - List partitionByList, - List> sortList) { + public UnresolvedExpression window( + UnresolvedExpression function, + List partitionByList, + List> sortList) { return new WindowFunction(function, partitionByList, sortList); } @@ -328,9 +329,10 @@ public static UnresolvedExpression compare( return new Compare(operator, left, right); } - public static UnresolvedExpression between(UnresolvedExpression value, - UnresolvedExpression lowerBound, - UnresolvedExpression upperBound) { + public static UnresolvedExpression between( + UnresolvedExpression value, + UnresolvedExpression lowerBound, + UnresolvedExpression upperBound) { return new Between(value, lowerBound, upperBound); } @@ -398,9 +400,7 @@ public static List defaultFieldsArgs() { return exprList(argument("exclude", booleanLiteral(false))); } - /** - * Default Stats Command Args. - */ + /** Default Stats Command Args. */ public static List defaultStatsArgs() { return exprList( argument("partitions", intLiteral(1)), @@ -409,9 +409,7 @@ public static List defaultStatsArgs() { argument("dedupsplit", booleanLiteral(false))); } - /** - * Default Dedup Command Args. - */ + /** Default Dedup Command Args. */ public static List defaultDedupArgs() { return exprList( argument("number", intLiteral(1)), @@ -447,9 +445,12 @@ public static List defaultTopArgs() { return exprList(argument("noOfResults", intLiteral(10))); } - public static RareTopN rareTopN(UnresolvedPlan input, CommandType commandType, - List noOfResults, List groupList, - Field... fields) { + public static RareTopN rareTopN( + UnresolvedPlan input, + CommandType commandType, + List noOfResults, + List groupList, + Field... fields) { return new RareTopN(input, commandType, noOfResults, Arrays.asList(fields), groupList) .attach(input); } @@ -458,11 +459,12 @@ public static Limit limit(UnresolvedPlan input, Integer limit, Integer offset) { return new Limit(limit, offset).attach(input); } - public static Parse parse(UnresolvedPlan input, ParseMethod parseMethod, - UnresolvedExpression sourceField, - Literal pattern, - java.util.Map arguments) { + public static Parse parse( + UnresolvedPlan input, + ParseMethod parseMethod, + UnresolvedExpression sourceField, + Literal pattern, + java.util.Map arguments) { return new Parse(parseMethod, sourceField, pattern, arguments, input); } - } diff --git a/core/src/main/java/org/opensearch/sql/ast/expression/QualifiedName.java b/core/src/main/java/org/opensearch/sql/ast/expression/QualifiedName.java index 73c6e3782a..b7bfcd542e 100644 --- a/core/src/main/java/org/opensearch/sql/ast/expression/QualifiedName.java +++ b/core/src/main/java/org/opensearch/sql/ast/expression/QualifiedName.java @@ -75,16 +75,21 @@ public Optional first() { } /** + * + * + *
    * Get rest parts of the qualified name. Assume that there must be remaining parts so caller is
-   * responsible for the check (first() or size() must be called first).
- * For example:
- * {@code
- *   QualifiedName name = ...
- *   Optional first = name.first();
- *   if (first.isPresent()) {
- *   name.rest() ...
- *   }
+ * responsible for the check (first() or size() must be called first). + * For example: + * {@code + * QualifiedName name = ... + * Optional first = name.first(); + * if (first.isPresent()) { + * name.rest() ... * } + * } + *
+ * * @return rest part(s) */ public QualifiedName rest() { diff --git a/core/src/main/java/org/opensearch/sql/data/model/AbstractExprValue.java b/core/src/main/java/org/opensearch/sql/data/model/AbstractExprValue.java index f5ac4d493b..fd2cc90297 100644 --- a/core/src/main/java/org/opensearch/sql/data/model/AbstractExprValue.java +++ b/core/src/main/java/org/opensearch/sql/data/model/AbstractExprValue.java @@ -29,8 +29,8 @@ public int compareTo(ExprValue other) { } /** - * The customize equals logic. - * The table below list the NULL and MISSING handling logic. + * The customize equals logic. The table below list the NULL and MISSING handling logic. + * * * * diff --git a/core/src/main/java/org/opensearch/sql/data/model/ExprTimeValue.java b/core/src/main/java/org/opensearch/sql/data/model/ExprTimeValue.java index c22b423c7d..d808af49b1 100644 --- a/core/src/main/java/org/opensearch/sql/data/model/ExprTimeValue.java +++ b/core/src/main/java/org/opensearch/sql/data/model/ExprTimeValue.java @@ -34,8 +34,7 @@ public ExprTimeValue(String time) { this.time = LocalTime.parse(time, DATE_TIME_FORMATTER_VARIABLE_NANOS_OPTIONAL); } catch (DateTimeParseException e) { throw new SemanticCheckException( - String.format( - "time:%s in unsupported format, please use 'HH:mm:ss[.SSSSSSSSS]'", time)); + String.format("time:%s in unsupported format, please use 'HH:mm:ss[.SSSSSSSSS]'", time)); } } diff --git a/core/src/main/java/org/opensearch/sql/data/type/WideningTypeRule.java b/core/src/main/java/org/opensearch/sql/data/type/WideningTypeRule.java index c9b5c29157..723d09956d 100644 --- a/core/src/main/java/org/opensearch/sql/data/type/WideningTypeRule.java +++ b/core/src/main/java/org/opensearch/sql/data/type/WideningTypeRule.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.data.type; import static org.opensearch.sql.data.type.ExprCoreType.UNKNOWN; @@ -13,6 +12,7 @@ /** * The definition of widening type rule for expression value. + * *
A
* * @@ -31,8 +31,8 @@ public class WideningTypeRule { public static final int TYPE_EQUAL = 0; /** - * The widening distance is calculated from the leaf to root. - * e.g. distance(INTEGER, FLOAT) = 2, but distance(FLOAT, INTEGER) = IMPOSSIBLE_WIDENING + * The widening distance is calculated from the leaf to root. e.g. distance(INTEGER, FLOAT) = 2, + * but distance(FLOAT, INTEGER) = IMPOSSIBLE_WIDENING * * @param type1 widen from type * @param type2 widen to type @@ -50,14 +50,15 @@ private static int distance(ExprType type1, ExprType type2, int distance) { } else { return type1.getParent().stream() .map(parentOfType1 -> distance(parentOfType1, type2, distance + 1)) - .reduce(Math::min).get(); + .reduce(Math::min) + .get(); } } /** * The max type among two types. The max is defined as follow if type1 could widen to type2, then - * max is type2, vice versa if type1 couldn't widen to type2 and type2 could't widen to type1, then - * throw {@link ExpressionEvaluationException}. + * max is type2, vice versa if type1 couldn't widen to type2 and type2 could't widen to type1, + * then throw {@link ExpressionEvaluationException}. * * @param type1 type1 * @param type2 type2 diff --git a/core/src/test/java/org/opensearch/sql/data/model/DateTimeValueTest.java b/core/src/test/java/org/opensearch/sql/data/model/DateTimeValueTest.java index c455f77969..fcdc52e374 100644 --- a/core/src/test/java/org/opensearch/sql/data/model/DateTimeValueTest.java +++ b/core/src/test/java/org/opensearch/sql/data/model/DateTimeValueTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.data.model; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -47,13 +46,14 @@ public void timeValueInterfaceTest() { assertEquals(today, timeValue.dateValue(functionProperties)); assertEquals(today.atTime(1, 1, 1), timeValue.datetimeValue(functionProperties)); - assertEquals(ZonedDateTime.of(LocalTime.parse("01:01:01").atDate(today), - UTC_ZONE_ID).toInstant(), timeValue.timestampValue(functionProperties)); + assertEquals( + ZonedDateTime.of(LocalTime.parse("01:01:01").atDate(today), UTC_ZONE_ID).toInstant(), + timeValue.timestampValue(functionProperties)); assertEquals("01:01:01", timeValue.value()); assertEquals("TIME '01:01:01'", timeValue.toString()); - exception = assertThrows(ExpressionEvaluationException.class, - () -> integerValue(1).timeValue()); + exception = + assertThrows(ExpressionEvaluationException.class, () -> integerValue(1).timeValue()); assertEquals("invalid to get timeValue from value of type INTEGER", exception.getMessage()); } @@ -62,14 +62,17 @@ public void timestampValueInterfaceTest() { ExprValue timestampValue = new ExprTimestampValue("2020-07-07 01:01:01"); assertEquals(TIMESTAMP, timestampValue.type()); - assertEquals(ZonedDateTime.of(LocalDateTime.parse("2020-07-07T01:01:01"), - UTC_ZONE_ID).toInstant(), timestampValue.timestampValue()); + assertEquals( + ZonedDateTime.of(LocalDateTime.parse("2020-07-07T01:01:01"), UTC_ZONE_ID).toInstant(), + timestampValue.timestampValue()); assertEquals("2020-07-07 01:01:01", timestampValue.value()); assertEquals("TIMESTAMP '2020-07-07 01:01:01'", timestampValue.toString()); assertEquals(LocalDate.parse("2020-07-07"), timestampValue.dateValue()); assertEquals(LocalTime.parse("01:01:01"), timestampValue.timeValue()); assertEquals(LocalDateTime.parse("2020-07-07T01:01:01"), timestampValue.datetimeValue()); - assertThrows(ExpressionEvaluationException.class, () -> integerValue(1).timestampValue(), + assertThrows( + ExpressionEvaluationException.class, + () -> integerValue(1).timestampValue(), "invalid to get timestampValue from value of type INTEGER"); } @@ -80,12 +83,12 @@ public void dateValueInterfaceTest() { assertEquals(LocalDate.parse("2012-07-07"), dateValue.dateValue()); assertEquals(LocalTime.parse("00:00:00"), dateValue.timeValue()); assertEquals(LocalDateTime.parse("2012-07-07T00:00:00"), dateValue.datetimeValue()); - assertEquals(ZonedDateTime.of(LocalDateTime.parse("2012-07-07T00:00:00"), - UTC_ZONE_ID).toInstant(), dateValue.timestampValue()); + assertEquals( + ZonedDateTime.of(LocalDateTime.parse("2012-07-07T00:00:00"), UTC_ZONE_ID).toInstant(), + dateValue.timestampValue()); ExpressionEvaluationException exception = assertThrows(ExpressionEvaluationException.class, () -> integerValue(1).dateValue()); - assertEquals("invalid to get dateValue from value of type INTEGER", - exception.getMessage()); + assertEquals("invalid to get dateValue from value of type INTEGER", exception.getMessage()); } @Test @@ -95,10 +98,13 @@ public void datetimeValueInterfaceTest() { assertEquals(LocalDateTime.parse("2020-08-17T19:44:00"), datetimeValue.datetimeValue()); assertEquals(LocalDate.parse("2020-08-17"), datetimeValue.dateValue()); assertEquals(LocalTime.parse("19:44:00"), datetimeValue.timeValue()); - assertEquals(ZonedDateTime.of(LocalDateTime.parse("2020-08-17T19:44:00"), - UTC_ZONE_ID).toInstant(), datetimeValue.timestampValue()); + assertEquals( + ZonedDateTime.of(LocalDateTime.parse("2020-08-17T19:44:00"), UTC_ZONE_ID).toInstant(), + datetimeValue.timestampValue()); assertEquals("DATETIME '2020-08-17 19:44:00'", datetimeValue.toString()); - assertThrows(ExpressionEvaluationException.class, () -> integerValue(1).datetimeValue(), + assertThrows( + ExpressionEvaluationException.class, + () -> integerValue(1).datetimeValue(), "invalid to get datetimeValue from value of type INTEGER"); } @@ -122,8 +128,8 @@ public void timeInUnsupportedFormat() { @Test public void timestampInUnsupportedFormat() { SemanticCheckException exception = - assertThrows(SemanticCheckException.class, - () -> new ExprTimestampValue("2020-07-07T01:01:01Z")); + assertThrows( + SemanticCheckException.class, () -> new ExprTimestampValue("2020-07-07T01:01:01Z")); assertEquals( "timestamp:2020-07-07T01:01:01Z in unsupported format, " + "please use yyyy-MM-dd HH:mm:ss[.SSSSSSSSS]", @@ -133,8 +139,8 @@ public void timestampInUnsupportedFormat() { @Test public void datetimeInUnsupportedFormat() { SemanticCheckException exception = - assertThrows(SemanticCheckException.class, - () -> new ExprDatetimeValue("2020-07-07T01:01:01Z")); + assertThrows( + SemanticCheckException.class, () -> new ExprDatetimeValue("2020-07-07T01:01:01Z")); assertEquals( "datetime:2020-07-07T01:01:01Z in unsupported format, " + "please use yyyy-MM-dd HH:mm:ss[.SSSSSSSSS]", @@ -151,7 +157,8 @@ public void stringDateTimeValue() { assertEquals("\"2020-08-17 19:44:00\"", stringValue.toString()); SemanticCheckException exception = - assertThrows(SemanticCheckException.class, + assertThrows( + SemanticCheckException.class, () -> new ExprStringValue("2020-07-07T01:01:01Z").datetimeValue()); assertEquals( "datetime:2020-07-07T01:01:01Z in unsupported format, " @@ -249,7 +256,8 @@ public void datetimeWithVariableNanoPrecision() { @Test public void timestampOverMaxNanoPrecision() { SemanticCheckException exception = - assertThrows(SemanticCheckException.class, + assertThrows( + SemanticCheckException.class, () -> new ExprTimestampValue("2020-07-07 01:01:01.1234567890")); assertEquals( "timestamp:2020-07-07 01:01:01.1234567890 in unsupported format, please use " @@ -260,7 +268,8 @@ public void timestampOverMaxNanoPrecision() { @Test public void datetimeOverMaxNanoPrecision() { SemanticCheckException exception = - assertThrows(SemanticCheckException.class, + assertThrows( + SemanticCheckException.class, () -> new ExprDatetimeValue("2020-07-07 01:01:01.1234567890")); assertEquals( "datetime:2020-07-07 01:01:01.1234567890 in unsupported format, " @@ -271,8 +280,7 @@ public void datetimeOverMaxNanoPrecision() { @Test public void timeOverMaxNanoPrecision() { SemanticCheckException exception = - assertThrows(SemanticCheckException.class, - () -> new ExprTimeValue("01:01:01.1234567890")); + assertThrows(SemanticCheckException.class, () -> new ExprTimeValue("01:01:01.1234567890")); assertEquals( "time:01:01:01.1234567890 in unsupported format, please use HH:mm:ss[.SSSSSSSSS]", exception.getMessage()); diff --git a/core/src/test/java/org/opensearch/sql/executor/ExplainTest.java b/core/src/test/java/org/opensearch/sql/executor/ExplainTest.java index 7d438c870d..897347f22d 100644 --- a/core/src/test/java/org/opensearch/sql/executor/ExplainTest.java +++ b/core/src/test/java/org/opensearch/sql/executor/ExplainTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.executor; import static java.util.Collections.emptyList; @@ -68,36 +67,30 @@ void can_explain_project_filter_table_scan() { DSL.equal(ref("balance", INTEGER), literal(10000)), DSL.greater(ref("age", INTEGER), literal(30))); NamedExpression[] projectList = { - named("full_name", ref("full_name", STRING), "name"), - named("age", ref("age", INTEGER)) + named("full_name", ref("full_name", STRING), "name"), named("age", ref("age", INTEGER)) }; - PhysicalPlan plan = - project( - filter( - tableScan, - filterExpr), - projectList); + PhysicalPlan plan = project(filter(tableScan, filterExpr), projectList); assertEquals( new ExplainResponse( new ExplainResponseNode( "ProjectOperator", Map.of("fields", "[name, age]"), - singletonList(new ExplainResponseNode( - "FilterOperator", - Map.of("conditions", "and(=(balance, 10000), >(age, 30))"), - singletonList(tableScan.explainNode()))))), + singletonList( + new ExplainResponseNode( + "FilterOperator", + Map.of("conditions", "and(=(balance, 10000), >(age, 30))"), + singletonList(tableScan.explainNode()))))), explain.apply(plan)); } @Test void can_explain_aggregations() { List aggExprs = List.of(ref("balance", DOUBLE)); - List aggList = List.of( - named("avg(balance)", DSL.avg(aggExprs.toArray(new Expression[0])))); - List groupByList = List.of( - named("state", ref("state", STRING))); + List aggList = + List.of(named("avg(balance)", DSL.avg(aggExprs.toArray(new Expression[0])))); + List groupByList = List.of(named("state", ref("state", STRING))); PhysicalPlan plan = agg(new FakeTableScan(), aggList, groupByList); assertEquals( @@ -120,11 +113,7 @@ void can_explain_rare_top_n() { new ExplainResponse( new ExplainResponseNode( "RareTopNOperator", - Map.of( - "commandType", TOP, - "noOfResults", 10, - "fields", "[state]", - "groupBy", "[]"), + Map.of("commandType", TOP, "noOfResults", 10, "fields", "[state]", "groupBy", "[]"), singletonList(tableScan.explainNode()))), explain.apply(plan)); } @@ -132,22 +121,27 @@ void can_explain_rare_top_n() { @Test void can_explain_window() { List partitionByList = List.of(DSL.ref("state", STRING)); - List> sortList = List.of( - ImmutablePair.of(DEFAULT_ASC, ref("age", INTEGER))); + List> sortList = + List.of(ImmutablePair.of(DEFAULT_ASC, ref("age", INTEGER))); - PhysicalPlan plan = window(tableScan, named(DSL.rank()), - new WindowDefinition(partitionByList, sortList)); + PhysicalPlan plan = + window(tableScan, named(DSL.rank()), new WindowDefinition(partitionByList, sortList)); assertEquals( new ExplainResponse( new ExplainResponseNode( "WindowOperator", Map.of( - "function", "rank()", - "definition", Map.of( - "partitionBy", "[state]", - "sortList", Map.of( - "age", Map.of( + "function", + "rank()", + "definition", + Map.of( + "partitionBy", + "[state]", + "sortList", + Map.of( + "age", + Map.of( "sortOrder", "ASC", "nullOrder", "NULL_FIRST")))), singletonList(tableScan.explainNode()))), @@ -157,60 +151,61 @@ void can_explain_window() { @Test void can_explain_other_operators() { ReferenceExpression[] removeList = {ref("state", STRING)}; - Map renameMapping = Map.of( - ref("state", STRING), ref("s", STRING)); - Pair evalExprs = ImmutablePair.of( - ref("age", INTEGER), DSL.add(ref("age", INTEGER), literal(2))); + Map renameMapping = + Map.of(ref("state", STRING), ref("s", STRING)); + Pair evalExprs = + ImmutablePair.of(ref("age", INTEGER), DSL.add(ref("age", INTEGER), literal(2))); Expression[] dedupeList = {ref("age", INTEGER)}; - Pair sortList = ImmutablePair.of( - DEFAULT_ASC, ref("age", INTEGER)); + Pair sortList = ImmutablePair.of(DEFAULT_ASC, ref("age", INTEGER)); List values = List.of(literal("WA"), literal(30)); PhysicalPlan plan = remove( rename( - eval( - dedupe( - sort( - values(values), - sortList), - dedupeList), - evalExprs), - renameMapping), - removeList); + eval(dedupe(sort(values(values), sortList), dedupeList), evalExprs), renameMapping), + removeList); assertEquals( new ExplainResponse( new ExplainResponseNode( "RemoveOperator", Map.of("removeList", "[state]"), - singletonList(new ExplainResponseNode( - "RenameOperator", - Map.of("mapping", Map.of("state", "s")), - singletonList(new ExplainResponseNode( - "EvalOperator", - Map.of("expressions", Map.of("age", "+(age, 2)")), - singletonList(new ExplainResponseNode( - "DedupeOperator", - Map.of( - "dedupeList", "[age]", - "allowedDuplication", 1, - "keepEmpty", false, - "consecutive", false), - singletonList(new ExplainResponseNode( - "SortOperator", - Map.of( - "sortList", Map.of( - "age", Map.of( - "sortOrder", "ASC", - "nullOrder", "NULL_FIRST"))), - singletonList(new ExplainResponseNode( - "ValuesOperator", - Map.of("values", List.of(values)), - emptyList()))))))))))) - ), - explain.apply(plan) - ); + singletonList( + new ExplainResponseNode( + "RenameOperator", + Map.of("mapping", Map.of("state", "s")), + singletonList( + new ExplainResponseNode( + "EvalOperator", + Map.of("expressions", Map.of("age", "+(age, 2)")), + singletonList( + new ExplainResponseNode( + "DedupeOperator", + Map.of( + "dedupeList", + "[age]", + "allowedDuplication", + 1, + "keepEmpty", + false, + "consecutive", + false), + singletonList( + new ExplainResponseNode( + "SortOperator", + Map.of( + "sortList", + Map.of( + "age", + Map.of( + "sortOrder", "ASC", + "nullOrder", "NULL_FIRST"))), + singletonList( + new ExplainResponseNode( + "ValuesOperator", + Map.of("values", List.of(values)), + emptyList())))))))))))), + explain.apply(plan)); } @Test @@ -222,15 +217,13 @@ void can_explain_limit() { "LimitOperator", Map.of("limit", 10, "offset", 5), singletonList(tableScan.explainNode()))), - explain.apply(plan) - ); + explain.apply(plan)); } @Test void can_explain_nested() { Set nestedOperatorArgs = Set.of("message.info", "message"); - Map> groupedFieldsByPath = - Map.of("message", List.of("message.info")); + Map> groupedFieldsByPath = Map.of("message", List.of("message.info")); PhysicalPlan plan = nested(tableScan, nestedOperatorArgs, groupedFieldsByPath); assertEquals( @@ -239,8 +232,7 @@ void can_explain_nested() { "NestedOperator", Map.of("nested", Set.of("message.info", "message")), singletonList(tableScan.explainNode()))), - explain.apply(plan) - ); + explain.apply(plan)); } private static class FakeTableScan extends TableScanOperator { @@ -262,14 +254,11 @@ public String toString() { /** Used to ignore table scan which is duplicate but required for each operator test. */ public ExplainResponseNode explainNode() { return new ExplainResponseNode( - "FakeTableScan", - Map.of("request", "Fake DSL request"), - emptyList()); + "FakeTableScan", Map.of("request", "Fake DSL request"), emptyList()); } public String explain() { return "explain"; } } - } diff --git a/core/src/test/java/org/opensearch/sql/executor/QueryServiceTest.java b/core/src/test/java/org/opensearch/sql/executor/QueryServiceTest.java index 1510b304e6..f6b66b4e77 100644 --- a/core/src/test/java/org/opensearch/sql/executor/QueryServiceTest.java +++ b/core/src/test/java/org/opensearch/sql/executor/QueryServiceTest.java @@ -37,73 +37,52 @@ class QueryServiceTest { private QueryService queryService; - @Mock - private ExecutionEngine executionEngine; + @Mock private ExecutionEngine executionEngine; - @Mock - private Analyzer analyzer; + @Mock private Analyzer analyzer; - @Mock - private Planner planner; + @Mock private Planner planner; - @Mock - private UnresolvedPlan ast; + @Mock private UnresolvedPlan ast; - @Mock - private LogicalPlan logicalPlan; + @Mock private LogicalPlan logicalPlan; - @Mock - private PhysicalPlan plan; + @Mock private PhysicalPlan plan; - @Mock - private ExecutionEngine.Schema schema; + @Mock private ExecutionEngine.Schema schema; - @Mock - private PlanContext planContext; + @Mock private PlanContext planContext; - @Mock - private Split split; + @Mock private Split split; @Test public void executeWithoutContext() { - queryService() - .executeSuccess() - .handledByOnResponse(); + queryService().executeSuccess().handledByOnResponse(); } @Test public void executeWithContext() { - queryService() - .executeSuccess(split) - .handledByOnResponse(); + queryService().executeSuccess(split).handledByOnResponse(); } @Test public void testExplainShouldPass() { - queryService() - .explainSuccess() - .handledByExplainOnResponse(); + queryService().explainSuccess().handledByExplainOnResponse(); } @Test public void testExecuteWithExceptionShouldBeCaughtByHandler() { - queryService() - .executeFail() - .handledByOnFailure(); + queryService().executeFail().handledByOnFailure(); } @Test public void explainWithIllegalQueryShouldBeCaughtByHandler() { - queryService() - .explainFail() - .handledByExplainOnFailure(); + queryService().explainFail().handledByExplainOnFailure(); } @Test public void analyzeExceptionShouldBeCached() { - queryService() - .analyzeFail() - .handledByOnFailure(); + queryService().analyzeFail().handledByOnFailure(); } Helper queryService() { @@ -130,13 +109,14 @@ Helper executeSuccess() { Helper executeSuccess(Split split) { this.split = Optional.ofNullable(split); doAnswer( - invocation -> { - ResponseListener listener = invocation.getArgument(2); - listener.onResponse( - new ExecutionEngine.QueryResponse(schema, Collections.emptyList(), - Cursor.None)); - return null; - }) + invocation -> { + ResponseListener listener = + invocation.getArgument(2); + listener.onResponse( + new ExecutionEngine.QueryResponse( + schema, Collections.emptyList(), Cursor.None)); + return null; + }) .when(executionEngine) .execute(any(), any(), any()); lenient().when(planContext.getSplit()).thenReturn(this.split); @@ -145,9 +125,7 @@ Helper executeSuccess(Split split) { } Helper analyzeFail() { - doThrow(new IllegalStateException("analyze exception")) - .when(analyzer) - .analyze(any(), any()); + doThrow(new IllegalStateException("analyze exception")).when(analyzer).analyze(any(), any()); return this; } @@ -162,14 +140,14 @@ Helper executeFail() { Helper explainSuccess() { doAnswer( - invocation -> { - ResponseListener listener = - invocation.getArgument(1); - listener.onResponse( - new ExecutionEngine.ExplainResponse( - new ExecutionEngine.ExplainResponseNode("test"))); - return null; - }) + invocation -> { + ResponseListener listener = + invocation.getArgument(1); + listener.onResponse( + new ExecutionEngine.ExplainResponse( + new ExecutionEngine.ExplainResponseNode("test"))); + return null; + }) .when(executionEngine) .explain(any(), any()); @@ -184,36 +162,37 @@ Helper explainFail() { return this; } - void handledByOnResponse() { - ResponseListener responseListener = new ResponseListener<>() { - @Override - public void onResponse(ExecutionEngine.QueryResponse pplQueryResponse) { - assertNotNull(pplQueryResponse); - } - - @Override - public void onFailure(Exception e) { - fail(); - } - }; + ResponseListener responseListener = + new ResponseListener<>() { + @Override + public void onResponse(ExecutionEngine.QueryResponse pplQueryResponse) { + assertNotNull(pplQueryResponse); + } + + @Override + public void onFailure(Exception e) { + fail(); + } + }; split.ifPresentOrElse( split -> queryService.executePlan(logicalPlan, planContext, responseListener), () -> queryService.execute(ast, responseListener)); } void handledByOnFailure() { - ResponseListener responseListener = new ResponseListener<>() { - @Override - public void onResponse(ExecutionEngine.QueryResponse pplQueryResponse) { - fail(); - } - - @Override - public void onFailure(Exception e) { - assertTrue(e instanceof IllegalStateException); - } - }; + ResponseListener responseListener = + new ResponseListener<>() { + @Override + public void onResponse(ExecutionEngine.QueryResponse pplQueryResponse) { + fail(); + } + + @Override + public void onFailure(Exception e) { + assertTrue(e instanceof IllegalStateException); + } + }; split.ifPresentOrElse( split -> queryService.executePlan(logicalPlan, planContext, responseListener), () -> queryService.execute(ast, responseListener)); @@ -250,6 +229,5 @@ public void onFailure(Exception e) { } }); } - } } diff --git a/core/src/test/java/org/opensearch/sql/executor/execution/CommandPlanTest.java b/core/src/test/java/org/opensearch/sql/executor/execution/CommandPlanTest.java index aa300cb0da..aff5a0d867 100644 --- a/core/src/test/java/org/opensearch/sql/executor/execution/CommandPlanTest.java +++ b/core/src/test/java/org/opensearch/sql/executor/execution/CommandPlanTest.java @@ -47,8 +47,7 @@ public void execute_without_error() { public void execute_with_error() { QueryService qs = mock(QueryService.class, withSettings().defaultAnswer(CALLS_REAL_METHODS)); ResponseListener listener = mock(ResponseListener.class); - doThrow(new RuntimeException()) - .when(qs).executePlan(any(LogicalPlan.class), any(), any()); + doThrow(new RuntimeException()).when(qs).executePlan(any(LogicalPlan.class), any(), any()); new CommandPlan(QueryId.queryId(), mock(UnresolvedPlan.class), qs, listener).execute(); @@ -62,9 +61,12 @@ public void explain_not_supported() { ResponseListener listener = mock(ResponseListener.class); ResponseListener explainListener = mock(ResponseListener.class); - var exception = assertThrows(Throwable.class, () -> - new CommandPlan(QueryId.queryId(), mock(UnresolvedPlan.class), qs, listener) - .explain(explainListener)); + var exception = + assertThrows( + Throwable.class, + () -> + new CommandPlan(QueryId.queryId(), mock(UnresolvedPlan.class), qs, listener) + .explain(explainListener)); assertEquals("CommandPlan does not support explain", exception.getMessage()); verify(listener, never()).onResponse(any()); diff --git a/core/src/test/java/org/opensearch/sql/executor/execution/ExplainPlanTest.java b/core/src/test/java/org/opensearch/sql/executor/execution/ExplainPlanTest.java index 54b4f24db0..cdb7f9dcb8 100644 --- a/core/src/test/java/org/opensearch/sql/executor/execution/ExplainPlanTest.java +++ b/core/src/test/java/org/opensearch/sql/executor/execution/ExplainPlanTest.java @@ -25,14 +25,11 @@ @ExtendWith(MockitoExtension.class) public class ExplainPlanTest { - @Mock - private QueryId queryId; + @Mock private QueryId queryId; - @Mock - private QueryPlan queryPlan; + @Mock private QueryPlan queryPlan; - @Mock - private ResponseListener explainListener; + @Mock private ResponseListener explainListener; @Test public void execute() { diff --git a/core/src/test/java/org/opensearch/sql/executor/execution/IntervalTriggerExecutionTest.java b/core/src/test/java/org/opensearch/sql/executor/execution/IntervalTriggerExecutionTest.java index e0638ba88f..9eb99d37e3 100644 --- a/core/src/test/java/org/opensearch/sql/executor/execution/IntervalTriggerExecutionTest.java +++ b/core/src/test/java/org/opensearch/sql/executor/execution/IntervalTriggerExecutionTest.java @@ -18,16 +18,12 @@ public class IntervalTriggerExecutionTest { @Test void executeTaskWithInterval() { - triggerTask(2) - .taskRun(1) - .aroundInterval(); + triggerTask(2).taskRun(1).aroundInterval(); } @Test void continueExecuteIfTaskRunningLongerThanInterval() { - triggerTask(1) - .taskRun(2) - .aroundTaskRuntime(); + triggerTask(1).taskRun(2).aroundTaskRuntime(); } Helper triggerTask(long interval) { diff --git a/core/src/test/java/org/opensearch/sql/executor/execution/QueryPlanFactoryTest.java b/core/src/test/java/org/opensearch/sql/executor/execution/QueryPlanFactoryTest.java index 2d346e4c2a..5aed9acc63 100644 --- a/core/src/test/java/org/opensearch/sql/executor/execution/QueryPlanFactoryTest.java +++ b/core/src/test/java/org/opensearch/sql/executor/execution/QueryPlanFactoryTest.java @@ -41,20 +41,15 @@ @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) class QueryPlanFactoryTest { - @Mock - private UnresolvedPlan plan; + @Mock private UnresolvedPlan plan; - @Mock - private QueryService queryService; + @Mock private QueryService queryService; - @Mock - private ResponseListener queryListener; + @Mock private ResponseListener queryListener; - @Mock - private ResponseListener explainListener; + @Mock private ResponseListener explainListener; - @Mock - private ExecutionEngine.QueryResponse queryResponse; + @Mock private ExecutionEngine.QueryResponse queryResponse; private QueryPlanFactory factory; @@ -81,14 +76,11 @@ public void create_from_explain_should_success() { @Test public void create_from_cursor_should_success() { - AbstractPlan queryExecution = factory.create("", false, - queryListener, explainListener); - AbstractPlan explainExecution = factory.create("", true, - queryListener, explainListener); + AbstractPlan queryExecution = factory.create("", false, queryListener, explainListener); + AbstractPlan explainExecution = factory.create("", true, queryListener, explainListener); assertAll( () -> assertTrue(queryExecution instanceof QueryPlan), - () -> assertTrue(explainExecution instanceof ExplainPlan) - ); + () -> assertTrue(explainExecution instanceof ExplainPlan)); } @Test @@ -96,8 +88,9 @@ public void create_from_query_without_query_listener_should_throw_exception() { Statement query = new Query(plan, 0); IllegalArgumentException exception = - assertThrows(IllegalArgumentException.class, () -> factory.create( - query, Optional.empty(), Optional.empty())); + assertThrows( + IllegalArgumentException.class, + () -> factory.create(query, Optional.empty(), Optional.empty())); assertEquals("[BUG] query listener must be not null", exception.getMessage()); } @@ -106,8 +99,9 @@ public void create_from_explain_without_explain_listener_should_throw_exception( Statement query = new Explain(new Query(plan, 0)); IllegalArgumentException exception = - assertThrows(IllegalArgumentException.class, () -> factory.create( - query, Optional.empty(), Optional.empty())); + assertThrows( + IllegalArgumentException.class, + () -> factory.create(query, Optional.empty(), Optional.empty())); assertEquals("[BUG] explain listener must be not null", exception.getMessage()); } @@ -143,9 +137,9 @@ public void create_query_with_fetch_size_which_cannot_be_paged() { when(plan.accept(any(CanPaginateVisitor.class), any())).thenReturn(Boolean.FALSE); factory = new QueryPlanFactory(queryService); Statement query = new Query(plan, 10); - assertThrows(UnsupportedCursorRequestException.class, - () -> factory.create(query, - Optional.of(queryListener), Optional.empty())); + assertThrows( + UnsupportedCursorRequestException.class, + () -> factory.create(query, Optional.of(queryListener), Optional.empty())); } @Test diff --git a/core/src/test/java/org/opensearch/sql/executor/execution/QueryPlanTest.java b/core/src/test/java/org/opensearch/sql/executor/execution/QueryPlanTest.java index a0a98e2be7..57ff5c70e9 100644 --- a/core/src/test/java/org/opensearch/sql/executor/execution/QueryPlanTest.java +++ b/core/src/test/java/org/opensearch/sql/executor/execution/QueryPlanTest.java @@ -34,20 +34,15 @@ @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) class QueryPlanTest { - @Mock - private QueryId queryId; + @Mock private QueryId queryId; - @Mock - private UnresolvedPlan plan; + @Mock private UnresolvedPlan plan; - @Mock - private QueryService queryService; + @Mock private QueryService queryService; - @Mock - private ResponseListener explainListener; + @Mock private ResponseListener explainListener; - @Mock - private ResponseListener queryListener; + @Mock private ResponseListener queryListener; @Test public void execute_no_page_size() { @@ -67,53 +62,62 @@ public void explain_no_page_size() { @Test public void can_execute_paginated_plan() { - var listener = new ResponseListener() { - @Override - public void onResponse(ExecutionEngine.QueryResponse response) { - assertNotNull(response); - } - - @Override - public void onFailure(Exception e) { - fail(); - } - }; - var plan = new QueryPlan(QueryId.queryId(), mock(UnresolvedPlan.class), 10, - queryService, listener); + var listener = + new ResponseListener() { + @Override + public void onResponse(ExecutionEngine.QueryResponse response) { + assertNotNull(response); + } + + @Override + public void onFailure(Exception e) { + fail(); + } + }; + var plan = + new QueryPlan(QueryId.queryId(), mock(UnresolvedPlan.class), 10, queryService, listener); plan.execute(); } @Test // Same as previous test, but with incomplete QueryService public void can_handle_error_while_executing_plan() { - var listener = new ResponseListener() { - @Override - public void onResponse(ExecutionEngine.QueryResponse response) { - fail(); - } - - @Override - public void onFailure(Exception e) { - assertNotNull(e); - } - }; - var plan = new QueryPlan(QueryId.queryId(), mock(UnresolvedPlan.class), 10, - new QueryService(null, new DefaultExecutionEngine(), null), listener); + var listener = + new ResponseListener() { + @Override + public void onResponse(ExecutionEngine.QueryResponse response) { + fail(); + } + + @Override + public void onFailure(Exception e) { + assertNotNull(e); + } + }; + var plan = + new QueryPlan( + QueryId.queryId(), + mock(UnresolvedPlan.class), + 10, + new QueryService(null, new DefaultExecutionEngine(), null), + listener); plan.execute(); } @Test public void explain_is_not_supported_for_pagination() { - new QueryPlan(null, null, 0, null, null).explain(new ResponseListener<>() { - @Override - public void onResponse(ExecutionEngine.ExplainResponse response) { - fail(); - } - - @Override - public void onFailure(Exception e) { - assertTrue(e instanceof NotImplementedException); - } - }); + new QueryPlan(null, null, 0, null, null) + .explain( + new ResponseListener<>() { + @Override + public void onResponse(ExecutionEngine.ExplainResponse response) { + fail(); + } + + @Override + public void onFailure(Exception e) { + assertTrue(e instanceof NotImplementedException); + } + }); } } diff --git a/core/src/test/java/org/opensearch/sql/executor/execution/StreamingQueryPlanTest.java b/core/src/test/java/org/opensearch/sql/executor/execution/StreamingQueryPlanTest.java index 7357e99d18..2e8666aea4 100644 --- a/core/src/test/java/org/opensearch/sql/executor/execution/StreamingQueryPlanTest.java +++ b/core/src/test/java/org/opensearch/sql/executor/execution/StreamingQueryPlanTest.java @@ -49,9 +49,7 @@ class StreamingQueryPlanTest { @Test void executionSuccess() throws InterruptedException { - streamingQuery() - .streamingSource() - .shouldSuccess(); + streamingQuery().streamingSource().shouldSuccess(); } @Test @@ -70,9 +68,7 @@ void failIfNoStreamingSource() throws InterruptedException { @Test void taskExecutionShouldNotCallListener() throws InterruptedException { - streamingQuery() - .streamingSource() - .taskExecutionShouldNotCallListener(); + streamingQuery().streamingSource().taskExecutionShouldNotCallListener(); } Helper streamingQuery() { diff --git a/core/src/test/java/org/opensearch/sql/executor/pagination/CanPaginateVisitorTest.java b/core/src/test/java/org/opensearch/sql/executor/pagination/CanPaginateVisitorTest.java index 003967d6aa..5f2ba86c2f 100644 --- a/core/src/test/java/org/opensearch/sql/executor/pagination/CanPaginateVisitorTest.java +++ b/core/src/test/java/org/opensearch/sql/executor/pagination/CanPaginateVisitorTest.java @@ -121,8 +121,7 @@ public void allow_query_with_select_fields_and_from() { @Test // select x public void allow_query_without_from() { - var plan = project(values(List.of(intLiteral(1))), - alias("1", intLiteral(1))); + var plan = project(values(List.of(intLiteral(1))), alias("1", intLiteral(1))); assertTrue(plan.accept(visitor, null)); } @@ -130,106 +129,124 @@ public void allow_query_without_from() { public void visitField() { // test combinations of acceptable and not acceptable args for coverage assertAll( - () -> assertFalse(project(relation("dummy"), - field(map("1", "2"), argument("name", intLiteral(0)))) - .accept(visitor, null)), - () -> assertFalse(project(relation("dummy"), - field("field", new Argument("", new Literal(1, DataType.INTEGER) { - @Override - public List getChild() { - return List.of(map("1", "2")); - } - }))) - .accept(visitor, null)) - ); + () -> + assertFalse( + project(relation("dummy"), field(map("1", "2"), argument("name", intLiteral(0)))) + .accept(visitor, null)), + () -> + assertFalse( + project( + relation("dummy"), + field( + "field", + new Argument( + "", + new Literal(1, DataType.INTEGER) { + @Override + public List getChild() { + return List.of(map("1", "2")); + } + }))) + .accept(visitor, null))); } @Test public void visitAlias() { // test combinations of acceptable and not acceptable args for coverage assertAll( - () -> assertFalse(project(relation("dummy"), - alias("pew", map("1", "2"), "pew")) - .accept(visitor, null)), - () -> assertFalse(project(relation("dummy"), new Alias("pew", field("pew")) { - @Override - public List getChild() { - return List.of(map("1", "2")); - } - }) - .accept(visitor, null)) - ); + () -> + assertFalse( + project(relation("dummy"), alias("pew", map("1", "2"), "pew")) + .accept(visitor, null)), + () -> + assertFalse( + project( + relation("dummy"), + new Alias("pew", field("pew")) { + @Override + public List getChild() { + return List.of(map("1", "2")); + } + }) + .accept(visitor, null))); } @Test // select a = b public void visitEqualTo() { - var plan = project(values(List.of(intLiteral(1))), - alias("1", equalTo(intLiteral(1), intLiteral(1)))); + var plan = + project(values(List.of(intLiteral(1))), alias("1", equalTo(intLiteral(1), intLiteral(1)))); assertTrue(plan.accept(visitor, null)); } @Test // select interval public void visitInterval() { - var plan = project(values(List.of(intLiteral(1))), - alias("1", intervalLiteral(intLiteral(1), DataType.INTEGER, "days"))); + var plan = + project( + values(List.of(intLiteral(1))), + alias("1", intervalLiteral(intLiteral(1), DataType.INTEGER, "days"))); assertTrue(plan.accept(visitor, null)); } @Test // select a != b public void visitCompare() { - var plan = project(values(List.of(intLiteral(1))), - alias("1", compare("!=", intLiteral(1), intLiteral(1)))); + var plan = + project( + values(List.of(intLiteral(1))), + alias("1", compare("!=", intLiteral(1), intLiteral(1)))); assertTrue(plan.accept(visitor, null)); } @Test // select NOT a public void visitNot() { - var plan = project(values(List.of(intLiteral(1))), - alias("1", not(booleanLiteral(true)))); + var plan = project(values(List.of(intLiteral(1))), alias("1", not(booleanLiteral(true)))); assertTrue(plan.accept(visitor, null)); } @Test // select a OR b public void visitOr() { - var plan = project(values(List.of(intLiteral(1))), - alias("1", or(booleanLiteral(true), booleanLiteral(false)))); + var plan = + project( + values(List.of(intLiteral(1))), + alias("1", or(booleanLiteral(true), booleanLiteral(false)))); assertTrue(plan.accept(visitor, null)); } @Test // select a AND b public void visitAnd() { - var plan = project(values(List.of(intLiteral(1))), - alias("1", and(booleanLiteral(true), booleanLiteral(false)))); + var plan = + project( + values(List.of(intLiteral(1))), + alias("1", and(booleanLiteral(true), booleanLiteral(false)))); assertTrue(plan.accept(visitor, null)); } @Test // select a XOR b public void visitXor() { - var plan = project(values(List.of(intLiteral(1))), - alias("1", xor(booleanLiteral(true), booleanLiteral(false)))); + var plan = + project( + values(List.of(intLiteral(1))), + alias("1", xor(booleanLiteral(true), booleanLiteral(false)))); assertTrue(plan.accept(visitor, null)); } @Test // select f() public void visitFunction() { - var plan = project(values(List.of(intLiteral(1))), - function("func")); + var plan = project(values(List.of(intLiteral(1))), function("func")); assertTrue(plan.accept(visitor, null)); } @Test // select nested() ... public void visitNested() { - var plan = project(values(List.of(intLiteral(1))), - function("nested")); + var plan = project(values(List.of(intLiteral(1))), function("nested")); assertFalse(plan.accept(visitor, null)); } @@ -238,30 +255,37 @@ public void visitNested() { public void visitIn() { // test combinations of acceptable and not acceptable args for coverage assertAll( - () -> assertTrue(project(values(List.of(intLiteral(1))), alias("1", in(field("a")))) - .accept(visitor, null)), - () -> assertFalse(project(values(List.of(intLiteral(1))), - alias("1", in(field("a"), map("1", "2")))) - .accept(visitor, null)), - () -> assertFalse(project(values(List.of(intLiteral(1))), - alias("1", in(map("1", "2"), field("a")))) - .accept(visitor, null)) - ); + () -> + assertTrue( + project(values(List.of(intLiteral(1))), alias("1", in(field("a")))) + .accept(visitor, null)), + () -> + assertFalse( + project(values(List.of(intLiteral(1))), alias("1", in(field("a"), map("1", "2")))) + .accept(visitor, null)), + () -> + assertFalse( + project(values(List.of(intLiteral(1))), alias("1", in(map("1", "2"), field("a")))) + .accept(visitor, null))); } @Test // select a BETWEEN 1 AND 2 public void visitBetween() { - var plan = project(values(List.of(intLiteral(1))), - alias("1", between(field("a"), intLiteral(1), intLiteral(2)))); + var plan = + project( + values(List.of(intLiteral(1))), + alias("1", between(field("a"), intLiteral(1), intLiteral(2)))); assertTrue(plan.accept(visitor, null)); } @Test // select a CASE 1 WHEN 2 public void visitCase() { - var plan = project(values(List.of(intLiteral(1))), - alias("1", caseWhen(intLiteral(1), when(intLiteral(3), intLiteral(4))))); + var plan = + project( + values(List.of(intLiteral(1))), + alias("1", caseWhen(intLiteral(1), when(intLiteral(3), intLiteral(4))))); assertTrue(plan.accept(visitor, null)); } @@ -270,21 +294,33 @@ public void visitCase() { public void visitCast() { // test combinations of acceptable and not acceptable args for coverage assertAll( - () -> assertTrue(project(values(List.of(intLiteral(1))), - alias("1", cast(intLiteral(2), stringLiteral("int")))) - .accept(visitor, null)), - () -> assertFalse(project(values(List.of(intLiteral(1))), - alias("1", cast(intLiteral(2), new Literal(1, DataType.INTEGER) { - @Override - public List getChild() { - return List.of(map("1", "2")); - } - }))) - .accept(visitor, null)), - () -> assertFalse(project(values(List.of(intLiteral(1))), - alias("1", cast(map("1", "2"), stringLiteral("int")))) - .accept(visitor, null)) - ); + () -> + assertTrue( + project( + values(List.of(intLiteral(1))), + alias("1", cast(intLiteral(2), stringLiteral("int")))) + .accept(visitor, null)), + () -> + assertFalse( + project( + values(List.of(intLiteral(1))), + alias( + "1", + cast( + intLiteral(2), + new Literal(1, DataType.INTEGER) { + @Override + public List getChild() { + return List.of(map("1", "2")); + } + }))) + .accept(visitor, null)), + () -> + assertFalse( + project( + values(List.of(intLiteral(1))), + alias("1", cast(map("1", "2"), stringLiteral("int")))) + .accept(visitor, null))); } @Test @@ -305,20 +341,22 @@ public void reject_query_with_eval() { // simple_query_string(["Tags" ^ 1.5, "Title", "Body" 4.2], "taste") // and Tags like "% % %" and Title like "%"; public void accept_query_with_highlight_and_relevance_func() { - var plan = project( - filter( - relation("beer.stackexchange"), - and( + var plan = + project( + filter( + relation("beer.stackexchange"), and( - function("like", qualifiedName("Tags"), stringLiteral("% % %")), - function("like", qualifiedName("Title"), stringLiteral("%"))), - function("simple_query_string", - unresolvedArg("fields", - new RelevanceFieldList(Map.of("Title", 1.0F, "Body", 4.2F, "Tags", 1.5F))), - unresolvedArg("query", - stringLiteral("taste"))))), - alias("highlight(\"Body\")", - highlight(stringLiteral("Body"), Map.of()))); + and( + function("like", qualifiedName("Tags"), stringLiteral("% % %")), + function("like", qualifiedName("Title"), stringLiteral("%"))), + function( + "simple_query_string", + unresolvedArg( + "fields", + new RelevanceFieldList( + Map.of("Title", 1.0F, "Body", 4.2F, "Tags", 1.5F))), + unresolvedArg("query", stringLiteral("taste"))))), + alias("highlight(\"Body\")", highlight(stringLiteral("Body"), Map.of()))); assertTrue(plan.accept(visitor, null)); } @@ -339,12 +377,13 @@ public void reject_query_with_offset() { // test added for coverage only @Test public void visitLimit() { - var visitor = new CanPaginateVisitor() { - @Override - public Boolean visitRelation(Relation node, Object context) { - return Boolean.FALSE; - } - }; + var visitor = + new CanPaginateVisitor() { + @Override + public Boolean visitRelation(Relation node, Object context) { + return Boolean.FALSE; + } + }; var plan = project(limit(relation("dummy"), 0, 0), allFields()); assertFalse(plan.accept(visitor, null)); } @@ -352,8 +391,7 @@ public Boolean visitRelation(Relation node, Object context) { @Test // select * from y where z public void allow_query_with_where() { - var plan = project(filter(relation("dummy"), - booleanLiteral(true)), allFields()); + var plan = project(filter(relation("dummy"), booleanLiteral(true)), allFields()); assertTrue(plan.accept(visitor, null)); } @@ -367,28 +405,29 @@ public void allow_query_with_order_by_with_column_references_only() { @Test // select * from y order by func(z) public void reject_query_with_order_by_with_an_expression() { - var plan = project(sort(relation("dummy"), field(function("func"))), - allFields()); + var plan = project(sort(relation("dummy"), field(function("func"))), allFields()); assertFalse(plan.accept(visitor, null)); } // test added for coverage only @Test public void visitSort() { - CanPaginateVisitor visitor = new CanPaginateVisitor() { - @Override - public Boolean visitRelation(Relation node, Object context) { - return Boolean.FALSE; - } - }; + CanPaginateVisitor visitor = + new CanPaginateVisitor() { + @Override + public Boolean visitRelation(Relation node, Object context) { + return Boolean.FALSE; + } + }; var plan = project(sort(relation("dummy"), field("1")), allFields()); assertFalse(plan.accept(visitor, null)); - visitor = new CanPaginateVisitor() { - @Override - public Boolean visitField(Field node, Object context) { - return Boolean.FALSE; - } - }; + visitor = + new CanPaginateVisitor() { + @Override + public Boolean visitField(Field node, Object context) { + return Boolean.FALSE; + } + }; plan = project(sort(relation("dummy"), field("1")), allFields()); assertFalse(plan.accept(visitor, null)); } @@ -396,31 +435,38 @@ public Boolean visitField(Field node, Object context) { @Test // select * from y group by z public void reject_query_with_group_by() { - var plan = project(agg( - relation("dummy"), List.of(), List.of(), List.of(field("1")), List.of()), - allFields()); + var plan = + project( + agg(relation("dummy"), List.of(), List.of(), List.of(field("1")), List.of()), + allFields()); assertFalse(plan.accept(visitor, null)); } @Test // select agg(x) from y public void reject_query_with_aggregation_function() { - var plan = project(agg( - relation("dummy"), - List.of(alias("agg", aggregate("func", field("pewpew")))), - List.of(), List.of(), List.of()), - allFields()); + var plan = + project( + agg( + relation("dummy"), + List.of(alias("agg", aggregate("func", field("pewpew")))), + List.of(), + List.of(), + List.of()), + allFields()); assertFalse(plan.accept(visitor, null)); } @Test // select window(x) from y public void reject_query_with_window_function() { - var plan = project(relation("dummy"), - alias("pewpew", - window( - aggregate("func", field("pewpew")), - List.of(qualifiedName("1")), List.of()))); + var plan = + project( + relation("dummy"), + alias( + "pewpew", + window( + aggregate("func", field("pewpew")), List.of(qualifiedName("1")), List.of()))); assertFalse(plan.accept(visitor, null)); } @@ -449,12 +495,13 @@ public void reject_project_when_relation_has_child() { // test combinations of acceptable and not acceptable args for coverage public void visitFilter() { assertAll( - () -> assertTrue(project(filter(relation("dummy"), booleanLiteral(true))) - .accept(visitor, null)), - () -> assertFalse(project(filter(relation("dummy"), map("1", "2"))) - .accept(visitor, null)), - () -> assertFalse(project(filter(tableFunction(List.of("1", "2")), booleanLiteral(true))) - .accept(visitor, null)) - ); + () -> + assertTrue( + project(filter(relation("dummy"), booleanLiteral(true))).accept(visitor, null)), + () -> assertFalse(project(filter(relation("dummy"), map("1", "2"))).accept(visitor, null)), + () -> + assertFalse( + project(filter(tableFunction(List.of("1", "2")), booleanLiteral(true))) + .accept(visitor, null))); } } diff --git a/core/src/test/java/org/opensearch/sql/executor/pagination/PlanSerializerTest.java b/core/src/test/java/org/opensearch/sql/executor/pagination/PlanSerializerTest.java index 8211a3bc12..495a7db80c 100644 --- a/core/src/test/java/org/opensearch/sql/executor/pagination/PlanSerializerTest.java +++ b/core/src/test/java/org/opensearch/sql/executor/pagination/PlanSerializerTest.java @@ -44,9 +44,14 @@ void setUp() { } @ParameterizedTest - @ValueSource(strings = {"pewpew", "asdkfhashdfjkgakgfwuigfaijkb", "ajdhfgajklghadfjkhgjkadhgad" - + "kadfhgadhjgfjklahdgqheygvskjfbvgsdklgfuirehiluANUIfgauighbahfuasdlhfnhaughsdlfhaughaggf" - + "and_some_other_funny_stuff_which_could_be_generated_while_sleeping_on_the_keyboard"}) + @ValueSource( + strings = { + "pewpew", + "asdkfhashdfjkgakgfwuigfaijkb", + "ajdhfgajklghadfjkhgjkadhgad" + + "kadfhgadhjgfjklahdgqheygvskjfbvgsdklgfuirehiluANUIfgauighbahfuasdlhfnhaughsdlfhaughaggf" + + "and_some_other_funny_stuff_which_could_be_generated_while_sleeping_on_the_keyboard" + }) void serialize_deserialize_str(String input) { var compressed = serialize(input); assertEquals(input, deserialize(compressed)); @@ -98,8 +103,7 @@ void deserialize_throws() { // from gzip - damaged header () -> assertThrows(Throwable.class, () -> deserialize("00")), // from HashCode::fromString - () -> assertThrows(Throwable.class, () -> deserialize("000")) - ); + () -> assertThrows(Throwable.class, () -> deserialize("000"))); } @Test @@ -109,8 +113,7 @@ void convertToCursor_returns_no_cursor_if_cant_serialize() { plan.setThrowNoCursorOnWrite(true); assertAll( () -> assertThrows(NoCursorException.class, () -> serialize(plan)), - () -> assertEquals(Cursor.None, planCache.convertToCursor(plan)) - ); + () -> assertEquals(Cursor.None, planCache.convertToCursor(plan))); } @Test @@ -122,14 +125,14 @@ void convertToCursor_returns_no_cursor_if_plan_is_not_paginate() { @Test void convertToPlan_throws_cursor_has_no_prefix() { - assertThrows(UnsupportedOperationException.class, () -> - planCache.convertToPlan("abc")); + assertThrows(UnsupportedOperationException.class, () -> planCache.convertToPlan("abc")); } @Test void convertToPlan_throws_if_failed_to_deserialize() { - assertThrows(UnsupportedOperationException.class, () -> - planCache.convertToPlan("n:" + serialize(mock(Serializable.class)))); + assertThrows( + UnsupportedOperationException.class, + () -> planCache.convertToPlan("n:" + serialize(mock(Serializable.class)))); } @Test @@ -144,8 +147,8 @@ void serialize_and_deserialize() { @Test void convertToCursor_and_convertToPlan() { var plan = new TestOperator(100500); - var roundTripPlan = (SerializablePlan) - planCache.convertToPlan(planCache.convertToCursor(plan).toString()); + var roundTripPlan = + (SerializablePlan) planCache.convertToPlan(planCache.convertToCursor(plan).toString()); assertEquals(plan, roundTripPlan); assertNotSame(plan, roundTripPlan); } @@ -158,8 +161,8 @@ void resolveObject() { objectOutput.writeObject("Hello, world!"); objectOutput.flush(); - var cds = planCache.getCursorDeserializationStream( - new ByteArrayInputStream(output.toByteArray())); + var cds = + planCache.getCursorDeserializationStream(new ByteArrayInputStream(output.toByteArray())); assertEquals(storageEngine, cds.resolveObject("engine")); var object = new Object(); assertSame(object, cds.resolveObject(object)); diff --git a/core/src/test/java/org/opensearch/sql/executor/streaming/DefaultMetadataLogTest.java b/core/src/test/java/org/opensearch/sql/executor/streaming/DefaultMetadataLogTest.java index 4d8c4f3e93..17ea253e2a 100644 --- a/core/src/test/java/org/opensearch/sql/executor/streaming/DefaultMetadataLogTest.java +++ b/core/src/test/java/org/opensearch/sql/executor/streaming/DefaultMetadataLogTest.java @@ -8,7 +8,6 @@ package org.opensearch.sql.executor.streaming; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; diff --git a/core/src/test/java/org/opensearch/sql/executor/streaming/MicroBatchStreamingExecutionTest.java b/core/src/test/java/org/opensearch/sql/executor/streaming/MicroBatchStreamingExecutionTest.java index 589b093c2f..bd0c8ed3e1 100644 --- a/core/src/test/java/org/opensearch/sql/executor/streaming/MicroBatchStreamingExecutionTest.java +++ b/core/src/test/java/org/opensearch/sql/executor/streaming/MicroBatchStreamingExecutionTest.java @@ -45,19 +45,12 @@ void executedSuccess() { @Test void executedFailed() { - streamingQuery() - .addData() - .executeFailed() - .latestOffsetLogShouldBe(0L) - .noCommittedLog(); + streamingQuery().addData().executeFailed().latestOffsetLogShouldBe(0L).noCommittedLog(); } @Test void noDataInSource() { - streamingQuery() - .neverProcess() - .noOffsetLog() - .noCommittedLog(); + streamingQuery().neverProcess().noOffsetLog().noCommittedLog(); } @Test @@ -170,8 +163,7 @@ Helper executeSuccess(Long... offsets) { ResponseListener listener = invocation.getArgument(2); listener.onResponse( - new ExecutionEngine.QueryResponse(null, Collections.emptyList(), - Cursor.None)); + new ExecutionEngine.QueryResponse(null, Collections.emptyList(), Cursor.None)); PlanContext planContext = invocation.getArgument(1); assertTrue(planContext.getSplit().isPresent()); @@ -257,8 +249,8 @@ public Optional getLatestOffset() { public Batch getBatch(Optional start, Offset end) { return new Batch( new TestOffsetSplit( - start.map(v -> v.getOffset() + 1).orElse(0L), Long.min(offset.get(), - end.getOffset()))); + start.map(v -> v.getOffset() + 1).orElse(0L), + Long.min(offset.get(), end.getOffset()))); } } diff --git a/core/src/test/java/org/opensearch/sql/expression/ExpressionNodeVisitorTest.java b/core/src/test/java/org/opensearch/sql/expression/ExpressionNodeVisitorTest.java index 47fe9dad0f..2f3e855430 100644 --- a/core/src/test/java/org/opensearch/sql/expression/ExpressionNodeVisitorTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/ExpressionNodeVisitorTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -31,70 +30,69 @@ class ExpressionNodeVisitorTest { @Test void should_return_null_by_default() { - ExpressionNodeVisitor visitor = new ExpressionNodeVisitor(){}; + ExpressionNodeVisitor visitor = new ExpressionNodeVisitor() {}; assertNull(new HighlightExpression(DSL.literal("Title")).accept(visitor, null)); assertNull(literal(10).accept(visitor, null)); assertNull(ref("name", STRING).accept(visitor, null)); assertNull(named("bool", literal(true)).accept(visitor, null)); assertNull(DSL.abs(literal(-10)).accept(visitor, null)); assertNull(DSL.sum(literal(10)).accept(visitor, null)); - assertNull(named("avg", new AvgAggregator(Collections.singletonList(ref("age", INTEGER)), - INTEGER)).accept(visitor, null)); + assertNull( + named("avg", new AvgAggregator(Collections.singletonList(ref("age", INTEGER)), INTEGER)) + .accept(visitor, null)); assertNull(new CaseClause(ImmutableList.of(), null).accept(visitor, null)); assertNull(new WhenClause(literal("test"), literal(10)).accept(visitor, null)); assertNull(DSL.namedArgument("field", literal("message")).accept(visitor, null)); assertNull(DSL.span(ref("age", INTEGER), literal(1), "").accept(visitor, null)); - assertNull(DSL.regex(ref("name", STRING), DSL.literal("(?\\d+)"), DSL.literal("group")) - .accept(visitor, null)); + assertNull( + DSL.regex(ref("name", STRING), DSL.literal("(?\\d+)"), DSL.literal("group")) + .accept(visitor, null)); } @Test void can_visit_all_types_of_expression_node() { Expression expr = DSL.regex( - DSL.castString( - DSL.sum( - DSL.add( - ref("balance", INTEGER), - literal(10)) - )), + DSL.castString(DSL.sum(DSL.add(ref("balance", INTEGER), literal(10)))), DSL.literal("(?\\d+)"), DSL.literal("group")); - Expression actual = expr.accept(new ExpressionNodeVisitor() { - @Override - public Expression visitLiteral(LiteralExpression node, Object context) { - return node; - } + Expression actual = + expr.accept( + new ExpressionNodeVisitor() { + @Override + public Expression visitLiteral(LiteralExpression node, Object context) { + return node; + } - @Override - public Expression visitReference(ReferenceExpression node, Object context) { - return node; - } + @Override + public Expression visitReference(ReferenceExpression node, Object context) { + return node; + } - @Override - public Expression visitParse(ParseExpression node, Object context) { - return node; - } + @Override + public Expression visitParse(ParseExpression node, Object context) { + return node; + } - @Override - public Expression visitFunction(FunctionExpression node, Object context) { - return DSL.add(visitArguments(node.getArguments(), context)); - } + @Override + public Expression visitFunction(FunctionExpression node, Object context) { + return DSL.add(visitArguments(node.getArguments(), context)); + } - @Override - public Expression visitAggregator(Aggregator node, Object context) { - return DSL.sum(visitArguments(node.getArguments(), context)); - } + @Override + public Expression visitAggregator(Aggregator node, Object context) { + return DSL.sum(visitArguments(node.getArguments(), context)); + } - private Expression[] visitArguments(List arguments, Object context) { - return arguments.stream() - .map(arg -> arg.accept(this, context)) - .toArray(Expression[]::new); - } - }, null); + private Expression[] visitArguments(List arguments, Object context) { + return arguments.stream() + .map(arg -> arg.accept(this, context)) + .toArray(Expression[]::new); + } + }, + null); assertEquals(expr, actual); } - } diff --git a/core/src/test/java/org/opensearch/sql/expression/ExpressionTestBase.java b/core/src/test/java/org/opensearch/sql/expression/ExpressionTestBase.java index 8ce7a52394..fd886cdda3 100644 --- a/core/src/test/java/org/opensearch/sql/expression/ExpressionTestBase.java +++ b/core/src/test/java/org/opensearch/sql/expression/ExpressionTestBase.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression; import static org.opensearch.sql.config.TestConfig.BOOL_TYPE_MISSING_VALUE_FIELD; diff --git a/core/src/test/java/org/opensearch/sql/expression/HighlightExpressionTest.java b/core/src/test/java/org/opensearch/sql/expression/HighlightExpressionTest.java index 41f3bad030..bc6b3628b0 100644 --- a/core/src/test/java/org/opensearch/sql/expression/HighlightExpressionTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/HighlightExpressionTest.java @@ -18,13 +18,13 @@ import org.opensearch.sql.data.model.ExprValueUtils; import org.opensearch.sql.expression.env.Environment; - public class HighlightExpressionTest extends ExpressionTestBase { @Test public void single_highlight_test() { - Environment hlTuple = ExprValueUtils.tupleValue( - ImmutableMap.of("_highlight.Title", "result value")).bindingTuples(); + Environment hlTuple = + ExprValueUtils.tupleValue(ImmutableMap.of("_highlight.Title", "result value")) + .bindingTuples(); HighlightExpression expr = new HighlightExpression(DSL.literal("Title")); ExprValue resultVal = expr.valueOf(hlTuple); @@ -34,8 +34,9 @@ public void single_highlight_test() { @Test public void missing_highlight_test() { - Environment hlTuple = ExprValueUtils.tupleValue( - ImmutableMap.of("_highlight.Title", "result value")).bindingTuples(); + Environment hlTuple = + ExprValueUtils.tupleValue(ImmutableMap.of("_highlight.Title", "result value")) + .bindingTuples(); HighlightExpression expr = new HighlightExpression(DSL.literal("invalid")); ExprValue resultVal = expr.valueOf(hlTuple); @@ -52,8 +53,8 @@ public void missing_highlight_wildcard_test() { builder.put("_highlight", ExprTupleValue.fromExprValueMap(hlBuilder.build())); HighlightExpression hlExpr = new HighlightExpression(DSL.literal("invalid*")); - ExprValue resultVal = hlExpr.valueOf( - ExprTupleValue.fromExprValueMap(builder.build()).bindingTuples()); + ExprValue resultVal = + hlExpr.valueOf(ExprTupleValue.fromExprValueMap(builder.build()).bindingTuples()); assertTrue(resultVal.isMissing()); } @@ -67,20 +68,23 @@ public void highlight_all_test() { builder.put("_highlight", ExprTupleValue.fromExprValueMap(hlBuilder.build())); HighlightExpression hlExpr = new HighlightExpression(DSL.literal("T*")); - ExprValue resultVal = hlExpr.valueOf( - ExprTupleValue.fromExprValueMap(builder.build()).bindingTuples()); + ExprValue resultVal = + hlExpr.valueOf(ExprTupleValue.fromExprValueMap(builder.build()).bindingTuples()); assertEquals(STRUCT, resultVal.type()); - assertTrue(resultVal.tupleValue().containsValue( - ExprValueUtils.stringValue("correct result value"))); - assertFalse(resultVal.tupleValue().containsValue( - ExprValueUtils.stringValue("secondary correct result value"))); + assertTrue( + resultVal.tupleValue().containsValue(ExprValueUtils.stringValue("correct result value"))); + assertFalse( + resultVal + .tupleValue() + .containsValue(ExprValueUtils.stringValue("secondary correct result value"))); } @Test public void do_nothing_with_missing_value() { - Environment hlTuple = ExprValueUtils.tupleValue( - ImmutableMap.of("NonHighlightField", "ResultValue")).bindingTuples(); + Environment hlTuple = + ExprValueUtils.tupleValue(ImmutableMap.of("NonHighlightField", "ResultValue")) + .bindingTuples(); HighlightExpression expr = new HighlightExpression(DSL.literal("*")); ExprValue resultVal = expr.valueOf(hlTuple); @@ -96,13 +100,13 @@ public void highlight_wildcard_test() { builder.put("_highlight", ExprTupleValue.fromExprValueMap(hlBuilder.build())); HighlightExpression hlExpr = new HighlightExpression(DSL.literal("T*")); - ExprValue resultVal = hlExpr.valueOf( - ExprTupleValue.fromExprValueMap(builder.build()).bindingTuples()); + ExprValue resultVal = + hlExpr.valueOf(ExprTupleValue.fromExprValueMap(builder.build()).bindingTuples()); assertEquals(STRUCT, resultVal.type()); - assertTrue(resultVal.tupleValue().containsValue( - ExprValueUtils.stringValue("correct result value"))); - assertFalse(resultVal.tupleValue().containsValue( - ExprValueUtils.stringValue("incorrect result value"))); + assertTrue( + resultVal.tupleValue().containsValue(ExprValueUtils.stringValue("correct result value"))); + assertFalse( + resultVal.tupleValue().containsValue(ExprValueUtils.stringValue("incorrect result value"))); } } diff --git a/core/src/test/java/org/opensearch/sql/expression/NamedExpressionTest.java b/core/src/test/java/org/opensearch/sql/expression/NamedExpressionTest.java index 38f1ce3ca9..915952cca8 100644 --- a/core/src/test/java/org/opensearch/sql/expression/NamedExpressionTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/NamedExpressionTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -55,11 +54,12 @@ void name_a_span_expression() { @Test void name_a_parse_expression() { ParseExpression parse = - DSL.regex(DSL.ref("string_value", STRING), DSL.literal("(?\\w{2})\\w"), + DSL.regex( + DSL.ref("string_value", STRING), + DSL.literal("(?\\w{2})\\w"), DSL.literal("group")); NamedExpression named = DSL.named(parse); assertEquals(parse, named.getDelegated()); assertEquals(parse.getIdentifier().valueOf().stringValue(), named.getName()); } - } diff --git a/core/src/test/java/org/opensearch/sql/expression/ReferenceExpressionTest.java b/core/src/test/java/org/opensearch/sql/expression/ReferenceExpressionTest.java index 46aae069bb..da8c15d19f 100644 --- a/core/src/test/java/org/opensearch/sql/expression/ReferenceExpressionTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/ReferenceExpressionTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -54,13 +53,13 @@ public void resolve_value() { assertEquals(doubleValue(1d), DSL.ref("double_value", DOUBLE).valueOf(valueEnv())); assertEquals(booleanValue(true), DSL.ref("boolean_value", BOOLEAN).valueOf(valueEnv())); assertEquals(stringValue("str"), DSL.ref("string_value", STRING).valueOf(valueEnv())); - assertEquals(tupleValue(ImmutableMap.of("str", 1)), - DSL.ref("struct_value", STRUCT).valueOf(valueEnv())); - assertEquals(collectionValue(ImmutableList.of(1)), - DSL.ref("array_value", ARRAY).valueOf(valueEnv())); + assertEquals( + tupleValue(ImmutableMap.of("str", 1)), DSL.ref("struct_value", STRUCT).valueOf(valueEnv())); + assertEquals( + collectionValue(ImmutableList.of(1)), DSL.ref("array_value", ARRAY).valueOf(valueEnv())); assertEquals(LITERAL_NULL, DSL.ref(BOOL_TYPE_NULL_VALUE_FIELD, BOOLEAN).valueOf(valueEnv())); - assertEquals(LITERAL_MISSING, - DSL.ref(BOOL_TYPE_MISSING_VALUE_FIELD, BOOLEAN).valueOf(valueEnv())); + assertEquals( + LITERAL_MISSING, DSL.ref(BOOL_TYPE_MISSING_VALUE_FIELD, BOOLEAN).valueOf(valueEnv())); } @Test @@ -138,6 +137,9 @@ public void array_with_multiple_path_value() { } /** + * + * + *
    * {
    *   "name": "bob smith"
    *   "project.year": 1990,
@@ -157,39 +159,31 @@ public void array_with_multiple_path_value() {
    *     { "info": "Only first index of array used" }
    *   ]
    * }
+   * 
*/ private ExprTupleValue tuple() { ExprValue address = - ExprValueUtils.tupleValue(ImmutableMap.of("state", "WA", "city", "seattle", "project" - + ".year", 1990)); - ExprValue project = - ExprValueUtils.tupleValue(ImmutableMap.of("year", 2020)); - ExprValue addressLocal = - ExprValueUtils.tupleValue(ImmutableMap.of("state", "WA")); + ExprValueUtils.tupleValue( + ImmutableMap.of("state", "WA", "city", "seattle", "project" + ".year", 1990)); + ExprValue project = ExprValueUtils.tupleValue(ImmutableMap.of("year", 2020)); + ExprValue addressLocal = ExprValueUtils.tupleValue(ImmutableMap.of("state", "WA")); ExprValue messageCollectionValue = new ExprCollectionValue( ImmutableList.of( ExprValueUtils.tupleValue( - ImmutableMap.of( - "info", stringValue("First message in array") - ) - ), + ImmutableMap.of("info", stringValue("First message in array"))), ExprValueUtils.tupleValue( - ImmutableMap.of( - "info", stringValue("Only first index of array used") - ) - ) - ) - ); - - ExprTupleValue tuple = ExprTupleValue.fromExprValueMap(ImmutableMap.of( - "name", new ExprStringValue("bob smith"), - "project.year", new ExprIntegerValue(1990), - "project", project, - "address", address, - "address.local", addressLocal, - "message", messageCollectionValue - )); + ImmutableMap.of("info", stringValue("Only first index of array used"))))); + + ExprTupleValue tuple = + ExprTupleValue.fromExprValueMap( + ImmutableMap.of( + "name", new ExprStringValue("bob smith"), + "project.year", new ExprIntegerValue(1990), + "project", project, + "address", address, + "address.local", addressLocal, + "message", messageCollectionValue)); return tuple; } } diff --git a/core/src/test/java/org/opensearch/sql/expression/aggregation/AggregationTest.java b/core/src/test/java/org/opensearch/sql/expression/aggregation/AggregationTest.java index 7742e6c4d0..f1a3a9d948 100644 --- a/core/src/test/java/org/opensearch/sql/expression/aggregation/AggregationTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/aggregation/AggregationTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.aggregation; import com.google.common.collect.ImmutableList; @@ -98,26 +97,46 @@ public class AggregationTest extends ExpressionTestBase { protected static List tuples_with_duplicates = Arrays.asList( - ExprValueUtils.tupleValue(ImmutableMap.of( - "integer_value", 1, - "double_value", 4d, - "struct_value", ImmutableMap.of("str", 1), - "array_value", ImmutableList.of(1))), - ExprValueUtils.tupleValue(ImmutableMap.of( - "integer_value", 1, - "double_value", 3d, - "struct_value", ImmutableMap.of("str", 1), - "array_value", ImmutableList.of(1))), - ExprValueUtils.tupleValue(ImmutableMap.of( - "integer_value", 2, - "double_value", 2d, - "struct_value", ImmutableMap.of("str", 2), - "array_value", ImmutableList.of(2))), - ExprValueUtils.tupleValue(ImmutableMap.of( - "integer_value", 3, - "double_value", 1d, - "struct_value", ImmutableMap.of("str1", 1), - "array_value", ImmutableList.of(1, 2)))); + ExprValueUtils.tupleValue( + ImmutableMap.of( + "integer_value", + 1, + "double_value", + 4d, + "struct_value", + ImmutableMap.of("str", 1), + "array_value", + ImmutableList.of(1))), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "integer_value", + 1, + "double_value", + 3d, + "struct_value", + ImmutableMap.of("str", 1), + "array_value", + ImmutableList.of(1))), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "integer_value", + 2, + "double_value", + 2d, + "struct_value", + ImmutableMap.of("str", 2), + "array_value", + ImmutableList.of(2))), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "integer_value", + 3, + "double_value", + 1d, + "struct_value", + ImmutableMap.of("str1", 1), + "array_value", + ImmutableList.of(1, 2)))); protected static List tuples_with_null_and_missing = Arrays.asList( diff --git a/core/src/test/java/org/opensearch/sql/expression/aggregation/AvgAggregatorTest.java b/core/src/test/java/org/opensearch/sql/expression/aggregation/AvgAggregatorTest.java index b3b0052bc3..f465a6477e 100644 --- a/core/src/test/java/org/opensearch/sql/expression/aggregation/AvgAggregatorTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/aggregation/AvgAggregatorTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.aggregation; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -37,16 +36,23 @@ public void avg_field_expression() { @Test public void avg_arithmetic_expression() { - ExprValue result = aggregation(DSL.avg( - DSL.multiply(DSL.ref("integer_value", INTEGER), - DSL.literal(ExprValueUtils.integerValue(10)))), tuples); + ExprValue result = + aggregation( + DSL.avg( + DSL.multiply( + DSL.ref("integer_value", INTEGER), + DSL.literal(ExprValueUtils.integerValue(10)))), + tuples); assertEquals(25.0, result.value()); } @Test public void filtered_avg() { - ExprValue result = aggregation(DSL.avg(DSL.ref("integer_value", INTEGER)) - .condition(DSL.greater(DSL.ref("integer_value", INTEGER), DSL.literal(1))), tuples); + ExprValue result = + aggregation( + DSL.avg(DSL.ref("integer_value", INTEGER)) + .condition(DSL.greater(DSL.ref("integer_value", INTEGER), DSL.literal(1))), + tuples); assertEquals(3.0, result.value()); } @@ -128,16 +134,17 @@ public void avg_timestamp() { @Test public void valueOf() { - ExpressionEvaluationException exception = assertThrows(ExpressionEvaluationException.class, - () -> DSL.avg(DSL.ref("double_value", DOUBLE)).valueOf(valueEnv())); + ExpressionEvaluationException exception = + assertThrows( + ExpressionEvaluationException.class, + () -> DSL.avg(DSL.ref("double_value", DOUBLE)).valueOf(valueEnv())); assertEquals("can't evaluate on aggregator: avg", exception.getMessage()); } @Test public void avg_on_unsupported_type() { var aggregator = new AvgAggregator(List.of(DSL.ref("string", STRING)), STRING); - var exception = assertThrows(IllegalArgumentException.class, - () -> aggregator.create()); + var exception = assertThrows(IllegalArgumentException.class, () -> aggregator.create()); assertEquals("avg aggregation over STRING type is not supported", exception.getMessage()); } @@ -149,9 +156,12 @@ public void test_to_string() { @Test public void test_nested_to_string() { - Aggregator avgAggregator = DSL.avg(DSL.multiply(DSL.ref("integer_value", INTEGER), - DSL.literal(ExprValueUtils.integerValue(10)))); - assertEquals(String.format("avg(*(%s, %d))", DSL.ref("integer_value", INTEGER), 10), + Aggregator avgAggregator = + DSL.avg( + DSL.multiply( + DSL.ref("integer_value", INTEGER), DSL.literal(ExprValueUtils.integerValue(10)))); + assertEquals( + String.format("avg(*(%s, %d))", DSL.ref("integer_value", INTEGER), 10), avgAggregator.toString()); } } diff --git a/core/src/test/java/org/opensearch/sql/expression/aggregation/CountAggregatorTest.java b/core/src/test/java/org/opensearch/sql/expression/aggregation/CountAggregatorTest.java index fd27529a70..50bd3fedfe 100644 --- a/core/src/test/java/org/opensearch/sql/expression/aggregation/CountAggregatorTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/aggregation/CountAggregatorTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.aggregation; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -72,9 +71,13 @@ public void count_datetime_field_expression() { @Test public void count_arithmetic_expression() { - ExprValue result = aggregation(DSL.count( - DSL.multiply(DSL.ref("integer_value", INTEGER), - DSL.literal(ExprValueUtils.integerValue(10)))), tuples); + ExprValue result = + aggregation( + DSL.count( + DSL.multiply( + DSL.ref("integer_value", INTEGER), + DSL.literal(ExprValueUtils.integerValue(10)))), + tuples); assertEquals(4, result.value()); } @@ -104,51 +107,56 @@ public void count_array_field_expression() { @Test public void filtered_count() { - ExprValue result = aggregation(DSL.count(DSL.ref("integer_value", INTEGER)) - .condition(DSL.greater(DSL.ref("integer_value", INTEGER), DSL.literal(1))), tuples); + ExprValue result = + aggregation( + DSL.count(DSL.ref("integer_value", INTEGER)) + .condition(DSL.greater(DSL.ref("integer_value", INTEGER), DSL.literal(1))), + tuples); assertEquals(3, result.value()); } @Test public void distinct_count() { - ExprValue result = aggregation(DSL.distinctCount(DSL.ref("integer_value", INTEGER)), - tuples_with_duplicates); + ExprValue result = + aggregation(DSL.distinctCount(DSL.ref("integer_value", INTEGER)), tuples_with_duplicates); assertEquals(3, result.value()); } @Test public void filtered_distinct_count() { - ExprValue result = aggregation(DSL.distinctCount(DSL.ref("integer_value", INTEGER)) - .condition(DSL.greater(DSL.ref("double_value", DOUBLE), DSL.literal(1d))), - tuples_with_duplicates); + ExprValue result = + aggregation( + DSL.distinctCount(DSL.ref("integer_value", INTEGER)) + .condition(DSL.greater(DSL.ref("double_value", DOUBLE), DSL.literal(1d))), + tuples_with_duplicates); assertEquals(2, result.value()); } @Test public void distinct_count_map() { - ExprValue result = aggregation(DSL.distinctCount(DSL.ref("struct_value", STRUCT)), - tuples_with_duplicates); + ExprValue result = + aggregation(DSL.distinctCount(DSL.ref("struct_value", STRUCT)), tuples_with_duplicates); assertEquals(3, result.value()); } @Test public void distinct_count_array() { - ExprValue result = aggregation(DSL.distinctCount(DSL.ref("array_value", ARRAY)), - tuples_with_duplicates); + ExprValue result = + aggregation(DSL.distinctCount(DSL.ref("array_value", ARRAY)), tuples_with_duplicates); assertEquals(3, result.value()); } @Test public void count_with_missing() { - ExprValue result = aggregation(DSL.count(DSL.ref("integer_value", INTEGER)), - tuples_with_null_and_missing); + ExprValue result = + aggregation(DSL.count(DSL.ref("integer_value", INTEGER)), tuples_with_null_and_missing); assertEquals(2, result.value()); } @Test public void count_with_null() { - ExprValue result = aggregation(DSL.count(DSL.ref("double_value", DOUBLE)), - tuples_with_null_and_missing); + ExprValue result = + aggregation(DSL.count(DSL.ref("double_value", DOUBLE)), tuples_with_null_and_missing); assertEquals(2, result.value()); } @@ -166,8 +174,10 @@ public void count_literal_with_null_and_missing() { @Test public void valueOf() { - ExpressionEvaluationException exception = assertThrows(ExpressionEvaluationException.class, - () -> DSL.count(DSL.ref("double_value", DOUBLE)).valueOf(valueEnv())); + ExpressionEvaluationException exception = + assertThrows( + ExpressionEvaluationException.class, + () -> DSL.count(DSL.ref("double_value", DOUBLE)).valueOf(valueEnv())); assertEquals("can't evaluate on aggregator: count", exception.getMessage()); } @@ -183,7 +193,8 @@ public void test_to_string() { @Test public void test_nested_to_string() { Aggregator countAggregator = DSL.count(DSL.abs(DSL.ref("integer_value", INTEGER))); - assertEquals(String.format("count(abs(%s))", DSL.ref("integer_value", INTEGER)), + assertEquals( + String.format("count(abs(%s))", DSL.ref("integer_value", INTEGER)), countAggregator.toString()); } } diff --git a/core/src/test/java/org/opensearch/sql/expression/aggregation/MaxAggregatorTest.java b/core/src/test/java/org/opensearch/sql/expression/aggregation/MaxAggregatorTest.java index 6886622704..c6cd380ad5 100644 --- a/core/src/test/java/org/opensearch/sql/expression/aggregation/MaxAggregatorTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/aggregation/MaxAggregatorTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.aggregation; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -83,16 +82,23 @@ public void test_max_timestamp() { @Test public void test_max_arithmetic_expression() { - ExprValue result = aggregation( - DSL.max(DSL.add(DSL.ref("integer_value", INTEGER), - DSL.literal(ExprValueUtils.integerValue(0)))), tuples); + ExprValue result = + aggregation( + DSL.max( + DSL.add( + DSL.ref("integer_value", INTEGER), + DSL.literal(ExprValueUtils.integerValue(0)))), + tuples); assertEquals(4, result.value()); } @Test public void filtered_max() { - ExprValue result = aggregation(DSL.max(DSL.ref("integer_value", INTEGER)) - .condition(DSL.less(DSL.ref("integer_value", INTEGER), DSL.literal(4))), tuples); + ExprValue result = + aggregation( + DSL.max(DSL.ref("integer_value", INTEGER)) + .condition(DSL.less(DSL.ref("integer_value", INTEGER), DSL.literal(4))), + tuples); assertEquals(3, result.value()); } @@ -119,8 +125,10 @@ public void test_max_all_missing_or_null() { @Test public void test_value_of() { - ExpressionEvaluationException exception = assertThrows(ExpressionEvaluationException.class, - () -> DSL.max(DSL.ref("double_value", DOUBLE)).valueOf(valueEnv())); + ExpressionEvaluationException exception = + assertThrows( + ExpressionEvaluationException.class, + () -> DSL.max(DSL.ref("double_value", DOUBLE)).valueOf(valueEnv())); assertEquals("can't evaluate on aggregator: max", exception.getMessage()); } @@ -132,9 +140,12 @@ public void test_to_string() { @Test public void test_nested_to_string() { - Aggregator maxAggregator = DSL.max(DSL.add(DSL.ref("integer_value", INTEGER), - DSL.literal(ExprValueUtils.integerValue(10)))); - assertEquals(String.format("max(+(%s, %d))", DSL.ref("integer_value", INTEGER), 10), + Aggregator maxAggregator = + DSL.max( + DSL.add( + DSL.ref("integer_value", INTEGER), DSL.literal(ExprValueUtils.integerValue(10)))); + assertEquals( + String.format("max(+(%s, %d))", DSL.ref("integer_value", INTEGER), 10), maxAggregator.toString()); } } diff --git a/core/src/test/java/org/opensearch/sql/expression/aggregation/MinAggregatorTest.java b/core/src/test/java/org/opensearch/sql/expression/aggregation/MinAggregatorTest.java index 1437f4dfda..1aee0f3a6c 100644 --- a/core/src/test/java/org/opensearch/sql/expression/aggregation/MinAggregatorTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/aggregation/MinAggregatorTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.aggregation; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -83,16 +82,23 @@ public void test_min_timestamp() { @Test public void test_min_arithmetic_expression() { - ExprValue result = aggregation( - DSL.min(DSL.add(DSL.ref("integer_value", INTEGER), - DSL.literal(ExprValueUtils.integerValue(0)))), tuples); + ExprValue result = + aggregation( + DSL.min( + DSL.add( + DSL.ref("integer_value", INTEGER), + DSL.literal(ExprValueUtils.integerValue(0)))), + tuples); assertEquals(1, result.value()); } @Test public void filtered_min() { - ExprValue result = aggregation(DSL.min(DSL.ref("integer_value", INTEGER)) - .condition(DSL.greater(DSL.ref("integer_value", INTEGER), DSL.literal(1))), tuples); + ExprValue result = + aggregation( + DSL.min(DSL.ref("integer_value", INTEGER)) + .condition(DSL.greater(DSL.ref("integer_value", INTEGER), DSL.literal(1))), + tuples); assertEquals(2, result.value()); } @@ -119,8 +125,10 @@ public void test_min_all_missing_or_null() { @Test public void test_value_of() { - ExpressionEvaluationException exception = assertThrows(ExpressionEvaluationException.class, - () -> DSL.min(DSL.ref("double_value", DOUBLE)).valueOf(valueEnv())); + ExpressionEvaluationException exception = + assertThrows( + ExpressionEvaluationException.class, + () -> DSL.min(DSL.ref("double_value", DOUBLE)).valueOf(valueEnv())); assertEquals("can't evaluate on aggregator: min", exception.getMessage()); } @@ -132,9 +140,12 @@ public void test_to_string() { @Test public void test_nested_to_string() { - Aggregator minAggregator = DSL.min(DSL.add(DSL.ref("integer_value", INTEGER), - DSL.literal(ExprValueUtils.integerValue(10)))); - assertEquals(String.format("min(+(%s, %d))", DSL.ref("integer_value", INTEGER), 10), + Aggregator minAggregator = + DSL.min( + DSL.add( + DSL.ref("integer_value", INTEGER), DSL.literal(ExprValueUtils.integerValue(10)))); + assertEquals( + String.format("min(+(%s, %d))", DSL.ref("integer_value", INTEGER), 10), minAggregator.toString()); } } diff --git a/core/src/test/java/org/opensearch/sql/expression/aggregation/StdDevAggregatorTest.java b/core/src/test/java/org/opensearch/sql/expression/aggregation/StdDevAggregatorTest.java index fe4923d4df..ceb76815dc 100644 --- a/core/src/test/java/org/opensearch/sql/expression/aggregation/StdDevAggregatorTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/aggregation/StdDevAggregatorTest.java @@ -40,14 +40,11 @@ @ExtendWith(MockitoExtension.class) public class StdDevAggregatorTest extends AggregationTest { - @Mock - Expression expression; + @Mock Expression expression; - @Mock - ExprValue tupleValue; + @Mock ExprValue tupleValue; - @Mock - BindingTuple tuple; + @Mock BindingTuple tuple; @Test public void stddev_sample_field_expression() { diff --git a/core/src/test/java/org/opensearch/sql/expression/aggregation/SumAggregatorTest.java b/core/src/test/java/org/opensearch/sql/expression/aggregation/SumAggregatorTest.java index 676306041e..eb5a18f248 100644 --- a/core/src/test/java/org/opensearch/sql/expression/aggregation/SumAggregatorTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/aggregation/SumAggregatorTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.aggregation; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -53,9 +52,13 @@ public void sum_double_field_expression() { @Test public void sum_arithmetic_expression() { - ExprValue result = aggregation(DSL.sum( - DSL.multiply(DSL.ref("integer_value", INTEGER), - DSL.literal(ExprValueUtils.integerValue(10)))), tuples); + ExprValue result = + aggregation( + DSL.sum( + DSL.multiply( + DSL.ref("integer_value", INTEGER), + DSL.literal(ExprValueUtils.integerValue(10)))), + tuples); assertEquals(100, result.value()); } @@ -64,19 +67,23 @@ public void sum_string_field_expression() { SumAggregator sumAggregator = new SumAggregator(ImmutableList.of(DSL.ref("string_value", STRING)), ExprCoreType.STRING); SumState sumState = sumAggregator.create(); - ExpressionEvaluationException exception = assertThrows(ExpressionEvaluationException.class, - () -> sumAggregator - .iterate( - ExprValueUtils.tupleValue(ImmutableMap.of("string_value", "m")).bindingTuples(), - sumState) - ); + ExpressionEvaluationException exception = + assertThrows( + ExpressionEvaluationException.class, + () -> + sumAggregator.iterate( + ExprValueUtils.tupleValue(ImmutableMap.of("string_value", "m")).bindingTuples(), + sumState)); assertEquals("unexpected type [STRING] in sum aggregation", exception.getMessage()); } @Test public void filtered_sum() { - ExprValue result = aggregation(DSL.sum(DSL.ref("integer_value", INTEGER)) - .condition(DSL.greater(DSL.ref("integer_value", INTEGER), DSL.literal(1))), tuples); + ExprValue result = + aggregation( + DSL.sum(DSL.ref("integer_value", INTEGER)) + .condition(DSL.greater(DSL.ref("integer_value", INTEGER), DSL.literal(1))), + tuples); assertEquals(9, result.value()); } @@ -103,8 +110,10 @@ public void sum_with_all_missing_or_null() { @Test public void valueOf() { - ExpressionEvaluationException exception = assertThrows(ExpressionEvaluationException.class, - () -> DSL.sum(DSL.ref("double_value", DOUBLE)).valueOf(valueEnv())); + ExpressionEvaluationException exception = + assertThrows( + ExpressionEvaluationException.class, + () -> DSL.sum(DSL.ref("double_value", DOUBLE)).valueOf(valueEnv())); assertEquals("can't evaluate on aggregator: sum", exception.getMessage()); } @@ -116,9 +125,12 @@ public void test_to_string() { @Test public void test_nested_to_string() { - Aggregator sumAggregator = DSL.sum(DSL.multiply(DSL.ref("integer_value", INTEGER), - DSL.literal(ExprValueUtils.integerValue(10)))); - assertEquals(String.format("sum(*(%s, %d))", DSL.ref("integer_value", INTEGER), 10), + Aggregator sumAggregator = + DSL.sum( + DSL.multiply( + DSL.ref("integer_value", INTEGER), DSL.literal(ExprValueUtils.integerValue(10)))); + assertEquals( + String.format("sum(*(%s, %d))", DSL.ref("integer_value", INTEGER), 10), sumAggregator.toString()); } } diff --git a/core/src/test/java/org/opensearch/sql/expression/aggregation/TakeAggregatorTest.java b/core/src/test/java/org/opensearch/sql/expression/aggregation/TakeAggregatorTest.java index 6d9aac4957..2409ec49d2 100644 --- a/core/src/test/java/org/opensearch/sql/expression/aggregation/TakeAggregatorTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/aggregation/TakeAggregatorTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.aggregation; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -35,15 +34,18 @@ public void take_string_field_expression_with_large_size() { @Test public void filtered_take() { ExprValue result = - aggregation(DSL.take(DSL.ref("string_value", STRING), DSL.literal(10)) - .condition(DSL.equal(DSL.ref("string_value", STRING), DSL.literal("m"))), tuples); + aggregation( + DSL.take(DSL.ref("string_value", STRING), DSL.literal(10)) + .condition(DSL.equal(DSL.ref("string_value", STRING), DSL.literal("m"))), + tuples); assertEquals(ImmutableList.of("m", "m"), result.value()); } @Test public void test_take_null() { ExprValue result = - aggregation(DSL.take(DSL.ref("string_value", STRING), DSL.literal(10)), + aggregation( + DSL.take(DSL.ref("string_value", STRING), DSL.literal(10)), tuples_with_null_and_missing); assertEquals(ImmutableList.of("m", "f"), result.value()); } @@ -51,7 +53,8 @@ public void test_take_null() { @Test public void test_take_missing() { ExprValue result = - aggregation(DSL.take(DSL.ref("string_value", STRING), DSL.literal(10)), + aggregation( + DSL.take(DSL.ref("string_value", STRING), DSL.literal(10)), tuples_with_null_and_missing); assertEquals(ImmutableList.of("m", "f"), result.value()); } @@ -59,22 +62,27 @@ public void test_take_missing() { @Test public void test_take_all_missing_or_null() { ExprValue result = - aggregation(DSL.take(DSL.ref("string_value", STRING), DSL.literal(10)), + aggregation( + DSL.take(DSL.ref("string_value", STRING), DSL.literal(10)), tuples_with_all_null_or_missing); assertEquals(ImmutableList.of(), result.value()); } @Test public void test_take_with_invalid_size() { - IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, - () -> aggregation(DSL.take(DSL.ref("string_value", STRING), DSL.literal(0)), tuples)); + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> aggregation(DSL.take(DSL.ref("string_value", STRING), DSL.literal(0)), tuples)); assertEquals("size must be greater than 0", exception.getMessage()); } @Test public void test_value_of() { - ExpressionEvaluationException exception = assertThrows(ExpressionEvaluationException.class, - () -> DSL.take(DSL.ref("string_value", STRING), DSL.literal(10)).valueOf(valueEnv())); + ExpressionEvaluationException exception = + assertThrows( + ExpressionEvaluationException.class, + () -> DSL.take(DSL.ref("string_value", STRING), DSL.literal(10)).valueOf(valueEnv())); assertEquals("can't evaluate on aggregator: take", exception.getMessage()); } diff --git a/core/src/test/java/org/opensearch/sql/expression/conditional/ConditionalFunctionTest.java b/core/src/test/java/org/opensearch/sql/expression/conditional/ConditionalFunctionTest.java index ae8b714dd8..33654a71cf 100644 --- a/core/src/test/java/org/opensearch/sql/expression/conditional/ConditionalFunctionTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/conditional/ConditionalFunctionTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.conditional; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -29,12 +28,9 @@ @ExtendWith(MockitoExtension.class) public class ConditionalFunctionTest extends ExpressionTestBase { - @Mock - Environment env; + @Mock Environment env; - /** - * Arguments for case test. - */ + /** Arguments for case test. */ private static Stream caseArguments() { Stream.Builder builder = Stream.builder(); return builder @@ -46,28 +42,25 @@ private static Stream caseArguments() { @ParameterizedTest(name = "case {0} when {1} then {2} when {3} then {4} else {5}") @MethodSource("caseArguments") - void case_value(int value, - int cond1, int result1, - int cond2, int result2, - int defaultVal) throws Exception { - Callable expect = () -> { - if (cond1 == value) { - return result1; - } else if (cond2 == value) { - return result2; - } else { - return defaultVal; - } - }; + void case_value(int value, int cond1, int result1, int cond2, int result2, int defaultVal) + throws Exception { + Callable expect = + () -> { + if (cond1 == value) { + return result1; + } else if (cond2 == value) { + return result2; + } else { + return defaultVal; + } + }; - Expression cases = DSL.cases( - DSL.literal(defaultVal), - DSL.when(DSL.equal(DSL.literal(cond1), DSL.literal(value)), DSL.literal(result1)), - DSL.when(DSL.equal(DSL.literal(cond2), DSL.literal(value)), DSL.literal(result2))); + Expression cases = + DSL.cases( + DSL.literal(defaultVal), + DSL.when(DSL.equal(DSL.literal(cond1), DSL.literal(value)), DSL.literal(result1)), + DSL.when(DSL.equal(DSL.literal(cond2), DSL.literal(value)), DSL.literal(result2))); - assertEquals( - new ExprIntegerValue(expect.call()), - cases.valueOf(env)); + assertEquals(new ExprIntegerValue(expect.call()), cases.valueOf(env)); } - } diff --git a/core/src/test/java/org/opensearch/sql/expression/conditional/cases/CaseClauseTest.java b/core/src/test/java/org/opensearch/sql/expression/conditional/cases/CaseClauseTest.java index 3c95c4f461..61ff7ef022 100644 --- a/core/src/test/java/org/opensearch/sql/expression/conditional/cases/CaseClauseTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/conditional/cases/CaseClauseTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.conditional.cases; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -29,8 +28,7 @@ @ExtendWith(MockitoExtension.class) class CaseClauseTest extends ExpressionTestBase { - @Mock - private WhenClause whenClause; + @Mock private WhenClause whenClause; @Test void should_return_when_clause_result_if_matched() { @@ -93,8 +91,7 @@ void should_return_all_result_types_including_default() { CaseClause caseClause = new CaseClause(ImmutableList.of(whenClause), defaultResult); assertEquals( - ImmutableList.of(ExprCoreType.INTEGER, ExprCoreType.STRING), - caseClause.allResultTypes()); + ImmutableList.of(ExprCoreType.INTEGER, ExprCoreType.STRING), caseClause.allResultTypes()); } @Test @@ -104,9 +101,6 @@ void should_return_all_result_types_excluding_null_result() { when(defaultResult.type()).thenReturn(ExprCoreType.UNDEFINED); CaseClause caseClause = new CaseClause(ImmutableList.of(whenClause), defaultResult); - assertEquals( - ImmutableList.of(), - caseClause.allResultTypes()); + assertEquals(ImmutableList.of(), caseClause.allResultTypes()); } - } diff --git a/core/src/test/java/org/opensearch/sql/expression/conditional/cases/WhenClauseTest.java b/core/src/test/java/org/opensearch/sql/expression/conditional/cases/WhenClauseTest.java index a13f072510..e03c851694 100644 --- a/core/src/test/java/org/opensearch/sql/expression/conditional/cases/WhenClauseTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/conditional/cases/WhenClauseTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.conditional.cases; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -59,5 +58,4 @@ void should_use_result_expression_type() { WhenClause whenClause = new WhenClause(DSL.literal(true), DSL.literal(30)); assertEquals(ExprCoreType.INTEGER, whenClause.type()); } - } diff --git a/core/src/test/java/org/opensearch/sql/expression/datetime/AddTimeAndSubTimeTest.java b/core/src/test/java/org/opensearch/sql/expression/datetime/AddTimeAndSubTimeTest.java index e917e2ee62..eed83f4fa9 100644 --- a/core/src/test/java/org/opensearch/sql/expression/datetime/AddTimeAndSubTimeTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/datetime/AddTimeAndSubTimeTest.java @@ -74,38 +74,73 @@ public void time_limited_by_24_hours() { private static Stream getTestData() { return Stream.of( // DATETIME and TIME/DATE/DATETIME/TIMESTAMP - Arguments.of(LocalDateTime.of(1961, 4, 12, 9, 7), LocalTime.of(1, 48), - LocalDateTime.of(1961, 4, 12, 10, 55), LocalDateTime.of(1961, 4, 12, 7, 19)), - Arguments.of(LocalDateTime.of(1961, 4, 12, 9, 7), LocalDate.of(2000, 1, 1), - LocalDateTime.of(1961, 4, 12, 9, 7), LocalDateTime.of(1961, 4, 12, 9, 7)), - Arguments.of(LocalDateTime.of(1961, 4, 12, 9, 7), LocalDateTime.of(1235, 5, 6, 1, 48), - LocalDateTime.of(1961, 4, 12, 10, 55), LocalDateTime.of(1961, 4, 12, 7, 19)), - Arguments.of(LocalDateTime.of(1961, 4, 12, 9, 7), Instant.ofEpochSecond(42), - LocalDateTime.of(1961, 4, 12, 9, 7, 42), LocalDateTime.of(1961, 4, 12, 9, 6, 18)), + Arguments.of( + LocalDateTime.of(1961, 4, 12, 9, 7), + LocalTime.of(1, 48), + LocalDateTime.of(1961, 4, 12, 10, 55), + LocalDateTime.of(1961, 4, 12, 7, 19)), + Arguments.of( + LocalDateTime.of(1961, 4, 12, 9, 7), + LocalDate.of(2000, 1, 1), + LocalDateTime.of(1961, 4, 12, 9, 7), + LocalDateTime.of(1961, 4, 12, 9, 7)), + Arguments.of( + LocalDateTime.of(1961, 4, 12, 9, 7), + LocalDateTime.of(1235, 5, 6, 1, 48), + LocalDateTime.of(1961, 4, 12, 10, 55), + LocalDateTime.of(1961, 4, 12, 7, 19)), + Arguments.of( + LocalDateTime.of(1961, 4, 12, 9, 7), + Instant.ofEpochSecond(42), + LocalDateTime.of(1961, 4, 12, 9, 7, 42), + LocalDateTime.of(1961, 4, 12, 9, 6, 18)), // DATE and TIME/DATE/DATETIME/TIMESTAMP - Arguments.of(LocalDate.of(1961, 4, 12), LocalTime.of(9, 7), - LocalDateTime.of(1961, 4, 12, 9, 7), LocalDateTime.of(1961, 4, 11, 14, 53)), - Arguments.of(LocalDate.of(1961, 4, 12), LocalDate.of(2000, 1, 1), - LocalDateTime.of(1961, 4, 12, 0, 0), LocalDateTime.of(1961, 4, 12, 0, 0)), - Arguments.of(LocalDate.of(1961, 4, 12), LocalDateTime.of(1235, 5, 6, 1, 48), - LocalDateTime.of(1961, 4, 12, 1, 48), LocalDateTime.of(1961, 4, 11, 22, 12)), - Arguments.of(LocalDate.of(1961, 4, 12), Instant.ofEpochSecond(42), - LocalDateTime.of(1961, 4, 12, 0, 0, 42), LocalDateTime.of(1961, 4, 11, 23, 59, 18)), + Arguments.of( + LocalDate.of(1961, 4, 12), + LocalTime.of(9, 7), + LocalDateTime.of(1961, 4, 12, 9, 7), + LocalDateTime.of(1961, 4, 11, 14, 53)), + Arguments.of( + LocalDate.of(1961, 4, 12), + LocalDate.of(2000, 1, 1), + LocalDateTime.of(1961, 4, 12, 0, 0), + LocalDateTime.of(1961, 4, 12, 0, 0)), + Arguments.of( + LocalDate.of(1961, 4, 12), + LocalDateTime.of(1235, 5, 6, 1, 48), + LocalDateTime.of(1961, 4, 12, 1, 48), + LocalDateTime.of(1961, 4, 11, 22, 12)), + Arguments.of( + LocalDate.of(1961, 4, 12), + Instant.ofEpochSecond(42), + LocalDateTime.of(1961, 4, 12, 0, 0, 42), + LocalDateTime.of(1961, 4, 11, 23, 59, 18)), // TIMESTAMP and TIME/DATE/DATETIME/TIMESTAMP - Arguments.of(Instant.ofEpochSecond(42), LocalTime.of(9, 7), - LocalDateTime.of(1970, 1, 1, 9, 7, 42), LocalDateTime.of(1969, 12, 31, 14, 53, 42)), - Arguments.of(Instant.ofEpochSecond(42), LocalDate.of(1961, 4, 12), - LocalDateTime.of(1970, 1, 1, 0, 0, 42), LocalDateTime.of(1970, 1, 1, 0, 0, 42)), - Arguments.of(Instant.ofEpochSecond(42), LocalDateTime.of(1961, 4, 12, 9, 7), - LocalDateTime.of(1970, 1, 1, 9, 7, 42), LocalDateTime.of(1969, 12, 31, 14, 53, 42)), - Arguments.of(Instant.ofEpochSecond(42), Instant.ofEpochMilli(42), + Arguments.of( + Instant.ofEpochSecond(42), + LocalTime.of(9, 7), + LocalDateTime.of(1970, 1, 1, 9, 7, 42), + LocalDateTime.of(1969, 12, 31, 14, 53, 42)), + Arguments.of( + Instant.ofEpochSecond(42), + LocalDate.of(1961, 4, 12), + LocalDateTime.of(1970, 1, 1, 0, 0, 42), + LocalDateTime.of(1970, 1, 1, 0, 0, 42)), + Arguments.of( + Instant.ofEpochSecond(42), + LocalDateTime.of(1961, 4, 12, 9, 7), + LocalDateTime.of(1970, 1, 1, 9, 7, 42), + LocalDateTime.of(1969, 12, 31, 14, 53, 42)), + Arguments.of( + Instant.ofEpochSecond(42), + Instant.ofEpochMilli(42), LocalDateTime.of(1970, 1, 1, 0, 0, 42, 42000000), - LocalDateTime.of(1970, 1, 1, 0, 0, 41, 958000000)) - ); + LocalDateTime.of(1970, 1, 1, 0, 0, 41, 958000000))); } /** * Check that `ADDTIME` and `SUBTIME` functions result value and type. + * * @param arg1 First argument. * @param arg2 Second argument. * @param addTimeExpectedResult Expected result for `ADDTIME`. @@ -113,9 +148,11 @@ private static Stream getTestData() { */ @ParameterizedTest @MethodSource("getTestData") - public void return_datetime_when_first_arg_is_not_time(Temporal arg1, Temporal arg2, - LocalDateTime addTimeExpectedResult, - LocalDateTime subTimeExpectedResult) { + public void return_datetime_when_first_arg_is_not_time( + Temporal arg1, + Temporal arg2, + LocalDateTime addTimeExpectedResult, + LocalDateTime subTimeExpectedResult) { var res = addtime(arg1, arg2); assertEquals(DATETIME, res.type()); assertEquals(addTimeExpectedResult, res.datetimeValue()); diff --git a/core/src/test/java/org/opensearch/sql/expression/datetime/ConvertTZTest.java b/core/src/test/java/org/opensearch/sql/expression/datetime/ConvertTZTest.java index 7bc788c9a7..17ff4f67ab 100644 --- a/core/src/test/java/org/opensearch/sql/expression/datetime/ConvertTZTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/datetime/ConvertTZTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.datetime; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -20,150 +19,162 @@ class ConvertTZTest extends ExpressionTestBase { @Test public void invalidDate() { - FunctionExpression expr = DSL.convert_tz(DSL.datetime( - DSL.literal("2021-04-31 10:00:00")), - DSL.literal("+00:00"), - DSL.literal("+00:00")); + FunctionExpression expr = + DSL.convert_tz( + DSL.datetime(DSL.literal("2021-04-31 10:00:00")), + DSL.literal("+00:00"), + DSL.literal("+00:00")); assertEquals(DATETIME, expr.type()); assertEquals(nullValue(), expr.valueOf()); } @Test public void conversionFromNoOffset() { - FunctionExpression expr = DSL.convert_tz(DSL.datetime( - DSL.literal("2008-05-15 22:00:00")), - DSL.literal("+00:00"), - DSL.literal("+10:00")); + FunctionExpression expr = + DSL.convert_tz( + DSL.datetime(DSL.literal("2008-05-15 22:00:00")), + DSL.literal("+00:00"), + DSL.literal("+10:00")); assertEquals(DATETIME, expr.type()); assertEquals(new ExprDatetimeValue("2008-05-16 08:00:00"), expr.valueOf()); } @Test public void conversionToInvalidInput3Over() { - FunctionExpression expr = DSL.convert_tz(DSL.datetime( - DSL.literal("2008-05-15 22:00:00")), - DSL.literal("+00:00"), - DSL.literal("+16:00")); + FunctionExpression expr = + DSL.convert_tz( + DSL.datetime(DSL.literal("2008-05-15 22:00:00")), + DSL.literal("+00:00"), + DSL.literal("+16:00")); assertEquals(DATETIME, expr.type()); assertEquals(nullValue(), expr.valueOf()); } @Test public void conversionToInvalidInput3Under() { - FunctionExpression expr = DSL.convert_tz(DSL.datetime( - DSL.literal("2008-05-15 22:00:00")), - DSL.literal("+00:00"), - DSL.literal("-16:00")); + FunctionExpression expr = + DSL.convert_tz( + DSL.datetime(DSL.literal("2008-05-15 22:00:00")), + DSL.literal("+00:00"), + DSL.literal("-16:00")); assertEquals(DATETIME, expr.type()); assertEquals(nullValue(), expr.valueOf()); } @Test public void conversionFromPositiveToPositive() { - FunctionExpression expr = DSL.convert_tz(DSL.datetime( - DSL.literal("2008-05-15 22:00:00")), - DSL.literal("+15:00"), - DSL.literal("+01:00")); + FunctionExpression expr = + DSL.convert_tz( + DSL.datetime(DSL.literal("2008-05-15 22:00:00")), + DSL.literal("+15:00"), + DSL.literal("+01:00")); assertEquals(DATETIME, expr.type()); assertEquals(nullValue(), expr.valueOf()); } @Test public void invalidInput2Under() { - FunctionExpression expr = DSL.convert_tz(DSL.datetime( - DSL.literal("2008-05-15 22:00:00")), - DSL.literal("-15:00"), - DSL.literal("+01:00")); + FunctionExpression expr = + DSL.convert_tz( + DSL.datetime(DSL.literal("2008-05-15 22:00:00")), + DSL.literal("-15:00"), + DSL.literal("+01:00")); assertEquals(DATETIME, expr.type()); assertEquals(nullValue(), expr.valueOf()); } @Test public void invalidInput3Over() { - FunctionExpression expr = DSL.convert_tz(DSL.datetime( - DSL.literal("2008-05-15 22:00:00")), - DSL.literal("-12:00"), - DSL.literal("+15:00")); + FunctionExpression expr = + DSL.convert_tz( + DSL.datetime(DSL.literal("2008-05-15 22:00:00")), + DSL.literal("-12:00"), + DSL.literal("+15:00")); assertEquals(DATETIME, expr.type()); assertEquals(nullValue(), expr.valueOf()); } @Test public void conversionToPositiveEdge() { - FunctionExpression expr = DSL.convert_tz(DSL.datetime( - DSL.literal("2008-05-15 22:00:00")), - DSL.literal("+00:00"), - DSL.literal("+14:00")); + FunctionExpression expr = + DSL.convert_tz( + DSL.datetime(DSL.literal("2008-05-15 22:00:00")), + DSL.literal("+00:00"), + DSL.literal("+14:00")); assertEquals(DATETIME, expr.type()); assertEquals(new ExprDatetimeValue("2008-05-16 12:00:00"), expr.valueOf()); } @Test public void conversionToNegativeEdge() { - FunctionExpression expr = DSL.convert_tz(DSL.datetime( - DSL.literal("2008-05-15 22:00:00")), - DSL.literal("+00:01"), - DSL.literal("-13:59")); + FunctionExpression expr = + DSL.convert_tz( + DSL.datetime(DSL.literal("2008-05-15 22:00:00")), + DSL.literal("+00:01"), + DSL.literal("-13:59")); assertEquals(DATETIME, expr.type()); assertEquals(new ExprDatetimeValue("2008-05-15 08:00:00"), expr.valueOf()); } @Test public void invalidInput2() { - FunctionExpression expr = DSL.convert_tz(DSL.datetime( - DSL.literal("2008-05-15 22:00:00")), - DSL.literal("+)()"), - DSL.literal("+12:00")); + FunctionExpression expr = + DSL.convert_tz( + DSL.datetime(DSL.literal("2008-05-15 22:00:00")), + DSL.literal("+)()"), + DSL.literal("+12:00")); assertEquals(DATETIME, expr.type()); assertEquals(nullValue(), expr.valueOf()); } @Test public void invalidInput3() { - FunctionExpression expr = DSL.convert_tz(DSL.datetime( - DSL.literal("2008-05-15 22:00:00")), - DSL.literal("+00:00"), - DSL.literal("test")); + FunctionExpression expr = + DSL.convert_tz( + DSL.datetime(DSL.literal("2008-05-15 22:00:00")), + DSL.literal("+00:00"), + DSL.literal("test")); assertEquals(DATETIME, expr.type()); assertEquals(nullValue(), expr.valueOf()); } @Test public void invalidInput1() { - FunctionExpression expr = DSL.convert_tz( - DSL.literal("test"), - DSL.literal("+00:00"), - DSL.literal("+00:00")); + FunctionExpression expr = + DSL.convert_tz(DSL.literal("test"), DSL.literal("+00:00"), DSL.literal("+00:00")); assertEquals(DATETIME, expr.type()); assertEquals(nullValue(), expr.valueOf()); } @Test public void invalidDateFeb30() { - FunctionExpression expr = DSL.convert_tz(DSL.datetime( - DSL.literal("2021-02-30 10:00:00")), - DSL.literal("+00:00"), - DSL.literal("+00:00")); + FunctionExpression expr = + DSL.convert_tz( + DSL.datetime(DSL.literal("2021-02-30 10:00:00")), + DSL.literal("+00:00"), + DSL.literal("+00:00")); assertEquals(DATETIME, expr.type()); assertEquals(nullValue(), expr.valueOf()); } @Test public void invalidDateApril31() { - FunctionExpression expr = DSL.convert_tz(DSL.datetime( - DSL.literal("2021-04-31 10:00:00")), - DSL.literal("+00:00"), - DSL.literal("+00:00")); + FunctionExpression expr = + DSL.convert_tz( + DSL.datetime(DSL.literal("2021-04-31 10:00:00")), + DSL.literal("+00:00"), + DSL.literal("+00:00")); assertEquals(DATETIME, expr.type()); assertEquals(nullValue(), expr.valueOf()); } @Test public void invalidMonth13() { - FunctionExpression expr = DSL.convert_tz(DSL.datetime( - DSL.literal("2021-13-03 10:00:00")), - DSL.literal("+00:00"), - DSL.literal("+00:00")); + FunctionExpression expr = + DSL.convert_tz( + DSL.datetime(DSL.literal("2021-13-03 10:00:00")), + DSL.literal("+00:00"), + DSL.literal("+00:00")); assertEquals(DATETIME, expr.type()); assertEquals(nullValue(), expr.valueOf()); } diff --git a/core/src/test/java/org/opensearch/sql/expression/datetime/DateAddAndAddDateTest.java b/core/src/test/java/org/opensearch/sql/expression/datetime/DateAddAndAddDateTest.java index 973b168355..52db0a17e5 100644 --- a/core/src/test/java/org/opensearch/sql/expression/datetime/DateAddAndAddDateTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/datetime/DateAddAndAddDateTest.java @@ -35,8 +35,8 @@ public void adddate_returns_datetime_when_args_are_time_and_time_interval() { @Test public void date_add_returns_datetime_when_args_are_time_and_time_interval() { - var res = date_add(LocalTime.of(10, 20, 30), - Duration.ofHours(1).plusMinutes(2).plusSeconds(42)); + var res = + date_add(LocalTime.of(10, 20, 30), Duration.ofHours(1).plusMinutes(2).plusSeconds(42)); assertEquals(DATETIME, res.type()); assertEquals(LocalTime.of(11, 23, 12).atDate(today()), res.datetimeValue()); } @@ -50,8 +50,8 @@ public void adddate_time_limited_by_24_hours() { @Test public void date_add_time_limited_by_24_hours() { - var res = date_add(LocalTime.of(10, 20, 30), - Duration.ofHours(20).plusMinutes(50).plusSeconds(7)); + var res = + date_add(LocalTime.of(10, 20, 30), Duration.ofHours(20).plusMinutes(50).plusSeconds(7)); assertEquals(DATETIME, res.type()); assertEquals(LocalTime.of(7, 10, 37), res.datetimeValue().toLocalTime()); } @@ -108,8 +108,9 @@ public void adddate_returns_datetime_when_first_arg_is_datetime() { @Test public void date_add_returns_datetime_when_first_arg_is_timestamp() { - var res = date_add(LocalDateTime.of(1961, 4, 12, 9, 7).toInstant(ZoneOffset.UTC), - Duration.ofMinutes(108)); + var res = + date_add( + LocalDateTime.of(1961, 4, 12, 9, 7).toInstant(ZoneOffset.UTC), Duration.ofMinutes(108)); assertEquals(DATETIME, res.type()); assertEquals(LocalDateTime.of(1961, 4, 12, 10, 55), res.datetimeValue()); } @@ -127,10 +128,13 @@ public void adddate_has_second_signature_but_not_date_add() { var res = adddate(LocalDateTime.of(1961, 4, 12, 9, 7), 100500); assertEquals(DATETIME, res.type()); - var exception = assertThrows(ExpressionEvaluationException.class, - () -> date_add(LocalDateTime.of(1961, 4, 12, 9, 7), 100500)); - assertEquals("date_add function expected {[DATE,INTERVAL],[DATETIME,INTERVAL]," - + "[TIMESTAMP,INTERVAL],[TIME,INTERVAL]}, but get [DATETIME,INTEGER]", + var exception = + assertThrows( + ExpressionEvaluationException.class, + () -> date_add(LocalDateTime.of(1961, 4, 12, 9, 7), 100500)); + assertEquals( + "date_add function expected {[DATE,INTERVAL],[DATETIME,INTERVAL]," + + "[TIMESTAMP,INTERVAL],[TIME,INTERVAL]}, but get [DATETIME,INTEGER]", exception.getMessage()); } diff --git a/core/src/test/java/org/opensearch/sql/expression/datetime/DateDiffTest.java b/core/src/test/java/org/opensearch/sql/expression/datetime/DateDiffTest.java index 72c1ceba03..a630758456 100644 --- a/core/src/test/java/org/opensearch/sql/expression/datetime/DateDiffTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/datetime/DateDiffTest.java @@ -40,33 +40,26 @@ private static Stream getTestData() { Arguments.of(timeSample1, timeSample2, 0L), Arguments.of(timeSample1, dateNow, 0L), Arguments.of(timeSample1, LocalDateTime.now(), 0L), - Arguments.of(timeSample1, - Instant.now().plusMillis(TimeZone.getDefault().getRawOffset()), 0L), - Arguments.of(dateSample1, timeSample1, - -DAYS.between(dateSample1, dateNow)), - Arguments.of(dateSample1, dateSample3, - -DAYS.between(dateSample1, dateSample3)), - Arguments.of(dateSample1, dateTimeSample1, - -DAYS.between(dateSample1, dateSample2)), - Arguments.of(dateSample1, Instant.ofEpochSecond(42), - -DAYS.between(dateSample1, epochStart)), - Arguments.of(dateTimeSample1, LocalTime.now(), - -DAYS.between(dateSample2, dateNow)), - Arguments.of(dateTimeSample1, dateSample3, - -DAYS.between(dateSample2, dateSample3)), - Arguments.of(dateTimeSample1, dateTimeSample2, - -DAYS.between(dateSample2, dateSample3)), - Arguments.of(dateTimeSample1, Instant.ofEpochSecond(0), - -DAYS.between(dateSample2, epochStart)), - Arguments.of(Instant.ofEpochSecond(0), LocalTime.MAX, - -DAYS.between(epochStart, dateNow)), - Arguments.of(Instant.ofEpochSecond(0), dateSample3, - -DAYS.between(epochStart, dateSample3)), - Arguments.of(Instant.ofEpochSecond(0), dateTimeSample2, - -DAYS.between(epochStart, dateSample3)), - Arguments.of(Instant.ofEpochSecond(0), Instant.now(), - -DAYS.between(epochStart, LocalDateTime.now(ZoneId.of("UTC")))) - ); + Arguments.of( + timeSample1, Instant.now().plusMillis(TimeZone.getDefault().getRawOffset()), 0L), + Arguments.of(dateSample1, timeSample1, -DAYS.between(dateSample1, dateNow)), + Arguments.of(dateSample1, dateSample3, -DAYS.between(dateSample1, dateSample3)), + Arguments.of(dateSample1, dateTimeSample1, -DAYS.between(dateSample1, dateSample2)), + Arguments.of( + dateSample1, Instant.ofEpochSecond(42), -DAYS.between(dateSample1, epochStart)), + Arguments.of(dateTimeSample1, LocalTime.now(), -DAYS.between(dateSample2, dateNow)), + Arguments.of(dateTimeSample1, dateSample3, -DAYS.between(dateSample2, dateSample3)), + Arguments.of(dateTimeSample1, dateTimeSample2, -DAYS.between(dateSample2, dateSample3)), + Arguments.of( + dateTimeSample1, Instant.ofEpochSecond(0), -DAYS.between(dateSample2, epochStart)), + Arguments.of(Instant.ofEpochSecond(0), LocalTime.MAX, -DAYS.between(epochStart, dateNow)), + Arguments.of(Instant.ofEpochSecond(0), dateSample3, -DAYS.between(epochStart, dateSample3)), + Arguments.of( + Instant.ofEpochSecond(0), dateTimeSample2, -DAYS.between(epochStart, dateSample3)), + Arguments.of( + Instant.ofEpochSecond(0), + Instant.now(), + -DAYS.between(epochStart, LocalDateTime.now(ZoneId.of("UTC"))))); } @ParameterizedTest diff --git a/core/src/test/java/org/opensearch/sql/expression/datetime/DateSubAndSubDateTest.java b/core/src/test/java/org/opensearch/sql/expression/datetime/DateSubAndSubDateTest.java index 37c62313db..460e12384b 100644 --- a/core/src/test/java/org/opensearch/sql/expression/datetime/DateSubAndSubDateTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/datetime/DateSubAndSubDateTest.java @@ -35,8 +35,8 @@ public void subdate_returns_datetime_when_args_are_time_and_time_interval() { @Test public void date_sub_returns_datetime_when_args_are_time_and_time_interval() { - var res = date_sub(LocalTime.of(10, 20, 30), - Duration.ofHours(1).plusMinutes(2).plusSeconds(42)); + var res = + date_sub(LocalTime.of(10, 20, 30), Duration.ofHours(1).plusMinutes(2).plusSeconds(42)); assertEquals(DATETIME, res.type()); assertEquals(LocalTime.of(9, 17, 48).atDate(today()), res.datetimeValue()); } @@ -50,8 +50,8 @@ public void subdate_time_limited_by_24_hours() { @Test public void date_sub_time_limited_by_24_hours() { - var res = date_sub(LocalTime.of(10, 20, 30), - Duration.ofHours(20).plusMinutes(50).plusSeconds(7)); + var res = + date_sub(LocalTime.of(10, 20, 30), Duration.ofHours(20).plusMinutes(50).plusSeconds(7)); assertEquals(DATETIME, res.type()); assertEquals(LocalTime.of(13, 30, 23), res.datetimeValue().toLocalTime()); } @@ -108,8 +108,9 @@ public void subdate_returns_datetime_when_first_arg_is_datetime() { @Test public void date_sub_returns_datetime_when_first_arg_is_timestamp() { - var res = date_sub(LocalDateTime.of(1961, 4, 12, 9, 7).toInstant(ZoneOffset.UTC), - Duration.ofMinutes(108)); + var res = + date_sub( + LocalDateTime.of(1961, 4, 12, 9, 7).toInstant(ZoneOffset.UTC), Duration.ofMinutes(108)); assertEquals(DATETIME, res.type()); assertEquals(LocalDateTime.of(1961, 4, 12, 7, 19), res.datetimeValue()); } @@ -127,10 +128,13 @@ public void subdate_has_second_signature_but_not_date_sub() { var res = subdate(LocalDateTime.of(1961, 4, 12, 9, 7), 100500); assertEquals(DATETIME, res.type()); - var exception = assertThrows(ExpressionEvaluationException.class, - () -> date_sub(LocalDateTime.of(1961, 4, 12, 9, 7), 100500)); - assertEquals("date_sub function expected {[DATE,INTERVAL],[DATETIME,INTERVAL]," - + "[TIMESTAMP,INTERVAL],[TIME,INTERVAL]}, but get [DATETIME,INTEGER]", + var exception = + assertThrows( + ExpressionEvaluationException.class, + () -> date_sub(LocalDateTime.of(1961, 4, 12, 9, 7), 100500)); + assertEquals( + "date_sub function expected {[DATE,INTERVAL],[DATETIME,INTERVAL]," + + "[TIMESTAMP,INTERVAL],[TIME,INTERVAL]}, but get [DATETIME,INTEGER]", exception.getMessage()); } diff --git a/core/src/test/java/org/opensearch/sql/expression/datetime/DateTimeFunctionTest.java b/core/src/test/java/org/opensearch/sql/expression/datetime/DateTimeFunctionTest.java index f8abfe7580..c2a6129626 100644 --- a/core/src/test/java/org/opensearch/sql/expression/datetime/DateTimeFunctionTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/datetime/DateTimeFunctionTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.datetime; import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_YEAR; @@ -51,79 +50,81 @@ class DateTimeFunctionTest extends ExpressionTestBase { - final List dateFormatTesters = ImmutableList.of( - new DateFormatTester("1998-01-31 13:14:15.012345", - ImmutableList.of("%H","%I","%k","%l","%i","%p","%r","%S","%T"," %M", - "%W","%D","%Y","%y","%a","%b","%j","%m","%d","%h","%s","%w","%f", - "%q","%"), - ImmutableList.of("13","01","13","1","14","PM","01:14:15 PM","15","13:14:15"," January", - "Saturday","31st","1998","98","Sat","Jan","031","01","31","01","15","6","012345", - "q","%") - ), - new DateFormatTester("1999-12-01", - ImmutableList.of("%D"), - ImmutableList.of("1st") - ), - new DateFormatTester("1999-12-02", - ImmutableList.of("%D"), - ImmutableList.of("2nd") - ), - new DateFormatTester("1999-12-03", - ImmutableList.of("%D"), - ImmutableList.of("3rd") - ), - new DateFormatTester("1999-12-04", - ImmutableList.of("%D"), - ImmutableList.of("4th") - ), - new DateFormatTester("1999-12-11", - ImmutableList.of("%D"), - ImmutableList.of("11th") - ), - new DateFormatTester("1999-12-12", - ImmutableList.of("%D"), - ImmutableList.of("12th") - ), - new DateFormatTester("1999-12-13", - ImmutableList.of("%D"), - ImmutableList.of("13th") - ), - new DateFormatTester("1999-12-31", - ImmutableList.of("%x","%v","%X","%V","%u","%U"), - ImmutableList.of("1999", "52", "1999", "52", "52", "52") - ), - new DateFormatTester("2000-01-01", - ImmutableList.of("%x","%v","%X","%V","%u","%U"), - ImmutableList.of("1999", "52", "1999", "52", "0", "0") - ), - new DateFormatTester("1998-12-31", - ImmutableList.of("%x","%v","%X","%V","%u","%U"), - ImmutableList.of("1998", "52", "1998", "52", "52", "52") - ), - new DateFormatTester("1999-01-01", - ImmutableList.of("%x","%v","%X","%V","%u","%U"), - ImmutableList.of("1998", "52", "1998", "52", "0", "0") - ), - new DateFormatTester("2020-01-04", - ImmutableList.of("%x","%X"), - ImmutableList.of("2020", "2019") - ), - new DateFormatTester("2008-12-31", - ImmutableList.of("%v","%V","%u","%U"), - ImmutableList.of("53","52","53","52") - ), - new DateFormatTester("1998-01-31 13:14:15.012345", - ImmutableList.of("%Y-%m-%dT%TZ"), - ImmutableList.of("1998-01-31T13:14:15Z") - ), - new DateFormatTester("1998-01-31 13:14:15.012345", - ImmutableList.of("%Y-%m-%da %T a"), - ImmutableList.of("1998-01-31PM 13:14:15 PM") - ), - new DateFormatTester("1998-01-31 13:14:15.012345", - ImmutableList.of("%Y-%m-%db %T b"), - ImmutableList.of("1998-01-31b 13:14:15 b")) - ); + final List dateFormatTesters = + ImmutableList.of( + new DateFormatTester( + "1998-01-31 13:14:15.012345", + ImmutableList.of( + "%H", + "%I", "%k", "%l", "%i", "%p", "%r", "%S", "%T", " %M", "%W", "%D", "%Y", "%y", + "%a", "%b", "%j", "%m", "%d", "%h", "%s", "%w", "%f", "%q", "%"), + ImmutableList.of( + "13", + "01", + "13", + "1", + "14", + "PM", + "01:14:15 PM", + "15", + "13:14:15", + " January", + "Saturday", + "31st", + "1998", + "98", + "Sat", + "Jan", + "031", + "01", + "31", + "01", + "15", + "6", + "012345", + "q", + "%")), + new DateFormatTester("1999-12-01", ImmutableList.of("%D"), ImmutableList.of("1st")), + new DateFormatTester("1999-12-02", ImmutableList.of("%D"), ImmutableList.of("2nd")), + new DateFormatTester("1999-12-03", ImmutableList.of("%D"), ImmutableList.of("3rd")), + new DateFormatTester("1999-12-04", ImmutableList.of("%D"), ImmutableList.of("4th")), + new DateFormatTester("1999-12-11", ImmutableList.of("%D"), ImmutableList.of("11th")), + new DateFormatTester("1999-12-12", ImmutableList.of("%D"), ImmutableList.of("12th")), + new DateFormatTester("1999-12-13", ImmutableList.of("%D"), ImmutableList.of("13th")), + new DateFormatTester( + "1999-12-31", + ImmutableList.of("%x", "%v", "%X", "%V", "%u", "%U"), + ImmutableList.of("1999", "52", "1999", "52", "52", "52")), + new DateFormatTester( + "2000-01-01", + ImmutableList.of("%x", "%v", "%X", "%V", "%u", "%U"), + ImmutableList.of("1999", "52", "1999", "52", "0", "0")), + new DateFormatTester( + "1998-12-31", + ImmutableList.of("%x", "%v", "%X", "%V", "%u", "%U"), + ImmutableList.of("1998", "52", "1998", "52", "52", "52")), + new DateFormatTester( + "1999-01-01", + ImmutableList.of("%x", "%v", "%X", "%V", "%u", "%U"), + ImmutableList.of("1998", "52", "1998", "52", "0", "0")), + new DateFormatTester( + "2020-01-04", ImmutableList.of("%x", "%X"), ImmutableList.of("2020", "2019")), + new DateFormatTester( + "2008-12-31", + ImmutableList.of("%v", "%V", "%u", "%U"), + ImmutableList.of("53", "52", "53", "52")), + new DateFormatTester( + "1998-01-31 13:14:15.012345", + ImmutableList.of("%Y-%m-%dT%TZ"), + ImmutableList.of("1998-01-31T13:14:15Z")), + new DateFormatTester( + "1998-01-31 13:14:15.012345", + ImmutableList.of("%Y-%m-%da %T a"), + ImmutableList.of("1998-01-31PM 13:14:15 PM")), + new DateFormatTester( + "1998-01-31 13:14:15.012345", + ImmutableList.of("%Y-%m-%db %T b"), + ImmutableList.of("1998-01-31b 13:14:15 b"))); @AllArgsConstructor private class DateFormatTester { @@ -196,8 +197,8 @@ public void dayName() { @Test public void dayOfMonth() { - FunctionExpression expression = DSL.dayofmonth( - functionProperties, DSL.literal(new ExprDateValue("2020-08-07"))); + FunctionExpression expression = + DSL.dayofmonth(functionProperties, DSL.literal(new ExprDateValue("2020-08-07"))); assertEquals(INTEGER, expression.type()); assertEquals("dayofmonth(DATE '2020-08-07')", expression.toString()); assertEquals(integerValue(7), eval(expression)); @@ -215,23 +216,21 @@ private void testDayOfMonthWithUnderscores(FunctionExpression dateExpression, in @Test public void dayOfMonthWithUnderscores() { - FunctionExpression expression1 = DSL.dayofmonth( - functionProperties, DSL.literal(new ExprDateValue("2020-08-07"))); + FunctionExpression expression1 = + DSL.dayofmonth(functionProperties, DSL.literal(new ExprDateValue("2020-08-07"))); FunctionExpression expression2 = DSL.dayofmonth(functionProperties, DSL.literal("2020-07-08")); assertAll( () -> testDayOfMonthWithUnderscores(expression1, 7), () -> assertEquals("dayofmonth(DATE '2020-08-07')", expression1.toString()), - () -> testDayOfMonthWithUnderscores(expression2, 8), - () -> assertEquals("dayofmonth(\"2020-07-08\")", expression2.toString()) - ); + () -> assertEquals("dayofmonth(\"2020-07-08\")", expression2.toString())); } @Test public void testDayOfMonthWithTimeType() { - FunctionExpression expression = DSL.day_of_month( - functionProperties, DSL.literal(new ExprTimeValue("12:23:34"))); + FunctionExpression expression = + DSL.day_of_month(functionProperties, DSL.literal(new ExprTimeValue("12:23:34"))); assertEquals(INTEGER, eval(expression).type()); assertEquals( @@ -241,40 +240,35 @@ public void testDayOfMonthWithTimeType() { } private void testInvalidDayOfMonth(String date) { - FunctionExpression expression = DSL.day_of_month( - functionProperties, DSL.literal(new ExprDateValue(date))); + FunctionExpression expression = + DSL.day_of_month(functionProperties, DSL.literal(new ExprDateValue(date))); eval(expression); } @Test public void dayOfMonthWithUnderscoresLeapYear() { - //Feb. 29 of a leap year - testDayOfMonthWithUnderscores(DSL.day_of_month( - functionProperties, DSL.literal("2020-02-29")), 29); + // Feb. 29 of a leap year + testDayOfMonthWithUnderscores( + DSL.day_of_month(functionProperties, DSL.literal("2020-02-29")), 29); - //Feb. 29 of a non-leap year + // Feb. 29 of a non-leap year assertThrows(SemanticCheckException.class, () -> testInvalidDayOfMonth("2021-02-29")); } @Test public void dayOfMonthWithUnderscoresInvalidArguments() { assertAll( - //40th day of the month - () -> assertThrows( - SemanticCheckException.class, () -> testInvalidDayOfMonth("2021-02-40")), - //13th month of the year - () -> assertThrows( - SemanticCheckException.class, () -> testInvalidDayOfMonth("2021-13-40")), - //incorrect format - () -> assertThrows( - SemanticCheckException.class, () -> testInvalidDayOfMonth("asdfasdfasdf")) - ); - } - - private void dayOfWeekQuery( - FunctionExpression dateExpression, - int dayOfWeek, - String testExpr) { + // 40th day of the month + () -> assertThrows(SemanticCheckException.class, () -> testInvalidDayOfMonth("2021-02-40")), + // 13th month of the year + () -> assertThrows(SemanticCheckException.class, () -> testInvalidDayOfMonth("2021-13-40")), + // incorrect format + () -> + assertThrows( + SemanticCheckException.class, () -> testInvalidDayOfMonth("asdfasdfasdf"))); + } + + private void dayOfWeekQuery(FunctionExpression dateExpression, int dayOfWeek, String testExpr) { assertEquals(INTEGER, dateExpression.type()); assertEquals(integerValue(dayOfWeek), eval(dateExpression)); assertEquals(testExpr, dateExpression.toString()); @@ -282,34 +276,23 @@ private void dayOfWeekQuery( @Test public void dayOfWeek() { - FunctionExpression expression1 = DSL.dayofweek( - functionProperties, - DSL.literal(new ExprDateValue("2020-08-07"))); - FunctionExpression expression2 = DSL.dayofweek( - functionProperties, - DSL.literal(new ExprDateValue("2020-08-09"))); - FunctionExpression expression3 = DSL.dayofweek( - functionProperties, - DSL.literal("2020-08-09")); - FunctionExpression expression4 = DSL.dayofweek( - functionProperties, - DSL.literal("2020-08-09 01:02:03")); + FunctionExpression expression1 = + DSL.dayofweek(functionProperties, DSL.literal(new ExprDateValue("2020-08-07"))); + FunctionExpression expression2 = + DSL.dayofweek(functionProperties, DSL.literal(new ExprDateValue("2020-08-09"))); + FunctionExpression expression3 = DSL.dayofweek(functionProperties, DSL.literal("2020-08-09")); + FunctionExpression expression4 = + DSL.dayofweek(functionProperties, DSL.literal("2020-08-09 01:02:03")); assertAll( () -> dayOfWeekQuery(expression1, 6, "dayofweek(DATE '2020-08-07')"), - () -> dayOfWeekQuery(expression2, 1, "dayofweek(DATE '2020-08-09')"), - () -> dayOfWeekQuery(expression3, 1, "dayofweek(\"2020-08-09\")"), - - () -> dayOfWeekQuery(expression4, 1, "dayofweek(\"2020-08-09 01:02:03\")") - ); + () -> dayOfWeekQuery(expression4, 1, "dayofweek(\"2020-08-09 01:02:03\")")); } private void dayOfWeekWithUnderscoresQuery( - FunctionExpression dateExpression, - int dayOfWeek, - String testExpr) { + FunctionExpression dateExpression, int dayOfWeek, String testExpr) { assertEquals(INTEGER, dateExpression.type()); assertEquals(integerValue(dayOfWeek), eval(dateExpression)); assertEquals(testExpr, dateExpression.toString()); @@ -317,88 +300,80 @@ private void dayOfWeekWithUnderscoresQuery( @Test public void dayOfWeekWithUnderscores() { - FunctionExpression expression1 = DSL.day_of_week( - functionProperties, - DSL.literal(new ExprDateValue("2020-08-07"))); - FunctionExpression expression2 = DSL.day_of_week( - functionProperties, - DSL.literal(new ExprDateValue("2020-08-09"))); - FunctionExpression expression3 = DSL.day_of_week( - functionProperties, - DSL.literal("2020-08-09")); - FunctionExpression expression4 = DSL.day_of_week( - functionProperties, - DSL.literal("2020-08-09 01:02:03")); + FunctionExpression expression1 = + DSL.day_of_week(functionProperties, DSL.literal(new ExprDateValue("2020-08-07"))); + FunctionExpression expression2 = + DSL.day_of_week(functionProperties, DSL.literal(new ExprDateValue("2020-08-09"))); + FunctionExpression expression3 = DSL.day_of_week(functionProperties, DSL.literal("2020-08-09")); + FunctionExpression expression4 = + DSL.day_of_week(functionProperties, DSL.literal("2020-08-09 01:02:03")); assertAll( () -> dayOfWeekWithUnderscoresQuery(expression1, 6, "day_of_week(DATE '2020-08-07')"), - () -> dayOfWeekWithUnderscoresQuery(expression2, 1, "day_of_week(DATE '2020-08-09')"), - () -> dayOfWeekWithUnderscoresQuery(expression3, 1, "day_of_week(\"2020-08-09\")"), - - () -> dayOfWeekWithUnderscoresQuery( - expression4, 1, "day_of_week(\"2020-08-09 01:02:03\")") - ); + () -> + dayOfWeekWithUnderscoresQuery(expression4, 1, "day_of_week(\"2020-08-09 01:02:03\")")); } @Test public void testDayOfWeekWithTimeType() { - FunctionExpression expression = DSL.day_of_week( - functionProperties, DSL.literal(new ExprTimeValue("12:23:34"))); + FunctionExpression expression = + DSL.day_of_week(functionProperties, DSL.literal(new ExprTimeValue("12:23:34"))); assertAll( () -> assertEquals(INTEGER, eval(expression).type()), - () -> assertEquals(( - LocalDate.now( - functionProperties.getQueryStartClock()).getDayOfWeek().getValue() % 7) + 1, - eval(expression).integerValue()), - () -> assertEquals("day_of_week(TIME '12:23:34')", expression.toString()) - ); + () -> + assertEquals( + (LocalDate.now(functionProperties.getQueryStartClock()).getDayOfWeek().getValue() + % 7) + + 1, + eval(expression).integerValue()), + () -> assertEquals("day_of_week(TIME '12:23:34')", expression.toString())); } private void testInvalidDayOfWeek(String date) { - FunctionExpression expression = DSL.day_of_week( - functionProperties, DSL.literal(new ExprDateValue(date))); + FunctionExpression expression = + DSL.day_of_week(functionProperties, DSL.literal(new ExprDateValue(date))); eval(expression); } @Test public void dayOfWeekWithUnderscoresLeapYear() { assertAll( - //Feb. 29 of a leap year - () -> dayOfWeekWithUnderscoresQuery(DSL.day_of_week( - functionProperties, - DSL.literal("2020-02-29")), 7, "day_of_week(\"2020-02-29\")"), - //day after Feb. 29 of a leap year - () -> dayOfWeekWithUnderscoresQuery(DSL.day_of_week( - functionProperties, - DSL.literal("2020-03-01")), 1, "day_of_week(\"2020-03-01\")"), - //Feb. 28 of a non-leap year - () -> dayOfWeekWithUnderscoresQuery(DSL.day_of_week( - functionProperties, - DSL.literal("2021-02-28")), 1, "day_of_week(\"2021-02-28\")"), - //Feb. 29 of a non-leap year - () -> assertThrows( - SemanticCheckException.class, () -> testInvalidDayOfWeek("2021-02-29")) - ); + // Feb. 29 of a leap year + () -> + dayOfWeekWithUnderscoresQuery( + DSL.day_of_week(functionProperties, DSL.literal("2020-02-29")), + 7, + "day_of_week(\"2020-02-29\")"), + // day after Feb. 29 of a leap year + () -> + dayOfWeekWithUnderscoresQuery( + DSL.day_of_week(functionProperties, DSL.literal("2020-03-01")), + 1, + "day_of_week(\"2020-03-01\")"), + // Feb. 28 of a non-leap year + () -> + dayOfWeekWithUnderscoresQuery( + DSL.day_of_week(functionProperties, DSL.literal("2021-02-28")), + 1, + "day_of_week(\"2021-02-28\")"), + // Feb. 29 of a non-leap year + () -> assertThrows(SemanticCheckException.class, () -> testInvalidDayOfWeek("2021-02-29"))); } @Test public void dayOfWeekWithUnderscoresInvalidArgument() { assertAll( - //40th day of the month - () -> assertThrows(SemanticCheckException.class, - () -> testInvalidDayOfWeek("2021-02-40")), + // 40th day of the month + () -> assertThrows(SemanticCheckException.class, () -> testInvalidDayOfWeek("2021-02-40")), - //13th month of the year - () -> assertThrows(SemanticCheckException.class, - () -> testInvalidDayOfWeek("2021-13-29")), + // 13th month of the year + () -> assertThrows(SemanticCheckException.class, () -> testInvalidDayOfWeek("2021-13-29")), - //incorrect format - () -> assertThrows(SemanticCheckException.class, - () -> testInvalidDayOfWeek("asdfasdf")) - ); + // incorrect format + () -> assertThrows(SemanticCheckException.class, () -> testInvalidDayOfWeek("asdfasdf"))); } @Test @@ -421,40 +396,26 @@ public void dayOfYear() { private static Stream getTestDataForDayOfYear() { return Stream.of( - Arguments.of(DSL.literal( - new ExprDateValue("2020-08-07")), - "day_of_year(DATE '2020-08-07')", - 220), - Arguments.of(DSL.literal( - new ExprDatetimeValue("2020-08-07 12:23:34")), + Arguments.of( + DSL.literal(new ExprDateValue("2020-08-07")), "day_of_year(DATE '2020-08-07')", 220), + Arguments.of( + DSL.literal(new ExprDatetimeValue("2020-08-07 12:23:34")), "day_of_year(DATETIME '2020-08-07 12:23:34')", 220), - Arguments.of(DSL.literal( - new ExprTimestampValue("2020-08-07 12:23:34")), + Arguments.of( + DSL.literal(new ExprTimestampValue("2020-08-07 12:23:34")), "day_of_year(TIMESTAMP '2020-08-07 12:23:34')", 220), - Arguments.of(DSL.literal( - "2020-08-07"), - "day_of_year(\"2020-08-07\")", - 220), - Arguments.of(DSL.literal( - "2020-08-07 01:02:03"), - "day_of_year(\"2020-08-07 01:02:03\")", - 220) - ); + Arguments.of(DSL.literal("2020-08-07"), "day_of_year(\"2020-08-07\")", 220), + Arguments.of( + DSL.literal("2020-08-07 01:02:03"), "day_of_year(\"2020-08-07 01:02:03\")", 220)); } @ParameterizedTest(name = "{0}") @MethodSource("getTestDataForDayOfYear") public void dayOfYearWithUnderscores( - LiteralExpression arg, - String expectedString, - int expectedResult) { - validateStringFormat( - DSL.day_of_year(functionProperties, arg), - expectedString, - expectedResult - ); + LiteralExpression arg, String expectedString, int expectedResult) { + validateStringFormat(DSL.day_of_year(functionProperties, arg), expectedString, expectedResult); } @Test @@ -466,98 +427,81 @@ public void testDayOfYearWithTimeType() { } public void dayOfYearWithUnderscoresQuery(String date, int dayOfYear) { - FunctionExpression expression = DSL.day_of_year( - functionProperties, - DSL.literal(new ExprDateValue(date))); + FunctionExpression expression = + DSL.day_of_year(functionProperties, DSL.literal(new ExprDateValue(date))); assertAll( () -> assertEquals(INTEGER, expression.type()), - () -> assertEquals(integerValue(dayOfYear), eval(expression)) - ); + () -> assertEquals(integerValue(dayOfYear), eval(expression))); } @Test public void dayOfYearWithUnderscoresDifferentArgumentFormats() { - FunctionExpression expression1 = DSL.day_of_year( - functionProperties, - DSL.literal(new ExprDateValue("2020-08-07"))); - FunctionExpression expression2 = DSL.day_of_year( - functionProperties, - DSL.literal("2020-08-07")); - FunctionExpression expression3 = DSL.day_of_year( - functionProperties, - DSL.literal("2020-08-07 01:02:03")); + FunctionExpression expression1 = + DSL.day_of_year(functionProperties, DSL.literal(new ExprDateValue("2020-08-07"))); + FunctionExpression expression2 = DSL.day_of_year(functionProperties, DSL.literal("2020-08-07")); + FunctionExpression expression3 = + DSL.day_of_year(functionProperties, DSL.literal("2020-08-07 01:02:03")); assertAll( () -> dayOfYearWithUnderscoresQuery("2020-08-07", 220), () -> assertEquals("day_of_year(DATE '2020-08-07')", expression1.toString()), - () -> dayOfYearWithUnderscoresQuery("2020-08-07", 220), - () -> assertEquals("day_of_year(\"2020-08-07\")", expression2.toString()), - + () -> assertEquals("day_of_year(\"2020-08-07\")", expression2.toString()), () -> dayOfYearWithUnderscoresQuery("2020-08-07 01:02:03", 220), - () -> assertEquals("day_of_year(\"2020-08-07 01:02:03\")", expression3.toString()) - ); + () -> assertEquals("day_of_year(\"2020-08-07 01:02:03\")", expression3.toString())); } @Test public void dayOfYearWithUnderscoresCornerCaseDates() { assertAll( - //31st of December during non leap year (should be 365) + // 31st of December during non leap year (should be 365) () -> dayOfYearWithUnderscoresQuery("2019-12-31", 365), - //Year 1200 + // Year 1200 () -> dayOfYearWithUnderscoresQuery("1200-02-28", 59), - //Year 4000 - () -> dayOfYearWithUnderscoresQuery("4000-02-28", 59) - ); + // Year 4000 + () -> dayOfYearWithUnderscoresQuery("4000-02-28", 59)); } @Test public void dayOfYearWithUnderscoresLeapYear() { assertAll( - //28th of Feb + // 28th of Feb () -> dayOfYearWithUnderscoresQuery("2020-02-28", 59), - //29th of Feb during leap year + // 29th of Feb during leap year () -> dayOfYearWithUnderscoresQuery("2020-02-29 23:59:59", 60), () -> dayOfYearWithUnderscoresQuery("2020-02-29", 60), - //1st of March during leap year + // 1st of March during leap year () -> dayOfYearWithUnderscoresQuery("2020-03-01 00:00:00", 61), () -> dayOfYearWithUnderscoresQuery("2020-03-01", 61), - //1st of March during non leap year + // 1st of March during non leap year () -> dayOfYearWithUnderscoresQuery("2019-03-01", 60), - //31st of December during leap year (should be 366) - () -> dayOfYearWithUnderscoresQuery("2020-12-31", 366) - ); + // 31st of December during leap year (should be 366) + () -> dayOfYearWithUnderscoresQuery("2020-12-31", 366)); } private void invalidDayOfYearQuery(String date) { - FunctionExpression expression = DSL.day_of_year( - functionProperties, - DSL.literal(new ExprDateValue(date))); + FunctionExpression expression = + DSL.day_of_year(functionProperties, DSL.literal(new ExprDateValue(date))); eval(expression); } @Test public void invalidDayOfYearArgument() { assertAll( - //29th of Feb non-leapyear - () -> assertThrows( - SemanticCheckException.class, - () -> invalidDayOfYearQuery("2019-02-29")), + // 29th of Feb non-leapyear + () -> assertThrows(SemanticCheckException.class, () -> invalidDayOfYearQuery("2019-02-29")), - //13th month - () -> assertThrows( - SemanticCheckException.class, - () -> invalidDayOfYearQuery("2019-13-15")), + // 13th month + () -> assertThrows(SemanticCheckException.class, () -> invalidDayOfYearQuery("2019-13-15")), - //incorrect format for type - () -> assertThrows( - SemanticCheckException.class, - () -> invalidDayOfYearQuery("asdfasdfasdf")) - ); + // incorrect format for type + () -> + assertThrows( + SemanticCheckException.class, () -> invalidDayOfYearQuery("asdfasdfasdf"))); } @Test @@ -589,13 +533,11 @@ private static Stream getTestDataForGetFormat() { Arguments.of("TIMESTAMP", "JIS", "%Y-%m-%d %H:%i:%s"), Arguments.of("TIMESTAMP", "ISO", "%Y-%m-%d %H:%i:%s"), Arguments.of("TIMESTAMP", "EUR", "%Y-%m-%d %H.%i.%s"), - Arguments.of("TIMESTAMP", "INTERNAL", "%Y%m%d%H%i%s") - ); + Arguments.of("TIMESTAMP", "INTERNAL", "%Y%m%d%H%i%s")); } - private void getFormatQuery(LiteralExpression argType, - LiteralExpression namedFormat, - String expectedResult) { + private void getFormatQuery( + LiteralExpression argType, LiteralExpression namedFormat, String expectedResult) { FunctionExpression expr = DSL.get_format(argType, namedFormat); assertEquals(STRING, expr.type()); assertEquals(expectedResult, eval(expr).stringValue()); @@ -603,20 +545,13 @@ private void getFormatQuery(LiteralExpression argType, @ParameterizedTest(name = "{0}{1}") @MethodSource("getTestDataForGetFormat") - public void testGetFormat(String arg, - String format, - String expectedResult) { - getFormatQuery( - DSL.literal(arg), - DSL.literal(new ExprStringValue(format)), - expectedResult); + public void testGetFormat(String arg, String format, String expectedResult) { + getFormatQuery(DSL.literal(arg), DSL.literal(new ExprStringValue(format)), expectedResult); } @Test public void testGetFormatInvalidFormat() { - FunctionExpression expr = DSL.get_format( - DSL.literal("DATE"), - DSL.literal("1SA")); + FunctionExpression expr = DSL.get_format(DSL.literal("DATE"), DSL.literal("1SA")); assertEquals(nullValue(), eval(expr)); } @@ -655,25 +590,20 @@ private void testInvalidMinuteOfDay(String date) { @Test public void invalidMinuteOfDay() { - assertThrows(SemanticCheckException.class, - () -> testInvalidMinuteOfDay("2022-12-14 12:23:3400")); - assertThrows(SemanticCheckException.class, - () -> testInvalidMinuteOfDay("2022-12-14 12:2300:34")); - assertThrows(SemanticCheckException.class, - () -> testInvalidMinuteOfDay("2022-12-14 1200:23:34")); - assertThrows(SemanticCheckException.class, - () -> testInvalidMinuteOfDay("2022-12-1400 12:23:34")); - assertThrows(SemanticCheckException.class, - () -> testInvalidMinuteOfDay("2022-1200-14 12:23:34")); - assertThrows(SemanticCheckException.class, - () -> testInvalidMinuteOfDay("12:23:3400")); - assertThrows(SemanticCheckException.class, - () -> testInvalidMinuteOfDay("12:2300:34")); - assertThrows(SemanticCheckException.class, - () -> testInvalidMinuteOfDay("1200:23:34")); - assertThrows(SemanticCheckException.class, - () -> testInvalidMinuteOfDay("asdfasdfasdf")); - + assertThrows( + SemanticCheckException.class, () -> testInvalidMinuteOfDay("2022-12-14 12:23:3400")); + assertThrows( + SemanticCheckException.class, () -> testInvalidMinuteOfDay("2022-12-14 12:2300:34")); + assertThrows( + SemanticCheckException.class, () -> testInvalidMinuteOfDay("2022-12-14 1200:23:34")); + assertThrows( + SemanticCheckException.class, () -> testInvalidMinuteOfDay("2022-12-1400 12:23:34")); + assertThrows( + SemanticCheckException.class, () -> testInvalidMinuteOfDay("2022-1200-14 12:23:34")); + assertThrows(SemanticCheckException.class, () -> testInvalidMinuteOfDay("12:23:3400")); + assertThrows(SemanticCheckException.class, () -> testInvalidMinuteOfDay("12:2300:34")); + assertThrows(SemanticCheckException.class, () -> testInvalidMinuteOfDay("1200:23:34")); + assertThrows(SemanticCheckException.class, () -> testInvalidMinuteOfDay("asdfasdfasdf")); } private void hourOfDayQuery(FunctionExpression dateExpression, int hour) { @@ -685,28 +615,23 @@ private void hourOfDayQuery(FunctionExpression dateExpression, int hour) { public void hourOfDay() { FunctionExpression expression1 = DSL.hour_of_day(DSL.literal(new ExprTimeValue("01:02:03"))); FunctionExpression expression2 = DSL.hour_of_day(DSL.literal("01:02:03")); - FunctionExpression expression3 = DSL.hour_of_day( - DSL.literal(new ExprTimestampValue("2020-08-17 01:02:03"))); - FunctionExpression expression4 = DSL.hour_of_day( - DSL.literal(new ExprDatetimeValue("2020-08-17 01:02:03"))); + FunctionExpression expression3 = + DSL.hour_of_day(DSL.literal(new ExprTimestampValue("2020-08-17 01:02:03"))); + FunctionExpression expression4 = + DSL.hour_of_day(DSL.literal(new ExprDatetimeValue("2020-08-17 01:02:03"))); FunctionExpression expression5 = DSL.hour_of_day(DSL.literal("2020-08-17 01:02:03")); assertAll( () -> hourOfDayQuery(expression1, 1), () -> assertEquals("hour_of_day(TIME '01:02:03')", expression1.toString()), - () -> hourOfDayQuery(expression2, 1), () -> assertEquals("hour_of_day(\"01:02:03\")", expression2.toString()), - () -> hourOfDayQuery(expression3, 1), () -> assertEquals("hour_of_day(TIMESTAMP '2020-08-17 01:02:03')", expression3.toString()), - () -> hourOfDayQuery(expression4, 1), () -> assertEquals("hour_of_day(DATETIME '2020-08-17 01:02:03')", expression4.toString()), - () -> hourOfDayQuery(expression5, 1), - () -> assertEquals("hour_of_day(\"2020-08-17 01:02:03\")", expression5.toString()) - ); + () -> assertEquals("hour_of_day(\"2020-08-17 01:02:03\")", expression5.toString())); } private void invalidHourOfDayQuery(String time) { @@ -717,24 +642,20 @@ private void invalidHourOfDayQuery(String time) { @Test public void hourOfDayInvalidArguments() { assertAll( - //Invalid Seconds + // Invalid Seconds () -> assertThrows(SemanticCheckException.class, () -> invalidHourOfDayQuery("12:23:61")), - //Invalid Minutes + // Invalid Minutes () -> assertThrows(SemanticCheckException.class, () -> invalidHourOfDayQuery("12:61:34")), - //Invalid Hours + // Invalid Hours () -> assertThrows(SemanticCheckException.class, () -> invalidHourOfDayQuery("25:23:34")), - //incorrect format - () -> assertThrows(SemanticCheckException.class, () -> invalidHourOfDayQuery("asdfasdf")) - ); - + // incorrect format + () -> assertThrows(SemanticCheckException.class, () -> invalidHourOfDayQuery("asdfasdf"))); } private void checkForExpectedDay( - FunctionExpression functionExpression, - String expectedDay, - String testExpr) { + FunctionExpression functionExpression, String expectedDay, String testExpr) { assertEquals(DATE, functionExpression.type()); assertEquals(new ExprDateValue(expectedDay), eval(functionExpression)); assertEquals(testExpr, functionExpression.toString()); @@ -743,9 +664,9 @@ private void checkForExpectedDay( private static Stream getTestDataForLastDay() { return Stream.of( Arguments.of(new ExprDateValue("2017-01-20"), "2017-01-31", "last_day(DATE '2017-01-20')"), - //Leap year + // Leap year Arguments.of(new ExprDateValue("2020-02-20"), "2020-02-29", "last_day(DATE '2020-02-20')"), - //Non leap year + // Non leap year Arguments.of(new ExprDateValue("2017-02-20"), "2017-02-28", "last_day(DATE '2017-02-20')"), Arguments.of(new ExprDateValue("2017-03-20"), "2017-03-31", "last_day(DATE '2017-03-20')"), Arguments.of(new ExprDateValue("2017-04-20"), "2017-04-30", "last_day(DATE '2017-04-20')"), @@ -756,8 +677,7 @@ private static Stream getTestDataForLastDay() { Arguments.of(new ExprDateValue("2017-09-20"), "2017-09-30", "last_day(DATE '2017-09-20')"), Arguments.of(new ExprDateValue("2017-10-20"), "2017-10-31", "last_day(DATE '2017-10-20')"), Arguments.of(new ExprDateValue("2017-11-20"), "2017-11-30", "last_day(DATE '2017-11-20')"), - Arguments.of(new ExprDateValue("2017-12-20"), "2017-12-31", "last_day(DATE '2017-12-20')") - ); + Arguments.of(new ExprDateValue("2017-12-20"), "2017-12-31", "last_day(DATE '2017-12-20')")); } @ParameterizedTest(name = "{2}") @@ -766,40 +686,37 @@ public void testLastDay(ExprValue testedDateTime, String expectedResult, String checkForExpectedDay( DSL.last_day(functionProperties, DSL.literal(testedDateTime)), expectedResult, - expectedQuery - ); + expectedQuery); } @Test public void testLastDayWithTimeType() { - FunctionExpression expression = DSL.last_day( - functionProperties, DSL.literal(new ExprTimeValue("12:23:34"))); + FunctionExpression expression = + DSL.last_day(functionProperties, DSL.literal(new ExprTimeValue("12:23:34"))); LocalDate expected = LocalDate.now(functionProperties.getQueryStartClock()); LocalDate result = eval(expression).dateValue(); - assertAll( () -> assertEquals((expected.lengthOfMonth()), result.getDayOfMonth()), - () -> assertEquals("last_day(TIME '12:23:34')", expression.toString()) - ); + () -> assertEquals("last_day(TIME '12:23:34')", expression.toString())); } private void lastDay(String date) { - FunctionExpression expression = DSL.day_of_week( - functionProperties, DSL.literal(new ExprDateValue(date))); + FunctionExpression expression = + DSL.day_of_week(functionProperties, DSL.literal(new ExprDateValue(date))); eval(expression); } @Test public void testLastDayInvalidArgument() { - assertThrows(SemanticCheckException.class, () -> lastDay("asdfasdf")); + assertThrows(SemanticCheckException.class, () -> lastDay("asdfasdf")); } @Test public void microsecond() { - FunctionExpression expression = DSL - .microsecond(DSL.literal(new ExprTimeValue("01:02:03.123456"))); + FunctionExpression expression = + DSL.microsecond(DSL.literal(new ExprTimeValue("01:02:03.123456"))); assertEquals(INTEGER, expression.type()); assertEquals(integerValue(123456), eval(expression)); assertEquals("microsecond(TIME '01:02:03.123456')", expression.toString()); @@ -904,20 +821,14 @@ private void minuteOfHourQuery(FunctionExpression dateExpression, int minute, St assertAll( () -> assertEquals(INTEGER, dateExpression.type()), () -> assertEquals(integerValue(minute), eval(dateExpression)), - () -> assertEquals(testExpr, dateExpression.toString()) - ); + () -> assertEquals(testExpr, dateExpression.toString())); } private static Stream getTestDataForMinuteOfHour() { return Stream.of( Arguments.of( - DSL.literal(new ExprTimeValue("01:02:03")), - 2, - "minute_of_hour(TIME '01:02:03')"), - Arguments.of( - DSL.literal("01:02:03"), - 2, - "minute_of_hour(\"01:02:03\")"), + DSL.literal(new ExprTimeValue("01:02:03")), 2, "minute_of_hour(TIME '01:02:03')"), + Arguments.of(DSL.literal("01:02:03"), 2, "minute_of_hour(\"01:02:03\")"), Arguments.of( DSL.literal(new ExprTimestampValue("2020-08-17 01:02:03")), 2, @@ -927,10 +838,7 @@ private static Stream getTestDataForMinuteOfHour() { 2, "minute_of_hour(DATETIME '2020-08-17 01:02:03')"), Arguments.of( - DSL.literal("2020-08-17 01:02:03"), - 2, - "minute_of_hour(\"2020-08-17 01:02:03\")") - ); + DSL.literal("2020-08-17 01:02:03"), 2, "minute_of_hour(\"2020-08-17 01:02:03\")")); } @ParameterizedTest(name = "{2}") @@ -947,29 +855,23 @@ private void invalidMinuteOfHourQuery(String time) { @Test public void minuteOfHourInvalidArguments() { assertAll( - //Invalid Seconds - () -> assertThrows( - SemanticCheckException.class, - () -> invalidMinuteOfHourQuery("12:23:61")), + // Invalid Seconds + () -> + assertThrows(SemanticCheckException.class, () -> invalidMinuteOfHourQuery("12:23:61")), - //Invalid Minutes - () -> assertThrows( - SemanticCheckException.class, - () -> invalidMinuteOfHourQuery("12:61:34")), + // Invalid Minutes + () -> + assertThrows(SemanticCheckException.class, () -> invalidMinuteOfHourQuery("12:61:34")), - //Invalid Hours - () -> assertThrows( - SemanticCheckException.class, - () -> invalidMinuteOfHourQuery("25:23:34")), + // Invalid Hours + () -> + assertThrows(SemanticCheckException.class, () -> invalidMinuteOfHourQuery("25:23:34")), - //incorrect format - () -> assertThrows( - SemanticCheckException.class, - () -> invalidMinuteOfHourQuery("asdfasdf")) - ); + // incorrect format + () -> + assertThrows(SemanticCheckException.class, () -> invalidMinuteOfHourQuery("asdfasdf"))); } - @Test public void month() { FunctionExpression expression = DSL.month(DSL.literal(new ExprDateValue("2020-08-07"))); @@ -991,9 +893,7 @@ public void month() { private static Stream getTestDataForMonthOfYear() { return Stream.of( Arguments.of( - DSL.literal(new ExprDateValue("2020-08-07")), - "month_of_year(DATE '2020-08-07')", - 8), + DSL.literal(new ExprDateValue("2020-08-07")), "month_of_year(DATE '2020-08-07')", 8), Arguments.of( DSL.literal(new ExprDatetimeValue("2020-08-07 12:23:34")), "month_of_year(DATETIME '2020-08-07 12:23:34')", @@ -1002,25 +902,16 @@ private static Stream getTestDataForMonthOfYear() { DSL.literal(new ExprTimestampValue("2020-08-07 12:23:34")), "month_of_year(TIMESTAMP '2020-08-07 12:23:34')", 8), + Arguments.of(DSL.literal("2020-08-07"), "month_of_year(\"2020-08-07\")", 8), Arguments.of( - DSL.literal("2020-08-07"), - "month_of_year(\"2020-08-07\")", - 8), - Arguments.of( - DSL.literal("2020-08-07 01:02:03"), - "month_of_year(\"2020-08-07 01:02:03\")", - 8) - ); + DSL.literal("2020-08-07 01:02:03"), "month_of_year(\"2020-08-07 01:02:03\")", 8)); } @ParameterizedTest(name = "{0}") @MethodSource("getTestDataForMonthOfYear") public void monthOfYear(LiteralExpression arg, String expectedString, int expectedResult) { validateStringFormat( - DSL.month_of_year(functionProperties, arg), - expectedString, - expectedResult - ); + DSL.month_of_year(functionProperties, arg), expectedString, expectedResult); } @Test @@ -1032,41 +923,34 @@ public void testMonthOfYearWithTimeType() { } private void invalidDatesQuery(String date) throws SemanticCheckException { - FunctionExpression expression = DSL.month_of_year( - functionProperties, - DSL.literal(new ExprDateValue(date))); + FunctionExpression expression = + DSL.month_of_year(functionProperties, DSL.literal(new ExprDateValue(date))); eval(expression); } @Test public void monthOfYearInvalidDates() { assertAll( - () -> assertThrows(SemanticCheckException.class, () -> invalidDatesQuery("2019-01-50")), - () -> assertThrows(SemanticCheckException.class, () -> invalidDatesQuery("2019-02-29")), - () -> assertThrows(SemanticCheckException.class, () -> invalidDatesQuery("2019-02-31")), - () -> assertThrows(SemanticCheckException.class, () -> invalidDatesQuery("2019-13-05")) - ); + () -> assertThrows(SemanticCheckException.class, () -> invalidDatesQuery("2019-01-50")), + () -> assertThrows(SemanticCheckException.class, () -> invalidDatesQuery("2019-02-29")), + () -> assertThrows(SemanticCheckException.class, () -> invalidDatesQuery("2019-02-31")), + () -> assertThrows(SemanticCheckException.class, () -> invalidDatesQuery("2019-13-05"))); } @Test public void monthOfYearAlternateArgumentSyntaxes() { - FunctionExpression expression = DSL.month_of_year( - functionProperties, - DSL.literal(new ExprDateValue("2020-08-07"))); + FunctionExpression expression = + DSL.month_of_year(functionProperties, DSL.literal(new ExprDateValue("2020-08-07"))); assertEquals(INTEGER, expression.type()); assertEquals("month_of_year(DATE '2020-08-07')", expression.toString()); assertEquals(integerValue(8), eval(expression)); - expression = DSL.month_of_year( - functionProperties, - DSL.literal("2020-08-07")); + expression = DSL.month_of_year(functionProperties, DSL.literal("2020-08-07")); assertEquals(INTEGER, expression.type()); assertEquals("month_of_year(\"2020-08-07\")", expression.toString()); assertEquals(integerValue(8), eval(expression)); - expression = DSL.month_of_year( - functionProperties, - DSL.literal("2020-08-07 01:02:03")); + expression = DSL.month_of_year(functionProperties, DSL.literal("2020-08-07 01:02:03")); assertEquals(INTEGER, expression.type()); assertEquals("month_of_year(\"2020-08-07 01:02:03\")", expression.toString()); assertEquals(integerValue(8), eval(expression)); @@ -1117,15 +1001,13 @@ private static Stream getTestDataForSecToTime() { Arguments.of(-169200, "01:00:00"), Arguments.of(3600, "01:00:00"), Arguments.of(90000, "01:00:00"), - Arguments.of(176400, "01:00:00") - ); + Arguments.of(176400, "01:00:00")); } @ParameterizedTest(name = "{0}") @MethodSource("getTestDataForSecToTime") public void testSecToTime(int seconds, String expected) { - FunctionExpression expr = DSL.sec_to_time( - DSL.literal(new ExprIntegerValue(seconds))); + FunctionExpression expr = DSL.sec_to_time(DSL.literal(new ExprIntegerValue(seconds))); assertEquals(TIME, expr.type()); assertEquals(new ExprTimeValue(expected), eval(expr)); @@ -1137,8 +1019,7 @@ private static Stream getTestDataForSecToTimeWithDecimal() { Arguments.of(1.00123, "00:00:01.00123"), Arguments.of(1.001023, "00:00:01.001023"), Arguments.of(1.000000042, "00:00:01.000000042"), - Arguments.of(3.14, "00:00:03.14") - ); + Arguments.of(3.14, "00:00:03.14")); } @ParameterizedTest(name = "{0}") @@ -1187,28 +1068,18 @@ private void secondOfMinuteQuery(FunctionExpression dateExpression, int second, private static Stream getTestDataForSecondOfMinute() { return Stream.of( Arguments.of( - DSL.literal(new ExprTimeValue("01:02:03")), - 3, - "second_of_minute(TIME '01:02:03')"), - Arguments.of( - DSL.literal("01:02:03"), - 3, - "second_of_minute(\"01:02:03\")"), + DSL.literal(new ExprTimeValue("01:02:03")), 3, "second_of_minute(TIME '01:02:03')"), + Arguments.of(DSL.literal("01:02:03"), 3, "second_of_minute(\"01:02:03\")"), Arguments.of( - DSL.literal("2020-08-17 01:02:03"), - 3, - "second_of_minute(\"2020-08-17 01:02:03\")"), + DSL.literal("2020-08-17 01:02:03"), 3, "second_of_minute(\"2020-08-17 01:02:03\")"), Arguments.of( - DSL.literal(new ExprTimestampValue("2020-08-17 01:02:03")), 3, "second_of_minute(TIMESTAMP '2020-08-17 01:02:03')"), Arguments.of( - DSL.literal(new ExprDatetimeValue("2020-08-17 01:02:03")), 3, - "second_of_minute(DATETIME '2020-08-17 01:02:03')") - ); + "second_of_minute(DATETIME '2020-08-17 01:02:03')")); } @ParameterizedTest(name = "{2}") @@ -1225,19 +1096,22 @@ private void invalidSecondOfMinuteQuery(String time) { @Test public void secondOfMinuteInvalidArguments() { assertAll( - //Invalid Seconds - () -> assertThrows(SemanticCheckException.class, - () -> invalidSecondOfMinuteQuery("12:23:61")), - //Invalid Minutes - () -> assertThrows(SemanticCheckException.class, - () -> invalidSecondOfMinuteQuery("12:61:34")), - //Invalid Hours - () -> assertThrows(SemanticCheckException.class, - () -> invalidSecondOfMinuteQuery("25:23:34")), - //incorrect format - () -> assertThrows(SemanticCheckException.class, - () -> invalidSecondOfMinuteQuery("asdfasdf")) - ); + // Invalid Seconds + () -> + assertThrows( + SemanticCheckException.class, () -> invalidSecondOfMinuteQuery("12:23:61")), + // Invalid Minutes + () -> + assertThrows( + SemanticCheckException.class, () -> invalidSecondOfMinuteQuery("12:61:34")), + // Invalid Hours + () -> + assertThrows( + SemanticCheckException.class, () -> invalidSecondOfMinuteQuery("25:23:34")), + // incorrect format + () -> + assertThrows( + SemanticCheckException.class, () -> invalidSecondOfMinuteQuery("asdfasdf"))); } @Test @@ -1304,35 +1178,32 @@ public void timestamp() { } private void weekQuery(String date, int mode, int expectedResult) { - FunctionExpression expression = DSL - .week(functionProperties, DSL.literal(new ExprDateValue(date)), DSL.literal(mode)); + FunctionExpression expression = + DSL.week(functionProperties, DSL.literal(new ExprDateValue(date)), DSL.literal(mode)); assertEquals(INTEGER, expression.type()); assertEquals(String.format("week(DATE '%s', %d)", date, mode), expression.toString()); assertEquals(integerValue(expectedResult), eval(expression)); } private void weekOfYearUnderscoresQuery(String date, int mode, int expectedResult) { - FunctionExpression expression = DSL - .week_of_year( - functionProperties, - DSL.literal(new ExprDateValue(date)), DSL.literal(mode)); + FunctionExpression expression = + DSL.week_of_year( + functionProperties, DSL.literal(new ExprDateValue(date)), DSL.literal(mode)); assertEquals(INTEGER, expression.type()); assertEquals(String.format("week_of_year(DATE '%s', %d)", date, mode), expression.toString()); assertEquals(integerValue(expectedResult), eval(expression)); } private void weekOfYearQuery(String date, int mode, int expectedResult) { - FunctionExpression expression = DSL - .weekofyear( - functionProperties, - DSL.literal(new ExprDateValue(date)), DSL.literal(mode)); + FunctionExpression expression = + DSL.weekofyear(functionProperties, DSL.literal(new ExprDateValue(date)), DSL.literal(mode)); assertEquals(INTEGER, expression.type()); assertEquals(String.format("weekofyear(DATE '%s', %d)", date, mode), expression.toString()); assertEquals(integerValue(expectedResult), eval(expression)); } private static Stream getTestDataForWeek() { - //Test the behavior of different modes passed into the 'week_of_year' function + // Test the behavior of different modes passed into the 'week_of_year' function return Stream.of( Arguments.of("2019-01-05", 0, 0), Arguments.of("2019-01-05", 1, 1), @@ -1342,7 +1213,6 @@ private static Stream getTestDataForWeek() { Arguments.of("2019-01-05", 5, 0), Arguments.of("2019-01-05", 6, 1), Arguments.of("2019-01-05", 7, 53), - Arguments.of("2019-01-06", 0, 1), Arguments.of("2019-01-06", 1, 1), Arguments.of("2019-01-06", 2, 1), @@ -1351,7 +1221,6 @@ private static Stream getTestDataForWeek() { Arguments.of("2019-01-06", 5, 0), Arguments.of("2019-01-06", 6, 2), Arguments.of("2019-01-06", 7, 53), - Arguments.of("2019-01-07", 0, 1), Arguments.of("2019-01-07", 1, 2), Arguments.of("2019-01-07", 2, 1), @@ -1360,11 +1229,9 @@ private static Stream getTestDataForWeek() { Arguments.of("2019-01-07", 5, 1), Arguments.of("2019-01-07", 6, 2), Arguments.of("2019-01-07", 7, 1), - Arguments.of("2000-01-01", 0, 0), Arguments.of("2000-01-01", 2, 52), - Arguments.of("1999-12-31", 0, 52) - ); + Arguments.of("1999-12-31", 0, 52)); } @ParameterizedTest(name = "{1}{2}") @@ -1376,145 +1243,130 @@ public void testWeek(String date, int mode, int expected) { } private void validateStringFormat( - FunctionExpression expr, - String expectedString, - int expectedResult) { + FunctionExpression expr, String expectedString, int expectedResult) { assertAll( () -> assertEquals(INTEGER, expr.type()), () -> assertEquals(expectedString, expr.toString()), - () -> assertEquals(integerValue(expectedResult), eval(expr)) - ); + () -> assertEquals(integerValue(expectedResult), eval(expr))); } private static Stream getTestDataForWeekFormats() { return Stream.of( - Arguments.of(DSL.literal(new ExprDateValue("2019-01-05")), - "DATE '2019-01-05'", - 0), - Arguments.of(DSL.literal(new ExprDatetimeValue("2019-01-05 01:02:03")), + Arguments.of(DSL.literal(new ExprDateValue("2019-01-05")), "DATE '2019-01-05'", 0), + Arguments.of( + DSL.literal(new ExprDatetimeValue("2019-01-05 01:02:03")), "DATETIME '2019-01-05 01:02:03'", 0), - Arguments.of(DSL.literal(new ExprTimestampValue("2019-01-05 01:02:03")), - "TIMESTAMP '2019-01-05 01:02:03'", - 0), Arguments.of( - DSL.literal("2019-01-05"), - "\"2019-01-05\"", + DSL.literal(new ExprTimestampValue("2019-01-05 01:02:03")), + "TIMESTAMP '2019-01-05 01:02:03'", 0), - Arguments.of( - DSL.literal("2019-01-05 00:01:00"), - "\"2019-01-05 00:01:00\"", - 0) - ); + Arguments.of(DSL.literal("2019-01-05"), "\"2019-01-05\"", 0), + Arguments.of(DSL.literal("2019-01-05 00:01:00"), "\"2019-01-05 00:01:00\"", 0)); } @ParameterizedTest(name = "{0}") @MethodSource("getTestDataForWeekFormats") public void testWeekFormats( - LiteralExpression arg, - String expectedString, - Integer expectedInteger) { + LiteralExpression arg, String expectedString, Integer expectedInteger) { validateStringFormat( DSL.week(functionProperties, arg), - String.format("week(%s)", expectedString), expectedInteger); + String.format("week(%s)", expectedString), + expectedInteger); validateStringFormat( DSL.week_of_year(functionProperties, arg), - String.format("week_of_year(%s)", expectedString), expectedInteger); + String.format("week_of_year(%s)", expectedString), + expectedInteger); validateStringFormat( DSL.weekofyear(functionProperties, arg), - String.format("weekofyear(%s)", expectedString), expectedInteger); + String.format("weekofyear(%s)", expectedString), + expectedInteger); } @Test public void testWeekOfYearWithTimeType() { assertAll( - () -> validateStringFormat( - DSL.week( - functionProperties, - DSL.literal(new ExprTimeValue("12:23:34")), - DSL.literal(0)), - "week(TIME '12:23:34', 0)", - LocalDate.now(functionProperties.getQueryStartClock()).get(ALIGNED_WEEK_OF_YEAR)), - - () -> validateStringFormat( - DSL.week_of_year(functionProperties, DSL.literal(new ExprTimeValue("12:23:34"))), - "week_of_year(TIME '12:23:34')", - LocalDate.now(functionProperties.getQueryStartClock()).get(ALIGNED_WEEK_OF_YEAR)), - - () -> validateStringFormat( - DSL.weekofyear(functionProperties, DSL.literal(new ExprTimeValue("12:23:34"))), - "weekofyear(TIME '12:23:34')", - LocalDate.now(functionProperties.getQueryStartClock()).get(ALIGNED_WEEK_OF_YEAR)) - ); + () -> + validateStringFormat( + DSL.week( + functionProperties, DSL.literal(new ExprTimeValue("12:23:34")), DSL.literal(0)), + "week(TIME '12:23:34', 0)", + LocalDate.now(functionProperties.getQueryStartClock()).get(ALIGNED_WEEK_OF_YEAR)), + () -> + validateStringFormat( + DSL.week_of_year(functionProperties, DSL.literal(new ExprTimeValue("12:23:34"))), + "week_of_year(TIME '12:23:34')", + LocalDate.now(functionProperties.getQueryStartClock()).get(ALIGNED_WEEK_OF_YEAR)), + () -> + validateStringFormat( + DSL.weekofyear(functionProperties, DSL.literal(new ExprTimeValue("12:23:34"))), + "weekofyear(TIME '12:23:34')", + LocalDate.now(functionProperties.getQueryStartClock()).get(ALIGNED_WEEK_OF_YEAR))); } @Test public void modeInUnsupportedFormat() { - FunctionExpression expression1 = DSL - .week(functionProperties, DSL.literal(new ExprDateValue("2019-01-05")), DSL.literal(8)); + FunctionExpression expression1 = + DSL.week(functionProperties, DSL.literal(new ExprDateValue("2019-01-05")), DSL.literal(8)); SemanticCheckException exception = assertThrows(SemanticCheckException.class, () -> eval(expression1)); - assertEquals("mode:8 is invalid, please use mode value between 0-7", - exception.getMessage()); + assertEquals("mode:8 is invalid, please use mode value between 0-7", exception.getMessage()); - FunctionExpression expression2 = DSL - .week(functionProperties, DSL.literal(new ExprDateValue("2019-01-05")), DSL.literal(-1)); + FunctionExpression expression2 = + DSL.week(functionProperties, DSL.literal(new ExprDateValue("2019-01-05")), DSL.literal(-1)); exception = assertThrows(SemanticCheckException.class, () -> eval(expression2)); - assertEquals("mode:-1 is invalid, please use mode value between 0-7", - exception.getMessage()); + assertEquals("mode:-1 is invalid, please use mode value between 0-7", exception.getMessage()); } @Test public void testInvalidWeekOfYear() { assertAll( - //Test for WeekOfYear - //test invalid month - () -> assertThrows( - SemanticCheckException.class, - () -> weekOfYearQuery("2019-13-05 01:02:03", 0, 0)), - //test invalid day - () -> assertThrows( - SemanticCheckException.class, - () -> weekOfYearQuery("2019-01-50 01:02:03", 0, 0)), - //test invalid leap year - () -> assertThrows( - SemanticCheckException.class, - () -> weekOfYearQuery("2019-02-29 01:02:03", 0, 0)), - - //Test for Week_Of_Year - //test invalid month - () -> assertThrows( - SemanticCheckException.class, - () -> weekOfYearUnderscoresQuery("2019-13-05 01:02:03", 0, 0)), - //test invalid day - () -> assertThrows( - SemanticCheckException.class, - () -> weekOfYearUnderscoresQuery("2019-01-50 01:02:03", 0, 0)), - //test invalid leap year - () -> assertThrows( - SemanticCheckException.class, - () -> weekOfYearUnderscoresQuery("2019-02-29 01:02:03", 0, 0)) - ); + // Test for WeekOfYear + // test invalid month + () -> + assertThrows( + SemanticCheckException.class, () -> weekOfYearQuery("2019-13-05 01:02:03", 0, 0)), + // test invalid day + () -> + assertThrows( + SemanticCheckException.class, () -> weekOfYearQuery("2019-01-50 01:02:03", 0, 0)), + // test invalid leap year + () -> + assertThrows( + SemanticCheckException.class, () -> weekOfYearQuery("2019-02-29 01:02:03", 0, 0)), + + // Test for Week_Of_Year + // test invalid month + () -> + assertThrows( + SemanticCheckException.class, + () -> weekOfYearUnderscoresQuery("2019-13-05 01:02:03", 0, 0)), + // test invalid day + () -> + assertThrows( + SemanticCheckException.class, + () -> weekOfYearUnderscoresQuery("2019-01-50 01:02:03", 0, 0)), + // test invalid leap year + () -> + assertThrows( + SemanticCheckException.class, + () -> weekOfYearUnderscoresQuery("2019-02-29 01:02:03", 0, 0))); } @Test public void weekOfYearModeInUnsupportedFormat() { - FunctionExpression expression1 = DSL - .week_of_year( - functionProperties, - DSL.literal(new ExprDateValue("2019-01-05")), DSL.literal(8)); + FunctionExpression expression1 = + DSL.week_of_year( + functionProperties, DSL.literal(new ExprDateValue("2019-01-05")), DSL.literal(8)); SemanticCheckException exception = assertThrows(SemanticCheckException.class, () -> eval(expression1)); - assertEquals("mode:8 is invalid, please use mode value between 0-7", - exception.getMessage()); + assertEquals("mode:8 is invalid, please use mode value between 0-7", exception.getMessage()); - FunctionExpression expression2 = DSL - .week_of_year( - functionProperties, - DSL.literal(new ExprDateValue("2019-01-05")), DSL.literal(-1)); + FunctionExpression expression2 = + DSL.week_of_year( + functionProperties, DSL.literal(new ExprDateValue("2019-01-05")), DSL.literal(-1)); exception = assertThrows(SemanticCheckException.class, () -> eval(expression2)); - assertEquals("mode:-1 is invalid, please use mode value between 0-7", - exception.getMessage()); + assertEquals("mode:-1 is invalid, please use mode value between 0-7", exception.getMessage()); } @Test @@ -1557,15 +1409,14 @@ public void year() { public void date_format() { dateFormatTesters.forEach(this::testDateFormat); String timestamp = "1998-01-31 13:14:15.012345"; - String timestampFormat = "%a %b %c %D %d %e %f %H %h %I %i %j %k %l %M " - + "%m %p %r %S %s %T %% %P"; - String timestampFormatted = "Sat Jan 01 31st 31 31 012345 13 01 01 14 031 13 1 " - + "January 01 PM 01:14:15 PM 15 15 13:14:15 % P"; - - FunctionExpression expr = DSL.date_format( - functionProperties, - DSL.literal(timestamp), - DSL.literal(timestampFormat)); + String timestampFormat = + "%a %b %c %D %d %e %f %H %h %I %i %j %k %l %M " + "%m %p %r %S %s %T %% %P"; + String timestampFormatted = + "Sat Jan 01 31st 31 31 012345 13 01 01 14 031 13 1 " + + "January 01 PM 01:14:15 PM 15 15 13:14:15 % P"; + + FunctionExpression expr = + DSL.date_format(functionProperties, DSL.literal(timestamp), DSL.literal(timestampFormat)); assertEquals(STRING, expr.type()); assertEquals(timestampFormatted, eval(expr).stringValue()); } @@ -1578,108 +1429,55 @@ void testDateFormat(DateFormatTester dft) { @Test public void testDateFormatWithTimeType() { - FunctionExpression expr = DSL.date_format( - functionProperties, - DSL.literal(new ExprTimeValue("12:23:34")), - DSL.literal(new ExprStringValue("%m %d"))); + FunctionExpression expr = + DSL.date_format( + functionProperties, + DSL.literal(new ExprTimeValue("12:23:34")), + DSL.literal(new ExprStringValue("%m %d"))); + assertEquals(expr.toString(), "date_format(TIME '12:23:34', \"%m %d\")"); assertEquals( - expr.toString(), - "date_format(TIME '12:23:34', \"%m %d\")" - ); - assertEquals( - LocalDateTime.now( - functionProperties.getQueryStartClock()).format( - DateTimeFormatter.ofPattern("\"MM dd\"")), - eval(expr).toString() - ); + LocalDateTime.now(functionProperties.getQueryStartClock()) + .format(DateTimeFormatter.ofPattern("\"MM dd\"")), + eval(expr).toString()); } @Test public void testTimeFormatWithDateType() { - FunctionExpression expr = DSL.time_format( - functionProperties, - DSL.literal(new ExprDateValue("2023-01-16")), - DSL.literal(new ExprStringValue("%h %s"))); + FunctionExpression expr = + DSL.time_format( + functionProperties, + DSL.literal(new ExprDateValue("2023-01-16")), + DSL.literal(new ExprStringValue("%h %s"))); - assertEquals( - expr.toString(), - "time_format(DATE '2023-01-16', \"%h %s\")" - ); - assertEquals( - "\"12 00\"", - eval(expr).toString() - ); + assertEquals(expr.toString(), "time_format(DATE '2023-01-16', \"%h %s\")"); + assertEquals("\"12 00\"", eval(expr).toString()); } private static Stream getTestDataForTimeFormat() { return Stream.of( - Arguments.of( - DSL.literal("1998-01-31 13:14:15.012345"), - DSL.literal("%f"), - "012345"), - Arguments.of( - DSL.literal("1998-01-31 13:14:15.002345"), - DSL.literal("%f"), - "002345"), - Arguments.of( - DSL.literal("1998-01-31 13:14:15.012300"), - DSL.literal("%f"), - "012300"), - Arguments.of( - DSL.literal("1998-01-31 13:14:15.012345"), - DSL.literal("%H"), - "13"), - Arguments.of( - DSL.literal("1998-01-31 13:14:15.012345"), - DSL.literal("%h"), - "01"), - Arguments.of( - DSL.literal("1998-01-31 13:14:15.012345"), - DSL.literal("%I"), - "01"), - Arguments.of( - DSL.literal("1998-01-31 13:14:15.012345"), - DSL.literal("%i"), - "14"), - Arguments.of( - DSL.literal("1998-01-31 13:14:15.012345"), - DSL.literal("%k"), - "13"), - Arguments.of( - DSL.literal("1998-01-31 13:14:15.012345"), - DSL.literal("%l"), - "1"), - Arguments.of( - DSL.literal("1998-01-31 13:14:15.012345"), - DSL.literal("%p"), - "PM"), - Arguments.of( - DSL.literal("1998-01-31 13:14:15.012345"), - DSL.literal("%r"), - "01:14:15 PM"), - Arguments.of( - DSL.literal("1998-01-31 13:14:15.012345"), - DSL.literal("%S"), - "15"), - Arguments.of( - DSL.literal("1998-01-31 13:14:15.012345"), - DSL.literal("%s"), - "15"), - Arguments.of( - DSL.literal("1998-01-31 13:14:15.012345"), - DSL.literal("%T"), - "13:14:15"), + Arguments.of(DSL.literal("1998-01-31 13:14:15.012345"), DSL.literal("%f"), "012345"), + Arguments.of(DSL.literal("1998-01-31 13:14:15.002345"), DSL.literal("%f"), "002345"), + Arguments.of(DSL.literal("1998-01-31 13:14:15.012300"), DSL.literal("%f"), "012300"), + Arguments.of(DSL.literal("1998-01-31 13:14:15.012345"), DSL.literal("%H"), "13"), + Arguments.of(DSL.literal("1998-01-31 13:14:15.012345"), DSL.literal("%h"), "01"), + Arguments.of(DSL.literal("1998-01-31 13:14:15.012345"), DSL.literal("%I"), "01"), + Arguments.of(DSL.literal("1998-01-31 13:14:15.012345"), DSL.literal("%i"), "14"), + Arguments.of(DSL.literal("1998-01-31 13:14:15.012345"), DSL.literal("%k"), "13"), + Arguments.of(DSL.literal("1998-01-31 13:14:15.012345"), DSL.literal("%l"), "1"), + Arguments.of(DSL.literal("1998-01-31 13:14:15.012345"), DSL.literal("%p"), "PM"), + Arguments.of(DSL.literal("1998-01-31 13:14:15.012345"), DSL.literal("%r"), "01:14:15 PM"), + Arguments.of(DSL.literal("1998-01-31 13:14:15.012345"), DSL.literal("%S"), "15"), + Arguments.of(DSL.literal("1998-01-31 13:14:15.012345"), DSL.literal("%s"), "15"), + Arguments.of(DSL.literal("1998-01-31 13:14:15.012345"), DSL.literal("%T"), "13:14:15"), Arguments.of( DSL.literal("1998-01-31 13:14:15.012345"), DSL.literal("%f %H %h %I %i %k %l %p %r %S %s %T"), - "012345 13 01 01 14 13 1 PM 01:14:15 PM 15 15 13:14:15") - ); + "012345 13 01 01 14 13 1 PM 01:14:15 PM 15 15 13:14:15")); } - private void timeFormatQuery(LiteralExpression arg, - LiteralExpression format, - String expectedResult) { + private void timeFormatQuery( + LiteralExpression arg, LiteralExpression format, String expectedResult) { FunctionExpression expr = DSL.time_format(functionProperties, arg, format); assertEquals(STRING, expr.type()); assertEquals(expectedResult, eval(expr).stringValue()); @@ -1687,30 +1485,18 @@ private void timeFormatQuery(LiteralExpression arg, @ParameterizedTest(name = "{0}{1}") @MethodSource("getTestDataForTimeFormat") - public void testTimeFormat(LiteralExpression arg, - LiteralExpression format, - String expectedResult) { + public void testTimeFormat( + LiteralExpression arg, LiteralExpression format, String expectedResult) { timeFormatQuery(arg, format, expectedResult); } private static Stream getInvalidTestDataForTimeFormat() { return Stream.of( - Arguments.of( - DSL.literal("asdfasdf"), - DSL.literal("%f")), - Arguments.of( - DSL.literal("12345"), - DSL.literal("%h")), - Arguments.of( - DSL.literal("10:11:61"), - DSL.literal("%h")), - Arguments.of( - DSL.literal("10:61:12"), - DSL.literal("%h")), - Arguments.of( - DSL.literal("61:11:12"), - DSL.literal("%h")) - ); + Arguments.of(DSL.literal("asdfasdf"), DSL.literal("%f")), + Arguments.of(DSL.literal("12345"), DSL.literal("%h")), + Arguments.of(DSL.literal("10:11:61"), DSL.literal("%h")), + Arguments.of(DSL.literal("10:61:12"), DSL.literal("%h")), + Arguments.of(DSL.literal("61:11:12"), DSL.literal("%h"))); } @ParameterizedTest(name = "{0}{1}") @@ -1734,41 +1520,39 @@ private static Stream getInvalidTimeFormatHandlers() { Arguments.of("%V"), Arguments.of("%v"), Arguments.of("%X"), - Arguments.of("%x") - ); + Arguments.of("%x")); } @ParameterizedTest(name = "{0}") @MethodSource("getInvalidTimeFormatHandlers") public void testTimeFormatWithInvalidHandlers(String handler) { - FunctionExpression expr = DSL.time_format( - functionProperties, - DSL.literal("12:23:34"), - DSL.literal(handler)); + FunctionExpression expr = + DSL.time_format(functionProperties, DSL.literal("12:23:34"), DSL.literal(handler)); assertEquals(ExprNullValue.of(), eval(expr)); } @Test public void testTimeFormatWithDateHandlers() { - FunctionExpression expr = DSL.time_format( - functionProperties, - DSL.literal(new ExprDateValue("2023-01-17")), - DSL.literal("%c %d %e %m %Y %y")); - assertEquals( - "0 00 0 00 0000 00", - eval(expr).stringValue()); + FunctionExpression expr = + DSL.time_format( + functionProperties, + DSL.literal(new ExprDateValue("2023-01-17")), + DSL.literal("%c %d %e %m %Y %y")); + assertEquals("0 00 0 00 0000 00", eval(expr).stringValue()); } @Test public void testTimeFormatAndDateFormatReturnSameResult() { - FunctionExpression timeFormatExpr = DSL.time_format( - functionProperties, - DSL.literal(new ExprDateValue("1998-01-31 13:14:15.012345")), - DSL.literal("%f %H %h %I %i %k %l %p %r %S %s %T")); - FunctionExpression dateFormatExpr = DSL.date_format( - functionProperties, - DSL.literal(new ExprDateValue("1998-01-31 13:14:15.012345")), - DSL.literal("%f %H %h %I %i %k %l %p %r %S %s %T")); + FunctionExpression timeFormatExpr = + DSL.time_format( + functionProperties, + DSL.literal(new ExprDateValue("1998-01-31 13:14:15.012345")), + DSL.literal("%f %H %h %I %i %k %l %p %r %S %s %T")); + FunctionExpression dateFormatExpr = + DSL.date_format( + functionProperties, + DSL.literal(new ExprDateValue("1998-01-31 13:14:15.012345")), + DSL.literal("%f %H %h %I %i %k %l %p %r %S %s %T")); assertEquals(eval(dateFormatExpr), eval(timeFormatExpr)); } diff --git a/core/src/test/java/org/opensearch/sql/expression/datetime/DateTimeTest.java b/core/src/test/java/org/opensearch/sql/expression/datetime/DateTimeTest.java index 22c3571aca..d857122534 100644 --- a/core/src/test/java/org/opensearch/sql/expression/datetime/DateTimeTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/datetime/DateTimeTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.datetime; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -39,8 +38,8 @@ public void positiveTimeZoneNoField2() { @Test public void positiveField1WrittenField2() { - FunctionExpression expr = DSL.datetime(DSL.literal("2008-05-15 22:00:00+01:00"), - DSL.literal("America/Los_Angeles")); + FunctionExpression expr = + DSL.datetime(DSL.literal("2008-05-15 22:00:00+01:00"), DSL.literal("America/Los_Angeles")); assertEquals(DATETIME, expr.type()); assertEquals(new ExprDatetimeValue("2008-05-15 14:00:00"), expr.valueOf()); } @@ -53,42 +52,43 @@ public void localDateTimeConversion() { String dt = "2008-05-15 22:00:00"; String timeZone = "America/Los_Angeles"; LocalDateTime timeConverted = LocalDateTime.parse(dt, formatter); - ZonedDateTime timeZoneLocal = timeConverted.atZone(ZoneId.of(TimeZone.getDefault().getID())) - .withZoneSameInstant(ZoneId.of(timeZone)); - FunctionExpression expr = DSL.datetime(DSL.literal(dt), - DSL.literal(timeZone)); + ZonedDateTime timeZoneLocal = + timeConverted + .atZone(ZoneId.of(TimeZone.getDefault().getID())) + .withZoneSameInstant(ZoneId.of(timeZone)); + FunctionExpression expr = DSL.datetime(DSL.literal(dt), DSL.literal(timeZone)); assertEquals(DATETIME, expr.type()); assertEquals(new ExprDatetimeValue(timeZoneLocal.toLocalDateTime()), expr.valueOf()); } @Test public void negativeField1WrittenField2() { - FunctionExpression expr = DSL.datetime(DSL.literal("2008-05-15 22:00:00-11:00"), - DSL.literal("America/Los_Angeles")); + FunctionExpression expr = + DSL.datetime(DSL.literal("2008-05-15 22:00:00-11:00"), DSL.literal("America/Los_Angeles")); assertEquals(DATETIME, expr.type()); assertEquals(new ExprDatetimeValue("2008-05-16 02:00:00"), expr.valueOf()); } @Test public void negativeField1PositiveField2() { - FunctionExpression expr = DSL.datetime(DSL.literal("2008-05-15 22:00:00-12:00"), - DSL.literal("+15:00")); + FunctionExpression expr = + DSL.datetime(DSL.literal("2008-05-15 22:00:00-12:00"), DSL.literal("+15:00")); assertEquals(DATETIME, expr.type()); assertEquals(nullValue(), expr.valueOf()); } @Test public void twentyFourHourDifference() { - FunctionExpression expr = DSL.datetime(DSL.literal("2008-05-15 22:00:00-14:00"), - DSL.literal("+10:00")); + FunctionExpression expr = + DSL.datetime(DSL.literal("2008-05-15 22:00:00-14:00"), DSL.literal("+10:00")); assertEquals(DATETIME, expr.type()); assertEquals(nullValue(), expr.valueOf()); } @Test public void negativeToNull() { - FunctionExpression expr = DSL.datetime(DSL.literal("2008-05-15 22:00:00-11:00"), - DSL.literal(nullValue())); + FunctionExpression expr = + DSL.datetime(DSL.literal("2008-05-15 22:00:00-11:00"), DSL.literal(nullValue())); assertEquals(DATETIME, expr.type()); assertEquals(nullValue(), expr.valueOf()); } diff --git a/core/src/test/java/org/opensearch/sql/expression/datetime/DateTimeTestBase.java b/core/src/test/java/org/opensearch/sql/expression/datetime/DateTimeTestBase.java index 4c8d42e8f9..023a3574aa 100644 --- a/core/src/test/java/org/opensearch/sql/expression/datetime/DateTimeTestBase.java +++ b/core/src/test/java/org/opensearch/sql/expression/datetime/DateTimeTestBase.java @@ -27,16 +27,17 @@ public class DateTimeTestBase extends ExpressionTestBase { - protected final BuiltinFunctionRepository functionRepository - = BuiltinFunctionRepository.getInstance(); + protected final BuiltinFunctionRepository functionRepository = + BuiltinFunctionRepository.getInstance(); protected ExprValue eval(Expression expression) { return expression.valueOf(); } protected FunctionExpression adddate(Expression date, Expression interval) { - return (FunctionExpression) functionRepository.compile(functionProperties, - BuiltinFunctionName.ADDDATE.getName(), List.of(date, interval)); + return (FunctionExpression) + functionRepository.compile( + functionProperties, BuiltinFunctionName.ADDDATE.getName(), List.of(date, interval)); } protected ExprValue adddate(Object first, Object interval) { @@ -45,8 +46,9 @@ protected ExprValue adddate(Object first, Object interval) { } protected FunctionExpression addtime(Expression date, Expression interval) { - return (FunctionExpression) functionRepository.compile(functionProperties, - BuiltinFunctionName.ADDTIME.getName(), List.of(date, interval)); + return (FunctionExpression) + functionRepository.compile( + functionProperties, BuiltinFunctionName.ADDTIME.getName(), List.of(date, interval)); } protected ExprValue addtime(Temporal first, Temporal second) { @@ -55,8 +57,9 @@ protected ExprValue addtime(Temporal first, Temporal second) { } protected FunctionExpression date_add(Expression date, Expression interval) { - return (FunctionExpression) functionRepository.compile(functionProperties, - BuiltinFunctionName.DATE_ADD.getName(), List.of(date, interval)); + return (FunctionExpression) + functionRepository.compile( + functionProperties, BuiltinFunctionName.DATE_ADD.getName(), List.of(date, interval)); } protected ExprValue date_add(Object first, Object second) { @@ -65,8 +68,9 @@ protected ExprValue date_add(Object first, Object second) { } protected FunctionExpression date_sub(Expression date, Expression interval) { - return (FunctionExpression) functionRepository.compile(functionProperties, - BuiltinFunctionName.DATE_SUB.getName(), List.of(date, interval)); + return (FunctionExpression) + functionRepository.compile( + functionProperties, BuiltinFunctionName.DATE_SUB.getName(), List.of(date, interval)); } protected ExprValue date_sub(Object first, Object second) { @@ -75,13 +79,15 @@ protected ExprValue date_sub(Object first, Object second) { } protected FunctionExpression datediff(Expression first, Expression second) { - return (FunctionExpression) functionRepository.compile(functionProperties, - BuiltinFunctionName.DATEDIFF.getName(), List.of(first, second)); + return (FunctionExpression) + functionRepository.compile( + functionProperties, BuiltinFunctionName.DATEDIFF.getName(), List.of(first, second)); } protected Long datediff(Temporal first, Temporal second) { return datediff(DSL.literal(fromObjectValue(first)), DSL.literal(fromObjectValue(second))) - .valueOf().longValue(); + .valueOf() + .longValue(); } protected LocalDateTime fromUnixTime(Double value) { @@ -89,13 +95,17 @@ protected LocalDateTime fromUnixTime(Double value) { } protected FunctionExpression fromUnixTime(Expression value) { - return (FunctionExpression) functionRepository.compile(functionProperties, - BuiltinFunctionName.FROM_UNIXTIME.getName(), List.of(value)); + return (FunctionExpression) + functionRepository.compile( + functionProperties, BuiltinFunctionName.FROM_UNIXTIME.getName(), List.of(value)); } protected FunctionExpression fromUnixTime(Expression value, Expression format) { - return (FunctionExpression) functionRepository.compile(functionProperties, - BuiltinFunctionName.FROM_UNIXTIME.getName(), List.of(value, format)); + return (FunctionExpression) + functionRepository.compile( + functionProperties, + BuiltinFunctionName.FROM_UNIXTIME.getName(), + List.of(value, format)); } protected LocalDateTime fromUnixTime(Long value) { @@ -103,28 +113,31 @@ protected LocalDateTime fromUnixTime(Long value) { } protected String fromUnixTime(Long value, String format) { - return fromUnixTime(DSL.literal(value), DSL.literal(format)) - .valueOf().stringValue(); + return fromUnixTime(DSL.literal(value), DSL.literal(format)).valueOf().stringValue(); } protected String fromUnixTime(Double value, String format) { - return fromUnixTime(DSL.literal(value), DSL.literal(format)) - .valueOf().stringValue(); + return fromUnixTime(DSL.literal(value), DSL.literal(format)).valueOf().stringValue(); } protected FunctionExpression maketime(Expression hour, Expression minute, Expression second) { - return (FunctionExpression) functionRepository.compile(functionProperties, - BuiltinFunctionName.MAKETIME.getName(), List.of(hour, minute, second)); + return (FunctionExpression) + functionRepository.compile( + functionProperties, + BuiltinFunctionName.MAKETIME.getName(), + List.of(hour, minute, second)); } protected LocalTime maketime(Double hour, Double minute, Double second) { return maketime(DSL.literal(hour), DSL.literal(minute), DSL.literal(second)) - .valueOf().timeValue(); + .valueOf() + .timeValue(); } protected FunctionExpression makedate(Expression year, Expression dayOfYear) { - return (FunctionExpression) functionRepository.compile(functionProperties, - BuiltinFunctionName.MAKEDATE.getName(), List.of(year, dayOfYear)); + return (FunctionExpression) + functionRepository.compile( + functionProperties, BuiltinFunctionName.MAKEDATE.getName(), List.of(year, dayOfYear)); } protected LocalDate makedate(double year, double dayOfYear) { @@ -132,29 +145,29 @@ protected LocalDate makedate(double year, double dayOfYear) { } protected FunctionExpression period_add(Expression period, Expression months) { - return (FunctionExpression) functionRepository.compile(functionProperties, - BuiltinFunctionName.PERIOD_ADD.getName(), List.of(period, months)); + return (FunctionExpression) + functionRepository.compile( + functionProperties, BuiltinFunctionName.PERIOD_ADD.getName(), List.of(period, months)); } protected Integer period_add(Integer period, Integer months) { - return period_add(DSL.literal(period), DSL.literal(months)) - .valueOf().integerValue(); + return period_add(DSL.literal(period), DSL.literal(months)).valueOf().integerValue(); } protected FunctionExpression period_diff(Expression first, Expression second) { - return (FunctionExpression) functionRepository.compile( - functionProperties, - BuiltinFunctionName.PERIOD_DIFF.getName(), List.of(first, second)); + return (FunctionExpression) + functionRepository.compile( + functionProperties, BuiltinFunctionName.PERIOD_DIFF.getName(), List.of(first, second)); } protected Integer period_diff(Integer first, Integer second) { - return period_diff(DSL.literal(first), DSL.literal(second)) - .valueOf().integerValue(); + return period_diff(DSL.literal(first), DSL.literal(second)).valueOf().integerValue(); } protected FunctionExpression subdate(Expression date, Expression interval) { - return (FunctionExpression) functionRepository.compile(functionProperties, - BuiltinFunctionName.SUBDATE.getName(), List.of(date, interval)); + return (FunctionExpression) + functionRepository.compile( + functionProperties, BuiltinFunctionName.SUBDATE.getName(), List.of(date, interval)); } protected ExprValue subdate(Object first, Object interval) { @@ -163,8 +176,9 @@ protected ExprValue subdate(Object first, Object interval) { } protected FunctionExpression subtime(Expression date, Expression interval) { - return (FunctionExpression) functionRepository.compile(functionProperties, - BuiltinFunctionName.SUBTIME.getName(), List.of(date, interval)); + return (FunctionExpression) + functionRepository.compile( + functionProperties, BuiltinFunctionName.SUBTIME.getName(), List.of(date, interval)); } protected ExprValue subtime(Temporal first, Temporal second) { @@ -173,18 +187,21 @@ protected ExprValue subtime(Temporal first, Temporal second) { } protected FunctionExpression timediff(Expression first, Expression second) { - return (FunctionExpression) functionRepository.compile(functionProperties, - BuiltinFunctionName.TIMEDIFF.getName(), List.of(first, second)); + return (FunctionExpression) + functionRepository.compile( + functionProperties, BuiltinFunctionName.TIMEDIFF.getName(), List.of(first, second)); } protected LocalTime timediff(LocalTime first, LocalTime second) { return timediff(DSL.literal(new ExprTimeValue(first)), DSL.literal(new ExprTimeValue(second))) - .valueOf().timeValue(); + .valueOf() + .timeValue(); } protected FunctionExpression unixTimeStampExpr() { - return (FunctionExpression) functionRepository.compile(functionProperties, - BuiltinFunctionName.UNIX_TIMESTAMP.getName(), List.of()); + return (FunctionExpression) + functionRepository.compile( + functionProperties, BuiltinFunctionName.UNIX_TIMESTAMP.getName(), List.of()); } protected Long unixTimeStamp() { @@ -192,8 +209,9 @@ protected Long unixTimeStamp() { } protected FunctionExpression unixTimeStampOf(Expression value) { - return (FunctionExpression) functionRepository.compile(functionProperties, - BuiltinFunctionName.UNIX_TIMESTAMP.getName(), List.of(value)); + return (FunctionExpression) + functionRepository.compile( + functionProperties, BuiltinFunctionName.UNIX_TIMESTAMP.getName(), List.of(value)); } protected Double unixTimeStampOf(Double value) { @@ -201,17 +219,14 @@ protected Double unixTimeStampOf(Double value) { } protected Double unixTimeStampOf(LocalDate value) { - return unixTimeStampOf(DSL.literal(new ExprDateValue(value))) - .valueOf().doubleValue(); + return unixTimeStampOf(DSL.literal(new ExprDateValue(value))).valueOf().doubleValue(); } protected Double unixTimeStampOf(LocalDateTime value) { - return unixTimeStampOf(DSL.literal(new ExprDatetimeValue(value))) - .valueOf().doubleValue(); + return unixTimeStampOf(DSL.literal(new ExprDatetimeValue(value))).valueOf().doubleValue(); } protected Double unixTimeStampOf(Instant value) { - return unixTimeStampOf(DSL.literal(new ExprTimestampValue(value))) - .valueOf().doubleValue(); + return unixTimeStampOf(DSL.literal(new ExprTimestampValue(value))).valueOf().doubleValue(); } } diff --git a/core/src/test/java/org/opensearch/sql/expression/datetime/ExtractTest.java b/core/src/test/java/org/opensearch/sql/expression/datetime/ExtractTest.java index 338933333a..820158b722 100644 --- a/core/src/test/java/org/opensearch/sql/expression/datetime/ExtractTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/datetime/ExtractTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.datetime; import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_YEAR; @@ -38,8 +37,7 @@ private static Stream getDatetimeResultsForExtractFunction() { Arguments.of("DAY_MICROSECOND", 11101112123000L), Arguments.of("DAY_SECOND", 11101112), Arguments.of("DAY_MINUTE", 111011), - Arguments.of("DAY_HOUR", 1110) - ); + Arguments.of("DAY_HOUR", 1110)); } private static Stream getTimeResultsForExtractFunction() { @@ -53,8 +51,7 @@ private static Stream getTimeResultsForExtractFunction() { Arguments.of("MINUTE_SECOND", 1112), Arguments.of("HOUR_MICROSECOND", 101112123000L), Arguments.of("HOUR_SECOND", 101112), - Arguments.of("HOUR_MINUTE", 1011) - ); + Arguments.of("HOUR_MINUTE", 1011)); } private static Stream getDateResultsForExtractFunction() { @@ -64,19 +61,18 @@ private static Stream getDateResultsForExtractFunction() { Arguments.of("MONTH", 2), Arguments.of("QUARTER", 1), Arguments.of("YEAR", 2023), - Arguments.of("YEAR_MONTH", 202302) - ); + Arguments.of("YEAR_MONTH", 202302)); } @ParameterizedTest(name = "{0}") @MethodSource({ - "getDatetimeResultsForExtractFunction", - "getTimeResultsForExtractFunction", - "getDateResultsForExtractFunction"}) + "getDatetimeResultsForExtractFunction", + "getTimeResultsForExtractFunction", + "getDateResultsForExtractFunction" + }) public void testExtractWithDatetime(String part, long expected) { - FunctionExpression datetimeExpression = DSL.extract( - DSL.literal(part), - DSL.literal(new ExprDatetimeValue(datetimeInput))); + FunctionExpression datetimeExpression = + DSL.extract(DSL.literal(part), DSL.literal(new ExprDatetimeValue(datetimeInput))); assertEquals(LONG, datetimeExpression.type()); assertEquals(expected, eval(datetimeExpression).longValue()); @@ -87,23 +83,17 @@ public void testExtractWithDatetime(String part, long expected) { private void datePartWithTimeArgQuery(String part, String time, long expected) { ExprTimeValue timeValue = new ExprTimeValue(time); - FunctionExpression datetimeExpression = DSL.extract( - functionProperties, - DSL.literal(part), - DSL.literal(timeValue)); + FunctionExpression datetimeExpression = + DSL.extract(functionProperties, DSL.literal(part), DSL.literal(timeValue)); assertEquals(LONG, datetimeExpression.type()); - assertEquals(expected, - eval(datetimeExpression).longValue()); + assertEquals(expected, eval(datetimeExpression).longValue()); } - @Test public void testExtractDatePartWithTimeType() { datePartWithTimeArgQuery( - "DAY", - timeInput, - LocalDate.now(functionProperties.getQueryStartClock()).getDayOfMonth()); + "DAY", timeInput, LocalDate.now(functionProperties.getQueryStartClock()).getDayOfMonth()); datePartWithTimeArgQuery( "WEEK", @@ -111,43 +101,35 @@ public void testExtractDatePartWithTimeType() { LocalDate.now(functionProperties.getQueryStartClock()).get(ALIGNED_WEEK_OF_YEAR)); datePartWithTimeArgQuery( - "MONTH", - timeInput, - LocalDate.now(functionProperties.getQueryStartClock()).getMonthValue()); + "MONTH", timeInput, LocalDate.now(functionProperties.getQueryStartClock()).getMonthValue()); datePartWithTimeArgQuery( - "YEAR", - timeInput, - LocalDate.now(functionProperties.getQueryStartClock()).getYear()); + "YEAR", timeInput, LocalDate.now(functionProperties.getQueryStartClock()).getYear()); } @ParameterizedTest(name = "{0}") @MethodSource("getDateResultsForExtractFunction") public void testExtractWithDate(String part, long expected) { - FunctionExpression datetimeExpression = DSL.extract( - DSL.literal(part), - DSL.literal(new ExprDateValue(dateInput))); + FunctionExpression datetimeExpression = + DSL.extract(DSL.literal(part), DSL.literal(new ExprDateValue(dateInput))); assertEquals(LONG, datetimeExpression.type()); assertEquals(expected, eval(datetimeExpression).longValue()); assertEquals( - String.format("extract(\"%s\", DATE '2023-02-11')", part), - datetimeExpression.toString()); + String.format("extract(\"%s\", DATE '2023-02-11')", part), datetimeExpression.toString()); } @ParameterizedTest(name = "{0}") @MethodSource("getTimeResultsForExtractFunction") public void testExtractWithTime(String part, long expected) { - FunctionExpression datetimeExpression = DSL.extract( - functionProperties, - DSL.literal(part), - DSL.literal(new ExprTimeValue(timeInput))); + FunctionExpression datetimeExpression = + DSL.extract( + functionProperties, DSL.literal(part), DSL.literal(new ExprTimeValue(timeInput))); assertEquals(LONG, datetimeExpression.type()); assertEquals(expected, eval(datetimeExpression).longValue()); assertEquals( - String.format("extract(\"%s\", TIME '10:11:12.123')", part), - datetimeExpression.toString()); + String.format("extract(\"%s\", TIME '10:11:12.123')", part), datetimeExpression.toString()); } private ExprValue eval(Expression expression) { diff --git a/core/src/test/java/org/opensearch/sql/expression/datetime/FromUnixTimeTest.java b/core/src/test/java/org/opensearch/sql/expression/datetime/FromUnixTimeTest.java index 58387ef04f..8fcc6904b2 100644 --- a/core/src/test/java/org/opensearch/sql/expression/datetime/FromUnixTimeTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/datetime/FromUnixTimeTest.java @@ -31,20 +31,21 @@ private static Stream getLongSamples() { Arguments.of(1L), Arguments.of(1447430881L), Arguments.of(2147483647L), - Arguments.of(1662577241L) - ); + Arguments.of(1662577241L)); } /** * Test processing different Long values. + * * @param value a value */ @ParameterizedTest @MethodSource("getLongSamples") public void checkOfLong(Long value) { - assertEquals(LocalDateTime.of(1970, 1, 1, 0, 0, 0).plus(value, ChronoUnit.SECONDS), - fromUnixTime(value)); - assertEquals(LocalDateTime.of(1970, 1, 1, 0, 0, 0).plus(value, ChronoUnit.SECONDS), + assertEquals( + LocalDateTime.of(1970, 1, 1, 0, 0, 0).plus(value, ChronoUnit.SECONDS), fromUnixTime(value)); + assertEquals( + LocalDateTime.of(1970, 1, 1, 0, 0, 0).plus(value, ChronoUnit.SECONDS), eval(fromUnixTime(DSL.literal(new ExprLongValue(value)))).datetimeValue()); } @@ -54,12 +55,12 @@ private static Stream getDoubleSamples() { Arguments.of(100500.100500d), Arguments.of(1447430881.564d), Arguments.of(2147483647.451232d), - Arguments.of(1662577241.d) - ); + Arguments.of(1662577241.d)); } /** * Test processing different Double values. + * * @param value a value */ @ParameterizedTest @@ -70,11 +71,11 @@ public void checkOfDouble(Double value) { var valueAsString = new DecimalFormat("0.#").format(value); assertEquals( - LocalDateTime.ofEpochSecond(intPart, (int)Math.round(fracPart * 1E9), ZoneOffset.UTC), + LocalDateTime.ofEpochSecond(intPart, (int) Math.round(fracPart * 1E9), ZoneOffset.UTC), fromUnixTime(value), valueAsString); assertEquals( - LocalDateTime.ofEpochSecond(intPart, (int)Math.round(fracPart * 1E9), ZoneOffset.UTC), + LocalDateTime.ofEpochSecond(intPart, (int) Math.round(fracPart * 1E9), ZoneOffset.UTC), eval(fromUnixTime(DSL.literal(new ExprDoubleValue(value)))).datetimeValue(), valueAsString); } @@ -88,11 +89,12 @@ private static Stream getLongSamplesWithFormat() { Arguments.of(1447430881L, "%s", "01"), // 2015-11-13 16:08:01, %s - second Arguments.of(2147483647L, "%T", "03:14:07"), // 2038-01-19 03:14:07, %T - time Arguments.of(1662577241L, "%d", "07") // 1662577241, %d - day of the month - ); + ); } /** * Test processing different Long values with format. + * * @param value a value * @param format a format * @param expected expected result @@ -101,8 +103,11 @@ private static Stream getLongSamplesWithFormat() { @MethodSource("getLongSamplesWithFormat") public void checkOfLongWithFormat(Long value, String format, String expected) { assertEquals(expected, fromUnixTime(value, format)); - assertEquals(expected, eval(fromUnixTime(DSL.literal(new ExprLongValue(value)), - DSL.literal(new ExprStringValue(format)))).stringValue()); + assertEquals( + expected, + eval(fromUnixTime( + DSL.literal(new ExprLongValue(value)), DSL.literal(new ExprStringValue(format)))) + .stringValue()); } private static Stream getDoubleSamplesWithFormat() { @@ -112,11 +117,12 @@ private static Stream getDoubleSamplesWithFormat() { Arguments.of(1447430881.56d, "%M", "November"), // 2015-11-13 16:08:01.56, %M - Month name Arguments.of(2147483647.42d, "%j", "019"), // 2038-01-19 03:14:07.42, %j - day of the year Arguments.of(1662577241.d, "%l", "7") // 2022-09-07 19:00:41, %l - 12 hour clock, no 0 pad - ); + ); } /** * Test processing different Double values with format. + * * @param value a value * @param format a format * @param expected expected result @@ -125,16 +131,18 @@ private static Stream getDoubleSamplesWithFormat() { @MethodSource("getDoubleSamplesWithFormat") public void checkOfDoubleWithFormat(Double value, String format, String expected) { assertEquals(expected, fromUnixTime(value, format)); - assertEquals(expected, eval(fromUnixTime(DSL.literal(new ExprDoubleValue(value)), - DSL.literal(new ExprStringValue(format)))).stringValue()); + assertEquals( + expected, + eval(fromUnixTime( + DSL.literal(new ExprDoubleValue(value)), DSL.literal(new ExprStringValue(format)))) + .stringValue()); } @Test public void checkInvalidFormat() { - assertEquals(new ExprStringValue("q"), - fromUnixTime(DSL.literal(0L), DSL.literal("%q")).valueOf()); - assertEquals(new ExprStringValue(""), - fromUnixTime(DSL.literal(0L), DSL.literal("")).valueOf()); + assertEquals( + new ExprStringValue("q"), fromUnixTime(DSL.literal(0L), DSL.literal("%q")).valueOf()); + assertEquals(new ExprStringValue(""), fromUnixTime(DSL.literal(0L), DSL.literal("")).valueOf()); } @Test @@ -153,33 +161,33 @@ public void checkInsideTheRangeWithoutFormat() { @Test public void checkValueOutsideOfTheRangeWithFormat() { - assertEquals(ExprNullValue.of(), - fromUnixTime(DSL.literal(32536771200L), DSL.literal("%d")).valueOf()); - assertEquals(ExprNullValue.of(), - fromUnixTime(DSL.literal(32536771200d), DSL.literal("%d")).valueOf()); + assertEquals( + ExprNullValue.of(), fromUnixTime(DSL.literal(32536771200L), DSL.literal("%d")).valueOf()); + assertEquals( + ExprNullValue.of(), fromUnixTime(DSL.literal(32536771200d), DSL.literal("%d")).valueOf()); } @Test public void checkInsideTheRangeWithFormat() { - assertNotEquals(ExprNullValue.of(), - fromUnixTime(DSL.literal(32536771199L), DSL.literal("%d")).valueOf()); - assertNotEquals(ExprNullValue.of(), - fromUnixTime(DSL.literal(32536771199d), DSL.literal("%d")).valueOf()); + assertNotEquals( + ExprNullValue.of(), fromUnixTime(DSL.literal(32536771199L), DSL.literal("%d")).valueOf()); + assertNotEquals( + ExprNullValue.of(), fromUnixTime(DSL.literal(32536771199d), DSL.literal("%d")).valueOf()); } @Test public void checkNullOrNegativeValues() { assertEquals(ExprNullValue.of(), fromUnixTime(DSL.literal(ExprNullValue.of())).valueOf()); - assertEquals(ExprNullValue.of(), - fromUnixTime(DSL.literal(-1L), DSL.literal("%d")).valueOf()); - assertEquals(ExprNullValue.of(), - fromUnixTime(DSL.literal(-1.5d), DSL.literal("%d")).valueOf()); - assertEquals(ExprNullValue.of(), + assertEquals(ExprNullValue.of(), fromUnixTime(DSL.literal(-1L), DSL.literal("%d")).valueOf()); + assertEquals(ExprNullValue.of(), fromUnixTime(DSL.literal(-1.5d), DSL.literal("%d")).valueOf()); + assertEquals( + ExprNullValue.of(), fromUnixTime(DSL.literal(42L), DSL.literal(ExprNullValue.of())).valueOf()); - assertEquals(ExprNullValue.of(), + assertEquals( + ExprNullValue.of(), fromUnixTime(DSL.literal(ExprNullValue.of()), DSL.literal("%d")).valueOf()); - assertEquals(ExprNullValue.of(), - fromUnixTime(DSL.literal(ExprNullValue.of()), DSL.literal(ExprNullValue.of())) - .valueOf()); + assertEquals( + ExprNullValue.of(), + fromUnixTime(DSL.literal(ExprNullValue.of()), DSL.literal(ExprNullValue.of())).valueOf()); } } diff --git a/core/src/test/java/org/opensearch/sql/expression/datetime/IntervalClauseTest.java b/core/src/test/java/org/opensearch/sql/expression/datetime/IntervalClauseTest.java index e63acc94c0..d89e5f978a 100644 --- a/core/src/test/java/org/opensearch/sql/expression/datetime/IntervalClauseTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/datetime/IntervalClauseTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.datetime; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -31,14 +30,11 @@ @ExtendWith(MockitoExtension.class) public class IntervalClauseTest extends ExpressionTestBase { - @Mock - Environment env; + @Mock Environment env; - @Mock - Expression nullRef; + @Mock Expression nullRef; - @Mock - Expression missingRef; + @Mock Expression missingRef; @Test public void microsecond() { @@ -106,7 +102,9 @@ public void year() { @Test public void unsupported_unit() { FunctionExpression expr = DSL.interval(DSL.literal(1), DSL.literal("year_month")); - assertThrows(ExpressionEvaluationException.class, () -> expr.valueOf(env), + assertThrows( + ExpressionEvaluationException.class, + () -> expr.valueOf(env), "interval unit year_month is not supported"); } diff --git a/core/src/test/java/org/opensearch/sql/expression/datetime/MakeDateTest.java b/core/src/test/java/org/opensearch/sql/expression/datetime/MakeDateTest.java index fbd7e61c8d..b607d907db 100644 --- a/core/src/test/java/org/opensearch/sql/expression/datetime/MakeDateTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/datetime/MakeDateTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.datetime; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -22,21 +21,32 @@ public class MakeDateTest extends DateTimeTestBase { @Test public void checkEdgeCases() { - assertEquals(LocalDate.ofYearDay(2002, 1), makedate(2001., 366.), + assertEquals( + LocalDate.ofYearDay(2002, 1), + makedate(2001., 366.), "No switch to the next year on getting 366th day of a non-leap year"); - assertEquals(LocalDate.ofYearDay(2005, 1), makedate(2004., 367.), + assertEquals( + LocalDate.ofYearDay(2005, 1), + makedate(2004., 367.), "No switch to the next year on getting 367th day of a leap year"); - assertEquals(LocalDate.ofYearDay(2000, 42), makedate(0., 42.), + assertEquals( + LocalDate.ofYearDay(2000, 42), + makedate(0., 42.), "0 year is not interpreted as 2000 as in MySQL"); - assertEquals(nullValue(), eval(makedate(DSL.literal(-1.), DSL.literal(42.))), + assertEquals( + nullValue(), + eval(makedate(DSL.literal(-1.), DSL.literal(42.))), "Negative year doesn't produce NULL"); - assertEquals(nullValue(), eval(makedate(DSL.literal(42.), DSL.literal(-1.))), + assertEquals( + nullValue(), + eval(makedate(DSL.literal(42.), DSL.literal(-1.))), "Negative dayOfYear doesn't produce NULL"); - assertEquals(nullValue(), eval(makedate(DSL.literal(42.), DSL.literal(0.))), + assertEquals( + nullValue(), + eval(makedate(DSL.literal(42.), DSL.literal(0.))), "Zero dayOfYear doesn't produce NULL"); - assertEquals(LocalDate.of(1999, 3, 1), makedate(1999., 60.), - "Got Feb 29th of a non-lear year"); + assertEquals(LocalDate.of(1999, 3, 1), makedate(1999., 60.), "Got Feb 29th of a non-lear year"); assertEquals(LocalDate.of(1999, 12, 31), makedate(1999., 365.)); assertEquals(LocalDate.of(2004, 12, 31), makedate(2004., 366.)); } @@ -73,12 +83,12 @@ private static Stream getTestData() { Arguments.of(3617.452566, 619.795467), Arguments.of(2210.322073, 106.914268), Arguments.of(675.757974, 147.702828), - Arguments.of(1101.801820, 40.055318) - ); + Arguments.of(1101.801820, 40.055318)); } /** * Test function with given pseudo-random values. + * * @param year year * @param dayOfYear day of year */ @@ -88,20 +98,20 @@ public void checkRandomValues(double year, double dayOfYear) { LocalDate actual = makedate(year, dayOfYear); LocalDate expected = getReferenceValue(year, dayOfYear); - assertEquals(expected, actual, - String.format("year = %f, dayOfYear = %f", year, dayOfYear)); + assertEquals(expected, actual, String.format("year = %f, dayOfYear = %f", year, dayOfYear)); } /** - * Using another algorithm to get reference value. - * We should go to the next year until remaining @dayOfYear is bigger than 365/366. + * Using another algorithm to get reference value. We should go to the next year until + * remaining @dayOfYear is bigger than 365/366. + * * @param year Year. * @param dayOfYear Day of the year. * @return The calculated date. */ private LocalDate getReferenceValue(double year, double dayOfYear) { - var yearL = (int)Math.round(year); - var dayL = (int)Math.round(dayOfYear); + var yearL = (int) Math.round(year); + var dayL = (int) Math.round(dayOfYear); while (true) { int daysInYear = Year.isLeap(yearL) ? 366 : 365; if (dayL > daysInYear) { diff --git a/core/src/test/java/org/opensearch/sql/expression/datetime/MakeTimeTest.java b/core/src/test/java/org/opensearch/sql/expression/datetime/MakeTimeTest.java index 2f8e45b4c3..ff6896647d 100644 --- a/core/src/test/java/org/opensearch/sql/expression/datetime/MakeTimeTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/datetime/MakeTimeTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.datetime; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -24,18 +23,27 @@ public class MakeTimeTest extends DateTimeTestBase { @Test public void checkEdgeCases() { - assertEquals(nullValue(), eval(maketime(DSL.literal(-1.), DSL.literal(42.), DSL.literal(42.))), + assertEquals( + nullValue(), + eval(maketime(DSL.literal(-1.), DSL.literal(42.), DSL.literal(42.))), "Negative hour doesn't produce NULL"); - assertEquals(nullValue(), eval(maketime(DSL.literal(42.), DSL.literal(-1.), DSL.literal(42.))), + assertEquals( + nullValue(), + eval(maketime(DSL.literal(42.), DSL.literal(-1.), DSL.literal(42.))), "Negative minute doesn't produce NULL"); - assertEquals(nullValue(), eval(maketime(DSL.literal(12.), DSL.literal(42.), DSL.literal(-1.))), + assertEquals( + nullValue(), + eval(maketime(DSL.literal(12.), DSL.literal(42.), DSL.literal(-1.))), "Negative second doesn't produce NULL"); - assertThrows(DateTimeParseException.class, + assertThrows( + DateTimeParseException.class, () -> eval(maketime(DSL.literal(24.), DSL.literal(42.), DSL.literal(42.)))); - assertThrows(DateTimeParseException.class, + assertThrows( + DateTimeParseException.class, () -> eval(maketime(DSL.literal(12.), DSL.literal(60.), DSL.literal(42.)))); - assertThrows(DateTimeParseException.class, + assertThrows( + DateTimeParseException.class, () -> eval(maketime(DSL.literal(12.), DSL.literal(42.), DSL.literal(60.)))); assertEquals(LocalTime.of(23, 59, 59), maketime(23., 59., 59.)); @@ -81,12 +89,12 @@ private static Stream getTestData() { Arguments.of(7.494112, 9.761983, 17.444988), Arguments.of(17.867756, 10.313120, 36.391815), Arguments.of(19.712155, 3.197562, 6.607233), - Arguments.of(2.385090, 41.761568, 33.342590) - ); + Arguments.of(2.385090, 41.761568, 33.342590)); } /** * Test function with given pseudo-random values. + * * @param hour hour * @param minute minute * @param second second @@ -95,11 +103,15 @@ private static Stream getTestData() { @MethodSource("getTestData") public void checkRandomValues(double hour, double minute, double second) { // results could have 1 nanosec diff because of rounding FP - var expected = LocalTime.of((int)Math.round(hour), (int)Math.round(minute), - // pick fraction second part as nanos - (int)Math.floor(second)).withNano((int)((second % 1) * 1E9)); + var expected = + LocalTime.of( + (int) Math.round(hour), + (int) Math.round(minute), + // pick fraction second part as nanos + (int) Math.floor(second)) + .withNano((int) ((second % 1) * 1E9)); var delta = Duration.between(expected, maketime(hour, minute, second)).getNano(); - assertEquals(0, delta, 1, - String.format("hour = %f, minute = %f, second = %f", hour, minute, second)); + assertEquals( + 0, delta, 1, String.format("hour = %f, minute = %f, second = %f", hour, minute, second)); } } diff --git a/core/src/test/java/org/opensearch/sql/expression/datetime/NowLikeFunctionTest.java b/core/src/test/java/org/opensearch/sql/expression/datetime/NowLikeFunctionTest.java index b67f4efc21..0e5c00084f 100644 --- a/core/src/test/java/org/opensearch/sql/expression/datetime/NowLikeFunctionTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/datetime/NowLikeFunctionTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.datetime; import static org.hamcrest.MatcherAssert.assertThat; @@ -41,11 +40,11 @@ import org.opensearch.sql.expression.FunctionExpression; import org.opensearch.sql.expression.function.FunctionProperties; - class NowLikeFunctionTest extends ExpressionTestBase { @Test void now() { - test_now_like_functions(DSL::now, + test_now_like_functions( + DSL::now, DATETIME, false, () -> LocalDateTime.now(functionProperties.getQueryStartClock())); @@ -53,19 +52,28 @@ void now() { @Test void current_timestamp() { - test_now_like_functions(DSL::current_timestamp, DATETIME, false, + test_now_like_functions( + DSL::current_timestamp, + DATETIME, + false, () -> LocalDateTime.now(functionProperties.getQueryStartClock())); } @Test void localtimestamp() { - test_now_like_functions(DSL::localtimestamp, DATETIME, false, + test_now_like_functions( + DSL::localtimestamp, + DATETIME, + false, () -> LocalDateTime.now(functionProperties.getQueryStartClock())); } @Test void localtime() { - test_now_like_functions(DSL::localtime, DATETIME, false, + test_now_like_functions( + DSL::localtime, + DATETIME, + false, () -> LocalDateTime.now(functionProperties.getQueryStartClock())); } @@ -76,21 +84,21 @@ void sysdate() { @Test void curtime() { - test_now_like_functions(DSL::curtime, TIME, false, - () -> LocalTime.now(functionProperties.getQueryStartClock())); + test_now_like_functions( + DSL::curtime, TIME, false, () -> LocalTime.now(functionProperties.getQueryStartClock())); } @Test void currdate() { - test_now_like_functions(DSL::curdate, - DATE, false, - () -> LocalDate.now(functionProperties.getQueryStartClock())); + test_now_like_functions( + DSL::curdate, DATE, false, () -> LocalDate.now(functionProperties.getQueryStartClock())); } @Test void current_time() { - test_now_like_functions(DSL::current_time, + test_now_like_functions( + DSL::current_time, TIME, false, () -> LocalTime.now(functionProperties.getQueryStartClock())); @@ -98,26 +106,29 @@ void current_time() { @Test void current_date() { - test_now_like_functions(DSL::current_date, DATE, false, + test_now_like_functions( + DSL::current_date, + DATE, + false, () -> LocalDate.now(functionProperties.getQueryStartClock())); } @Test void utc_date() { - test_now_like_functions(DSL::utc_date, DATE, false, - () -> utcDateTimeNow(functionProperties).toLocalDate()); + test_now_like_functions( + DSL::utc_date, DATE, false, () -> utcDateTimeNow(functionProperties).toLocalDate()); } @Test void utc_time() { - test_now_like_functions(DSL::utc_time, TIME, false, - () -> utcDateTimeNow(functionProperties).toLocalTime()); + test_now_like_functions( + DSL::utc_time, TIME, false, () -> utcDateTimeNow(functionProperties).toLocalTime()); } @Test void utc_timestamp() { - test_now_like_functions(DSL::utc_timestamp, DATETIME, false, - () -> utcDateTimeNow(functionProperties)); + test_now_like_functions( + DSL::utc_timestamp, DATETIME, false, () -> utcDateTimeNow(functionProperties)); } private static LocalDateTime utcDateTimeNow(FunctionProperties functionProperties) { @@ -130,16 +141,16 @@ private static LocalDateTime utcDateTimeNow(FunctionProperties functionPropertie /** * Check how NOW-like functions are processed. * - * @param function Function - * @param resType Return type - * @param hasFsp Whether function has fsp argument + * @param function Function + * @param resType Return type + * @param hasFsp Whether function has fsp argument * @param referenceGetter A callback to get reference value */ void test_now_like_functions( BiFunction function, - ExprCoreType resType, - Boolean hasFsp, - Supplier referenceGetter) { + ExprCoreType resType, + Boolean hasFsp, + Supplier referenceGetter) { // Check return types: // `func()` FunctionExpression expr = function.apply(functionProperties, new Expression[] {}); @@ -153,10 +164,15 @@ void test_now_like_functions( assertEquals(resType, expr.type()); for (var wrongFspValue : List.of(-1, 10)) { - var exception = assertThrows(IllegalArgumentException.class, - () -> function.apply(functionProperties, - new Expression[] {DSL.literal(wrongFspValue)}).valueOf()); - assertEquals(String.format("Invalid `fsp` value: %d, allowed 0 to 6", wrongFspValue), + var exception = + assertThrows( + IllegalArgumentException.class, + () -> + function + .apply(functionProperties, new Expression[] {DSL.literal(wrongFspValue)}) + .valueOf()); + assertEquals( + String.format("Invalid `fsp` value: %d, allowed 0 to 6", wrongFspValue), exception.getMessage()); } } @@ -170,11 +186,9 @@ void test_now_like_functions( assertThat(sample, isCloseTo(reference, maxDiff, unit)); if (hasFsp) { // `func(fsp)` - Temporal value = extractValue(function.apply(functionProperties, - new Expression[] {DSL.literal(0)})); - assertThat(referenceGetter.get(), - isCloseTo(value, maxDiff, unit)); - + Temporal value = + extractValue(function.apply(functionProperties, new Expression[] {DSL.literal(0)})); + assertThat(referenceGetter.get(), isCloseTo(value, maxDiff, unit)); } } @@ -182,7 +196,8 @@ static Matcher isCloseTo(Temporal reference, long maxDiff, TemporalUni return new BaseMatcher<>() { @Override public void describeTo(Description description) { - description.appendText("value between ") + description + .appendText("value between ") .appendValue(reference.minus(maxDiff, units)) .appendText(" and ") .appendValue(reference.plus(maxDiff, units)); @@ -197,24 +212,21 @@ public boolean matches(Object value) { } return false; } - - }; } @TestFactory Stream constantValueTestFactory() { - BiFunction, DynamicTest> buildTest - = (name, action) -> - DynamicTest.dynamicTest( - String.format("multiple_invocations_same_value_test[%s]", name), - () -> { - var v1 = extractValue(action.apply(functionProperties)); - Thread.sleep(1000); - var v2 = extractValue(action.apply(functionProperties)); - assertEquals(v1, v2); - } - ); + BiFunction, DynamicTest> buildTest = + (name, action) -> + DynamicTest.dynamicTest( + String.format("multiple_invocations_same_value_test[%s]", name), + () -> { + var v1 = extractValue(action.apply(functionProperties)); + Thread.sleep(1000); + var v2 = extractValue(action.apply(functionProperties)); + assertEquals(v1, v2); + }); return Stream.of( buildTest.apply("now", DSL::now), buildTest.apply("current_timestamp", DSL::current_timestamp), @@ -222,8 +234,7 @@ Stream constantValueTestFactory() { buildTest.apply("curdate", DSL::curdate), buildTest.apply("curtime", DSL::curtime), buildTest.apply("localtimestamp", DSL::localtimestamp), - buildTest.apply("localtime", DSL::localtime) - ); + buildTest.apply("localtime", DSL::localtime)); } @Test @@ -232,7 +243,6 @@ void sysdate_multiple_invocations_differ() throws InterruptedException { Thread.sleep(1000); var v2 = extractValue(DSL.sysdate(functionProperties)); assertThat(v1, IsNot.not(isCloseTo(v2, 1, ChronoUnit.NANOS))); - } private Temporal extractValue(FunctionExpression func) { @@ -243,7 +253,7 @@ private Temporal extractValue(FunctionExpression func) { return func.valueOf().datetimeValue(); case TIME: return func.valueOf().timeValue(); - // unreachable code + // unreachable code default: throw new IllegalArgumentException(String.format("%s", func.type())); } diff --git a/core/src/test/java/org/opensearch/sql/expression/datetime/PeriodFunctionsTest.java b/core/src/test/java/org/opensearch/sql/expression/datetime/PeriodFunctionsTest.java index bf228dd509..c6a6392c9b 100644 --- a/core/src/test/java/org/opensearch/sql/expression/datetime/PeriodFunctionsTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/datetime/PeriodFunctionsTest.java @@ -18,6 +18,7 @@ public class PeriodFunctionsTest extends DateTimeTestBase { /** * Generate sample data for `PERIOD_ADD` function. + * * @return A data set. */ public static Stream getTestDataForPeriodAdd() { @@ -27,8 +28,7 @@ public static Stream getTestDataForPeriodAdd() { Arguments.of(3, -1, 200002), // Mar 2000 - 1 Arguments.of(12, 0, 200012), // Dec 2000 + 0 Arguments.of(6104, 100, 206908), // Apr 2061 + 100m (8y4m) - Arguments.of(201510, 14, 201612) - ); + Arguments.of(201510, 14, 201612)); } @ParameterizedTest @@ -39,6 +39,7 @@ public void period_add_with_different_data(int period, int months, int expected) /** * Generate sample data for `PERIOD_DIFF` function. + * * @return A data set. */ public static Stream getTestDataForPeriodDiff() { @@ -51,7 +52,7 @@ public static Stream getTestDataForPeriodDiff() { Arguments.of(200505, 7505, 360), // May 2005 - May 1975 Arguments.of(6104, 8509, 907), // Apr 2061 - Sep 1985 Arguments.of(207707, 7707, 1200) // Jul 2077 - Jul 1977 - ); + ); } @ParameterizedTest @@ -68,29 +69,30 @@ public void two_way_conversion(int period1, int period2, int expected) { /** * Generate invalid sample data for test. + * * @return A data set. */ public static Stream getInvalidTestData() { return Stream.of( - Arguments.of(0), - Arguments.of(123), - Arguments.of(100), - Arguments.of(1234), - Arguments.of(1000), - Arguments.of(2020), - Arguments.of(12345), - Arguments.of(123456), - Arguments.of(1234567), - Arguments.of(200213), - Arguments.of(200300), - Arguments.of(-1), - Arguments.of(-1234), - Arguments.of(-123401) - ); + Arguments.of(0), + Arguments.of(123), + Arguments.of(100), + Arguments.of(1234), + Arguments.of(1000), + Arguments.of(2020), + Arguments.of(12345), + Arguments.of(123456), + Arguments.of(1234567), + Arguments.of(200213), + Arguments.of(200300), + Arguments.of(-1), + Arguments.of(-1234), + Arguments.of(-123401)); } /** * Check that `PERIOD_ADD` and `PERIOD_DIFF` return NULL on invalid input. + * * @param period An invalid data. */ @ParameterizedTest diff --git a/core/src/test/java/org/opensearch/sql/expression/datetime/StrToDateTest.java b/core/src/test/java/org/opensearch/sql/expression/datetime/StrToDateTest.java index a35627247a..42d4aab1f6 100644 --- a/core/src/test/java/org/opensearch/sql/expression/datetime/StrToDateTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/datetime/StrToDateTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.datetime; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -33,89 +32,46 @@ class StrToDateTest extends ExpressionTestBase { private static Stream getTestDataForStrToDate() { return Stream.of( - //Date arguments + // Date arguments Arguments.of( - "01,5,2013", - "%d,%m,%Y", - new ExprDatetimeValue("2013-05-01 00:00:00"), - DATETIME), + "01,5,2013", "%d,%m,%Y", new ExprDatetimeValue("2013-05-01 00:00:00"), DATETIME), Arguments.of( - "May 1, 2013", - "%M %d, %Y", - new ExprDatetimeValue("2013-05-01 00:00:00"), - DATETIME), + "May 1, 2013", "%M %d, %Y", new ExprDatetimeValue("2013-05-01 00:00:00"), DATETIME), Arguments.of( "May 1, 2013 - 9,23,11", "%M %d, %Y - %h,%i,%s", new ExprDatetimeValue("2013-05-01 09:23:11"), DATETIME), Arguments.of( - "2000,1,1", - "%Y,%m,%d", - new ExprDatetimeValue("2000-01-01 00:00:00"), - DATETIME), + "2000,1,1", "%Y,%m,%d", new ExprDatetimeValue("2000-01-01 00:00:00"), DATETIME), Arguments.of( - "2000,1,1,10", - "%Y,%m,%d,%h", - new ExprDatetimeValue("2000-01-01 10:00:00"), - DATETIME), + "2000,1,1,10", "%Y,%m,%d,%h", new ExprDatetimeValue("2000-01-01 10:00:00"), DATETIME), Arguments.of( "2000,1,1,10,11", "%Y,%m,%d,%h,%i", new ExprDatetimeValue("2000-01-01 10:11:00"), DATETIME), - //Invalid Arguments (should return null) - Arguments.of( - "a09:30:17", - "a%h:%i:%s", - ExprNullValue.of(), - UNDEFINED), - Arguments.of( - "abc", - "abc", - ExprNullValue.of(), - UNDEFINED), - Arguments.of( - "2000,1", - "%Y,%m", - ExprNullValue.of(), - UNDEFINED), - Arguments.of( - "2000,1,10", - "%Y,%m,%h", - ExprNullValue.of(), - UNDEFINED), - Arguments.of( - "2000,1,10,11", - "%Y,%m,%h,%i", - ExprNullValue.of(), - UNDEFINED), - Arguments.of( - "9", - "%m", - ExprNullValue.of(), - UNDEFINED), - Arguments.of( - "9", - "%s", - ExprNullValue.of(), - UNDEFINED) - ); + // Invalid Arguments (should return null) + Arguments.of("a09:30:17", "a%h:%i:%s", ExprNullValue.of(), UNDEFINED), + Arguments.of("abc", "abc", ExprNullValue.of(), UNDEFINED), + Arguments.of("2000,1", "%Y,%m", ExprNullValue.of(), UNDEFINED), + Arguments.of("2000,1,10", "%Y,%m,%h", ExprNullValue.of(), UNDEFINED), + Arguments.of("2000,1,10,11", "%Y,%m,%h,%i", ExprNullValue.of(), UNDEFINED), + Arguments.of("9", "%m", ExprNullValue.of(), UNDEFINED), + Arguments.of("9", "%s", ExprNullValue.of(), UNDEFINED)); } @ParameterizedTest(name = "{0} | {1}") @MethodSource("getTestDataForStrToDate") public void test_str_to_date( - String datetime, - String format, - ExprValue expectedResult, - ExprCoreType expectedType) { + String datetime, String format, ExprValue expectedResult, ExprCoreType expectedType) { - FunctionExpression expression = DSL.str_to_date( - functionProperties, - DSL.literal(new ExprStringValue(datetime)), - DSL.literal(new ExprStringValue(format))); + FunctionExpression expression = + DSL.str_to_date( + functionProperties, + DSL.literal(new ExprStringValue(datetime)), + DSL.literal(new ExprStringValue(format))); ExprValue result = eval(expression); @@ -130,26 +86,25 @@ private static LocalDateTime getExpectedTimeResult(int hour, int minute, int sec LocalDate.now().getDayOfMonth(), hour, minute, - seconds - ); + seconds); } private static Stream getTestDataForStrToDateWithTime() { return Stream.of( Arguments.of("9,23,11", "%h,%i,%s"), Arguments.of("2000,9,23,11", "%Y,%h,%i,%s"), - Arguments.of("2000,3,9,23,11", "%Y,%m,%h,%i,%s") - ); + Arguments.of("2000,3,9,23,11", "%Y,%m,%h,%i,%s")); } @ParameterizedTest(name = "{1}") @MethodSource("getTestDataForStrToDateWithTime") public void test_str_to_date_with_time_type(String parsed, String format) { - FunctionExpression expression = DSL.str_to_date( - functionProperties, - DSL.literal(new ExprStringValue(parsed)), - DSL.literal(new ExprStringValue(format))); + FunctionExpression expression = + DSL.str_to_date( + functionProperties, + DSL.literal(new ExprStringValue(parsed)), + DSL.literal(new ExprStringValue(format))); ExprValue result = eval(expression); @@ -160,19 +115,21 @@ public void test_str_to_date_with_time_type(String parsed, String format) { @Test public void test_str_to_date_with_date_format() { - LocalDateTime arg = LocalDateTime.of(2023, 2, 27, 10, 11,12); + LocalDateTime arg = LocalDateTime.of(2023, 2, 27, 10, 11, 12); String format = "%Y,%m,%d %h,%i,%s"; - FunctionExpression dateFormatExpr = DSL.date_format( - functionProperties, - DSL.literal(new ExprDatetimeValue(arg)), - DSL.literal(new ExprStringValue(format))); + FunctionExpression dateFormatExpr = + DSL.date_format( + functionProperties, + DSL.literal(new ExprDatetimeValue(arg)), + DSL.literal(new ExprStringValue(format))); String dateFormatResult = eval(dateFormatExpr).stringValue(); - FunctionExpression strToDateExpr = DSL.str_to_date( - functionProperties, - DSL.literal(new ExprStringValue(dateFormatResult)), - DSL.literal(new ExprStringValue(format))); + FunctionExpression strToDateExpr = + DSL.str_to_date( + functionProperties, + DSL.literal(new ExprStringValue(dateFormatResult)), + DSL.literal(new ExprStringValue(format))); LocalDateTime strToDateResult = eval(strToDateExpr).datetimeValue(); assertEquals(arg, strToDateResult); @@ -184,24 +141,24 @@ public void test_str_to_date_with_time_format() { final int MINUTES = 11; final int SECONDS = 12; - LocalTime arg = LocalTime.of(HOURS, MINUTES,SECONDS); + LocalTime arg = LocalTime.of(HOURS, MINUTES, SECONDS); String format = "%h,%i,%s"; - FunctionExpression dateFormatExpr = DSL.time_format( - functionProperties, - DSL.literal(new ExprTimeValue(arg)), - DSL.literal(new ExprStringValue(format))); + FunctionExpression dateFormatExpr = + DSL.time_format( + functionProperties, + DSL.literal(new ExprTimeValue(arg)), + DSL.literal(new ExprStringValue(format))); String timeFormatResult = eval(dateFormatExpr).stringValue(); - FunctionExpression strToDateExpr = DSL.str_to_date( - functionProperties, - DSL.literal(new ExprStringValue(timeFormatResult)), - DSL.literal(new ExprStringValue(format))); + FunctionExpression strToDateExpr = + DSL.str_to_date( + functionProperties, + DSL.literal(new ExprStringValue(timeFormatResult)), + DSL.literal(new ExprStringValue(format))); LocalDateTime strToDateResult = eval(strToDateExpr).datetimeValue(); - assertEquals( - getExpectedTimeResult(HOURS, MINUTES, SECONDS), - strToDateResult); + assertEquals(getExpectedTimeResult(HOURS, MINUTES, SECONDS), strToDateResult); } private ExprValue eval(Expression expression) { diff --git a/core/src/test/java/org/opensearch/sql/expression/datetime/TimeDiffTest.java b/core/src/test/java/org/opensearch/sql/expression/datetime/TimeDiffTest.java index 8bfb09bd49..88218bc63c 100644 --- a/core/src/test/java/org/opensearch/sql/expression/datetime/TimeDiffTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/datetime/TimeDiffTest.java @@ -22,12 +22,12 @@ private static Stream getTestData() { Arguments.of(LocalTime.of(12, 42), LocalTime.of(7, 40), LocalTime.of(5, 2)), Arguments.of(LocalTime.of(7, 40), LocalTime.of(12, 42), LocalTime.of(18, 58)), Arguments.of(LocalTime.of(7, 40), LocalTime.of(7, 40), LocalTime.of(0, 0)), - Arguments.of(LocalTime.MAX, LocalTime.MIN, LocalTime.MAX) - ); + Arguments.of(LocalTime.MAX, LocalTime.MIN, LocalTime.MAX)); } /** * Test `TIME_DIFF` function with different data. + * * @param arg1 First argument. * @param arg2 Second argument. * @param expectedResult Expected result. @@ -36,7 +36,9 @@ private static Stream getTestData() { @MethodSource("getTestData") public void try_different_data(LocalTime arg1, LocalTime arg2, LocalTime expectedResult) { assertEquals(expectedResult, timediff(arg1, arg2)); - assertEquals(expectedResult, eval(timediff(DSL.literal(new ExprTimeValue(arg1)), - DSL.literal(new ExprTimeValue(arg2)))).timeValue()); + assertEquals( + expectedResult, + eval(timediff(DSL.literal(new ExprTimeValue(arg1)), DSL.literal(new ExprTimeValue(arg2)))) + .timeValue()); } } diff --git a/core/src/test/java/org/opensearch/sql/expression/datetime/TimeStampAddTest.java b/core/src/test/java/org/opensearch/sql/expression/datetime/TimeStampAddTest.java index 63514ab352..243eb6bb7b 100644 --- a/core/src/test/java/org/opensearch/sql/expression/datetime/TimeStampAddTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/datetime/TimeStampAddTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.datetime; import static org.junit.jupiter.api.Assertions.assertAll; @@ -36,99 +35,90 @@ class TimeStampAddTest extends ExpressionTestBase { private static Stream getTestDataForTimestampAdd() { return Stream.of( - Arguments.of("MINUTE", 1, new ExprStringValue("2003-01-02 00:00:00"), - "2003-01-02 00:01:00"), - Arguments.of("WEEK", 1, new ExprStringValue("2003-01-02 00:00:00"), - "2003-01-09 00:00:00"), - - //Date - Arguments.of("MINUTE", 1, new ExprDateValue("2003-01-02"), - "2003-01-02 00:01:00"), - Arguments.of("WEEK", 1, new ExprDateValue("2003-01-02"), - "2003-01-09 00:00:00"), - - //Datetime - Arguments.of("MINUTE", 1, new ExprDatetimeValue("2003-01-02 00:00:00"), - "2003-01-02 00:01:00"), - Arguments.of("WEEK", 1, new ExprDatetimeValue("2003-01-02 00:00:00"), - "2003-01-09 00:00:00"), - - //Timestamp - Arguments.of("MINUTE", 1, new ExprTimestampValue("2003-01-02 00:00:00"), - "2003-01-02 00:01:00"), - Arguments.of("WEEK", 1, new ExprTimestampValue("2003-01-02 00:00:00"), - "2003-01-09 00:00:00"), - - //Cases surrounding leap year - Arguments.of("SECOND", 1, new ExprTimestampValue("2020-02-28 23:59:59"), - "2020-02-29 00:00:00"), - Arguments.of("MINUTE", 1, new ExprTimestampValue("2020-02-28 23:59:59"), - "2020-02-29 00:00:59"), - Arguments.of("HOUR", 1, new ExprTimestampValue("2020-02-28 23:59:59"), - "2020-02-29 00:59:59"), - Arguments.of("DAY", 1, new ExprTimestampValue("2020-02-28 23:59:59"), - "2020-02-29 23:59:59"), - Arguments.of("WEEK", 1, new ExprTimestampValue("2020-02-28 23:59:59"), - "2020-03-06 23:59:59"), - - //Cases surrounding end-of-year - Arguments.of("SECOND", 1, new ExprTimestampValue("2020-12-31 23:59:59"), - "2021-01-01 00:00:00"), - Arguments.of("MINUTE", 1, new ExprTimestampValue("2020-12-31 23:59:59"), - "2021-01-01 00:00:59"), - Arguments.of("HOUR", 1, new ExprTimestampValue("2020-12-31 23:59:59"), - "2021-01-01 00:59:59"), - Arguments.of("DAY", 1, new ExprTimestampValue("2020-12-31 23:59:59"), - "2021-01-01 23:59:59"), - Arguments.of("WEEK", 1, new ExprTimestampValue("2020-12-31 23:59:59"), - "2021-01-07 23:59:59"), - - //Test adding a month (including special cases) - Arguments.of("MONTH", 1, new ExprStringValue("2003-01-02 00:00:00"), - "2003-02-02 00:00:00"), - Arguments.of("MONTH", 1, new ExprDateValue("2024-03-30"), - "2024-04-30 00:00:00"), - Arguments.of("MONTH", 1, new ExprDateValue("2024-03-31"), - "2024-04-30 00:00:00"), - - //Test remaining interval types - Arguments.of("MICROSECOND", 123, new ExprStringValue("2003-01-02 00:00:00"), + Arguments.of( + "MINUTE", 1, new ExprStringValue("2003-01-02 00:00:00"), "2003-01-02 00:01:00"), + Arguments.of("WEEK", 1, new ExprStringValue("2003-01-02 00:00:00"), "2003-01-09 00:00:00"), + + // Date + Arguments.of("MINUTE", 1, new ExprDateValue("2003-01-02"), "2003-01-02 00:01:00"), + Arguments.of("WEEK", 1, new ExprDateValue("2003-01-02"), "2003-01-09 00:00:00"), + + // Datetime + Arguments.of( + "MINUTE", 1, new ExprDatetimeValue("2003-01-02 00:00:00"), "2003-01-02 00:01:00"), + Arguments.of( + "WEEK", 1, new ExprDatetimeValue("2003-01-02 00:00:00"), "2003-01-09 00:00:00"), + + // Timestamp + Arguments.of( + "MINUTE", 1, new ExprTimestampValue("2003-01-02 00:00:00"), "2003-01-02 00:01:00"), + Arguments.of( + "WEEK", 1, new ExprTimestampValue("2003-01-02 00:00:00"), "2003-01-09 00:00:00"), + + // Cases surrounding leap year + Arguments.of( + "SECOND", 1, new ExprTimestampValue("2020-02-28 23:59:59"), "2020-02-29 00:00:00"), + Arguments.of( + "MINUTE", 1, new ExprTimestampValue("2020-02-28 23:59:59"), "2020-02-29 00:00:59"), + Arguments.of( + "HOUR", 1, new ExprTimestampValue("2020-02-28 23:59:59"), "2020-02-29 00:59:59"), + Arguments.of( + "DAY", 1, new ExprTimestampValue("2020-02-28 23:59:59"), "2020-02-29 23:59:59"), + Arguments.of( + "WEEK", 1, new ExprTimestampValue("2020-02-28 23:59:59"), "2020-03-06 23:59:59"), + + // Cases surrounding end-of-year + Arguments.of( + "SECOND", 1, new ExprTimestampValue("2020-12-31 23:59:59"), "2021-01-01 00:00:00"), + Arguments.of( + "MINUTE", 1, new ExprTimestampValue("2020-12-31 23:59:59"), "2021-01-01 00:00:59"), + Arguments.of( + "HOUR", 1, new ExprTimestampValue("2020-12-31 23:59:59"), "2021-01-01 00:59:59"), + Arguments.of( + "DAY", 1, new ExprTimestampValue("2020-12-31 23:59:59"), "2021-01-01 23:59:59"), + Arguments.of( + "WEEK", 1, new ExprTimestampValue("2020-12-31 23:59:59"), "2021-01-07 23:59:59"), + + // Test adding a month (including special cases) + Arguments.of("MONTH", 1, new ExprStringValue("2003-01-02 00:00:00"), "2003-02-02 00:00:00"), + Arguments.of("MONTH", 1, new ExprDateValue("2024-03-30"), "2024-04-30 00:00:00"), + Arguments.of("MONTH", 1, new ExprDateValue("2024-03-31"), "2024-04-30 00:00:00"), + + // Test remaining interval types + Arguments.of( + "MICROSECOND", + 123, + new ExprStringValue("2003-01-02 00:00:00"), "2003-01-02 00:00:00.000123"), - Arguments.of("QUARTER", 1, new ExprStringValue("2003-01-02 00:00:00"), - "2003-04-02 00:00:00"), - Arguments.of("YEAR", 1, new ExprStringValue("2003-01-02 00:00:00"), - "2004-01-02 00:00:00"), - - //Test negative value for amount (Test for all intervals) - Arguments.of("MICROSECOND", -1, new ExprStringValue("2000-01-01 00:00:00"), + Arguments.of( + "QUARTER", 1, new ExprStringValue("2003-01-02 00:00:00"), "2003-04-02 00:00:00"), + Arguments.of("YEAR", 1, new ExprStringValue("2003-01-02 00:00:00"), "2004-01-02 00:00:00"), + + // Test negative value for amount (Test for all intervals) + Arguments.of( + "MICROSECOND", + -1, + new ExprStringValue("2000-01-01 00:00:00"), "1999-12-31 23:59:59.999999"), - Arguments.of("SECOND", -1, new ExprStringValue("2000-01-01 00:00:00"), - "1999-12-31 23:59:59"), - Arguments.of("MINUTE", -1, new ExprStringValue("2000-01-01 00:00:00"), - "1999-12-31 23:59:00"), - Arguments.of("HOUR", -1, new ExprStringValue("2000-01-01 00:00:00"), - "1999-12-31 23:00:00"), - Arguments.of("DAY", -1, new ExprStringValue("2000-01-01 00:00:00"), - "1999-12-31 00:00:00"), - Arguments.of("WEEK", -1, new ExprStringValue("2000-01-01 00:00:00"), - "1999-12-25 00:00:00"), - Arguments.of("MONTH", -1, new ExprStringValue("2000-01-01 00:00:00"), - "1999-12-01 00:00:00"), - Arguments.of("QUARTER", -1, new ExprStringValue("2000-01-01 00:00:00"), - "1999-10-01 00:00:00"), - Arguments.of("YEAR", -1, new ExprStringValue("2000-01-01 00:00:00"), - "1999-01-01 00:00:00") - ); + Arguments.of( + "SECOND", -1, new ExprStringValue("2000-01-01 00:00:00"), "1999-12-31 23:59:59"), + Arguments.of( + "MINUTE", -1, new ExprStringValue("2000-01-01 00:00:00"), "1999-12-31 23:59:00"), + Arguments.of("HOUR", -1, new ExprStringValue("2000-01-01 00:00:00"), "1999-12-31 23:00:00"), + Arguments.of("DAY", -1, new ExprStringValue("2000-01-01 00:00:00"), "1999-12-31 00:00:00"), + Arguments.of("WEEK", -1, new ExprStringValue("2000-01-01 00:00:00"), "1999-12-25 00:00:00"), + Arguments.of( + "MONTH", -1, new ExprStringValue("2000-01-01 00:00:00"), "1999-12-01 00:00:00"), + Arguments.of( + "QUARTER", -1, new ExprStringValue("2000-01-01 00:00:00"), "1999-10-01 00:00:00"), + Arguments.of( + "YEAR", -1, new ExprStringValue("2000-01-01 00:00:00"), "1999-01-01 00:00:00")); } - private static FunctionExpression timestampaddQuery(String unit, - int amount, - ExprValue datetimeExpr) { + private static FunctionExpression timestampaddQuery( + String unit, int amount, ExprValue datetimeExpr) { return DSL.timestampadd( - DSL.literal(unit), - DSL.literal(new ExprIntegerValue(amount)), - DSL.literal(datetimeExpr) - ); + DSL.literal(unit), DSL.literal(new ExprIntegerValue(amount)), DSL.literal(datetimeExpr)); } @ParameterizedTest @@ -159,22 +149,19 @@ private static Stream getTestDataForTestAddingDatePartToTime() { Arguments.of("YEAR", 1, "10:11:12", LocalDate.now().plusYears(1)), Arguments.of("YEAR", 5, "10:11:12", LocalDate.now().plusYears(5)), Arguments.of("YEAR", 10, "10:11:12", LocalDate.now().plusYears(10)), - Arguments.of("YEAR", -10, "10:11:12", LocalDate.now().plusYears(-10)) - ); + Arguments.of("YEAR", -10, "10:11:12", LocalDate.now().plusYears(-10))); } @ParameterizedTest @MethodSource("getTestDataForTestAddingDatePartToTime") - public void testAddingDatePartToTime(String interval, - int addedInterval, - String timeArg, - LocalDate expectedDate) { - FunctionExpression expr = DSL.timestampadd( - functionProperties, - DSL.literal(interval), - DSL.literal(new ExprIntegerValue(addedInterval)), - DSL.literal(new ExprTimeValue(timeArg)) - ); + public void testAddingDatePartToTime( + String interval, int addedInterval, String timeArg, LocalDate expectedDate) { + FunctionExpression expr = + DSL.timestampadd( + functionProperties, + DSL.literal(interval), + DSL.literal(new ExprIntegerValue(addedInterval)), + DSL.literal(new ExprTimeValue(timeArg))); LocalDateTime expected1 = LocalDateTime.of(expectedDate, LocalTime.parse(timeArg)); @@ -187,16 +174,15 @@ public void testAddingTimePartToTime() { int addedInterval = 1; String timeArg = "10:11:12"; - FunctionExpression expr = DSL.timestampadd( - functionProperties, - DSL.literal(interval), - DSL.literal(new ExprIntegerValue(addedInterval)), - DSL.literal(new ExprTimeValue(timeArg)) - ); + FunctionExpression expr = + DSL.timestampadd( + functionProperties, + DSL.literal(interval), + DSL.literal(new ExprIntegerValue(addedInterval)), + DSL.literal(new ExprTimeValue(timeArg))); - LocalDateTime expected = LocalDateTime.of( - LocalDate.now(), - LocalTime.parse(timeArg).plusMinutes(addedInterval)); + LocalDateTime expected = + LocalDateTime.of(LocalDate.now(), LocalTime.parse(timeArg).plusMinutes(addedInterval)); assertEquals(new ExprDatetimeValue(expected), eval(expr)); } @@ -205,38 +191,27 @@ public void testAddingTimePartToTime() { public void testDifferentInputTypesHaveSameResult() { String part = "SECOND"; int amount = 1; - FunctionExpression dateExpr = timestampaddQuery( - part, - amount, - new ExprDateValue("2000-01-01")); - - FunctionExpression stringExpr = timestampaddQuery( - part, - amount, - new ExprStringValue("2000-01-01 00:00:00")); - - FunctionExpression datetimeExpr = timestampaddQuery( - part, - amount, - new ExprDatetimeValue("2000-01-01 00:00:00")); - - FunctionExpression timestampExpr = timestampaddQuery( - part, - amount, - new ExprTimestampValue("2000-01-01 00:00:00")); + FunctionExpression dateExpr = timestampaddQuery(part, amount, new ExprDateValue("2000-01-01")); + + FunctionExpression stringExpr = + timestampaddQuery(part, amount, new ExprStringValue("2000-01-01 00:00:00")); + + FunctionExpression datetimeExpr = + timestampaddQuery(part, amount, new ExprDatetimeValue("2000-01-01 00:00:00")); + + FunctionExpression timestampExpr = + timestampaddQuery(part, amount, new ExprTimestampValue("2000-01-01 00:00:00")); assertAll( () -> assertEquals(eval(dateExpr), eval(stringExpr)), () -> assertEquals(eval(dateExpr), eval(datetimeExpr)), - () -> assertEquals(eval(dateExpr), eval(timestampExpr)) - ); + () -> assertEquals(eval(dateExpr), eval(timestampExpr))); } private static Stream getInvalidTestDataForTimestampAdd() { return Stream.of( Arguments.of("WEEK", 1, new ExprStringValue("2000-13-01")), - Arguments.of("WEEK", 1, new ExprStringValue("2000-01-40")) - ); + Arguments.of("WEEK", 1, new ExprStringValue("2000-01-40"))); } @ParameterizedTest diff --git a/core/src/test/java/org/opensearch/sql/expression/datetime/TimeStampDiffTest.java b/core/src/test/java/org/opensearch/sql/expression/datetime/TimeStampDiffTest.java index b00792e048..061420ceee 100644 --- a/core/src/test/java/org/opensearch/sql/expression/datetime/TimeStampDiffTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/datetime/TimeStampDiffTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.datetime; import static org.junit.jupiter.api.Assertions.assertAll; @@ -37,11 +36,9 @@ class TimeStampDiffTest extends ExpressionTestBase { - //Helper function to create an argument based on a passed in interval type - private static ExprValue generateArg(String intervalType, - String argType, - LocalDateTime base, - int added) { + // Helper function to create an argument based on a passed in interval type + private static ExprValue generateArg( + String intervalType, String argType, LocalDateTime base, int added) { LocalDateTime arg; switch (intervalType) { case "MICROSECOND": @@ -72,9 +69,8 @@ private static ExprValue generateArg(String intervalType, arg = base.plusYears(added); break; default: - throw new SemanticCheckException(String.format( - "%s is not a valid interval type.", - intervalType)); + throw new SemanticCheckException( + String.format("%s is not a valid interval type.", intervalType)); } switch (argType) { @@ -87,92 +83,69 @@ private static ExprValue generateArg(String intervalType, case "DATETIME": return new ExprDatetimeValue(arg); case "STRING": - return new ExprStringValue(String.format( - "%04d-%02d-%02d %02d:%02d:%02d.%06d", - arg.getYear(), - arg.getMonthValue(), - arg.getDayOfMonth(), - arg.getHour(), - arg.getMinute(), - arg.getSecond(), - arg.getNano() / 1000)); + return new ExprStringValue( + String.format( + "%04d-%02d-%02d %02d:%02d:%02d.%06d", + arg.getYear(), + arg.getMonthValue(), + arg.getDayOfMonth(), + arg.getHour(), + arg.getMinute(), + arg.getSecond(), + arg.getNano() / 1000)); default: - throw new SemanticCheckException(String.format( - "%s is not a valid ExprCoreValueType.", - argType)); + throw new SemanticCheckException( + String.format("%s is not a valid ExprCoreValueType.", argType)); } } - //Generate test data to test all permutations for args (intervalType, arg1, arg2) + // Generate test data to test all permutations for args (intervalType, arg1, arg2) private static Stream getGeneralTestDataForTimestampDiff() { - //Needs to be initialized with a value to prevent a null pointer exception. - Stream testData = Stream.of(Arguments.of( - "DAY", - new ExprDateValue("2000-01-01 00:00:00"), - new ExprDateValue("2000-01-01"), - 0)); - - final String[] timeIntervalTypes = { - "MICROSECOND", - "SECOND", - "MINUTE", - "HOUR" - }; - - final String[] dateIntervalTypes = { - "DAY", - "WEEK", - "MONTH", - "QUARTER", - "YEAR" - }; + // Needs to be initialized with a value to prevent a null pointer exception. + Stream testData = + Stream.of( + Arguments.of( + "DAY", + new ExprDateValue("2000-01-01 00:00:00"), + new ExprDateValue("2000-01-01"), + 0)); + + final String[] timeIntervalTypes = {"MICROSECOND", "SECOND", "MINUTE", "HOUR"}; + final String[] dateIntervalTypes = {"DAY", "WEEK", "MONTH", "QUARTER", "YEAR"}; final String[] intervalTypes = ArrayUtils.addAll(timeIntervalTypes, dateIntervalTypes); - //TIME type not included here as it is a special case handled by a different test - final String[] expressionTypes = { - "DATE", - "DATETIME", - "TIMESTAMP", - "STRING" - }; + // TIME type not included here as it is a special case handled by a different test + final String[] expressionTypes = {"DATE", "DATETIME", "TIMESTAMP", "STRING"}; final LocalDateTime baseDateTime = LocalDateTime.of(2000, 1, 1, 0, 0, 0); final int intervalDifference = 5; - //Iterate through each permutation of argument + // Iterate through each permutation of argument for (String intervalType : intervalTypes) { for (String firstArgExpressionType : expressionTypes) { for (String secondArgExpressionType : expressionTypes) { ExprValue firstArg = generateArg(intervalType, firstArgExpressionType, baseDateTime, 0); - ExprValue secondArg = generateArg( - intervalType, - secondArgExpressionType, - baseDateTime, - intervalDifference); - - //If second arg is a DATE and you are using a unit of TIME to measure then expected is 0. - //The second arg is equal to baseDatetime in this case. - int expected = ( - secondArgExpressionType == "DATE" - && Arrays.asList(timeIntervalTypes).contains(intervalType)) - ? 0 : intervalDifference; - - testData = Stream.concat(testData, Stream.of( - Arguments.of( - intervalType, - firstArg, - secondArg, - expected), - Arguments.of( - intervalType, - secondArg, - firstArg, - -expected) - )); + ExprValue secondArg = + generateArg(intervalType, secondArgExpressionType, baseDateTime, intervalDifference); + + // If second arg is a DATE and you are using a unit of TIME to measure then expected is 0. + // The second arg is equal to baseDatetime in this case. + int expected = + (secondArgExpressionType == "DATE" + && Arrays.asList(timeIntervalTypes).contains(intervalType)) + ? 0 + : intervalDifference; + + testData = + Stream.concat( + testData, + Stream.of( + Arguments.of(intervalType, firstArg, secondArg, expected), + Arguments.of(intervalType, secondArg, firstArg, -expected))); } } } @@ -183,7 +156,7 @@ private static Stream getGeneralTestDataForTimestampDiff() { private static Stream getCornerCaseTestDataForTimestampDiff() { return Stream.of( - //Test around Leap Year + // Test around Leap Year Arguments.of( "DAY", new ExprDatetimeValue("2019-02-28 00:00:00"), @@ -195,7 +168,7 @@ private static Stream getCornerCaseTestDataForTimestampDiff() { new ExprDatetimeValue("2020-03-01 00:00:00"), 2), - //Test around year change + // Test around year change Arguments.of( "SECOND", new ExprDatetimeValue("2019-12-31 23:59:59"), @@ -210,33 +183,27 @@ private static Stream getCornerCaseTestDataForTimestampDiff() { "DAY", new ExprDatetimeValue("2019-12-31 00:00:00"), new ExprDatetimeValue("2020-01-01 00:00:00"), - 1) - ); + 1)); } - private static FunctionExpression timestampdiffQuery(FunctionProperties functionProperties, - String unit, - ExprValue datetimeExpr1, - ExprValue datetimeExpr2) { + private static FunctionExpression timestampdiffQuery( + FunctionProperties functionProperties, + String unit, + ExprValue datetimeExpr1, + ExprValue datetimeExpr2) { return DSL.timestampdiff( functionProperties, DSL.literal(unit), DSL.literal(datetimeExpr1), - DSL.literal(datetimeExpr2) - ); + DSL.literal(datetimeExpr2)); } @ParameterizedTest @MethodSource({"getGeneralTestDataForTimestampDiff", "getCornerCaseTestDataForTimestampDiff"}) - public void testTimestampdiff(String unit, - ExprValue datetimeExpr1, - ExprValue datetimeExpr2, - long expected) { - FunctionExpression expr = timestampdiffQuery( - functionProperties, - unit, - datetimeExpr1, - datetimeExpr2); + public void testTimestampdiff( + String unit, ExprValue datetimeExpr1, ExprValue datetimeExpr2, long expected) { + FunctionExpression expr = + timestampdiffQuery(functionProperties, unit, datetimeExpr1, datetimeExpr2); assertEquals(expected, eval(expr).longValue()); } @@ -250,11 +217,10 @@ private static Stream getUnits() { Arguments.of("WEEK"), Arguments.of("MONTH"), Arguments.of("QUARTER"), - Arguments.of("YEAR") - ); + Arguments.of("YEAR")); } - //Test that Time arg uses today's date with all interval/part arguments + // Test that Time arg uses today's date with all interval/part arguments @ParameterizedTest @MethodSource("getUnits") public void testTimestampDiffWithTimeType(String unit) { @@ -266,16 +232,11 @@ public void testTimestampDiffWithTimeType(String unit) { ExprValue datetimeExpr = generateArg(unit, "TIMESTAMP", base, 0); ExprValue stringExpr = generateArg(unit, "TIMESTAMP", base, 0); - ExprValue[] expressions = {timeExpr, timestampExpr, dateExpr, datetimeExpr,stringExpr}; + ExprValue[] expressions = {timeExpr, timestampExpr, dateExpr, datetimeExpr, stringExpr}; for (ExprValue arg1 : expressions) { for (ExprValue arg2 : expressions) { - FunctionExpression funcExpr = timestampdiffQuery( - functionProperties, - unit, - arg1, - arg2 - ); + FunctionExpression funcExpr = timestampdiffQuery(functionProperties, unit, arg1, arg2); assertEquals(0L, eval(funcExpr).longValue()); } @@ -293,66 +254,65 @@ private static Stream getTimestampDiffInvalidArgs() { Arguments.of("SECOND", "2023-01-01 10:11:12", "2000-01-40 10:11:12"), Arguments.of("SECOND", "2023-01-01 10:11:12", "2000-01-01 25:11:12"), Arguments.of("SECOND", "2023-01-01 10:11:12", "2000-01-01 10:70:12"), - Arguments.of("SECOND", "2023-01-01 10:11:12", "2000-01-01 10:11:70") - ); + Arguments.of("SECOND", "2023-01-01 10:11:12", "2000-01-01 10:11:70")); } @ParameterizedTest @MethodSource("getTimestampDiffInvalidArgs") public void testTimestampDiffWithInvalidTimeArgs(String unit, String arg1, String arg2) { - FunctionExpression expr = timestampdiffQuery( - functionProperties, - unit, - new ExprStringValue(arg1), - new ExprStringValue(arg2) - ); + FunctionExpression expr = + timestampdiffQuery( + functionProperties, unit, new ExprStringValue(arg1), new ExprStringValue(arg2)); assertThrows(SemanticCheckException.class, () -> eval(expr)); } @Test public void testTimestampDiffWithInvalidPartReturnsNull() { - FunctionExpression expr = timestampdiffQuery( - functionProperties, + FunctionExpression expr = + timestampdiffQuery( + functionProperties, "INVALID", - new ExprStringValue("2023-01-01 10:11:12"), - new ExprStringValue("2000-01-01 10:11:12") - ); + new ExprStringValue("2023-01-01 10:11:12"), + new ExprStringValue("2000-01-01 10:11:12")); assertEquals(ExprNullValue.of(), eval(expr)); } - //Test that different input types have the same result + // Test that different input types have the same result @Test public void testDifferentInputTypesHaveSameResult() { String part = "SECOND"; - FunctionExpression dateExpr = timestampdiffQuery( - functionProperties, - part, - new ExprDateValue("2000-01-01"), - new ExprDateValue("2000-01-02")); + FunctionExpression dateExpr = + timestampdiffQuery( + functionProperties, + part, + new ExprDateValue("2000-01-01"), + new ExprDateValue("2000-01-02")); - FunctionExpression stringExpr = timestampdiffQuery( - functionProperties, - part, - new ExprStringValue("2000-01-01 00:00:00"), - new ExprStringValue("2000-01-02 00:00:00")); + FunctionExpression stringExpr = + timestampdiffQuery( + functionProperties, + part, + new ExprStringValue("2000-01-01 00:00:00"), + new ExprStringValue("2000-01-02 00:00:00")); - FunctionExpression datetimeExpr = timestampdiffQuery( - functionProperties, - part, - new ExprDatetimeValue("2000-01-01 00:00:00"), - new ExprDatetimeValue("2000-01-02 00:00:00")); + FunctionExpression datetimeExpr = + timestampdiffQuery( + functionProperties, + part, + new ExprDatetimeValue("2000-01-01 00:00:00"), + new ExprDatetimeValue("2000-01-02 00:00:00")); - FunctionExpression timestampExpr = timestampdiffQuery( - functionProperties, - part, - new ExprTimestampValue("2000-01-01 00:00:00"), - new ExprTimestampValue("2000-01-02 00:00:00")); + FunctionExpression timestampExpr = + timestampdiffQuery( + functionProperties, + part, + new ExprTimestampValue("2000-01-01 00:00:00"), + new ExprTimestampValue("2000-01-02 00:00:00")); assertAll( () -> assertEquals(eval(dateExpr), eval(stringExpr)), () -> assertEquals(eval(dateExpr), eval(datetimeExpr)), - () -> assertEquals(eval(dateExpr), eval(timestampExpr)) - ); + () -> assertEquals(eval(dateExpr), eval(timestampExpr))); } private ExprValue eval(Expression expression) { diff --git a/core/src/test/java/org/opensearch/sql/expression/datetime/TimestampTest.java b/core/src/test/java/org/opensearch/sql/expression/datetime/TimestampTest.java index 677ad9310e..7d25c0041b 100644 --- a/core/src/test/java/org/opensearch/sql/expression/datetime/TimestampTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/datetime/TimestampTest.java @@ -39,35 +39,39 @@ public void timestamp_one_arg_string() { expr = DSL.timestamp(functionProperties, DSL.literal("1961-04-12 09:07:00.123456")); assertEquals(TIMESTAMP, expr.type()); - assertEquals(LocalDateTime.of(1961, 4, 12, 9, 7, 0, 123456000), - expr.valueOf().datetimeValue()); + assertEquals(LocalDateTime.of(1961, 4, 12, 9, 7, 0, 123456000), expr.valueOf().datetimeValue()); } /** * Check that `TIMESTAMP` function throws an exception on incorrect string input. + * * @param value A value. * @param testName A test name. */ @ParameterizedTest(name = "{1}") @CsvSource({ - "1984-02-30 12:20:42, Feb 30th", - "1984-02-10 24:00:00, 24:00:00", - "84-02-10 12:20:42, 2 digit year" + "1984-02-30 12:20:42, Feb 30th", + "1984-02-10 24:00:00, 24:00:00", + "84-02-10 12:20:42, 2 digit year" }) public void timestamp_one_arg_string_invalid_format(String value, String testName) { // exception thrown from ExprTimestampValue(String) CTOR - var exception = assertThrows(SemanticCheckException.class, - () -> DSL.timestamp(functionProperties, DSL.literal(value)).valueOf()); - assertEquals(String.format("timestamp:%s in unsupported format, please " - + "use 'yyyy-MM-dd HH:mm:ss[.SSSSSSSSS]'", value), exception.getMessage()); + var exception = + assertThrows( + SemanticCheckException.class, + () -> DSL.timestamp(functionProperties, DSL.literal(value)).valueOf()); + assertEquals( + String.format( + "timestamp:%s in unsupported format, please " + "use 'yyyy-MM-dd HH:mm:ss[.SSSSSSSSS]'", + value), + exception.getMessage()); } @Test public void timestamp_one_arg_time() { var expr = DSL.timestamp(functionProperties, DSL.time(DSL.literal("22:33:44"))); assertEquals(TIMESTAMP, expr.type()); - var refValue = LocalDate.now().atTime(LocalTime.of(22, 33, 44)) - .atZone(UTC_ZONE_ID).toInstant(); + var refValue = LocalDate.now().atTime(LocalTime.of(22, 33, 44)).atZone(UTC_ZONE_ID).toInstant(); assertEquals(new ExprTimestampValue(refValue), expr.valueOf()); } @@ -75,8 +79,7 @@ public void timestamp_one_arg_time() { public void timestamp_one_arg_date() { var expr = DSL.timestamp(functionProperties, DSL.date(DSL.literal("2077-12-15"))); assertEquals(TIMESTAMP, expr.type()); - var refValue = LocalDate.of(2077, 12, 15).atStartOfDay() - .atZone(UTC_ZONE_ID).toInstant(); + var refValue = LocalDate.of(2077, 12, 15).atStartOfDay().atZone(UTC_ZONE_ID).toInstant(); assertEquals(new ExprTimestampValue(refValue), expr.valueOf()); } @@ -90,8 +93,8 @@ public void timestamp_one_arg_datetime() { @Test public void timestamp_one_arg_timestamp() { var refValue = new ExprTimestampValue(Instant.ofEpochSecond(10050042)); - var expr = DSL.timestamp(functionProperties, - DSL.timestamp(functionProperties, DSL.literal(refValue))); + var expr = + DSL.timestamp(functionProperties, DSL.timestamp(functionProperties, DSL.literal(refValue))); assertEquals(TIMESTAMP, expr.type()); assertEquals(refValue, expr.valueOf()); } @@ -109,71 +112,115 @@ private static Stream getTestData() { // First argument of `TIMESTAMP` function, second argument and expected result value return Stream.of( // STRING and STRING/DATE/TIME/DATETIME/TIMESTAMP - Arguments.of("1961-04-12 09:07:00", "2077-12-15 01:48:00", + Arguments.of( + "1961-04-12 09:07:00", + "2077-12-15 01:48:00", dateTime2ExprTs(LocalDateTime.of(1961, 4, 12, 10, 55, 0))), - Arguments.of("1984-02-10 12:20:42", LocalDate.of(2077, 12, 21), + Arguments.of( + "1984-02-10 12:20:42", + LocalDate.of(2077, 12, 21), dateTime2ExprTs(LocalDateTime.of(1984, 2, 10, 12, 20, 42))), - Arguments.of("1961-04-12 09:07:00", LocalTime.of(1, 48), + Arguments.of( + "1961-04-12 09:07:00", + LocalTime.of(1, 48), dateTime2ExprTs(LocalDateTime.of(1961, 4, 12, 10, 55, 0))), - Arguments.of("2020-12-31 17:30:00", LocalDateTime.of(2077, 12, 21, 12, 20, 42), + Arguments.of( + "2020-12-31 17:30:00", + LocalDateTime.of(2077, 12, 21, 12, 20, 42), dateTime2ExprTs(LocalDateTime.of(2021, 1, 1, 5, 50, 42))), - Arguments.of("2020-12-31 17:30:00", Instant.ofEpochSecond(42), + Arguments.of( + "2020-12-31 17:30:00", + Instant.ofEpochSecond(42), dateTime2ExprTs(LocalDateTime.of(2020, 12, 31, 17, 30, 42))), // DATE and STRING/DATE/TIME/DATETIME/TIMESTAMP - Arguments.of(LocalDate.of(2077, 12, 21), "2077-12-15 01:48:00", + Arguments.of( + LocalDate.of(2077, 12, 21), + "2077-12-15 01:48:00", dateTime2ExprTs(LocalDateTime.of(2077, 12, 21, 1, 48, 0))), - Arguments.of(LocalDate.of(2077, 12, 21), LocalDate.of(1984, 2, 3), + Arguments.of( + LocalDate.of(2077, 12, 21), + LocalDate.of(1984, 2, 3), dateTime2ExprTs(LocalDateTime.of(2077, 12, 21, 0, 0, 0))), - Arguments.of(LocalDate.of(2077, 12, 21), LocalTime.of(22, 33, 44), + Arguments.of( + LocalDate.of(2077, 12, 21), + LocalTime.of(22, 33, 44), dateTime2ExprTs(LocalDateTime.of(2077, 12, 21, 22, 33, 44))), - Arguments.of(LocalDate.of(2077, 12, 21), LocalDateTime.of(1999, 9, 9, 22, 33, 44), + Arguments.of( + LocalDate.of(2077, 12, 21), + LocalDateTime.of(1999, 9, 9, 22, 33, 44), dateTime2ExprTs(LocalDateTime.of(2077, 12, 21, 22, 33, 44))), - Arguments.of(LocalDate.of(2077, 12, 21), Instant.ofEpochSecond(42), + Arguments.of( + LocalDate.of(2077, 12, 21), + Instant.ofEpochSecond(42), dateTime2ExprTs(LocalDateTime.of(2077, 12, 21, 0, 0, 42))), // TIME and STRING/DATE/TIME/DATETIME/TIMESTAMP - Arguments.of(LocalTime.of(9, 7, 0), "2077-12-15 01:48:00", + Arguments.of( + LocalTime.of(9, 7, 0), + "2077-12-15 01:48:00", dateTime2ExprTs(today.atTime(LocalTime.of(10, 55, 0)))), - Arguments.of(LocalTime.of(12, 20, 42), LocalDate.of(2077, 12, 21), + Arguments.of( + LocalTime.of(12, 20, 42), + LocalDate.of(2077, 12, 21), dateTime2ExprTs(today.atTime(LocalTime.of(12, 20, 42)))), - Arguments.of(LocalTime.of(9, 7, 0), LocalTime.of(1, 48), + Arguments.of( + LocalTime.of(9, 7, 0), + LocalTime.of(1, 48), dateTime2ExprTs(today.atTime(LocalTime.of(10, 55, 0)))), - Arguments.of(LocalTime.of(17, 30, 0), LocalDateTime.of(2077, 12, 21, 12, 20, 42), + Arguments.of( + LocalTime.of(17, 30, 0), + LocalDateTime.of(2077, 12, 21, 12, 20, 42), dateTime2ExprTs(today.plusDays(1).atTime(LocalTime.of(5, 50, 42)))), - Arguments.of(LocalTime.of(17, 30, 0), Instant.ofEpochSecond(42), + Arguments.of( + LocalTime.of(17, 30, 0), + Instant.ofEpochSecond(42), dateTime2ExprTs(today.atTime(LocalTime.of(17, 30, 42)))), // DATETIME and STRING/DATE/TIME/DATETIME/TIMESTAMP - Arguments.of(LocalDateTime.of(1961, 4, 12, 9, 7, 0), "2077-12-15 01:48:00", + Arguments.of( + LocalDateTime.of(1961, 4, 12, 9, 7, 0), + "2077-12-15 01:48:00", dateTime2ExprTs(LocalDateTime.of(1961, 4, 12, 10, 55, 0))), - Arguments.of(LocalDateTime.of(1984, 2, 10, 12, 20, 42), LocalDate.of(2077, 12, 21), + Arguments.of( + LocalDateTime.of(1984, 2, 10, 12, 20, 42), + LocalDate.of(2077, 12, 21), dateTime2ExprTs(LocalDateTime.of(1984, 2, 10, 12, 20, 42))), - Arguments.of(LocalDateTime.of(1961, 4, 12, 9, 7, 0), LocalTime.of(1, 48), + Arguments.of( + LocalDateTime.of(1961, 4, 12, 9, 7, 0), + LocalTime.of(1, 48), dateTime2ExprTs(LocalDateTime.of(1961, 4, 12, 10, 55, 0))), - Arguments.of(LocalDateTime.of(2020, 12, 31, 17, 30, 0), + Arguments.of( + LocalDateTime.of(2020, 12, 31, 17, 30, 0), LocalDateTime.of(2077, 12, 21, 12, 20, 42), dateTime2ExprTs(LocalDateTime.of(2021, 1, 1, 5, 50, 42))), - Arguments.of(LocalDateTime.of(2020, 12, 31, 17, 30, 0), Instant.ofEpochSecond(42), + Arguments.of( + LocalDateTime.of(2020, 12, 31, 17, 30, 0), + Instant.ofEpochSecond(42), dateTime2ExprTs(LocalDateTime.of(2020, 12, 31, 17, 30, 42))), // TIMESTAMP and STRING/DATE/TIME/DATETIME/TIMESTAMP - Arguments.of(dateTime2Instant(LocalDateTime.of(1961, 4, 12, 9, 7, 0)), + Arguments.of( + dateTime2Instant(LocalDateTime.of(1961, 4, 12, 9, 7, 0)), "2077-12-15 01:48:00", dateTime2ExprTs(LocalDateTime.of(1961, 4, 12, 10, 55, 0))), - Arguments.of(dateTime2Instant(LocalDateTime.of(1984, 2, 10, 12, 20, 42)), + Arguments.of( + dateTime2Instant(LocalDateTime.of(1984, 2, 10, 12, 20, 42)), LocalDate.of(2077, 12, 21), dateTime2ExprTs(LocalDateTime.of(1984, 2, 10, 12, 20, 42))), - Arguments.of(dateTime2Instant(LocalDateTime.of(1961, 4, 12, 9, 7, 0)), + Arguments.of( + dateTime2Instant(LocalDateTime.of(1961, 4, 12, 9, 7, 0)), LocalTime.of(1, 48), dateTime2ExprTs(LocalDateTime.of(1961, 4, 12, 10, 55, 0))), - Arguments.of(dateTime2Instant(LocalDateTime.of(2020, 12, 31, 17, 30, 0)), + Arguments.of( + dateTime2Instant(LocalDateTime.of(2020, 12, 31, 17, 30, 0)), LocalDateTime.of(2077, 12, 21, 12, 20, 42), dateTime2ExprTs(LocalDateTime.of(2021, 1, 1, 5, 50, 42))), - Arguments.of(dateTime2Instant(LocalDateTime.of(2020, 12, 31, 17, 30, 0)), + Arguments.of( + dateTime2Instant(LocalDateTime.of(2020, 12, 31, 17, 30, 0)), Instant.ofEpochSecond(42), - dateTime2ExprTs(LocalDateTime.of(2020, 12, 31, 17, 30, 42))) - ); + dateTime2ExprTs(LocalDateTime.of(2020, 12, 31, 17, 30, 42)))); } /** * Test `TIMESTAMP` function which takes 2 arguments with input of different types. + * * @param arg1 First argument to be passed to `TIMESTAMP` function. * @param arg2 Second argument to be passed to `TIMESTAMP` function. * @param expected The expected result. @@ -181,9 +228,11 @@ private static Stream getTestData() { @ParameterizedTest @MethodSource("getTestData") public void timestamp_with_two_args(Object arg1, Object arg2, ExprTimestampValue expected) { - var expr = DSL.timestamp(functionProperties, - DSL.literal(ExprValueUtils.fromObjectValue(arg1)), - DSL.literal(ExprValueUtils.fromObjectValue(arg2))); + var expr = + DSL.timestamp( + functionProperties, + DSL.literal(ExprValueUtils.fromObjectValue(arg1)), + DSL.literal(ExprValueUtils.fromObjectValue(arg2))); assertEquals(TIMESTAMP, expr.type()); assertEquals(expected, expr.valueOf()); } diff --git a/core/src/test/java/org/opensearch/sql/expression/datetime/ToSecondsTest.java b/core/src/test/java/org/opensearch/sql/expression/datetime/ToSecondsTest.java index 1e89659de7..7aa824e61d 100644 --- a/core/src/test/java/org/opensearch/sql/expression/datetime/ToSecondsTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/datetime/ToSecondsTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.datetime; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -35,7 +34,6 @@ import org.opensearch.sql.expression.ExpressionTestBase; import org.opensearch.sql.expression.FunctionExpression; - class ToSecondsTest extends ExpressionTestBase { private static final long SECONDS_FROM_0001_01_01_TO_EPOCH_START = 62167219200L; @@ -54,11 +52,9 @@ private static Stream getTestDataForToSeconds() { Arguments.of(new ExprStringValue("2009-11-29 00:00:00"), new ExprLongValue(63426672000L)), Arguments.of(new ExprStringValue("2009-11-29 13:43:32"), new ExprLongValue(63426721412L)), Arguments.of(new ExprDateValue("2009-11-29"), new ExprLongValue(63426672000L)), - Arguments.of(new ExprDatetimeValue("2009-11-29 13:43:32"), - new ExprLongValue(63426721412L)), - Arguments.of(new ExprTimestampValue("2009-11-29 13:43:32"), - new ExprLongValue(63426721412L)) - ); + Arguments.of(new ExprDatetimeValue("2009-11-29 13:43:32"), new ExprLongValue(63426721412L)), + Arguments.of( + new ExprTimestampValue("2009-11-29 13:43:32"), new ExprLongValue(63426721412L))); } @ParameterizedTest @@ -71,12 +67,13 @@ public void testToSeconds(ExprValue arg, ExprValue expected) { @Test public void testToSecondsWithTimeType() { - FunctionExpression expr = DSL.to_seconds(functionProperties, - DSL.literal(new ExprTimeValue("10:11:12"))); + FunctionExpression expr = + DSL.to_seconds(functionProperties, DSL.literal(new ExprTimeValue("10:11:12"))); - long expected = SECONDS_FROM_0001_01_01_TO_EPOCH_START - + LocalDate.now(functionProperties.getQueryStartClock()) - .toEpochSecond(LocalTime.parse("10:11:12"), ZoneOffset.UTC); + long expected = + SECONDS_FROM_0001_01_01_TO_EPOCH_START + + LocalDate.now(functionProperties.getQueryStartClock()) + .toEpochSecond(LocalTime.parse("10:11:12"), ZoneOffset.UTC); assertEquals(expected, eval(expr).longValue()); } @@ -88,8 +85,7 @@ private static Stream getInvalidTestDataForToSeconds() { Arguments.of(new ExprStringValue("2000-10-45")), Arguments.of(new ExprStringValue("2000-10-10 70:00:00")), Arguments.of(new ExprStringValue("2000-10-10 00:70:00")), - Arguments.of(new ExprStringValue("2000-10-10 00:00:70")) - ); + Arguments.of(new ExprStringValue("2000-10-10 00:00:70"))); } @ParameterizedTest @@ -106,9 +102,10 @@ public void testToSecondsWithDateAdd() { long addedSeconds = SECONDS_PER_DAY; long expected = eval(dateExpr).longValue() + addedSeconds; - FunctionExpression dateAddExpr = DSL.date_add( - DSL.literal(new ExprDateValue(date)), - DSL.literal(new ExprIntervalValue(Duration.ofSeconds(addedSeconds)))); + FunctionExpression dateAddExpr = + DSL.date_add( + DSL.literal(new ExprDateValue(date)), + DSL.literal(new ExprIntervalValue(Duration.ofSeconds(addedSeconds)))); long result = eval(DSL.to_seconds(DSL.literal(eval(dateAddExpr)))).longValue(); diff --git a/core/src/test/java/org/opensearch/sql/expression/datetime/UnixTimeStampTest.java b/core/src/test/java/org/opensearch/sql/expression/datetime/UnixTimeStampTest.java index f6e24f4e27..c979b68302 100644 --- a/core/src/test/java/org/opensearch/sql/expression/datetime/UnixTimeStampTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/datetime/UnixTimeStampTest.java @@ -43,19 +43,20 @@ private static Stream getDateSamples() { Arguments.of(LocalDate.of(1999, 12, 31)), Arguments.of(LocalDate.of(2004, 2, 29)), Arguments.of(LocalDate.of(2100, 2, 28)), - Arguments.of(LocalDate.of(2012, 2, 21)) - ); + Arguments.of(LocalDate.of(2012, 2, 21))); } /** * Check processing valid values of type LocalDate. + * * @param value a value */ @ParameterizedTest @MethodSource("getDateSamples") public void checkOfDate(LocalDate value) { assertEquals(value.getLong(ChronoField.EPOCH_DAY) * 24 * 3600, unixTimeStampOf(value)); - assertEquals(value.getLong(ChronoField.EPOCH_DAY) * 24 * 3600, + assertEquals( + value.getLong(ChronoField.EPOCH_DAY) * 24 * 3600, eval(unixTimeStampOf(DSL.literal(new ExprDateValue(value)))).longValue()); } @@ -66,36 +67,39 @@ private static Stream getDateTimeSamples() { Arguments.of(LocalDateTime.of(1999, 12, 31, 23, 59)), Arguments.of(LocalDateTime.of(2004, 2, 29, 7, 40)), Arguments.of(LocalDateTime.of(2100, 2, 28, 13, 14)), - Arguments.of(LocalDateTime.of(2012, 2, 21, 0, 0)) - ); + Arguments.of(LocalDateTime.of(2012, 2, 21, 0, 0))); } /** * Check processing valid values of type LocalDateTime. + * * @param value a value */ @ParameterizedTest @MethodSource("getDateTimeSamples") public void checkOfDateTime(LocalDateTime value) { assertEquals(value.toEpochSecond(ZoneOffset.UTC), unixTimeStampOf(value)); - assertEquals(value.toEpochSecond(ZoneOffset.UTC), + assertEquals( + value.toEpochSecond(ZoneOffset.UTC), eval(unixTimeStampOf(DSL.literal(new ExprDatetimeValue(value)))).longValue()); } private static Stream getInstantSamples() { return getDateTimeSamples() - .map(v -> Arguments.of(((LocalDateTime)v.get()[0]).toInstant(ZoneOffset.UTC))); + .map(v -> Arguments.of(((LocalDateTime) v.get()[0]).toInstant(ZoneOffset.UTC))); } /** * Check processing valid values of type Instant. + * * @param value a value */ @ParameterizedTest @MethodSource("getInstantSamples") public void checkOfInstant(Instant value) { assertEquals(value.getEpochSecond(), unixTimeStampOf(value)); - assertEquals(value.getEpochSecond(), + assertEquals( + value.getEpochSecond(), eval(unixTimeStampOf(DSL.literal(new ExprTimestampValue(value)))).longValue()); } @@ -104,17 +108,17 @@ public void checkOfInstant(Instant value) { private static Stream getDoubleSamples() { return Stream.of( Arguments.of(840101d, LocalDateTime.of(1984, 1, 1, 0, 0, 0)), - Arguments.of(840101112233d, LocalDateTime.of(1984, 1, 1, 11,22,33)), + Arguments.of(840101112233d, LocalDateTime.of(1984, 1, 1, 11, 22, 33)), Arguments.of(840101112233.123456, LocalDateTime.of(1984, 1, 1, 11, 22, 33, 123456000)), Arguments.of(19840101d, LocalDateTime.of(1984, 1, 1, 0, 0, 0)), Arguments.of(19840101000000d, LocalDateTime.of(1984, 1, 1, 0, 0, 0)), - Arguments.of(19840101112233d, LocalDateTime.of(1984, 1, 1, 11,22,33)), - Arguments.of(19840101112233.123456, LocalDateTime.of(1984, 1, 1, 11, 22, 33, 123456000)) - ); + Arguments.of(19840101112233d, LocalDateTime.of(1984, 1, 1, 11, 22, 33)), + Arguments.of(19840101112233.123456, LocalDateTime.of(1984, 1, 1, 11, 22, 33, 123456000))); } /** * Check processing valid Double values. + * * @param valueAsDouble a value * @param valueAsLDT the value as LocalDateTime */ @@ -122,11 +126,13 @@ private static Stream getDoubleSamples() { @MethodSource("getDoubleSamples") public void checkOfDoubleFormats(Double valueAsDouble, LocalDateTime valueAsLDT) { var valueAsStr = new DecimalFormat("0.#").format(valueAsDouble); - assertEquals(valueAsLDT.toEpochSecond(ZoneOffset.UTC), - unixTimeStampOf(valueAsDouble), 1d, valueAsStr); - assertEquals(valueAsLDT.toEpochSecond(ZoneOffset.UTC), + assertEquals( + valueAsLDT.toEpochSecond(ZoneOffset.UTC), unixTimeStampOf(valueAsDouble), 1d, valueAsStr); + assertEquals( + valueAsLDT.toEpochSecond(ZoneOffset.UTC), eval(unixTimeStampOf(DSL.literal(new ExprDoubleValue(valueAsDouble)))).longValue(), - 1d, valueAsStr); + 1d, + valueAsStr); } @Test @@ -165,7 +171,7 @@ public void checkMaxValue() { private static Stream getInvalidDoubleSamples() { return Stream.of( - //invalid dates + // invalid dates Arguments.of(19990231.d), Arguments.of(19991320.d), Arguments.of(19991232.d), @@ -181,7 +187,7 @@ private static Stream getInvalidDoubleSamples() { Arguments.of(9912.d), Arguments.of(199912.d), Arguments.of(1999102.d), - //same as above, but with valid time + // same as above, but with valid time Arguments.of(19990231112233.d), Arguments.of(19991320112233.d), Arguments.of(19991232112233.d), @@ -197,7 +203,7 @@ private static Stream getInvalidDoubleSamples() { Arguments.of(9912112233.d), Arguments.of(199912112233.d), Arguments.of(1999102112233.d), - //invalid time + // invalid time Arguments.of(19840101242233.d), Arguments.of(19840101116033.d), Arguments.of(19840101112260.d), @@ -206,7 +212,7 @@ private static Stream getInvalidDoubleSamples() { Arguments.of(19840101123.d), Arguments.of(1984010113.d), Arguments.of(198401011.d), - //same, but with short date + // same, but with short date Arguments.of(840101242233.d), Arguments.of(840101116033.d), Arguments.of(840101112260.d), @@ -214,23 +220,24 @@ private static Stream getInvalidDoubleSamples() { Arguments.of(8401011123.d), Arguments.of(840101123.d), Arguments.of(8401011.d), - //misc + // misc Arguments.of(0d), Arguments.of(-1d), Arguments.of(42d), - //too many digits - Arguments.of(199902201122330d) - ); + // too many digits + Arguments.of(199902201122330d)); } /** * Check processing invalid Double values. + * * @param value a value */ @ParameterizedTest @MethodSource("getInvalidDoubleSamples") public void checkInvalidDoubleCausesNull(Double value) { - assertEquals(ExprNullValue.of(), + assertEquals( + ExprNullValue.of(), unixTimeStampOf(DSL.literal(new ExprDoubleValue(value))).valueOf(), new DecimalFormat("0.#").format(value)); } diff --git a/core/src/test/java/org/opensearch/sql/expression/datetime/UnixTwoWayConversionTest.java b/core/src/test/java/org/opensearch/sql/expression/datetime/UnixTwoWayConversionTest.java index 70fe299e97..c74b062fba 100644 --- a/core/src/test/java/org/opensearch/sql/expression/datetime/UnixTwoWayConversionTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/datetime/UnixTwoWayConversionTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.datetime; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -33,8 +32,7 @@ public void checkConvertNow_with_eval() { } private LocalDateTime getExpectedNow() { - return LocalDateTime.now( - functionProperties.getQueryStartClock().withZone(UTC_ZONE_ID)) + return LocalDateTime.now(functionProperties.getQueryStartClock().withZone(UTC_ZONE_ID)) .withNano(0); } @@ -44,23 +42,25 @@ private static Stream getDoubleSamples() { Arguments.of(100500.100500d), Arguments.of(1447430881.564d), Arguments.of(2147483647.451232d), - Arguments.of(1662577241.d) - ); + Arguments.of(1662577241.d)); } /** * Test converting valid Double values EpochTime -> DateTime -> EpochTime. + * * @param value a value */ @ParameterizedTest @MethodSource("getDoubleSamples") public void convertEpoch2DateTime2Epoch(Double value) { assertEquals(value, unixTimeStampOf(fromUnixTime(value))); - assertEquals(value, + assertEquals( + value, eval(unixTimeStampOf(fromUnixTime(DSL.literal(new ExprDoubleValue(value))))).doubleValue()); assertEquals(Math.round(value) + 0d, unixTimeStampOf(fromUnixTime(Math.round(value)))); - assertEquals(Math.round(value) + 0d, + assertEquals( + Math.round(value) + 0d, eval(unixTimeStampOf(fromUnixTime(DSL.literal(new ExprLongValue(Math.round(value)))))) .doubleValue()); } @@ -72,19 +72,20 @@ private static Stream getDateTimeSamples() { Arguments.of(LocalDateTime.of(1999, 12, 31, 23, 59, 59)), Arguments.of(LocalDateTime.of(2004, 2, 29, 7, 40)), Arguments.of(LocalDateTime.of(2100, 2, 28, 13, 14, 15)), - Arguments.of(LocalDateTime.of(2012, 2, 21, 0, 0, 17)) - ); + Arguments.of(LocalDateTime.of(2012, 2, 21, 0, 0, 17))); } /** * Test converting valid values DateTime -> EpochTime -> DateTime. + * * @param value a value */ @ParameterizedTest @MethodSource("getDateTimeSamples") public void convertDateTime2Epoch2DateTime(LocalDateTime value) { assertEquals(value, fromUnixTime(unixTimeStampOf(value))); - assertEquals(value, + assertEquals( + value, eval(fromUnixTime(unixTimeStampOf(DSL.literal(new ExprDatetimeValue(value))))) .datetimeValue()); } diff --git a/core/src/test/java/org/opensearch/sql/expression/datetime/WeekdayTest.java b/core/src/test/java/org/opensearch/sql/expression/datetime/WeekdayTest.java index 4b97639996..d2a6394503 100644 --- a/core/src/test/java/org/opensearch/sql/expression/datetime/WeekdayTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/datetime/WeekdayTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.datetime; import static org.junit.jupiter.api.Assertions.assertAll; @@ -28,109 +27,89 @@ import org.opensearch.sql.expression.FunctionExpression; import org.opensearch.sql.expression.LiteralExpression; - class WeekdayTest extends ExpressionTestBase { - private void weekdayQuery( - FunctionExpression dateExpression, - int dayOfWeek, - String testExpr) { + private void weekdayQuery(FunctionExpression dateExpression, int dayOfWeek, String testExpr) { assertAll( () -> assertEquals(INTEGER, dateExpression.type()), () -> assertEquals(integerValue(dayOfWeek), eval(dateExpression)), - () -> assertEquals(testExpr, dateExpression.toString()) - ); + () -> assertEquals(testExpr, dateExpression.toString())); } private static Stream getTestDataForWeekday() { return Stream.of( - Arguments.of( - DSL.literal(new ExprDateValue("2020-08-07")), - 4, - "weekday(DATE '2020-08-07')"), - Arguments.of( - DSL.literal(new ExprDateValue("2020-08-09")), - 6, - "weekday(DATE '2020-08-09')"), - Arguments.of( - DSL.literal("2020-08-09"), - 6, - "weekday(\"2020-08-09\")"), - Arguments.of( - DSL.literal("2020-08-09 01:02:03"), - 6, - "weekday(\"2020-08-09 01:02:03\")") - ); + Arguments.of(DSL.literal(new ExprDateValue("2020-08-07")), 4, "weekday(DATE '2020-08-07')"), + Arguments.of(DSL.literal(new ExprDateValue("2020-08-09")), 6, "weekday(DATE '2020-08-09')"), + Arguments.of(DSL.literal("2020-08-09"), 6, "weekday(\"2020-08-09\")"), + Arguments.of(DSL.literal("2020-08-09 01:02:03"), 6, "weekday(\"2020-08-09 01:02:03\")")); } @MethodSource("getTestDataForWeekday") @ParameterizedTest public void weekday(LiteralExpression arg, int expectedInt, String expectedString) { - FunctionExpression expression = DSL.weekday( - functionProperties, - arg); + FunctionExpression expression = DSL.weekday(functionProperties, arg); weekdayQuery(expression, expectedInt, expectedString); } @Test public void testWeekdayWithTimeType() { - FunctionExpression expression = DSL.weekday( - functionProperties, DSL.literal(new ExprTimeValue("12:23:34"))); + FunctionExpression expression = + DSL.weekday(functionProperties, DSL.literal(new ExprTimeValue("12:23:34"))); assertAll( () -> assertEquals(INTEGER, eval(expression).type()), - () -> assertEquals(( - LocalDate.now( - functionProperties.getQueryStartClock()).getDayOfWeek().getValue() - 1), - eval(expression).integerValue()), - () -> assertEquals("weekday(TIME '12:23:34')", expression.toString()) - ); + () -> + assertEquals( + (LocalDate.now(functionProperties.getQueryStartClock()).getDayOfWeek().getValue() + - 1), + eval(expression).integerValue()), + () -> assertEquals("weekday(TIME '12:23:34')", expression.toString())); } private void testInvalidWeekday(String date) { - FunctionExpression expression = DSL.weekday( - functionProperties, DSL.literal(new ExprDateValue(date))); + FunctionExpression expression = + DSL.weekday(functionProperties, DSL.literal(new ExprDateValue(date))); eval(expression); } @Test public void weekdayLeapYear() { assertAll( - //Feb. 29 of a leap year - () -> weekdayQuery(DSL.weekday( - functionProperties, - DSL.literal("2020-02-29")), 5, "weekday(\"2020-02-29\")"), - //day after Feb. 29 of a leap year - () -> weekdayQuery(DSL.weekday( - functionProperties, - DSL.literal("2020-03-01")), 6, "weekday(\"2020-03-01\")"), - //Feb. 28 of a non-leap year - () -> weekdayQuery(DSL.weekday( - functionProperties, - DSL.literal("2021-02-28")), 6, "weekday(\"2021-02-28\")"), - //Feb. 29 of a non-leap year - () -> assertThrows( - SemanticCheckException.class, () -> testInvalidWeekday("2021-02-29")) - ); + // Feb. 29 of a leap year + () -> + weekdayQuery( + DSL.weekday(functionProperties, DSL.literal("2020-02-29")), + 5, + "weekday(\"2020-02-29\")"), + // day after Feb. 29 of a leap year + () -> + weekdayQuery( + DSL.weekday(functionProperties, DSL.literal("2020-03-01")), + 6, + "weekday(\"2020-03-01\")"), + // Feb. 28 of a non-leap year + () -> + weekdayQuery( + DSL.weekday(functionProperties, DSL.literal("2021-02-28")), + 6, + "weekday(\"2021-02-28\")"), + // Feb. 29 of a non-leap year + () -> assertThrows(SemanticCheckException.class, () -> testInvalidWeekday("2021-02-29"))); } @Test public void weekdayInvalidArgument() { assertAll( - //40th day of the month - () -> assertThrows(SemanticCheckException.class, - () -> testInvalidWeekday("2021-02-40")), - - //13th month of the year - () -> assertThrows(SemanticCheckException.class, - () -> testInvalidWeekday("2021-13-29")), - - //incorrect format - () -> assertThrows(SemanticCheckException.class, - () -> testInvalidWeekday("asdfasdf")) - ); + // 40th day of the month + () -> assertThrows(SemanticCheckException.class, () -> testInvalidWeekday("2021-02-40")), + + // 13th month of the year + () -> assertThrows(SemanticCheckException.class, () -> testInvalidWeekday("2021-13-29")), + + // incorrect format + () -> assertThrows(SemanticCheckException.class, () -> testInvalidWeekday("asdfasdf"))); } private ExprValue eval(Expression expression) { diff --git a/core/src/test/java/org/opensearch/sql/expression/datetime/YearweekTest.java b/core/src/test/java/org/opensearch/sql/expression/datetime/YearweekTest.java index 7517c5e8bf..4f7208d141 100644 --- a/core/src/test/java/org/opensearch/sql/expression/datetime/YearweekTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/datetime/YearweekTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.datetime; import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_YEAR; @@ -32,20 +31,18 @@ class YearweekTest extends ExpressionTestBase { private void yearweekQuery(String date, int mode, int expectedResult) { - FunctionExpression expression = DSL - .yearweek( - functionProperties, - DSL.literal(new ExprDateValue(date)), DSL.literal(mode)); + FunctionExpression expression = + DSL.yearweek(functionProperties, DSL.literal(new ExprDateValue(date)), DSL.literal(mode)); assertAll( () -> assertEquals(INTEGER, expression.type()), - () -> assertEquals( - String.format("yearweek(DATE '%s', %d)", date, mode), expression.toString()), - () -> assertEquals(integerValue(expectedResult), eval(expression)) - ); + () -> + assertEquals( + String.format("yearweek(DATE '%s', %d)", date, mode), expression.toString()), + () -> assertEquals(integerValue(expectedResult), eval(expression))); } private static Stream getTestDataForYearweek() { - //Test the behavior of different modes passed into the 'yearweek' function + // Test the behavior of different modes passed into the 'yearweek' function return Stream.of( Arguments.of("2019-01-05", 0, 201852), Arguments.of("2019-01-05", 1, 201901), @@ -78,8 +75,7 @@ private static Stream getTestDataForYearweek() { Arguments.of("1999-01-01", 1, 199852), Arguments.of("1999-01-01", 4, 199852), Arguments.of("1999-01-01", 5, 199852), - Arguments.of("1999-01-01", 6, 199852) - ); + Arguments.of("1999-01-01", 6, 199852)); } @ParameterizedTest(name = "{0} | {1}") @@ -90,17 +86,13 @@ public void testYearweak(String date, int mode, int expected) { @Test public void testYearweekWithoutMode() { - LocalDate date = LocalDate.of(2019,1,05); + LocalDate date = LocalDate.of(2019, 1, 05); - FunctionExpression expression = DSL - .yearweek( - functionProperties, - DSL.literal(new ExprDateValue(date)), DSL.literal(0)); + FunctionExpression expression = + DSL.yearweek(functionProperties, DSL.literal(new ExprDateValue(date)), DSL.literal(0)); - FunctionExpression expressionWithoutMode = DSL - .yearweek( - functionProperties, - DSL.literal(new ExprDateValue(date))); + FunctionExpression expressionWithoutMode = + DSL.yearweek(functionProperties, DSL.literal(new ExprDateValue(date))); assertEquals(eval(expression), eval(expressionWithoutMode)); } @@ -111,58 +103,53 @@ public void testYearweekWithTimeType() { int year = LocalDate.now(functionProperties.getQueryStartClock()).getYear(); int expected = Integer.parseInt(String.format("%d%02d", year, week)); - FunctionExpression expression = DSL - .yearweek( - functionProperties, - DSL.literal(new ExprTimeValue("10:11:12")), DSL.literal(0)); + FunctionExpression expression = + DSL.yearweek( + functionProperties, DSL.literal(new ExprTimeValue("10:11:12")), DSL.literal(0)); - FunctionExpression expressionWithoutMode = DSL - .yearweek( - functionProperties, - DSL.literal(new ExprTimeValue("10:11:12"))); + FunctionExpression expressionWithoutMode = + DSL.yearweek(functionProperties, DSL.literal(new ExprTimeValue("10:11:12"))); assertAll( () -> assertEquals(expected, eval(expression).integerValue()), - () -> assertEquals(expected, eval(expressionWithoutMode).integerValue()) - ); + () -> assertEquals(expected, eval(expressionWithoutMode).integerValue())); } @Test public void testInvalidYearWeek() { assertAll( - //test invalid month - () -> assertThrows( - SemanticCheckException.class, - () -> yearweekQuery("2019-13-05 01:02:03", 0, 0)), - //test invalid day - () -> assertThrows( - SemanticCheckException.class, - () -> yearweekQuery("2019-01-50 01:02:03", 0, 0)), - //test invalid leap year - () -> assertThrows( - SemanticCheckException.class, - () -> yearweekQuery("2019-02-29 01:02:03", 0, 0)) - ); + // test invalid month + () -> + assertThrows( + SemanticCheckException.class, () -> yearweekQuery("2019-13-05 01:02:03", 0, 0)), + // test invalid day + () -> + assertThrows( + SemanticCheckException.class, () -> yearweekQuery("2019-01-50 01:02:03", 0, 0)), + // test invalid leap year + () -> + assertThrows( + SemanticCheckException.class, () -> yearweekQuery("2019-02-29 01:02:03", 0, 0))); } @Test public void yearweekModeInUnsupportedFormat() { - FunctionExpression expression1 = DSL - .yearweek( + FunctionExpression expression1 = + DSL.yearweek( functionProperties, - DSL.literal(new ExprDatetimeValue("2019-01-05 10:11:12")), DSL.literal(8)); + DSL.literal(new ExprDatetimeValue("2019-01-05 10:11:12")), + DSL.literal(8)); SemanticCheckException exception = assertThrows(SemanticCheckException.class, () -> eval(expression1)); - assertEquals("mode:8 is invalid, please use mode value between 0-7", - exception.getMessage()); + assertEquals("mode:8 is invalid, please use mode value between 0-7", exception.getMessage()); - FunctionExpression expression2 = DSL - .yearweek( + FunctionExpression expression2 = + DSL.yearweek( functionProperties, - DSL.literal(new ExprDatetimeValue("2019-01-05 10:11:12")), DSL.literal(-1)); + DSL.literal(new ExprDatetimeValue("2019-01-05 10:11:12")), + DSL.literal(-1)); exception = assertThrows(SemanticCheckException.class, () -> eval(expression2)); - assertEquals("mode:-1 is invalid, please use mode value between 0-7", - exception.getMessage()); + assertEquals("mode:-1 is invalid, please use mode value between 0-7", exception.getMessage()); } private ExprValue eval(Expression expression) { diff --git a/core/src/test/java/org/opensearch/sql/expression/function/BuiltinFunctionNameTest.java b/core/src/test/java/org/opensearch/sql/expression/function/BuiltinFunctionNameTest.java index 075d809544..774c471b7d 100644 --- a/core/src/test/java/org/opensearch/sql/expression/function/BuiltinFunctionNameTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/function/BuiltinFunctionNameTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.function; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -20,8 +19,7 @@ class BuiltinFunctionNameTest { private static Stream ofArguments() { Stream.Builder builder = Stream.builder(); - return Arrays.asList(BuiltinFunctionName.values()) - .stream() + return Arrays.asList(BuiltinFunctionName.values()).stream() .map(functionName -> Arguments.of(functionName.getName().getFunctionName(), functionName)); } diff --git a/core/src/test/java/org/opensearch/sql/expression/function/BuiltinFunctionRepositoryTest.java b/core/src/test/java/org/opensearch/sql/expression/function/BuiltinFunctionRepositoryTest.java index 98a4c32e2e..3ee12f59d4 100644 --- a/core/src/test/java/org/opensearch/sql/expression/function/BuiltinFunctionRepositoryTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/function/BuiltinFunctionRepositoryTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.function; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -47,20 +46,13 @@ @ExtendWith(MockitoExtension.class) class BuiltinFunctionRepositoryTest { - @Mock - private DefaultFunctionResolver mockfunctionResolver; - @Mock - private Map mockMap; - @Mock - FunctionProperties functionProperties; - @Mock - private FunctionName mockFunctionName; - @Mock - private FunctionBuilder functionExpressionBuilder; - @Mock - private FunctionSignature functionSignature; - @Mock - private Expression mockExpression; + @Mock private DefaultFunctionResolver mockfunctionResolver; + @Mock private Map mockMap; + @Mock FunctionProperties functionProperties; + @Mock private FunctionName mockFunctionName; + @Mock private FunctionBuilder functionExpressionBuilder; + @Mock private FunctionSignature functionSignature; + @Mock private Expression mockExpression; private BuiltinFunctionRepository repo; @@ -83,16 +75,15 @@ void compile() { when(mockExpression.type()).thenReturn(UNDEFINED); when(functionSignature.getParamTypeList()).thenReturn(Arrays.asList(UNDEFINED)); when(mockfunctionResolver.getFunctionName()).thenReturn(mockFunctionName); - when(mockfunctionResolver.resolve(any())).thenReturn( - Pair.of(functionSignature, functionExpressionBuilder)); + when(mockfunctionResolver.resolve(any())) + .thenReturn(Pair.of(functionSignature, functionExpressionBuilder)); when(mockMap.containsKey(mockFunctionName)).thenReturn(true); when(mockMap.get(mockFunctionName)).thenReturn(mockfunctionResolver); BuiltinFunctionRepository repo = new BuiltinFunctionRepository(mockMap); repo.register(mockfunctionResolver); repo.compile(functionProperties, mockFunctionName, Arrays.asList(mockExpression)); - verify(functionExpressionBuilder, times(1)) - .apply(eq(functionProperties), any()); + verify(functionExpressionBuilder, times(1)).apply(eq(functionProperties), any()); } @Test @@ -101,8 +92,8 @@ void compile_datasource_defined_function() { when(mockExpression.type()).thenReturn(UNDEFINED); when(functionSignature.getParamTypeList()).thenReturn(Arrays.asList(UNDEFINED)); when(dataSourceFunctionResolver.getFunctionName()).thenReturn(mockFunctionName); - when(dataSourceFunctionResolver.resolve(any())).thenReturn( - Pair.of(functionSignature, functionExpressionBuilder)); + when(dataSourceFunctionResolver.resolve(any())) + .thenReturn(Pair.of(functionSignature, functionExpressionBuilder)); BuiltinFunctionRepository repo = new BuiltinFunctionRepository(Map.of()); repo.compile( @@ -110,8 +101,7 @@ void compile_datasource_defined_function() { Collections.singletonList(dataSourceFunctionResolver), mockFunctionName, Arrays.asList(mockExpression)); - verify(functionExpressionBuilder, times(1)) - .apply(eq(functionProperties), any()); + verify(functionExpressionBuilder, times(1)).apply(eq(functionProperties), any()); } @Test @@ -119,22 +109,23 @@ void compile_datasource_defined_function() { void resolve() { when(functionSignature.getFunctionName()).thenReturn(mockFunctionName); when(mockfunctionResolver.getFunctionName()).thenReturn(mockFunctionName); - when(mockfunctionResolver.resolve(functionSignature)).thenReturn( - Pair.of(functionSignature, functionExpressionBuilder)); + when(mockfunctionResolver.resolve(functionSignature)) + .thenReturn(Pair.of(functionSignature, functionExpressionBuilder)); when(mockMap.containsKey(mockFunctionName)).thenReturn(true); when(mockMap.get(mockFunctionName)).thenReturn(mockfunctionResolver); BuiltinFunctionRepository repo = new BuiltinFunctionRepository(mockMap); repo.register(mockfunctionResolver); - assertEquals(functionExpressionBuilder, repo.resolve( - Collections.emptyList(), functionSignature)); + assertEquals( + functionExpressionBuilder, repo.resolve(Collections.emptyList(), functionSignature)); } @Test void resolve_should_not_cast_arguments_in_cast_function() { when(mockExpression.toString()).thenReturn("string"); FunctionImplementation function = - repo.resolve(Collections.emptyList(), + repo.resolve( + Collections.emptyList(), registerFunctionResolver(CAST_TO_BOOLEAN.getName(), DATETIME, BOOLEAN)) .apply(functionProperties, ImmutableList.of(mockExpression)); assertEquals("cast_to_boolean(string)", function.toString()); @@ -145,8 +136,8 @@ void resolve_should_not_cast_arguments_if_same_type() { when(mockFunctionName.getFunctionName()).thenReturn("mock"); when(mockExpression.toString()).thenReturn("string"); FunctionImplementation function = - repo.resolve(Collections.emptyList(), - registerFunctionResolver(mockFunctionName, STRING, STRING)) + repo.resolve( + Collections.emptyList(), registerFunctionResolver(mockFunctionName, STRING, STRING)) .apply(functionProperties, ImmutableList.of(mockExpression)); assertEquals("mock(string)", function.toString()); } @@ -156,8 +147,8 @@ void resolve_should_not_cast_arguments_if_both_numbers() { when(mockFunctionName.getFunctionName()).thenReturn("mock"); when(mockExpression.toString()).thenReturn("byte"); FunctionImplementation function = - repo.resolve(Collections.emptyList(), - registerFunctionResolver(mockFunctionName, BYTE, INTEGER)) + repo.resolve( + Collections.emptyList(), registerFunctionResolver(mockFunctionName, BYTE, INTEGER)) .apply(functionProperties, ImmutableList.of(mockExpression)); assertEquals("mock(byte)", function.toString()); } @@ -168,8 +159,7 @@ void resolve_should_cast_arguments() { when(mockExpression.toString()).thenReturn("string"); when(mockExpression.type()).thenReturn(STRING); - FunctionSignature signature = - registerFunctionResolver(mockFunctionName, STRING, BOOLEAN); + FunctionSignature signature = registerFunctionResolver(mockFunctionName, STRING, BOOLEAN); registerFunctionResolver(CAST_TO_BOOLEAN.getName(), STRING, STRING); FunctionImplementation function = @@ -181,10 +171,13 @@ void resolve_should_cast_arguments() { @Test void resolve_should_throw_exception_for_unsupported_conversion() { ExpressionEvaluationException error = - assertThrows(ExpressionEvaluationException.class, () -> - repo.resolve(Collections.emptyList(), - registerFunctionResolver(mockFunctionName, BYTE, STRUCT)) - .apply(functionProperties, ImmutableList.of(mockExpression))); + assertThrows( + ExpressionEvaluationException.class, + () -> + repo.resolve( + Collections.emptyList(), + registerFunctionResolver(mockFunctionName, BYTE, STRUCT)) + .apply(functionProperties, ImmutableList.of(mockExpression))); assertEquals(error.getMessage(), "Type conversion to type STRUCT is not supported"); } @@ -195,33 +188,37 @@ void resolve_unregistered() { BuiltinFunctionRepository repo = new BuiltinFunctionRepository(mockMap); repo.register(mockfunctionResolver); - ExpressionEvaluationException exception = assertThrows(ExpressionEvaluationException.class, - () -> repo.resolve(Collections.emptyList(), - new FunctionSignature(FunctionName.of("unknown"), List.of()))); + ExpressionEvaluationException exception = + assertThrows( + ExpressionEvaluationException.class, + () -> + repo.resolve( + Collections.emptyList(), + new FunctionSignature(FunctionName.of("unknown"), List.of()))); assertEquals("unsupported function name: unknown", exception.getMessage()); } - private FunctionSignature registerFunctionResolver(FunctionName funcName, - ExprType sourceType, - ExprType targetType) { - FunctionSignature unresolvedSignature = new FunctionSignature( - funcName, ImmutableList.of(sourceType)); - FunctionSignature resolvedSignature = new FunctionSignature( - funcName, ImmutableList.of(targetType)); + private FunctionSignature registerFunctionResolver( + FunctionName funcName, ExprType sourceType, ExprType targetType) { + FunctionSignature unresolvedSignature = + new FunctionSignature(funcName, ImmutableList.of(sourceType)); + FunctionSignature resolvedSignature = + new FunctionSignature(funcName, ImmutableList.of(targetType)); DefaultFunctionResolver funcResolver = mock(DefaultFunctionResolver.class); FunctionBuilder funcBuilder = mock(FunctionBuilder.class); when(mockMap.containsKey(eq(funcName))).thenReturn(true); when(mockMap.get(eq(funcName))).thenReturn(funcResolver); - when(funcResolver.resolve(eq(unresolvedSignature))).thenReturn( - Pair.of(resolvedSignature, funcBuilder)); + when(funcResolver.resolve(eq(unresolvedSignature))) + .thenReturn(Pair.of(resolvedSignature, funcBuilder)); repo.register(funcResolver); // Relax unnecessary stubbing check because error case test doesn't call this - lenient().doAnswer(invocation -> - new FakeFunctionExpression(funcName, invocation.getArgument(1)) - ).when(funcBuilder).apply(eq(functionProperties), any()); + lenient() + .doAnswer(invocation -> new FakeFunctionExpression(funcName, invocation.getArgument(1))) + .when(funcBuilder) + .apply(eq(functionProperties), any()); return unresolvedSignature; } @@ -244,8 +241,9 @@ public ExprType type() { @Override public String toString() { return getFunctionName().getFunctionName() - + "(" + StringUtils.join(getArguments(), ", ") + ")"; + + "(" + + StringUtils.join(getArguments(), ", ") + + ")"; } } - } diff --git a/core/src/test/java/org/opensearch/sql/expression/function/DefaultFunctionResolverTest.java b/core/src/test/java/org/opensearch/sql/expression/function/DefaultFunctionResolverTest.java index 202c1bd0aa..ad9e8a6661 100644 --- a/core/src/test/java/org/opensearch/sql/expression/function/DefaultFunctionResolverTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/function/DefaultFunctionResolverTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.function; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -27,32 +26,24 @@ @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) @ExtendWith(MockitoExtension.class) class DefaultFunctionResolverTest { - @Mock - private FunctionSignature exactlyMatchFS; - @Mock - private FunctionSignature bestMatchFS; - @Mock - private FunctionSignature leastMatchFS; - @Mock - private FunctionSignature notMatchFS; - @Mock - private FunctionSignature functionSignature; - @Mock - private FunctionBuilder exactlyMatchBuilder; - @Mock - private FunctionBuilder bestMatchBuilder; - @Mock - private FunctionBuilder leastMatchBuilder; - @Mock - private FunctionBuilder notMatchBuilder; + @Mock private FunctionSignature exactlyMatchFS; + @Mock private FunctionSignature bestMatchFS; + @Mock private FunctionSignature leastMatchFS; + @Mock private FunctionSignature notMatchFS; + @Mock private FunctionSignature functionSignature; + @Mock private FunctionBuilder exactlyMatchBuilder; + @Mock private FunctionBuilder bestMatchBuilder; + @Mock private FunctionBuilder leastMatchBuilder; + @Mock private FunctionBuilder notMatchBuilder; private FunctionName functionName = FunctionName.of("add"); @Test void resolve_function_signature_exactly_match() { when(functionSignature.match(exactlyMatchFS)).thenReturn(WideningTypeRule.TYPE_EQUAL); - DefaultFunctionResolver resolver = new DefaultFunctionResolver(functionName, - ImmutableMap.of(exactlyMatchFS, exactlyMatchBuilder)); + DefaultFunctionResolver resolver = + new DefaultFunctionResolver( + functionName, ImmutableMap.of(exactlyMatchFS, exactlyMatchBuilder)); assertEquals(exactlyMatchBuilder, resolver.resolve(functionSignature).getValue()); } @@ -61,8 +52,10 @@ void resolve_function_signature_exactly_match() { void resolve_function_signature_best_match() { when(functionSignature.match(bestMatchFS)).thenReturn(1); when(functionSignature.match(leastMatchFS)).thenReturn(2); - DefaultFunctionResolver resolver = new DefaultFunctionResolver(functionName, - ImmutableMap.of(bestMatchFS, bestMatchBuilder, leastMatchFS, leastMatchBuilder)); + DefaultFunctionResolver resolver = + new DefaultFunctionResolver( + functionName, + ImmutableMap.of(bestMatchFS, bestMatchBuilder, leastMatchFS, leastMatchBuilder)); assertEquals(bestMatchBuilder, resolver.resolve(functionSignature).getValue()); } @@ -72,12 +65,14 @@ void resolve_function_not_match() { when(functionSignature.match(notMatchFS)).thenReturn(WideningTypeRule.IMPOSSIBLE_WIDENING); when(notMatchFS.formatTypes()).thenReturn("[INTEGER,INTEGER]"); when(functionSignature.formatTypes()).thenReturn("[BOOLEAN,BOOLEAN]"); - DefaultFunctionResolver resolver = new DefaultFunctionResolver(functionName, - ImmutableMap.of(notMatchFS, notMatchBuilder)); - - ExpressionEvaluationException exception = assertThrows(ExpressionEvaluationException.class, - () -> resolver.resolve(functionSignature)); - assertEquals("add function expected {[INTEGER,INTEGER]}, but get [BOOLEAN,BOOLEAN]", + DefaultFunctionResolver resolver = + new DefaultFunctionResolver(functionName, ImmutableMap.of(notMatchFS, notMatchBuilder)); + + ExpressionEvaluationException exception = + assertThrows( + ExpressionEvaluationException.class, () -> resolver.resolve(functionSignature)); + assertEquals( + "add function expected {[INTEGER,INTEGER]}, but get [BOOLEAN,BOOLEAN]", exception.getMessage()); } @@ -88,8 +83,8 @@ void resolve_varargs_function_signature_match() { when(functionSignature.getParamTypeList()).thenReturn(ImmutableList.of(STRING)); when(bestMatchFS.getParamTypeList()).thenReturn(ImmutableList.of(ARRAY)); - DefaultFunctionResolver resolver = new DefaultFunctionResolver(functionName, - ImmutableMap.of(bestMatchFS, bestMatchBuilder)); + DefaultFunctionResolver resolver = + new DefaultFunctionResolver(functionName, ImmutableMap.of(bestMatchFS, bestMatchBuilder)); assertEquals(bestMatchBuilder, resolver.resolve(functionSignature).getValue()); } @@ -102,13 +97,13 @@ void resolve_varargs_no_args_function_signature_not_match() { // Concat function with no arguments when(functionSignature.getParamTypeList()).thenReturn(Collections.emptyList()); - DefaultFunctionResolver resolver = new DefaultFunctionResolver(functionName, - ImmutableMap.of(bestMatchFS, bestMatchBuilder)); + DefaultFunctionResolver resolver = + new DefaultFunctionResolver(functionName, ImmutableMap.of(bestMatchFS, bestMatchBuilder)); - ExpressionEvaluationException exception = assertThrows(ExpressionEvaluationException.class, - () -> resolver.resolve(functionSignature)); - assertEquals("concat function expected 1-9 arguments, but got 0", - exception.getMessage()); + ExpressionEvaluationException exception = + assertThrows( + ExpressionEvaluationException.class, () -> resolver.resolve(functionSignature)); + assertEquals("concat function expected 1-9 arguments, but got 0", exception.getMessage()); } @Test @@ -117,16 +112,17 @@ void resolve_varargs_too_many_args_function_signature_not_match() { when(functionSignature.match(bestMatchFS)).thenReturn(WideningTypeRule.TYPE_EQUAL); when(bestMatchFS.getParamTypeList()).thenReturn(ImmutableList.of(ARRAY)); // Concat function with more than 9 arguments - when(functionSignature.getParamTypeList()).thenReturn(ImmutableList - .of(STRING, STRING, STRING, STRING, STRING, - STRING, STRING, STRING, STRING, STRING)); - - DefaultFunctionResolver resolver = new DefaultFunctionResolver(functionName, - ImmutableMap.of(bestMatchFS, bestMatchBuilder)); - - ExpressionEvaluationException exception = assertThrows(ExpressionEvaluationException.class, - () -> resolver.resolve(functionSignature)); - assertEquals("concat function expected 1-9 arguments, but got 10", - exception.getMessage()); + when(functionSignature.getParamTypeList()) + .thenReturn( + ImmutableList.of( + STRING, STRING, STRING, STRING, STRING, STRING, STRING, STRING, STRING, STRING)); + + DefaultFunctionResolver resolver = + new DefaultFunctionResolver(functionName, ImmutableMap.of(bestMatchFS, bestMatchBuilder)); + + ExpressionEvaluationException exception = + assertThrows( + ExpressionEvaluationException.class, () -> resolver.resolve(functionSignature)); + assertEquals("concat function expected 1-9 arguments, but got 10", exception.getMessage()); } } diff --git a/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLDefineTest.java b/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLDefineTest.java index 8bf4d7ba24..670605c5a0 100644 --- a/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLDefineTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLDefineTest.java @@ -52,16 +52,15 @@ void define_name_test() { static class SampleFunctionBuilder implements FunctionBuilder { @Override - public FunctionImplementation apply(FunctionProperties functionProperties, - List arguments) { + public FunctionImplementation apply( + FunctionProperties functionProperties, List arguments) { return new SampleFunctionImplementation(arguments); } } @RequiredArgsConstructor static class SampleFunctionImplementation implements FunctionImplementation { - @Getter - private final List arguments; + @Getter private final List arguments; @Override public FunctionName getFunctionName() { diff --git a/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLTestBase.java b/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLTestBase.java index 93d0c32f57..a8b9e8da96 100644 --- a/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLTestBase.java +++ b/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLTestBase.java @@ -17,33 +17,33 @@ @ExtendWith(MockitoExtension.class) public class FunctionDSLTestBase { - @Mock - FunctionProperties functionProperties; + @Mock FunctionProperties functionProperties; public static final ExprNullValue NULL = ExprNullValue.of(); public static final ExprMissingValue MISSING = ExprMissingValue.of(); protected static final ExprType ANY_TYPE = () -> "ANY"; - protected static final ExprValue ANY = new ExprValue() { - @Override - public Object value() { - throw new RuntimeException(); - } + protected static final ExprValue ANY = + new ExprValue() { + @Override + public Object value() { + throw new RuntimeException(); + } - @Override - public ExprType type() { - return ANY_TYPE; - } + @Override + public ExprType type() { + return ANY_TYPE; + } - @Override - public String toString() { - return "ANY"; - } + @Override + public String toString() { + return "ANY"; + } - @Override - public int compareTo(ExprValue o) { - throw new RuntimeException(); - } - }; + @Override + public int compareTo(ExprValue o) { + throw new RuntimeException(); + } + }; static final FunctionName SAMPLE_NAME = FunctionName.of("sample"); static final FunctionSignature SAMPLE_SIGNATURE_A = new FunctionSignature(SAMPLE_NAME, List.of(ExprCoreType.UNDEFINED)); @@ -54,18 +54,16 @@ public int compareTo(ExprValue o) { static final SerializableTriFunction twoArgWithProperties = (functionProperties, v1, v2) -> ANY; - static final SerializableQuadFunction - + static final SerializableQuadFunction< + FunctionProperties, ExprValue, ExprValue, ExprValue, ExprValue> threeArgsWithProperties = (functionProperties, v1, v2, v3) -> ANY; - static final SerializableBiFunction - twoArgs = (v1, v2) -> ANY; - static final SerializableTriFunction - threeArgs = (v1, v2, v3) -> ANY; + static final SerializableBiFunction twoArgs = (v1, v2) -> ANY; + static final SerializableTriFunction threeArgs = + (v1, v2, v3) -> ANY; static final SerializableQuadFunction fourArgs = (v1, v2, v3, v4) -> ANY; - @Mock - FunctionProperties mockProperties; + @Mock FunctionProperties mockProperties; } diff --git a/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLimplTestBase.java b/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLimplTestBase.java index 8f494c01c3..a76e738e2d 100644 --- a/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLimplTestBase.java +++ b/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLimplTestBase.java @@ -42,16 +42,16 @@ void implementation_valid_functionBuilder() { @Test void implementation_functionBuilder_return_functionExpression() { - FunctionImplementation executable = getImplementation().getValue() - .apply(functionProperties, getSampleArguments()); + FunctionImplementation executable = + getImplementation().getValue().apply(functionProperties, getSampleArguments()); assertTrue(executable instanceof FunctionExpression); } @Test void implementation_functionExpression_valueOf() { FunctionExpression executable = - (FunctionExpression) getImplementation().getValue() - .apply(functionProperties, getSampleArguments()); + (FunctionExpression) + getImplementation().getValue().apply(functionProperties, getSampleArguments()); assertEquals(ANY, executable.valueOf(null)); } @@ -59,23 +59,20 @@ void implementation_functionExpression_valueOf() { @Test void implementation_functionExpression_type() { FunctionExpression executable = - (FunctionExpression) getImplementation().getValue() - .apply(functionProperties, getSampleArguments()); + (FunctionExpression) + getImplementation().getValue().apply(functionProperties, getSampleArguments()); assertEquals(ANY_TYPE, executable.type()); } @Test void implementation_functionExpression_toString() { FunctionExpression executable = - (FunctionExpression) getImplementation().getValue() - .apply(functionProperties, getSampleArguments()); + (FunctionExpression) + getImplementation().getValue().apply(functionProperties, getSampleArguments()); assertEquals(getExpected_toString(), executable.toString()); } - /** - * A lambda that takes a function name and returns an implementation - * of the function. - */ + /** A lambda that takes a function name and returns an implementation of the function. */ abstract SerializableFunction> getImplementationGenerator(); diff --git a/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLimplTwoArgTest.java b/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLimplTwoArgTest.java index 87d097c9eb..4e2626b9c3 100644 --- a/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLimplTwoArgTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLimplTwoArgTest.java @@ -19,7 +19,6 @@ class FunctionDSLimplTwoArgTest extends FunctionDSLimplTestBase { return impl(twoArgs, ANY_TYPE, ANY_TYPE, ANY_TYPE); } - @Override List getSampleArguments() { return List.of(DSL.literal(ANY), DSL.literal(ANY)); diff --git a/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLimplWithPropertiesNoArgsTest.java b/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLimplWithPropertiesNoArgsTest.java index c3c41b6c0c..f4b8d0090e 100644 --- a/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLimplWithPropertiesNoArgsTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLimplWithPropertiesNoArgsTest.java @@ -9,7 +9,7 @@ import org.apache.commons.lang3.tuple.Pair; import org.opensearch.sql.expression.Expression; -class FunctionDSLimplWithPropertiesNoArgsTest extends FunctionDSLimplTestBase { +class FunctionDSLimplWithPropertiesNoArgsTest extends FunctionDSLimplTestBase { @Override SerializableFunction> diff --git a/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLimplWithPropertiesOneArgTest.java b/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLimplWithPropertiesOneArgTest.java index 4a05326c0a..57960b5c1c 100644 --- a/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLimplWithPropertiesOneArgTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLimplWithPropertiesOneArgTest.java @@ -5,7 +5,6 @@ package org.opensearch.sql.expression.function; - import java.util.List; import org.apache.commons.lang3.tuple.Pair; import org.opensearch.sql.data.model.ExprValue; @@ -17,8 +16,8 @@ class FunctionDSLimplWithPropertiesOneArgTest extends FunctionDSLimplTestBase { @Override SerializableFunction> getImplementationGenerator() { - SerializableBiFunction functionBody - = (fp, arg) -> ANY; + SerializableBiFunction functionBody = + (fp, arg) -> ANY; return FunctionDSL.implWithProperties(functionBody, ANY_TYPE, ANY_TYPE); } diff --git a/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLimplWithPropertiesTwoArgTest.java b/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLimplWithPropertiesTwoArgTest.java index 18444a476e..3c42b412c8 100644 --- a/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLimplWithPropertiesTwoArgTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLimplWithPropertiesTwoArgTest.java @@ -16,8 +16,8 @@ class FunctionDSLimplWithPropertiesTwoArgTest extends FunctionDSLimplTestBase { @Override SerializableFunction> getImplementationGenerator() { - SerializableTriFunction functionBody - = (fp, arg1, arg2) -> ANY; + SerializableTriFunction functionBody = + (fp, arg1, arg2) -> ANY; return FunctionDSL.implWithProperties(functionBody, ANY_TYPE, ANY_TYPE, ANY_TYPE); } diff --git a/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLimplWithPropertiesTwoArgsTest.java b/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLimplWithPropertiesTwoArgsTest.java index f690485801..748d734373 100644 --- a/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLimplWithPropertiesTwoArgsTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLimplWithPropertiesTwoArgsTest.java @@ -5,7 +5,6 @@ package org.opensearch.sql.expression.function; - import java.util.List; import org.apache.commons.lang3.tuple.Pair; import org.opensearch.sql.data.model.ExprValue; @@ -17,8 +16,8 @@ class FunctionDSLimplWithPropertiesTwoArgsTest extends FunctionDSLimplTestBase { @Override SerializableFunction> getImplementationGenerator() { - SerializableTriFunction functionBody - = (fp, arg1, arg2) -> ANY; + SerializableTriFunction functionBody = + (fp, arg1, arg2) -> ANY; return FunctionDSL.implWithProperties(functionBody, ANY_TYPE, ANY_TYPE, ANY_TYPE); } diff --git a/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLnullMissingHandlingTest.java b/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLnullMissingHandlingTest.java index 0cea222843..a1cc305003 100644 --- a/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLnullMissingHandlingTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/function/FunctionDSLnullMissingHandlingTest.java @@ -28,106 +28,119 @@ void nullMissingHandling_oneArg_apply() { assertEquals(ANY, nullMissingHandling(oneArg).apply(ANY)); } - @Test void nullMissingHandling_oneArg_FunctionProperties_nullValue() { - assertEquals(NULL, + assertEquals( + NULL, nullMissingHandlingWithProperties(oneArgWithProperties).apply(functionProperties, NULL)); } @Test void nullMissingHandling_oneArg_FunctionProperties_missingValue() { - assertEquals(MISSING, + assertEquals( + MISSING, nullMissingHandlingWithProperties(oneArgWithProperties).apply(functionProperties, MISSING)); } @Test void nullMissingHandling_oneArg_FunctionProperties_apply() { - assertEquals(ANY, + assertEquals( + ANY, nullMissingHandlingWithProperties(oneArgWithProperties).apply(functionProperties, ANY)); } @Test void nullMissingHandling_twoArgs_FunctionProperties_nullValue_firstArg() { - assertEquals(NULL, + assertEquals( + NULL, nullMissingHandlingWithProperties(twoArgWithProperties) .apply(functionProperties, NULL, ANY)); } @Test void nullMissingHandling_twoArgs_FunctionProperties_nullValue_secondArg() { - assertEquals(NULL, + assertEquals( + NULL, nullMissingHandlingWithProperties(twoArgWithProperties) .apply(functionProperties, ANY, NULL)); } @Test void nullMissingHandling_twoArgs_FunctionProperties_missingValue_firstArg() { - assertEquals(MISSING, + assertEquals( + MISSING, nullMissingHandlingWithProperties(twoArgWithProperties) .apply(functionProperties, MISSING, ANY)); } @Test void nullMissingHandling_twoArgs_FunctionProperties_missingValue_secondArg() { - assertEquals(MISSING, + assertEquals( + MISSING, nullMissingHandlingWithProperties(twoArgWithProperties) .apply(functionProperties, ANY, MISSING)); } @Test void nullMissingHandling_twoArgs_FunctionProperties_apply() { - assertEquals(ANY, + assertEquals( + ANY, nullMissingHandlingWithProperties(twoArgWithProperties) .apply(functionProperties, ANY, ANY)); } @Test void nullMissingHandling_threeArgs_FunctionProperties_nullValue_firstArg() { - assertEquals(NULL, + assertEquals( + NULL, nullMissingHandlingWithProperties(threeArgsWithProperties) .apply(functionProperties, NULL, ANY, ANY)); } @Test void nullMissingHandling_threeArgs_FunctionProperties_nullValue_secondArg() { - assertEquals(NULL, + assertEquals( + NULL, nullMissingHandlingWithProperties(threeArgsWithProperties) .apply(functionProperties, ANY, NULL, ANY)); } @Test void nullMissingHandling_threeArgs_FunctionProperties_nullValue_thirdArg() { - assertEquals(NULL, + assertEquals( + NULL, nullMissingHandlingWithProperties(threeArgsWithProperties) .apply(functionProperties, ANY, ANY, NULL)); } - @Test void nullMissingHandling_threeArgs_FunctionProperties_missingValue_firstArg() { - assertEquals(MISSING, + assertEquals( + MISSING, nullMissingHandlingWithProperties(threeArgsWithProperties) .apply(functionProperties, MISSING, ANY, ANY)); } @Test void nullMissingHandling_threeArgs_FunctionProperties_missingValue_secondArg() { - assertEquals(MISSING, + assertEquals( + MISSING, nullMissingHandlingWithProperties(threeArgsWithProperties) .apply(functionProperties, ANY, MISSING, ANY)); } @Test void nullMissingHandling_threeArgs_FunctionProperties_missingValue_thirdArg() { - assertEquals(MISSING, + assertEquals( + MISSING, nullMissingHandlingWithProperties(threeArgsWithProperties) .apply(functionProperties, ANY, ANY, MISSING)); } @Test void nullMissingHandling_threeArgs_FunctionProperties_apply() { - assertEquals(ANY, + assertEquals( + ANY, nullMissingHandlingWithProperties(threeArgsWithProperties) .apply(functionProperties, ANY, ANY, ANY)); } @@ -142,7 +155,6 @@ void nullMissingHandling_twoArgs_secondArg_nullValue() { assertEquals(NULL, nullMissingHandling(twoArgs).apply(ANY, NULL)); } - @Test void nullMissingHandling_twoArgs_firstArg_missingValue() { assertEquals(MISSING, nullMissingHandling(twoArgs).apply(MISSING, ANY)); @@ -158,7 +170,6 @@ void nullMissingHandling_twoArgs_apply() { assertEquals(ANY, nullMissingHandling(twoArgs).apply(ANY, ANY)); } - @Test void nullMissingHandling_threeArgs_firstArg_nullValue() { assertEquals(NULL, nullMissingHandling(threeArgs).apply(NULL, ANY, ANY)); @@ -174,7 +185,6 @@ void nullMissingHandling_threeArgs_thirdArg_nullValue() { assertEquals(NULL, nullMissingHandling(threeArgs).apply(ANY, ANY, NULL)); } - @Test void nullMissingHandling_threeArgs_firstArg_missingValue() { assertEquals(MISSING, nullMissingHandling(threeArgs).apply(MISSING, ANY, ANY)); diff --git a/core/src/test/java/org/opensearch/sql/expression/function/FunctionPropertiesTest.java b/core/src/test/java/org/opensearch/sql/expression/function/FunctionPropertiesTest.java index ed4a8a514d..b531d049fd 100644 --- a/core/src/test/java/org/opensearch/sql/expression/function/FunctionPropertiesTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/function/FunctionPropertiesTest.java @@ -75,16 +75,17 @@ void functionProperties_can_be_deserialized() throws IOException, ClassNotFoundE @TestFactory Stream functionProperties_none_throws_on_access() { - Consumer tb = tc -> { - RuntimeException e = assertThrows(FunctionProperties.UnexpectedCallException.class, tc); - assertEquals("FunctionProperties.None is a null object and not meant to be accessed.", - e.getMessage()); - }; + Consumer tb = + tc -> { + RuntimeException e = assertThrows(FunctionProperties.UnexpectedCallException.class, tc); + assertEquals( + "FunctionProperties.None is a null object and not meant to be accessed.", + e.getMessage()); + }; return Stream.of( - DynamicTest.dynamicTest("getQueryStartClock", - () -> tb.accept(FunctionProperties.None::getQueryStartClock)), - DynamicTest.dynamicTest("getSystemClock", - () -> tb.accept(FunctionProperties.None::getSystemClock)) - ); + DynamicTest.dynamicTest( + "getQueryStartClock", () -> tb.accept(FunctionProperties.None::getQueryStartClock)), + DynamicTest.dynamicTest( + "getSystemClock", () -> tb.accept(FunctionProperties.None::getSystemClock))); } } diff --git a/core/src/test/java/org/opensearch/sql/expression/function/FunctionSignatureTest.java b/core/src/test/java/org/opensearch/sql/expression/function/FunctionSignatureTest.java index cc658bff98..2fb5dc468e 100644 --- a/core/src/test/java/org/opensearch/sql/expression/function/FunctionSignatureTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/function/FunctionSignatureTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.function; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -25,10 +24,8 @@ @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) @ExtendWith(MockitoExtension.class) class FunctionSignatureTest { - @Mock - private FunctionSignature funcSignature; - @Mock - private List funcParamTypeList; + @Mock private FunctionSignature funcSignature; + @Mock private List funcParamTypeList; private FunctionName unresolvedFuncName = FunctionName.of("add"); private List unresolvedParamTypeList = diff --git a/core/src/test/java/org/opensearch/sql/expression/function/OpenSearchFunctionsTest.java b/core/src/test/java/org/opensearch/sql/expression/function/OpenSearchFunctionsTest.java index d90d8295c4..168b73acc4 100644 --- a/core/src/test/java/org/opensearch/sql/expression/function/OpenSearchFunctionsTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/function/OpenSearchFunctionsTest.java @@ -24,44 +24,48 @@ import org.opensearch.sql.expression.NamedArgumentExpression; import org.opensearch.sql.expression.env.Environment; - public class OpenSearchFunctionsTest extends ExpressionTestBase { - private final NamedArgumentExpression field = new NamedArgumentExpression( - "field", DSL.literal("message")); - private final NamedArgumentExpression fields = new NamedArgumentExpression( - "fields", DSL.literal(new ExprTupleValue(new LinkedHashMap<>(Map.of( - "title", ExprValueUtils.floatValue(1.F), - "body", ExprValueUtils.floatValue(.3F)))))); - private final NamedArgumentExpression query = new NamedArgumentExpression( - "query", DSL.literal("search query")); - private final NamedArgumentExpression analyzer = new NamedArgumentExpression( - "analyzer", DSL.literal("keyword")); - private final NamedArgumentExpression autoGenerateSynonymsPhrase = new NamedArgumentExpression( - "auto_generate_synonyms_phrase", DSL.literal("true")); - private final NamedArgumentExpression fuzziness = new NamedArgumentExpression( - "fuzziness", DSL.literal("AUTO")); - private final NamedArgumentExpression maxExpansions = new NamedArgumentExpression( - "max_expansions", DSL.literal("10")); - private final NamedArgumentExpression prefixLength = new NamedArgumentExpression( - "prefix_length", DSL.literal("1")); - private final NamedArgumentExpression fuzzyTranspositions = new NamedArgumentExpression( - "fuzzy_transpositions", DSL.literal("false")); - private final NamedArgumentExpression fuzzyRewrite = new NamedArgumentExpression( - "fuzzy_rewrite", DSL.literal("rewrite method")); - private final NamedArgumentExpression lenient = new NamedArgumentExpression( - "lenient", DSL.literal("true")); - private final NamedArgumentExpression operator = new NamedArgumentExpression( - "operator", DSL.literal("OR")); - private final NamedArgumentExpression minimumShouldMatch = new NamedArgumentExpression( - "minimum_should_match", DSL.literal("1")); - private final NamedArgumentExpression zeroTermsQueryAll = new NamedArgumentExpression( - "zero_terms_query", DSL.literal("ALL")); - private final NamedArgumentExpression zeroTermsQueryNone = new NamedArgumentExpression( - "zero_terms_query", DSL.literal("None")); - private final NamedArgumentExpression boost = new NamedArgumentExpression( - "boost", DSL.literal("2.0")); - private final NamedArgumentExpression slop = new NamedArgumentExpression( - "slop", DSL.literal("3")); + private final NamedArgumentExpression field = + new NamedArgumentExpression("field", DSL.literal("message")); + private final NamedArgumentExpression fields = + new NamedArgumentExpression( + "fields", + DSL.literal( + new ExprTupleValue( + new LinkedHashMap<>( + Map.of( + "title", ExprValueUtils.floatValue(1.F), + "body", ExprValueUtils.floatValue(.3F)))))); + private final NamedArgumentExpression query = + new NamedArgumentExpression("query", DSL.literal("search query")); + private final NamedArgumentExpression analyzer = + new NamedArgumentExpression("analyzer", DSL.literal("keyword")); + private final NamedArgumentExpression autoGenerateSynonymsPhrase = + new NamedArgumentExpression("auto_generate_synonyms_phrase", DSL.literal("true")); + private final NamedArgumentExpression fuzziness = + new NamedArgumentExpression("fuzziness", DSL.literal("AUTO")); + private final NamedArgumentExpression maxExpansions = + new NamedArgumentExpression("max_expansions", DSL.literal("10")); + private final NamedArgumentExpression prefixLength = + new NamedArgumentExpression("prefix_length", DSL.literal("1")); + private final NamedArgumentExpression fuzzyTranspositions = + new NamedArgumentExpression("fuzzy_transpositions", DSL.literal("false")); + private final NamedArgumentExpression fuzzyRewrite = + new NamedArgumentExpression("fuzzy_rewrite", DSL.literal("rewrite method")); + private final NamedArgumentExpression lenient = + new NamedArgumentExpression("lenient", DSL.literal("true")); + private final NamedArgumentExpression operator = + new NamedArgumentExpression("operator", DSL.literal("OR")); + private final NamedArgumentExpression minimumShouldMatch = + new NamedArgumentExpression("minimum_should_match", DSL.literal("1")); + private final NamedArgumentExpression zeroTermsQueryAll = + new NamedArgumentExpression("zero_terms_query", DSL.literal("ALL")); + private final NamedArgumentExpression zeroTermsQueryNone = + new NamedArgumentExpression("zero_terms_query", DSL.literal("None")); + private final NamedArgumentExpression boost = + new NamedArgumentExpression("boost", DSL.literal("2.0")); + private final NamedArgumentExpression slop = + new NamedArgumentExpression("slop", DSL.literal("3")); @Test void match() { @@ -80,50 +84,135 @@ void match() { expr = DSL.match(field, query, analyzer, autoGenerateSynonymsPhrase, fuzziness, maxExpansions); assertEquals(BOOLEAN, expr.type()); - expr = DSL.match( - field, query, analyzer, autoGenerateSynonymsPhrase, fuzziness, maxExpansions, prefixLength); + expr = + DSL.match( + field, + query, + analyzer, + autoGenerateSynonymsPhrase, + fuzziness, + maxExpansions, + prefixLength); assertEquals(BOOLEAN, expr.type()); - expr = DSL.match( - field, query, analyzer, autoGenerateSynonymsPhrase, fuzziness, maxExpansions, prefixLength, - fuzzyTranspositions); + expr = + DSL.match( + field, + query, + analyzer, + autoGenerateSynonymsPhrase, + fuzziness, + maxExpansions, + prefixLength, + fuzzyTranspositions); assertEquals(BOOLEAN, expr.type()); - expr = DSL.match( - field, query, analyzer, autoGenerateSynonymsPhrase, fuzziness, maxExpansions, prefixLength, - fuzzyTranspositions, fuzzyRewrite); + expr = + DSL.match( + field, + query, + analyzer, + autoGenerateSynonymsPhrase, + fuzziness, + maxExpansions, + prefixLength, + fuzzyTranspositions, + fuzzyRewrite); assertEquals(BOOLEAN, expr.type()); - expr = DSL.match( - field, query, analyzer, autoGenerateSynonymsPhrase, fuzziness, maxExpansions, prefixLength, - fuzzyTranspositions, fuzzyRewrite, lenient); + expr = + DSL.match( + field, + query, + analyzer, + autoGenerateSynonymsPhrase, + fuzziness, + maxExpansions, + prefixLength, + fuzzyTranspositions, + fuzzyRewrite, + lenient); assertEquals(BOOLEAN, expr.type()); - expr = DSL.match( - field, query, analyzer, autoGenerateSynonymsPhrase, fuzziness, maxExpansions, prefixLength, - fuzzyTranspositions, fuzzyRewrite, lenient, operator); + expr = + DSL.match( + field, + query, + analyzer, + autoGenerateSynonymsPhrase, + fuzziness, + maxExpansions, + prefixLength, + fuzzyTranspositions, + fuzzyRewrite, + lenient, + operator); assertEquals(BOOLEAN, expr.type()); - expr = DSL.match( - field, query, analyzer, autoGenerateSynonymsPhrase, fuzziness, maxExpansions, prefixLength, - fuzzyTranspositions, fuzzyRewrite, lenient, operator); + expr = + DSL.match( + field, + query, + analyzer, + autoGenerateSynonymsPhrase, + fuzziness, + maxExpansions, + prefixLength, + fuzzyTranspositions, + fuzzyRewrite, + lenient, + operator); assertEquals(BOOLEAN, expr.type()); - expr = DSL.match( - field, query, analyzer, autoGenerateSynonymsPhrase, fuzziness, maxExpansions, prefixLength, - fuzzyTranspositions, fuzzyRewrite, lenient, operator, minimumShouldMatch); + expr = + DSL.match( + field, + query, + analyzer, + autoGenerateSynonymsPhrase, + fuzziness, + maxExpansions, + prefixLength, + fuzzyTranspositions, + fuzzyRewrite, + lenient, + operator, + minimumShouldMatch); assertEquals(BOOLEAN, expr.type()); - expr = DSL.match( - field, query, analyzer, autoGenerateSynonymsPhrase, fuzziness, maxExpansions, prefixLength, - fuzzyTranspositions, fuzzyRewrite, lenient, operator, minimumShouldMatch, - zeroTermsQueryAll); + expr = + DSL.match( + field, + query, + analyzer, + autoGenerateSynonymsPhrase, + fuzziness, + maxExpansions, + prefixLength, + fuzzyTranspositions, + fuzzyRewrite, + lenient, + operator, + minimumShouldMatch, + zeroTermsQueryAll); assertEquals(BOOLEAN, expr.type()); - expr = DSL.match( - field, query, analyzer, autoGenerateSynonymsPhrase, fuzziness, maxExpansions, prefixLength, - fuzzyTranspositions, fuzzyRewrite, lenient, operator, minimumShouldMatch, - zeroTermsQueryNone, boost); + expr = + DSL.match( + field, + query, + analyzer, + autoGenerateSynonymsPhrase, + fuzziness, + maxExpansions, + prefixLength, + fuzzyTranspositions, + fuzzyRewrite, + lenient, + operator, + minimumShouldMatch, + zeroTermsQueryNone, + boost); assertEquals(BOOLEAN, expr.type()); } @@ -134,20 +223,16 @@ void match_phrase() { } } - List match_phrase_dsl_expressions() { return List.of( - DSL.match_phrase(field, query), - DSL.match_phrase(field, query, analyzer), - DSL.match_phrase(field, query, analyzer, zeroTermsQueryAll), - DSL.match_phrase(field, query, analyzer, zeroTermsQueryNone, slop) - ); + DSL.match_phrase(field, query), + DSL.match_phrase(field, query, analyzer), + DSL.match_phrase(field, query, analyzer, zeroTermsQueryAll), + DSL.match_phrase(field, query, analyzer, zeroTermsQueryNone, slop)); } List match_phrase_prefix_dsl_expressions() { - return List.of( - DSL.match_phrase_prefix(field, query) - ); + return List.of(DSL.match_phrase_prefix(field, query)); } @Test @@ -160,7 +245,8 @@ public void match_phrase_prefix() { @Test void match_in_memory() { FunctionExpression expr = DSL.match(field, query); - assertThrows(UnsupportedOperationException.class, + assertThrows( + UnsupportedOperationException.class, () -> expr.valueOf(valueEnv()), "OpenSearch defined function [match] is only supported in WHERE and HAVING clause."); } @@ -174,50 +260,52 @@ void match_to_string() { @Test void multi_match() { FunctionExpression expr = DSL.multi_match(fields, query); - assertEquals(String.format("multi_match(fields=%s, query=%s)", - fields.getValue(), query.getValue()), + assertEquals( + String.format("multi_match(fields=%s, query=%s)", fields.getValue(), query.getValue()), expr.toString()); } @Test void simple_query_string() { FunctionExpression expr = DSL.simple_query_string(fields, query); - assertEquals(String.format("simple_query_string(fields=%s, query=%s)", - fields.getValue(), query.getValue()), + assertEquals( + String.format( + "simple_query_string(fields=%s, query=%s)", fields.getValue(), query.getValue()), expr.toString()); } @Test void query() { FunctionExpression expr = DSL.query(query); - assertEquals(String.format("query(query=%s)", query.getValue()), - expr.toString()); + assertEquals(String.format("query(query=%s)", query.getValue()), expr.toString()); } @Test void query_string() { FunctionExpression expr = DSL.query_string(fields, query); - assertEquals(String.format("query_string(fields=%s, query=%s)", - fields.getValue(), query.getValue()), + assertEquals( + String.format("query_string(fields=%s, query=%s)", fields.getValue(), query.getValue()), expr.toString()); } @Test void wildcard_query() { FunctionExpression expr = DSL.wildcard_query(field, query); - assertEquals(String.format("wildcard_query(field=%s, query=%s)", - field.getValue(), query.getValue()), + assertEquals( + String.format("wildcard_query(field=%s, query=%s)", field.getValue(), query.getValue()), expr.toString()); } @Test void nested_query() { FunctionExpression expr = DSL.nested(DSL.ref("message.info", STRING)); - assertEquals(String.format("FunctionExpression(functionName=%s, arguments=[message.info])", - BuiltinFunctionName.NESTED.getName()), + assertEquals( + String.format( + "FunctionExpression(functionName=%s, arguments=[message.info])", + BuiltinFunctionName.NESTED.getName()), expr.toString()); - Environment nestedTuple = ExprValueUtils.tupleValue( - Map.of("message", Map.of("info", "result"))).bindingTuples(); + Environment nestedTuple = + ExprValueUtils.tupleValue(Map.of("message", Map.of("info", "result"))).bindingTuples(); assertEquals(expr.valueOf(nestedTuple), ExprValueUtils.stringValue("result")); assertEquals(expr.type(), STRING); } diff --git a/core/src/test/java/org/opensearch/sql/expression/function/RelevanceFunctionResolverTest.java b/core/src/test/java/org/opensearch/sql/expression/function/RelevanceFunctionResolverTest.java index 85fc3a0276..c678ac6eb4 100644 --- a/core/src/test/java/org/opensearch/sql/expression/function/RelevanceFunctionResolverTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/function/RelevanceFunctionResolverTest.java @@ -36,18 +36,15 @@ void resolve_correct_name_test() { void resolve_invalid_name_test() { var wrongFuncName = FunctionName.of("wrong_func"); var sig = new FunctionSignature(wrongFuncName, List.of(STRING)); - Exception exception = assertThrows(SemanticCheckException.class, - () -> resolver.resolve(sig)); - assertEquals("Expected 'sample_function' but got 'wrong_func'", - exception.getMessage()); + Exception exception = assertThrows(SemanticCheckException.class, () -> resolver.resolve(sig)); + assertEquals("Expected 'sample_function' but got 'wrong_func'", exception.getMessage()); } @Test void resolve_invalid_third_param_type_test() { var sig = new FunctionSignature(sampleFuncName, List.of(STRING, STRING, INTEGER, STRING)); - Exception exception = assertThrows(SemanticCheckException.class, - () -> resolver.resolve(sig)); - assertEquals("Expected type STRING instead of INTEGER for parameter #3", - exception.getMessage()); + Exception exception = assertThrows(SemanticCheckException.class, () -> resolver.resolve(sig)); + assertEquals( + "Expected type STRING instead of INTEGER for parameter #3", exception.getMessage()); } } diff --git a/core/src/test/java/org/opensearch/sql/expression/function/WideningTypeRuleTest.java b/core/src/test/java/org/opensearch/sql/expression/function/WideningTypeRuleTest.java index 27b36a0fec..3b6e5f7586 100644 --- a/core/src/test/java/org/opensearch/sql/expression/function/WideningTypeRuleTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/function/WideningTypeRuleTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.function; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -39,8 +38,7 @@ class WideningTypeRuleTest { private static Table numberWidenRule = - new ImmutableTable.Builder() + new ImmutableTable.Builder() .put(BYTE, SHORT, 1) .put(BYTE, INTEGER, 2) .put(BYTE, LONG, 3) @@ -77,35 +75,37 @@ class WideningTypeRuleTest { private static Stream distanceArguments() { List exprTypes = ExprCoreType.coreTypes(); return Lists.cartesianProduct(exprTypes, exprTypes).stream() - .map(list -> { - ExprCoreType type1 = list.get(0); - ExprCoreType type2 = list.get(1); - if (type1 == type2) { - return Arguments.of(type1, type2, TYPE_EQUAL); - } else if (numberWidenRule.contains(type1, type2)) { - return Arguments.of(type1, type2, numberWidenRule.get(type1, type2)); - } else { - return Arguments.of(type1, type2, IMPOSSIBLE_WIDENING); - } - }); + .map( + list -> { + ExprCoreType type1 = list.get(0); + ExprCoreType type2 = list.get(1); + if (type1 == type2) { + return Arguments.of(type1, type2, TYPE_EQUAL); + } else if (numberWidenRule.contains(type1, type2)) { + return Arguments.of(type1, type2, numberWidenRule.get(type1, type2)); + } else { + return Arguments.of(type1, type2, IMPOSSIBLE_WIDENING); + } + }); } private static Stream validMaxTypes() { List exprTypes = ExprCoreType.coreTypes(); return Lists.cartesianProduct(exprTypes, exprTypes).stream() - .map(list -> { - ExprCoreType type1 = list.get(0); - ExprCoreType type2 = list.get(1); - if (type1 == type2) { - return Arguments.of(type1, type2, type1); - } else if (numberWidenRule.contains(type1, type2)) { - return Arguments.of(type1, type2, type2); - } else if (numberWidenRule.contains(type2, type1)) { - return Arguments.of(type1, type2, type1); - } else { - return Arguments.of(type1, type2, null); - } - }); + .map( + list -> { + ExprCoreType type1 = list.get(0); + ExprCoreType type2 = list.get(1); + if (type1 == type2) { + return Arguments.of(type1, type2, type1); + } else if (numberWidenRule.contains(type1, type2)) { + return Arguments.of(type1, type2, type2); + } else if (numberWidenRule.contains(type2, type1)) { + return Arguments.of(type1, type2, type1); + } else { + return Arguments.of(type1, type2, null); + } + }); } @ParameterizedTest @@ -118,8 +118,8 @@ public void distance(ExprCoreType v1, ExprCoreType v2, Integer expected) { @MethodSource("validMaxTypes") public void max(ExprCoreType v1, ExprCoreType v2, ExprCoreType expected) { if (null == expected) { - ExpressionEvaluationException exception = assertThrows( - ExpressionEvaluationException.class, () -> WideningTypeRule.max(v1, v2)); + ExpressionEvaluationException exception = + assertThrows(ExpressionEvaluationException.class, () -> WideningTypeRule.max(v1, v2)); assertEquals(String.format("no max type of %s and %s ", v1, v2), exception.getMessage()); } else { assertEquals(expected, WideningTypeRule.max(v1, v2)); @@ -128,10 +128,9 @@ public void max(ExprCoreType v1, ExprCoreType v2, ExprCoreType expected) { @Test public void maxOfUndefinedAndOthersShouldBeTheOtherType() { - ExprCoreType.coreTypes().forEach(type -> - assertEquals(type, WideningTypeRule.max(type, UNDEFINED))); - ExprCoreType.coreTypes().forEach(type -> - assertEquals(type, WideningTypeRule.max(UNDEFINED, type))); + ExprCoreType.coreTypes() + .forEach(type -> assertEquals(type, WideningTypeRule.max(type, UNDEFINED))); + ExprCoreType.coreTypes() + .forEach(type -> assertEquals(type, WideningTypeRule.max(UNDEFINED, type))); } - } diff --git a/core/src/test/java/org/opensearch/sql/expression/operator/arthmetic/ArithmeticFunctionTest.java b/core/src/test/java/org/opensearch/sql/expression/operator/arthmetic/ArithmeticFunctionTest.java index 028ace6231..24c0d0decf 100644 --- a/core/src/test/java/org/opensearch/sql/expression/operator/arthmetic/ArithmeticFunctionTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/operator/arthmetic/ArithmeticFunctionTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.operator.arthmetic; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -40,21 +39,34 @@ @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) class ArithmeticFunctionTest extends ExpressionTestBase { private static Stream arithmeticFunctionArguments() { - List numberOp1 = Arrays.asList(new ExprByteValue(3), new ExprShortValue(3), - new ExprIntegerValue(3), new ExprLongValue(3L), new ExprFloatValue(3f), - new ExprDoubleValue(3D)); + List numberOp1 = + Arrays.asList( + new ExprByteValue(3), + new ExprShortValue(3), + new ExprIntegerValue(3), + new ExprLongValue(3L), + new ExprFloatValue(3f), + new ExprDoubleValue(3D)); List numberOp2 = - Arrays.asList(new ExprByteValue(2), new ExprShortValue(2), new ExprIntegerValue(2), + Arrays.asList( + new ExprByteValue(2), + new ExprShortValue(2), + new ExprIntegerValue(2), new ExprLongValue(3L), - new ExprFloatValue(2f), new ExprDoubleValue(2D)); + new ExprFloatValue(2f), + new ExprDoubleValue(2D)); return Lists.cartesianProduct(numberOp1, numberOp2).stream() .map(list -> Arguments.of(list.get(0), list.get(1))); } private static Stream arithmeticOperatorArguments() { - return Stream - .of(BuiltinFunctionName.ADD, BuiltinFunctionName.SUBTRACT, BuiltinFunctionName.MULTIPLY, - BuiltinFunctionName.DIVIDE, BuiltinFunctionName.DIVIDE).map(Arguments::of); + return Stream.of( + BuiltinFunctionName.ADD, + BuiltinFunctionName.SUBTRACT, + BuiltinFunctionName.MULTIPLY, + BuiltinFunctionName.DIVIDE, + BuiltinFunctionName.DIVIDE) + .map(Arguments::of); } @ParameterizedTest(name = "add({1}, {2})") @@ -73,10 +85,9 @@ public void addFunction(ExprValue op1, ExprValue op2) { FunctionExpression expression = DSL.addFunction(literal(op1), literal(op2)); ExprType expectedType = WideningTypeRule.max(op1.type(), op2.type()); assertEquals(expectedType, expression.type()); - assertValueEqual(BuiltinFunctionName.ADDFUNCTION, - expectedType, op1, op2, expression.valueOf()); - assertEquals(String.format("add(%s, %s)", - op1.toString(), op2.toString()), expression.toString()); + assertValueEqual(BuiltinFunctionName.ADDFUNCTION, expectedType, op1, op2, expression.valueOf()); + assertEquals( + String.format("add(%s, %s)", op1.toString(), op2.toString()), expression.toString()); } @ParameterizedTest(name = "subtract({1}, {2})") @@ -85,10 +96,8 @@ public void subtract(ExprValue op1, ExprValue op2) { FunctionExpression expression = DSL.subtract(literal(op1), literal(op2)); ExprType expectedType = WideningTypeRule.max(op1.type(), op2.type()); assertEquals(expectedType, expression.type()); - assertValueEqual(BuiltinFunctionName.SUBTRACT, expectedType, op1, op2, - expression.valueOf()); - assertEquals(String.format("-(%s, %s)", op1.toString(), op2.toString()), - expression.toString()); + assertValueEqual(BuiltinFunctionName.SUBTRACT, expectedType, op1, op2, expression.valueOf()); + assertEquals(String.format("-(%s, %s)", op1.toString(), op2.toString()), expression.toString()); } @ParameterizedTest(name = "subtractFunction({1}, {2})") @@ -97,10 +106,10 @@ public void subtractFunction(ExprValue op1, ExprValue op2) { FunctionExpression expression = DSL.subtractFunction(literal(op1), literal(op2)); ExprType expectedType = WideningTypeRule.max(op1.type(), op2.type()); assertEquals(expectedType, expression.type()); - assertValueEqual(BuiltinFunctionName.SUBTRACTFUNCTION, expectedType, op1, op2, - expression.valueOf()); - assertEquals(String.format("subtract(%s, %s)", op1.toString(), op2.toString()), - expression.toString()); + assertValueEqual( + BuiltinFunctionName.SUBTRACTFUNCTION, expectedType, op1, op2, expression.valueOf()); + assertEquals( + String.format("subtract(%s, %s)", op1.toString(), op2.toString()), expression.toString()); } @ParameterizedTest(name = "mod({1}, {2})") @@ -110,8 +119,8 @@ public void mod(ExprValue op1, ExprValue op2) { ExprType expectedType = WideningTypeRule.max(op1.type(), op2.type()); assertEquals(expectedType, expression.type()); assertValueEqual(BuiltinFunctionName.MOD, expectedType, op1, op2, expression.valueOf()); - assertEquals(String.format("mod(%s, %s)", op1.toString(), op2.toString()), - expression.toString()); + assertEquals( + String.format("mod(%s, %s)", op1.toString(), op2.toString()), expression.toString()); expression = DSL.mod(literal(op1), literal(new ExprByteValue(0))); assertTrue(expression.valueOf(valueEnv()).isNull()); @@ -125,8 +134,8 @@ public void modulus(ExprValue op1, ExprValue op2) { ExprType expectedType = WideningTypeRule.max(op1.type(), op2.type()); assertEquals(expectedType, expression.type()); assertValueEqual(BuiltinFunctionName.MODULUS, expectedType, op1, op2, expression.valueOf()); - assertEquals(String.format("%%(%s, %s)", op1.toString(), op2.toString()), - expression.toString()); + assertEquals( + String.format("%%(%s, %s)", op1.toString(), op2.toString()), expression.toString()); expression = DSL.modulus(literal(op1), literal(new ExprByteValue(0))); assertTrue(expression.valueOf(valueEnv()).isNull()); @@ -139,10 +148,10 @@ public void modulusFunction(ExprValue op1, ExprValue op2) { FunctionExpression expression = DSL.modulusFunction(literal(op1), literal(op2)); ExprType expectedType = WideningTypeRule.max(op1.type(), op2.type()); assertEquals(expectedType, expression.type()); - assertValueEqual(BuiltinFunctionName.MODULUSFUNCTION, - expectedType, op1, op2, expression.valueOf()); - assertEquals(String.format("modulus(%s, %s)", op1.toString(), op2.toString()), - expression.toString()); + assertValueEqual( + BuiltinFunctionName.MODULUSFUNCTION, expectedType, op1, op2, expression.valueOf()); + assertEquals( + String.format("modulus(%s, %s)", op1.toString(), op2.toString()), expression.toString()); expression = DSL.modulusFunction(literal(op1), literal(new ExprByteValue(0))); assertTrue(expression.valueOf(valueEnv()).isNull()); @@ -155,10 +164,8 @@ public void multiply(ExprValue op1, ExprValue op2) { FunctionExpression expression = DSL.multiply(literal(op1), literal(op2)); ExprType expectedType = WideningTypeRule.max(op1.type(), op2.type()); assertEquals(expectedType, expression.type()); - assertValueEqual(BuiltinFunctionName.MULTIPLY, expectedType, op1, op2, - expression.valueOf()); - assertEquals(String.format("*(%s, %s)", op1.toString(), op2.toString()), - expression.toString()); + assertValueEqual(BuiltinFunctionName.MULTIPLY, expectedType, op1, op2, expression.valueOf()); + assertEquals(String.format("*(%s, %s)", op1.toString(), op2.toString()), expression.toString()); } @ParameterizedTest(name = "multiplyFunction({1}, {2})") @@ -167,10 +174,10 @@ public void multiplyFunction(ExprValue op1, ExprValue op2) { FunctionExpression expression = DSL.multiplyFunction(literal(op1), literal(op2)); ExprType expectedType = WideningTypeRule.max(op1.type(), op2.type()); assertEquals(expectedType, expression.type()); - assertValueEqual(BuiltinFunctionName.MULTIPLYFUNCTION, expectedType, op1, op2, - expression.valueOf()); - assertEquals(String.format("multiply(%s, %s)", op1.toString(), op2.toString()), - expression.toString()); + assertValueEqual( + BuiltinFunctionName.MULTIPLYFUNCTION, expectedType, op1, op2, expression.valueOf()); + assertEquals( + String.format("multiply(%s, %s)", op1.toString(), op2.toString()), expression.toString()); } @ParameterizedTest(name = "divide({1}, {2})") @@ -180,8 +187,7 @@ public void divide(ExprValue op1, ExprValue op2) { ExprType expectedType = WideningTypeRule.max(op1.type(), op2.type()); assertEquals(expectedType, expression.type()); assertValueEqual(BuiltinFunctionName.DIVIDE, expectedType, op1, op2, expression.valueOf()); - assertEquals(String.format("/(%s, %s)", op1.toString(), op2.toString()), - expression.toString()); + assertEquals(String.format("/(%s, %s)", op1.toString(), op2.toString()), expression.toString()); expression = DSL.divide(literal(op1), literal(new ExprByteValue(0))); assertTrue(expression.valueOf(valueEnv()).isNull()); @@ -194,10 +200,10 @@ public void divideFunction(ExprValue op1, ExprValue op2) { FunctionExpression expression = DSL.divideFunction(literal(op1), literal(op2)); ExprType expectedType = WideningTypeRule.max(op1.type(), op2.type()); assertEquals(expectedType, expression.type()); - assertValueEqual(BuiltinFunctionName.DIVIDEFUNCTION, - expectedType, op1, op2, expression.valueOf()); - assertEquals(String.format("divide(%s, %s)", op1.toString(), op2.toString()), - expression.toString()); + assertValueEqual( + BuiltinFunctionName.DIVIDEFUNCTION, expectedType, op1, op2, expression.valueOf()); + assertEquals( + String.format("divide(%s, %s)", op1.toString(), op2.toString()), expression.toString()); expression = DSL.divideFunction(literal(op1), literal(new ExprByteValue(0))); assertTrue(expression.valueOf(valueEnv()).isNull()); @@ -207,38 +213,51 @@ public void divideFunction(ExprValue op1, ExprValue op2) { @ParameterizedTest(name = "multipleParameters({1},{2})") @MethodSource("arithmeticFunctionArguments") public void multipleParameters(ExprValue op1) { - assertThrows(ExpressionEvaluationException.class, - () -> DSL.add(literal(op1), literal(op1), literal(op1))); - assertThrows(ExpressionEvaluationException.class, - () -> DSL.addFunction(literal(op1), literal(op1), literal(op1))); + assertThrows( + ExpressionEvaluationException.class, + () -> DSL.add(literal(op1), literal(op1), literal(op1))); + assertThrows( + ExpressionEvaluationException.class, + () -> DSL.addFunction(literal(op1), literal(op1), literal(op1))); - assertThrows(ExpressionEvaluationException.class, - () -> DSL.subtract(literal(op1), literal(op1), literal(op1))); - assertThrows(ExpressionEvaluationException.class, - () -> DSL.subtractFunction(literal(op1), literal(op1), literal(op1))); + assertThrows( + ExpressionEvaluationException.class, + () -> DSL.subtract(literal(op1), literal(op1), literal(op1))); + assertThrows( + ExpressionEvaluationException.class, + () -> DSL.subtractFunction(literal(op1), literal(op1), literal(op1))); - assertThrows(ExpressionEvaluationException.class, - () -> DSL.multiply(literal(op1), literal(op1), literal(op1))); - assertThrows(ExpressionEvaluationException.class, - () -> DSL.multiplyFunction(literal(op1), literal(op1), literal(op1))); + assertThrows( + ExpressionEvaluationException.class, + () -> DSL.multiply(literal(op1), literal(op1), literal(op1))); + assertThrows( + ExpressionEvaluationException.class, + () -> DSL.multiplyFunction(literal(op1), literal(op1), literal(op1))); - assertThrows(ExpressionEvaluationException.class, - () -> DSL.divide(literal(op1), literal(op1), literal(op1))); - assertThrows(ExpressionEvaluationException.class, - () -> DSL.divideFunction(literal(op1), literal(op1), literal(op1))); + assertThrows( + ExpressionEvaluationException.class, + () -> DSL.divide(literal(op1), literal(op1), literal(op1))); + assertThrows( + ExpressionEvaluationException.class, + () -> DSL.divideFunction(literal(op1), literal(op1), literal(op1))); - assertThrows(ExpressionEvaluationException.class, - () -> DSL.mod(literal(op1), literal(op1), literal(op1))); - assertThrows(ExpressionEvaluationException.class, - () -> DSL.modulus(literal(op1), literal(op1), literal(op1))); - assertThrows(ExpressionEvaluationException.class, - () -> DSL.modulusFunction(literal(op1), literal(op1), literal(op1))); + assertThrows( + ExpressionEvaluationException.class, + () -> DSL.mod(literal(op1), literal(op1), literal(op1))); + assertThrows( + ExpressionEvaluationException.class, + () -> DSL.modulus(literal(op1), literal(op1), literal(op1))); + assertThrows( + ExpressionEvaluationException.class, + () -> DSL.modulusFunction(literal(op1), literal(op1), literal(op1))); } - protected void assertValueEqual(BuiltinFunctionName builtinFunctionName, ExprType type, - ExprValue op1, - ExprValue op2, - ExprValue actual) { + protected void assertValueEqual( + BuiltinFunctionName builtinFunctionName, + ExprType type, + ExprValue op1, + ExprValue op2, + ExprValue actual) { switch ((ExprCoreType) type) { case BYTE: Byte vb1 = op1.byteValue(); diff --git a/core/src/test/java/org/opensearch/sql/expression/operator/arthmetic/MathematicalFunctionTest.java b/core/src/test/java/org/opensearch/sql/expression/operator/arthmetic/MathematicalFunctionTest.java index 4267805c74..e084bf1d53 100644 --- a/core/src/test/java/org/opensearch/sql/expression/operator/arthmetic/MathematicalFunctionTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/operator/arthmetic/MathematicalFunctionTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.operator.arthmetic; import static org.hamcrest.MatcherAssert.assertThat; @@ -76,28 +75,30 @@ private static Stream testLogDoubleArguments() { } private static Stream testLogInvalidDoubleArguments() { - return Stream.of(Arguments.of(0D, -2D), - Arguments.of(0D, 2D), - Arguments.of(2D, 0D)); + return Stream.of(Arguments.of(0D, -2D), Arguments.of(0D, 2D), Arguments.of(2D, 0D)); } private static Stream trigonometricArguments() { Stream.Builder builder = Stream.builder(); return builder - .add(Arguments.of(1)).add(Arguments.of(1L)).add(Arguments.of(1F)).add(Arguments.of(1D)) + .add(Arguments.of(1)) + .add(Arguments.of(1L)) + .add(Arguments.of(1F)) + .add(Arguments.of(1D)) .build(); } private static Stream trigonometricDoubleArguments() { Stream.Builder builder = Stream.builder(); return builder - .add(Arguments.of(1, 2)).add(Arguments.of(1L, 2L)).add(Arguments.of(1F, 2F)) - .add(Arguments.of(1D, 2D)).build(); + .add(Arguments.of(1, 2)) + .add(Arguments.of(1L, 2L)) + .add(Arguments.of(1F, 2F)) + .add(Arguments.of(1D, 2D)) + .build(); } - /** - * Test abs with byte value. - */ + /** Test abs with byte value. */ @ParameterizedTest(name = "abs({0})") @ValueSource(bytes = {-2, 2}) public void abs_byte_value(Byte value) { @@ -106,61 +107,43 @@ public void abs_byte_value(Byte value) { assertEquals(String.format("abs(%s)", value.toString()), abs.toString()); } - /** - * Test abs with integer value. - */ + /** Test abs with integer value. */ @ParameterizedTest(name = "abs({0})") @ValueSource(ints = {-2, 2}) public void abs_int_value(Integer value) { FunctionExpression abs = DSL.abs(DSL.literal(value)); - assertThat( - abs.valueOf(valueEnv()), - allOf(hasType(INTEGER), hasValue(Math.abs(value)))); + assertThat(abs.valueOf(valueEnv()), allOf(hasType(INTEGER), hasValue(Math.abs(value)))); assertEquals(String.format("abs(%s)", value.toString()), abs.toString()); } - /** - * Test abs with long value. - */ + /** Test abs with long value. */ @ParameterizedTest(name = "abs({0})") @ValueSource(longs = {-2L, 2L}) public void abs_long_value(Long value) { FunctionExpression abs = DSL.abs(DSL.literal(value)); - assertThat( - abs.valueOf(valueEnv()), - allOf(hasType(LONG), hasValue(Math.abs(value)))); + assertThat(abs.valueOf(valueEnv()), allOf(hasType(LONG), hasValue(Math.abs(value)))); assertEquals(String.format("abs(%s)", value.toString()), abs.toString()); } - /** - * Test abs with float value. - */ + /** Test abs with float value. */ @ParameterizedTest(name = "abs({0})") @ValueSource(floats = {-2f, 2f}) public void abs_float_value(Float value) { FunctionExpression abs = DSL.abs(DSL.literal(value)); - assertThat( - abs.valueOf(valueEnv()), - allOf(hasType(FLOAT), hasValue(Math.abs(value)))); + assertThat(abs.valueOf(valueEnv()), allOf(hasType(FLOAT), hasValue(Math.abs(value)))); assertEquals(String.format("abs(%s)", value.toString()), abs.toString()); } - /** - * Test abs with double value. - */ + /** Test abs with double value. */ @ParameterizedTest(name = "abs({0})") @ValueSource(doubles = {-2L, 2L}) public void abs_double_value(Double value) { FunctionExpression abs = DSL.abs(DSL.literal(value)); - assertThat( - abs.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.abs(value)))); + assertThat(abs.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.abs(value)))); assertEquals(String.format("abs(%s)", value.toString()), abs.toString()); } - /** - * Test abs with short value. - */ + /** Test abs with short value. */ @ParameterizedTest(name = "abs({0})") @ValueSource(shorts = {-2, 2}) public void abs_short_value(Short value) { @@ -171,16 +154,12 @@ public void abs_short_value(Short value) { assertEquals(String.format("abs(%s)", value.toString()), abs.toString()); } - /** - * Test ceil/ceiling with integer value. - */ + /** Test ceil/ceiling with integer value. */ @ParameterizedTest(name = "ceil({0})") @ValueSource(ints = {2, -2}) public void ceil_int_value(Integer value) { FunctionExpression ceil = DSL.ceil(DSL.literal(value)); - assertThat( - ceil.valueOf(valueEnv()), - allOf(hasType(LONG), hasValue((long) Math.ceil(value)))); + assertThat(ceil.valueOf(valueEnv()), allOf(hasType(LONG), hasValue((long) Math.ceil(value)))); assertEquals(String.format("ceil(%s)", value.toString()), ceil.toString()); FunctionExpression ceiling = DSL.ceiling(DSL.literal(value)); @@ -189,15 +168,12 @@ public void ceil_int_value(Integer value) { assertEquals(String.format("ceiling(%s)", value.toString()), ceiling.toString()); } - /** - * Test ceil/ceiling with long value. - */ + /** Test ceil/ceiling with long value. */ @ParameterizedTest(name = "ceil({0})") @ValueSource(longs = {2L, -2L}) public void ceil_long_value(Long value) { FunctionExpression ceil = DSL.ceil(DSL.literal(value)); - assertThat( - ceil.valueOf(valueEnv()), allOf(hasType(LONG), hasValue((long) Math.ceil(value)))); + assertThat(ceil.valueOf(valueEnv()), allOf(hasType(LONG), hasValue((long) Math.ceil(value)))); assertEquals(String.format("ceil(%s)", value.toString()), ceil.toString()); FunctionExpression ceiling = DSL.ceiling(DSL.literal(value)); @@ -206,15 +182,12 @@ public void ceil_long_value(Long value) { assertEquals(String.format("ceiling(%s)", value.toString()), ceiling.toString()); } - /** - * Test ceil/ceiling with long value. - */ + /** Test ceil/ceiling with long value. */ @ParameterizedTest(name = "ceil({0})") @ValueSource(longs = {9223372036854775805L, -9223372036854775805L}) public void ceil_long_value_long(Long value) { FunctionExpression ceil = DSL.ceil(DSL.literal(value)); - assertThat( - ceil.valueOf(valueEnv()), allOf(hasType(LONG), hasValue((long) Math.ceil(value)))); + assertThat(ceil.valueOf(valueEnv()), allOf(hasType(LONG), hasValue((long) Math.ceil(value)))); assertEquals(String.format("ceil(%s)", value.toString()), ceil.toString()); FunctionExpression ceiling = DSL.ceiling(DSL.literal(value)); @@ -223,15 +196,12 @@ public void ceil_long_value_long(Long value) { assertEquals(String.format("ceiling(%s)", value.toString()), ceiling.toString()); } - /** - * Test ceil/ceiling with float value. - */ + /** Test ceil/ceiling with float value. */ @ParameterizedTest(name = "ceil({0})") @ValueSource(floats = {2F, -2F}) public void ceil_float_value(Float value) { FunctionExpression ceil = DSL.ceil(DSL.literal(value)); - assertThat( - ceil.valueOf(valueEnv()), allOf(hasType(LONG), hasValue((long) Math.ceil(value)))); + assertThat(ceil.valueOf(valueEnv()), allOf(hasType(LONG), hasValue((long) Math.ceil(value)))); assertEquals(String.format("ceil(%s)", value.toString()), ceil.toString()); FunctionExpression ceiling = DSL.ceiling(DSL.literal(value)); @@ -240,15 +210,12 @@ public void ceil_float_value(Float value) { assertEquals(String.format("ceiling(%s)", value.toString()), ceiling.toString()); } - /** - * Test ceil/ceiling with double value. - */ + /** Test ceil/ceiling with double value. */ @ParameterizedTest(name = "ceil({0})") @ValueSource(doubles = {-2L, 2L}) public void ceil_double_value(Double value) { FunctionExpression ceil = DSL.ceil(DSL.literal(value)); - assertThat( - ceil.valueOf(valueEnv()), allOf(hasType(LONG), hasValue((long) Math.ceil(value)))); + assertThat(ceil.valueOf(valueEnv()), allOf(hasType(LONG), hasValue((long) Math.ceil(value)))); assertEquals(String.format("ceil(%s)", value.toString()), ceil.toString()); FunctionExpression ceiling = DSL.ceiling(DSL.literal(value)); @@ -257,9 +224,7 @@ public void ceil_double_value(Double value) { assertEquals(String.format("ceiling(%s)", value.toString()), ceiling.toString()); } - /** - * Test conv from decimal base with string as a number. - */ + /** Test conv from decimal base with string as a number. */ @ParameterizedTest(name = "conv({0})") @ValueSource(strings = {"1", "0", "-1"}) public void conv_from_decimal(String value) { @@ -282,34 +247,27 @@ public void conv_from_decimal(String value) { assertEquals(String.format("conv(\"%s\", 10, 16)", value), conv.toString()); } - /** - * Test conv from decimal base with integer as a number. - */ + /** Test conv from decimal base with integer as a number. */ @ParameterizedTest(name = "conv({0})") @ValueSource(ints = {1, 0, -1}) public void conv_from_decimal(Integer value) { FunctionExpression conv = DSL.conv(DSL.literal(value), DSL.literal(10), DSL.literal(2)); assertThat( - conv.valueOf(valueEnv()), - allOf(hasType(STRING), hasValue(Integer.toString(value, 2)))); + conv.valueOf(valueEnv()), allOf(hasType(STRING), hasValue(Integer.toString(value, 2)))); assertEquals(String.format("conv(%s, 10, 2)", value), conv.toString()); conv = DSL.conv(DSL.literal(value), DSL.literal(10), DSL.literal(8)); assertThat( - conv.valueOf(valueEnv()), - allOf(hasType(STRING), hasValue(Integer.toString(value, 8)))); + conv.valueOf(valueEnv()), allOf(hasType(STRING), hasValue(Integer.toString(value, 8)))); assertEquals(String.format("conv(%s, 10, 8)", value), conv.toString()); conv = DSL.conv(DSL.literal(value), DSL.literal(10), DSL.literal(16)); assertThat( - conv.valueOf(valueEnv()), - allOf(hasType(STRING), hasValue(Integer.toString(value, 16)))); + conv.valueOf(valueEnv()), allOf(hasType(STRING), hasValue(Integer.toString(value, 16)))); assertEquals(String.format("conv(%s, 10, 16)", value), conv.toString()); } - /** - * Test conv to decimal base with string as a number. - */ + /** Test conv to decimal base with string as a number. */ @ParameterizedTest(name = "conv({0})") @ValueSource(strings = {"11", "0", "11111"}) public void conv_to_decimal(String value) { @@ -332,9 +290,7 @@ public void conv_to_decimal(String value) { assertEquals(String.format("conv(\"%s\", 16, 10)", value), conv.toString()); } - /** - * Test conv to decimal base with integer as a number. - */ + /** Test conv to decimal base with integer as a number. */ @ParameterizedTest(name = "conv({0})") @ValueSource(ints = {11, 0, 11111}) public void conv_to_decimal(Integer value) { @@ -357,273 +313,187 @@ public void conv_to_decimal(Integer value) { assertEquals(String.format("conv(%s, 16, 10)", value), conv.toString()); } - /** - * Test crc32 with string value. - */ + /** Test crc32 with string value. */ @ParameterizedTest(name = "crc({0})") @ValueSource(strings = {"odfe", "sql"}) public void crc32_string_value(String value) { FunctionExpression crc = DSL.crc32(DSL.literal(value)); CRC32 crc32 = new CRC32(); crc32.update(value.getBytes()); - assertThat( - crc.valueOf(valueEnv()), - allOf(hasType(LONG), hasValue(crc32.getValue()))); + assertThat(crc.valueOf(valueEnv()), allOf(hasType(LONG), hasValue(crc32.getValue()))); assertEquals(String.format("crc32(\"%s\")", value), crc.toString()); } - /** - * Test constant e. - */ + /** Test constant e. */ @Test public void test_e() { FunctionExpression e = DSL.euler(); assertThat(e.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.E))); } - /** - * Test exp with integer value. - */ + /** Test exp with integer value. */ @ParameterizedTest(name = "exp({0})") @ValueSource(ints = {-2, 2}) public void exp_int_value(Integer value) { FunctionExpression exp = DSL.exp(DSL.literal(value)); - assertThat( - exp.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.exp(value)))); + assertThat(exp.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.exp(value)))); assertEquals(String.format("exp(%s)", value.toString()), exp.toString()); } - /** - * Test exp with long value. - */ + /** Test exp with long value. */ @ParameterizedTest(name = "exp({0})") @ValueSource(longs = {-2L, 2L}) public void exp_long_value(Long value) { FunctionExpression exp = DSL.exp(DSL.literal(value)); - assertThat( - exp.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.exp(value)))); + assertThat(exp.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.exp(value)))); assertEquals(String.format("exp(%s)", value.toString()), exp.toString()); } - /** - * Test exp with float value. - */ + /** Test exp with float value. */ @ParameterizedTest(name = "exp({0})") @ValueSource(floats = {-2F, 2F}) public void exp_float_value(Float value) { FunctionExpression exp = DSL.exp(DSL.literal(value)); - assertThat( - exp.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.exp(value)))); + assertThat(exp.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.exp(value)))); assertEquals(String.format("exp(%s)", value.toString()), exp.toString()); } - /** - * Test exp with double value. - */ + /** Test exp with double value. */ @ParameterizedTest(name = "exp({0})") @ValueSource(doubles = {-2D, 2D}) public void exp_double_value(Double value) { FunctionExpression exp = DSL.exp(DSL.literal(value)); - assertThat( - exp.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.exp(value)))); + assertThat(exp.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.exp(value)))); assertEquals(String.format("exp(%s)", value.toString()), exp.toString()); } - /** - * Test expm1 with integer value. - */ + /** Test expm1 with integer value. */ @ParameterizedTest(name = "expm1({0})") - @ValueSource(ints = { - -1, 0, 1, Integer.MAX_VALUE, Integer.MIN_VALUE}) + @ValueSource(ints = {-1, 0, 1, Integer.MAX_VALUE, Integer.MIN_VALUE}) public void expm1_int_value(Integer value) { FunctionExpression expm1 = DSL.expm1(DSL.literal(value)); - assertThat( - expm1.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.expm1(value)))); + assertThat(expm1.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.expm1(value)))); assertEquals(String.format("expm1(%s)", value), expm1.toString()); } - /** - * Test expm1 with long value. - */ + /** Test expm1 with long value. */ @ParameterizedTest(name = "expm1({0})") - @ValueSource(longs = { - -1L, 0L, 1L, Long.MAX_VALUE, Long.MIN_VALUE}) + @ValueSource(longs = {-1L, 0L, 1L, Long.MAX_VALUE, Long.MIN_VALUE}) public void expm1_long_value(Long value) { FunctionExpression expm1 = DSL.expm1(DSL.literal(value)); - assertThat( - expm1.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.expm1(value)))); + assertThat(expm1.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.expm1(value)))); assertEquals(String.format("expm1(%s)", value), expm1.toString()); } - /** - * Test expm1 with float value. - */ + /** Test expm1 with float value. */ @ParameterizedTest(name = "expm1({0})") - @ValueSource(floats = { - -1.5F, -1F, 0F, 1F, 1.5F, Float.MAX_VALUE, Float.MIN_VALUE}) + @ValueSource(floats = {-1.5F, -1F, 0F, 1F, 1.5F, Float.MAX_VALUE, Float.MIN_VALUE}) public void expm1_float_value(Float value) { FunctionExpression expm1 = DSL.expm1(DSL.literal(value)); - assertThat( - expm1.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.expm1(value)))); + assertThat(expm1.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.expm1(value)))); assertEquals(String.format("expm1(%s)", value), expm1.toString()); } - /** - * Test expm1 with double value. - */ + /** Test expm1 with double value. */ @ParameterizedTest(name = "expm1({0})") - @ValueSource(doubles = { - -1.5D, -1D, 0D, 1D, 1.5D, Double.MAX_VALUE, Double.MIN_VALUE}) + @ValueSource(doubles = {-1.5D, -1D, 0D, 1D, 1.5D, Double.MAX_VALUE, Double.MIN_VALUE}) public void expm1_double_value(Double value) { FunctionExpression expm1 = DSL.expm1(DSL.literal(value)); - assertThat( - expm1.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.expm1(value)))); + assertThat(expm1.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.expm1(value)))); assertEquals(String.format("expm1(%s)", value), expm1.toString()); } - /** - * Test expm1 with short value. - */ + /** Test expm1 with short value. */ @ParameterizedTest(name = "expm1({0})") - @ValueSource(shorts = { - -1, 0, 1, Short.MAX_VALUE, Short.MIN_VALUE}) + @ValueSource(shorts = {-1, 0, 1, Short.MAX_VALUE, Short.MIN_VALUE}) public void expm1_short_value(Short value) { FunctionExpression expm1 = DSL.expm1(DSL.literal(value)); - assertThat( - expm1.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.expm1(value)))); + assertThat(expm1.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.expm1(value)))); assertEquals(String.format("expm1(%s)", value), expm1.toString()); } - /** - * Test expm1 with byte value. - */ + /** Test expm1 with byte value. */ @ParameterizedTest(name = "expm1({0})") - @ValueSource(bytes = { - -1, 0, 1, Byte.MAX_VALUE, Byte.MIN_VALUE}) + @ValueSource(bytes = {-1, 0, 1, Byte.MAX_VALUE, Byte.MIN_VALUE}) public void expm1_byte_value(Byte value) { FunctionExpression expm1 = DSL.expm1(DSL.literal(value)); - assertThat( - expm1.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.expm1(value)))); + assertThat(expm1.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.expm1(value)))); assertEquals(String.format("expm1(%s)", value), expm1.toString()); } - /** - * Test floor with integer value. - */ + /** Test floor with integer value. */ @ParameterizedTest(name = "floor({0})") @ValueSource(ints = {-2, 2}) public void floor_int_value(Integer value) { FunctionExpression floor = DSL.floor(DSL.literal(value)); - assertThat( - floor.valueOf(valueEnv()), - allOf(hasType(LONG), hasValue((long) Math.floor(value)))); + assertThat(floor.valueOf(valueEnv()), allOf(hasType(LONG), hasValue((long) Math.floor(value)))); assertEquals(String.format("floor(%s)", value), floor.toString()); } - /** - * Test floor with long value. - */ + /** Test floor with long value. */ @ParameterizedTest(name = "floor({0})") @ValueSource(longs = {-2L, 2L}) public void floor_long_value(Long value) { FunctionExpression floor = DSL.floor(DSL.literal(value)); - assertThat( - floor.valueOf(valueEnv()), - allOf(hasType(LONG), hasValue((long) Math.floor(value)))); + assertThat(floor.valueOf(valueEnv()), allOf(hasType(LONG), hasValue((long) Math.floor(value)))); assertEquals(String.format("floor(%s)", value.toString()), floor.toString()); } - /** - * Test floor with float value. - */ + /** Test floor with float value. */ @ParameterizedTest(name = "floor({0})") @ValueSource(floats = {-2F, 2F}) public void floor_float_value(Float value) { FunctionExpression floor = DSL.floor(DSL.literal(value)); - assertThat( - floor.valueOf(valueEnv()), - allOf(hasType(LONG), hasValue((long) Math.floor(value)))); + assertThat(floor.valueOf(valueEnv()), allOf(hasType(LONG), hasValue((long) Math.floor(value)))); assertEquals(String.format("floor(%s)", value.toString()), floor.toString()); } - /** - * Test floor with double value. - */ + /** Test floor with double value. */ @ParameterizedTest(name = "floor({0})") @ValueSource(doubles = {-2D, 2D}) public void floor_double_value(Double value) { FunctionExpression floor = DSL.floor(DSL.literal(value)); - assertThat( - floor.valueOf(valueEnv()), - allOf(hasType(LONG), hasValue((long) Math.floor(value)))); + assertThat(floor.valueOf(valueEnv()), allOf(hasType(LONG), hasValue((long) Math.floor(value)))); assertEquals(String.format("floor(%s)", value.toString()), floor.toString()); } - /** - * Test ln with integer value. - */ + /** Test ln with integer value. */ @ParameterizedTest(name = "ln({0})") @ValueSource(ints = {2, 3}) public void ln_int_value(Integer value) { FunctionExpression ln = DSL.ln(DSL.literal(value)); - assertThat( - ln.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.log(value)))); + assertThat(ln.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.log(value)))); assertEquals(String.format("ln(%s)", value.toString()), ln.toString()); } - /** - * Test ln with long value. - */ + /** Test ln with long value. */ @ParameterizedTest(name = "ln({0})") @ValueSource(longs = {2L, 3L}) public void ln_long_value(Long value) { FunctionExpression ln = DSL.ln(DSL.literal(value)); - assertThat( - ln.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.log(value)))); + assertThat(ln.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.log(value)))); assertEquals(String.format("ln(%s)", value.toString()), ln.toString()); } - /** - * Test ln with float value. - */ + /** Test ln with float value. */ @ParameterizedTest(name = "ln({0})") @ValueSource(floats = {2F, 3F}) public void ln_float_value(Float value) { FunctionExpression ln = DSL.ln(DSL.literal(value)); - assertThat( - ln.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.log(value)))); + assertThat(ln.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.log(value)))); assertEquals(String.format("ln(%s)", value.toString()), ln.toString()); } - /** - * Test ln with double value. - */ + /** Test ln with double value. */ @ParameterizedTest(name = "ln({0})") @ValueSource(doubles = {2D, 3D}) public void ln_double_value(Double value) { FunctionExpression ln = DSL.ln(DSL.literal(value)); - assertThat( - ln.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.log(value)))); + assertThat(ln.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.log(value)))); assertEquals(String.format("ln(%s)", value.toString()), ln.toString()); } - /** - * Test ln with invalid value. - */ + /** Test ln with invalid value. */ @ParameterizedTest(name = "ln({0})") @ValueSource(doubles = {0D, -3D}) public void ln_invalid_value(Double value) { @@ -632,69 +502,47 @@ public void ln_invalid_value(Double value) { assertTrue(ln.valueOf(valueEnv()).isNull()); } - /** - * Test log with 1 int argument. - */ + /** Test log with 1 int argument. */ @ParameterizedTest(name = "log({0})") @ValueSource(ints = {2, 3}) public void log_int_value(Integer v) { FunctionExpression log = DSL.log(DSL.literal(v)); assertEquals(log.type(), DOUBLE); - assertThat( - getDoubleValue(log.valueOf(valueEnv())), - closeTo(Math.log(v), 0.0001) - ); + assertThat(getDoubleValue(log.valueOf(valueEnv())), closeTo(Math.log(v), 0.0001)); assertEquals(String.format("log(%s)", v.toString()), log.toString()); } - /** - * Test log with 1 long argument. - */ + /** Test log with 1 long argument. */ @ParameterizedTest(name = "log({0})") @ValueSource(longs = {2L, 3L}) public void log_int_value(Long v) { FunctionExpression log = DSL.log(DSL.literal(v)); assertEquals(log.type(), DOUBLE); - assertThat( - getDoubleValue(log.valueOf(valueEnv())), - closeTo(Math.log(v), 0.0001) - ); + assertThat(getDoubleValue(log.valueOf(valueEnv())), closeTo(Math.log(v), 0.0001)); assertEquals(String.format("log(%s)", v.toString()), log.toString()); } - /** - * Test log with 1 float argument. - */ + /** Test log with 1 float argument. */ @ParameterizedTest(name = "log({0})") @ValueSource(floats = {2F, 3F}) public void log_float_value(Float v) { FunctionExpression log = DSL.log(DSL.literal(v)); assertEquals(log.type(), DOUBLE); - assertThat( - getDoubleValue(log.valueOf(valueEnv())), - closeTo(Math.log(v), 0.0001) - ); + assertThat(getDoubleValue(log.valueOf(valueEnv())), closeTo(Math.log(v), 0.0001)); assertEquals(String.format("log(%s)", v.toString()), log.toString()); } - /** - * Test log with 1 double argument. - */ + /** Test log with 1 double argument. */ @ParameterizedTest(name = "log({0})") @ValueSource(doubles = {2D, 3D}) public void log_double_value(Double v) { FunctionExpression log = DSL.log(DSL.literal(v)); assertEquals(log.type(), DOUBLE); - assertThat( - getDoubleValue(log.valueOf(valueEnv())), - closeTo(Math.log(v), 0.0001) - ); + assertThat(getDoubleValue(log.valueOf(valueEnv())), closeTo(Math.log(v), 0.0001)); assertEquals(String.format("log(%s)", v.toString()), log.toString()); } - /** - * Test log with 1 invalid value. - */ + /** Test log with 1 invalid value. */ @ParameterizedTest(name = "log({0})") @ValueSource(doubles = {0D, -3D}) public void log_invalid_value(Double value) { @@ -703,65 +551,51 @@ public void log_invalid_value(Double value) { assertTrue(log.valueOf(valueEnv()).isNull()); } - /** - * Test log with 2 int arguments. - */ + /** Test log with 2 int arguments. */ @ParameterizedTest(name = "log({0}, {1})") @MethodSource("testLogIntegerArguments") public void log_two_int_value(Integer v1, Integer v2) { FunctionExpression log = DSL.log(DSL.literal(v1), DSL.literal(v2)); assertEquals(log.type(), DOUBLE); assertThat( - getDoubleValue(log.valueOf(valueEnv())), - closeTo(Math.log(v2) / Math.log(v1), 0.0001)); + getDoubleValue(log.valueOf(valueEnv())), closeTo(Math.log(v2) / Math.log(v1), 0.0001)); assertEquals(String.format("log(%s, %s)", v1.toString(), v2.toString()), log.toString()); } - /** - * Test log with 2 long arguments. - */ + /** Test log with 2 long arguments. */ @ParameterizedTest(name = "log({0}, {1})") @MethodSource("testLogLongArguments") public void log_two_long_value(Long v1, Long v2) { FunctionExpression log = DSL.log(DSL.literal(v1), DSL.literal(v2)); assertEquals(log.type(), DOUBLE); assertThat( - getDoubleValue(log.valueOf(valueEnv())), - closeTo(Math.log(v2) / Math.log(v1), 0.0001)); + getDoubleValue(log.valueOf(valueEnv())), closeTo(Math.log(v2) / Math.log(v1), 0.0001)); assertEquals(String.format("log(%s, %s)", v1.toString(), v2.toString()), log.toString()); } - /** - * Test log with 2 float arguments. - */ + /** Test log with 2 float arguments. */ @ParameterizedTest(name = "log({0}, {1})") @MethodSource("testLogFloatArguments") public void log_two_double_value(Float v1, Float v2) { FunctionExpression log = DSL.log(DSL.literal(v1), DSL.literal(v2)); assertEquals(log.type(), DOUBLE); assertThat( - getDoubleValue(log.valueOf(valueEnv())), - closeTo(Math.log(v2) / Math.log(v1), 0.0001)); + getDoubleValue(log.valueOf(valueEnv())), closeTo(Math.log(v2) / Math.log(v1), 0.0001)); assertEquals(String.format("log(%s, %s)", v1.toString(), v2.toString()), log.toString()); } - /** - * Test log with 2 double arguments. - */ + /** Test log with 2 double arguments. */ @ParameterizedTest(name = "log({0}, {1})") @MethodSource("testLogDoubleArguments") public void log_two_double_value(Double v1, Double v2) { FunctionExpression log = DSL.log(DSL.literal(v1), DSL.literal(v2)); assertEquals(log.type(), DOUBLE); assertThat( - getDoubleValue(log.valueOf(valueEnv())), - closeTo(Math.log(v2) / Math.log(v1), 0.0001)); + getDoubleValue(log.valueOf(valueEnv())), closeTo(Math.log(v2) / Math.log(v1), 0.0001)); assertEquals(String.format("log(%s, %s)", v1.toString(), v2.toString()), log.toString()); } - /** - * Test log with 2 invalid double arguments. - */ + /** Test log with 2 invalid double arguments. */ @ParameterizedTest(name = "log({0}, {2})") @MethodSource("testLogInvalidDoubleArguments") public void log_two_invalid_double_value(Double v1, Double v2) { @@ -770,69 +604,47 @@ public void log_two_invalid_double_value(Double v1, Double v2) { assertTrue(log.valueOf(valueEnv()).isNull()); } - /** - * Test log10 with int value. - */ + /** Test log10 with int value. */ @ParameterizedTest(name = "log10({0})") @ValueSource(ints = {2, 3}) public void log10_int_value(Integer v) { FunctionExpression log = DSL.log10(DSL.literal(v)); assertEquals(log.type(), DOUBLE); - assertThat( - getDoubleValue(log.valueOf(valueEnv())), - closeTo(Math.log10(v), 0.0001) - ); + assertThat(getDoubleValue(log.valueOf(valueEnv())), closeTo(Math.log10(v), 0.0001)); assertEquals(String.format("log10(%s)", v.toString()), log.toString()); } - /** - * Test log10 with long value. - */ + /** Test log10 with long value. */ @ParameterizedTest(name = "log10({0})") @ValueSource(longs = {2L, 3L}) public void log10_long_value(Long v) { FunctionExpression log = DSL.log10(DSL.literal(v)); assertEquals(log.type(), DOUBLE); - assertThat( - getDoubleValue(log.valueOf(valueEnv())), - closeTo(Math.log10(v), 0.0001) - ); + assertThat(getDoubleValue(log.valueOf(valueEnv())), closeTo(Math.log10(v), 0.0001)); assertEquals(String.format("log10(%s)", v.toString()), log.toString()); } - /** - * Test log10 with float value. - */ + /** Test log10 with float value. */ @ParameterizedTest(name = "log10({0})") @ValueSource(floats = {2F, 3F}) public void log10_float_value(Float v) { FunctionExpression log = DSL.log10(DSL.literal(v)); assertEquals(log.type(), DOUBLE); - assertThat( - getDoubleValue(log.valueOf(valueEnv())), - closeTo(Math.log10(v), 0.0001) - ); + assertThat(getDoubleValue(log.valueOf(valueEnv())), closeTo(Math.log10(v), 0.0001)); assertEquals(String.format("log10(%s)", v.toString()), log.toString()); } - /** - * Test log10 with int value. - */ + /** Test log10 with int value. */ @ParameterizedTest(name = "log10({0})") @ValueSource(doubles = {2D, 3D}) public void log10_double_value(Double v) { FunctionExpression log = DSL.log10(DSL.literal(v)); assertEquals(log.type(), DOUBLE); - assertThat( - getDoubleValue(log.valueOf(valueEnv())), - closeTo(Math.log10(v), 0.0001) - ); + assertThat(getDoubleValue(log.valueOf(valueEnv())), closeTo(Math.log10(v), 0.0001)); assertEquals(String.format("log10(%s)", v.toString()), log.toString()); } - /** - * Test log10 with 1 invalid double argument. - */ + /** Test log10 with 1 invalid double argument. */ @ParameterizedTest(name = "log10({0})") @ValueSource(doubles = {0D, -3D}) public void log10_two_invalid_value(Double v) { @@ -841,69 +653,47 @@ public void log10_two_invalid_value(Double v) { assertTrue(log.valueOf(valueEnv()).isNull()); } - /** - * Test log2 with int value. - */ + /** Test log2 with int value. */ @ParameterizedTest(name = "log10({0})") @ValueSource(ints = {2, 3}) public void log2_int_value(Integer v) { FunctionExpression log = DSL.log2(DSL.literal(v)); assertEquals(log.type(), DOUBLE); - assertThat( - getDoubleValue(log.valueOf(valueEnv())), - closeTo(Math.log(v) / Math.log(2), 0.0001) - ); + assertThat(getDoubleValue(log.valueOf(valueEnv())), closeTo(Math.log(v) / Math.log(2), 0.0001)); assertEquals(String.format("log2(%s)", v.toString()), log.toString()); } - /** - * Test log2 with long value. - */ + /** Test log2 with long value. */ @ParameterizedTest(name = "log10({0})") @ValueSource(longs = {2L, 3L}) public void log2_long_value(Long v) { FunctionExpression log = DSL.log2(DSL.literal(v)); assertEquals(log.type(), DOUBLE); - assertThat( - getDoubleValue(log.valueOf(valueEnv())), - closeTo(Math.log(v) / Math.log(2), 0.0001) - ); + assertThat(getDoubleValue(log.valueOf(valueEnv())), closeTo(Math.log(v) / Math.log(2), 0.0001)); assertEquals(String.format("log2(%s)", v.toString()), log.toString()); } - /** - * Test log2 with float value. - */ + /** Test log2 with float value. */ @ParameterizedTest(name = "log10({0})") @ValueSource(floats = {2F, 3F}) public void log2_float_value(Float v) { FunctionExpression log = DSL.log2(DSL.literal(v)); assertEquals(log.type(), DOUBLE); - assertThat( - getDoubleValue(log.valueOf(valueEnv())), - closeTo(Math.log(v) / Math.log(2), 0.0001) - ); + assertThat(getDoubleValue(log.valueOf(valueEnv())), closeTo(Math.log(v) / Math.log(2), 0.0001)); assertEquals(String.format("log2(%s)", v.toString()), log.toString()); } - /** - * Test log2 with double value. - */ + /** Test log2 with double value. */ @ParameterizedTest(name = "log10({0})") @ValueSource(doubles = {2D, 3D}) public void log2_double_value(Double v) { FunctionExpression log = DSL.log2(DSL.literal(v)); assertEquals(log.type(), DOUBLE); - assertThat( - getDoubleValue(log.valueOf(valueEnv())), - closeTo(Math.log(v) / Math.log(2), 0.0001) - ); + assertThat(getDoubleValue(log.valueOf(valueEnv())), closeTo(Math.log(v) / Math.log(2), 0.0001)); assertEquals(String.format("log2(%s)", v.toString()), log.toString()); } - /** - * Test log2 with an invalid double value. - */ + /** Test log2 with an invalid double value. */ @ParameterizedTest(name = "log2({0})") @ValueSource(doubles = {0D, -2D}) public void log2_invalid_double_value(Double v) { @@ -912,9 +702,7 @@ public void log2_invalid_double_value(Double v) { assertTrue(log.valueOf(valueEnv()).isNull()); } - /** - * Test mod with byte value. - */ + /** Test mod with byte value. */ @ParameterizedTest(name = "mod({0}, {1})") @MethodSource("testLogByteArguments") public void mod_byte_value(Byte v1, Byte v2) { @@ -930,9 +718,7 @@ public void mod_byte_value(Byte v1, Byte v2) { assertTrue(mod.valueOf(valueEnv()).isNull()); } - /** - * Test mod with short value. - */ + /** Test mod with short value. */ @ParameterizedTest(name = "mod({0}, {1})") @MethodSource("testLogShortArguments") public void mod_short_value(Short v1, Short v2) { @@ -940,8 +726,7 @@ public void mod_short_value(Short v1, Short v2) { assertThat( mod.valueOf(valueEnv()), - allOf(hasType(SHORT), - hasValue(Integer.valueOf(v1 % v2).shortValue()))); + allOf(hasType(SHORT), hasValue(Integer.valueOf(v1 % v2).shortValue()))); assertEquals(String.format("mod(%s, %s)", v1, v2), mod.toString()); mod = DSL.mod(DSL.literal(v1), DSL.literal(new ExprShortValue(0))); @@ -949,16 +734,12 @@ public void mod_short_value(Short v1, Short v2) { assertTrue(mod.valueOf(valueEnv()).isNull()); } - /** - * Test mod with integer value. - */ + /** Test mod with integer value. */ @ParameterizedTest(name = "mod({0}, {1})") @MethodSource("testLogIntegerArguments") public void mod_int_value(Integer v1, Integer v2) { FunctionExpression mod = DSL.mod(DSL.literal(v1), DSL.literal(v2)); - assertThat( - mod.valueOf(valueEnv()), - allOf(hasType(INTEGER), hasValue(v1 % v2))); + assertThat(mod.valueOf(valueEnv()), allOf(hasType(INTEGER), hasValue(v1 % v2))); assertEquals(String.format("mod(%s, %s)", v1, v2), mod.toString()); mod = DSL.mod(DSL.literal(v1), DSL.literal(0)); @@ -966,16 +747,12 @@ public void mod_int_value(Integer v1, Integer v2) { assertTrue(mod.valueOf(valueEnv()).isNull()); } - /** - * Test mod with long value. - */ + /** Test mod with long value. */ @ParameterizedTest(name = "mod({0}, {1})") @MethodSource("testLogLongArguments") public void mod_long_value(Long v1, Long v2) { FunctionExpression mod = DSL.mod(DSL.literal(v1), DSL.literal(v2)); - assertThat( - mod.valueOf(valueEnv()), - allOf(hasType(LONG), hasValue(v1 % v2))); + assertThat(mod.valueOf(valueEnv()), allOf(hasType(LONG), hasValue(v1 % v2))); assertEquals(String.format("mod(%s, %s)", v1, v2), mod.toString()); mod = DSL.mod(DSL.literal(v1), DSL.literal(0)); @@ -983,16 +760,12 @@ public void mod_long_value(Long v1, Long v2) { assertTrue(mod.valueOf(valueEnv()).isNull()); } - /** - * Test mod with long value. - */ + /** Test mod with long value. */ @ParameterizedTest(name = "mod({0}, {1})") @MethodSource("testLogFloatArguments") public void mod_float_value(Float v1, Float v2) { FunctionExpression mod = DSL.mod(DSL.literal(v1), DSL.literal(v2)); - assertThat( - mod.valueOf(valueEnv()), - allOf(hasType(FLOAT), hasValue(v1 % v2))); + assertThat(mod.valueOf(valueEnv()), allOf(hasType(FLOAT), hasValue(v1 % v2))); assertEquals(String.format("mod(%s, %s)", v1, v2), mod.toString()); mod = DSL.mod(DSL.literal(v1), DSL.literal(0)); @@ -1000,16 +773,12 @@ public void mod_float_value(Float v1, Float v2) { assertTrue(mod.valueOf(valueEnv()).isNull()); } - /** - * Test mod with double value. - */ + /** Test mod with double value. */ @ParameterizedTest(name = "mod({0}, {1})") @MethodSource("testLogDoubleArguments") public void mod_double_value(Double v1, Double v2) { FunctionExpression mod = DSL.mod(DSL.literal(v1), DSL.literal(v2)); - assertThat( - mod.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(v1 % v2))); + assertThat(mod.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(v1 % v2))); assertEquals(String.format("mod(%s, %s)", v1, v2), mod.toString()); mod = DSL.mod(DSL.literal(v1), DSL.literal(0)); @@ -1017,105 +786,72 @@ public void mod_double_value(Double v1, Double v2) { assertTrue(mod.valueOf(valueEnv()).isNull()); } - /** - * Test pow/power with short value. - */ + /** Test pow/power with short value. */ @ParameterizedTest(name = "pow({0}, {1}") @MethodSource("testLogShortArguments") public void pow_short_value(Short v1, Short v2) { FunctionExpression pow = DSL.pow(DSL.literal(v1), DSL.literal(v2)); - assertThat( - pow.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.pow(v1, v2)))); + assertThat(pow.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.pow(v1, v2)))); assertEquals(String.format("pow(%s, %s)", v1, v2), pow.toString()); - FunctionExpression power = - DSL.power(DSL.literal(v1), DSL.literal(v2)); - assertThat( - power.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.pow(v1, v2)))); + FunctionExpression power = DSL.power(DSL.literal(v1), DSL.literal(v2)); + assertThat(power.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.pow(v1, v2)))); assertEquals(String.format("pow(%s, %s)", v1, v2), pow.toString()); } - /** - * Test pow/power with integer value. - */ + /** Test pow/power with integer value. */ @ParameterizedTest(name = "pow({0}, {1}") @MethodSource("testLogIntegerArguments") public void pow_int_value(Integer v1, Integer v2) { FunctionExpression pow = DSL.pow(DSL.literal(v1), DSL.literal(v2)); - assertThat( - pow.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.pow(v1, v2)))); + assertThat(pow.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.pow(v1, v2)))); assertEquals(String.format("pow(%s, %s)", v1, v2), pow.toString()); FunctionExpression power = DSL.power(DSL.literal(v1), DSL.literal(v2)); - assertThat( - power.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.pow(v1, v2)))); + assertThat(power.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.pow(v1, v2)))); assertEquals(String.format("pow(%s, %s)", v1, v2), pow.toString()); } - /** - * Test pow/power with long value. - */ + /** Test pow/power with long value. */ @ParameterizedTest(name = "pow({0}, {1}") @MethodSource("testLogLongArguments") public void pow_long_value(Long v1, Long v2) { FunctionExpression pow = DSL.pow(DSL.literal(v1), DSL.literal(v2)); - assertThat( - pow.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.pow(v1, v2)))); + assertThat(pow.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.pow(v1, v2)))); assertEquals(String.format("pow(%s, %s)", v1, v2), pow.toString()); FunctionExpression power = DSL.power(DSL.literal(v1), DSL.literal(v2)); - assertThat( - power.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.pow(v1, v2)))); + assertThat(power.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.pow(v1, v2)))); assertEquals(String.format("pow(%s, %s)", v1, v2), pow.toString()); } - /** - * Test pow/power with float value. - */ + /** Test pow/power with float value. */ @ParameterizedTest(name = "pow({0}, {1}") @MethodSource("testLogFloatArguments") public void pow_float_value(Float v1, Float v2) { FunctionExpression pow = DSL.pow(DSL.literal(v1), DSL.literal(v2)); - assertThat( - pow.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.pow(v1, v2)))); + assertThat(pow.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.pow(v1, v2)))); assertEquals(String.format("pow(%s, %s)", v1, v2), pow.toString()); FunctionExpression power = DSL.power(DSL.literal(v1), DSL.literal(v2)); - assertThat( - power.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.pow(v1, v2)))); + assertThat(power.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.pow(v1, v2)))); assertEquals(String.format("pow(%s, %s)", v1, v2), pow.toString()); } - /** - * Test pow/power with double value. - */ + /** Test pow/power with double value. */ @ParameterizedTest(name = "pow({0}, {1}") @MethodSource("testLogDoubleArguments") public void pow_double_value(Double v1, Double v2) { FunctionExpression pow = DSL.pow(DSL.literal(v1), DSL.literal(v2)); - assertThat( - pow.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.pow(v1, v2)))); + assertThat(pow.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.pow(v1, v2)))); assertEquals(String.format("pow(%s, %s)", v1, v2), pow.toString()); FunctionExpression power = DSL.power(DSL.literal(v1), DSL.literal(v2)); - assertThat( - power.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.pow(v1, v2)))); + assertThat(power.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.pow(v1, v2)))); assertEquals(String.format("pow(%s, %s)", v1, v2), pow.toString()); } - /** - * Test pow/power with null output. - */ + /** Test pow/power with null output. */ @Test public void pow_null_output() { FunctionExpression pow = DSL.pow(DSL.literal((double) -2), DSL.literal(1.5)); @@ -1129,367 +865,318 @@ public void pow_null_output() { assertTrue(pow.valueOf(valueEnv()).isNull()); } - /** - * Test pow/power with edge cases. - */ + /** Test pow/power with edge cases. */ @Test public void pow_edge_cases() { FunctionExpression pow = DSL.pow(DSL.literal((double) -2), DSL.literal((double) 2)); assertEquals(pow.type(), DOUBLE); - assertEquals(String.format("pow(%s, %s)",(double) -2, (double) 2), pow.toString()); - assertThat( - pow.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.pow(-2, 2)))); + assertEquals(String.format("pow(%s, %s)", (double) -2, (double) 2), pow.toString()); + assertThat(pow.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.pow(-2, 2)))); pow = DSL.pow(DSL.literal((double) 2), DSL.literal((double) 1.5)); assertEquals(pow.type(), DOUBLE); assertEquals(String.format("pow(%s, %s)", (double) 2, (double) 1.5), pow.toString()); - assertThat( - pow.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.pow(2, 1.5)))); + assertThat(pow.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.pow(2, 1.5)))); pow = DSL.pow(DSL.literal((float) -2), DSL.literal((float) 2)); assertEquals(pow.type(), DOUBLE); assertEquals(String.format("pow(%s, %s)", (float) -2, (float) 2), pow.toString()); assertThat( - pow.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.pow((float) -2, (float) 2)))); + pow.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.pow((float) -2, (float) 2)))); pow = DSL.pow(DSL.literal((float) 2), DSL.literal((float) 1.5)); assertEquals(pow.type(), DOUBLE); assertEquals(String.format("pow(%s, %s)", (float) 2, (float) 1.5), pow.toString()); assertThat( - pow.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.pow((float) 2, (float) 1.5)))); + pow.valueOf(valueEnv()), + allOf(hasType(DOUBLE), hasValue(Math.pow((float) 2, (float) 1.5)))); } - /** - * Test rint with byte value. - */ + /** Test rint with byte value. */ @ParameterizedTest(name = "rint({0})") - @ValueSource(bytes = { - -1, 0, 1, Byte.MAX_VALUE, Byte.MIN_VALUE}) + @ValueSource(bytes = {-1, 0, 1, Byte.MAX_VALUE, Byte.MIN_VALUE}) public void rint_byte_value(Byte value) { FunctionExpression rint = DSL.rint(DSL.literal(value)); - assertThat( - rint.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.rint(value)))); + assertThat(rint.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.rint(value)))); assertEquals(String.format("rint(%s)", value), rint.toString()); } - /** - * Test rint with short value. - */ + /** Test rint with short value. */ @ParameterizedTest(name = "rint({0})") - @ValueSource(shorts = { - -1, 0, 1, Short.MAX_VALUE, Short.MIN_VALUE}) + @ValueSource(shorts = {-1, 0, 1, Short.MAX_VALUE, Short.MIN_VALUE}) public void rint_short_value(Short value) { FunctionExpression rint = DSL.rint(DSL.literal(value)); - assertThat( - rint.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.rint(value)))); + assertThat(rint.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.rint(value)))); assertEquals(String.format("rint(%s)", value), rint.toString()); } - /** - * Test rint with integer value. - */ + /** Test rint with integer value. */ @ParameterizedTest(name = "rint({0})") - @ValueSource(ints = { - -1, 0, 1, Integer.MAX_VALUE, Integer.MIN_VALUE}) + @ValueSource(ints = {-1, 0, 1, Integer.MAX_VALUE, Integer.MIN_VALUE}) public void rint_int_value(Integer value) { FunctionExpression rint = DSL.rint(DSL.literal(value)); - assertThat( - rint.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.rint(value)))); + assertThat(rint.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.rint(value)))); assertEquals(String.format("rint(%s)", value), rint.toString()); } - /** - * Test rint with long value. - */ + /** Test rint with long value. */ @ParameterizedTest(name = "rint({0})") - @ValueSource(longs = { - -1L, 0L, 1L, Long.MAX_VALUE, Long.MIN_VALUE}) + @ValueSource(longs = {-1L, 0L, 1L, Long.MAX_VALUE, Long.MIN_VALUE}) public void rint_long_value(Long value) { FunctionExpression rint = DSL.rint(DSL.literal(value)); - assertThat( - rint.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.rint(value)))); + assertThat(rint.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.rint(value)))); assertEquals(String.format("rint(%s)", value), rint.toString()); } - /** - * Test rint with float value. - */ + /** Test rint with float value. */ @ParameterizedTest(name = "rint({0})") - @ValueSource(floats = { - -1F, -0.75F, -0.5F, 0F, 0.5F, 0.500000001F, - 0.75F, 1F, 1.9999F, 42.42F, Float.MAX_VALUE, Float.MIN_VALUE}) + @ValueSource( + floats = { + -1F, + -0.75F, + -0.5F, + 0F, + 0.5F, + 0.500000001F, + 0.75F, + 1F, + 1.9999F, + 42.42F, + Float.MAX_VALUE, + Float.MIN_VALUE + }) public void rint_float_value(Float value) { FunctionExpression rint = DSL.rint(DSL.literal(value)); - assertThat( - rint.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.rint(value)))); + assertThat(rint.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.rint(value)))); assertEquals(String.format("rint(%s)", value), rint.toString()); } - /** - * Test rint with double value. - */ + /** Test rint with double value. */ @ParameterizedTest(name = "rint({0})") - @ValueSource(doubles = { - -1F, -0.75F, -0.5F, 0F, 0.5F, 0.500000001F, - 0.75F, 1F, 1.9999F, 42.42F, Double.MAX_VALUE, Double.MIN_VALUE}) + @ValueSource( + doubles = { + -1F, + -0.75F, + -0.5F, + 0F, + 0.5F, + 0.500000001F, + 0.75F, + 1F, + 1.9999F, + 42.42F, + Double.MAX_VALUE, + Double.MIN_VALUE + }) public void rint_double_value(Double value) { FunctionExpression rint = DSL.rint(DSL.literal(value)); - assertThat( - rint.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.rint(value)))); + assertThat(rint.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.rint(value)))); assertEquals(String.format("rint(%s)", value), rint.toString()); } - /** - * Test round with integer value. - */ + /** Test round with integer value. */ @ParameterizedTest(name = "round({0}") @ValueSource(ints = {21, -21}) public void round_int_value(Integer value) { FunctionExpression round = DSL.round(DSL.literal(value)); - assertThat( - round.valueOf(valueEnv()), - allOf(hasType(LONG), hasValue((long) Math.round(value)))); + assertThat(round.valueOf(valueEnv()), allOf(hasType(LONG), hasValue((long) Math.round(value)))); assertEquals(String.format("round(%s)", value), round.toString()); round = DSL.round(DSL.literal(value), DSL.literal(1)); assertThat( round.valueOf(valueEnv()), - allOf(hasType(LONG), hasValue( - new BigDecimal(value).setScale(1, RoundingMode.HALF_UP).longValue()))); + allOf( + hasType(LONG), + hasValue(new BigDecimal(value).setScale(1, RoundingMode.HALF_UP).longValue()))); assertEquals(String.format("round(%s, 1)", value), round.toString()); round = DSL.round(DSL.literal(value), DSL.literal(-1)); assertThat( round.valueOf(valueEnv()), - allOf(hasType(LONG), hasValue( - new BigDecimal(value).setScale(-1, RoundingMode.HALF_UP).longValue()))); + allOf( + hasType(LONG), + hasValue(new BigDecimal(value).setScale(-1, RoundingMode.HALF_UP).longValue()))); assertEquals(String.format("round(%s, -1)", value), round.toString()); } - /** - * Test round with long value. - */ + /** Test round with long value. */ @ParameterizedTest(name = "round({0}") @ValueSource(longs = {21L, -21L}) public void round_long_value(Long value) { FunctionExpression round = DSL.round(DSL.literal(value)); - assertThat( - round.valueOf(valueEnv()), - allOf(hasType(LONG), hasValue((long) Math.round(value)))); + assertThat(round.valueOf(valueEnv()), allOf(hasType(LONG), hasValue((long) Math.round(value)))); assertEquals(String.format("round(%s)", value), round.toString()); round = DSL.round(DSL.literal(value), DSL.literal(1)); assertThat( round.valueOf(valueEnv()), - allOf(hasType(LONG), hasValue( - new BigDecimal(value).setScale(1, RoundingMode.HALF_UP).longValue()))); + allOf( + hasType(LONG), + hasValue(new BigDecimal(value).setScale(1, RoundingMode.HALF_UP).longValue()))); assertEquals(String.format("round(%s, 1)", value), round.toString()); round = DSL.round(DSL.literal(value), DSL.literal(-1)); assertThat( round.valueOf(valueEnv()), - allOf(hasType(LONG), hasValue( - new BigDecimal(value).setScale(-1, RoundingMode.HALF_UP).longValue()))); + allOf( + hasType(LONG), + hasValue(new BigDecimal(value).setScale(-1, RoundingMode.HALF_UP).longValue()))); assertEquals(String.format("round(%s, -1)", value), round.toString()); } - /** - * Test round with float value. - */ + /** Test round with float value. */ @ParameterizedTest(name = "round({0}") @ValueSource(floats = {21F, -21F}) public void round_float_value(Float value) { FunctionExpression round = DSL.round(DSL.literal(value)); assertThat( - round.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue((double) Math.round(value)))); + round.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue((double) Math.round(value)))); assertEquals(String.format("round(%s)", value), round.toString()); round = DSL.round(DSL.literal(value), DSL.literal(1)); assertThat( round.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue( - new BigDecimal(value).setScale(1, RoundingMode.HALF_UP).doubleValue()))); + allOf( + hasType(DOUBLE), + hasValue(new BigDecimal(value).setScale(1, RoundingMode.HALF_UP).doubleValue()))); assertEquals(String.format("round(%s, 1)", value), round.toString()); round = DSL.round(DSL.literal(value), DSL.literal(-1)); assertThat( round.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue( - new BigDecimal(value).setScale(-1, RoundingMode.HALF_UP).doubleValue()))); + allOf( + hasType(DOUBLE), + hasValue(new BigDecimal(value).setScale(-1, RoundingMode.HALF_UP).doubleValue()))); assertEquals(String.format("round(%s, -1)", value), round.toString()); } - /** - * Test round with double value. - */ + /** Test round with double value. */ @ParameterizedTest(name = "round({0}") @ValueSource(doubles = {21D, -21D}) public void round_double_value(Double value) { FunctionExpression round = DSL.round(DSL.literal(value)); assertThat( - round.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue((double) Math.round(value)))); + round.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue((double) Math.round(value)))); assertEquals(String.format("round(%s)", value), round.toString()); round = DSL.round(DSL.literal(value), DSL.literal(1)); assertThat( round.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue( - new BigDecimal(value).setScale(1, RoundingMode.HALF_UP).doubleValue()))); + allOf( + hasType(DOUBLE), + hasValue(new BigDecimal(value).setScale(1, RoundingMode.HALF_UP).doubleValue()))); assertEquals(String.format("round(%s, 1)", value), round.toString()); round = DSL.round(DSL.literal(value), DSL.literal(-1)); assertThat( round.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue( - new BigDecimal(value).setScale(-1, RoundingMode.HALF_UP).doubleValue()))); + allOf( + hasType(DOUBLE), + hasValue(new BigDecimal(value).setScale(-1, RoundingMode.HALF_UP).doubleValue()))); assertEquals(String.format("round(%s, -1)", value), round.toString()); } - /** - * Test sign with integer value. - */ + /** Test sign with integer value. */ @ParameterizedTest(name = "sign({0})") @ValueSource(ints = {2, -2}) public void sign_int_value(Integer value) { FunctionExpression sign = DSL.sign(DSL.literal(value)); assertThat( - sign.valueOf(valueEnv()), - allOf(hasType(INTEGER), hasValue((int) Math.signum(value)))); + sign.valueOf(valueEnv()), allOf(hasType(INTEGER), hasValue((int) Math.signum(value)))); assertEquals(String.format("sign(%s)", value), sign.toString()); } - /** - * Test sign with long value. - */ + /** Test sign with long value. */ @ParameterizedTest(name = "sign({0})") @ValueSource(longs = {2L, -2L}) public void sign_long_value(Long value) { FunctionExpression sign = DSL.sign(DSL.literal(value)); assertThat( - sign.valueOf(valueEnv()), - allOf(hasType(INTEGER), hasValue((int) Math.signum(value)))); + sign.valueOf(valueEnv()), allOf(hasType(INTEGER), hasValue((int) Math.signum(value)))); assertEquals(String.format("sign(%s)", value), sign.toString()); } - /** - * Test sign with float value. - */ + /** Test sign with float value. */ @ParameterizedTest(name = "sign({0})") @ValueSource(floats = {2F, -2F}) public void sign_float_value(Float value) { FunctionExpression sign = DSL.sign(DSL.literal(value)); assertThat( - sign.valueOf(valueEnv()), - allOf(hasType(INTEGER), hasValue((int) Math.signum(value)))); + sign.valueOf(valueEnv()), allOf(hasType(INTEGER), hasValue((int) Math.signum(value)))); assertEquals(String.format("sign(%s)", value), sign.toString()); } - /** - * Test sign with double value. - */ + /** Test sign with double value. */ @ParameterizedTest(name = "sign({0})") @ValueSource(doubles = {2, -2}) public void sign_double_value(Double value) { FunctionExpression sign = DSL.sign(DSL.literal(value)); assertThat( - sign.valueOf(valueEnv()), - allOf(hasType(INTEGER), hasValue((int) Math.signum(value)))); + sign.valueOf(valueEnv()), allOf(hasType(INTEGER), hasValue((int) Math.signum(value)))); assertEquals(String.format("sign(%s)", value), sign.toString()); } - /** - * Test signum with byte value. - */ + /** Test signum with byte value. */ @ParameterizedTest(name = "signum({0})") @ValueSource(bytes = {2, 0, -2}) public void signum_bytes_value(Byte value) { FunctionExpression signum = DSL.signum(DSL.literal(value)); assertThat( - signum.valueOf(valueEnv()), - allOf(hasType(INTEGER), hasValue((int) Math.signum(value)))); + signum.valueOf(valueEnv()), allOf(hasType(INTEGER), hasValue((int) Math.signum(value)))); assertEquals(String.format("signum(%s)", value), signum.toString()); } - /** - * Test signum with short value. - */ + /** Test signum with short value. */ @ParameterizedTest(name = "signum({0})") @ValueSource(shorts = {2, 0, -2}) public void signum_short_value(Short value) { FunctionExpression signum = DSL.signum(DSL.literal(value)); assertThat( - signum.valueOf(valueEnv()), - allOf(hasType(INTEGER), hasValue((int) Math.signum(value)))); + signum.valueOf(valueEnv()), allOf(hasType(INTEGER), hasValue((int) Math.signum(value)))); assertEquals(String.format("signum(%s)", value), signum.toString()); } - /** - * Test signum with integer value. - */ + /** Test signum with integer value. */ @ParameterizedTest(name = "signum({0})") @ValueSource(ints = {2, 0, -2}) public void signum_int_value(Integer value) { FunctionExpression signum = DSL.signum(DSL.literal(value)); assertThat( - signum.valueOf(valueEnv()), - allOf(hasType(INTEGER), hasValue((int) Math.signum(value)))); + signum.valueOf(valueEnv()), allOf(hasType(INTEGER), hasValue((int) Math.signum(value)))); assertEquals(String.format("signum(%s)", value), signum.toString()); } - /** - * Test signum with long value. - */ + /** Test signum with long value. */ @ParameterizedTest(name = "signum({0})") @ValueSource(longs = {2L, 0L, -2L}) public void signum_long_value(Long value) { FunctionExpression signum = DSL.signum(DSL.literal(value)); assertThat( - signum.valueOf(valueEnv()), - allOf(hasType(INTEGER), hasValue((int) Math.signum(value)))); + signum.valueOf(valueEnv()), allOf(hasType(INTEGER), hasValue((int) Math.signum(value)))); assertEquals(String.format("signum(%s)", value), signum.toString()); } - /** - * Test signum with float value. - */ + /** Test signum with float value. */ @ParameterizedTest(name = "signum({0})") @ValueSource(floats = {2F, 0F, -2F}) public void signum_float_value(Float value) { FunctionExpression signum = DSL.signum(DSL.literal(value)); assertThat( - signum.valueOf(valueEnv()), - allOf(hasType(INTEGER), hasValue((int) Math.signum(value)))); + signum.valueOf(valueEnv()), allOf(hasType(INTEGER), hasValue((int) Math.signum(value)))); assertEquals(String.format("signum(%s)", value), signum.toString()); } - /** - * Test signum with double value. - */ + /** Test signum with double value. */ @ParameterizedTest(name = "signum({0})") @ValueSource(doubles = {2, 0, -2}) public void signum_double_value(Double value) { FunctionExpression signum = DSL.signum(DSL.literal(value)); assertThat( - signum.valueOf(valueEnv()), - allOf(hasType(INTEGER), hasValue((int) Math.signum(value)))); + signum.valueOf(valueEnv()), allOf(hasType(INTEGER), hasValue((int) Math.signum(value)))); assertEquals(String.format("signum(%s)", value), signum.toString()); } - /** - * Test sinh with byte value. - */ + /** Test sinh with byte value. */ @ParameterizedTest(name = "sinh({0})") @ValueSource(bytes = {-1, 1, 2, Byte.MAX_VALUE, Byte.MIN_VALUE}) public void sinh_byte_value(Byte value) { @@ -1498,9 +1185,7 @@ public void sinh_byte_value(Byte value) { assertEquals(String.format("sinh(%s)", value), sinh.toString()); } - /** - * Test sinh with short value. - */ + /** Test sinh with short value. */ @ParameterizedTest(name = "sinh({0})") @ValueSource(shorts = {-1, 1, 2, Short.MAX_VALUE, Short.MIN_VALUE}) public void sinh_short_value(Short value) { @@ -1509,9 +1194,7 @@ public void sinh_short_value(Short value) { assertEquals(String.format("sinh(%s)", value), sinh.toString()); } - /** - * Test sinh with integer value. - */ + /** Test sinh with integer value. */ @ParameterizedTest(name = "sinh({0})") @ValueSource(ints = {-1, 1, 2, Integer.MAX_VALUE, Integer.MIN_VALUE}) public void sinh_int_value(Integer value) { @@ -1520,9 +1203,7 @@ public void sinh_int_value(Integer value) { assertEquals(String.format("sinh(%s)", value), sinh.toString()); } - /** - * Test sinh with long value. - */ + /** Test sinh with long value. */ @ParameterizedTest(name = "sinh({0})") @ValueSource(longs = {-1L, 1L, 2L, Long.MAX_VALUE, Long.MIN_VALUE}) public void sinh_long_value(Long value) { @@ -1531,9 +1212,7 @@ public void sinh_long_value(Long value) { assertEquals(String.format("sinh(%s)", value), sinh.toString()); } - /** - * Test sinh with float value. - */ + /** Test sinh with float value. */ @ParameterizedTest(name = "sinh({0})") @ValueSource(floats = {-1.5F, -1F, 1F, 1.5F, 2F, 2.7F, Float.MAX_VALUE, Float.MIN_VALUE}) public void sinh_float_value(Float value) { @@ -1542,9 +1221,7 @@ public void sinh_float_value(Float value) { assertEquals(String.format("sinh(%s)", value), sinh.toString()); } - /** - * Test sinh with double value. - */ + /** Test sinh with double value. */ @ParameterizedTest(name = "sinh({0})") @ValueSource(doubles = {-1.5, -1D, 1D, 1.5D, 2D, 2.7D, Double.MAX_VALUE, Double.MIN_VALUE}) public void sinh_double_value(Double value) { @@ -1553,9 +1230,7 @@ public void sinh_double_value(Double value) { assertEquals(String.format("sinh(%s)", value), sinh.toString()); } - /** - * Test sqrt with int value. - */ + /** Test sqrt with int value. */ @ParameterizedTest(name = "sqrt({0})") @ValueSource(ints = {1, 2}) public void sqrt_int_value(Integer value) { @@ -1564,9 +1239,7 @@ public void sqrt_int_value(Integer value) { assertEquals(String.format("sqrt(%s)", value), sqrt.toString()); } - /** - * Test sqrt with long value. - */ + /** Test sqrt with long value. */ @ParameterizedTest(name = "sqrt({0})") @ValueSource(longs = {1L, 2L}) public void sqrt_long_value(Long value) { @@ -1575,9 +1248,7 @@ public void sqrt_long_value(Long value) { assertEquals(String.format("sqrt(%s)", value), sqrt.toString()); } - /** - * Test sqrt with float value. - */ + /** Test sqrt with float value. */ @ParameterizedTest(name = "sqrt({0})") @ValueSource(floats = {1F, 2F}) public void sqrt_float_value(Float value) { @@ -1586,9 +1257,7 @@ public void sqrt_float_value(Float value) { assertEquals(String.format("sqrt(%s)", value), sqrt.toString()); } - /** - * Test sqrt with double value. - */ + /** Test sqrt with double value. */ @ParameterizedTest(name = "sqrt({0})") @ValueSource(doubles = {1D, 2D}) public void sqrt_double_value(Double value) { @@ -1597,9 +1266,7 @@ public void sqrt_double_value(Double value) { assertEquals(String.format("sqrt(%s)", value), sqrt.toString()); } - /** - * Test sqrt with negative value. - */ + /** Test sqrt with negative value. */ @ParameterizedTest(name = "sqrt({0})") @ValueSource(doubles = {-1D, -2D}) public void sqrt_negative_value(Double value) { @@ -1608,73 +1275,90 @@ public void sqrt_negative_value(Double value) { assertTrue(sqrt.valueOf(valueEnv()).isNull()); } - /** - * Test truncate with integer value. - */ + /** Test truncate with integer value. */ @ParameterizedTest(name = "truncate({0}, {1})") @ValueSource(ints = {2, -2, Integer.MAX_VALUE, Integer.MIN_VALUE}) public void truncate_int_value(Integer value) { FunctionExpression truncate = DSL.truncate(DSL.literal(value), DSL.literal(1)); assertThat( - truncate.valueOf(valueEnv()), allOf(hasType(LONG), + truncate.valueOf(valueEnv()), + allOf( + hasType(LONG), hasValue(BigDecimal.valueOf(value).setScale(1, RoundingMode.DOWN).longValue()))); assertEquals(String.format("truncate(%s, 1)", value), truncate.toString()); } - /** - * Test truncate with long value. - */ + /** Test truncate with long value. */ @ParameterizedTest(name = "truncate({0}, {1})") @ValueSource(longs = {2L, -2L, Long.MAX_VALUE, Long.MIN_VALUE}) public void truncate_long_value(Long value) { FunctionExpression truncate = DSL.truncate(DSL.literal(value), DSL.literal(1)); assertThat( - truncate.valueOf(valueEnv()), allOf(hasType(LONG), + truncate.valueOf(valueEnv()), + allOf( + hasType(LONG), hasValue(BigDecimal.valueOf(value).setScale(1, RoundingMode.DOWN).longValue()))); assertEquals(String.format("truncate(%s, 1)", value), truncate.toString()); } - /** - * Test truncate with float value. - */ + /** Test truncate with float value. */ @ParameterizedTest(name = "truncate({0}, {1})") @ValueSource(floats = {2F, -2F, Float.MAX_VALUE, Float.MIN_VALUE}) public void truncate_float_value(Float value) { FunctionExpression truncate = DSL.truncate(DSL.literal(value), DSL.literal(1)); assertThat( - truncate.valueOf(valueEnv()), allOf(hasType(DOUBLE), + truncate.valueOf(valueEnv()), + allOf( + hasType(DOUBLE), hasValue(BigDecimal.valueOf(value).setScale(1, RoundingMode.DOWN).doubleValue()))); assertEquals(String.format("truncate(%s, 1)", value), truncate.toString()); } - /** - * Test truncate with double value. - */ + /** Test truncate with double value. */ @ParameterizedTest(name = "truncate({0}, {1})") - @ValueSource(doubles = {2D, -9.223372036854776e+18D, -2147483649.0D, -2147483648.0D, - -32769.0D, -32768.0D, -34.84D, -2.0D, -1.2D, -1.0D, 0.0D, 1.0D, - 1.3D, 2.0D, 1004.3D, 32767.0D, 32768.0D, 2147483647.0D, 2147483648.0D, - 9.223372036854776e+18D, Double.MAX_VALUE, Double.MIN_VALUE}) + @ValueSource( + doubles = { + 2D, + -9.223372036854776e+18D, + -2147483649.0D, + -2147483648.0D, + -32769.0D, + -32768.0D, + -34.84D, + -2.0D, + -1.2D, + -1.0D, + 0.0D, + 1.0D, + 1.3D, + 2.0D, + 1004.3D, + 32767.0D, + 32768.0D, + 2147483647.0D, + 2147483648.0D, + 9.223372036854776e+18D, + Double.MAX_VALUE, + Double.MIN_VALUE + }) public void truncate_double_value(Double value) { FunctionExpression truncate = DSL.truncate(DSL.literal(value), DSL.literal(1)); assertThat( - truncate.valueOf(valueEnv()), allOf(hasType(DOUBLE), + truncate.valueOf(valueEnv()), + allOf( + hasType(DOUBLE), hasValue(BigDecimal.valueOf(value).setScale(1, RoundingMode.DOWN).doubleValue()))); assertEquals(String.format("truncate(%s, 1)", value), truncate.toString()); } - /** - * Test constant pi. - */ + /** Test constant pi. */ @Test public void test_pi() { FunctionExpression pi = DSL.pi(); assertThat(pi.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.PI))); } - /** - * Test rand with no argument. - */ + /** Test rand with no argument. */ @Test public void rand_no_arg() { FunctionExpression rand = DSL.rand(); @@ -1685,9 +1369,7 @@ public void rand_no_arg() { assertEquals("rand()", rand.toString()); } - /** - * Test rand with integer value. - */ + /** Test rand with integer value. */ @ParameterizedTest(name = "rand({0})") @ValueSource(ints = {2, 3}) public void rand_int_value(Integer n) { @@ -1695,27 +1377,22 @@ public void rand_int_value(Integer n) { assertEquals(FLOAT, rand.type()); assertTrue( getFloatValue(rand.valueOf(valueEnv())) >= 0 - && getFloatValue(rand.valueOf(valueEnv())) < 1); + && getFloatValue(rand.valueOf(valueEnv())) < 1); assertEquals(getFloatValue(rand.valueOf(valueEnv())), new Random(n).nextFloat()); assertEquals(String.format("rand(%s)", n), rand.toString()); } - /** - * Test acos with integer, long, float, double values. - */ + /** Test acos with integer, long, float, double values. */ @ParameterizedTest(name = "acos({0})") @MethodSource("trigonometricArguments") public void test_acos(Number value) { FunctionExpression acos = DSL.acos(DSL.literal(value)); assertThat( - acos.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.acos(value.doubleValue())))); + acos.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.acos(value.doubleValue())))); assertEquals(String.format("acos(%s)", value), acos.toString()); } - /** - * Test acos with illegal values. - */ + /** Test acos with illegal values. */ @ParameterizedTest(name = "acos({0})") @ValueSource(doubles = {2D, -2D}) public void acos_with_illegal_value(Number value) { @@ -1724,22 +1401,17 @@ public void acos_with_illegal_value(Number value) { assertTrue(acos.valueOf(valueEnv()).isNull()); } - /** - * Test asin with integer, long, float, double values. - */ + /** Test asin with integer, long, float, double values. */ @ParameterizedTest(name = "asin({0})") @MethodSource("trigonometricArguments") public void test_asin(Number value) { FunctionExpression asin = DSL.asin(DSL.literal(value)); assertThat( - asin.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.asin(value.doubleValue())))); + asin.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.asin(value.doubleValue())))); assertEquals(String.format("asin(%s)", value), asin.toString()); } - /** - * Test asin with illegal value. - */ + /** Test asin with illegal value. */ @ParameterizedTest(name = "asin({0})") @ValueSource(doubles = {2D, -2D}) public void asin_with_illegal_value(Number value) { @@ -1748,36 +1420,28 @@ public void asin_with_illegal_value(Number value) { assertTrue(asin.valueOf(valueEnv()).isNull()); } - /** - * Test atan with one argument integer, long, float, double values. - */ + /** Test atan with one argument integer, long, float, double values. */ @ParameterizedTest(name = "atan({0})") @MethodSource("trigonometricArguments") public void atan_one_arg(Number value) { FunctionExpression atan = DSL.atan(DSL.literal(value)); assertThat( - atan.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.atan(value.doubleValue())))); + atan.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.atan(value.doubleValue())))); assertEquals(String.format("atan(%s)", value), atan.toString()); } - /** - * Test atan with two arguments of integer, long, float, double values. - */ + /** Test atan with two arguments of integer, long, float, double values. */ @ParameterizedTest(name = "atan({0}, {1})") @MethodSource("trigonometricDoubleArguments") public void atan_two_args(Number v1, Number v2) { - FunctionExpression atan = - DSL.atan(DSL.literal(v1), DSL.literal(v2)); + FunctionExpression atan = DSL.atan(DSL.literal(v1), DSL.literal(v2)); assertThat( atan.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.atan2(v1.doubleValue(), v2.doubleValue())))); assertEquals(String.format("atan(%s, %s)", v1, v2), atan.toString()); } - /** - * Test atan2 with integer, long, float, double values. - */ + /** Test atan2 with integer, long, float, double values. */ @ParameterizedTest(name = "atan2({0}, {1})") @MethodSource("trigonometricDoubleArguments") public void test_atan2(Number v1, Number v2) { @@ -1788,22 +1452,17 @@ public void test_atan2(Number v1, Number v2) { assertEquals(String.format("atan2(%s, %s)", v1, v2), atan2.toString()); } - /** - * Test cos with integer, long, float, double values. - */ + /** Test cos with integer, long, float, double values. */ @ParameterizedTest(name = "cos({0})") @MethodSource("trigonometricArguments") public void test_cos(Number value) { FunctionExpression cos = DSL.cos(DSL.literal(value)); assertThat( - cos.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.cos(value.doubleValue())))); + cos.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.cos(value.doubleValue())))); assertEquals(String.format("cos(%s)", value), cos.toString()); } - /** - * Test cosh with byte value. - */ + /** Test cosh with byte value. */ @ParameterizedTest(name = "cosh({0})") @ValueSource(bytes = {-1, 1, 2}) public void cosh_byte_value(Byte value) { @@ -1812,9 +1471,7 @@ public void cosh_byte_value(Byte value) { assertEquals(String.format("cosh(%s)", value), cosh.toString()); } - /** - * Test cosh with short value. - */ + /** Test cosh with short value. */ @ParameterizedTest(name = "cosh({0})") @ValueSource(shorts = {-1, 1, 2}) public void cosh_short_value(Short value) { @@ -1823,9 +1480,7 @@ public void cosh_short_value(Short value) { assertEquals(String.format("cosh(%s)", value), cosh.toString()); } - /** - * Test cosh with integer value. - */ + /** Test cosh with integer value. */ @ParameterizedTest(name = "cosh({0})") @ValueSource(ints = {-1, 1, 2}) public void cosh_int_value(Integer value) { @@ -1834,9 +1489,7 @@ public void cosh_int_value(Integer value) { assertEquals(String.format("cosh(%s)", value), cosh.toString()); } - /** - * Test cosh with long value. - */ + /** Test cosh with long value. */ @ParameterizedTest(name = "cosh({0})") @ValueSource(longs = {-1L, 1L, 2L}) public void cosh_long_value(Long value) { @@ -1845,9 +1498,7 @@ public void cosh_long_value(Long value) { assertEquals(String.format("cosh(%s)", value), cosh.toString()); } - /** - * Test cosh with float value. - */ + /** Test cosh with float value. */ @ParameterizedTest(name = "cosh({0})") @ValueSource(floats = {-1F, 1F, 2F}) public void cosh_float_value(Float value) { @@ -1856,9 +1507,7 @@ public void cosh_float_value(Float value) { assertEquals(String.format("cosh(%s)", value), cosh.toString()); } - /** - * Test cosh with double value. - */ + /** Test cosh with double value. */ @ParameterizedTest(name = "cosh({0})") @ValueSource(doubles = {-1D, 1D, 2D}) public void cosh_double_value(Double value) { @@ -1867,9 +1516,7 @@ public void cosh_double_value(Double value) { assertEquals(String.format("cosh(%s)", value), cosh.toString()); } - /** - * Test cot with integer, long, float, double values. - */ + /** Test cot with integer, long, float, double values. */ @ParameterizedTest(name = "cot({0})") @MethodSource("trigonometricArguments") public void test_cot(Number value) { @@ -1880,21 +1527,18 @@ public void test_cot(Number value) { assertEquals(String.format("cot(%s)", value), cot.toString()); } - /** - * Test cot with out-of-range value 0. - */ + /** Test cot with out-of-range value 0. */ @ParameterizedTest(name = "cot({0})") @ValueSource(doubles = {0}) public void cot_with_zero(Number value) { FunctionExpression cot = DSL.cot(DSL.literal(value)); assertThrows( - ArithmeticException.class, () -> cot.valueOf(valueEnv()), + ArithmeticException.class, + () -> cot.valueOf(valueEnv()), String.format("Out of range value for cot(%s)", value)); } - /** - * Test degrees with integer, long, float, double values. - */ + /** Test degrees with integer, long, float, double values. */ @ParameterizedTest(name = "degrees({0})") @MethodSource("trigonometricArguments") public void test_degrees(Number value) { @@ -1905,9 +1549,7 @@ public void test_degrees(Number value) { assertEquals(String.format("degrees(%s)", value), degrees.toString()); } - /** - * Test radians with integer, long, float, double values. - */ + /** Test radians with integer, long, float, double values. */ @ParameterizedTest(name = "radians({0})") @MethodSource("trigonometricArguments") public void test_radians(Number value) { @@ -1918,35 +1560,27 @@ public void test_radians(Number value) { assertEquals(String.format("radians(%s)", value), radians.toString()); } - /** - * Test sin with integer, long, float, double values. - */ + /** Test sin with integer, long, float, double values. */ @ParameterizedTest(name = "sin({0})") @MethodSource("trigonometricArguments") public void test_sin(Number value) { FunctionExpression sin = DSL.sin(DSL.literal(value)); assertThat( - sin.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.sin(value.doubleValue())))); + sin.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.sin(value.doubleValue())))); assertEquals(String.format("sin(%s)", value), sin.toString()); } - /** - * Test tan with integer, long, float, double values. - */ + /** Test tan with integer, long, float, double values. */ @ParameterizedTest(name = "tan({0})") @MethodSource("trigonometricArguments") public void test_tan(Number value) { FunctionExpression tan = DSL.tan(DSL.literal(value)); assertThat( - tan.valueOf(valueEnv()), - allOf(hasType(DOUBLE), hasValue(Math.tan(value.doubleValue())))); + tan.valueOf(valueEnv()), allOf(hasType(DOUBLE), hasValue(Math.tan(value.doubleValue())))); assertEquals(String.format("tan(%s)", value), tan.toString()); } - /** - * Test cbrt with int value. - */ + /** Test cbrt with int value. */ @ParameterizedTest(name = "cbrt({0})") @ValueSource(ints = {1, 2}) public void cbrt_int_value(Integer value) { @@ -1955,9 +1589,7 @@ public void cbrt_int_value(Integer value) { assertEquals(String.format("cbrt(%s)", value), cbrt.toString()); } - /** - * Test cbrt with long value. - */ + /** Test cbrt with long value. */ @ParameterizedTest(name = "cbrt({0})") @ValueSource(longs = {1L, 2L}) public void cbrt_long_value(Long value) { @@ -1966,9 +1598,7 @@ public void cbrt_long_value(Long value) { assertEquals(String.format("cbrt(%s)", value), cbrt.toString()); } - /** - * Test cbrt with float value. - */ + /** Test cbrt with float value. */ @ParameterizedTest(name = "cbrt({0})") @ValueSource(floats = {1F, 2F}) public void cbrt_float_value(Float value) { @@ -1977,9 +1607,7 @@ public void cbrt_float_value(Float value) { assertEquals(String.format("cbrt(%s)", value), cbrt.toString()); } - /** - * Test cbrt with double value. - */ + /** Test cbrt with double value. */ @ParameterizedTest(name = "cbrt({0})") @ValueSource(doubles = {1D, 2D, Double.MAX_VALUE, Double.MIN_VALUE}) public void cbrt_double_value(Double value) { @@ -1988,9 +1616,7 @@ public void cbrt_double_value(Double value) { assertEquals(String.format("cbrt(%s)", value), cbrt.toString()); } - /** - * Test cbrt with negative value. - */ + /** Test cbrt with negative value. */ @ParameterizedTest(name = "cbrt({0})") @ValueSource(doubles = {-1D, -2D}) public void cbrt_negative_value(Double value) { diff --git a/core/src/test/java/org/opensearch/sql/expression/operator/convert/TypeCastOperatorTest.java b/core/src/test/java/org/opensearch/sql/expression/operator/convert/TypeCastOperatorTest.java index 742313922a..7803a4dbca 100644 --- a/core/src/test/java/org/opensearch/sql/expression/operator/convert/TypeCastOperatorTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/operator/convert/TypeCastOperatorTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.operator.convert; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -44,8 +43,12 @@ class TypeCastOperatorTest { private static Stream numberData() { - return Stream.of(new ExprByteValue(3), new ExprShortValue(3), - new ExprIntegerValue(3), new ExprLongValue(3L), new ExprFloatValue(3.14f), + return Stream.of( + new ExprByteValue(3), + new ExprShortValue(3), + new ExprIntegerValue(3), + new ExprLongValue(3L), + new ExprFloatValue(3.14f), new ExprDoubleValue(3.1415D)); } @@ -357,5 +360,4 @@ void castToDatetime() { assertEquals(DATETIME, expression.type()); assertEquals(new ExprDatetimeValue("2012-08-07 00:00:00"), expression.valueOf()); } - } diff --git a/core/src/test/java/org/opensearch/sql/expression/operator/predicate/BinaryPredicateOperatorTest.java b/core/src/test/java/org/opensearch/sql/expression/operator/predicate/BinaryPredicateOperatorTest.java index 52b1e8d8fc..e6290553ce 100644 --- a/core/src/test/java/org/opensearch/sql/expression/operator/predicate/BinaryPredicateOperatorTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/operator/predicate/BinaryPredicateOperatorTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.operator.predicate; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -59,7 +58,8 @@ class BinaryPredicateOperatorTest extends ExpressionTestBase { - private static List STRING_PATTERN_PAIRS = ImmutableList.of( + private static List STRING_PATTERN_PAIRS = + ImmutableList.of( new StringPatternPair("Michael!", ".*"), new StringPatternPair("new*\\n*line", "new\\\\*.\\\\*line"), new StringPatternPair("a", "^[a-d]"), @@ -102,8 +102,7 @@ private static List> getValuesForComparisonTests() { List.of(Instant.ofEpochSecond(100500), LocalDate.of(1961, 4, 12)), List.of(Instant.ofEpochSecond(100500), LocalTime.of(7, 40, 0)), List.of(LocalTime.of(7, 40, 0), LocalDateTime.of(1984, 10, 25, 7, 40)), - List.of(Instant.ofEpochSecond(42), LocalDateTime.of(1984, 10, 25, 7, 40)) - ); + List.of(Instant.ofEpochSecond(42), LocalDateTime.of(1984, 10, 25, 7, 40))); } private static Stream testEqualArguments() { @@ -112,22 +111,33 @@ private static Stream testEqualArguments() { builder.add(Arguments.of(fromObjectValue(argPair.get(0)), fromObjectValue(argPair.get(0)))); builder.add(Arguments.of(fromObjectValue(argPair.get(1)), fromObjectValue(argPair.get(1)))); } - builder.add(Arguments.of(fromObjectValue(LocalTime.of(7, 40, 0)), - fromObjectValue(LocalTime.of(7, 40, 0).atDate(LocalDate.now())))); - builder.add(Arguments.of(fromObjectValue(LocalDateTime.of(1970, 1, 1, 0, 0, 42)), - fromObjectValue(Instant.ofEpochSecond(42)))); - builder.add(Arguments.of(fromObjectValue(LocalDate.of(1970, 1, 1)), - fromObjectValue(Instant.ofEpochSecond(0)))); - builder.add(Arguments.of(fromObjectValue(LocalDate.of(1984, 10, 25)), - fromObjectValue(LocalDateTime.of(1984, 10, 25, 0, 0)))); - builder.add(Arguments.of(fromObjectValue(LocalTime.of(0, 0, 0)), - fromObjectValue(LocalDate.now()))); - builder.add(Arguments.of(fromObjectValue(LocalTime.of(0, 0, 0)), - fromObjectValue(LocalDate.now().atStartOfDay(ZoneId.of("UTC")).toInstant()))); - builder.add(Arguments.of(fromObjectValue(ImmutableList.of(1)), - fromObjectValue(ImmutableList.of(1)))); - builder.add(Arguments.of(fromObjectValue(ImmutableMap.of("str", 1)), - fromObjectValue(ImmutableMap.of("str", 1)))); + builder.add( + Arguments.of( + fromObjectValue(LocalTime.of(7, 40, 0)), + fromObjectValue(LocalTime.of(7, 40, 0).atDate(LocalDate.now())))); + builder.add( + Arguments.of( + fromObjectValue(LocalDateTime.of(1970, 1, 1, 0, 0, 42)), + fromObjectValue(Instant.ofEpochSecond(42)))); + builder.add( + Arguments.of( + fromObjectValue(LocalDate.of(1970, 1, 1)), fromObjectValue(Instant.ofEpochSecond(0)))); + builder.add( + Arguments.of( + fromObjectValue(LocalDate.of(1984, 10, 25)), + fromObjectValue(LocalDateTime.of(1984, 10, 25, 0, 0)))); + builder.add( + Arguments.of(fromObjectValue(LocalTime.of(0, 0, 0)), fromObjectValue(LocalDate.now()))); + builder.add( + Arguments.of( + fromObjectValue(LocalTime.of(0, 0, 0)), + fromObjectValue(LocalDate.now().atStartOfDay(ZoneId.of("UTC")).toInstant()))); + builder.add( + Arguments.of(fromObjectValue(ImmutableList.of(1)), fromObjectValue(ImmutableList.of(1)))); + builder.add( + Arguments.of( + fromObjectValue(ImmutableMap.of("str", 1)), + fromObjectValue(ImmutableMap.of("str", 1)))); return builder.build(); } @@ -137,24 +147,37 @@ private static Stream testNotEqualArguments() { builder.add(Arguments.of(fromObjectValue(argPair.get(0)), fromObjectValue(argPair.get(1)))); builder.add(Arguments.of(fromObjectValue(argPair.get(1)), fromObjectValue(argPair.get(0)))); } - builder.add(Arguments.of(fromObjectValue(LocalTime.of(7, 40, 0)), - fromObjectValue(LocalDateTime.of(1984, 10, 25, 7, 40, 0)))); - builder.add(Arguments.of(fromObjectValue(LocalDateTime.of(1984, 10, 25, 7, 40, 0)), - fromObjectValue(Instant.ofEpochSecond(42)))); - builder.add(Arguments.of(fromObjectValue(LocalDate.of(1984, 10, 25)), - fromObjectValue(Instant.ofEpochSecond(42)))); - builder.add(Arguments.of(fromObjectValue(LocalTime.of(7, 40, 0)), - fromObjectValue(Instant.ofEpochSecond(42)))); - builder.add(Arguments.of(fromObjectValue(LocalDate.of(1984, 10, 25)), - fromObjectValue(LocalDateTime.of(1984, 10, 25, 7, 40)))); - builder.add(Arguments.of(fromObjectValue(LocalDate.of(1984, 10, 25)), - fromObjectValue(LocalTime.of(7, 40, 0)))); - builder.add(Arguments.of(fromObjectValue(ImmutableList.of(1)), - fromObjectValue(ImmutableList.of(1, 2)))); - builder.add(Arguments.of(fromObjectValue(ImmutableList.of(1)), - fromObjectValue(ImmutableList.of(2)))); - builder.add(Arguments.of(fromObjectValue(ImmutableMap.of("str", 1)), - fromObjectValue(ImmutableMap.of("str2", 2)))); + builder.add( + Arguments.of( + fromObjectValue(LocalTime.of(7, 40, 0)), + fromObjectValue(LocalDateTime.of(1984, 10, 25, 7, 40, 0)))); + builder.add( + Arguments.of( + fromObjectValue(LocalDateTime.of(1984, 10, 25, 7, 40, 0)), + fromObjectValue(Instant.ofEpochSecond(42)))); + builder.add( + Arguments.of( + fromObjectValue(LocalDate.of(1984, 10, 25)), + fromObjectValue(Instant.ofEpochSecond(42)))); + builder.add( + Arguments.of( + fromObjectValue(LocalTime.of(7, 40, 0)), fromObjectValue(Instant.ofEpochSecond(42)))); + builder.add( + Arguments.of( + fromObjectValue(LocalDate.of(1984, 10, 25)), + fromObjectValue(LocalDateTime.of(1984, 10, 25, 7, 40)))); + builder.add( + Arguments.of( + fromObjectValue(LocalDate.of(1984, 10, 25)), fromObjectValue(LocalTime.of(7, 40, 0)))); + builder.add( + Arguments.of( + fromObjectValue(ImmutableList.of(1)), fromObjectValue(ImmutableList.of(1, 2)))); + builder.add( + Arguments.of(fromObjectValue(ImmutableList.of(1)), fromObjectValue(ImmutableList.of(2)))); + builder.add( + Arguments.of( + fromObjectValue(ImmutableMap.of("str", 1)), + fromObjectValue(ImmutableMap.of("str2", 2)))); return builder.build(); } @@ -169,13 +192,17 @@ private static Stream testCompareValueArguments() { } private static Stream testLikeArguments() { - List> arguments = Arrays.asList( - Arrays.asList("foo", "foo"), Arrays.asList("notFoo", "foo"), - Arrays.asList("foobar", "%bar"), Arrays.asList("bar", "%bar"), - Arrays.asList("foo", "fo_"), Arrays.asList("foo", "foo_"), - Arrays.asList("foorbar", "%o_ar"), Arrays.asList("foobar", "%o_a%"), - Arrays.asList("fooba%_\\^$.*[]()|+r", "%\\%\\_\\\\\\^\\$\\.\\*\\[\\]\\(\\)\\|\\+_") - ); + List> arguments = + Arrays.asList( + Arrays.asList("foo", "foo"), + Arrays.asList("notFoo", "foo"), + Arrays.asList("foobar", "%bar"), + Arrays.asList("bar", "%bar"), + Arrays.asList("foo", "fo_"), + Arrays.asList("foo", "foo_"), + Arrays.asList("foorbar", "%o_ar"), + Arrays.asList("foobar", "%o_a%"), + Arrays.asList("fooba%_\\^$.*[]()|+r", "%\\%\\_\\\\\\^\\$\\.\\*\\[\\]\\(\\)\\|\\+_")); Stream.Builder builder = Stream.builder(); for (List argPair : arguments) { builder.add(Arguments.of(fromObjectValue(argPair.get(0)), fromObjectValue(argPair.get(1)))); @@ -186,8 +213,7 @@ private static Stream testLikeArguments() { @ParameterizedTest(name = "and({0}, {1})") @MethodSource("binaryPredicateArguments") public void test_and(Boolean v1, Boolean v2) { - FunctionExpression and = - DSL.and(DSL.literal(booleanValue(v1)), DSL.literal(booleanValue(v2))); + FunctionExpression and = DSL.and(DSL.literal(booleanValue(v1)), DSL.literal(booleanValue(v2))); assertEquals(BOOLEAN, and.type()); assertEquals(v1 && v2, ExprValueUtils.getBooleanValue(and.valueOf(valueEnv()))); assertEquals(String.format("and(%s, %s)", v1.toString(), v2.toString()), and.toString()); @@ -235,23 +261,31 @@ public void test_boolean_and_missing() { @Test public void test_null_and_missing() { - FunctionExpression and = DSL.and(DSL.ref(BOOL_TYPE_MISSING_VALUE_FIELD, BOOLEAN), - DSL.ref(BOOL_TYPE_MISSING_VALUE_FIELD, BOOLEAN)); + FunctionExpression and = + DSL.and( + DSL.ref(BOOL_TYPE_MISSING_VALUE_FIELD, BOOLEAN), + DSL.ref(BOOL_TYPE_MISSING_VALUE_FIELD, BOOLEAN)); assertEquals(BOOLEAN, and.type()); assertEquals(LITERAL_MISSING, and.valueOf(valueEnv())); - and = DSL.and(DSL.ref(BOOL_TYPE_NULL_VALUE_FIELD, BOOLEAN), - DSL.ref(BOOL_TYPE_NULL_VALUE_FIELD, BOOLEAN)); + and = + DSL.and( + DSL.ref(BOOL_TYPE_NULL_VALUE_FIELD, BOOLEAN), + DSL.ref(BOOL_TYPE_NULL_VALUE_FIELD, BOOLEAN)); assertEquals(BOOLEAN, and.type()); assertEquals(LITERAL_NULL, and.valueOf(valueEnv())); - and = DSL.and(DSL.ref(BOOL_TYPE_NULL_VALUE_FIELD, BOOLEAN), - DSL.ref(BOOL_TYPE_MISSING_VALUE_FIELD, BOOLEAN)); + and = + DSL.and( + DSL.ref(BOOL_TYPE_NULL_VALUE_FIELD, BOOLEAN), + DSL.ref(BOOL_TYPE_MISSING_VALUE_FIELD, BOOLEAN)); assertEquals(BOOLEAN, and.type()); assertEquals(LITERAL_MISSING, and.valueOf(valueEnv())); - and = DSL.and(DSL.ref(BOOL_TYPE_MISSING_VALUE_FIELD, BOOLEAN), - DSL.ref(BOOL_TYPE_NULL_VALUE_FIELD, BOOLEAN)); + and = + DSL.and( + DSL.ref(BOOL_TYPE_MISSING_VALUE_FIELD, BOOLEAN), + DSL.ref(BOOL_TYPE_NULL_VALUE_FIELD, BOOLEAN)); assertEquals(BOOLEAN, and.type()); assertEquals(LITERAL_MISSING, and.valueOf(valueEnv())); } @@ -259,8 +293,7 @@ public void test_null_and_missing() { @ParameterizedTest(name = "or({0}, {1})") @MethodSource("binaryPredicateArguments") public void test_or(Boolean v1, Boolean v2) { - FunctionExpression or = - DSL.or(DSL.literal(booleanValue(v1)), DSL.literal(booleanValue(v2))); + FunctionExpression or = DSL.or(DSL.literal(booleanValue(v1)), DSL.literal(booleanValue(v2))); assertEquals(BOOLEAN, or.type()); assertEquals(v1 || v2, ExprValueUtils.getBooleanValue(or.valueOf(valueEnv()))); assertEquals(String.format("or(%s, %s)", v1.toString(), v2.toString()), or.toString()); @@ -308,34 +341,39 @@ public void test_boolean_or_missing() { @Test public void test_null_or_missing() { - FunctionExpression or = DSL.or(DSL.ref(BOOL_TYPE_MISSING_VALUE_FIELD, BOOLEAN), - DSL.ref(BOOL_TYPE_MISSING_VALUE_FIELD, BOOLEAN)); + FunctionExpression or = + DSL.or( + DSL.ref(BOOL_TYPE_MISSING_VALUE_FIELD, BOOLEAN), + DSL.ref(BOOL_TYPE_MISSING_VALUE_FIELD, BOOLEAN)); assertEquals(BOOLEAN, or.type()); assertEquals(LITERAL_MISSING, or.valueOf(valueEnv())); or = - DSL.or(DSL.ref(BOOL_TYPE_NULL_VALUE_FIELD, BOOLEAN), + DSL.or( + DSL.ref(BOOL_TYPE_NULL_VALUE_FIELD, BOOLEAN), DSL.ref(BOOL_TYPE_NULL_VALUE_FIELD, BOOLEAN)); assertEquals(BOOLEAN, or.type()); assertEquals(LITERAL_NULL, or.valueOf(valueEnv())); - or = DSL.or(DSL.ref(BOOL_TYPE_NULL_VALUE_FIELD, BOOLEAN), - DSL.ref(BOOL_TYPE_MISSING_VALUE_FIELD, BOOLEAN)); + or = + DSL.or( + DSL.ref(BOOL_TYPE_NULL_VALUE_FIELD, BOOLEAN), + DSL.ref(BOOL_TYPE_MISSING_VALUE_FIELD, BOOLEAN)); assertEquals(BOOLEAN, or.type()); assertEquals(LITERAL_NULL, or.valueOf(valueEnv())); - or = DSL.or(DSL.ref(BOOL_TYPE_MISSING_VALUE_FIELD, BOOLEAN), - DSL.ref(BOOL_TYPE_NULL_VALUE_FIELD, BOOLEAN)); + or = + DSL.or( + DSL.ref(BOOL_TYPE_MISSING_VALUE_FIELD, BOOLEAN), + DSL.ref(BOOL_TYPE_NULL_VALUE_FIELD, BOOLEAN)); assertEquals(BOOLEAN, or.type()); assertEquals(LITERAL_NULL, or.valueOf(valueEnv())); } - @ParameterizedTest(name = "xor({0}, {1})") @MethodSource("binaryPredicateArguments") public void test_xor(Boolean v1, Boolean v2) { - FunctionExpression xor = - DSL.xor(DSL.literal(booleanValue(v1)), DSL.literal(booleanValue(v2))); + FunctionExpression xor = DSL.xor(DSL.literal(booleanValue(v1)), DSL.literal(booleanValue(v2))); assertEquals(BOOLEAN, xor.type()); assertEquals(v1 ^ v2, ExprValueUtils.getBooleanValue(xor.valueOf(valueEnv()))); assertEquals(String.format("xor(%s, %s)", v1.toString(), v2.toString()), xor.toString()); @@ -383,23 +421,31 @@ public void test_boolean_xor_missing() { @Test public void test_null_xor_missing() { - FunctionExpression xor = DSL.xor(DSL.ref(BOOL_TYPE_MISSING_VALUE_FIELD, BOOLEAN), - DSL.ref(BOOL_TYPE_MISSING_VALUE_FIELD, BOOLEAN)); + FunctionExpression xor = + DSL.xor( + DSL.ref(BOOL_TYPE_MISSING_VALUE_FIELD, BOOLEAN), + DSL.ref(BOOL_TYPE_MISSING_VALUE_FIELD, BOOLEAN)); assertEquals(BOOLEAN, xor.type()); assertEquals(LITERAL_MISSING, xor.valueOf(valueEnv())); - xor = DSL.xor(DSL.ref(BOOL_TYPE_NULL_VALUE_FIELD, BOOLEAN), - DSL.ref(BOOL_TYPE_NULL_VALUE_FIELD, BOOLEAN)); + xor = + DSL.xor( + DSL.ref(BOOL_TYPE_NULL_VALUE_FIELD, BOOLEAN), + DSL.ref(BOOL_TYPE_NULL_VALUE_FIELD, BOOLEAN)); assertEquals(BOOLEAN, xor.type()); assertEquals(LITERAL_NULL, xor.valueOf(valueEnv())); - xor = DSL.xor(DSL.ref(BOOL_TYPE_NULL_VALUE_FIELD, BOOLEAN), - DSL.ref(BOOL_TYPE_MISSING_VALUE_FIELD, BOOLEAN)); + xor = + DSL.xor( + DSL.ref(BOOL_TYPE_NULL_VALUE_FIELD, BOOLEAN), + DSL.ref(BOOL_TYPE_MISSING_VALUE_FIELD, BOOLEAN)); assertEquals(BOOLEAN, xor.type()); assertEquals(LITERAL_NULL, xor.valueOf(valueEnv())); - xor = DSL.xor(DSL.ref(BOOL_TYPE_MISSING_VALUE_FIELD, BOOLEAN), - DSL.ref(BOOL_TYPE_NULL_VALUE_FIELD, BOOLEAN)); + xor = + DSL.xor( + DSL.ref(BOOL_TYPE_MISSING_VALUE_FIELD, BOOLEAN), + DSL.ref(BOOL_TYPE_NULL_VALUE_FIELD, BOOLEAN)); assertEquals(BOOLEAN, xor.type()); assertEquals(LITERAL_NULL, xor.valueOf(valueEnv())); } @@ -410,24 +456,28 @@ public void test_equal(ExprValue v1, ExprValue v2) { FunctionExpression equal = DSL.equal(functionProperties, DSL.literal(v1), DSL.literal(v2)); assertEquals(BOOLEAN, equal.type()); if (v1.type() == v2.type()) { - assertEquals(v1.value().equals(v2.value()), - ExprValueUtils.getBooleanValue(equal.valueOf(valueEnv()))); + assertEquals( + v1.value().equals(v2.value()), ExprValueUtils.getBooleanValue(equal.valueOf(valueEnv()))); } if (v1.type() != STRUCT && v1.type() != ARRAY) { - assertEquals(0 == compare(functionProperties, v1, v2), + assertEquals( + 0 == compare(functionProperties, v1, v2), ExprValueUtils.getBooleanValue(equal.valueOf(valueEnv()))); } assertStringRepr(v1, v2, "=", equal); } - private void assertStringRepr(ExprValue v1, ExprValue v2, String function, - FunctionExpression functionExpression) { + private void assertStringRepr( + ExprValue v1, ExprValue v2, String function, FunctionExpression functionExpression) { if (v1.type() == v2.type()) { assertEquals(String.format("%s(%s, %s)", function, v1, v2), functionExpression.toString()); } else { var widerType = v1.type() == TIMESTAMP || v2.type() == TIMESTAMP ? TIMESTAMP : DATETIME; - assertEquals(String.format("%s(%s, %s)", function, getExpectedStringRepr(widerType, v1), - getExpectedStringRepr(widerType, v2)), functionExpression.toString()); + assertEquals( + String.format( + "%s(%s, %s)", + function, getExpectedStringRepr(widerType, v1), getExpectedStringRepr(widerType, v2)), + functionExpression.toString()); } } @@ -441,15 +491,17 @@ private String getExpectedStringRepr(ExprType widerType, ExprValue value) { @ParameterizedTest(name = "equal({0}, {1})") @MethodSource({"testEqualArguments", "testNotEqualArguments"}) public void test_notequal(ExprValue v1, ExprValue v2) { - FunctionExpression notequal = DSL.notequal(functionProperties, - DSL.literal(v1), DSL.literal(v2)); + FunctionExpression notequal = + DSL.notequal(functionProperties, DSL.literal(v1), DSL.literal(v2)); assertEquals(BOOLEAN, notequal.type()); if (v1.type() == v2.type()) { - assertEquals(!v1.value().equals(v2.value()), + assertEquals( + !v1.value().equals(v2.value()), ExprValueUtils.getBooleanValue(notequal.valueOf(valueEnv()))); } if (v1.type() != STRUCT && v1.type() != ARRAY) { - assertEquals(0 != compare(functionProperties, v1, v2), + assertEquals( + 0 != compare(functionProperties, v1, v2), ExprValueUtils.getBooleanValue(notequal.valueOf(valueEnv()))); } assertStringRepr(v1, v2, "!=", notequal); @@ -460,7 +512,8 @@ public void test_notequal(ExprValue v1, ExprValue v2) { public void test_less(ExprValue v1, ExprValue v2) { FunctionExpression less = DSL.less(functionProperties, DSL.literal(v1), DSL.literal(v2)); assertEquals(BOOLEAN, less.type()); - assertEquals(compare(functionProperties, v1, v2) < 0, + assertEquals( + compare(functionProperties, v1, v2) < 0, ExprValueUtils.getBooleanValue(less.valueOf(valueEnv()))); assertStringRepr(v1, v2, "<", less); } @@ -470,7 +523,8 @@ public void test_less(ExprValue v1, ExprValue v2) { public void test_lte(ExprValue v1, ExprValue v2) { FunctionExpression lte = DSL.lte(functionProperties, DSL.literal(v1), DSL.literal(v2)); assertEquals(BOOLEAN, lte.type()); - assertEquals(compare(functionProperties, v1, v2) <= 0, + assertEquals( + compare(functionProperties, v1, v2) <= 0, ExprValueUtils.getBooleanValue(lte.valueOf(valueEnv()))); assertStringRepr(v1, v2, "<=", lte); } @@ -480,7 +534,8 @@ public void test_lte(ExprValue v1, ExprValue v2) { public void test_greater(ExprValue v1, ExprValue v2) { FunctionExpression greater = DSL.greater(functionProperties, DSL.literal(v1), DSL.literal(v2)); assertEquals(BOOLEAN, greater.type()); - assertEquals(compare(functionProperties, v1, v2) > 0, + assertEquals( + compare(functionProperties, v1, v2) > 0, ExprValueUtils.getBooleanValue(greater.valueOf(valueEnv()))); assertStringRepr(v1, v2, ">", greater); } @@ -490,7 +545,8 @@ public void test_greater(ExprValue v1, ExprValue v2) { public void test_gte(ExprValue v1, ExprValue v2) { FunctionExpression gte = DSL.gte(functionProperties, DSL.literal(v1), DSL.literal(v2)); assertEquals(BOOLEAN, gte.type()); - assertEquals(compare(functionProperties, v1, v2) >= 0, + assertEquals( + compare(functionProperties, v1, v2) >= 0, ExprValueUtils.getBooleanValue(gte.valueOf(valueEnv()))); assertStringRepr(v1, v2, ">=", gte); } @@ -522,17 +578,15 @@ void test_regexp() { } void testRegexpString(StringPatternPair stringPatternPair) { - FunctionExpression expression = DSL.regexp( + FunctionExpression expression = + DSL.regexp( DSL.literal(new ExprStringValue(stringPatternPair.getStr())), DSL.literal(new ExprStringValue(stringPatternPair.getPatt()))); assertEquals(INTEGER, expression.type()); - assertEquals(stringPatternPair.regExpTest(), expression - .valueOf(valueEnv()).integerValue()); + assertEquals(stringPatternPair.regExpTest(), expression.valueOf(valueEnv()).integerValue()); } - /** - * Todo. remove this test cases after script serilization implemented. - */ + /** Todo. remove this test cases after script serilization implemented. */ @Test public void serializationTest() throws Exception { Expression expression = DSL.equal(DSL.literal("v1"), DSL.literal("v2")); diff --git a/core/src/test/java/org/opensearch/sql/expression/operator/predicate/UnaryPredicateOperatorTest.java b/core/src/test/java/org/opensearch/sql/expression/operator/predicate/UnaryPredicateOperatorTest.java index de3f5a3e7e..f7a1a7008a 100644 --- a/core/src/test/java/org/opensearch/sql/expression/operator/predicate/UnaryPredicateOperatorTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/operator/predicate/UnaryPredicateOperatorTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.operator.predicate; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -50,15 +49,15 @@ private static Stream isNullArguments() { expressions.add(DSL.literal(LITERAL_NULL)); return Lists.cartesianProduct(expressions, expressions).stream() - .map(list -> { - Expression e1 = list.get(0); - if (e1.valueOf(valueEnv()).isNull() - || e1.valueOf(valueEnv()).isMissing()) { - return Arguments.of(e1, DSL.literal(LITERAL_TRUE)); - } else { - return Arguments.of(e1, DSL.literal(LITERAL_FALSE)); - } - }); + .map( + list -> { + Expression e1 = list.get(0); + if (e1.valueOf(valueEnv()).isNull() || e1.valueOf(valueEnv()).isMissing()) { + return Arguments.of(e1, DSL.literal(LITERAL_TRUE)); + } else { + return Arguments.of(e1, DSL.literal(LITERAL_FALSE)); + } + }); } private static Stream ifNullArguments() { @@ -69,16 +68,17 @@ private static Stream ifNullArguments() { exprValueArrayList.add(DSL.literal(LITERAL_NULL)); return Lists.cartesianProduct(exprValueArrayList, exprValueArrayList).stream() - .map(list -> { - Expression e1 = list.get(0); - Expression e2 = list.get(1); - if (e1.valueOf(valueEnv()).value() == LITERAL_NULL.value() + .map( + list -> { + Expression e1 = list.get(0); + Expression e2 = list.get(1); + if (e1.valueOf(valueEnv()).value() == LITERAL_NULL.value() || e1.valueOf(valueEnv()).value() == LITERAL_MISSING) { - return Arguments.of(e1, e2, e2); - } else { - return Arguments.of(e1, e2, e1); - } - }); + return Arguments.of(e1, e2, e2); + } else { + return Arguments.of(e1, e2, e1); + } + }); } private static Stream nullIfArguments() { @@ -87,16 +87,17 @@ private static Stream nullIfArguments() { exprValueArrayList.add(DSL.literal(321)); return Lists.cartesianProduct(exprValueArrayList, exprValueArrayList).stream() - .map(list -> { - Expression e1 = list.get(0); - Expression e2 = list.get(1); + .map( + list -> { + Expression e1 = list.get(0); + Expression e2 = list.get(1); - if (e1.equals(e2)) { - return Arguments.of(e1, e2, DSL.literal(LITERAL_NULL)); - } else { - return Arguments.of(e1, e2, e1); - } - }); + if (e1.equals(e2)) { + return Arguments.of(e1, e2, DSL.literal(LITERAL_NULL)); + } else { + return Arguments.of(e1, e2, e1); + } + }); } private static Stream ifArguments() { @@ -107,14 +108,15 @@ private static Stream ifArguments() { exprValueArrayList.add(DSL.literal(LITERAL_MISSING)); return Lists.cartesianProduct(exprValueArrayList, exprValueArrayList).stream() - .map(list -> { - Expression e1 = list.get(0); - if (e1.valueOf(valueEnv()).value() == LITERAL_TRUE.value()) { - return Arguments.of(e1, DSL.literal("123"), DSL.literal("321"), DSL.literal("123")); - } else { - return Arguments.of(e1, DSL.literal("123"), DSL.literal("321"), DSL.literal("321")); - } - }); + .map( + list -> { + Expression e1 = list.get(0); + if (e1.valueOf(valueEnv()).value() == LITERAL_TRUE.value()) { + return Arguments.of(e1, DSL.literal("123"), DSL.literal("321"), DSL.literal("123")); + } else { + return Arguments.of(e1, DSL.literal("123"), DSL.literal("321"), DSL.literal("321")); + } + }); } private static Stream exprIfNullArguments() { @@ -125,15 +127,16 @@ private static Stream exprIfNullArguments() { exprValues.add(ExprValueUtils.integerValue(456)); return Lists.cartesianProduct(exprValues, exprValues).stream() - .map(list -> { - ExprValue e1 = list.get(0); - ExprValue e2 = list.get(1); - if (e1.isNull() || e1.isMissing()) { - return Arguments.of(e1, e2, e2); - } else { - return Arguments.of(e1, e2, e1); - } - }); + .map( + list -> { + ExprValue e1 = list.get(0); + ExprValue e2 = list.get(1); + if (e1.isNull() || e1.isMissing()) { + return Arguments.of(e1, e2, e2); + } else { + return Arguments.of(e1, e2, e1); + } + }); } private static Stream exprNullIfArguments() { @@ -143,15 +146,16 @@ private static Stream exprNullIfArguments() { exprValues.add(ExprValueUtils.integerValue(123)); return Lists.cartesianProduct(exprValues, exprValues).stream() - .map(list -> { - ExprValue e1 = list.get(0); - ExprValue e2 = list.get(1); - if (e1.equals(e2)) { - return Arguments.of(e1, e2, LITERAL_NULL); - } else { - return Arguments.of(e1, e2, e1); - } - }); + .map( + list -> { + ExprValue e1 = list.get(0); + ExprValue e2 = list.get(1); + if (e1.equals(e2)) { + return Arguments.of(e1, e2, LITERAL_NULL); + } else { + return Arguments.of(e1, e2, e1); + } + }); } @Test @@ -225,5 +229,4 @@ public void test_exprIfNull_predicate(ExprValue v1, ExprValue v2, ExprValue expe public void test_exprNullIf_predicate(ExprValue v1, ExprValue v2, ExprValue expected) { assertEquals(expected.value(), UnaryPredicateOperator.exprNullIf(v1, v2).value()); } - } diff --git a/core/src/test/java/org/opensearch/sql/expression/parse/GrokExpressionTest.java b/core/src/test/java/org/opensearch/sql/expression/parse/GrokExpressionTest.java index 28bd3467fd..fec851c1ed 100644 --- a/core/src/test/java/org/opensearch/sql/expression/parse/GrokExpressionTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/parse/GrokExpressionTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.parse; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -37,70 +36,100 @@ @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) class GrokExpressionTest extends ExpressionTestBase { - @Mock - Environment env; + @Mock Environment env; @Test public void resolve_grok_groups_and_parsed_values() { - when(DSL.ref("log_value", STRING).valueOf(env)).thenReturn(stringValue( - "145.128.75.121 - - [29/Aug/2022:13:26:44 -0700] \"GET /deliverables HTTP/2.0\" 501 2721")); + when(DSL.ref("log_value", STRING).valueOf(env)) + .thenReturn( + stringValue( + "145.128.75.121 - - [29/Aug/2022:13:26:44 -0700] \"GET /deliverables HTTP/2.0\" 501" + + " 2721")); String rawPattern = "%{COMMONAPACHELOG}"; - Map expected = ImmutableMap.builder() - .put("COMMONAPACHELOG", "145.128.75.121 - - [29/Aug/2022:13:26:44 -0700] " - + "\"GET /deliverables HTTP/2.0\" 501 2721") - .put("clientip", "145.128.75.121") - .put("ident", "-") - .put("auth", "-") - .put("timestamp", "29/Aug/2022:13:26:44 -0700") - .put("MONTHDAY", "29") - .put("MONTH", "Aug") - .put("YEAR", "2022") - .put("TIME", "13:26:44") - .put("HOUR", "13") - .put("MINUTE", "26") - .put("SECOND", "44") - .put("INT", "-0700") - .put("verb", "GET") - .put("request", "/deliverables") - .put("httpversion", "2.0") - .put("rawrequest", "") - .put("response", "501") - .put("bytes", "2721") - .build(); + Map expected = + ImmutableMap.builder() + .put( + "COMMONAPACHELOG", + "145.128.75.121 - - [29/Aug/2022:13:26:44 -0700] " + + "\"GET /deliverables HTTP/2.0\" 501 2721") + .put("clientip", "145.128.75.121") + .put("ident", "-") + .put("auth", "-") + .put("timestamp", "29/Aug/2022:13:26:44 -0700") + .put("MONTHDAY", "29") + .put("MONTH", "Aug") + .put("YEAR", "2022") + .put("TIME", "13:26:44") + .put("HOUR", "13") + .put("MINUTE", "26") + .put("SECOND", "44") + .put("INT", "-0700") + .put("verb", "GET") + .put("request", "/deliverables") + .put("httpversion", "2.0") + .put("rawrequest", "") + .put("response", "501") + .put("bytes", "2721") + .build(); List identifiers = new ArrayList<>(expected.keySet()); assertEquals(identifiers, GrokExpression.getNamedGroupCandidates(rawPattern)); - identifiers.forEach(identifier -> assertEquals(stringValue(expected.get(identifier)), - DSL.grok(DSL.ref("log_value", STRING), DSL.literal(rawPattern), DSL.literal(identifier)) - .valueOf(env))); + identifiers.forEach( + identifier -> + assertEquals( + stringValue(expected.get(identifier)), + DSL.grok( + DSL.ref("log_value", STRING), + DSL.literal(rawPattern), + DSL.literal(identifier)) + .valueOf(env))); } @Test public void resolve_null_and_empty_values() { - assertEquals(stringValue(""), - DSL.grok(DSL.ref("string_value", STRING), DSL.literal("%{COMMONAPACHELOG}"), - DSL.literal("request")).valueOf(valueEnv())); - assertEquals(LITERAL_NULL, - DSL.grok(DSL.ref(STRING_TYPE_NULL_VALUE_FIELD, STRING), - DSL.literal("%{COMMONAPACHELOG}"), DSL.literal("request")).valueOf(valueEnv())); - assertEquals(LITERAL_NULL, - DSL.grok(DSL.ref(STRING_TYPE_MISSING_VALUE_FIELD, STRING), - DSL.literal("p%{COMMONAPACHELOG}"), DSL.literal("request")).valueOf(valueEnv())); + assertEquals( + stringValue(""), + DSL.grok( + DSL.ref("string_value", STRING), + DSL.literal("%{COMMONAPACHELOG}"), + DSL.literal("request")) + .valueOf(valueEnv())); + assertEquals( + LITERAL_NULL, + DSL.grok( + DSL.ref(STRING_TYPE_NULL_VALUE_FIELD, STRING), + DSL.literal("%{COMMONAPACHELOG}"), + DSL.literal("request")) + .valueOf(valueEnv())); + assertEquals( + LITERAL_NULL, + DSL.grok( + DSL.ref(STRING_TYPE_MISSING_VALUE_FIELD, STRING), + DSL.literal("p%{COMMONAPACHELOG}"), + DSL.literal("request")) + .valueOf(valueEnv())); } @Test public void resolve_type() { - assertEquals(STRING, - DSL.grok(DSL.ref("string_value", STRING), DSL.literal("%{COMMONAPACHELOG}"), - DSL.literal("request")).type()); + assertEquals( + STRING, + DSL.grok( + DSL.ref("string_value", STRING), + DSL.literal("%{COMMONAPACHELOG}"), + DSL.literal("request")) + .type()); } @Test public void throws_semantic_exception_if_value_type_is_not_string() { assertThrows( SemanticCheckException.class, - () -> DSL.grok(DSL.ref("boolean_value", BOOLEAN), DSL.literal("%{COMMONAPACHELOG}"), - DSL.literal("request")) - .valueOf(valueEnv())); + () -> + DSL.grok( + DSL.ref("boolean_value", BOOLEAN), + DSL.literal("%{COMMONAPACHELOG}"), + DSL.literal("request")) + .valueOf(valueEnv())); } } diff --git a/core/src/test/java/org/opensearch/sql/expression/parse/PatternsExpressionTest.java b/core/src/test/java/org/opensearch/sql/expression/parse/PatternsExpressionTest.java index 1593e94a8a..7237f0673b 100644 --- a/core/src/test/java/org/opensearch/sql/expression/parse/PatternsExpressionTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/parse/PatternsExpressionTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.parse; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -33,46 +32,58 @@ @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) class PatternsExpressionTest extends ExpressionTestBase { - @Mock - Environment env; + @Mock Environment env; @Test public void resolve_value() { - when(DSL.ref("log_value", STRING).valueOf(env)).thenReturn(stringValue( - "145.128.75.121 - - [29/Aug/2022:13:26:44 -0700] \"GET /deliverables HTTP/2.0\" 501 2721")); - assertEquals(stringValue("... - - [//::: -] \" / /.\" "), - DSL.patterns(DSL.ref("log_value", STRING), DSL.literal(""), - DSL.literal("punct_field")).valueOf(env)); - assertEquals(stringValue("... - - [/Aug/::: -] \"GET /deliverables HTTP/.\" "), - DSL.patterns(DSL.ref("log_value", STRING), DSL.literal("[0-9]"), - DSL.literal("regex_field")).valueOf(env)); + when(DSL.ref("log_value", STRING).valueOf(env)) + .thenReturn( + stringValue( + "145.128.75.121 - - [29/Aug/2022:13:26:44 -0700] \"GET /deliverables HTTP/2.0\" 501" + + " 2721")); + assertEquals( + stringValue("... - - [//::: -] \" / /.\" "), + DSL.patterns(DSL.ref("log_value", STRING), DSL.literal(""), DSL.literal("punct_field")) + .valueOf(env)); + assertEquals( + stringValue("... - - [/Aug/::: -] \"GET /deliverables HTTP/.\" "), + DSL.patterns(DSL.ref("log_value", STRING), DSL.literal("[0-9]"), DSL.literal("regex_field")) + .valueOf(env)); } @Test public void resolve_null_and_missing_values() { - assertEquals(LITERAL_NULL, - DSL.patterns(DSL.ref(STRING_TYPE_NULL_VALUE_FIELD, STRING), - DSL.literal("pattern"), DSL.literal("patterns_field")).valueOf(valueEnv())); - assertEquals(LITERAL_NULL, - DSL.patterns(DSL.ref(STRING_TYPE_MISSING_VALUE_FIELD, STRING), - DSL.literal("pattern"), DSL.literal("patterns_field")).valueOf(valueEnv())); + assertEquals( + LITERAL_NULL, + DSL.patterns( + DSL.ref(STRING_TYPE_NULL_VALUE_FIELD, STRING), + DSL.literal("pattern"), + DSL.literal("patterns_field")) + .valueOf(valueEnv())); + assertEquals( + LITERAL_NULL, + DSL.patterns( + DSL.ref(STRING_TYPE_MISSING_VALUE_FIELD, STRING), + DSL.literal("pattern"), + DSL.literal("patterns_field")) + .valueOf(valueEnv())); } @Test public void resolve_type() { - assertEquals(STRING, - DSL.patterns(DSL.ref("string_value", STRING), - DSL.literal("pattern"), - DSL.literal("group")).type()); + assertEquals( + STRING, + DSL.patterns(DSL.ref("string_value", STRING), DSL.literal("pattern"), DSL.literal("group")) + .type()); } @Test public void throws_semantic_exception_if_value_type_is_not_string() { assertThrows( SemanticCheckException.class, - () -> DSL.patterns(DSL.ref("boolean_value", BOOLEAN), - DSL.literal("pattern"), - DSL.literal("group")) - .valueOf(valueEnv())); + () -> + DSL.patterns( + DSL.ref("boolean_value", BOOLEAN), DSL.literal("pattern"), DSL.literal("group")) + .valueOf(valueEnv())); } } diff --git a/core/src/test/java/org/opensearch/sql/expression/parse/RegexExpressionTest.java b/core/src/test/java/org/opensearch/sql/expression/parse/RegexExpressionTest.java index 95d836042e..846aff6911 100644 --- a/core/src/test/java/org/opensearch/sql/expression/parse/RegexExpressionTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/parse/RegexExpressionTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.parse; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -37,62 +36,97 @@ @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) class RegexExpressionTest extends ExpressionTestBase { - @Mock - Environment env; + @Mock Environment env; @Test public void resolve_regex_groups_and_parsed_values() { - when(DSL.ref("log_value", STRING).valueOf(env)).thenReturn(stringValue( - "130.246.123.197 - - [2018-07-22T03:26:21.326Z] \"GET /beats/metricbeat_1 HTTP/1.1\" " - + "200 6850 \"-\" \"Mozilla/5.0 (X11; Linux x86_64; rv:6.0a1) Gecko/20110421 " - + "Firefox/6.0a1\"")); + when(DSL.ref("log_value", STRING).valueOf(env)) + .thenReturn( + stringValue( + "130.246.123.197 - - [2018-07-22T03:26:21.326Z] \"GET /beats/metricbeat_1" + + " HTTP/1.1\" 200 6850 \"-\" \"Mozilla/5.0 (X11; Linux x86_64; rv:6.0a1)" + + " Gecko/20110421 Firefox/6.0a1\"")); String rawPattern = "(?(\\d{1,3}\\.){3}\\d{1,3}) - - \\[(?\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:" + "[0-5]\\d:[0-5]\\d\\.\\d+([+-][0-2]\\d:[0-5]\\d|Z))] \"(?[^\"]+)\" " + "(?\\d+) (?\\d+) \"-\" \"(?[^\"]+)\""; Map expected = - ImmutableMap.of("ip", "130.246.123.197", "date", "2018-07-22T03:26:21.326Z", "request", - "GET /beats/metricbeat_1 HTTP/1.1", "status", "200", "bytes", "6850", "userAgent", + ImmutableMap.of( + "ip", + "130.246.123.197", + "date", + "2018-07-22T03:26:21.326Z", + "request", + "GET /beats/metricbeat_1 HTTP/1.1", + "status", + "200", + "bytes", + "6850", + "userAgent", "Mozilla/5.0 (X11; Linux x86_64; rv:6.0a1) Gecko/20110421 Firefox/6.0a1"); List identifiers = new ArrayList<>(expected.keySet()); assertEquals(identifiers, RegexExpression.getNamedGroupCandidates(rawPattern)); - identifiers.forEach(identifier -> assertEquals(stringValue(expected.get(identifier)), - DSL.regex(DSL.ref("log_value", STRING), DSL.literal(rawPattern), DSL.literal(identifier)) - .valueOf(env))); + identifiers.forEach( + identifier -> + assertEquals( + stringValue(expected.get(identifier)), + DSL.regex( + DSL.ref("log_value", STRING), + DSL.literal(rawPattern), + DSL.literal(identifier)) + .valueOf(env))); } @Test public void resolve_not_parsable_inputs_as_empty_string() { - assertEquals(stringValue(""), - DSL.regex(DSL.ref("string_value", STRING), DSL.literal("(?not-matching)"), - DSL.literal("group")).valueOf(valueEnv())); + assertEquals( + stringValue(""), + DSL.regex( + DSL.ref("string_value", STRING), + DSL.literal("(?not-matching)"), + DSL.literal("group")) + .valueOf(valueEnv())); } @Test public void resolve_null_and_missing_values() { - assertEquals(LITERAL_NULL, - DSL.regex(DSL.ref(STRING_TYPE_NULL_VALUE_FIELD, STRING), - DSL.literal("(?\\w{2})\\w"), DSL.literal("group")).valueOf(valueEnv())); - assertEquals(LITERAL_NULL, - DSL.regex(DSL.ref(STRING_TYPE_MISSING_VALUE_FIELD, STRING), - DSL.literal("(?\\w{2})\\w"), DSL.literal("group")).valueOf(valueEnv())); + assertEquals( + LITERAL_NULL, + DSL.regex( + DSL.ref(STRING_TYPE_NULL_VALUE_FIELD, STRING), + DSL.literal("(?\\w{2})\\w"), + DSL.literal("group")) + .valueOf(valueEnv())); + assertEquals( + LITERAL_NULL, + DSL.regex( + DSL.ref(STRING_TYPE_MISSING_VALUE_FIELD, STRING), + DSL.literal("(?\\w{2})\\w"), + DSL.literal("group")) + .valueOf(valueEnv())); } @Test public void resolve_type() { - assertEquals(STRING, - DSL.regex(DSL.ref("string_value", STRING), DSL.literal("(?\\w{2})\\w"), - DSL.literal("group")).type()); + assertEquals( + STRING, + DSL.regex( + DSL.ref("string_value", STRING), + DSL.literal("(?\\w{2})\\w"), + DSL.literal("group")) + .type()); } @Test public void throws_semantic_exception_if_value_type_is_not_string() { assertThrows( SemanticCheckException.class, - () -> DSL.regex(DSL.ref("boolean_value", BOOLEAN), DSL.literal("(?\\w{2})\\w"), - DSL.literal("group")) - .valueOf(valueEnv())); + () -> + DSL.regex( + DSL.ref("boolean_value", BOOLEAN), + DSL.literal("(?\\w{2})\\w"), + DSL.literal("group")) + .valueOf(valueEnv())); } - } diff --git a/core/src/test/java/org/opensearch/sql/expression/system/SystemFunctionsTest.java b/core/src/test/java/org/opensearch/sql/expression/system/SystemFunctionsTest.java index 62d219e576..ac4153f59f 100644 --- a/core/src/test/java/org/opensearch/sql/expression/system/SystemFunctionsTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/system/SystemFunctionsTest.java @@ -62,27 +62,30 @@ void typeof() { assertEquals("TIMESTAMP", typeofGetValue(new ExprTimestampValue(Instant.now()))); assertEquals("UNDEFINED", typeofGetValue(ExprNullValue.of())); assertEquals("UNDEFINED", typeofGetValue(ExprMissingValue.of())); - assertEquals("UNKNOWN", typeofGetValue(new AbstractExprValue() { - @Override - public int compare(ExprValue other) { - return 0; - } + assertEquals( + "UNKNOWN", + typeofGetValue( + new AbstractExprValue() { + @Override + public int compare(ExprValue other) { + return 0; + } - @Override - public boolean equal(ExprValue other) { - return false; - } + @Override + public boolean equal(ExprValue other) { + return false; + } - @Override - public Object value() { - return null; - } + @Override + public Object value() { + return null; + } - @Override - public ExprType type() { - return ExprCoreType.UNKNOWN; - } - })); + @Override + public ExprType type() { + return ExprCoreType.UNKNOWN; + } + })); } private String typeofGetValue(ExprValue input) { diff --git a/core/src/test/java/org/opensearch/sql/expression/text/TextFunctionTest.java b/core/src/test/java/org/opensearch/sql/expression/text/TextFunctionTest.java index 54d2e5c400..84ae0b844f 100644 --- a/core/src/test/java/org/opensearch/sql/expression/text/TextFunctionTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/text/TextFunctionTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.text; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -36,45 +35,44 @@ @ExtendWith(MockitoExtension.class) public class TextFunctionTest extends ExpressionTestBase { - @Mock - Environment env; - - @Mock - Expression nullRef; - - @Mock - Expression missingRef; - - - private static List SUBSTRING_STRINGS = ImmutableList.of( - new SubstringInfo("", 1, 1, ""), - new SubstringInfo("Quadratically", 5, null, "ratically"), - new SubstringInfo("foobarbar", 4, null, "barbar"), - new SubstringInfo("Quadratically", 5, 6, "ratica"), - new SubstringInfo("Quadratically", 5, 600, "ratically"), - new SubstringInfo("Quadratically", 500, 1, ""), - new SubstringInfo("Quadratically", 500, null, ""), - new SubstringInfo("Sakila", -3, null, "ila"), - new SubstringInfo("Sakila", -5, 3, "aki"), - new SubstringInfo("Sakila", -4, 2, "ki"), - new SubstringInfo("Quadratically", 0, null, ""), - new SubstringInfo("Sakila", 0, 2, ""), - new SubstringInfo("Sakila", 2, 0, ""), - new SubstringInfo("Sakila", 0, 0, "")); - private static List UPPER_LOWER_STRINGS = ImmutableList.of( - "test", " test", "test ", " test ", "TesT", "TEST", " TEST", "TEST ", " TEST ", " ", ""); - private static List STRING_PATTERN_PAIRS = ImmutableList.of( - new StringPatternPair("Michael!", "Michael!"), - new StringPatternPair("hello", "world"), - new StringPatternPair("world", "hello")); - private static List TRIM_STRINGS = ImmutableList.of( - " test", " test", "test ", "test", " test ", "", " "); - private static List> CONCAT_STRING_LISTS = ImmutableList.of( - ImmutableList.of("hello", "world"), - ImmutableList.of("123", "5325")); - private static List> CONCAT_STRING_LISTS_WITH_MANY_STRINGS = ImmutableList.of( - ImmutableList.of("he", "llo", "wo", "rld", "!"), - ImmutableList.of("0", "123", "53", "25", "7")); + @Mock Environment env; + + @Mock Expression nullRef; + + @Mock Expression missingRef; + + private static List SUBSTRING_STRINGS = + ImmutableList.of( + new SubstringInfo("", 1, 1, ""), + new SubstringInfo("Quadratically", 5, null, "ratically"), + new SubstringInfo("foobarbar", 4, null, "barbar"), + new SubstringInfo("Quadratically", 5, 6, "ratica"), + new SubstringInfo("Quadratically", 5, 600, "ratically"), + new SubstringInfo("Quadratically", 500, 1, ""), + new SubstringInfo("Quadratically", 500, null, ""), + new SubstringInfo("Sakila", -3, null, "ila"), + new SubstringInfo("Sakila", -5, 3, "aki"), + new SubstringInfo("Sakila", -4, 2, "ki"), + new SubstringInfo("Quadratically", 0, null, ""), + new SubstringInfo("Sakila", 0, 2, ""), + new SubstringInfo("Sakila", 2, 0, ""), + new SubstringInfo("Sakila", 0, 0, "")); + private static List UPPER_LOWER_STRINGS = + ImmutableList.of( + "test", " test", "test ", " test ", "TesT", "TEST", " TEST", "TEST ", " TEST ", " ", ""); + private static List STRING_PATTERN_PAIRS = + ImmutableList.of( + new StringPatternPair("Michael!", "Michael!"), + new StringPatternPair("hello", "world"), + new StringPatternPair("world", "hello")); + private static List TRIM_STRINGS = + ImmutableList.of(" test", " test", "test ", "test", " test ", "", " "); + private static List> CONCAT_STRING_LISTS = + ImmutableList.of(ImmutableList.of("hello", "world"), ImmutableList.of("123", "5325")); + private static List> CONCAT_STRING_LISTS_WITH_MANY_STRINGS = + ImmutableList.of( + ImmutableList.of("he", "llo", "wo", "rld", "!"), + ImmutableList.of("0", "123", "53", "25", "7")); interface SubstrSubstring { FunctionExpression getFunction(SubstringInfo strInfo); @@ -86,9 +84,11 @@ public FunctionExpression getFunction(SubstringInfo strInfo) { if (strInfo.getLen() == null) { expr = DSL.substr(DSL.literal(strInfo.getExpr()), DSL.literal(strInfo.getStart())); } else { - expr = DSL.substr(DSL.literal(strInfo.getExpr()), - DSL.literal(strInfo.getStart()), - DSL.literal(strInfo.getLen())); + expr = + DSL.substr( + DSL.literal(strInfo.getExpr()), + DSL.literal(strInfo.getStart()), + DSL.literal(strInfo.getLen())); } return expr; } @@ -100,9 +100,11 @@ public FunctionExpression getFunction(SubstringInfo strInfo) { if (strInfo.getLen() == null) { expr = DSL.substring(DSL.literal(strInfo.getExpr()), DSL.literal(strInfo.getStart())); } else { - expr = DSL.substring(DSL.literal(strInfo.getExpr()), - DSL.literal(strInfo.getStart()), - DSL.literal(strInfo.getLen())); + expr = + DSL.substring( + DSL.literal(strInfo.getExpr()), + DSL.literal(strInfo.getStart()), + DSL.literal(strInfo.getLen())); } return expr; } @@ -235,15 +237,11 @@ void concat() { when(nullRef.type()).thenReturn(STRING); when(missingRef.type()).thenReturn(STRING); - assertEquals(missingValue(), eval( - DSL.concat(missingRef, DSL.literal("1")))); + assertEquals(missingValue(), eval(DSL.concat(missingRef, DSL.literal("1")))); // If any of the expressions is a NULL value, it returns NULL. - assertEquals(nullValue(), eval( - DSL.concat(nullRef, DSL.literal("1")))); - assertEquals(missingValue(), eval( - DSL.concat(DSL.literal("1"), missingRef))); - assertEquals(nullValue(), eval( - DSL.concat(DSL.literal("1"), nullRef))); + assertEquals(nullValue(), eval(DSL.concat(nullRef, DSL.literal("1")))); + assertEquals(missingValue(), eval(DSL.concat(DSL.literal("1"), missingRef))); + assertEquals(nullValue(), eval(DSL.concat(DSL.literal("1"), nullRef))); } @Test @@ -252,18 +250,15 @@ void concat_ws() { when(nullRef.type()).thenReturn(STRING); when(missingRef.type()).thenReturn(STRING); - assertEquals(missingValue(), eval( - DSL.concat_ws(missingRef, DSL.literal("1"), DSL.literal("1")))); - assertEquals(nullValue(), eval( - DSL.concat_ws(nullRef, DSL.literal("1"), DSL.literal("1")))); - assertEquals(missingValue(), eval( - DSL.concat_ws(DSL.literal("1"), missingRef, DSL.literal("1")))); - assertEquals(nullValue(), eval( - DSL.concat_ws(DSL.literal("1"), nullRef, DSL.literal("1")))); - assertEquals(missingValue(), eval( - DSL.concat_ws(DSL.literal("1"), DSL.literal("1"), missingRef))); - assertEquals(nullValue(), eval( - DSL.concat_ws(DSL.literal("1"), DSL.literal("1"), nullRef))); + assertEquals( + missingValue(), eval(DSL.concat_ws(missingRef, DSL.literal("1"), DSL.literal("1")))); + assertEquals(nullValue(), eval(DSL.concat_ws(nullRef, DSL.literal("1"), DSL.literal("1")))); + assertEquals( + missingValue(), eval(DSL.concat_ws(DSL.literal("1"), missingRef, DSL.literal("1")))); + assertEquals(nullValue(), eval(DSL.concat_ws(DSL.literal("1"), nullRef, DSL.literal("1")))); + assertEquals( + missingValue(), eval(DSL.concat_ws(DSL.literal("1"), DSL.literal("1"), missingRef))); + assertEquals(nullValue(), eval(DSL.concat_ws(DSL.literal("1"), DSL.literal("1"), nullRef))); } @Test @@ -290,9 +285,9 @@ void strcmp() { @Test void right() { - FunctionExpression expression = DSL.right( - DSL.literal(new ExprStringValue("foobarbar")), - DSL.literal(new ExprIntegerValue(4))); + FunctionExpression expression = + DSL.right( + DSL.literal(new ExprStringValue("foobarbar")), DSL.literal(new ExprIntegerValue(4))); assertEquals(STRING, expression.type()); assertEquals("rbar", eval(expression).stringValue()); @@ -319,9 +314,9 @@ void right() { @Test void left() { - FunctionExpression expression = DSL.left( - DSL.literal(new ExprStringValue("helloworld")), - DSL.literal(new ExprIntegerValue(5))); + FunctionExpression expression = + DSL.left( + DSL.literal(new ExprStringValue("helloworld")), DSL.literal(new ExprIntegerValue(5))); assertEquals(STRING, expression.type()); assertEquals("hello", eval(expression).stringValue()); @@ -360,16 +355,11 @@ void ascii() { @Test void locate() { - FunctionExpression expression = DSL.locate( - DSL.literal("world"), - DSL.literal("helloworld")); + FunctionExpression expression = DSL.locate(DSL.literal("world"), DSL.literal("helloworld")); assertEquals(INTEGER, expression.type()); assertEquals(6, eval(expression).integerValue()); - expression = DSL.locate( - DSL.literal("world"), - DSL.literal("helloworldworld"), - DSL.literal(7)); + expression = DSL.locate(DSL.literal("world"), DSL.literal("helloworldworld"), DSL.literal(7)); assertEquals(INTEGER, expression.type()); assertEquals(11, eval(expression).integerValue()); @@ -378,21 +368,18 @@ void locate() { assertEquals(nullValue(), eval(DSL.locate(nullRef, DSL.literal("hello"), DSL.literal(1)))); when(missingRef.type()).thenReturn(STRING); assertEquals(missingValue(), eval(DSL.locate(missingRef, DSL.literal("hello")))); - assertEquals(missingValue(), eval( - DSL.locate(missingRef, DSL.literal("hello"), DSL.literal(1)))); + assertEquals( + missingValue(), eval(DSL.locate(missingRef, DSL.literal("hello"), DSL.literal(1)))); } @Test void position() { - FunctionExpression expression = DSL.position( - DSL.literal("world"), - DSL.literal("helloworldworld")); + FunctionExpression expression = + DSL.position(DSL.literal("world"), DSL.literal("helloworldworld")); assertEquals(INTEGER, expression.type()); assertEquals(6, eval(expression).integerValue()); - expression = DSL.position( - DSL.literal("abc"), - DSL.literal("hello world")); + expression = DSL.position(DSL.literal("abc"), DSL.literal("hello world")); assertEquals(INTEGER, expression.type()); assertEquals(0, eval(expression).integerValue()); @@ -404,10 +391,8 @@ void position() { @Test void replace() { - FunctionExpression expression = DSL.replace( - DSL.literal("helloworld"), - DSL.literal("world"), - DSL.literal("opensearch")); + FunctionExpression expression = + DSL.replace(DSL.literal("helloworld"), DSL.literal("world"), DSL.literal("opensearch")); assertEquals(STRING, expression.type()); assertEquals("helloopensearch", eval(expression).stringValue()); @@ -435,18 +420,17 @@ void testConcatString(List strings) { expected = String.join("", strings); } - FunctionExpression expression = DSL.concat( - DSL.literal(strings.get(0)), DSL.literal(strings.get(1))); + FunctionExpression expression = + DSL.concat(DSL.literal(strings.get(0)), DSL.literal(strings.get(1))); assertEquals(STRING, expression.type()); assertEquals(expected, eval(expression).stringValue()); } void testConcatString(List strings, String delim) { - String expected = strings.stream() - .filter(Objects::nonNull).collect(Collectors.joining(",")); + String expected = strings.stream().filter(Objects::nonNull).collect(Collectors.joining(",")); - FunctionExpression expression = DSL.concat_ws( - DSL.literal(delim), DSL.literal(strings.get(0)), DSL.literal(strings.get(1))); + FunctionExpression expression = + DSL.concat_ws(DSL.literal(delim), DSL.literal(strings.get(0)), DSL.literal(strings.get(1))); assertEquals(STRING, expression.type()); assertEquals(expected, eval(expression).stringValue()); } @@ -457,7 +441,8 @@ void testConcatMultipleString(List strings) { expected = String.join("", strings); } - FunctionExpression expression = DSL.concat( + FunctionExpression expression = + DSL.concat( DSL.literal(strings.get(0)), DSL.literal(strings.get(1)), DSL.literal(strings.get(2)), @@ -474,7 +459,8 @@ void testLengthString(String str) { } void testStcmpString(StringPatternPair stringPatternPair) { - FunctionExpression expression = DSL.strcmp( + FunctionExpression expression = + DSL.strcmp( DSL.literal(new ExprStringValue(stringPatternPair.getStr())), DSL.literal(new ExprStringValue(stringPatternPair.getPatt()))); assertEquals(INTEGER, expression.type()); diff --git a/core/src/test/java/org/opensearch/sql/expression/window/CurrentRowWindowFrameTest.java b/core/src/test/java/org/opensearch/sql/expression/window/CurrentRowWindowFrameTest.java index f2e54f9654..3964f36fb7 100644 --- a/core/src/test/java/org/opensearch/sql/expression/window/CurrentRowWindowFrameTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/window/CurrentRowWindowFrameTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.window; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -29,10 +28,11 @@ class CurrentRowWindowFrameTest { - private final CurrentRowWindowFrame windowFrame = new CurrentRowWindowFrame( - new WindowDefinition( - ImmutableList.of(DSL.ref("state", STRING)), - ImmutableList.of(ImmutablePair.of(DEFAULT_ASC, DSL.ref("age", INTEGER))))); + private final CurrentRowWindowFrame windowFrame = + new CurrentRowWindowFrame( + new WindowDefinition( + ImmutableList.of(DSL.ref("state", STRING)), + ImmutableList.of(ImmutablePair.of(DEFAULT_ASC, DSL.ref("age", INTEGER))))); @Test void test_iterator_methods() { @@ -42,17 +42,21 @@ void test_iterator_methods() { @Test void should_return_new_partition_if_partition_by_field_value_changed() { - PeekingIterator iterator = Iterators.peekingIterator( - Iterators.forArray( - ExprTupleValue.fromExprValueMap(ImmutableMap.of( - "state", new ExprStringValue("WA"), - "age", new ExprIntegerValue(20))), - ExprTupleValue.fromExprValueMap(ImmutableMap.of( - "state", new ExprStringValue("WA"), - "age", new ExprIntegerValue(30))), - ExprTupleValue.fromExprValueMap(ImmutableMap.of( - "state", new ExprStringValue("CA"), - "age", new ExprIntegerValue(18))))); + PeekingIterator iterator = + Iterators.peekingIterator( + Iterators.forArray( + ExprTupleValue.fromExprValueMap( + ImmutableMap.of( + "state", new ExprStringValue("WA"), + "age", new ExprIntegerValue(20))), + ExprTupleValue.fromExprValueMap( + ImmutableMap.of( + "state", new ExprStringValue("WA"), + "age", new ExprIntegerValue(30))), + ExprTupleValue.fromExprValueMap( + ImmutableMap.of( + "state", new ExprStringValue("CA"), + "age", new ExprIntegerValue(18))))); windowFrame.load(iterator); assertTrue(windowFrame.isNewPartition()); @@ -66,24 +70,28 @@ void should_return_new_partition_if_partition_by_field_value_changed() { @Test void can_resolve_single_expression_value() { - windowFrame.load(Iterators.peekingIterator( - Iterators.singletonIterator( - ExprTupleValue.fromExprValueMap(ImmutableMap.of( - "state", new ExprStringValue("WA"), - "age", new ExprIntegerValue(20)))))); - assertEquals( - new ExprIntegerValue(20), - windowFrame.resolve(DSL.ref("age", INTEGER))); + windowFrame.load( + Iterators.peekingIterator( + Iterators.singletonIterator( + ExprTupleValue.fromExprValueMap( + ImmutableMap.of( + "state", new ExprStringValue("WA"), + "age", new ExprIntegerValue(20)))))); + assertEquals(new ExprIntegerValue(20), windowFrame.resolve(DSL.ref("age", INTEGER))); } @Test void can_return_previous_and_current_row() { - ExprValue row1 = ExprTupleValue.fromExprValueMap(ImmutableMap.of( - "state", new ExprStringValue("WA"), - "age", new ExprIntegerValue(20))); - ExprValue row2 = ExprTupleValue.fromExprValueMap(ImmutableMap.of( - "state", new ExprStringValue("WA"), - "age", new ExprIntegerValue(30))); + ExprValue row1 = + ExprTupleValue.fromExprValueMap( + ImmutableMap.of( + "state", new ExprStringValue("WA"), + "age", new ExprIntegerValue(20))); + ExprValue row2 = + ExprTupleValue.fromExprValueMap( + ImmutableMap.of( + "state", new ExprStringValue("WA"), + "age", new ExprIntegerValue(30))); PeekingIterator iterator = Iterators.peekingIterator(Iterators.forArray(row1, row2)); windowFrame.load(iterator); @@ -94,5 +102,4 @@ void can_return_previous_and_current_row() { assertEquals(row1, windowFrame.previous()); assertEquals(row2, windowFrame.current()); } - } diff --git a/core/src/test/java/org/opensearch/sql/expression/window/aggregation/AggregateWindowFunctionTest.java b/core/src/test/java/org/opensearch/sql/expression/window/aggregation/AggregateWindowFunctionTest.java index d7062d4e47..b728a413ba 100644 --- a/core/src/test/java/org/opensearch/sql/expression/window/aggregation/AggregateWindowFunctionTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/window/aggregation/AggregateWindowFunctionTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.window.aggregation; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -27,9 +26,7 @@ import org.opensearch.sql.expression.aggregation.Aggregator; import org.opensearch.sql.expression.window.frame.PeerRowsWindowFrame; -/** - * Aggregate window function test collection. - */ +/** Aggregate window function test collection. */ @SuppressWarnings("unchecked") @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) @ExtendWith(MockitoExtension.class) @@ -56,15 +53,17 @@ void should_accumulate_all_peer_values_and_not_reset_state_if_same_partition() { new AggregateWindowFunction(DSL.sum(DSL.ref("age", INTEGER))); when(windowFrame.isNewPartition()).thenReturn(true); - when(windowFrame.next()).thenReturn(ImmutableList.of( - fromExprValueMap(ImmutableMap.of("age", new ExprIntegerValue(10))), - fromExprValueMap(ImmutableMap.of("age", new ExprIntegerValue(20))))); + when(windowFrame.next()) + .thenReturn( + ImmutableList.of( + fromExprValueMap(ImmutableMap.of("age", new ExprIntegerValue(10))), + fromExprValueMap(ImmutableMap.of("age", new ExprIntegerValue(20))))); assertEquals(new ExprIntegerValue(30), windowFunction.valueOf(windowFrame)); when(windowFrame.isNewPartition()).thenReturn(false); - when(windowFrame.next()).thenReturn(ImmutableList.of( - fromExprValueMap(ImmutableMap.of("age", new ExprIntegerValue(30))))); + when(windowFrame.next()) + .thenReturn( + ImmutableList.of(fromExprValueMap(ImmutableMap.of("age", new ExprIntegerValue(30))))); assertEquals(new ExprIntegerValue(60), windowFunction.valueOf(windowFrame)); } - } diff --git a/core/src/test/java/org/opensearch/sql/expression/window/frame/PeerRowsWindowFrameTest.java b/core/src/test/java/org/opensearch/sql/expression/window/frame/PeerRowsWindowFrameTest.java index 26f6bb2f5e..1da2e50322 100644 --- a/core/src/test/java/org/opensearch/sql/expression/window/frame/PeerRowsWindowFrameTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/window/frame/PeerRowsWindowFrameTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.window.frame; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -34,15 +33,16 @@ @ExtendWith(MockitoExtension.class) class PeerRowsWindowFrameTest { - private final PeerRowsWindowFrame windowFrame = new PeerRowsWindowFrame( - new WindowDefinition( - ImmutableList.of(DSL.ref("state", STRING)), - ImmutableList.of(Pair.of(DEFAULT_ASC, DSL.ref("age", INTEGER))))); + private final PeerRowsWindowFrame windowFrame = + new PeerRowsWindowFrame( + new WindowDefinition( + ImmutableList.of(DSL.ref("state", STRING)), + ImmutableList.of(Pair.of(DEFAULT_ASC, DSL.ref("age", INTEGER))))); @Test void test_single_row() { - PeekingIterator tuples = Iterators.peekingIterator( - Iterators.singletonIterator(tuple("WA", 10, 100))); + PeekingIterator tuples = + Iterators.peekingIterator(Iterators.singletonIterator(tuple("WA", 10, 100))); windowFrame.load(tuples); assertTrue(windowFrame.isNewPartition()); assertEquals(ImmutableList.of(tuple("WA", 10, 100)), windowFrame.next()); @@ -50,11 +50,9 @@ void test_single_row() { @Test void test_single_partition_with_no_more_rows_after_peers() { - PeekingIterator tuples = Iterators.peekingIterator( - Iterators.forArray( - tuple("WA", 10, 100), - tuple("WA", 20, 200), - tuple("WA", 20, 50))); + PeekingIterator tuples = + Iterators.peekingIterator( + Iterators.forArray(tuple("WA", 10, 100), tuple("WA", 20, 200), tuple("WA", 20, 50))); // Here we simulate how WindowFrame interacts with WindowOperator which calls load() // and WindowFunction which calls isNewPartition() and move() @@ -64,9 +62,7 @@ void test_single_partition_with_no_more_rows_after_peers() { windowFrame.load(tuples); assertFalse(windowFrame.isNewPartition()); - assertEquals( - ImmutableList.of(tuple("WA", 20, 200), tuple("WA", 20, 50)), - windowFrame.next()); + assertEquals(ImmutableList.of(tuple("WA", 20, 200), tuple("WA", 20, 50)), windowFrame.next()); windowFrame.load(tuples); assertFalse(windowFrame.isNewPartition()); @@ -75,180 +71,124 @@ void test_single_partition_with_no_more_rows_after_peers() { @Test void test_single_partition_with_more_rows_after_peers() { - PeekingIterator tuples = Iterators.peekingIterator( - Iterators.forArray( - tuple("WA", 10, 100), - tuple("WA", 20, 200), - tuple("WA", 20, 50), - tuple("WA", 35, 150))); + PeekingIterator tuples = + Iterators.peekingIterator( + Iterators.forArray( + tuple("WA", 10, 100), + tuple("WA", 20, 200), + tuple("WA", 20, 50), + tuple("WA", 35, 150))); windowFrame.load(tuples); assertTrue(windowFrame.isNewPartition()); - assertEquals( - ImmutableList.of( - tuple("WA", 10, 100)), - windowFrame.next()); + assertEquals(ImmutableList.of(tuple("WA", 10, 100)), windowFrame.next()); windowFrame.load(tuples); assertFalse(windowFrame.isNewPartition()); - assertEquals( - ImmutableList.of( - tuple("WA", 20, 200), - tuple("WA", 20, 50)), - windowFrame.next()); + assertEquals(ImmutableList.of(tuple("WA", 20, 200), tuple("WA", 20, 50)), windowFrame.next()); windowFrame.load(tuples); assertFalse(windowFrame.isNewPartition()); - assertEquals( - ImmutableList.of(), - windowFrame.next()); + assertEquals(ImmutableList.of(), windowFrame.next()); windowFrame.load(tuples); assertFalse(windowFrame.isNewPartition()); - assertEquals( - ImmutableList.of( - tuple("WA", 35, 150)), - windowFrame.next()); + assertEquals(ImmutableList.of(tuple("WA", 35, 150)), windowFrame.next()); } @Test void test_two_partitions_with_all_same_peers_in_second_partition() { - PeekingIterator tuples = Iterators.peekingIterator( - Iterators.forArray( - tuple("WA", 10, 100), - tuple("CA", 18, 150), - tuple("CA", 18, 100))); + PeekingIterator tuples = + Iterators.peekingIterator( + Iterators.forArray(tuple("WA", 10, 100), tuple("CA", 18, 150), tuple("CA", 18, 100))); windowFrame.load(tuples); assertTrue(windowFrame.isNewPartition()); - assertEquals( - ImmutableList.of( - tuple("WA", 10, 100)), - windowFrame.next()); + assertEquals(ImmutableList.of(tuple("WA", 10, 100)), windowFrame.next()); windowFrame.load(tuples); assertTrue(windowFrame.isNewPartition()); - assertEquals( - ImmutableList.of( - tuple("CA", 18, 150), - tuple("CA", 18, 100)), - windowFrame.next()); + assertEquals(ImmutableList.of(tuple("CA", 18, 150), tuple("CA", 18, 100)), windowFrame.next()); windowFrame.load(tuples); assertFalse(windowFrame.isNewPartition()); - assertEquals( - ImmutableList.of(), - windowFrame.next()); + assertEquals(ImmutableList.of(), windowFrame.next()); } @Test void test_two_partitions_with_single_row_in_each_partition() { - PeekingIterator tuples = Iterators.peekingIterator( - Iterators.forArray( - tuple("WA", 10, 100), - tuple("CA", 30, 200))); + PeekingIterator tuples = + Iterators.peekingIterator(Iterators.forArray(tuple("WA", 10, 100), tuple("CA", 30, 200))); windowFrame.load(tuples); assertTrue(windowFrame.isNewPartition()); - assertEquals( - ImmutableList.of( - tuple("WA", 10, 100)), - windowFrame.next()); + assertEquals(ImmutableList.of(tuple("WA", 10, 100)), windowFrame.next()); windowFrame.load(tuples); assertTrue(windowFrame.isNewPartition()); - assertEquals( - ImmutableList.of( - tuple("CA", 30, 200)), - windowFrame.next()); + assertEquals(ImmutableList.of(tuple("CA", 30, 200)), windowFrame.next()); } @Test void test_window_definition_with_no_partition_by() { - PeerRowsWindowFrame windowFrame = new PeerRowsWindowFrame( - new WindowDefinition( - ImmutableList.of(), - ImmutableList.of(Pair.of(DEFAULT_ASC, DSL.ref("age", INTEGER))))); + PeerRowsWindowFrame windowFrame = + new PeerRowsWindowFrame( + new WindowDefinition( + ImmutableList.of(), + ImmutableList.of(Pair.of(DEFAULT_ASC, DSL.ref("age", INTEGER))))); - PeekingIterator tuples = Iterators.peekingIterator( - Iterators.forArray( - tuple("WA", 10, 100), - tuple("CA", 30, 200))); + PeekingIterator tuples = + Iterators.peekingIterator(Iterators.forArray(tuple("WA", 10, 100), tuple("CA", 30, 200))); windowFrame.load(tuples); assertTrue(windowFrame.isNewPartition()); - assertEquals( - ImmutableList.of( - tuple("WA", 10, 100)), - windowFrame.next()); + assertEquals(ImmutableList.of(tuple("WA", 10, 100)), windowFrame.next()); windowFrame.load(tuples); assertFalse(windowFrame.isNewPartition()); - assertEquals( - ImmutableList.of( - tuple("CA", 30, 200)), - windowFrame.next()); + assertEquals(ImmutableList.of(tuple("CA", 30, 200)), windowFrame.next()); } @Test void test_window_definition_with_no_order_by() { - PeerRowsWindowFrame windowFrame = new PeerRowsWindowFrame( - new WindowDefinition( - ImmutableList.of(DSL.ref("state", STRING)), - ImmutableList.of())); + PeerRowsWindowFrame windowFrame = + new PeerRowsWindowFrame( + new WindowDefinition(ImmutableList.of(DSL.ref("state", STRING)), ImmutableList.of())); - PeekingIterator tuples = Iterators.peekingIterator( - Iterators.forArray( - tuple("WA", 10, 100), - tuple("CA", 30, 200))); + PeekingIterator tuples = + Iterators.peekingIterator(Iterators.forArray(tuple("WA", 10, 100), tuple("CA", 30, 200))); windowFrame.load(tuples); assertTrue(windowFrame.isNewPartition()); - assertEquals( - ImmutableList.of( - tuple("WA", 10, 100)), - windowFrame.next()); + assertEquals(ImmutableList.of(tuple("WA", 10, 100)), windowFrame.next()); windowFrame.load(tuples); assertTrue(windowFrame.isNewPartition()); - assertEquals( - ImmutableList.of( - tuple("CA", 30, 200)), - windowFrame.next()); + assertEquals(ImmutableList.of(tuple("CA", 30, 200)), windowFrame.next()); } @Test void test_window_definition_with_no_partition_by_and_order_by() { - PeerRowsWindowFrame windowFrame = new PeerRowsWindowFrame( - new WindowDefinition( - ImmutableList.of(), - ImmutableList.of())); + PeerRowsWindowFrame windowFrame = + new PeerRowsWindowFrame(new WindowDefinition(ImmutableList.of(), ImmutableList.of())); - PeekingIterator tuples = Iterators.peekingIterator( - Iterators.forArray( - tuple("WA", 10, 100), - tuple("CA", 30, 200))); + PeekingIterator tuples = + Iterators.peekingIterator(Iterators.forArray(tuple("WA", 10, 100), tuple("CA", 30, 200))); windowFrame.load(tuples); assertTrue(windowFrame.isNewPartition()); - assertEquals( - ImmutableList.of( - tuple("WA", 10, 100), - tuple("CA", 30, 200)), - windowFrame.next()); + assertEquals(ImmutableList.of(tuple("WA", 10, 100), tuple("CA", 30, 200)), windowFrame.next()); windowFrame.load(tuples); assertFalse(windowFrame.isNewPartition()); - assertEquals( - ImmutableList.of(), - windowFrame.next()); + assertEquals(ImmutableList.of(), windowFrame.next()); } private ExprValue tuple(String state, int age, int balance) { - return fromExprValueMap(ImmutableMap.of( - "state", new ExprStringValue(state), - "age", new ExprIntegerValue(age), - "balance", new ExprIntegerValue(balance))); + return fromExprValueMap( + ImmutableMap.of( + "state", new ExprStringValue(state), + "age", new ExprIntegerValue(age), + "balance", new ExprIntegerValue(balance))); } - } diff --git a/core/src/test/java/org/opensearch/sql/expression/window/ranking/RankingWindowFunctionTest.java b/core/src/test/java/org/opensearch/sql/expression/window/ranking/RankingWindowFunctionTest.java index 7b2b5a42f2..dc2f8fd147 100644 --- a/core/src/test/java/org/opensearch/sql/expression/window/ranking/RankingWindowFunctionTest.java +++ b/core/src/test/java/org/opensearch/sql/expression/window/ranking/RankingWindowFunctionTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.expression.window.ranking; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -31,57 +30,72 @@ import org.opensearch.sql.expression.window.WindowDefinition; import org.opensearch.sql.expression.window.frame.CurrentRowWindowFrame; -/** - * Rank window function test collection. - */ +/** Rank window function test collection. */ @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) @ExtendWith(MockitoExtension.class) class RankingWindowFunctionTest extends ExpressionTestBase { - private final CurrentRowWindowFrame windowFrame1 = new CurrentRowWindowFrame( - new WindowDefinition( - ImmutableList.of(DSL.ref("state", STRING)), - ImmutableList.of(Pair.of(DEFAULT_ASC, DSL.ref("age", INTEGER))))); + private final CurrentRowWindowFrame windowFrame1 = + new CurrentRowWindowFrame( + new WindowDefinition( + ImmutableList.of(DSL.ref("state", STRING)), + ImmutableList.of(Pair.of(DEFAULT_ASC, DSL.ref("age", INTEGER))))); - private final CurrentRowWindowFrame windowFrame2 = new CurrentRowWindowFrame( - new WindowDefinition( - ImmutableList.of(DSL.ref("state", STRING)), - ImmutableList.of())); // No sort items defined + private final CurrentRowWindowFrame windowFrame2 = + new CurrentRowWindowFrame( + new WindowDefinition( + ImmutableList.of(DSL.ref("state", STRING)), + ImmutableList.of())); // No sort items defined private PeekingIterator iterator1; private PeekingIterator iterator2; @BeforeEach void set_up() { - iterator1 = Iterators.peekingIterator(Iterators.forArray( - fromExprValueMap(ImmutableMap.of( - "state", new ExprStringValue("WA"), "age", new ExprIntegerValue(30))), - fromExprValueMap(ImmutableMap.of( - "state", new ExprStringValue("WA"), "age", new ExprIntegerValue(30))), - fromExprValueMap(ImmutableMap.of( - "state", new ExprStringValue("WA"), "age", new ExprIntegerValue(40))), - fromExprValueMap(ImmutableMap.of( - "state", new ExprStringValue("CA"), "age", new ExprIntegerValue(20))))); - - iterator2 = Iterators.peekingIterator(Iterators.forArray( - fromExprValueMap(ImmutableMap.of( - "state", new ExprStringValue("WA"), "age", new ExprIntegerValue(30))), - fromExprValueMap(ImmutableMap.of( - "state", new ExprStringValue("WA"), "age", new ExprIntegerValue(30))), - fromExprValueMap(ImmutableMap.of( - "state", new ExprStringValue("WA"), "age", new ExprIntegerValue(50))), - fromExprValueMap(ImmutableMap.of( - "state", new ExprStringValue("WA"), "age", new ExprIntegerValue(55))), - fromExprValueMap(ImmutableMap.of( - "state", new ExprStringValue("CA"), "age", new ExprIntegerValue(15))))); + iterator1 = + Iterators.peekingIterator( + Iterators.forArray( + fromExprValueMap( + ImmutableMap.of( + "state", new ExprStringValue("WA"), "age", new ExprIntegerValue(30))), + fromExprValueMap( + ImmutableMap.of( + "state", new ExprStringValue("WA"), "age", new ExprIntegerValue(30))), + fromExprValueMap( + ImmutableMap.of( + "state", new ExprStringValue("WA"), "age", new ExprIntegerValue(40))), + fromExprValueMap( + ImmutableMap.of( + "state", new ExprStringValue("CA"), "age", new ExprIntegerValue(20))))); + + iterator2 = + Iterators.peekingIterator( + Iterators.forArray( + fromExprValueMap( + ImmutableMap.of( + "state", new ExprStringValue("WA"), "age", new ExprIntegerValue(30))), + fromExprValueMap( + ImmutableMap.of( + "state", new ExprStringValue("WA"), "age", new ExprIntegerValue(30))), + fromExprValueMap( + ImmutableMap.of( + "state", new ExprStringValue("WA"), "age", new ExprIntegerValue(50))), + fromExprValueMap( + ImmutableMap.of( + "state", new ExprStringValue("WA"), "age", new ExprIntegerValue(55))), + fromExprValueMap( + ImmutableMap.of( + "state", new ExprStringValue("CA"), "age", new ExprIntegerValue(15))))); } @Test void test_value_of() { - PeekingIterator iterator = Iterators.peekingIterator( - Iterators.singletonIterator( - fromExprValueMap(ImmutableMap.of( - "state", new ExprStringValue("WA"), "age", new ExprIntegerValue(30))))); + PeekingIterator iterator = + Iterators.peekingIterator( + Iterators.singletonIterator( + fromExprValueMap( + ImmutableMap.of( + "state", new ExprStringValue("WA"), "age", new ExprIntegerValue(30))))); RankingWindowFunction rowNumber = DSL.rowNumber(); @@ -165,18 +179,24 @@ void row_number_should_work_if_no_sort_items_defined() { @Test void rank_should_always_return_1_if_no_sort_items_defined() { - PeekingIterator iterator = Iterators.peekingIterator( - Iterators.forArray( - fromExprValueMap(ImmutableMap.of( - "state", new ExprStringValue("WA"), "age", new ExprIntegerValue(30))), - fromExprValueMap(ImmutableMap.of( - "state", new ExprStringValue("WA"), "age", new ExprIntegerValue(30))), - fromExprValueMap(ImmutableMap.of( - "state", new ExprStringValue("WA"), "age", new ExprIntegerValue(50))), - fromExprValueMap(ImmutableMap.of( - "state", new ExprStringValue("WA"), "age", new ExprIntegerValue(55))), - fromExprValueMap(ImmutableMap.of( - "state", new ExprStringValue("CA"), "age", new ExprIntegerValue(15))))); + PeekingIterator iterator = + Iterators.peekingIterator( + Iterators.forArray( + fromExprValueMap( + ImmutableMap.of( + "state", new ExprStringValue("WA"), "age", new ExprIntegerValue(30))), + fromExprValueMap( + ImmutableMap.of( + "state", new ExprStringValue("WA"), "age", new ExprIntegerValue(30))), + fromExprValueMap( + ImmutableMap.of( + "state", new ExprStringValue("WA"), "age", new ExprIntegerValue(50))), + fromExprValueMap( + ImmutableMap.of( + "state", new ExprStringValue("WA"), "age", new ExprIntegerValue(55))), + fromExprValueMap( + ImmutableMap.of( + "state", new ExprStringValue("CA"), "age", new ExprIntegerValue(15))))); RankingWindowFunction rank = DSL.rank(); @@ -215,5 +235,4 @@ void dense_rank_should_always_return_1_if_no_sort_items_defined() { windowFrame2.load(iterator2); assertEquals(1, denseRank.rank(windowFrame2)); } - } diff --git a/core/src/test/java/org/opensearch/sql/monitor/AlwaysHealthyMonitorTest.java b/core/src/test/java/org/opensearch/sql/monitor/AlwaysHealthyMonitorTest.java index 676f59a44b..9eb7a816a7 100644 --- a/core/src/test/java/org/opensearch/sql/monitor/AlwaysHealthyMonitorTest.java +++ b/core/src/test/java/org/opensearch/sql/monitor/AlwaysHealthyMonitorTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.monitor; import static org.junit.jupiter.api.Assertions.assertTrue; diff --git a/core/src/test/java/org/opensearch/sql/planner/DefaultImplementorTest.java b/core/src/test/java/org/opensearch/sql/planner/DefaultImplementorTest.java index 2d233e9a6f..45d8f6c03c 100644 --- a/core/src/test/java/org/opensearch/sql/planner/DefaultImplementorTest.java +++ b/core/src/test/java/org/opensearch/sql/planner/DefaultImplementorTest.java @@ -81,8 +81,7 @@ @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) class DefaultImplementorTest { - @Mock - private Table table; + @Mock private Table table; private final DefaultImplementor implementor = new DefaultImplementor<>(); @@ -107,50 +106,43 @@ public void visit_should_return_default_physical_operator() { ImmutablePair.of(Sort.SortOption.DEFAULT_ASC, ref("name1", STRING)); Integer limit = 1; Integer offset = 1; - List> nestedArgs = List.of( - Map.of( - "field", new ReferenceExpression("message.info", STRING), - "path", new ReferenceExpression("message", STRING) - ) - ); + List> nestedArgs = + List.of( + Map.of( + "field", new ReferenceExpression("message.info", STRING), + "path", new ReferenceExpression("message", STRING))); List nestedProjectList = List.of( - new NamedExpression( - "message.info", - DSL.nested(DSL.ref("message.info", STRING)), - null - ) - ); + new NamedExpression("message.info", DSL.nested(DSL.ref("message.info", STRING)), null)); Set nestedOperatorArgs = Set.of("message.info"); - Map> groupedFieldsByPath = - Map.of("message", List.of("message.info")); - + Map> groupedFieldsByPath = Map.of("message", List.of("message.info")); LogicalPlan plan = project( nested( - limit( - LogicalPlanDSL.dedupe( - rareTopN( - sort( - eval( - remove( - rename( - aggregation( - filter(values(emptyList()), filterExpr), - aggregators, - groupByExprs), - mappings), - exclude), - newEvalField), - sortField), - CommandType.TOP, - topByExprs, - rareTopNField), - dedupeField), - limit, - offset), - nestedArgs, nestedProjectList), + limit( + LogicalPlanDSL.dedupe( + rareTopN( + sort( + eval( + remove( + rename( + aggregation( + filter(values(emptyList()), filterExpr), + aggregators, + groupByExprs), + mappings), + exclude), + newEvalField), + sortField), + CommandType.TOP, + topByExprs, + rareTopNField), + dedupeField), + limit, + offset), + nestedArgs, + nestedProjectList), include); PhysicalPlan actual = plan.accept(implementor, null); @@ -158,37 +150,39 @@ public void visit_should_return_default_physical_operator() { assertEquals( PhysicalPlanDSL.project( PhysicalPlanDSL.nested( - PhysicalPlanDSL.limit( - PhysicalPlanDSL.dedupe( - PhysicalPlanDSL.rareTopN( - PhysicalPlanDSL.sort( - PhysicalPlanDSL.eval( - PhysicalPlanDSL.remove( - PhysicalPlanDSL.rename( - PhysicalPlanDSL.agg( - PhysicalPlanDSL.filter( - PhysicalPlanDSL.values(emptyList()), - filterExpr), - aggregators, - groupByExprs), - mappings), - exclude), - newEvalField), - sortField), - CommandType.TOP, - topByExprs, - rareTopNField), - dedupeField), - limit, - offset), - nestedOperatorArgs, groupedFieldsByPath), + PhysicalPlanDSL.limit( + PhysicalPlanDSL.dedupe( + PhysicalPlanDSL.rareTopN( + PhysicalPlanDSL.sort( + PhysicalPlanDSL.eval( + PhysicalPlanDSL.remove( + PhysicalPlanDSL.rename( + PhysicalPlanDSL.agg( + PhysicalPlanDSL.filter( + PhysicalPlanDSL.values(emptyList()), + filterExpr), + aggregators, + groupByExprs), + mappings), + exclude), + newEvalField), + sortField), + CommandType.TOP, + topByExprs, + rareTopNField), + dedupeField), + limit, + offset), + nestedOperatorArgs, + groupedFieldsByPath), include), actual); } @Test public void visitRelation_should_throw_an_exception() { - assertThrows(UnsupportedOperationException.class, + assertThrows( + UnsupportedOperationException.class, () -> new LogicalRelation("test", table).accept(implementor, null)); } @@ -196,36 +190,27 @@ public void visitRelation_should_throw_an_exception() { @Test public void visitWindowOperator_should_return_PhysicalWindowOperator() { NamedExpression windowFunction = named(new RowNumberFunction()); - WindowDefinition windowDefinition = new WindowDefinition( - Collections.singletonList(ref("state", STRING)), - Collections.singletonList( - ImmutablePair.of(Sort.SortOption.DEFAULT_DESC, ref("age", INTEGER)))); + WindowDefinition windowDefinition = + new WindowDefinition( + Collections.singletonList(ref("state", STRING)), + Collections.singletonList( + ImmutablePair.of(Sort.SortOption.DEFAULT_DESC, ref("age", INTEGER)))); NamedExpression[] projectList = { - named("state", ref("state", STRING)), - named("row_number", ref("row_number", INTEGER)) + named("state", ref("state", STRING)), named("row_number", ref("row_number", INTEGER)) }; Pair[] sortList = { - ImmutablePair.of(Sort.SortOption.DEFAULT_ASC, ref("state", STRING)), - ImmutablePair.of(Sort.SortOption.DEFAULT_DESC, ref("age", STRING)) + ImmutablePair.of(Sort.SortOption.DEFAULT_ASC, ref("state", STRING)), + ImmutablePair.of(Sort.SortOption.DEFAULT_DESC, ref("age", STRING)) }; LogicalPlan logicalPlan = - project( - window( - sort( - values(), - sortList), - windowFunction, - windowDefinition), - projectList); + project(window(sort(values(), sortList), windowFunction, windowDefinition), projectList); PhysicalPlan physicalPlan = PhysicalPlanDSL.project( PhysicalPlanDSL.window( - PhysicalPlanDSL.sort( - PhysicalPlanDSL.values(), - sortList), + PhysicalPlanDSL.sort(PhysicalPlanDSL.values(), sortList), windowFunction, windowDefinition), projectList); @@ -238,20 +223,22 @@ void visitLogicalCursor_deserializes_it() { var engine = mock(StorageEngine.class); var physicalPlan = new TestOperator(); - var logicalPlan = LogicalPlanDSL.fetchCursor(new PlanSerializer(engine) - .convertToCursor(physicalPlan).toString(), engine); + var logicalPlan = + LogicalPlanDSL.fetchCursor( + new PlanSerializer(engine).convertToCursor(physicalPlan).toString(), engine); assertEquals(physicalPlan, logicalPlan.accept(implementor, null)); } @Test public void visitTableScanBuilder_should_build_TableScanOperator() { TableScanOperator tableScanOperator = mock(TableScanOperator.class); - TableScanBuilder tableScanBuilder = new TableScanBuilder() { - @Override - public TableScanOperator build() { - return tableScanOperator; - } - }; + TableScanBuilder tableScanBuilder = + new TableScanBuilder() { + @Override + public TableScanOperator build() { + return tableScanOperator; + } + }; assertEquals(tableScanOperator, tableScanBuilder.accept(implementor, null)); } @@ -259,12 +246,13 @@ public TableScanOperator build() { public void visitTableWriteBuilder_should_build_TableWriteOperator() { LogicalPlan child = values(); TableWriteOperator tableWriteOperator = mock(TableWriteOperator.class); - TableWriteBuilder logicalPlan = new TableWriteBuilder(child) { - @Override - public TableWriteOperator build(PhysicalPlan child) { - return tableWriteOperator; - } - }; + TableWriteBuilder logicalPlan = + new TableWriteBuilder(child) { + @Override + public TableWriteOperator build(PhysicalPlan child) { + return tableWriteOperator; + } + }; assertEquals(tableWriteOperator, logicalPlan.accept(implementor, null)); } @@ -281,11 +269,13 @@ public void visitCloseCursor_should_build_CursorCloseOperator() { @Test public void visitPaginate_should_remove_it_from_tree() { - var logicalPlanTree = new LogicalPaginate(42, List.of( - new LogicalProject( - new LogicalValues(List.of(List.of())), List.of(), List.of()))); - var physicalPlanTree = new ProjectOperator( - new ValuesOperator(List.of(List.of())), List.of(), List.of()); + var logicalPlanTree = + new LogicalPaginate( + 42, + List.of( + new LogicalProject(new LogicalValues(List.of(List.of())), List.of(), List.of()))); + var physicalPlanTree = + new ProjectOperator(new ValuesOperator(List.of(List.of())), List.of(), List.of()); assertEquals(physicalPlanTree, logicalPlanTree.accept(implementor, null)); } } diff --git a/core/src/test/java/org/opensearch/sql/planner/PlanContextTest.java b/core/src/test/java/org/opensearch/sql/planner/PlanContextTest.java index 77ae78f77e..76ccb6613a 100644 --- a/core/src/test/java/org/opensearch/sql/planner/PlanContextTest.java +++ b/core/src/test/java/org/opensearch/sql/planner/PlanContextTest.java @@ -16,8 +16,7 @@ @ExtendWith(MockitoExtension.class) class PlanContextTest { - @Mock - private Split split; + @Mock private Split split; @Test void createEmptyPlanContext() { diff --git a/core/src/test/java/org/opensearch/sql/planner/PlannerTest.java b/core/src/test/java/org/opensearch/sql/planner/PlannerTest.java index 64498f76cd..6ad44c303b 100644 --- a/core/src/test/java/org/opensearch/sql/planner/PlannerTest.java +++ b/core/src/test/java/org/opensearch/sql/planner/PlannerTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.planner; import static java.util.Collections.emptyList; @@ -47,14 +46,11 @@ @ExtendWith(MockitoExtension.class) public class PlannerTest extends PhysicalPlanTestBase { - @Mock - private PhysicalPlan scan; + @Mock private PhysicalPlan scan; - @Mock - private StorageEngine storageEngine; + @Mock private StorageEngine storageEngine; - @Mock - private LogicalPlanOptimizer optimizer; + @Mock private LogicalPlanOptimizer optimizer; @BeforeEach public void setUp() { @@ -68,29 +64,22 @@ public void planner_test() { PhysicalPlanDSL.rename( PhysicalPlanDSL.agg( PhysicalPlanDSL.filter( - scan, - DSL.equal(DSL.ref("response", INTEGER), DSL.literal(10)) - ), + scan, DSL.equal(DSL.ref("response", INTEGER), DSL.literal(10))), ImmutableList.of(DSL.named("avg(response)", DSL.avg(DSL.ref("response", INTEGER)))), - ImmutableList.of() - ), - ImmutableMap.of(DSL.ref("ivalue", INTEGER), DSL.ref("avg(response)", DOUBLE)) - ), + ImmutableList.of()), + ImmutableMap.of(DSL.ref("ivalue", INTEGER), DSL.ref("avg(response)", DOUBLE))), LogicalPlanDSL.rename( LogicalPlanDSL.aggregation( LogicalPlanDSL.filter( - LogicalPlanDSL.relation("schema", + LogicalPlanDSL.relation( + "schema", storageEngine.getTable( new DataSourceSchemaName(DEFAULT_DATASOURCE_NAME, "default"), - "schema")), - DSL.equal(DSL.ref("response", INTEGER), DSL.literal(10)) - ), + "schema")), + DSL.equal(DSL.ref("response", INTEGER), DSL.literal(10))), ImmutableList.of(DSL.named("avg(response)", DSL.avg(DSL.ref("response", INTEGER)))), - ImmutableList.of() - ), - ImmutableMap.of(DSL.ref("ivalue", INTEGER), DSL.ref("avg(response)", DOUBLE)) - ) - ); + ImmutableList.of()), + ImmutableMap.of(DSL.ref("ivalue", INTEGER), DSL.ref("avg(response)", DOUBLE)))); } @Test @@ -103,15 +92,12 @@ public void plan_a_query_without_relation_involved() { PhysicalPlanDSL.values(emptyList()), DSL.named("123", DSL.literal(123)), DSL.named("hello", DSL.literal("hello")), - DSL.named("false", DSL.literal(false)) - ), + DSL.named("false", DSL.literal(false))), LogicalPlanDSL.project( LogicalPlanDSL.values(emptyList()), DSL.named("123", DSL.literal(123)), DSL.named("hello", DSL.literal("hello")), - DSL.named("false", DSL.literal(false)) - ) - ); + DSL.named("false", DSL.literal(false)))); } protected void assertPhysicalPlan(PhysicalPlan expected, LogicalPlan logicalPlan) { @@ -156,15 +142,15 @@ public PhysicalPlan visitFilter(LogicalFilter plan, Object context) { @Override public PhysicalPlan visitAggregation(LogicalAggregation plan, Object context) { - return new AggregationOperator(plan.getChild().get(0).accept(this, context), - plan.getAggregatorList(), plan.getGroupByList() - ); + return new AggregationOperator( + plan.getChild().get(0).accept(this, context), + plan.getAggregatorList(), + plan.getGroupByList()); } @Override public PhysicalPlan visitRename(LogicalRename plan, Object context) { - return new RenameOperator(plan.getChild().get(0).accept(this, context), - plan.getRenameMap()); + return new RenameOperator(plan.getChild().get(0).accept(this, context), plan.getRenameMap()); } } } diff --git a/core/src/test/java/org/opensearch/sql/planner/logical/LogicalDedupeTest.java b/core/src/test/java/org/opensearch/sql/planner/logical/LogicalDedupeTest.java index fe751506ce..d128885a6a 100644 --- a/core/src/test/java/org/opensearch/sql/planner/logical/LogicalDedupeTest.java +++ b/core/src/test/java/org/opensearch/sql/planner/logical/LogicalDedupeTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.planner.logical; import static org.opensearch.sql.ast.dsl.AstDSL.argument; @@ -30,10 +29,7 @@ public void analyze_dedup_with_two_field_with_default_option() { DSL.ref("integer_value", INTEGER), DSL.ref("double_value", DOUBLE)), dedupe( - relation("schema"), - defaultDedupArgs(), - field("integer_value"), field("double_value") - )); + relation("schema"), defaultDedupArgs(), field("integer_value"), field("double_value"))); } @Test @@ -41,7 +37,9 @@ public void analyze_dedup_with_one_field_with_customize_option() { assertAnalyzeEqual( LogicalPlanDSL.dedupe( LogicalPlanDSL.relation("schema", table), - 3, false, true, + 3, + false, + true, DSL.ref("integer_value", INTEGER), DSL.ref("double_value", DOUBLE)), dedupe( @@ -49,9 +47,8 @@ public void analyze_dedup_with_one_field_with_customize_option() { exprList( argument("number", intLiteral(3)), argument("keepempty", booleanLiteral(false)), - argument("consecutive", booleanLiteral(true)) - ), - field("integer_value"), field("double_value") - )); + argument("consecutive", booleanLiteral(true))), + field("integer_value"), + field("double_value"))); } } diff --git a/core/src/test/java/org/opensearch/sql/planner/logical/LogicalEvalTest.java b/core/src/test/java/org/opensearch/sql/planner/logical/LogicalEvalTest.java index 55bc793045..746441ef4a 100644 --- a/core/src/test/java/org/opensearch/sql/planner/logical/LogicalEvalTest.java +++ b/core/src/test/java/org/opensearch/sql/planner/logical/LogicalEvalTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.planner.logical; import static org.opensearch.sql.ast.dsl.AstDSL.field; @@ -25,8 +24,8 @@ public void analyze_eval_with_one_field() { assertAnalyzeEqual( LogicalPlanDSL.eval( LogicalPlanDSL.relation("schema", table), - ImmutablePair - .of(DSL.ref("absValue", INTEGER), DSL.abs(DSL.ref("integer_value", INTEGER)))), + ImmutablePair.of( + DSL.ref("absValue", INTEGER), DSL.abs(DSL.ref("integer_value", INTEGER)))), AstDSL.eval( AstDSL.relation("schema"), AstDSL.let(AstDSL.field("absValue"), AstDSL.function("abs", field("integer_value"))))); @@ -37,8 +36,8 @@ public void analyze_eval_with_two_field() { assertAnalyzeEqual( LogicalPlanDSL.eval( LogicalPlanDSL.relation("schema", table), - ImmutablePair - .of(DSL.ref("absValue", INTEGER), DSL.abs(DSL.ref("integer_value", INTEGER))), + ImmutablePair.of( + DSL.ref("absValue", INTEGER), DSL.abs(DSL.ref("integer_value", INTEGER))), ImmutablePair.of(DSL.ref("iValue", INTEGER), DSL.abs(DSL.ref("absValue", INTEGER)))), AstDSL.eval( AstDSL.relation("schema"), diff --git a/core/src/test/java/org/opensearch/sql/planner/logical/LogicalPlanNodeVisitorTest.java b/core/src/test/java/org/opensearch/sql/planner/logical/LogicalPlanNodeVisitorTest.java index d4d5c89c9b..df8baab55d 100644 --- a/core/src/test/java/org/opensearch/sql/planner/logical/LogicalPlanNodeVisitorTest.java +++ b/core/src/test/java/org/opensearch/sql/planner/logical/LogicalPlanNodeVisitorTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.planner.logical; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -44,9 +43,7 @@ import org.opensearch.sql.storage.write.TableWriteBuilder; import org.opensearch.sql.storage.write.TableWriteOperator; -/** - * Todo. Temporary added for UT coverage, Will be removed. - */ +/** Todo. Temporary added for UT coverage, Will be removed. */ @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) class LogicalPlanNodeVisitorTest { @@ -84,50 +81,59 @@ public void logical_plan_should_be_traversable() { @SuppressWarnings("unchecked") private static Stream getLogicalPlansForVisitorTest() { LogicalPlan relation = LogicalPlanDSL.relation("schema", table); - LogicalPlan tableScanBuilder = new TableScanBuilder() { - @Override - public TableScanOperator build() { - return null; - } - }; - TableWriteBuilder tableWriteBuilder = new TableWriteBuilder(null) { - @Override - public TableWriteOperator build(PhysicalPlan child) { - return null; - } - }; + LogicalPlan tableScanBuilder = + new TableScanBuilder() { + @Override + public TableScanOperator build() { + return null; + } + }; + TableWriteBuilder tableWriteBuilder = + new TableWriteBuilder(null) { + @Override + public TableWriteOperator build(PhysicalPlan child) { + return null; + } + }; LogicalPlan write = LogicalPlanDSL.write(null, table, Collections.emptyList()); LogicalPlan filter = LogicalPlanDSL.filter(relation, expression); - LogicalPlan aggregation = LogicalPlanDSL.aggregation( - filter, ImmutableList.of(DSL.named("avg", aggregator)), ImmutableList.of(DSL.named( - "group", expression))); + LogicalPlan aggregation = + LogicalPlanDSL.aggregation( + filter, + ImmutableList.of(DSL.named("avg", aggregator)), + ImmutableList.of(DSL.named("group", expression))); LogicalPlan rename = LogicalPlanDSL.rename(aggregation, ImmutableMap.of(ref, ref)); LogicalPlan project = LogicalPlanDSL.project(relation, named("ref", ref)); LogicalPlan remove = LogicalPlanDSL.remove(relation, ref); LogicalPlan eval = LogicalPlanDSL.eval(relation, Pair.of(ref, expression)); LogicalPlan sort = LogicalPlanDSL.sort(relation, Pair.of(SortOption.DEFAULT_ASC, expression)); LogicalPlan dedup = LogicalPlanDSL.dedupe(relation, 1, false, false, expression); - LogicalPlan window = LogicalPlanDSL.window(relation, named(expression), new WindowDefinition( - ImmutableList.of(ref), ImmutableList.of(Pair.of(SortOption.DEFAULT_ASC, expression)))); - LogicalPlan rareTopN = LogicalPlanDSL.rareTopN( - relation, CommandType.TOP, ImmutableList.of(expression), expression); - LogicalPlan highlight = new LogicalHighlight(filter, - new LiteralExpression(ExprValueUtils.stringValue("fieldA")), Map.of()); + LogicalPlan window = + LogicalPlanDSL.window( + relation, + named(expression), + new WindowDefinition( + ImmutableList.of(ref), + ImmutableList.of(Pair.of(SortOption.DEFAULT_ASC, expression)))); + LogicalPlan rareTopN = + LogicalPlanDSL.rareTopN( + relation, CommandType.TOP, ImmutableList.of(expression), expression); + LogicalPlan highlight = + new LogicalHighlight( + filter, new LiteralExpression(ExprValueUtils.stringValue("fieldA")), Map.of()); LogicalPlan mlCommons = new LogicalMLCommons(relation, "kmeans", Map.of()); LogicalPlan ad = new LogicalAD(relation, Map.of()); LogicalPlan ml = new LogicalML(relation, Map.of()); LogicalPlan paginate = new LogicalPaginate(42, List.of(relation)); - List> nestedArgs = List.of( - Map.of( - "field", new ReferenceExpression("message.info", STRING), - "path", new ReferenceExpression("message", STRING) - ) - ); + List> nestedArgs = + List.of( + Map.of( + "field", new ReferenceExpression("message.info", STRING), + "path", new ReferenceExpression("message", STRING))); List projectList = List.of( - new NamedExpression("message.info", DSL.nested(DSL.ref("message.info", STRING)), null) - ); + new NamedExpression("message.info", DSL.nested(DSL.ref("message.info", STRING)), null)); LogicalNested nested = new LogicalNested(null, nestedArgs, projectList); @@ -136,20 +142,37 @@ public TableWriteOperator build(PhysicalPlan child) { LogicalCloseCursor closeCursor = new LogicalCloseCursor(cursor); return Stream.of( - relation, tableScanBuilder, write, tableWriteBuilder, filter, aggregation, rename, project, - remove, eval, sort, dedup, window, rareTopN, highlight, mlCommons, ad, ml, paginate, nested, - cursor, closeCursor - ).map(Arguments::of); + relation, + tableScanBuilder, + write, + tableWriteBuilder, + filter, + aggregation, + rename, + project, + remove, + eval, + sort, + dedup, + window, + rareTopN, + highlight, + mlCommons, + ad, + ml, + paginate, + nested, + cursor, + closeCursor) + .map(Arguments::of); } @ParameterizedTest @MethodSource("getLogicalPlansForVisitorTest") public void abstract_plan_node_visitor_should_return_null(LogicalPlan plan) { - assertNull(plan.accept(new LogicalPlanNodeVisitor() { - }, null)); + assertNull(plan.accept(new LogicalPlanNodeVisitor() {}, null)); } - private static class NodesCount extends LogicalPlanNodeVisitor { @Override public Integer visitRelation(LogicalRelation plan, Object context) { @@ -160,28 +183,36 @@ public Integer visitRelation(LogicalRelation plan, Object context) { public Integer visitFilter(LogicalFilter plan, Object context) { return 1 + plan.getChild().stream() - .map(child -> child.accept(this, context)).mapToInt(Integer::intValue).sum(); + .map(child -> child.accept(this, context)) + .mapToInt(Integer::intValue) + .sum(); } @Override public Integer visitAggregation(LogicalAggregation plan, Object context) { return 1 + plan.getChild().stream() - .map(child -> child.accept(this, context)).mapToInt(Integer::intValue).sum(); + .map(child -> child.accept(this, context)) + .mapToInt(Integer::intValue) + .sum(); } @Override public Integer visitRename(LogicalRename plan, Object context) { return 1 + plan.getChild().stream() - .map(child -> child.accept(this, context)).mapToInt(Integer::intValue).sum(); + .map(child -> child.accept(this, context)) + .mapToInt(Integer::intValue) + .sum(); } @Override public Integer visitRareTopN(LogicalRareTopN plan, Object context) { return 1 + plan.getChild().stream() - .map(child -> child.accept(this, context)).mapToInt(Integer::intValue).sum(); + .map(child -> child.accept(this, context)) + .mapToInt(Integer::intValue) + .sum(); } } } diff --git a/core/src/test/java/org/opensearch/sql/planner/logical/LogicalRelationTest.java b/core/src/test/java/org/opensearch/sql/planner/logical/LogicalRelationTest.java index 9cf40d3c4d..7181c91da9 100644 --- a/core/src/test/java/org/opensearch/sql/planner/logical/LogicalRelationTest.java +++ b/core/src/test/java/org/opensearch/sql/planner/logical/LogicalRelationTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.planner.logical; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -17,8 +16,7 @@ @ExtendWith(MockitoExtension.class) class LogicalRelationTest { - @Mock - Table table; + @Mock Table table; @Test public void logicalRelationHasNoInput() { @@ -31,5 +29,4 @@ public void logicalRelationWithDataSourceHasNoInput() { LogicalPlan relation = LogicalPlanDSL.relation("prometheus.index", table); assertEquals(0, relation.getChild().size()); } - } diff --git a/core/src/test/java/org/opensearch/sql/planner/logical/LogicalSortTest.java b/core/src/test/java/org/opensearch/sql/planner/logical/LogicalSortTest.java index 1a33795009..8757473d24 100644 --- a/core/src/test/java/org/opensearch/sql/planner/logical/LogicalSortTest.java +++ b/core/src/test/java/org/opensearch/sql/planner/logical/LogicalSortTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.planner.logical; import static org.opensearch.sql.ast.dsl.AstDSL.argument; diff --git a/core/src/test/java/org/opensearch/sql/planner/optimizer/LogicalPlanOptimizerTest.java b/core/src/test/java/org/opensearch/sql/planner/optimizer/LogicalPlanOptimizerTest.java index faedb88111..2cdcb76e71 100644 --- a/core/src/test/java/org/opensearch/sql/planner/optimizer/LogicalPlanOptimizerTest.java +++ b/core/src/test/java/org/opensearch/sql/planner/optimizer/LogicalPlanOptimizerTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.planner.optimizer; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -61,117 +60,85 @@ @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) class LogicalPlanOptimizerTest { - @Mock - private Table table; + @Mock private Table table; - @Spy - private TableScanBuilder tableScanBuilder; + @Spy private TableScanBuilder tableScanBuilder; @BeforeEach void setUp() { lenient().when(table.createScanBuilder()).thenReturn(tableScanBuilder); } - /** - * Filter - Filter --> Filter. - */ + /** Filter - Filter --> Filter. */ @Test void filter_merge_filter() { assertEquals( filter( tableScanBuilder, - DSL.and(DSL.equal(DSL.ref("integer_value", INTEGER), DSL.literal(integerValue(2))), - DSL.equal(DSL.ref("integer_value", INTEGER), DSL.literal(integerValue(1)))) - ), + DSL.and( + DSL.equal(DSL.ref("integer_value", INTEGER), DSL.literal(integerValue(2))), + DSL.equal(DSL.ref("integer_value", INTEGER), DSL.literal(integerValue(1))))), optimize( filter( filter( relation("schema", table), - DSL.equal(DSL.ref("integer_value", INTEGER), DSL.literal(integerValue(1))) - ), - DSL.equal(DSL.ref("integer_value", INTEGER), DSL.literal(integerValue(2))) - ) - ) - ); + DSL.equal(DSL.ref("integer_value", INTEGER), DSL.literal(integerValue(1)))), + DSL.equal(DSL.ref("integer_value", INTEGER), DSL.literal(integerValue(2)))))); } - /** - * Filter - Sort --> Sort - Filter. - */ + /** Filter - Sort --> Sort - Filter. */ @Test void push_filter_under_sort() { assertEquals( sort( filter( tableScanBuilder, - DSL.equal(DSL.ref("intV", INTEGER), DSL.literal(integerValue(1))) - ), - Pair.of(Sort.SortOption.DEFAULT_ASC, DSL.ref("longV", LONG)) - ), + DSL.equal(DSL.ref("intV", INTEGER), DSL.literal(integerValue(1)))), + Pair.of(Sort.SortOption.DEFAULT_ASC, DSL.ref("longV", LONG))), optimize( filter( sort( relation("schema", table), - Pair.of(Sort.SortOption.DEFAULT_ASC, DSL.ref("longV", LONG)) - ), - DSL.equal(DSL.ref("intV", INTEGER), DSL.literal(integerValue(1))) - ) - ) - ); + Pair.of(Sort.SortOption.DEFAULT_ASC, DSL.ref("longV", LONG))), + DSL.equal(DSL.ref("intV", INTEGER), DSL.literal(integerValue(1)))))); } - /** - * Filter - Sort --> Sort - Filter. - */ + /** Filter - Sort --> Sort - Filter. */ @Test void multiple_filter_should_eventually_be_merged() { assertEquals( sort( filter( tableScanBuilder, - DSL.and(DSL.equal(DSL.ref("intV", INTEGER), DSL.literal(integerValue(1))), - DSL.less(DSL.ref("longV", INTEGER), DSL.literal(longValue(1L)))) - ), - Pair.of(Sort.SortOption.DEFAULT_ASC, DSL.ref("longV", LONG)) - ), + DSL.and( + DSL.equal(DSL.ref("intV", INTEGER), DSL.literal(integerValue(1))), + DSL.less(DSL.ref("longV", INTEGER), DSL.literal(longValue(1L))))), + Pair.of(Sort.SortOption.DEFAULT_ASC, DSL.ref("longV", LONG))), optimize( filter( sort( filter( relation("schema", table), - DSL.less(DSL.ref("longV", INTEGER), DSL.literal(longValue(1L))) - ), - Pair.of(Sort.SortOption.DEFAULT_ASC, DSL.ref("longV", LONG)) - ), - DSL.equal(DSL.ref("intV", INTEGER), DSL.literal(integerValue(1))) - ) - ) - ); + DSL.less(DSL.ref("longV", INTEGER), DSL.literal(longValue(1L)))), + Pair.of(Sort.SortOption.DEFAULT_ASC, DSL.ref("longV", LONG))), + DSL.equal(DSL.ref("intV", INTEGER), DSL.literal(integerValue(1)))))); } @Test void default_table_scan_builder_should_not_push_down_anything() { LogicalPlan[] plans = { - project( - relation("schema", table), - DSL.named("i", DSL.ref("intV", INTEGER)) - ), - filter( - relation("schema", table), - DSL.equal(DSL.ref("intV", INTEGER), DSL.literal(integerValue(1))) - ), - aggregation( - relation("schema", table), - ImmutableList - .of(DSL.named("AVG(intV)", - DSL.avg(DSL.ref("intV", INTEGER)))), - ImmutableList.of(DSL.named("longV", DSL.ref("longV", LONG)))), - sort( - relation("schema", table), - Pair.of(Sort.SortOption.DEFAULT_ASC, DSL.ref("intV", INTEGER))), - limit( - relation("schema", table), - 1, 1) + project(relation("schema", table), DSL.named("i", DSL.ref("intV", INTEGER))), + filter( + relation("schema", table), + DSL.equal(DSL.ref("intV", INTEGER), DSL.literal(integerValue(1)))), + aggregation( + relation("schema", table), + ImmutableList.of(DSL.named("AVG(intV)", DSL.avg(DSL.ref("intV", INTEGER)))), + ImmutableList.of(DSL.named("longV", DSL.ref("longV", LONG)))), + sort( + relation("schema", table), + Pair.of(Sort.SortOption.DEFAULT_ASC, DSL.ref("intV", INTEGER))), + limit(relation("schema", table), 1, 1) }; for (LogicalPlan plan : plans) { @@ -185,12 +152,7 @@ void table_scan_builder_support_project_push_down_can_apply_its_rule() { assertEquals( tableScanBuilder, - optimize( - project( - relation("schema", table), - DSL.named("i", DSL.ref("intV", INTEGER))) - ) - ); + optimize(project(relation("schema", table), DSL.named("i", DSL.ref("intV", INTEGER))))); } @Test @@ -202,9 +164,7 @@ void table_scan_builder_support_filter_push_down_can_apply_its_rule() { optimize( filter( relation("schema", table), - DSL.equal(DSL.ref("intV", INTEGER), DSL.literal(integerValue(1)))) - ) - ); + DSL.equal(DSL.ref("intV", INTEGER), DSL.literal(integerValue(1)))))); } @Test @@ -216,12 +176,8 @@ void table_scan_builder_support_aggregation_push_down_can_apply_its_rule() { optimize( aggregation( relation("schema", table), - ImmutableList - .of(DSL.named("AVG(intV)", - DSL.avg(DSL.ref("intV", INTEGER)))), - ImmutableList.of(DSL.named("longV", DSL.ref("longV", LONG)))) - ) - ); + ImmutableList.of(DSL.named("AVG(intV)", DSL.avg(DSL.ref("intV", INTEGER)))), + ImmutableList.of(DSL.named("longV", DSL.ref("longV", LONG)))))); } @Test @@ -233,23 +189,14 @@ void table_scan_builder_support_sort_push_down_can_apply_its_rule() { optimize( sort( relation("schema", table), - Pair.of(Sort.SortOption.DEFAULT_ASC, DSL.ref("intV", INTEGER))) - ) - ); + Pair.of(Sort.SortOption.DEFAULT_ASC, DSL.ref("intV", INTEGER))))); } @Test void table_scan_builder_support_limit_push_down_can_apply_its_rule() { when(tableScanBuilder.pushDownLimit(any())).thenReturn(true); - assertEquals( - tableScanBuilder, - optimize( - limit( - relation("schema", table), - 1, 1) - ) - ); + assertEquals(tableScanBuilder, optimize(limit(relation("schema", table), 1, 1))); } @Test @@ -258,13 +205,7 @@ void table_scan_builder_support_highlight_push_down_can_apply_its_rule() { assertEquals( tableScanBuilder, - optimize( - highlight( - relation("schema", table), - DSL.literal("*"), - Collections.emptyMap()) - ) - ); + optimize(highlight(relation("schema", table), DSL.literal("*"), Collections.emptyMap()))); } @Test @@ -277,33 +218,27 @@ void table_scan_builder_support_nested_push_down_can_apply_its_rule() { nested( relation("schema", table), List.of(Map.of("field", new ReferenceExpression("message.info", STRING))), - List.of(new NamedExpression( - "message.info", - DSL.nested(DSL.ref("message.info", STRING)), - null)) - ) - ) - ); + List.of( + new NamedExpression( + "message.info", DSL.nested(DSL.ref("message.info", STRING)), null))))); } @Test void table_not_support_scan_builder_should_not_be_impact() { - Table table = new Table() { - @Override - public Map getFieldTypes() { - return null; - } - - @Override - public PhysicalPlan implement(LogicalPlan plan) { - return null; - } - }; - - assertEquals( - relation("schema", table), - optimize(relation("schema", table)) - ); + Table table = + new Table() { + @Override + public Map getFieldTypes() { + return null; + } + + @Override + public PhysicalPlan implement(LogicalPlan plan) { + return null; + } + }; + + assertEquals(relation("schema", table), optimize(relation("schema", table))); } @Test @@ -311,28 +246,25 @@ void table_support_write_builder_should_be_replaced() { TableWriteBuilder writeBuilder = Mockito.mock(TableWriteBuilder.class); when(table.createWriteBuilder(any())).thenReturn(writeBuilder); - assertEquals( - writeBuilder, - optimize(write(values(), table, Collections.emptyList())) - ); + assertEquals(writeBuilder, optimize(write(values(), table, Collections.emptyList()))); } @Test void table_not_support_write_builder_should_report_error() { - Table table = new Table() { - @Override - public Map getFieldTypes() { - return null; - } - - @Override - public PhysicalPlan implement(LogicalPlan plan) { - return null; - } - }; - - assertThrows(UnsupportedOperationException.class, - () -> table.createWriteBuilder(null)); + Table table = + new Table() { + @Override + public Map getFieldTypes() { + return null; + } + + @Override + public PhysicalPlan implement(LogicalPlan plan) { + return null; + } + }; + + assertThrows(UnsupportedOperationException.class, () -> table.createWriteBuilder(null)); } @Test @@ -340,8 +272,7 @@ void paged_table_scan_builder_support_project_push_down_can_apply_its_rule() { when(tableScanBuilder.pushDownPageSize(any())).thenReturn(true); var relation = relation("schema", table); - var optimized = LogicalPlanOptimizer.create() - .optimize(paginate(project(relation), 4)); + var optimized = LogicalPlanOptimizer.create().optimize(paginate(project(relation), 4)); verify(tableScanBuilder).pushDownPageSize(any()); assertEquals(project(tableScanBuilder), optimized); @@ -350,30 +281,29 @@ void paged_table_scan_builder_support_project_push_down_can_apply_its_rule() { @Test void push_down_page_size_multiple_children() { var relation = relation("schema", table); - var twoChildrenPlan = new LogicalPlan(List.of(relation, relation)) { - @Override - public R accept(LogicalPlanNodeVisitor visitor, C context) { - return null; - } - }; + var twoChildrenPlan = + new LogicalPlan(List.of(relation, relation)) { + @Override + public R accept(LogicalPlanNodeVisitor visitor, C context) { + return null; + } + }; var queryPlan = paginate(twoChildrenPlan, 4); var optimizer = LogicalPlanOptimizer.create(); - final var exception = assertThrows(UnsupportedOperationException.class, - () -> optimizer.optimize(queryPlan)); - assertEquals("Unsupported plan: relation operator cannot have siblings", - exception.getMessage()); + final var exception = + assertThrows(UnsupportedOperationException.class, () -> optimizer.optimize(queryPlan)); + assertEquals( + "Unsupported plan: relation operator cannot have siblings", exception.getMessage()); } @Test void push_down_page_size_push_failed() { when(tableScanBuilder.pushDownPageSize(any())).thenReturn(false); - var queryPlan = paginate( - project( - relation("schema", table)), 4); + var queryPlan = paginate(project(relation("schema", table)), 4); var optimizer = LogicalPlanOptimizer.create(); - final var exception = assertThrows(IllegalStateException.class, - () -> optimizer.optimize(queryPlan)); + final var exception = + assertThrows(IllegalStateException.class, () -> optimizer.optimize(queryPlan)); assertEquals("Failed to push down LogicalPaginate", exception.getMessage()); } @@ -386,8 +316,7 @@ void push_page_size_noop_if_no_relation() { @Test void push_page_size_noop_if_no_sub_plans() { var paginate = new LogicalPaginate(42, List.of()); - assertEquals(paginate, - LogicalPlanOptimizer.create().optimize(paginate)); + assertEquals(paginate, LogicalPlanOptimizer.create().optimize(paginate)); } @Test @@ -395,8 +324,8 @@ void table_scan_builder_support_offset_push_down_can_apply_its_rule() { when(tableScanBuilder.pushDownPageSize(any())).thenReturn(true); var relation = new LogicalRelation("schema", table); - var optimized = LogicalPlanOptimizer.create() - .optimize(new LogicalPaginate(42, List.of(project(relation)))); + var optimized = + LogicalPlanOptimizer.create().optimize(new LogicalPaginate(42, List.of(project(relation)))); // `optimized` structure: LogicalProject -> TableScanBuilder // LogicalRelation replaced by a TableScanBuilder instance assertEquals(project(tableScanBuilder), optimized); diff --git a/core/src/test/java/org/opensearch/sql/planner/optimizer/pattern/PatternsTest.java b/core/src/test/java/org/opensearch/sql/planner/optimizer/pattern/PatternsTest.java index 2cab54d272..d1e1a03521 100644 --- a/core/src/test/java/org/opensearch/sql/planner/optimizer/pattern/PatternsTest.java +++ b/core/src/test/java/org/opensearch/sql/planner/optimizer/pattern/PatternsTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.planner.optimizer.pattern; import static org.junit.jupiter.api.Assertions.assertAll; @@ -27,8 +26,8 @@ void source_is_empty() { when(plan.getChild()).thenReturn(Collections.emptyList()); assertAll( () -> assertFalse(Patterns.source().getFunction().apply(plan).isPresent()), - () -> assertFalse(Patterns.source(null).getProperty().getFunction().apply(plan).isPresent()) - ); + () -> + assertFalse(Patterns.source(null).getProperty().getFunction().apply(plan).isPresent())); } @Test @@ -36,7 +35,6 @@ void table_is_empty() { var plan = mock(LogicalFilter.class); assertAll( () -> assertFalse(Patterns.table().getFunction().apply(plan).isPresent()), - () -> assertFalse(Patterns.writeTable().getFunction().apply(plan).isPresent()) - ); + () -> assertFalse(Patterns.writeTable().getFunction().apply(plan).isPresent())); } } diff --git a/core/src/test/java/org/opensearch/sql/planner/physical/AggregationOperatorTest.java b/core/src/test/java/org/opensearch/sql/planner/physical/AggregationOperatorTest.java index 2585a21d7a..0f3f4bd61f 100644 --- a/core/src/test/java/org/opensearch/sql/planner/physical/AggregationOperatorTest.java +++ b/core/src/test/java/org/opensearch/sql/planner/physical/AggregationOperatorTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.planner.physical; import static org.hamcrest.MatcherAssert.assertThat; @@ -38,563 +37,733 @@ class AggregationOperatorTest extends PhysicalPlanTestBase { @Test public void sum_without_groups() { - PhysicalPlan plan = new AggregationOperator(new TestScan(), - Collections - .singletonList(DSL.named("sum(response)", DSL.sum(DSL.ref("response", INTEGER)))), - Collections.emptyList()); + PhysicalPlan plan = + new AggregationOperator( + new TestScan(), + Collections.singletonList( + DSL.named("sum(response)", DSL.sum(DSL.ref("response", INTEGER)))), + Collections.emptyList()); List result = execute(plan); assertEquals(1, result.size()); - assertThat(result, containsInAnyOrder( - ExprValueUtils.tupleValue(ImmutableMap.of("sum(response)", 1504d)) - )); + assertThat( + result, + containsInAnyOrder(ExprValueUtils.tupleValue(ImmutableMap.of("sum(response)", 1504d)))); } @Test public void avg_with_one_groups() { - PhysicalPlan plan = new AggregationOperator(new TestScan(), - Collections - .singletonList(DSL.named("avg(response)", DSL.avg(DSL.ref("response", INTEGER)))), - Collections.singletonList(DSL.named("action", DSL.ref("action", STRING)))); + PhysicalPlan plan = + new AggregationOperator( + new TestScan(), + Collections.singletonList( + DSL.named("avg(response)", DSL.avg(DSL.ref("response", INTEGER)))), + Collections.singletonList(DSL.named("action", DSL.ref("action", STRING)))); List result = execute(plan); assertEquals(2, result.size()); - assertThat(result, containsInAnyOrder( - ExprValueUtils.tupleValue(ImmutableMap.of("action", "GET", "avg(response)", 268d)), - ExprValueUtils.tupleValue(ImmutableMap.of("action", "POST", "avg(response)", 350d)) - )); + assertThat( + result, + containsInAnyOrder( + ExprValueUtils.tupleValue(ImmutableMap.of("action", "GET", "avg(response)", 268d)), + ExprValueUtils.tupleValue(ImmutableMap.of("action", "POST", "avg(response)", 350d)))); } @Test public void avg_with_two_groups() { - PhysicalPlan plan = new AggregationOperator(new TestScan(), - Collections - .singletonList(DSL.named("avg(response)", DSL.avg(DSL.ref("response", INTEGER)))), - Arrays.asList(DSL.named("action", DSL.ref("action", STRING)), - DSL.named("ip", DSL.ref("ip", STRING)))); + PhysicalPlan plan = + new AggregationOperator( + new TestScan(), + Collections.singletonList( + DSL.named("avg(response)", DSL.avg(DSL.ref("response", INTEGER)))), + Arrays.asList( + DSL.named("action", DSL.ref("action", STRING)), + DSL.named("ip", DSL.ref("ip", STRING)))); List result = execute(plan); assertEquals(3, result.size()); - assertThat(result, containsInAnyOrder( - ExprValueUtils.tupleValue( - ImmutableMap.of("action", "GET", "ip", "209.160.24.63", "avg(response)", 302d)), - ExprValueUtils.tupleValue( - ImmutableMap.of("action", "GET", "ip", "112.111.162.4", "avg(response)", 200d)), - ExprValueUtils.tupleValue( - ImmutableMap.of("action", "POST", "ip", "74.125.19.106", "avg(response)", 350d)) - )); + assertThat( + result, + containsInAnyOrder( + ExprValueUtils.tupleValue( + ImmutableMap.of("action", "GET", "ip", "209.160.24.63", "avg(response)", 302d)), + ExprValueUtils.tupleValue( + ImmutableMap.of("action", "GET", "ip", "112.111.162.4", "avg(response)", 200d)), + ExprValueUtils.tupleValue( + ImmutableMap.of("action", "POST", "ip", "74.125.19.106", "avg(response)", 350d)))); } @Test public void sum_with_one_groups() { - PhysicalPlan plan = new AggregationOperator(new TestScan(), - Collections - .singletonList(DSL.named("sum(response)", DSL.sum(DSL.ref("response", INTEGER)))), - Collections.singletonList(DSL.named("action", DSL.ref("action", STRING)))); + PhysicalPlan plan = + new AggregationOperator( + new TestScan(), + Collections.singletonList( + DSL.named("sum(response)", DSL.sum(DSL.ref("response", INTEGER)))), + Collections.singletonList(DSL.named("action", DSL.ref("action", STRING)))); List result = execute(plan); assertEquals(2, result.size()); - assertThat(result, containsInAnyOrder( - ExprValueUtils.tupleValue(ImmutableMap.of("action", "GET", "sum(response)", 804)), - ExprValueUtils.tupleValue(ImmutableMap.of("action", "POST", "sum(response)", 700)) - )); + assertThat( + result, + containsInAnyOrder( + ExprValueUtils.tupleValue(ImmutableMap.of("action", "GET", "sum(response)", 804)), + ExprValueUtils.tupleValue(ImmutableMap.of("action", "POST", "sum(response)", 700)))); } @Test public void millisecond_span() { - PhysicalPlan plan = new AggregationOperator(testScan(datetimeInputs), - Collections.singletonList(DSL - .named("count", DSL.count(DSL.ref("second", TIMESTAMP)))), - Collections.singletonList(DSL - .named("span", DSL.span(DSL.ref("second", TIMESTAMP), DSL.literal(6 * 1000), "ms")))); + PhysicalPlan plan = + new AggregationOperator( + testScan(datetimeInputs), + Collections.singletonList(DSL.named("count", DSL.count(DSL.ref("second", TIMESTAMP)))), + Collections.singletonList( + DSL.named( + "span", DSL.span(DSL.ref("second", TIMESTAMP), DSL.literal(6 * 1000), "ms")))); List result = execute(plan); assertEquals(2, result.size()); - assertThat(result, containsInRelativeOrder( - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprTimestampValue("2021-01-01 00:00:00"), "count", 2)), - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprTimestampValue("2021-01-01 00:00:12"), "count", 3)) - )); + assertThat( + result, + containsInRelativeOrder( + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprTimestampValue("2021-01-01 00:00:00"), "count", 2)), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "span", new ExprTimestampValue("2021-01-01 00:00:12"), "count", 3)))); } @Test public void second_span() { - PhysicalPlan plan = new AggregationOperator(testScan(datetimeInputs), - Collections.singletonList(DSL - .named("count", DSL.count(DSL.ref("second", TIMESTAMP)))), - Collections.singletonList(DSL - .named("span", DSL.span(DSL.ref("second", TIMESTAMP), DSL.literal(6), "s")))); + PhysicalPlan plan = + new AggregationOperator( + testScan(datetimeInputs), + Collections.singletonList(DSL.named("count", DSL.count(DSL.ref("second", TIMESTAMP)))), + Collections.singletonList( + DSL.named("span", DSL.span(DSL.ref("second", TIMESTAMP), DSL.literal(6), "s")))); List result = execute(plan); assertEquals(2, result.size()); - assertThat(result, containsInRelativeOrder( - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprTimestampValue("2021-01-01 00:00:00"), "count", 2)), - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprTimestampValue("2021-01-01 00:00:12"), "count", 3)) - )); + assertThat( + result, + containsInRelativeOrder( + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprTimestampValue("2021-01-01 00:00:00"), "count", 2)), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "span", new ExprTimestampValue("2021-01-01 00:00:12"), "count", 3)))); } @Test public void minute_span() { - PhysicalPlan plan = new AggregationOperator(testScan(datetimeInputs), - Collections.singletonList(DSL - .named("count", DSL.count(DSL.ref("minute", DATETIME)))), - Collections.singletonList(DSL - .named("span", DSL.span(DSL.ref("minute", DATETIME), DSL.literal(5), "m")))); + PhysicalPlan plan = + new AggregationOperator( + testScan(datetimeInputs), + Collections.singletonList(DSL.named("count", DSL.count(DSL.ref("minute", DATETIME)))), + Collections.singletonList( + DSL.named("span", DSL.span(DSL.ref("minute", DATETIME), DSL.literal(5), "m")))); List result = execute(plan); assertEquals(3, result.size()); - assertThat(result, containsInRelativeOrder( - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprDatetimeValue("2020-12-31 23:50:00"), "count", 1)), - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprDatetimeValue("2021-01-01 00:00:00"), "count", 3)), - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprDatetimeValue("2021-01-01 00:05:00"), "count", 1)) - )); - - plan = new AggregationOperator(testScan(datetimeInputs), - Collections.singletonList(DSL - .named("count", DSL.count(DSL.ref("hour", TIME)))), - Collections.singletonList(DSL - .named("span", DSL.span(DSL.ref("hour", TIME), DSL.literal(30), "m")))); + assertThat( + result, + containsInRelativeOrder( + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprDatetimeValue("2020-12-31 23:50:00"), "count", 1)), + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprDatetimeValue("2021-01-01 00:00:00"), "count", 3)), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "span", new ExprDatetimeValue("2021-01-01 00:05:00"), "count", 1)))); + + plan = + new AggregationOperator( + testScan(datetimeInputs), + Collections.singletonList(DSL.named("count", DSL.count(DSL.ref("hour", TIME)))), + Collections.singletonList( + DSL.named("span", DSL.span(DSL.ref("hour", TIME), DSL.literal(30), "m")))); result = execute(plan); assertEquals(4, result.size()); - assertThat(result, containsInRelativeOrder( - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprTimeValue("17:00:00"), "count", 2)), - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprTimeValue("18:00:00"), "count", 1)), - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprTimeValue("18:30:00"), "count", 1)), - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprTimeValue("19:00:00"), "count", 1)) - )); + assertThat( + result, + containsInRelativeOrder( + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprTimeValue("17:00:00"), "count", 2)), + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprTimeValue("18:00:00"), "count", 1)), + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprTimeValue("18:30:00"), "count", 1)), + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprTimeValue("19:00:00"), "count", 1)))); } @Test public void hour_span() { - PhysicalPlan plan = new AggregationOperator(testScan(datetimeInputs), - Collections.singletonList(DSL - .named("count", DSL.count(DSL.ref("hour", TIME)))), - Collections.singletonList(DSL - .named("span", DSL.span(DSL.ref("hour", TIME), DSL.literal(1), "h")))); + PhysicalPlan plan = + new AggregationOperator( + testScan(datetimeInputs), + Collections.singletonList(DSL.named("count", DSL.count(DSL.ref("hour", TIME)))), + Collections.singletonList( + DSL.named("span", DSL.span(DSL.ref("hour", TIME), DSL.literal(1), "h")))); List result = execute(plan); assertEquals(3, result.size()); - assertThat(result, containsInRelativeOrder( - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprTimeValue("17:00:00"), "count", 2)), - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprTimeValue("18:00:00"), "count", 2)), - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprTimeValue("19:00:00"), "count", 1)) - )); + assertThat( + result, + containsInRelativeOrder( + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprTimeValue("17:00:00"), "count", 2)), + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprTimeValue("18:00:00"), "count", 2)), + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprTimeValue("19:00:00"), "count", 1)))); } @Test public void day_span() { - PhysicalPlan plan = new AggregationOperator(testScan(dateInputs), - Collections.singletonList(DSL - .named("count(day)", DSL.count(DSL.ref("day", DATE)))), - Collections.singletonList(DSL - .named("span", DSL.span(DSL.ref("day", DATE), DSL.literal(1), "d")))); + PhysicalPlan plan = + new AggregationOperator( + testScan(dateInputs), + Collections.singletonList(DSL.named("count(day)", DSL.count(DSL.ref("day", DATE)))), + Collections.singletonList( + DSL.named("span", DSL.span(DSL.ref("day", DATE), DSL.literal(1), "d")))); List result = execute(plan); assertEquals(4, result.size()); - assertThat(result, containsInRelativeOrder( - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprDateValue("2021-01-01"), "count(day)", 2)), - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprDateValue("2021-01-02"), "count(day)", 1)), - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprDateValue("2021-01-03"), "count(day)", 1)), - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprDateValue("2021-01-04"), "count(day)", 1)) - )); - - plan = new AggregationOperator(testScan(dateInputs), - Collections.singletonList(DSL - .named("count", DSL.count(DSL.ref("month", DATE)))), - Collections.singletonList(DSL - .named("span", DSL.span(DSL.ref("month", DATE), DSL.literal(30), "d")))); + assertThat( + result, + containsInRelativeOrder( + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprDateValue("2021-01-01"), "count(day)", 2)), + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprDateValue("2021-01-02"), "count(day)", 1)), + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprDateValue("2021-01-03"), "count(day)", 1)), + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprDateValue("2021-01-04"), "count(day)", 1)))); + + plan = + new AggregationOperator( + testScan(dateInputs), + Collections.singletonList(DSL.named("count", DSL.count(DSL.ref("month", DATE)))), + Collections.singletonList( + DSL.named("span", DSL.span(DSL.ref("month", DATE), DSL.literal(30), "d")))); result = execute(plan); assertEquals(3, result.size()); - assertThat(result, containsInRelativeOrder( - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprDateValue("2020-12-04"), "count", 1)), - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprDateValue("2021-02-02"), "count", 3)), - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprDateValue("2021-03-04"), "count", 1)) - )); + assertThat( + result, + containsInRelativeOrder( + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprDateValue("2020-12-04"), "count", 1)), + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprDateValue("2021-02-02"), "count", 3)), + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprDateValue("2021-03-04"), "count", 1)))); } @Test public void week_span() { - PhysicalPlan plan = new AggregationOperator(testScan(dateInputs), - Collections.singletonList(DSL - .named("count", DSL.count(DSL.ref("month", DATE)))), - Collections.singletonList(DSL - .named("span", DSL.span(DSL.ref("month", DATE), DSL.literal(5), "w")))); + PhysicalPlan plan = + new AggregationOperator( + testScan(dateInputs), + Collections.singletonList(DSL.named("count", DSL.count(DSL.ref("month", DATE)))), + Collections.singletonList( + DSL.named("span", DSL.span(DSL.ref("month", DATE), DSL.literal(5), "w")))); List result = execute(plan); assertEquals(3, result.size()); - assertThat(result, containsInRelativeOrder( - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprDateValue("2020-11-16"), "count", 1)), - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprDateValue("2021-01-25"), "count", 3)), - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprDateValue("2021-03-01"), "count", 1)) - )); + assertThat( + result, + containsInRelativeOrder( + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprDateValue("2020-11-16"), "count", 1)), + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprDateValue("2021-01-25"), "count", 3)), + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprDateValue("2021-03-01"), "count", 1)))); } @Test public void month_span() { - PhysicalPlan plan = new AggregationOperator(testScan(dateInputs), - Collections.singletonList(DSL - .named("count", DSL.count(DSL.ref("month", DATE)))), - Collections.singletonList(DSL - .named("span", DSL.span(DSL.ref("month", DATE), DSL.literal(1), "M")))); + PhysicalPlan plan = + new AggregationOperator( + testScan(dateInputs), + Collections.singletonList(DSL.named("count", DSL.count(DSL.ref("month", DATE)))), + Collections.singletonList( + DSL.named("span", DSL.span(DSL.ref("month", DATE), DSL.literal(1), "M")))); List result = execute(plan); assertEquals(3, result.size()); - assertThat(result, containsInRelativeOrder( - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprDateValue("2020-12-01"), "count", 1)), - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprDateValue("2021-02-01"), "count", 3)), - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprDateValue("2021-03-01"), "count", 1)) - )); - - plan = new AggregationOperator(testScan(dateInputs), - Collections.singletonList(DSL - .named("count", DSL.count(DSL.ref("quarter", DATETIME)))), - Collections.singletonList(DSL - .named("span", DSL.span(DSL.ref("quarter", DATETIME), DSL.literal(2), "M")))); + assertThat( + result, + containsInRelativeOrder( + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprDateValue("2020-12-01"), "count", 1)), + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprDateValue("2021-02-01"), "count", 3)), + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprDateValue("2021-03-01"), "count", 1)))); + + plan = + new AggregationOperator( + testScan(dateInputs), + Collections.singletonList(DSL.named("count", DSL.count(DSL.ref("quarter", DATETIME)))), + Collections.singletonList( + DSL.named("span", DSL.span(DSL.ref("quarter", DATETIME), DSL.literal(2), "M")))); result = execute(plan); assertEquals(4, result.size()); - assertThat(result, containsInRelativeOrder( - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprDatetimeValue("2020-09-01 00:00:00"), "count", 1)), - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprDatetimeValue("2020-11-01 00:00:00"), "count", 1)), - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprDatetimeValue("2021-01-01 00:00:00"), "count", 1)), - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprDatetimeValue("2021-05-01 00:00:00"), "count", 2)) - )); - - plan = new AggregationOperator(testScan(dateInputs), - Collections.singletonList(DSL - .named("count", DSL.count(DSL.ref("year", TIMESTAMP)))), - Collections.singletonList(DSL - .named("span", DSL.span(DSL.ref("year", TIMESTAMP), DSL.literal(10 * 12), "M")))); + assertThat( + result, + containsInRelativeOrder( + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprDatetimeValue("2020-09-01 00:00:00"), "count", 1)), + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprDatetimeValue("2020-11-01 00:00:00"), "count", 1)), + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprDatetimeValue("2021-01-01 00:00:00"), "count", 1)), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "span", new ExprDatetimeValue("2021-05-01 00:00:00"), "count", 2)))); + + plan = + new AggregationOperator( + testScan(dateInputs), + Collections.singletonList(DSL.named("count", DSL.count(DSL.ref("year", TIMESTAMP)))), + Collections.singletonList( + DSL.named( + "span", DSL.span(DSL.ref("year", TIMESTAMP), DSL.literal(10 * 12), "M")))); result = execute(plan); assertEquals(3, result.size()); - assertThat(result, containsInRelativeOrder( - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprTimestampValue("1990-01-01 00:00:00"), "count", 1)), - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprTimestampValue("2010-01-01 00:00:00"), "count", 3)), - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprTimestampValue("2020-01-01 00:00:00"), "count", 1)) - )); - + assertThat( + result, + containsInRelativeOrder( + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprTimestampValue("1990-01-01 00:00:00"), "count", 1)), + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprTimestampValue("2010-01-01 00:00:00"), "count", 3)), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "span", new ExprTimestampValue("2020-01-01 00:00:00"), "count", 1)))); } @Test public void quarter_span() { - PhysicalPlan plan = new AggregationOperator(testScan(dateInputs), - Collections.singletonList(DSL - .named("count", DSL.count(DSL.ref("quarter", DATETIME)))), - Collections.singletonList(DSL - .named("span", DSL.span(DSL.ref("quarter", DATETIME), DSL.literal(2), "q")))); + PhysicalPlan plan = + new AggregationOperator( + testScan(dateInputs), + Collections.singletonList(DSL.named("count", DSL.count(DSL.ref("quarter", DATETIME)))), + Collections.singletonList( + DSL.named("span", DSL.span(DSL.ref("quarter", DATETIME), DSL.literal(2), "q")))); List result = execute(plan); assertEquals(2, result.size()); - assertThat(result, containsInRelativeOrder( - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprDatetimeValue("2020-07-01 00:00:00"), "count", 2)), - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprDatetimeValue("2021-01-01 00:00:00"), "count", 3)) - )); - - plan = new AggregationOperator(testScan(dateInputs), - Collections.singletonList(DSL - .named("count", DSL.count(DSL.ref("year", TIMESTAMP)))), - Collections.singletonList(DSL - .named("span", DSL.span(DSL.ref("year", TIMESTAMP), DSL.literal(10 * 4), "q")))); + assertThat( + result, + containsInRelativeOrder( + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprDatetimeValue("2020-07-01 00:00:00"), "count", 2)), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "span", new ExprDatetimeValue("2021-01-01 00:00:00"), "count", 3)))); + + plan = + new AggregationOperator( + testScan(dateInputs), + Collections.singletonList(DSL.named("count", DSL.count(DSL.ref("year", TIMESTAMP)))), + Collections.singletonList( + DSL.named("span", DSL.span(DSL.ref("year", TIMESTAMP), DSL.literal(10 * 4), "q")))); result = execute(plan); assertEquals(3, result.size()); - assertThat(result, containsInRelativeOrder( - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprTimestampValue("1990-01-01 00:00:00"), "count", 1)), - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprTimestampValue("2010-01-01 00:00:00"), "count", 3)), - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprTimestampValue("2020-01-01 00:00:00"), "count", 1)) - )); + assertThat( + result, + containsInRelativeOrder( + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprTimestampValue("1990-01-01 00:00:00"), "count", 1)), + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprTimestampValue("2010-01-01 00:00:00"), "count", 3)), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "span", new ExprTimestampValue("2020-01-01 00:00:00"), "count", 1)))); } @Test public void year_span() { - PhysicalPlan plan = new AggregationOperator(testScan(dateInputs), - Collections.singletonList(DSL - .named("count", DSL.count(DSL.ref("year", TIMESTAMP)))), - Collections.singletonList(DSL - .named("span", DSL.span(DSL.ref("year", TIMESTAMP), DSL.literal(10), "y")))); + PhysicalPlan plan = + new AggregationOperator( + testScan(dateInputs), + Collections.singletonList(DSL.named("count", DSL.count(DSL.ref("year", TIMESTAMP)))), + Collections.singletonList( + DSL.named("span", DSL.span(DSL.ref("year", TIMESTAMP), DSL.literal(10), "y")))); List result = execute(plan); assertEquals(3, result.size()); - assertThat(result, containsInRelativeOrder( - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprTimestampValue("1990-01-01 00:00:00"), "count", 1)), - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprTimestampValue("2010-01-01 00:00:00"), "count", 3)), - ExprValueUtils.tupleValue(ImmutableMap - .of("span", new ExprTimestampValue("2020-01-01 00:00:00"), "count", 1)) - )); + assertThat( + result, + containsInRelativeOrder( + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprTimestampValue("1990-01-01 00:00:00"), "count", 1)), + ExprValueUtils.tupleValue( + ImmutableMap.of("span", new ExprTimestampValue("2010-01-01 00:00:00"), "count", 3)), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "span", new ExprTimestampValue("2020-01-01 00:00:00"), "count", 1)))); } @Test public void integer_field() { - PhysicalPlan plan = new AggregationOperator(testScan(numericInputs), - Collections.singletonList(DSL.named("count", DSL.count(DSL.ref("integer", INTEGER)))), - Collections.singletonList(DSL.named("span", DSL.span(DSL.ref("integer", INTEGER), DSL - .literal(1), "")))); + PhysicalPlan plan = + new AggregationOperator( + testScan(numericInputs), + Collections.singletonList(DSL.named("count", DSL.count(DSL.ref("integer", INTEGER)))), + Collections.singletonList( + DSL.named("span", DSL.span(DSL.ref("integer", INTEGER), DSL.literal(1), "")))); List result = execute(plan); assertEquals(3, result.size()); - assertThat(result, containsInRelativeOrder( - ExprValueUtils.tupleValue(ImmutableMap.of("span", 1, "count", 1)), - ExprValueUtils.tupleValue(ImmutableMap.of("span", 2, "count", 1)), - ExprValueUtils.tupleValue(ImmutableMap.of("span", 5, "count", 1)))); - - plan = new AggregationOperator(testScan(numericInputs), - Collections.singletonList(DSL.named("count", DSL.count(DSL.ref("integer", INTEGER)))), - Collections.singletonList(DSL.named("span", DSL.span(DSL.ref("integer", INTEGER), DSL - .literal(1.5), "")))); + assertThat( + result, + containsInRelativeOrder( + ExprValueUtils.tupleValue(ImmutableMap.of("span", 1, "count", 1)), + ExprValueUtils.tupleValue(ImmutableMap.of("span", 2, "count", 1)), + ExprValueUtils.tupleValue(ImmutableMap.of("span", 5, "count", 1)))); + + plan = + new AggregationOperator( + testScan(numericInputs), + Collections.singletonList(DSL.named("count", DSL.count(DSL.ref("integer", INTEGER)))), + Collections.singletonList( + DSL.named("span", DSL.span(DSL.ref("integer", INTEGER), DSL.literal(1.5), "")))); result = execute(plan); assertEquals(3, result.size()); - assertThat(result, containsInRelativeOrder( - ExprValueUtils.tupleValue(ImmutableMap.of("span", 0D, "count", 1)), - ExprValueUtils.tupleValue(ImmutableMap.of("span", 1.5D, "count", 1)), - ExprValueUtils.tupleValue(ImmutableMap.of("span", 4.5D, "count", 1)))); + assertThat( + result, + containsInRelativeOrder( + ExprValueUtils.tupleValue(ImmutableMap.of("span", 0D, "count", 1)), + ExprValueUtils.tupleValue(ImmutableMap.of("span", 1.5D, "count", 1)), + ExprValueUtils.tupleValue(ImmutableMap.of("span", 4.5D, "count", 1)))); } @Test public void long_field() { - PhysicalPlan plan = new AggregationOperator(testScan(numericInputs), - Collections.singletonList(DSL.named("count", DSL.count(DSL.ref("long", LONG)))), - Collections.singletonList(DSL.named("span", DSL.span(DSL.ref("long", LONG), DSL - .literal(1), "")))); + PhysicalPlan plan = + new AggregationOperator( + testScan(numericInputs), + Collections.singletonList(DSL.named("count", DSL.count(DSL.ref("long", LONG)))), + Collections.singletonList( + DSL.named("span", DSL.span(DSL.ref("long", LONG), DSL.literal(1), "")))); List result = execute(plan); assertEquals(3, result.size()); - assertThat(result, containsInRelativeOrder( - ExprValueUtils.tupleValue(ImmutableMap.of("span", 1L, "count", 1)), - ExprValueUtils.tupleValue(ImmutableMap.of("span", 2L, "count", 1)), - ExprValueUtils.tupleValue(ImmutableMap.of("span", 5L, "count", 1)))); - - plan = new AggregationOperator(testScan(numericInputs), - Collections.singletonList(DSL.named("count", DSL.count(DSL.ref("long", LONG)))), - Collections.singletonList(DSL.named("span", DSL.span(DSL.ref("long", LONG), DSL - .literal(1.5), "")))); + assertThat( + result, + containsInRelativeOrder( + ExprValueUtils.tupleValue(ImmutableMap.of("span", 1L, "count", 1)), + ExprValueUtils.tupleValue(ImmutableMap.of("span", 2L, "count", 1)), + ExprValueUtils.tupleValue(ImmutableMap.of("span", 5L, "count", 1)))); + + plan = + new AggregationOperator( + testScan(numericInputs), + Collections.singletonList(DSL.named("count", DSL.count(DSL.ref("long", LONG)))), + Collections.singletonList( + DSL.named("span", DSL.span(DSL.ref("long", LONG), DSL.literal(1.5), "")))); result = execute(plan); assertEquals(3, result.size()); - assertThat(result, containsInRelativeOrder( - ExprValueUtils.tupleValue(ImmutableMap.of("span", 0D, "count", 1)), - ExprValueUtils.tupleValue(ImmutableMap.of("span", 1.5D, "count", 1)), - ExprValueUtils.tupleValue(ImmutableMap.of("span", 4.5D, "count", 1)))); + assertThat( + result, + containsInRelativeOrder( + ExprValueUtils.tupleValue(ImmutableMap.of("span", 0D, "count", 1)), + ExprValueUtils.tupleValue(ImmutableMap.of("span", 1.5D, "count", 1)), + ExprValueUtils.tupleValue(ImmutableMap.of("span", 4.5D, "count", 1)))); } @Test public void float_field() { - PhysicalPlan plan = new AggregationOperator(testScan(numericInputs), - Collections.singletonList(DSL.named("count", DSL.count(DSL.ref("float", FLOAT)))), - Collections.singletonList(DSL.named("span", DSL.span(DSL.ref("float", FLOAT), DSL - .literal(1), "")))); + PhysicalPlan plan = + new AggregationOperator( + testScan(numericInputs), + Collections.singletonList(DSL.named("count", DSL.count(DSL.ref("float", FLOAT)))), + Collections.singletonList( + DSL.named("span", DSL.span(DSL.ref("float", FLOAT), DSL.literal(1), "")))); List result = execute(plan); assertEquals(3, result.size()); - assertThat(result, containsInRelativeOrder( - ExprValueUtils.tupleValue(ImmutableMap.of("span", 1F, "count", 1)), - ExprValueUtils.tupleValue(ImmutableMap.of("span", 2F, "count", 1)), - ExprValueUtils.tupleValue(ImmutableMap.of("span", 5F, "count", 1)))); - - plan = new AggregationOperator(testScan(numericInputs), - Collections.singletonList(DSL.named("count", DSL.count(DSL.ref("float", FLOAT)))), - Collections.singletonList(DSL.named("span", DSL.span(DSL.ref("float", FLOAT), DSL - .literal(1.5), "")))); + assertThat( + result, + containsInRelativeOrder( + ExprValueUtils.tupleValue(ImmutableMap.of("span", 1F, "count", 1)), + ExprValueUtils.tupleValue(ImmutableMap.of("span", 2F, "count", 1)), + ExprValueUtils.tupleValue(ImmutableMap.of("span", 5F, "count", 1)))); + + plan = + new AggregationOperator( + testScan(numericInputs), + Collections.singletonList(DSL.named("count", DSL.count(DSL.ref("float", FLOAT)))), + Collections.singletonList( + DSL.named("span", DSL.span(DSL.ref("float", FLOAT), DSL.literal(1.5), "")))); result = execute(plan); assertEquals(3, result.size()); - assertThat(result, containsInRelativeOrder( - ExprValueUtils.tupleValue(ImmutableMap.of("span", 0D, "count", 1)), - ExprValueUtils.tupleValue(ImmutableMap.of("span", 1.5D, "count", 1)), - ExprValueUtils.tupleValue(ImmutableMap.of("span", 4.5D, "count", 1)))); + assertThat( + result, + containsInRelativeOrder( + ExprValueUtils.tupleValue(ImmutableMap.of("span", 0D, "count", 1)), + ExprValueUtils.tupleValue(ImmutableMap.of("span", 1.5D, "count", 1)), + ExprValueUtils.tupleValue(ImmutableMap.of("span", 4.5D, "count", 1)))); } @Test public void double_field() { - PhysicalPlan plan = new AggregationOperator(testScan(numericInputs), - Collections.singletonList(DSL.named("count", DSL.count(DSL.ref("double", DOUBLE)))), - Collections.singletonList(DSL.named("span", DSL.span(DSL.ref("double", DOUBLE), DSL - .literal(1), "")))); + PhysicalPlan plan = + new AggregationOperator( + testScan(numericInputs), + Collections.singletonList(DSL.named("count", DSL.count(DSL.ref("double", DOUBLE)))), + Collections.singletonList( + DSL.named("span", DSL.span(DSL.ref("double", DOUBLE), DSL.literal(1), "")))); List result = execute(plan); assertEquals(3, result.size()); - assertThat(result, containsInRelativeOrder( - ExprValueUtils.tupleValue(ImmutableMap.of("span", 1D, "count", 1)), - ExprValueUtils.tupleValue(ImmutableMap.of("span", 2D, "count", 1)), - ExprValueUtils.tupleValue(ImmutableMap.of("span", 5D, "count", 1)))); - - plan = new AggregationOperator(testScan(numericInputs), - Collections.singletonList(DSL.named("count", DSL.count(DSL.ref("double", DOUBLE)))), - Collections.singletonList(DSL.named("span", DSL.span(DSL.ref("double", DOUBLE), DSL - .literal(1.5), "")))); + assertThat( + result, + containsInRelativeOrder( + ExprValueUtils.tupleValue(ImmutableMap.of("span", 1D, "count", 1)), + ExprValueUtils.tupleValue(ImmutableMap.of("span", 2D, "count", 1)), + ExprValueUtils.tupleValue(ImmutableMap.of("span", 5D, "count", 1)))); + + plan = + new AggregationOperator( + testScan(numericInputs), + Collections.singletonList(DSL.named("count", DSL.count(DSL.ref("double", DOUBLE)))), + Collections.singletonList( + DSL.named("span", DSL.span(DSL.ref("double", DOUBLE), DSL.literal(1.5), "")))); result = execute(plan); assertEquals(3, result.size()); - assertThat(result, containsInRelativeOrder( - ExprValueUtils.tupleValue(ImmutableMap.of("span", 0D, "count", 1)), - ExprValueUtils.tupleValue(ImmutableMap.of("span", 1.5D, "count", 1)), - ExprValueUtils.tupleValue(ImmutableMap.of("span", 4.5D, "count", 1)))); + assertThat( + result, + containsInRelativeOrder( + ExprValueUtils.tupleValue(ImmutableMap.of("span", 0D, "count", 1)), + ExprValueUtils.tupleValue(ImmutableMap.of("span", 1.5D, "count", 1)), + ExprValueUtils.tupleValue(ImmutableMap.of("span", 4.5D, "count", 1)))); } @Test public void twoBucketsSpanAndLong() { - PhysicalPlan plan = new AggregationOperator(testScan(compoundInputs), - Collections.singletonList(DSL.named("max", DSL.max(DSL.ref("errors", INTEGER)))), - Arrays.asList( - DSL.named("span", DSL.span(DSL.ref("day", DATE), DSL.literal(1), "d")), - DSL.named("region", DSL.ref("region", STRING))) - ); + PhysicalPlan plan = + new AggregationOperator( + testScan(compoundInputs), + Collections.singletonList(DSL.named("max", DSL.max(DSL.ref("errors", INTEGER)))), + Arrays.asList( + DSL.named("span", DSL.span(DSL.ref("day", DATE), DSL.literal(1), "d")), + DSL.named("region", DSL.ref("region", STRING)))); List result = execute(plan); assertEquals(4, result.size()); - assertThat(result, containsInRelativeOrder( - ExprValueUtils.tupleValue(ImmutableMap.of( - "span", new ExprDateValue("2021-01-03"), "region","iad", "max", 3)), - ExprValueUtils.tupleValue(ImmutableMap.of( - "span", new ExprDateValue("2021-01-04"), "region","iad", "max", 10)), - ExprValueUtils.tupleValue(ImmutableMap.of( - "span", new ExprDateValue("2021-01-06"), "region","iad", "max", 1)), - ExprValueUtils.tupleValue(ImmutableMap.of( - "span", new ExprDateValue("2021-01-07"), "region","iad", "max", 8)) - )); - - plan = new AggregationOperator(testScan(compoundInputs), - Collections.singletonList(DSL.named("max", DSL.max(DSL.ref("errors", INTEGER)))), - Arrays.asList( - DSL.named("span", DSL.span(DSL.ref("day", DATE), DSL.literal(1), "d")), - DSL.named("region", DSL.ref("region", STRING)), - DSL.named("host", DSL.ref("host", STRING))) - ); + assertThat( + result, + containsInRelativeOrder( + ExprValueUtils.tupleValue( + ImmutableMap.of( + "span", new ExprDateValue("2021-01-03"), "region", "iad", "max", 3)), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "span", new ExprDateValue("2021-01-04"), "region", "iad", "max", 10)), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "span", new ExprDateValue("2021-01-06"), "region", "iad", "max", 1)), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "span", new ExprDateValue("2021-01-07"), "region", "iad", "max", 8)))); + + plan = + new AggregationOperator( + testScan(compoundInputs), + Collections.singletonList(DSL.named("max", DSL.max(DSL.ref("errors", INTEGER)))), + Arrays.asList( + DSL.named("span", DSL.span(DSL.ref("day", DATE), DSL.literal(1), "d")), + DSL.named("region", DSL.ref("region", STRING)), + DSL.named("host", DSL.ref("host", STRING)))); result = execute(plan); assertEquals(7, result.size()); - assertThat(result, containsInRelativeOrder( - ExprValueUtils.tupleValue(ImmutableMap.of( - "span", new ExprDateValue("2021-01-03"), "region","iad", "host", "h1", "max", 2)), - ExprValueUtils.tupleValue(ImmutableMap.of( - "span", new ExprDateValue("2021-01-03"), "region","iad", "host", "h2", "max", 3)), - ExprValueUtils.tupleValue(ImmutableMap.of( - "span", new ExprDateValue("2021-01-04"), "region","iad", "host", "h1", "max", 1)), - ExprValueUtils.tupleValue(ImmutableMap.of( - "span", new ExprDateValue("2021-01-04"), "region","iad", "host", "h2", "max", 10)), - ExprValueUtils.tupleValue(ImmutableMap.of( - "span", new ExprDateValue("2021-01-06"), "region","iad", "host", "h1", "max", 1)), - ExprValueUtils.tupleValue(ImmutableMap.of( - "span", new ExprDateValue("2021-01-07"), "region","iad", "host", "h1", "max", 6)), - ExprValueUtils.tupleValue(ImmutableMap.of( - "span", new ExprDateValue("2021-01-07"), "region","iad", "host", "h2", "max", 8)) - )); + assertThat( + result, + containsInRelativeOrder( + ExprValueUtils.tupleValue( + ImmutableMap.of( + "span", + new ExprDateValue("2021-01-03"), + "region", + "iad", + "host", + "h1", + "max", + 2)), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "span", + new ExprDateValue("2021-01-03"), + "region", + "iad", + "host", + "h2", + "max", + 3)), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "span", + new ExprDateValue("2021-01-04"), + "region", + "iad", + "host", + "h1", + "max", + 1)), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "span", + new ExprDateValue("2021-01-04"), + "region", + "iad", + "host", + "h2", + "max", + 10)), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "span", + new ExprDateValue("2021-01-06"), + "region", + "iad", + "host", + "h1", + "max", + 1)), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "span", + new ExprDateValue("2021-01-07"), + "region", + "iad", + "host", + "h1", + "max", + 6)), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "span", + new ExprDateValue("2021-01-07"), + "region", + "iad", + "host", + "h2", + "max", + 8)))); } @Test public void aggregate_with_two_groups_with_windowing() { - PhysicalPlan plan = new AggregationOperator(testScan(compoundInputs), - Collections.singletonList(DSL.named("sum", DSL.sum(DSL.ref("errors", INTEGER)))), - Arrays.asList( - DSL.named("host", DSL.ref("host", STRING)), - DSL.named("span", DSL.span(DSL.ref("day", DATE), DSL.literal(1), "d")))); + PhysicalPlan plan = + new AggregationOperator( + testScan(compoundInputs), + Collections.singletonList(DSL.named("sum", DSL.sum(DSL.ref("errors", INTEGER)))), + Arrays.asList( + DSL.named("host", DSL.ref("host", STRING)), + DSL.named("span", DSL.span(DSL.ref("day", DATE), DSL.literal(1), "d")))); List result = execute(plan); assertEquals(7, result.size()); - assertThat(result, containsInRelativeOrder( - ExprValueUtils.tupleValue(ImmutableMap.of( - "host", new ExprStringValue("h1"), - "span", new ExprDateValue("2021-01-03"), - "sum", 2)), - ExprValueUtils.tupleValue(ImmutableMap.of( - "host", new ExprStringValue("h1"), - "span", new ExprDateValue("2021-01-04"), - "sum", 1)), - ExprValueUtils.tupleValue(ImmutableMap.of( - "host", new ExprStringValue("h1"), - "span", new ExprDateValue("2021-01-06"), - "sum", 1)), - ExprValueUtils.tupleValue(ImmutableMap.of( - "host", new ExprStringValue("h1"), - "span", new ExprDateValue("2021-01-07"), - "sum", 6)), - ExprValueUtils.tupleValue(ImmutableMap.of( - "host", new ExprStringValue("h2"), - "span", new ExprDateValue("2021-01-03"), - "sum", 3)), - ExprValueUtils.tupleValue(ImmutableMap.of( - "host", new ExprStringValue("h2"), - "span", new ExprDateValue("2021-01-04"), - "sum", 10)), - ExprValueUtils.tupleValue(ImmutableMap.of( - "host", new ExprStringValue("h2"), - "span", new ExprDateValue("2021-01-07"), - "sum", 8)))); + assertThat( + result, + containsInRelativeOrder( + ExprValueUtils.tupleValue( + ImmutableMap.of( + "host", new ExprStringValue("h1"), + "span", new ExprDateValue("2021-01-03"), + "sum", 2)), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "host", new ExprStringValue("h1"), + "span", new ExprDateValue("2021-01-04"), + "sum", 1)), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "host", new ExprStringValue("h1"), + "span", new ExprDateValue("2021-01-06"), + "sum", 1)), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "host", new ExprStringValue("h1"), + "span", new ExprDateValue("2021-01-07"), + "sum", 6)), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "host", new ExprStringValue("h2"), + "span", new ExprDateValue("2021-01-03"), + "sum", 3)), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "host", new ExprStringValue("h2"), + "span", new ExprDateValue("2021-01-04"), + "sum", 10)), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "host", new ExprStringValue("h2"), + "span", new ExprDateValue("2021-01-07"), + "sum", 8)))); } @Test public void aggregate_with_three_groups_with_windowing() { - PhysicalPlan plan = new AggregationOperator(testScan(compoundInputs), - Collections.singletonList(DSL.named("sum", DSL.sum(DSL.ref("errors", INTEGER)))), - Arrays.asList( - DSL.named("host", DSL.ref("host", STRING)), - DSL.named("span", DSL.span(DSL.ref("day", DATE), DSL.literal(1), "d")), - DSL.named("region", DSL.ref("region", STRING)))); + PhysicalPlan plan = + new AggregationOperator( + testScan(compoundInputs), + Collections.singletonList(DSL.named("sum", DSL.sum(DSL.ref("errors", INTEGER)))), + Arrays.asList( + DSL.named("host", DSL.ref("host", STRING)), + DSL.named("span", DSL.span(DSL.ref("day", DATE), DSL.literal(1), "d")), + DSL.named("region", DSL.ref("region", STRING)))); List result = execute(plan); assertEquals(7, result.size()); - assertThat(result, containsInRelativeOrder( - ExprValueUtils.tupleValue(ImmutableMap.of( - "host", new ExprStringValue("h1"), - "span", new ExprDateValue("2021-01-03"), - "region", new ExprStringValue("iad"), - "sum", 2)), - ExprValueUtils.tupleValue(ImmutableMap.of( - "host", new ExprStringValue("h1"), - "span", new ExprDateValue("2021-01-04"), - "region", new ExprStringValue("iad"), - "sum", 1)), - ExprValueUtils.tupleValue(ImmutableMap.of( - "host", new ExprStringValue("h1"), - "span", new ExprDateValue("2021-01-06"), - "region", new ExprStringValue("iad"), - "sum", 1)), - ExprValueUtils.tupleValue(ImmutableMap.of( - "host", new ExprStringValue("h1"), - "span", new ExprDateValue("2021-01-07"), - "region", new ExprStringValue("iad"), - "sum", 6)), - ExprValueUtils.tupleValue(ImmutableMap.of( - "host", new ExprStringValue("h2"), - "span", new ExprDateValue("2021-01-03"), - "region", new ExprStringValue("iad"), - "sum", 3)), - ExprValueUtils.tupleValue(ImmutableMap.of( - "host", new ExprStringValue("h2"), - "span", new ExprDateValue("2021-01-04"), - "region", new ExprStringValue("iad"), - "sum", 10)), - ExprValueUtils.tupleValue(ImmutableMap.of( - "host", new ExprStringValue("h2"), - "span", new ExprDateValue("2021-01-07"), - "region", new ExprStringValue("iad"), - "sum", 8)))); + assertThat( + result, + containsInRelativeOrder( + ExprValueUtils.tupleValue( + ImmutableMap.of( + "host", new ExprStringValue("h1"), + "span", new ExprDateValue("2021-01-03"), + "region", new ExprStringValue("iad"), + "sum", 2)), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "host", new ExprStringValue("h1"), + "span", new ExprDateValue("2021-01-04"), + "region", new ExprStringValue("iad"), + "sum", 1)), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "host", new ExprStringValue("h1"), + "span", new ExprDateValue("2021-01-06"), + "region", new ExprStringValue("iad"), + "sum", 1)), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "host", new ExprStringValue("h1"), + "span", new ExprDateValue("2021-01-07"), + "region", new ExprStringValue("iad"), + "sum", 6)), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "host", new ExprStringValue("h2"), + "span", new ExprDateValue("2021-01-03"), + "region", new ExprStringValue("iad"), + "sum", 3)), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "host", new ExprStringValue("h2"), + "span", new ExprDateValue("2021-01-04"), + "region", new ExprStringValue("iad"), + "sum", 10)), + ExprValueUtils.tupleValue( + ImmutableMap.of( + "host", new ExprStringValue("h2"), + "span", new ExprDateValue("2021-01-07"), + "region", new ExprStringValue("iad"), + "sum", 8)))); } @Test public void copyOfAggregationOperatorShouldSame() { - AggregationOperator plan = new AggregationOperator(testScan(datetimeInputs), - Collections.singletonList(DSL - .named("count", DSL.count(DSL.ref("second", TIMESTAMP)))), - Collections.singletonList(DSL - .named("span", DSL.span(DSL.ref("second", TIMESTAMP), DSL.literal(6 * 1000), "ms")))); - AggregationOperator copy = new AggregationOperator(plan.getInput(), plan.getAggregatorList(), - plan.getGroupByExprList()); + AggregationOperator plan = + new AggregationOperator( + testScan(datetimeInputs), + Collections.singletonList(DSL.named("count", DSL.count(DSL.ref("second", TIMESTAMP)))), + Collections.singletonList( + DSL.named( + "span", DSL.span(DSL.ref("second", TIMESTAMP), DSL.literal(6 * 1000), "ms")))); + AggregationOperator copy = + new AggregationOperator( + plan.getInput(), plan.getAggregatorList(), plan.getGroupByExprList()); assertEquals(plan, copy); } diff --git a/core/src/test/java/org/opensearch/sql/planner/physical/DedupeOperatorTest.java b/core/src/test/java/org/opensearch/sql/planner/physical/DedupeOperatorTest.java index 13f35f9843..f6308aed53 100644 --- a/core/src/test/java/org/opensearch/sql/planner/physical/DedupeOperatorTest.java +++ b/core/src/test/java/org/opensearch/sql/planner/physical/DedupeOperatorTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.planner.physical; import static org.hamcrest.MatcherAssert.assertThat; @@ -26,8 +25,7 @@ @ExtendWith(MockitoExtension.class) class DedupeOperatorTest extends PhysicalPlanTestBase { - @Mock - private PhysicalPlan inputPlan; + @Mock private PhysicalPlan inputPlan; /** * construct the map which contain null value, because {@link ImmutableMap} doesn't support null @@ -182,8 +180,7 @@ public void dedupe_one_field_with_missing_value() { tupleValue(ImmutableMap.of("region", "us-east-1", "action", "GET", "response", 200))) .thenReturn( tupleValue(ImmutableMap.of("region", "us-east-1", "action", "POST", "response", 200))) - .thenReturn( - tupleValue(ImmutableMap.of("action", "POST", "response", 200))) + .thenReturn(tupleValue(ImmutableMap.of("action", "POST", "response", 200))) .thenReturn( tupleValue(ImmutableMap.of("region", "us-east-1", "action", "GET", "response", 200))); @@ -201,8 +198,7 @@ public void dedupe_one_field_with_missing_value_keep_empty() { tupleValue(ImmutableMap.of("region", "us-east-1", "action", "GET", "response", 200))) .thenReturn( tupleValue(ImmutableMap.of("region", "us-east-1", "action", "POST", "response", 200))) - .thenReturn( - tupleValue(ImmutableMap.of("action", "POST", "response", 200))) + .thenReturn(tupleValue(ImmutableMap.of("action", "POST", "response", 200))) .thenReturn( tupleValue(ImmutableMap.of("region", "us-east-1", "action", "GET", "response", 200))); @@ -221,8 +217,7 @@ public void dedupe_one_field_with_null_value() { tupleValue(ImmutableMap.of("region", "us-east-1", "action", "GET", "response", 200))) .thenReturn( tupleValue(ImmutableMap.of("region", "us-east-1", "action", "POST", "response", 200))) - .thenReturn( - tupleValue(NULL_MAP)) + .thenReturn(tupleValue(NULL_MAP)) .thenReturn( tupleValue(ImmutableMap.of("region", "us-east-1", "action", "GET", "response", 200))); diff --git a/core/src/test/java/org/opensearch/sql/planner/physical/EvalOperatorTest.java b/core/src/test/java/org/opensearch/sql/planner/physical/EvalOperatorTest.java index d32622834b..6f10cc435b 100644 --- a/core/src/test/java/org/opensearch/sql/planner/physical/EvalOperatorTest.java +++ b/core/src/test/java/org/opensearch/sql/planner/physical/EvalOperatorTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.planner.physical; import static org.hamcrest.MatcherAssert.assertThat; @@ -29,8 +28,7 @@ @ExtendWith(MockitoExtension.class) class EvalOperatorTest extends PhysicalPlanTestBase { - @Mock - private PhysicalPlan inputPlan; + @Mock private PhysicalPlan inputPlan; @Test public void create_new_field_that_contain_the_result_of_a_calculation() { @@ -63,8 +61,8 @@ public void create_multiple_field_using_field_defined_in_input_tuple() { eval( inputPlan, ImmutablePair.of( - DSL.ref("velocity", DOUBLE), DSL.divide(DSL.ref("distance", INTEGER), DSL.ref( - "time", INTEGER))), + DSL.ref("velocity", DOUBLE), + DSL.divide(DSL.ref("distance", INTEGER), DSL.ref("time", INTEGER))), ImmutablePair.of( DSL.ref("doubleDistance", INTEGER), DSL.multiply(DSL.ref("distance", INTEGER), DSL.literal(2)))); @@ -88,8 +86,8 @@ public void create_multiple_filed_using_field_defined_in_eval_operator() { eval( inputPlan, ImmutablePair.of( - DSL.ref("velocity", INTEGER), DSL.divide(DSL.ref("distance", INTEGER), DSL.ref( - "time", INTEGER))), + DSL.ref("velocity", INTEGER), + DSL.divide(DSL.ref("distance", INTEGER), DSL.ref("time", INTEGER))), ImmutablePair.of( DSL.ref("doubleVelocity", INTEGER), DSL.multiply(DSL.ref("velocity", INTEGER), DSL.literal(2)))); @@ -126,8 +124,8 @@ public void replace_existing_field() { public void do_nothing_with_none_tuple_value() { when(inputPlan.hasNext()).thenReturn(true, false); when(inputPlan.next()).thenReturn(ExprValueUtils.integerValue(1)); - PhysicalPlan plan = eval(inputPlan, ImmutablePair.of(DSL.ref("response", INTEGER), - DSL.ref("referer", STRING))); + PhysicalPlan plan = + eval(inputPlan, ImmutablePair.of(DSL.ref("response", INTEGER), DSL.ref("referer", STRING))); List result = execute(plan); assertThat(result, allOf(iterableWithSize(1), hasItems(ExprValueUtils.integerValue(1)))); diff --git a/core/src/test/java/org/opensearch/sql/planner/physical/FilterOperatorTest.java b/core/src/test/java/org/opensearch/sql/planner/physical/FilterOperatorTest.java index 66ca2de157..bfe3b323c4 100644 --- a/core/src/test/java/org/opensearch/sql/planner/physical/FilterOperatorTest.java +++ b/core/src/test/java/org/opensearch/sql/planner/physical/FilterOperatorTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.planner.physical; import static org.hamcrest.MatcherAssert.assertThat; @@ -31,20 +30,31 @@ @ExtendWith(MockitoExtension.class) @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) class FilterOperatorTest extends PhysicalPlanTestBase { - @Mock - private PhysicalPlan inputPlan; + @Mock private PhysicalPlan inputPlan; @Test public void filter_test() { - FilterOperator plan = new FilterOperator(new TestScan(), - DSL.and(DSL.notequal(DSL.ref("response", INTEGER), DSL.literal(200)), + FilterOperator plan = + new FilterOperator( + new TestScan(), + DSL.and( + DSL.notequal(DSL.ref("response", INTEGER), DSL.literal(200)), DSL.notequal(DSL.ref("response", INTEGER), DSL.literal(500)))); List result = execute(plan); assertEquals(1, result.size()); - assertThat(result, containsInAnyOrder(ExprValueUtils - .tupleValue(ImmutableMap - .of("ip", "209.160.24.63", "action", "GET", "response", 404, "referer", - "www.amazon.com")))); + assertThat( + result, + containsInAnyOrder( + ExprValueUtils.tupleValue( + ImmutableMap.of( + "ip", + "209.160.24.63", + "action", + "GET", + "response", + 404, + "referer", + "www.amazon.com")))); } @Test @@ -54,8 +64,8 @@ public void null_value_should_been_ignored() { when(inputPlan.hasNext()).thenReturn(true, false); when(inputPlan.next()).thenReturn(new ExprTupleValue(value)); - FilterOperator plan = new FilterOperator(inputPlan, - DSL.equal(DSL.ref("response", INTEGER), DSL.literal(404))); + FilterOperator plan = + new FilterOperator(inputPlan, DSL.equal(DSL.ref("response", INTEGER), DSL.literal(404))); List result = execute(plan); assertEquals(0, result.size()); } @@ -67,8 +77,8 @@ public void missing_value_should_been_ignored() { when(inputPlan.hasNext()).thenReturn(true, false); when(inputPlan.next()).thenReturn(new ExprTupleValue(value)); - FilterOperator plan = new FilterOperator(inputPlan, - DSL.equal(DSL.ref("response", INTEGER), DSL.literal(404))); + FilterOperator plan = + new FilterOperator(inputPlan, DSL.equal(DSL.ref("response", INTEGER), DSL.literal(404))); List result = execute(plan); assertEquals(0, result.size()); } diff --git a/core/src/test/java/org/opensearch/sql/planner/physical/LimitOperatorTest.java b/core/src/test/java/org/opensearch/sql/planner/physical/LimitOperatorTest.java index a9796bb11a..fa3788cc2d 100644 --- a/core/src/test/java/org/opensearch/sql/planner/physical/LimitOperatorTest.java +++ b/core/src/test/java/org/opensearch/sql/planner/physical/LimitOperatorTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.planner.physical; import static org.hamcrest.MatcherAssert.assertThat; @@ -23,10 +22,19 @@ public void limit() { PhysicalPlan plan = new LimitOperator(new TestScan(), 1, 0); List result = execute(plan); assertEquals(1, result.size()); - assertThat(result, containsInAnyOrder( - ExprValueUtils.tupleValue(ImmutableMap.of( - "ip", "209.160.24.63", "action", "GET", "response", 200, "referer", "www.amazon.com")) - )); + assertThat( + result, + containsInAnyOrder( + ExprValueUtils.tupleValue( + ImmutableMap.of( + "ip", + "209.160.24.63", + "action", + "GET", + "response", + 200, + "referer", + "www.amazon.com")))); } @Test @@ -34,15 +42,24 @@ public void limit_and_offset() { PhysicalPlan plan = new LimitOperator(new TestScan(), 1, 1); List result = execute(plan); assertEquals(1, result.size()); - assertThat(result, containsInAnyOrder( - ExprValueUtils.tupleValue(ImmutableMap.of( - "ip", "209.160.24.63", "action", "GET", "response", 404, "referer", "www.amazon.com")) - )); + assertThat( + result, + containsInAnyOrder( + ExprValueUtils.tupleValue( + ImmutableMap.of( + "ip", + "209.160.24.63", + "action", + "GET", + "response", + 404, + "referer", + "www.amazon.com")))); } @Test public void offset_exceeds_row_number() { - PhysicalPlan plan = new LimitOperator(new TestScan(),1, 6); + PhysicalPlan plan = new LimitOperator(new TestScan(), 1, 6); List result = execute(plan); assertEquals(0, result.size()); } diff --git a/core/src/test/java/org/opensearch/sql/planner/physical/NestedOperatorTest.java b/core/src/test/java/org/opensearch/sql/planner/physical/NestedOperatorTest.java index 5b3744c401..cf98183eb3 100644 --- a/core/src/test/java/org/opensearch/sql/planner/physical/NestedOperatorTest.java +++ b/core/src/test/java/org/opensearch/sql/planner/physical/NestedOperatorTest.java @@ -28,68 +28,40 @@ @ExtendWith(MockitoExtension.class) class NestedOperatorTest extends PhysicalPlanTestBase { - @Mock - private PhysicalPlan inputPlan; + @Mock private PhysicalPlan inputPlan; - private final ExprValue testData = tupleValue( - Map.of( - "message", - collectionValue( - List.of( - Map.of("info", "a"), - Map.of("info", "b"), - Map.of("info", "c") - ) - ), - "comment", - collectionValue( - List.of( - Map.of("data", "1"), - Map.of("data", "2"), - Map.of("data", "3") - ) - ) - ) - ); + private final ExprValue testData = + tupleValue( + Map.of( + "message", + collectionValue( + List.of(Map.of("info", "a"), Map.of("info", "b"), Map.of("info", "c"))), + "comment", + collectionValue( + List.of(Map.of("data", "1"), Map.of("data", "2"), Map.of("data", "3"))))); + private final ExprValue testDataWithSamePath = + tupleValue( + Map.of( + "message", + collectionValue( + List.of( + Map.of("info", "a", "id", "1"), + Map.of("info", "b", "id", "2"), + Map.of("info", "c", "id", "3"))))); - private final ExprValue testDataWithSamePath = tupleValue( - Map.of( - "message", - collectionValue( - List.of( - Map.of("info", "a", "id", "1"), - Map.of("info", "b", "id", "2"), - Map.of("info", "c", "id", "3") - ) - ) - ) - ); + private final ExprValue nonNestedTestData = tupleValue(Map.of("message", "val")); - private final ExprValue nonNestedTestData = tupleValue( - Map.of( - "message", "val" - ) - ); - - private final ExprValue missingArrayData = tupleValue( - Map.of( - "missing", - collectionValue( - List.of("value") - ) - ) - ); + private final ExprValue missingArrayData = + tupleValue(Map.of("missing", collectionValue(List.of("value")))); @Test public void nested_one_nested_field() { when(inputPlan.hasNext()).thenReturn(true, false); - when(inputPlan.next()) - .thenReturn(testData); + when(inputPlan.next()).thenReturn(testData); Set fields = Set.of("message.info"); - Map> groupedFieldsByPath = - Map.of("message", List.of("message.info")); + Map> groupedFieldsByPath = Map.of("message", List.of("message.info")); var nested = new NestedOperator(inputPlan, fields, groupedFieldsByPath); @@ -97,77 +69,104 @@ public void nested_one_nested_field() { execute(nested), contains( tupleValue( - new LinkedHashMap<>() {{ - put("message.info", "a"); - put("comment", collectionValue( - new ArrayList<>() {{ - add(new LinkedHashMap<>() {{ - put("data", "1"); - }} - ); - add(new LinkedHashMap<>() {{ - put("data", "2"); - }} - ); - add(new LinkedHashMap<>() {{ - put("data", "3"); - }} - ); - }} - )); - }} - ), + new LinkedHashMap<>() { + { + put("message.info", "a"); + put( + "comment", + collectionValue( + new ArrayList<>() { + { + add( + new LinkedHashMap<>() { + { + put("data", "1"); + } + }); + add( + new LinkedHashMap<>() { + { + put("data", "2"); + } + }); + add( + new LinkedHashMap<>() { + { + put("data", "3"); + } + }); + } + })); + } + }), tupleValue( - new LinkedHashMap<>() {{ - put("message.info", "b"); - put("comment", collectionValue( - new ArrayList<>() {{ - add(new LinkedHashMap<>() {{ - put("data", "1"); - }} - ); - add(new LinkedHashMap<>() {{ - put("data", "2"); - }} - ); - add(new LinkedHashMap<>() {{ - put("data", "3"); - }} - ); - }} - )); - }} - ), + new LinkedHashMap<>() { + { + put("message.info", "b"); + put( + "comment", + collectionValue( + new ArrayList<>() { + { + add( + new LinkedHashMap<>() { + { + put("data", "1"); + } + }); + add( + new LinkedHashMap<>() { + { + put("data", "2"); + } + }); + add( + new LinkedHashMap<>() { + { + put("data", "3"); + } + }); + } + })); + } + }), tupleValue( - new LinkedHashMap<>() {{ - put("message.info", "c"); - put("comment", collectionValue( - new ArrayList<>() {{ - add(new LinkedHashMap<>() {{ - put("data", "1"); - }} - ); - add(new LinkedHashMap<>() {{ - put("data", "2"); - }} - ); - add(new LinkedHashMap<>() {{ - put("data", "3"); - }} - ); - }} - )); - }} - ) - ) - ); + new LinkedHashMap<>() { + { + put("message.info", "c"); + put( + "comment", + collectionValue( + new ArrayList<>() { + { + add( + new LinkedHashMap<>() { + { + put("data", "1"); + } + }); + add( + new LinkedHashMap<>() { + { + put("data", "2"); + } + }); + add( + new LinkedHashMap<>() { + { + put("data", "3"); + } + }); + } + })); + } + }))); } @Test public void nested_two_nested_field() { when(inputPlan.hasNext()).thenReturn(true, false); - when(inputPlan.next()) - .thenReturn(testData); + when(inputPlan.next()).thenReturn(testData); List> fields = List.of( @@ -176,76 +175,81 @@ public void nested_two_nested_field() { "path", new ReferenceExpression("message", STRING)), Map.of( "field", new ReferenceExpression("comment.data", STRING), - "path", new ReferenceExpression("comment", STRING)) - ); + "path", new ReferenceExpression("comment", STRING))); var nested = new NestedOperator(inputPlan, fields); assertThat( execute(nested), contains( tupleValue( - new LinkedHashMap<>() {{ - put("message.info", "a"); - put("comment.data", "1"); - }} - ), + new LinkedHashMap<>() { + { + put("message.info", "a"); + put("comment.data", "1"); + } + }), tupleValue( - new LinkedHashMap<>() {{ - put("message.info", "a"); - put("comment.data", "2"); - }} - ), + new LinkedHashMap<>() { + { + put("message.info", "a"); + put("comment.data", "2"); + } + }), tupleValue( - new LinkedHashMap<>() {{ - put("message.info", "a"); - put("comment.data", "3"); - }} - ), + new LinkedHashMap<>() { + { + put("message.info", "a"); + put("comment.data", "3"); + } + }), tupleValue( - new LinkedHashMap<>() {{ - put("message.info", "b"); - put("comment.data", "1"); - }} - ), + new LinkedHashMap<>() { + { + put("message.info", "b"); + put("comment.data", "1"); + } + }), tupleValue( - new LinkedHashMap<>() {{ - put("message.info", "b"); - put("comment.data", "2"); - }} - ), + new LinkedHashMap<>() { + { + put("message.info", "b"); + put("comment.data", "2"); + } + }), tupleValue( - new LinkedHashMap<>() {{ - put("message.info", "b"); - put("comment.data", "3"); - }} - ), + new LinkedHashMap<>() { + { + put("message.info", "b"); + put("comment.data", "3"); + } + }), tupleValue( - new LinkedHashMap<>() {{ - put("message.info", "c"); - put("comment.data", "1"); - }} - ), + new LinkedHashMap<>() { + { + put("message.info", "c"); + put("comment.data", "1"); + } + }), tupleValue( - new LinkedHashMap<>() {{ - put("message.info", "c"); - put("comment.data", "2"); - }} - ), + new LinkedHashMap<>() { + { + put("message.info", "c"); + put("comment.data", "2"); + } + }), tupleValue( - new LinkedHashMap<>() {{ - put("message.info", "c"); - put("comment.data", "3"); - }} - ) - ) - ); + new LinkedHashMap<>() { + { + put("message.info", "c"); + put("comment.data", "3"); + } + }))); } @Test public void nested_two_nested_fields_with_same_path() { when(inputPlan.hasNext()).thenReturn(true, false); - when(inputPlan.next()) - .thenReturn(testDataWithSamePath); + when(inputPlan.next()).thenReturn(testDataWithSamePath); List> fields = List.of( @@ -254,85 +258,69 @@ public void nested_two_nested_fields_with_same_path() { "path", new ReferenceExpression("message", STRING)), Map.of( "field", new ReferenceExpression("message.id", STRING), - "path", new ReferenceExpression("message", STRING)) - ); + "path", new ReferenceExpression("message", STRING))); var nested = new NestedOperator(inputPlan, fields); assertThat( execute(nested), contains( tupleValue( - new LinkedHashMap<>() {{ - put("message.info", "a"); - put("message.id", "1"); - }} - ), + new LinkedHashMap<>() { + { + put("message.info", "a"); + put("message.id", "1"); + } + }), tupleValue( - new LinkedHashMap<>() {{ - put("message.info", "b"); - put("message.id", "2"); - }} - ), + new LinkedHashMap<>() { + { + put("message.info", "b"); + put("message.id", "2"); + } + }), tupleValue( - new LinkedHashMap<>() {{ - put("message.info", "c"); - put("message.id", "3"); - }} - ) - ) - ); + new LinkedHashMap<>() { + { + put("message.info", "c"); + put("message.id", "3"); + } + }))); } @Test public void non_nested_field_tests() { when(inputPlan.hasNext()).thenReturn(true, false); - when(inputPlan.next()) - .thenReturn(nonNestedTestData); + when(inputPlan.next()).thenReturn(nonNestedTestData); Set fields = Set.of("message"); - Map> groupedFieldsByPath = - Map.of("message", List.of("message.info")); + Map> groupedFieldsByPath = Map.of("message", List.of("message.info")); var nested = new NestedOperator(inputPlan, fields, groupedFieldsByPath); assertThat( - execute(nested), - contains( - tupleValue(new LinkedHashMap<>(Map.of("message", "val"))) - ) - ); + execute(nested), contains(tupleValue(new LinkedHashMap<>(Map.of("message", "val"))))); } @Test public void nested_missing_tuple_field() { when(inputPlan.hasNext()).thenReturn(true, false); - when(inputPlan.next()) - .thenReturn(tupleValue(Map.of())); + when(inputPlan.next()).thenReturn(tupleValue(Map.of())); Set fields = Set.of("message.val"); - Map> groupedFieldsByPath = - Map.of("message", List.of("message.val")); + Map> groupedFieldsByPath = Map.of("message", List.of("message.val")); var nested = new NestedOperator(inputPlan, fields, groupedFieldsByPath); assertThat( execute(nested), - contains( - tupleValue(new LinkedHashMap<>(Map.of("message.val", ExprNullValue.of()))) - ) - ); + contains(tupleValue(new LinkedHashMap<>(Map.of("message.val", ExprNullValue.of()))))); } @Test public void nested_missing_array_field() { when(inputPlan.hasNext()).thenReturn(true, false); - when(inputPlan.next()) - .thenReturn(missingArrayData); + when(inputPlan.next()).thenReturn(missingArrayData); Set fields = Set.of("missing.data"); - Map> groupedFieldsByPath = - Map.of("message", List.of("message.data")); + Map> groupedFieldsByPath = Map.of("message", List.of("message.data")); var nested = new NestedOperator(inputPlan, fields, groupedFieldsByPath); - assertEquals(0, execute(nested) - .get(0) - .tupleValue() - .size()); + assertEquals(0, execute(nested).get(0).tupleValue().size()); } } diff --git a/core/src/test/java/org/opensearch/sql/planner/physical/PhysicalPlanNodeVisitorTest.java b/core/src/test/java/org/opensearch/sql/planner/physical/PhysicalPlanNodeVisitorTest.java index 8ed4881d33..c91ae8787c 100644 --- a/core/src/test/java/org/opensearch/sql/planner/physical/PhysicalPlanNodeVisitorTest.java +++ b/core/src/test/java/org/opensearch/sql/planner/physical/PhysicalPlanNodeVisitorTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.planner.physical; import static java.util.Collections.emptyList; @@ -49,16 +48,12 @@ import org.opensearch.sql.expression.ReferenceExpression; import org.opensearch.sql.expression.window.WindowDefinition; -/** - * Todo, testing purpose, delete later. - */ +/** Todo, testing purpose, delete later. */ @ExtendWith(MockitoExtension.class) @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) class PhysicalPlanNodeVisitorTest extends PhysicalPlanTestBase { - @Mock - PhysicalPlan plan; - @Mock - ReferenceExpression ref; + @Mock PhysicalPlan plan; + @Mock ReferenceExpression ref; @Test public void print_physical_plan() { @@ -69,16 +64,13 @@ public void print_physical_plan() { agg( rareTopN( filter( - limit( - new TestScan(), - 1, 1 - ), + limit(new TestScan(), 1, 1), DSL.equal(DSL.ref("response", INTEGER), DSL.literal(10))), CommandType.TOP, ImmutableList.of(), DSL.ref("response", INTEGER)), - ImmutableList - .of(DSL.named("avg(response)", DSL.avg(DSL.ref("response", INTEGER)))), + ImmutableList.of( + DSL.named("avg(response)", DSL.avg(DSL.ref("response", INTEGER)))), ImmutableList.of()), ImmutableMap.of(DSL.ref("ivalue", INTEGER), DSL.ref("avg(response)", DOUBLE))), named("ref", ref)), @@ -104,17 +96,20 @@ public static Stream getPhysicalPlanForTest() { filter(new TestScan(), DSL.equal(DSL.ref("response", INTEGER), DSL.literal(10))); PhysicalPlan aggregation = - agg(filter, ImmutableList.of(DSL.named("avg(response)", - DSL.avg(DSL.ref("response", INTEGER)))), ImmutableList.of()); + agg( + filter, + ImmutableList.of(DSL.named("avg(response)", DSL.avg(DSL.ref("response", INTEGER)))), + ImmutableList.of()); PhysicalPlan rename = - rename(aggregation, ImmutableMap.of(DSL.ref("ivalue", INTEGER), DSL.ref("avg(response)", - DOUBLE))); + rename( + aggregation, + ImmutableMap.of(DSL.ref("ivalue", INTEGER), DSL.ref("avg(response)", DOUBLE))); PhysicalPlan project = project(plan, named("ref", ref)); - PhysicalPlan window = window(plan, named(DSL.rowNumber()), - new WindowDefinition(emptyList(), emptyList())); + PhysicalPlan window = + window(plan, named(DSL.rowNumber()), new WindowDefinition(emptyList(), emptyList())); PhysicalPlan remove = remove(plan, ref); @@ -136,26 +131,33 @@ public static Stream getPhysicalPlanForTest() { PhysicalPlan cursorClose = new CursorCloseOperator(plan); - return Stream.of(Arguments.of(filter, "filter"), Arguments.of(aggregation, "aggregation"), - Arguments.of(rename, "rename"), Arguments.of(project, "project"), - Arguments.of(window, "window"), Arguments.of(remove, "remove"), - Arguments.of(eval, "eval"), Arguments.of(sort, "sort"), Arguments.of(dedupe, "dedupe"), - Arguments.of(values, "values"), Arguments.of(rareTopN, "rareTopN"), - Arguments.of(limit, "limit"), Arguments.of(nested, "nested"), + return Stream.of( + Arguments.of(filter, "filter"), + Arguments.of(aggregation, "aggregation"), + Arguments.of(rename, "rename"), + Arguments.of(project, "project"), + Arguments.of(window, "window"), + Arguments.of(remove, "remove"), + Arguments.of(eval, "eval"), + Arguments.of(sort, "sort"), + Arguments.of(dedupe, "dedupe"), + Arguments.of(values, "values"), + Arguments.of(rareTopN, "rareTopN"), + Arguments.of(limit, "limit"), + Arguments.of(nested, "nested"), Arguments.of(cursorClose, "cursorClose")); } @ParameterizedTest(name = "{1}") @MethodSource("getPhysicalPlanForTest") public void test_PhysicalPlanVisitor_should_return_null(PhysicalPlan plan, String name) { - assertNull(plan.accept(new PhysicalPlanNodeVisitor() { - }, null)); + assertNull(plan.accept(new PhysicalPlanNodeVisitor() {}, null)); } @Test public void test_visitMLCommons() { PhysicalPlanNodeVisitor physicalPlanNodeVisitor = - new PhysicalPlanNodeVisitor() {}; + new PhysicalPlanNodeVisitor() {}; assertNull(physicalPlanNodeVisitor.visitMLCommons(plan, null)); } @@ -163,7 +165,7 @@ public void test_visitMLCommons() { @Test public void test_visitAD() { PhysicalPlanNodeVisitor physicalPlanNodeVisitor = - new PhysicalPlanNodeVisitor() {}; + new PhysicalPlanNodeVisitor() {}; assertNull(physicalPlanNodeVisitor.visitAD(plan, null)); } @@ -171,7 +173,7 @@ public void test_visitAD() { @Test public void test_visitML() { PhysicalPlanNodeVisitor physicalPlanNodeVisitor = - new PhysicalPlanNodeVisitor() {}; + new PhysicalPlanNodeVisitor() {}; assertNull(physicalPlanNodeVisitor.visitML(plan, null)); } diff --git a/core/src/test/java/org/opensearch/sql/planner/physical/PhysicalPlanTest.java b/core/src/test/java/org/opensearch/sql/planner/physical/PhysicalPlanTest.java index 1e42857205..d63ab35773 100644 --- a/core/src/test/java/org/opensearch/sql/planner/physical/PhysicalPlanTest.java +++ b/core/src/test/java/org/opensearch/sql/planner/physical/PhysicalPlanTest.java @@ -20,33 +20,32 @@ @ExtendWith(MockitoExtension.class) @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) class PhysicalPlanTest { - @Mock - Split split; - - @Mock - PhysicalPlan child; - - private PhysicalPlan testPlan = new PhysicalPlan() { - @Override - public R accept(PhysicalPlanNodeVisitor visitor, C context) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean hasNext() { - throw new UnsupportedOperationException(); - } - - @Override - public ExprValue next() { - throw new UnsupportedOperationException(); - } - - @Override - public List getChild() { - return List.of(child); - } - }; + @Mock Split split; + + @Mock PhysicalPlan child; + + private PhysicalPlan testPlan = + new PhysicalPlan() { + @Override + public R accept(PhysicalPlanNodeVisitor visitor, C context) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean hasNext() { + throw new UnsupportedOperationException(); + } + + @Override + public ExprValue next() { + throw new UnsupportedOperationException(); + } + + @Override + public List getChild() { + return List.of(child); + } + }; @Test void add_split_to_child_by_default() { diff --git a/core/src/test/java/org/opensearch/sql/planner/physical/PhysicalPlanTestBase.java b/core/src/test/java/org/opensearch/sql/planner/physical/PhysicalPlanTestBase.java index 60d97f159a..003e59959f 100644 --- a/core/src/test/java/org/opensearch/sql/planner/physical/PhysicalPlanTestBase.java +++ b/core/src/test/java/org/opensearch/sql/planner/physical/PhysicalPlanTestBase.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.planner.physical; import com.google.common.collect.ImmutableList; @@ -29,47 +28,71 @@ public class PhysicalPlanTestBase { - protected static final List countTestInputs = new ImmutableList.Builder() - .add(ExprValueUtils.tupleValue(ImmutableMap - .of("id", 1, "testString", "asdf"))) - .add(ExprValueUtils.tupleValue(ImmutableMap - .of("id", 2, "testString", "asdf"))) - .add(ExprValueUtils.tupleValue(ImmutableMap - .of("id", 3, "testString", "asdf"))) - .add(ExprValueUtils.tupleValue(ImmutableMap - .of("id", 4, "testString", "asdf"))) - .add(ExprValueUtils.tupleValue(ImmutableMap - .of("id", 5, "testString", "asdf"))) - .add(ExprValueUtils.tupleValue(ImmutableMap - .of("id", 6, "testString", "asdf"))) - .add(ExprValueUtils.tupleValue(ImmutableMap - .of("id", 7, "testString", "asdf"))) - .add(ExprValueUtils.tupleValue(ImmutableMap - .of("id", 8, "testString", "asdf"))) - .add(ExprValueUtils.tupleValue(ImmutableMap - .of("id", 9, "testString", "asdf"))) - .add(ExprValueUtils.tupleValue(ImmutableMap - .of("id", 10, "testString", "asdf"))) - .add(ExprValueUtils.tupleValue(ImmutableMap - .of("id", 11, "testString", "asdf"))) + protected static final List countTestInputs = + new ImmutableList.Builder() + .add(ExprValueUtils.tupleValue(ImmutableMap.of("id", 1, "testString", "asdf"))) + .add(ExprValueUtils.tupleValue(ImmutableMap.of("id", 2, "testString", "asdf"))) + .add(ExprValueUtils.tupleValue(ImmutableMap.of("id", 3, "testString", "asdf"))) + .add(ExprValueUtils.tupleValue(ImmutableMap.of("id", 4, "testString", "asdf"))) + .add(ExprValueUtils.tupleValue(ImmutableMap.of("id", 5, "testString", "asdf"))) + .add(ExprValueUtils.tupleValue(ImmutableMap.of("id", 6, "testString", "asdf"))) + .add(ExprValueUtils.tupleValue(ImmutableMap.of("id", 7, "testString", "asdf"))) + .add(ExprValueUtils.tupleValue(ImmutableMap.of("id", 8, "testString", "asdf"))) + .add(ExprValueUtils.tupleValue(ImmutableMap.of("id", 9, "testString", "asdf"))) + .add(ExprValueUtils.tupleValue(ImmutableMap.of("id", 10, "testString", "asdf"))) + .add(ExprValueUtils.tupleValue(ImmutableMap.of("id", 11, "testString", "asdf"))) .build(); - protected static final List inputs = new ImmutableList.Builder() - .add(ExprValueUtils.tupleValue(ImmutableMap - .of("ip", "209.160.24.63", "action", "GET", "response", 200, "referer", - "www.amazon.com"))) - .add(ExprValueUtils.tupleValue(ImmutableMap - .of("ip", "209.160.24.63", "action", "GET", "response", 404, "referer", - "www.amazon.com"))) - .add(ExprValueUtils.tupleValue(ImmutableMap - .of("ip", "112.111.162.4", "action", "GET", "response", 200, "referer", - "www.amazon.com"))) - .add(ExprValueUtils.tupleValue(ImmutableMap - .of("ip", "74.125.19.106", "action", "POST", "response", 200, "referer", - "www.google.com"))) - .add(ExprValueUtils - .tupleValue(ImmutableMap.of("ip", "74.125.19.106", "action", "POST", "response", 500))) - .build(); + protected static final List inputs = + new ImmutableList.Builder() + .add( + ExprValueUtils.tupleValue( + ImmutableMap.of( + "ip", + "209.160.24.63", + "action", + "GET", + "response", + 200, + "referer", + "www.amazon.com"))) + .add( + ExprValueUtils.tupleValue( + ImmutableMap.of( + "ip", + "209.160.24.63", + "action", + "GET", + "response", + 404, + "referer", + "www.amazon.com"))) + .add( + ExprValueUtils.tupleValue( + ImmutableMap.of( + "ip", + "112.111.162.4", + "action", + "GET", + "response", + 200, + "referer", + "www.amazon.com"))) + .add( + ExprValueUtils.tupleValue( + ImmutableMap.of( + "ip", + "74.125.19.106", + "action", + "POST", + "response", + 200, + "referer", + "www.google.com"))) + .add( + ExprValueUtils.tupleValue( + ImmutableMap.of("ip", "74.125.19.106", "action", "POST", "response", 500))) + .build(); private static Map typeMapping = new ImmutableMap.Builder() @@ -79,112 +102,172 @@ public class PhysicalPlanTestBase { .put("referer", ExprCoreType.STRING) .build(); - protected static final List dateInputs = new ImmutableList.Builder() - .add(ExprValueUtils.tupleValue(ImmutableMap.of( - "day", new ExprDateValue("2021-01-03"), - "month", new ExprDateValue("2021-02-04"), - "quarter", new ExprDatetimeValue("2021-01-01 12:25:02"), - "year", new ExprTimestampValue("2013-01-01 12:25:02")))) - .add(ExprValueUtils.tupleValue(ImmutableMap.of( - "day", new ExprDateValue("2021-01-01"), - "month", new ExprDateValue("2021-03-17"), - "quarter", new ExprDatetimeValue("2021-05-17 12:25:01"), - "year", new ExprTimestampValue("2021-01-01 12:25:02")))) - .add(ExprValueUtils.tupleValue(ImmutableMap.of( - "day", new ExprDateValue("2021-01-04"), - "month", new ExprDateValue("2021-02-08"), - "quarter", new ExprDatetimeValue("2021-06-08 12:25:02"), - "year", new ExprTimestampValue("2016-01-01 12:25:02")))) - .add(ExprValueUtils.tupleValue(ImmutableMap.of( - "day", new ExprDateValue("2021-01-02"), - "month", new ExprDateValue("2020-12-12"), - "quarter", new ExprDatetimeValue("2020-12-12 12:25:03"), - "year", new ExprTimestampValue("1999-01-01 12:25:02")))) - .add(ExprValueUtils.tupleValue(ImmutableMap.of( - "day", new ExprDateValue("2021-01-01"), - "month", new ExprDateValue("2021-02-28"), - "quarter", new ExprDatetimeValue("2020-09-28 12:25:01"), - "year", new ExprTimestampValue("2018-01-01 12:25:02")))) - .build(); + protected static final List dateInputs = + new ImmutableList.Builder() + .add( + ExprValueUtils.tupleValue( + ImmutableMap.of( + "day", new ExprDateValue("2021-01-03"), + "month", new ExprDateValue("2021-02-04"), + "quarter", new ExprDatetimeValue("2021-01-01 12:25:02"), + "year", new ExprTimestampValue("2013-01-01 12:25:02")))) + .add( + ExprValueUtils.tupleValue( + ImmutableMap.of( + "day", new ExprDateValue("2021-01-01"), + "month", new ExprDateValue("2021-03-17"), + "quarter", new ExprDatetimeValue("2021-05-17 12:25:01"), + "year", new ExprTimestampValue("2021-01-01 12:25:02")))) + .add( + ExprValueUtils.tupleValue( + ImmutableMap.of( + "day", new ExprDateValue("2021-01-04"), + "month", new ExprDateValue("2021-02-08"), + "quarter", new ExprDatetimeValue("2021-06-08 12:25:02"), + "year", new ExprTimestampValue("2016-01-01 12:25:02")))) + .add( + ExprValueUtils.tupleValue( + ImmutableMap.of( + "day", new ExprDateValue("2021-01-02"), + "month", new ExprDateValue("2020-12-12"), + "quarter", new ExprDatetimeValue("2020-12-12 12:25:03"), + "year", new ExprTimestampValue("1999-01-01 12:25:02")))) + .add( + ExprValueUtils.tupleValue( + ImmutableMap.of( + "day", new ExprDateValue("2021-01-01"), + "month", new ExprDateValue("2021-02-28"), + "quarter", new ExprDatetimeValue("2020-09-28 12:25:01"), + "year", new ExprTimestampValue("2018-01-01 12:25:02")))) + .build(); - protected static final List datetimeInputs = new ImmutableList.Builder() - .add(ExprValueUtils.tupleValue(ImmutableMap.of( - "hour", new ExprTimeValue("17:17:00"), - "minute", new ExprDatetimeValue("2020-12-31 23:54:12"), - "second", new ExprTimestampValue("2021-01-01 00:00:05")))) - .add(ExprValueUtils.tupleValue(ImmutableMap.of( - "hour", new ExprTimeValue("18:17:00"), - "minute", new ExprDatetimeValue("2021-01-01 00:05:12"), - "second", new ExprTimestampValue("2021-01-01 00:00:12")))) - .add(ExprValueUtils.tupleValue(ImmutableMap.of( - "hour", new ExprTimeValue("17:15:00"), - "minute", new ExprDatetimeValue("2021-01-01 00:03:12"), - "second", new ExprTimestampValue("2021-01-01 00:00:17")))) - .add(ExprValueUtils.tupleValue(ImmutableMap.of( - "hour", new ExprTimeValue("19:01:00"), - "minute", new ExprDatetimeValue("2021-01-01 00:02:12"), - "second", new ExprTimestampValue("2021-01-01 00:00:03")))) - .add(ExprValueUtils.tupleValue(ImmutableMap.of( - "hour", new ExprTimeValue("18:50:00"), - "minute", new ExprDatetimeValue("2021-01-01 00:00:12"), - "second", new ExprTimestampValue("2021-01-01 00:00:13")))) - .build(); + protected static final List datetimeInputs = + new ImmutableList.Builder() + .add( + ExprValueUtils.tupleValue( + ImmutableMap.of( + "hour", new ExprTimeValue("17:17:00"), + "minute", new ExprDatetimeValue("2020-12-31 23:54:12"), + "second", new ExprTimestampValue("2021-01-01 00:00:05")))) + .add( + ExprValueUtils.tupleValue( + ImmutableMap.of( + "hour", new ExprTimeValue("18:17:00"), + "minute", new ExprDatetimeValue("2021-01-01 00:05:12"), + "second", new ExprTimestampValue("2021-01-01 00:00:12")))) + .add( + ExprValueUtils.tupleValue( + ImmutableMap.of( + "hour", new ExprTimeValue("17:15:00"), + "minute", new ExprDatetimeValue("2021-01-01 00:03:12"), + "second", new ExprTimestampValue("2021-01-01 00:00:17")))) + .add( + ExprValueUtils.tupleValue( + ImmutableMap.of( + "hour", new ExprTimeValue("19:01:00"), + "minute", new ExprDatetimeValue("2021-01-01 00:02:12"), + "second", new ExprTimestampValue("2021-01-01 00:00:03")))) + .add( + ExprValueUtils.tupleValue( + ImmutableMap.of( + "hour", new ExprTimeValue("18:50:00"), + "minute", new ExprDatetimeValue("2021-01-01 00:00:12"), + "second", new ExprTimestampValue("2021-01-01 00:00:13")))) + .build(); - protected static final List numericInputs = new ImmutableList.Builder() - .add(ExprValueUtils.tupleValue(ImmutableMap.of( - "integer", 2, - "long", 2L, - "float", 2F, - "double", 2D))) - .add(ExprValueUtils.tupleValue(ImmutableMap.of( - "integer", 1, - "long", 1L, - "float", 1F, - "double", 1D))) - .add(ExprValueUtils.tupleValue(ImmutableMap.of( - "integer", 5, - "long", 5L, - "float", 5F, - "double", 5D))) - .build(); + protected static final List numericInputs = + new ImmutableList.Builder() + .add( + ExprValueUtils.tupleValue( + ImmutableMap.of("integer", 2, "long", 2L, "float", 2F, "double", 2D))) + .add( + ExprValueUtils.tupleValue( + ImmutableMap.of("integer", 1, "long", 1L, "float", 1F, "double", 1D))) + .add( + ExprValueUtils.tupleValue( + ImmutableMap.of("integer", 5, "long", 5L, "float", 5F, "double", 5D))) + .build(); - protected static final List compoundInputs = new ImmutableList.Builder() - .add(ExprValueUtils.tupleValue(ImmutableMap.of( - "day", new ExprDateValue("2021-01-03"), - "region", "iad", - "host", "h1", - "errors", 2))) - .add(ExprValueUtils.tupleValue(ImmutableMap.of( - "day", new ExprDateValue("2021-01-03"), - "region", "iad", - "host", "h2", - "errors", 3))) - .add(ExprValueUtils.tupleValue(ImmutableMap.of( - "day", new ExprDateValue("2021-01-04"), - "region", "iad", - "host", "h1", - "errors", 1))) - .add(ExprValueUtils.tupleValue(ImmutableMap.of( - "day", new ExprDateValue("2021-01-04"), - "region", "iad", - "host", "h2", - "errors", 10))) - .add(ExprValueUtils.tupleValue(ImmutableMap.of( - "day", new ExprDateValue("2021-01-06"), - "region", "iad", - "host", "h1", - "errors", 1))) - .add(ExprValueUtils.tupleValue(ImmutableMap.of( - "day", new ExprDateValue("2021-01-07"), - "region", "iad", - "host", "h1", - "errors", 6))) - .add(ExprValueUtils.tupleValue(ImmutableMap.of( - "day", new ExprDateValue("2021-01-07"), - "region", "iad", - "host", "h2", - "errors", 8))) - .build(); + protected static final List compoundInputs = + new ImmutableList.Builder() + .add( + ExprValueUtils.tupleValue( + ImmutableMap.of( + "day", + new ExprDateValue("2021-01-03"), + "region", + "iad", + "host", + "h1", + "errors", + 2))) + .add( + ExprValueUtils.tupleValue( + ImmutableMap.of( + "day", + new ExprDateValue("2021-01-03"), + "region", + "iad", + "host", + "h2", + "errors", + 3))) + .add( + ExprValueUtils.tupleValue( + ImmutableMap.of( + "day", + new ExprDateValue("2021-01-04"), + "region", + "iad", + "host", + "h1", + "errors", + 1))) + .add( + ExprValueUtils.tupleValue( + ImmutableMap.of( + "day", + new ExprDateValue("2021-01-04"), + "region", + "iad", + "host", + "h2", + "errors", + 10))) + .add( + ExprValueUtils.tupleValue( + ImmutableMap.of( + "day", + new ExprDateValue("2021-01-06"), + "region", + "iad", + "host", + "h1", + "errors", + 1))) + .add( + ExprValueUtils.tupleValue( + ImmutableMap.of( + "day", + new ExprDateValue("2021-01-07"), + "region", + "iad", + "host", + "h1", + "errors", + 6))) + .add( + ExprValueUtils.tupleValue( + ImmutableMap.of( + "day", + new ExprDateValue("2021-01-07"), + "region", + "iad", + "host", + "h2", + "errors", + 8))) + .build(); protected Environment typeEnv() { return var -> { @@ -244,12 +327,10 @@ public ExprValue next() { } @Override - public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { - } + public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {} @Override - public void writeExternal(ObjectOutput out) throws IOException { - } + public void writeExternal(ObjectOutput out) throws IOException {} public boolean equals(final Object o) { return o == this || o.hashCode() == hashCode(); diff --git a/core/src/test/java/org/opensearch/sql/planner/physical/ProjectOperatorTest.java b/core/src/test/java/org/opensearch/sql/planner/physical/ProjectOperatorTest.java index f5ecf76bd0..ded8605cf0 100644 --- a/core/src/test/java/org/opensearch/sql/planner/physical/ProjectOperatorTest.java +++ b/core/src/test/java/org/opensearch/sql/planner/physical/ProjectOperatorTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.planner.physical; import static org.hamcrest.MatcherAssert.assertThat; @@ -64,9 +63,11 @@ public void project_two_field_follow_the_project_order() { when(inputPlan.hasNext()).thenReturn(true, false); when(inputPlan.next()) .thenReturn(ExprValueUtils.tupleValue(ImmutableMap.of("action", "GET", "response", 200))); - PhysicalPlan plan = project(inputPlan, - DSL.named("response", DSL.ref("response", INTEGER)), - DSL.named("action", DSL.ref("action", STRING))); + PhysicalPlan plan = + project( + inputPlan, + DSL.named("response", DSL.ref("response", INTEGER)), + DSL.named("action", DSL.ref("action", STRING))); List result = execute(plan); assertThat( @@ -83,9 +84,11 @@ public void project_keep_missing_value() { when(inputPlan.next()) .thenReturn(ExprValueUtils.tupleValue(ImmutableMap.of("action", "GET", "response", 200))) .thenReturn(ExprValueUtils.tupleValue(ImmutableMap.of("action", "POST"))); - PhysicalPlan plan = project(inputPlan, - DSL.named("response", DSL.ref("response", INTEGER)), - DSL.named("action", DSL.ref("action", STRING))); + PhysicalPlan plan = + project( + inputPlan, + DSL.named("response", DSL.ref("response", INTEGER)), + DSL.named("action", DSL.ref("action", STRING))); List result = execute(plan); assertThat( @@ -94,21 +97,23 @@ public void project_keep_missing_value() { iterableWithSize(2), hasItems( ExprValueUtils.tupleValue(ImmutableMap.of("response", 200, "action", "GET")), - ExprTupleValue.fromExprValueMap(ImmutableMap.of("response", - LITERAL_MISSING, - "action", stringValue("POST")))))); + ExprTupleValue.fromExprValueMap( + ImmutableMap.of("response", LITERAL_MISSING, "action", stringValue("POST")))))); } @Test public void project_schema() { - PhysicalPlan project = project(inputPlan, - DSL.named("response", DSL.ref("response", INTEGER)), - DSL.named("action", DSL.ref("action", STRING), "act")); - - assertThat(project.schema().getColumns(), contains( - new ExecutionEngine.Schema.Column("response", null, INTEGER), - new ExecutionEngine.Schema.Column("action", "act", STRING) - )); + PhysicalPlan project = + project( + inputPlan, + DSL.named("response", DSL.ref("response", INTEGER)), + DSL.named("action", DSL.ref("action", STRING), "act")); + + assertThat( + project.schema().getColumns(), + contains( + new ExecutionEngine.Schema.Column("response", null, INTEGER), + new ExecutionEngine.Schema.Column("action", "act", STRING))); } @Test @@ -117,16 +122,24 @@ public void project_fields_with_parse_expressions() { when(inputPlan.next()) .thenReturn(ExprValueUtils.tupleValue(ImmutableMap.of("response", "GET 200"))); PhysicalPlan plan = - project(inputPlan, ImmutableList.of(DSL.named("action", DSL.ref("action", STRING)), + project( + inputPlan, + ImmutableList.of( + DSL.named("action", DSL.ref("action", STRING)), DSL.named("response", DSL.ref("response", STRING))), - ImmutableList.of(DSL.named("action", - DSL.regex(DSL.ref("response", STRING), - DSL.literal("(?\\w+) (?\\d+)"), - DSL.literal("action"))), DSL.named("response", - DSL.regex(DSL.ref("response", STRING), - DSL.literal("(?\\w+) (?\\d+)"), - DSL.literal("response")))) - ); + ImmutableList.of( + DSL.named( + "action", + DSL.regex( + DSL.ref("response", STRING), + DSL.literal("(?\\w+) (?\\d+)"), + DSL.literal("action"))), + DSL.named( + "response", + DSL.regex( + DSL.ref("response", STRING), + DSL.literal("(?\\w+) (?\\d+)"), + DSL.literal("response"))))); List result = execute(plan); assertThat( @@ -143,20 +156,23 @@ public void project_fields_with_unused_parse_expressions() { when(inputPlan.next()) .thenReturn(ExprValueUtils.tupleValue(ImmutableMap.of("response", "GET 200"))); PhysicalPlan plan = - project(inputPlan, ImmutableList.of(DSL.named("response", DSL.ref("response", STRING))), - ImmutableList.of(DSL.named("ignored", - DSL.regex(DSL.ref("response", STRING), - DSL.literal("(?\\w+) (?\\d+)"), - DSL.literal("ignored")))) - ); + project( + inputPlan, + ImmutableList.of(DSL.named("response", DSL.ref("response", STRING))), + ImmutableList.of( + DSL.named( + "ignored", + DSL.regex( + DSL.ref("response", STRING), + DSL.literal("(?\\w+) (?\\d+)"), + DSL.literal("ignored"))))); List result = execute(plan); assertThat( result, allOf( iterableWithSize(1), - hasItems( - ExprValueUtils.tupleValue(ImmutableMap.of("response", "GET 200"))))); + hasItems(ExprValueUtils.tupleValue(ImmutableMap.of("response", "GET 200"))))); } @Test @@ -166,14 +182,19 @@ public void project_fields_with_parse_expressions_and_runtime_fields() { .thenReturn( ExprValueUtils.tupleValue(ImmutableMap.of("response", "GET 200", "eval_field", 1))); PhysicalPlan plan = - project(inputPlan, ImmutableList.of(DSL.named("response", DSL.ref("response", STRING)), + project( + inputPlan, + ImmutableList.of( + DSL.named("response", DSL.ref("response", STRING)), DSL.named("action", DSL.ref("action", STRING)), DSL.named("eval_field", DSL.ref("eval_field", INTEGER))), - ImmutableList.of(DSL.named("action", - DSL.regex(DSL.ref("response", STRING), - DSL.literal("(?\\w+) (?\\d+)"), - DSL.literal("action")))) - ); + ImmutableList.of( + DSL.named( + "action", + DSL.regex( + DSL.ref("response", STRING), + DSL.literal("(?\\w+) (?\\d+)"), + DSL.literal("action"))))); List result = execute(plan); assertThat( @@ -193,16 +214,24 @@ public void project_parse_missing_will_fallback() { ExprValueUtils.tupleValue(ImmutableMap.of("action", "GET", "response", "GET 200"))) .thenReturn(ExprValueUtils.tupleValue(ImmutableMap.of("action", "POST"))); PhysicalPlan plan = - project(inputPlan, ImmutableList.of(DSL.named("action", DSL.ref("action", STRING)), + project( + inputPlan, + ImmutableList.of( + DSL.named("action", DSL.ref("action", STRING)), DSL.named("response", DSL.ref("response", STRING))), - ImmutableList.of(DSL.named("action", - DSL.regex(DSL.ref("response", STRING), - DSL.literal("(?\\w+) (?\\d+)"), - DSL.literal("action"))), DSL.named("response", - DSL.regex(DSL.ref("response", STRING), - DSL.literal("(?\\w+) (?\\d+)"), - DSL.literal("response")))) - ); + ImmutableList.of( + DSL.named( + "action", + DSL.regex( + DSL.ref("response", STRING), + DSL.literal("(?\\w+) (?\\d+)"), + DSL.literal("action"))), + DSL.named( + "response", + DSL.regex( + DSL.ref("response", STRING), + DSL.literal("(?\\w+) (?\\d+)"), + DSL.literal("response"))))); List result = execute(plan); assertThat( @@ -225,8 +254,8 @@ public void serializable() { objectOutput.writeObject(project); objectOutput.flush(); - ObjectInputStream objectInput = new ObjectInputStream( - new ByteArrayInputStream(output.toByteArray())); + ObjectInputStream objectInput = + new ObjectInputStream(new ByteArrayInputStream(output.toByteArray())); var roundTripPlan = (ProjectOperator) objectInput.readObject(); assertEquals(project, roundTripPlan); } diff --git a/core/src/test/java/org/opensearch/sql/planner/physical/RareTopNOperatorTest.java b/core/src/test/java/org/opensearch/sql/planner/physical/RareTopNOperatorTest.java index 5a77bf7f66..e252c41d1f 100644 --- a/core/src/test/java/org/opensearch/sql/planner/physical/RareTopNOperatorTest.java +++ b/core/src/test/java/org/opensearch/sql/planner/physical/RareTopNOperatorTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.planner.physical; import static org.hamcrest.MatcherAssert.assertThat; @@ -24,74 +23,87 @@ public class RareTopNOperatorTest extends PhysicalPlanTestBase { @Test public void rare_without_group() { - PhysicalPlan plan = new RareTopNOperator(new TestScan(), - CommandType.RARE, - Collections.singletonList(DSL.ref("action", ExprCoreType.STRING)), - Collections.emptyList()); + PhysicalPlan plan = + new RareTopNOperator( + new TestScan(), + CommandType.RARE, + Collections.singletonList(DSL.ref("action", ExprCoreType.STRING)), + Collections.emptyList()); List result = execute(plan); assertEquals(2, result.size()); - assertThat(result, containsInAnyOrder( - ExprValueUtils.tupleValue(ImmutableMap.of("action", "POST")), - ExprValueUtils.tupleValue(ImmutableMap.of("action", "GET")) - )); + assertThat( + result, + containsInAnyOrder( + ExprValueUtils.tupleValue(ImmutableMap.of("action", "POST")), + ExprValueUtils.tupleValue(ImmutableMap.of("action", "GET")))); } @Test public void rare_with_group() { - PhysicalPlan plan = new RareTopNOperator(new TestScan(), - CommandType.RARE, - Collections.singletonList(DSL.ref("response", ExprCoreType.INTEGER)), - Collections.singletonList(DSL.ref("action", ExprCoreType.STRING))); + PhysicalPlan plan = + new RareTopNOperator( + new TestScan(), + CommandType.RARE, + Collections.singletonList(DSL.ref("response", ExprCoreType.INTEGER)), + Collections.singletonList(DSL.ref("action", ExprCoreType.STRING))); List result = execute(plan); assertEquals(4, result.size()); - assertThat(result, containsInAnyOrder( - ExprValueUtils.tupleValue(ImmutableMap.of("action", "POST", "response", 200)), - ExprValueUtils.tupleValue(ImmutableMap.of("action", "POST", "response", 500)), - ExprValueUtils.tupleValue(ImmutableMap.of("action", "GET", "response", 404)), - ExprValueUtils.tupleValue(ImmutableMap.of("action", "GET", "response", 200)) - )); + assertThat( + result, + containsInAnyOrder( + ExprValueUtils.tupleValue(ImmutableMap.of("action", "POST", "response", 200)), + ExprValueUtils.tupleValue(ImmutableMap.of("action", "POST", "response", 500)), + ExprValueUtils.tupleValue(ImmutableMap.of("action", "GET", "response", 404)), + ExprValueUtils.tupleValue(ImmutableMap.of("action", "GET", "response", 200)))); } @Test public void top_without_group() { - PhysicalPlan plan = new RareTopNOperator(new TestScan(), - CommandType.TOP, - Collections.singletonList(DSL.ref("action", ExprCoreType.STRING)), - Collections.emptyList()); + PhysicalPlan plan = + new RareTopNOperator( + new TestScan(), + CommandType.TOP, + Collections.singletonList(DSL.ref("action", ExprCoreType.STRING)), + Collections.emptyList()); List result = execute(plan); assertEquals(2, result.size()); - assertThat(result, containsInAnyOrder( - ExprValueUtils.tupleValue(ImmutableMap.of("action", "GET")), - ExprValueUtils.tupleValue(ImmutableMap.of("action", "POST")) - )); + assertThat( + result, + containsInAnyOrder( + ExprValueUtils.tupleValue(ImmutableMap.of("action", "GET")), + ExprValueUtils.tupleValue(ImmutableMap.of("action", "POST")))); } @Test public void top_n_without_group() { - PhysicalPlan plan = new RareTopNOperator(new TestScan(), - CommandType.TOP, - 1, - Collections.singletonList(DSL.ref("action", ExprCoreType.STRING)), - Collections.emptyList()); + PhysicalPlan plan = + new RareTopNOperator( + new TestScan(), + CommandType.TOP, + 1, + Collections.singletonList(DSL.ref("action", ExprCoreType.STRING)), + Collections.emptyList()); List result = execute(plan); assertEquals(1, result.size()); - assertThat(result, containsInAnyOrder( - ExprValueUtils.tupleValue(ImmutableMap.of("action", "GET")) - )); + assertThat( + result, containsInAnyOrder(ExprValueUtils.tupleValue(ImmutableMap.of("action", "GET")))); } @Test public void top_n_with_group() { - PhysicalPlan plan = new RareTopNOperator(new TestScan(), - CommandType.TOP, - 1, - Collections.singletonList(DSL.ref("response", ExprCoreType.INTEGER)), - Collections.singletonList(DSL.ref("action", ExprCoreType.STRING))); + PhysicalPlan plan = + new RareTopNOperator( + new TestScan(), + CommandType.TOP, + 1, + Collections.singletonList(DSL.ref("response", ExprCoreType.INTEGER)), + Collections.singletonList(DSL.ref("action", ExprCoreType.STRING))); List result = execute(plan); assertEquals(2, result.size()); - assertThat(result, containsInAnyOrder( - ExprValueUtils.tupleValue(ImmutableMap.of("action", "POST", "response", 200)), - ExprValueUtils.tupleValue(ImmutableMap.of("action", "GET", "response", 200)) - )); + assertThat( + result, + containsInAnyOrder( + ExprValueUtils.tupleValue(ImmutableMap.of("action", "POST", "response", 200)), + ExprValueUtils.tupleValue(ImmutableMap.of("action", "GET", "response", 200)))); } } diff --git a/core/src/test/java/org/opensearch/sql/planner/physical/RemoveOperatorTest.java b/core/src/test/java/org/opensearch/sql/planner/physical/RemoveOperatorTest.java index ec950e6016..6ba5d3fba8 100644 --- a/core/src/test/java/org/opensearch/sql/planner/physical/RemoveOperatorTest.java +++ b/core/src/test/java/org/opensearch/sql/planner/physical/RemoveOperatorTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.planner.physical; import static org.hamcrest.MatcherAssert.assertThat; @@ -29,8 +28,7 @@ @ExtendWith(MockitoExtension.class) class RemoveOperatorTest extends PhysicalPlanTestBase { - @Mock - private PhysicalPlan inputPlan; + @Mock private PhysicalPlan inputPlan; @Test public void remove_one_field() { diff --git a/core/src/test/java/org/opensearch/sql/planner/physical/RenameOperatorTest.java b/core/src/test/java/org/opensearch/sql/planner/physical/RenameOperatorTest.java index a0da659a38..807d8b8836 100644 --- a/core/src/test/java/org/opensearch/sql/planner/physical/RenameOperatorTest.java +++ b/core/src/test/java/org/opensearch/sql/planner/physical/RenameOperatorTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.planner.physical; import static org.hamcrest.MatcherAssert.assertThat; @@ -27,34 +26,34 @@ @ExtendWith(MockitoExtension.class) public class RenameOperatorTest extends PhysicalPlanTestBase { - @Mock - private PhysicalPlan inputPlan; + @Mock private PhysicalPlan inputPlan; @Test public void avg_aggregation_rename() { - PhysicalPlan plan = new RenameOperator( - new AggregationOperator(new TestScan(), - Collections - .singletonList(DSL.named("avg(response)", DSL.avg(DSL.ref("response", INTEGER)))), - Collections.singletonList(DSL.named("action", DSL.ref("action", STRING)))), - ImmutableMap.of(DSL.ref("avg(response)", DOUBLE), DSL.ref("avg", DOUBLE)) - ); + PhysicalPlan plan = + new RenameOperator( + new AggregationOperator( + new TestScan(), + Collections.singletonList( + DSL.named("avg(response)", DSL.avg(DSL.ref("response", INTEGER)))), + Collections.singletonList(DSL.named("action", DSL.ref("action", STRING)))), + ImmutableMap.of(DSL.ref("avg(response)", DOUBLE), DSL.ref("avg", DOUBLE))); List result = execute(plan); assertEquals(2, result.size()); - assertThat(result, containsInAnyOrder( - ExprValueUtils.tupleValue(ImmutableMap.of("action", "GET", "avg", 268d)), - ExprValueUtils.tupleValue(ImmutableMap.of("action", "POST", "avg", 350d)) - )); + assertThat( + result, + containsInAnyOrder( + ExprValueUtils.tupleValue(ImmutableMap.of("action", "GET", "avg", 268d)), + ExprValueUtils.tupleValue(ImmutableMap.of("action", "POST", "avg", 350d)))); } @Test public void rename_int_value() { when(inputPlan.hasNext()).thenReturn(true, false); when(inputPlan.next()).thenReturn(ExprValueUtils.integerValue(1)); - PhysicalPlan plan = new RenameOperator( - inputPlan, - ImmutableMap.of(DSL.ref("avg(response)", DOUBLE), DSL.ref("avg", DOUBLE)) - ); + PhysicalPlan plan = + new RenameOperator( + inputPlan, ImmutableMap.of(DSL.ref("avg(response)", DOUBLE), DSL.ref("avg", DOUBLE))); List result = execute(plan); assertEquals(1, result.size()); assertThat(result, containsInAnyOrder(ExprValueUtils.integerValue(1))); diff --git a/core/src/test/java/org/opensearch/sql/planner/physical/SortOperatorTest.java b/core/src/test/java/org/opensearch/sql/planner/physical/SortOperatorTest.java index ef9bdfbca4..f9a44be3ab 100644 --- a/core/src/test/java/org/opensearch/sql/planner/physical/SortOperatorTest.java +++ b/core/src/test/java/org/opensearch/sql/planner/physical/SortOperatorTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.planner.physical; import static org.hamcrest.MatcherAssert.assertThat; @@ -27,8 +26,7 @@ @ExtendWith(MockitoExtension.class) class SortOperatorTest extends PhysicalPlanTestBase { - @Mock - private PhysicalPlan inputPlan; + @Mock private PhysicalPlan inputPlan; /** * construct the map which contain null value, because {@link ImmutableMap} doesn't support null @@ -264,7 +262,6 @@ public void sort_one_field_without_input() { assertEquals( 0, - execute(sort(inputPlan, - Pair.of(SortOption.DEFAULT_ASC, ref("response", INTEGER)))).size()); + execute(sort(inputPlan, Pair.of(SortOption.DEFAULT_ASC, ref("response", INTEGER)))).size()); } } diff --git a/core/src/test/java/org/opensearch/sql/planner/physical/ValuesOperatorTest.java b/core/src/test/java/org/opensearch/sql/planner/physical/ValuesOperatorTest.java index 9acab03d2b..ddf4014b7e 100644 --- a/core/src/test/java/org/opensearch/sql/planner/physical/ValuesOperatorTest.java +++ b/core/src/test/java/org/opensearch/sql/planner/physical/ValuesOperatorTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.planner.physical; import static org.hamcrest.MatcherAssert.assertThat; @@ -26,10 +25,7 @@ class ValuesOperatorTest { @Test public void shouldHaveNoChild() { ValuesOperator values = values(ImmutableList.of(literal(1))); - assertThat( - values.getChild(), - is(empty()) - ); + assertThat(values.getChild(), is(empty())); } @Test @@ -40,10 +36,6 @@ public void iterateSingleRow() { results.add(values.next()); } - assertThat( - results, - contains(collectionValue(Arrays.asList(1, "abc"))) - ); + assertThat(results, contains(collectionValue(Arrays.asList(1, "abc")))); } - } diff --git a/core/src/test/java/org/opensearch/sql/planner/physical/WindowOperatorTest.java b/core/src/test/java/org/opensearch/sql/planner/physical/WindowOperatorTest.java index 7f727d391b..3bd145ff91 100644 --- a/core/src/test/java/org/opensearch/sql/planner/physical/WindowOperatorTest.java +++ b/core/src/test/java/org/opensearch/sql/planner/physical/WindowOperatorTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.planner.physical; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -43,21 +42,56 @@ void test_ranking_window_function() { window(DSL.rank()) .partitionBy(ref("action", STRING)) .sortBy(DEFAULT_ASC, ref("response", INTEGER)) - .expectNext(ImmutableMap.of( - "ip", "209.160.24.63", "action", "GET", "response", 200, "referer", "www.amazon.com", - "rank()", 1)) - .expectNext(ImmutableMap.of( - "ip", "112.111.162.4", "action", "GET", "response", 200, "referer", "www.amazon.com", - "rank()", 1)) - .expectNext(ImmutableMap.of( - "ip", "209.160.24.63", "action", "GET", "response", 404, "referer", "www.amazon.com", - "rank()", 3)) - .expectNext(ImmutableMap.of( - "ip", "74.125.19.106", "action", "POST", "response", 200, "referer", "www.google.com", - "rank()", 1)) - .expectNext(ImmutableMap.of( - "ip", "74.125.19.106", "action", "POST", "response", 500, - "rank()", 2)) + .expectNext( + ImmutableMap.of( + "ip", + "209.160.24.63", + "action", + "GET", + "response", + 200, + "referer", + "www.amazon.com", + "rank()", + 1)) + .expectNext( + ImmutableMap.of( + "ip", + "112.111.162.4", + "action", + "GET", + "response", + 200, + "referer", + "www.amazon.com", + "rank()", + 1)) + .expectNext( + ImmutableMap.of( + "ip", + "209.160.24.63", + "action", + "GET", + "response", + 404, + "referer", + "www.amazon.com", + "rank()", + 3)) + .expectNext( + ImmutableMap.of( + "ip", + "74.125.19.106", + "action", + "POST", + "response", + 200, + "referer", + "www.google.com", + "rank()", + 1)) + .expectNext( + ImmutableMap.of("ip", "74.125.19.106", "action", "POST", "response", 500, "rank()", 2)) .done(); } @@ -67,21 +101,57 @@ void test_aggregate_window_function() { window(new AggregateWindowFunction(DSL.sum(ref("response", INTEGER)))) .partitionBy(ref("action", STRING)) .sortBy(DEFAULT_ASC, ref("response", INTEGER)) - .expectNext(ImmutableMap.of( - "ip", "209.160.24.63", "action", "GET", "response", 200, "referer", "www.amazon.com", - "sum(response)", 400)) - .expectNext(ImmutableMap.of( - "ip", "112.111.162.4", "action", "GET", "response", 200, "referer", "www.amazon.com", - "sum(response)", 400)) - .expectNext(ImmutableMap.of( - "ip", "209.160.24.63", "action", "GET", "response", 404, "referer", "www.amazon.com", - "sum(response)", 804)) - .expectNext(ImmutableMap.of( - "ip", "74.125.19.106", "action", "POST", "response", 200, "referer", "www.google.com", - "sum(response)", 200)) - .expectNext(ImmutableMap.of( - "ip", "74.125.19.106", "action", "POST", "response", 500, - "sum(response)", 700)) + .expectNext( + ImmutableMap.of( + "ip", + "209.160.24.63", + "action", + "GET", + "response", + 200, + "referer", + "www.amazon.com", + "sum(response)", + 400)) + .expectNext( + ImmutableMap.of( + "ip", + "112.111.162.4", + "action", + "GET", + "response", + 200, + "referer", + "www.amazon.com", + "sum(response)", + 400)) + .expectNext( + ImmutableMap.of( + "ip", + "209.160.24.63", + "action", + "GET", + "response", + 404, + "referer", + "www.amazon.com", + "sum(response)", + 804)) + .expectNext( + ImmutableMap.of( + "ip", + "74.125.19.106", + "action", + "POST", + "response", + 200, + "referer", + "www.google.com", + "sum(response)", + 200)) + .expectNext( + ImmutableMap.of( + "ip", "74.125.19.106", "action", "POST", "response", 500, "sum(response)", 700)) .done(); } @@ -89,21 +159,57 @@ void test_aggregate_window_function() { @Test void test_aggregate_window_function_without_sort_key() { window(new AggregateWindowFunction(DSL.sum(ref("response", INTEGER)))) - .expectNext(ImmutableMap.of( - "ip", "209.160.24.63", "action", "GET", "response", 200, "referer", "www.amazon.com", - "sum(response)", 1504)) - .expectNext(ImmutableMap.of( - "ip", "74.125.19.106", "action", "POST", "response", 500, - "sum(response)", 1504)) - .expectNext(ImmutableMap.of( - "ip", "74.125.19.106", "action", "POST", "response", 200, "referer", "www.google.com", - "sum(response)", 1504)) - .expectNext(ImmutableMap.of( - "ip", "112.111.162.4", "action", "GET", "response", 200, "referer", "www.amazon.com", - "sum(response)", 1504)) - .expectNext(ImmutableMap.of( - "ip", "209.160.24.63", "action", "GET", "response", 404, "referer", "www.amazon.com", - "sum(response)", 1504)) + .expectNext( + ImmutableMap.of( + "ip", + "209.160.24.63", + "action", + "GET", + "response", + 200, + "referer", + "www.amazon.com", + "sum(response)", + 1504)) + .expectNext( + ImmutableMap.of( + "ip", "74.125.19.106", "action", "POST", "response", 500, "sum(response)", 1504)) + .expectNext( + ImmutableMap.of( + "ip", + "74.125.19.106", + "action", + "POST", + "response", + 200, + "referer", + "www.google.com", + "sum(response)", + 1504)) + .expectNext( + ImmutableMap.of( + "ip", + "112.111.162.4", + "action", + "GET", + "response", + 200, + "referer", + "www.amazon.com", + "sum(response)", + 1504)) + .expectNext( + ImmutableMap.of( + "ip", + "209.160.24.63", + "action", + "GET", + "response", + 404, + "referer", + "www.amazon.com", + "sum(response)", + 1504)) .done(); } @@ -136,10 +242,11 @@ WindowOperatorAssertion sortBy(SortOption option, Expression expr) { WindowOperatorAssertion expectNext(Map expected) { if (windowOperator == null) { WindowDefinition definition = new WindowDefinition(partitionByList, sortList); - windowOperator = new WindowOperator( - new SortOperator(new TestScan(), definition.getAllSortItems()), - windowFunction, - definition); + windowOperator = + new WindowOperator( + new SortOperator(new TestScan(), definition.getAllSortItems()), + windowFunction, + definition); windowOperator.open(); } @@ -153,7 +260,5 @@ void done() { assertFalse(windowOperator.hasNext()); windowOperator.close(); } - } - } diff --git a/core/src/test/java/org/opensearch/sql/planner/physical/collector/RoundingTest.java b/core/src/test/java/org/opensearch/sql/planner/physical/collector/RoundingTest.java index f40e5c058b..3a2601a874 100644 --- a/core/src/test/java/org/opensearch/sql/planner/physical/collector/RoundingTest.java +++ b/core/src/test/java/org/opensearch/sql/planner/physical/collector/RoundingTest.java @@ -22,8 +22,8 @@ public class RoundingTest { void time_rounding_illegal_span() { SpanExpression span = DSL.span(DSL.ref("time", TIME), DSL.literal(1), "d"); Rounding rounding = Rounding.createRounding(span); - assertThrows(ExpressionEvaluationException.class, - () -> rounding.round(new ExprTimeValue("23:30:00"))); + assertThrows( + ExpressionEvaluationException.class, () -> rounding.round(new ExprTimeValue("23:30:00"))); } @Test @@ -36,7 +36,8 @@ void round_unknown_type() { @Test void resolve() { String illegalUnit = "illegal"; - assertThrows(IllegalArgumentException.class, + assertThrows( + IllegalArgumentException.class, () -> Rounding.DateTimeUnit.resolve(illegalUnit), "Unable to resolve unit " + illegalUnit); } diff --git a/core/src/test/java/org/opensearch/sql/planner/physical/datasource/DataSourceTableScanTest.java b/core/src/test/java/org/opensearch/sql/planner/physical/datasource/DataSourceTableScanTest.java index 93c02def86..28851f2454 100644 --- a/core/src/test/java/org/opensearch/sql/planner/physical/datasource/DataSourceTableScanTest.java +++ b/core/src/test/java/org/opensearch/sql/planner/physical/datasource/DataSourceTableScanTest.java @@ -35,11 +35,9 @@ @ExtendWith(MockitoExtension.class) public class DataSourceTableScanTest { - @Mock - private DataSourceService dataSourceService; + @Mock private DataSourceService dataSourceService; - @Mock - private StorageEngine storageEngine; + @Mock private StorageEngine storageEngine; private DataSourceTableScan dataSourceTableScan; @@ -58,10 +56,16 @@ void testIterator() { Set dataSourceSet = new HashSet<>(); dataSourceSet.add(new DataSource("prometheus", DataSourceType.PROMETHEUS, storageEngine)); dataSourceSet.add(new DataSource("opensearch", DataSourceType.OPENSEARCH, storageEngine)); - Set dataSourceMetadata = dataSourceSet.stream() - .map(dataSource -> new DataSourceMetadata(dataSource.getName(), - dataSource.getConnectorType(), Collections.emptyList(), ImmutableMap.of())) - .collect(Collectors.toSet()); + Set dataSourceMetadata = + dataSourceSet.stream() + .map( + dataSource -> + new DataSourceMetadata( + dataSource.getName(), + dataSource.getConnectorType(), + Collections.emptyList(), + ImmutableMap.of())) + .collect(Collectors.toSet()); when(dataSourceService.getDataSourceMetadata(true)).thenReturn(dataSourceMetadata); assertFalse(dataSourceTableScan.hasNext()); @@ -74,11 +78,14 @@ void testIterator() { Set expectedExprTupleValues = new HashSet<>(); for (DataSource dataSource : dataSourceSet) { - expectedExprTupleValues.add(new ExprTupleValue(new LinkedHashMap<>(ImmutableMap.of( - "DATASOURCE_NAME", ExprValueUtils.stringValue(dataSource.getName()), - "CONNECTOR_TYPE", ExprValueUtils.stringValue(dataSource.getConnectorType().name()))))); + expectedExprTupleValues.add( + new ExprTupleValue( + new LinkedHashMap<>( + ImmutableMap.of( + "DATASOURCE_NAME", ExprValueUtils.stringValue(dataSource.getName()), + "CONNECTOR_TYPE", + ExprValueUtils.stringValue(dataSource.getConnectorType().name()))))); } assertEquals(expectedExprTupleValues, exprTupleValues); } - } diff --git a/core/src/test/java/org/opensearch/sql/planner/physical/datasource/DataSourceTableTest.java b/core/src/test/java/org/opensearch/sql/planner/physical/datasource/DataSourceTableTest.java index c82a042770..75f21c3e52 100644 --- a/core/src/test/java/org/opensearch/sql/planner/physical/datasource/DataSourceTableTest.java +++ b/core/src/test/java/org/opensearch/sql/planner/physical/datasource/DataSourceTableTest.java @@ -27,13 +27,12 @@ @ExtendWith(MockitoExtension.class) public class DataSourceTableTest { - @Mock - private DataSourceService dataSourceService; + @Mock private DataSourceService dataSourceService; @Test void testGetFieldTypes() { DataSourceTable dataSourceTable = new DataSourceTable(dataSourceService); - Map fieldTypes = dataSourceTable.getFieldTypes(); + Map fieldTypes = dataSourceTable.getFieldTypes(); Map expectedTypes = new HashMap<>(); expectedTypes.put("DATASOURCE_NAME", ExprCoreType.STRING); expectedTypes.put("CONNECTOR_TYPE", ExprCoreType.STRING); @@ -43,9 +42,8 @@ void testGetFieldTypes() { @Test void testImplement() { DataSourceTable dataSourceTable = new DataSourceTable(dataSourceService); - PhysicalPlan physicalPlan - = dataSourceTable.implement( - LogicalPlanDSL.relation(DATASOURCES_TABLE_NAME, dataSourceTable)); + PhysicalPlan physicalPlan = + dataSourceTable.implement(LogicalPlanDSL.relation(DATASOURCES_TABLE_NAME, dataSourceTable)); assertTrue(physicalPlan instanceof DataSourceTableScan); } @@ -53,7 +51,8 @@ void testImplement() { @Test void testExist() { UnsupportedOperationException exception = - assertThrows(UnsupportedOperationException.class, + assertThrows( + UnsupportedOperationException.class, () -> new DataSourceTable(dataSourceService).exists()); assertEquals("Unsupported Operation", exception.getMessage()); } @@ -62,7 +61,8 @@ void testExist() { @Test void testCreateTable() { UnsupportedOperationException exception = - assertThrows(UnsupportedOperationException.class, + assertThrows( + UnsupportedOperationException.class, () -> new DataSourceTable(dataSourceService).create(new HashMap<>())); assertEquals("Unsupported Operation", exception.getMessage()); } diff --git a/core/src/test/java/org/opensearch/sql/planner/streaming/windowing/assigner/SlidingWindowAssignerTest.java b/core/src/test/java/org/opensearch/sql/planner/streaming/windowing/assigner/SlidingWindowAssignerTest.java index 886537e088..0c63f594d9 100644 --- a/core/src/test/java/org/opensearch/sql/planner/streaming/windowing/assigner/SlidingWindowAssignerTest.java +++ b/core/src/test/java/org/opensearch/sql/planner/streaming/windowing/assigner/SlidingWindowAssignerTest.java @@ -20,33 +20,21 @@ void testAssignWindows() { long slideSize = 500; SlidingWindowAssigner assigner = new SlidingWindowAssigner(windowSize, slideSize); - assertEquals( - List.of( - new Window(0, 1000), - new Window(500, 1500)), - assigner.assign(500)); - - assertEquals( - List.of( - new Window(0, 1000), - new Window(500, 1500)), - assigner.assign(999)); - - assertEquals( - List.of( - new Window(500, 1500), - new Window(1000, 2000)), - assigner.assign(1000)); + assertEquals(List.of(new Window(0, 1000), new Window(500, 1500)), assigner.assign(500)); + + assertEquals(List.of(new Window(0, 1000), new Window(500, 1500)), assigner.assign(999)); + + assertEquals(List.of(new Window(500, 1500), new Window(1000, 2000)), assigner.assign(1000)); } @Test void testConstructWithIllegalArguments() { - IllegalArgumentException error1 = assertThrows(IllegalArgumentException.class, - () -> new SlidingWindowAssigner(-1, 100)); + IllegalArgumentException error1 = + assertThrows(IllegalArgumentException.class, () -> new SlidingWindowAssigner(-1, 100)); assertEquals("Window size [-1] must be positive number", error1.getMessage()); - IllegalArgumentException error2 = assertThrows(IllegalArgumentException.class, - () -> new SlidingWindowAssigner(1000, 0)); + IllegalArgumentException error2 = + assertThrows(IllegalArgumentException.class, () -> new SlidingWindowAssigner(1000, 0)); assertEquals("Slide size [0] must be positive number", error2.getMessage()); } } diff --git a/core/src/test/java/org/opensearch/sql/planner/streaming/windowing/assigner/TumblingWindowAssignerTest.java b/core/src/test/java/org/opensearch/sql/planner/streaming/windowing/assigner/TumblingWindowAssignerTest.java index 55a8750c11..a8ab048701 100644 --- a/core/src/test/java/org/opensearch/sql/planner/streaming/windowing/assigner/TumblingWindowAssignerTest.java +++ b/core/src/test/java/org/opensearch/sql/planner/streaming/windowing/assigner/TumblingWindowAssignerTest.java @@ -19,21 +19,15 @@ void testAssignWindow() { long windowSize = 1000; TumblingWindowAssigner assigner = new TumblingWindowAssigner(windowSize); - assertEquals( - Collections.singletonList(new Window(0, 1000)), - assigner.assign(500)); - assertEquals( - Collections.singletonList(new Window(1000, 2000)), - assigner.assign(1999)); - assertEquals( - Collections.singletonList(new Window(2000, 3000)), - assigner.assign(2000)); + assertEquals(Collections.singletonList(new Window(0, 1000)), assigner.assign(500)); + assertEquals(Collections.singletonList(new Window(1000, 2000)), assigner.assign(1999)); + assertEquals(Collections.singletonList(new Window(2000, 3000)), assigner.assign(2000)); } @Test void testConstructWithIllegalWindowSize() { - IllegalArgumentException error = assertThrows(IllegalArgumentException.class, - () -> new TumblingWindowAssigner(-1)); + IllegalArgumentException error = + assertThrows(IllegalArgumentException.class, () -> new TumblingWindowAssigner(-1)); assertEquals("Window size [-1] must be positive number", error.getMessage()); } } diff --git a/core/src/test/java/org/opensearch/sql/storage/TableScanOperatorTest.java b/core/src/test/java/org/opensearch/sql/storage/TableScanOperatorTest.java index f2f556a957..81680455cc 100644 --- a/core/src/test/java/org/opensearch/sql/storage/TableScanOperatorTest.java +++ b/core/src/test/java/org/opensearch/sql/storage/TableScanOperatorTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.storage; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -15,36 +14,40 @@ class TableScanOperatorTest { - private final TableScanOperator tableScan = new TableScanOperator() { - @Override - public String explain() { - return "explain"; - } + private final TableScanOperator tableScan = + new TableScanOperator() { + @Override + public String explain() { + return "explain"; + } - @Override - public boolean hasNext() { - return false; - } + @Override + public boolean hasNext() { + return false; + } - @Override - public ExprValue next() { - return null; - } - }; + @Override + public ExprValue next() { + return null; + } + }; @Test public void accept() { - Boolean isVisited = tableScan.accept(new PhysicalPlanNodeVisitor() { - @Override - protected Boolean visitNode(PhysicalPlan node, Object context) { - return (node instanceof TableScanOperator); - } - - @Override - public Boolean visitTableScan(TableScanOperator node, Object context) { - return super.visitTableScan(node, context); - } - }, null); + Boolean isVisited = + tableScan.accept( + new PhysicalPlanNodeVisitor() { + @Override + protected Boolean visitNode(PhysicalPlan node, Object context) { + return (node instanceof TableScanOperator); + } + + @Override + public Boolean visitTableScan(TableScanOperator node, Object context) { + return super.visitTableScan(node, context); + } + }, + null); assertTrue(isVisited); } @@ -53,5 +56,4 @@ public Boolean visitTableScan(TableScanOperator node, Object context) { public void getChild() { assertTrue(tableScan.getChild().isEmpty()); } - } diff --git a/core/src/test/java/org/opensearch/sql/storage/bindingtuple/BindingTupleTest.java b/core/src/test/java/org/opensearch/sql/storage/bindingtuple/BindingTupleTest.java index 780d1cd2dd..89d2372707 100644 --- a/core/src/test/java/org/opensearch/sql/storage/bindingtuple/BindingTupleTest.java +++ b/core/src/test/java/org/opensearch/sql/storage/bindingtuple/BindingTupleTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.storage.bindingtuple; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -21,30 +20,31 @@ class BindingTupleTest { public void resolve_ref_expression() { BindingTuple bindingTuple = ExprValueUtils.tupleValue(ImmutableMap.of("ip", "209.160.24.63")).bindingTuples(); - assertEquals(ExprValueUtils.stringValue("209.160.24.63"), - bindingTuple.resolve(DSL.ref("ip", STRING))); + assertEquals( + ExprValueUtils.stringValue("209.160.24.63"), bindingTuple.resolve(DSL.ref("ip", STRING))); } @Test public void resolve_missing_expression() { BindingTuple bindingTuple = ExprValueUtils.tupleValue(ImmutableMap.of("ip", "209.160.24.63")).bindingTuples(); - assertEquals(ExprValueUtils.LITERAL_MISSING, - bindingTuple.resolve(DSL.ref("ip_missing", STRING))); + assertEquals( + ExprValueUtils.LITERAL_MISSING, bindingTuple.resolve(DSL.ref("ip_missing", STRING))); } @Test public void resolve_from_empty_tuple() { - assertEquals(ExprValueUtils.LITERAL_MISSING, - BindingTuple.EMPTY.resolve(DSL.ref("ip_missing", STRING))); + assertEquals( + ExprValueUtils.LITERAL_MISSING, BindingTuple.EMPTY.resolve(DSL.ref("ip_missing", STRING))); } @Test public void resolve_literal_expression_throw_exception() { BindingTuple bindingTuple = ExprValueUtils.tupleValue(ImmutableMap.of("ip", "209.160.24.63")).bindingTuples(); - ExpressionEvaluationException exception = assertThrows(ExpressionEvaluationException.class, - () -> bindingTuple.resolve(DSL.literal(1))); + ExpressionEvaluationException exception = + assertThrows( + ExpressionEvaluationException.class, () -> bindingTuple.resolve(DSL.literal(1))); assertEquals("can resolve expression: 1", exception.getMessage()); } } diff --git a/core/src/test/java/org/opensearch/sql/storage/write/TableWriteOperatorTest.java b/core/src/test/java/org/opensearch/sql/storage/write/TableWriteOperatorTest.java index 112192bde0..e5b2c9f61a 100644 --- a/core/src/test/java/org/opensearch/sql/storage/write/TableWriteOperatorTest.java +++ b/core/src/test/java/org/opensearch/sql/storage/write/TableWriteOperatorTest.java @@ -21,44 +21,47 @@ @ExtendWith(MockitoExtension.class) class TableWriteOperatorTest { - @Mock - private PhysicalPlan child; + @Mock private PhysicalPlan child; private TableWriteOperator tableWrite; @BeforeEach void setUp() { - tableWrite = new TableWriteOperator(child) { - @Override - public String explain() { - return "explain"; - } + tableWrite = + new TableWriteOperator(child) { + @Override + public String explain() { + return "explain"; + } - @Override - public boolean hasNext() { - return false; - } + @Override + public boolean hasNext() { + return false; + } - @Override - public ExprValue next() { - return null; - } - }; + @Override + public ExprValue next() { + return null; + } + }; } @Test void testAccept() { - Boolean isVisited = tableWrite.accept(new PhysicalPlanNodeVisitor<>() { - @Override - protected Boolean visitNode(PhysicalPlan node, Object context) { - return (node instanceof TableWriteOperator); - } + Boolean isVisited = + tableWrite.accept( + new PhysicalPlanNodeVisitor<>() { + @Override + protected Boolean visitNode(PhysicalPlan node, Object context) { + return (node instanceof TableWriteOperator); + } - @Override - public Boolean visitTableWrite(TableWriteOperator node, Object context) { - return super.visitTableWrite(node, context); - } - }, null); + @Override + public Boolean visitTableWrite(TableWriteOperator node, Object context) { + return super.visitTableWrite(node, context); + } + }, + null); assertTrue(isVisited); } diff --git a/core/src/test/java/org/opensearch/sql/utils/ComparisonUtil.java b/core/src/test/java/org/opensearch/sql/utils/ComparisonUtil.java index d6f0ef02cd..b25f4d1053 100644 --- a/core/src/test/java/org/opensearch/sql/utils/ComparisonUtil.java +++ b/core/src/test/java/org/opensearch/sql/utils/ComparisonUtil.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.utils; import static org.opensearch.sql.data.model.ExprValueUtils.getDoubleValue; @@ -21,8 +20,8 @@ public class ComparisonUtil { /** - * Util to compare the object (integer, long, float, double, string) values. - * Allows comparing different datetime types and requires `FunctionProperties` object for that. + * Util to compare the object (integer, long, float, double, string) values. Allows comparing + * different datetime types and requires `FunctionProperties` object for that. */ public static int compare(FunctionProperties functionProperties, ExprValue v1, ExprValue v2) { if (v1.isMissing() || v2.isMissing()) { @@ -36,9 +35,7 @@ public static int compare(FunctionProperties functionProperties, ExprValue v1, E return compare(v1, v2); } - /** - * Util to compare the object (integer, long, float, double, string) values. - */ + /** Util to compare the object (integer, long, float, double, string) values. */ public static int compare(ExprValue v1, ExprValue v2) { if (v1.isMissing() || v2.isMissing()) { throw new ExpressionEvaluationException("invalid to call compare operation on missing value"); @@ -49,21 +46,34 @@ public static int compare(ExprValue v1, ExprValue v2) { "invalid to call compare operation on values of different types"); } - switch ((ExprCoreType)v1.type()) { - case BYTE: return v1.byteValue().compareTo(v2.byteValue()); - case SHORT: return v1.shortValue().compareTo(v2.shortValue()); - case INTEGER: return getIntegerValue(v1).compareTo(getIntegerValue(v2)); - case LONG: return getLongValue(v1).compareTo(getLongValue(v2)); - case FLOAT: return getFloatValue(v1).compareTo(getFloatValue(v2)); - case DOUBLE: return getDoubleValue(v1).compareTo(getDoubleValue(v2)); - case STRING: return getStringValue(v1).compareTo(getStringValue(v2)); - case BOOLEAN: return v1.booleanValue().compareTo(v2.booleanValue()); - case TIME: return v1.timeValue().compareTo(v2.timeValue()); - case DATE: return v1.dateValue().compareTo(v2.dateValue()); - case DATETIME: return v1.datetimeValue().compareTo(v2.datetimeValue()); - case TIMESTAMP: return v1.timestampValue().compareTo(v2.timestampValue()); - default: throw new ExpressionEvaluationException( - String.format("%s instances are not comparable", v1.getClass().getSimpleName())); + switch ((ExprCoreType) v1.type()) { + case BYTE: + return v1.byteValue().compareTo(v2.byteValue()); + case SHORT: + return v1.shortValue().compareTo(v2.shortValue()); + case INTEGER: + return getIntegerValue(v1).compareTo(getIntegerValue(v2)); + case LONG: + return getLongValue(v1).compareTo(getLongValue(v2)); + case FLOAT: + return getFloatValue(v1).compareTo(getFloatValue(v2)); + case DOUBLE: + return getDoubleValue(v1).compareTo(getDoubleValue(v2)); + case STRING: + return getStringValue(v1).compareTo(getStringValue(v2)); + case BOOLEAN: + return v1.booleanValue().compareTo(v2.booleanValue()); + case TIME: + return v1.timeValue().compareTo(v2.timeValue()); + case DATE: + return v1.dateValue().compareTo(v2.dateValue()); + case DATETIME: + return v1.datetimeValue().compareTo(v2.datetimeValue()); + case TIMESTAMP: + return v1.timestampValue().compareTo(v2.timestampValue()); + default: + throw new ExpressionEvaluationException( + String.format("%s instances are not comparable", v1.getClass().getSimpleName())); } } } diff --git a/core/src/test/java/org/opensearch/sql/utils/DateTimeUtilsTest.java b/core/src/test/java/org/opensearch/sql/utils/DateTimeUtilsTest.java index 9bf0a53ff6..989759681f 100644 --- a/core/src/test/java/org/opensearch/sql/utils/DateTimeUtilsTest.java +++ b/core/src/test/java/org/opensearch/sql/utils/DateTimeUtilsTest.java @@ -16,11 +16,16 @@ public class DateTimeUtilsTest { @Test void round() { - long actual = LocalDateTime.parse("2021-09-28T23:40:00").atZone(ZoneId.systemDefault()) - .toInstant().toEpochMilli(); + long actual = + LocalDateTime.parse("2021-09-28T23:40:00") + .atZone(ZoneId.systemDefault()) + .toInstant() + .toEpochMilli(); long rounded = DateTimeUtils.roundFloor(actual, TimeUnit.HOURS.toMillis(1)); assertEquals( - LocalDateTime.parse("2021-09-28T23:00:00").atZone(ZoneId.systemDefault()).toInstant() + LocalDateTime.parse("2021-09-28T23:00:00") + .atZone(ZoneId.systemDefault()) + .toInstant() .toEpochMilli(), Instant.ofEpochMilli(rounded).toEpochMilli()); } diff --git a/core/src/test/java/org/opensearch/sql/utils/MatcherUtils.java b/core/src/test/java/org/opensearch/sql/utils/MatcherUtils.java index 8b1a3dda2e..206f05a38a 100644 --- a/core/src/test/java/org/opensearch/sql/utils/MatcherUtils.java +++ b/core/src/test/java/org/opensearch/sql/utils/MatcherUtils.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.utils; import org.hamcrest.Description; @@ -11,13 +10,9 @@ import org.opensearch.sql.data.model.ExprValue; import org.opensearch.sql.data.type.ExprCoreType; -/** - * Matcher Utils. - */ +/** Matcher Utils. */ public class MatcherUtils { - /** - * Check {@link ExprValue} type equal to {@link ExprCoreType}. - */ + /** Check {@link ExprValue} type equal to {@link ExprCoreType}. */ public static TypeSafeMatcher hasType(ExprCoreType type) { return new TypeSafeMatcher() { @Override @@ -32,9 +27,7 @@ protected boolean matchesSafely(ExprValue value) { }; } - /** - * Check {@link ExprValue} value equal to {@link Object}. - */ + /** Check {@link ExprValue} value equal to {@link Object}. */ public static TypeSafeMatcher hasValue(Object object) { return new TypeSafeMatcher() { @Override diff --git a/core/src/test/java/org/opensearch/sql/utils/SystemIndexUtilsTest.java b/core/src/test/java/org/opensearch/sql/utils/SystemIndexUtilsTest.java index 81d28f40db..903077ca29 100644 --- a/core/src/test/java/org/opensearch/sql/utils/SystemIndexUtilsTest.java +++ b/core/src/test/java/org/opensearch/sql/utils/SystemIndexUtilsTest.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: Apache-2.0 */ - package org.opensearch.sql.utils; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -49,8 +48,8 @@ void test_mapping_info_table() { @Test void test_mapping_info_table_with_special_index_name() { - final SystemIndexUtils.SystemTable table - = systemTable("logs-2021.01.11.MAPPINGS_ODFE_SYS_TABLE"); + final SystemIndexUtils.SystemTable table = + systemTable("logs-2021.01.11.MAPPINGS_ODFE_SYS_TABLE"); assertTrue(table.isMetaInfoTable()); assertFalse(table.isSystemInfoTable()); assertEquals("logs-2021.01.11", table.getTableName()); diff --git a/core/src/test/java/org/opensearch/sql/utils/TestOperator.java b/core/src/test/java/org/opensearch/sql/utils/TestOperator.java index 584cf6f3fd..d356f2f866 100644 --- a/core/src/test/java/org/opensearch/sql/utils/TestOperator.java +++ b/core/src/test/java/org/opensearch/sql/utils/TestOperator.java @@ -18,13 +18,10 @@ public class TestOperator extends PhysicalPlan implements SerializablePlan { private int field; - @Setter - private boolean throwNoCursorOnWrite = false; - @Setter - private boolean throwIoOnWrite = false; + @Setter private boolean throwNoCursorOnWrite = false; + @Setter private boolean throwIoOnWrite = false; - public TestOperator() { - } + public TestOperator() {} public TestOperator(int value) { field = value; diff --git a/core/src/testFixtures/java/org/opensearch/sql/executor/DefaultExecutionEngine.java b/core/src/testFixtures/java/org/opensearch/sql/executor/DefaultExecutionEngine.java index db72498a1d..61219d4637 100644 --- a/core/src/testFixtures/java/org/opensearch/sql/executor/DefaultExecutionEngine.java +++ b/core/src/testFixtures/java/org/opensearch/sql/executor/DefaultExecutionEngine.java @@ -12,9 +12,7 @@ import org.opensearch.sql.executor.pagination.Cursor; import org.opensearch.sql.planner.physical.PhysicalPlan; -/** - * Used for testing purpose. - */ +/** Used for testing purpose. */ public class DefaultExecutionEngine implements ExecutionEngine { @Override public void execute(PhysicalPlan plan, ResponseListener listener) { @@ -33,8 +31,8 @@ public void execute( while (plan.hasNext()) { result.add(plan.next()); } - QueryResponse response = new QueryResponse(new Schema(new ArrayList<>()), new ArrayList<>(), - Cursor.None); + QueryResponse response = + new QueryResponse(new Schema(new ArrayList<>()), new ArrayList<>(), Cursor.None); listener.onResponse(response); } catch (Exception e) { listener.onFailure(e); diff --git a/core/src/testFixtures/java/org/opensearch/sql/executor/DefaultQueryManager.java b/core/src/testFixtures/java/org/opensearch/sql/executor/DefaultQueryManager.java index 41888a0581..3167d4843a 100644 --- a/core/src/testFixtures/java/org/opensearch/sql/executor/DefaultQueryManager.java +++ b/core/src/testFixtures/java/org/opensearch/sql/executor/DefaultQueryManager.java @@ -13,9 +13,7 @@ import java.util.concurrent.TimeUnit; import org.opensearch.sql.executor.execution.AbstractPlan; -/** - * Default QueryManager implementation which execute {@link AbstractPlan} on caller thread. - */ +/** Default QueryManager implementation which execute {@link AbstractPlan} on caller thread. */ public class DefaultQueryManager implements QueryManager { private final ExecutorService executorService;
ExprTypeWidens to data types
INTEGERLONG, FLOAT, DOUBLE