From e22f5010188b688b6a1ebd6efd8978ee6c3c4a5f Mon Sep 17 00:00:00 2001 From: Costin Leau Date: Mon, 27 Jan 2020 22:03:58 +0200 Subject: [PATCH] QL: Backport project to 7.x (#51497) * Introduce reusable QL plugin for SQL and EQL (#50815) Extract reusable functionality from SQL into its own dedicated project QL. Implemented as a plugin, it provides common components across SQL and the upcoming EQL. While this commit is fairly large, for the most part it's just a big file move from sql package to the newly introduced ql. (cherry picked from commit ec1ac0d463bfa12a02c8174afbcdd6984345e8b4) * SQL: Fix incomplete registration of geo NamedWritables (cherry picked from commit e295763686f9592976e551e504fdad1d2a3a566d) * QL: Extend NodeSubclass to read classes from jars (#50866) As the test classes are spread across more than one project, the Gradle classpath contains not just folders but also jars. This commit allows the test class to explore the archive content and load matching classes from said source. (cherry picked from commit 25ad74928afcbf286dc58f7d430491b0af662f04) * QL: Remove implicit conversion inside Literal (#50962) Literal constructor makes an implicit conversion for each value given which turns out has some subtle side-effects. Improve MathProcessors to preserve numeric type where possible Fix bug on issue compatibility between date and intervals Preserve the source when folding inside the Optimizer (cherry picked from commit 9b73e225b0aa07a23859550fb117bae571a2b672) * QL: Refactor DataType for pluggability (#51328) Change DataType from enum to class Break DataType enums into QL (default) and SQL types Make data type conversion pluggable so that new types can be introduced As part of the process: - static type conversion in QL package (such as Literal) has been removed - several utility classes have been broken into base (QL) and extended (SQL) parts based on type awareness - operators (+,-,/,*) are - due to extensibility, serialization of arithmetic operation has been slightly changed and pushed down to the operator executor itself (cherry picked from commit aebda81b30e1563b877a8896309fd50633e0b663) * Compilation fixes for 7.x --- x-pack/plugin/ql/build.gradle | 36 + .../xpack/ql/ParsingException.java | 61 ++ .../xpack/ql/QlClientException.java | 29 + .../elasticsearch/xpack/ql/QlException.java} | 14 +- .../xpack/ql/QlIllegalArgumentException.java | 32 + .../xpack/ql/QlServerException.java | 29 + .../xpack/ql}/capabilities/Resolvable.java | 2 +- .../xpack/ql}/capabilities/Resolvables.java | 2 +- .../xpack/ql}/capabilities/Unresolvable.java | 2 +- .../ql}/capabilities/UnresolvedException.java | 6 +- .../xpack/ql}/execution/search/AggRef.java | 4 +- .../ql}/execution/search/FieldExtraction.java | 4 +- .../ql/execution/search/QlSourceBuilder.java} | 16 +- .../extractor/AbstractFieldHitExtractor.java | 334 ++++++++ .../search/extractor/BucketExtractor.java | 2 +- .../search/extractor/BucketExtractors.java | 28 + .../search/extractor/ComputingExtractor.java | 9 +- .../search/extractor/ConstantExtractor.java | 2 +- .../search/extractor/HitExtractor.java | 2 +- .../search/extractor/HitExtractors.java | 4 +- .../xpack/ql}/expression/Alias.java | 8 +- .../xpack/ql}/expression/Attribute.java | 6 +- .../xpack/ql}/expression/AttributeMap.java | 2 +- .../xpack/ql}/expression/AttributeSet.java | 2 +- .../xpack/ql}/expression/Expression.java | 25 +- .../xpack/ql}/expression/ExpressionSet.java | 2 +- .../xpack/ql}/expression/Expressions.java | 21 +- .../xpack/ql}/expression/FieldAttribute.java | 17 +- .../xpack/ql}/expression/LeafExpression.java | 4 +- .../xpack/ql}/expression/Literal.java | 33 +- .../xpack/ql}/expression/NameId.java | 2 +- .../xpack/ql}/expression/NamedExpression.java | 4 +- .../xpack/ql}/expression/Nullability.java | 2 +- .../xpack/ql}/expression/Order.java | 10 +- .../ql}/expression/ReferenceAttribute.java | 8 +- .../xpack/ql}/expression/TypeResolutions.java | 48 +- .../xpack/ql}/expression/TypedAttribute.java | 6 +- .../xpack/ql}/expression/UnaryExpression.java | 6 +- .../xpack/ql}/expression/UnresolvedAlias.java | 8 +- .../ql}/expression/UnresolvedAttribute.java | 16 +- .../expression/UnresolvedNamedExpression.java | 10 +- .../xpack/ql}/expression/UnresolvedStar.java | 8 +- .../function/DefaultFunctionTypeRegistry.java | 36 + .../ql}/expression/function/Function.java | 18 +- .../function/FunctionDefinition.java | 20 +- .../expression/function/FunctionRegistry.java | 420 ++++++++++ .../function/FunctionTypeRegistry.java} | 8 +- .../ql}/expression/function/Functions.java | 8 +- .../expression/function/OptionalArgument.java | 15 + .../function/UnresolvedFunction.java | 29 +- .../function/aggregate/AggregateFunction.java | 24 +- .../function/aggregate/CompoundAggregate.java | 21 + .../expression/function/aggregate/Count.java | 13 +- .../function/aggregate/EnclosedAgg.java | 2 +- .../function/aggregate/InnerAggregate.java | 21 +- .../function/grouping/GroupingFunction.java | 20 +- .../function/scalar/BinaryScalarFunction.java | 10 +- .../function/scalar/IntervalScripting.java | 18 + .../function/scalar/ScalarFunction.java | 147 ++++ .../function/scalar/UnaryScalarFunction.java | 16 +- .../whitelist/InternalQlScriptUtils.java | 93 +++ .../gen/pipeline/AggExtractorInput.java | 20 +- .../expression/gen/pipeline/AggNameInput.java | 8 +- .../expression/gen/pipeline/AggPathInput.java | 12 +- .../gen/pipeline/AttributeInput.java | 14 +- .../expression/gen/pipeline/BinaryPipe.java | 10 +- .../pipeline/CommonNonExecutableInput.java | 16 +- .../gen/pipeline/ConstantInput.java | 16 +- .../gen/pipeline/HitExtractorInput.java | 18 +- .../expression/gen/pipeline/LeafInput.java | 6 +- .../expression/gen/pipeline/MultiPipe.java | 8 +- .../gen/pipeline/NonExecutableInput.java | 12 +- .../ql}/expression/gen/pipeline/Pipe.java | 22 +- .../gen/pipeline/ReferenceInput.java | 14 +- .../expression/gen/pipeline/UnaryPipe.java | 16 +- .../gen/processor/BinaryProcessor.java | 2 +- .../processor/BucketExtractorProcessor.java | 8 +- .../gen/processor/ChainingProcessor.java | 2 +- .../gen/processor/ConstantNamedWriteable.java | 16 + .../gen/processor/ConstantProcessor.java | 16 +- .../processor/FunctionalBinaryProcessor.java | 12 +- .../FunctionalEnumBinaryProcessor.java | 33 + .../gen/processor/HitExtractorProcessor.java | 8 +- .../expression/gen/processor/Processor.java | 2 +- .../gen/processor/UnaryProcessor.java | 2 +- .../xpack/ql}/expression/gen/script/Agg.java | 13 +- .../ql}/expression/gen/script/Grouping.java | 4 +- .../ql}/expression/gen/script/Param.java | 2 +- .../ql}/expression/gen/script/Params.java | 6 +- .../expression/gen/script/ParamsBuilder.java | 6 +- .../ql}/expression/gen/script/Script.java | 2 +- .../expression/gen/script/ScriptTemplate.java | 9 +- .../ql}/expression/gen/script/Scripts.java | 22 +- .../xpack/ql}/expression/gen/script/Var.java | 2 +- .../expression/predicate/BinaryOperator.java | 10 +- .../expression/predicate/BinaryPredicate.java | 8 +- .../ql}/expression/predicate/Negatable.java | 4 +- .../predicate/PredicateBiFunction.java | 2 +- .../ql}/expression/predicate/Predicates.java | 14 +- .../xpack/ql}/expression/predicate/Range.java | 41 +- .../predicate/fulltext/FullTextPredicate.java | 13 +- .../predicate/fulltext/FullTextUtils.java | 8 +- .../fulltext/MatchQueryPredicate.java | 13 +- .../fulltext/MultiMatchQueryPredicate.java | 13 +- .../fulltext/StringQueryPredicate.java | 12 +- .../ql}/expression/predicate/logical/And.java | 12 +- .../predicate/logical/BinaryLogic.java | 23 +- .../predicate/logical/BinaryLogicPipe.java | 16 +- .../logical/BinaryLogicProcessor.java | 16 +- .../ql}/expression/predicate/logical/Not.java | 27 +- .../predicate/logical/NotProcessor.java | 8 +- .../ql}/expression/predicate/logical/Or.java | 12 +- .../predicate/operator/arithmetic/Add.java | 29 + .../arithmetic/ArithmeticOperation.java | 21 +- .../operator/arithmetic/Arithmetics.java | 82 +- .../arithmetic/BinaryArithmeticOperation.java | 16 + .../arithmetic/BinaryArithmeticPipe.java | 16 +- .../arithmetic/BinaryArithmeticProcessor.java | 47 ++ .../DateTimeArithmeticOperation.java | 38 + .../DefaultBinaryArithmeticOperation.java | 66 ++ .../predicate/operator/arithmetic/Div.java | 37 + .../predicate/operator/arithmetic/Mod.java | 33 + .../predicate/operator/arithmetic/Mul.java | 51 ++ .../predicate/operator/arithmetic/Neg.java | 26 +- .../predicate/operator/arithmetic/Sub.java | 30 + .../arithmetic/UnaryArithmeticProcessor.java | 8 +- .../operator/comparison/BinaryComparison.java | 23 +- .../comparison/BinaryComparisonPipe.java | 16 +- .../comparison/BinaryComparisonProcessor.java | 12 +- .../operator/comparison/Comparisons.java | 2 +- .../predicate/operator/comparison/Equals.java | 12 +- .../operator/comparison/GreaterThan.java | 12 +- .../comparison/GreaterThanOrEqual.java | 12 +- .../operator/comparison/LessThan.java | 12 +- .../operator/comparison/LessThanOrEqual.java | 12 +- .../operator/comparison/NotEquals.java | 12 +- .../operator/comparison/NullEquals.java | 12 +- .../ql}/expression/predicate/regex/Like.java | 12 +- .../predicate/regex/LikePattern.java | 4 +- .../ql}/expression/predicate/regex/RLike.java | 12 +- .../predicate/regex/RegexMatch.java | 19 +- .../predicate/regex/RegexProcessor.java | 4 +- .../ql/expression/processor/Processors.java | 65 ++ .../xpack/ql}/index/EsIndex.java | 4 +- .../xpack/ql}/index/IndexResolution.java | 2 +- .../xpack/ql}/index/IndexResolver.java | 103 +-- .../xpack/ql}/index/MappingException.java | 6 +- .../xpack/ql}/plan/QueryPlan.java | 16 +- .../xpack/ql}/plan/TableIdentifier.java | 4 +- .../xpack/ql}/plan/logical/Aggregate.java | 16 +- .../xpack/ql}/plan/logical/BinaryPlan.java | 12 +- .../xpack/ql}/plan/logical/EsRelation.java | 16 +- .../xpack/ql}/plan/logical/Filter.java | 10 +- .../xpack/ql}/plan/logical/LeafPlan.java | 6 +- .../xpack/ql}/plan/logical/Limit.java | 10 +- .../xpack/ql}/plan/logical/LogicalPlan.java | 10 +- .../xpack/ql}/plan/logical/OrderBy.java | 12 +- .../xpack/ql}/plan/logical/Project.java | 18 +- .../xpack/ql}/plan/logical/UnaryPlan.java | 11 +- .../ql}/plan/logical/UnresolvedRelation.java | 12 +- .../xpack/ql/plugin/QlPlugin.java | 14 + .../elasticsearch/xpack/ql}/rule/Rule.java | 10 +- .../ql}/rule/RuleExecutionException.java | 6 +- .../xpack/ql}/rule/RuleExecutor.java | 6 +- .../xpack/ql/session/Configuration.java | 41 + .../xpack/ql}/tree/Location.java | 2 +- .../elasticsearch/xpack/ql}/tree/Node.java | 6 +- .../xpack/ql}/tree/NodeInfo.java | 2 +- .../xpack/ql}/tree/NodeUtils.java | 2 +- .../elasticsearch/xpack/ql}/tree/Source.java | 6 +- .../xpack/ql/type/Converter.java | 14 + .../elasticsearch/xpack/ql/type/DataType.java | 112 +++ .../xpack/ql/type/DataTypeConverter.java | 519 +++++++++++++ .../xpack/ql/type/DataTypeRegistry.java | 35 + .../xpack/ql/type/DataTypes.java | 167 ++++ .../xpack/ql}/type/DateEsField.java | 4 +- .../xpack/ql/type/DateUtils.java | 42 + .../ql/type/DefaultDataTypeRegistry.java | 51 ++ .../elasticsearch/xpack/ql}/type/EsField.java | 15 +- .../xpack/ql}/type/InvalidMappedField.java | 8 +- .../xpack/ql}/type/KeywordEsField.java | 24 +- .../elasticsearch/xpack/ql}/type/Schema.java | 9 +- .../xpack/ql/type/StringUtils.java | 145 ++++ .../xpack/ql}/type/TextEsField.java | 13 +- .../elasticsearch/xpack/ql}/type/Types.java | 73 +- .../xpack/ql}/type/UnsupportedEsField.java | 4 +- .../elasticsearch/xpack/ql/util/Check.java | 38 + .../xpack/ql}/util/CollectionUtils.java | 9 +- .../xpack/ql/util/DateUtils.java | 150 ++++ .../xpack/ql}/util/Graphviz.java | 6 +- .../elasticsearch/xpack/ql}/util/Holder.java | 2 +- .../xpack/ql}/util/ReflectionUtils.java | 10 +- .../xpack/ql}/util/StringUtils.java | 30 +- x-pack/plugin/ql/src/main/resources/file.txt | 0 .../org/elasticsearch/xpack/ql/TestUtils.java | 48 ++ .../extractor/ConstantExtractorTests.java | 2 +- .../ql}/expression/AttributeMapTests.java | 4 +- .../ql}/expression/ExpressionIdTests.java | 3 +- .../xpack/ql}/expression/LiteralTests.java | 55 +- .../ql}/expression/NullabilityTests.java | 8 +- .../ql/expression/TyperResolutionTests.java | 26 + .../expression/UnresolvedAttributeTests.java | 8 +- .../function/FunctionRegistryTests.java | 48 +- .../function/NamedExpressionTests.java | 33 +- .../function/TestFunctionRegistry.java | 14 + .../function/UnresolvedFunctionTests.java | 12 +- .../function/scalar/FunctionTestUtils.java | 23 +- .../gen/pipeline/AttributeInputTests.java | 10 +- .../gen/pipeline/BinaryPipesTests.java | 25 +- .../gen/pipeline/UnaryPipeTests.java | 16 +- .../gen/processor/ChainingProcessorTests.java | 24 +- .../gen/processor/ConstantProcessorTests.java | 11 +- .../fulltext/FullTextUtilsTests.java | 10 +- .../logical/BinaryLogicProcessorTests.java | 8 +- .../BinaryArithmeticProcessorTests.java | 26 +- .../BinaryComparisonProcessorTests.java | 15 +- .../xpack/ql}/tree/AbstractNodeTestCase.java | 2 +- .../xpack/ql}/tree/NodeSubclassTests.java | 216 +++--- .../xpack/ql}/tree/NodeTests.java | 4 +- .../xpack/ql}/tree/SourceTests.java | 2 +- .../xpack/ql/tree/TestCompoundAggregate.java | 40 + .../xpack/ql/tree/TestEnclosedAgg.java | 45 ++ .../ql/type/DataTypeConversionTests.java | 401 ++++++++++ .../xpack/ql}/type/TypesTests.java | 65 +- .../resources/mapping-basic-incompatible.json | 0 .../resources/mapping-basic-nodocvalues.json | 0 .../src/test/resources/mapping-basic.json | 0 .../test/resources/mapping-date-multi.json | 0 .../resources/mapping-date-no-format.json | 0 .../src/test/resources/mapping-date.json | 0 .../resources/mapping-default-string.json | 0 .../src/test/resources/mapping-docvalues.json | 0 .../test/resources/mapping-dotted-field.json | 0 .../src/test/resources/mapping-geo.json | 0 .../src/test/resources/mapping-ip.json | 0 .../src/test/resources/mapping-keyword.json | 0 .../mapping-multi-field-options.json | 0 .../mapping-multi-field-variation.json | 0 .../mapping-multi-field-with-nested.json | 0 .../test/resources/mapping-multi-field.json | 0 .../src/test/resources/mapping-nested.json | 0 .../src/test/resources/mapping-numeric.json | 0 .../src/test/resources/mapping-object.json | 0 .../test/resources/mapping-parent-child.json | 0 .../src/test/resources/mapping-text.json | 0 .../test/resources/mapping-unsupported.json | 0 x-pack/plugin/sql/build.gradle | 7 +- .../src/main/resources/conditionals.csv-spec | 2 +- .../xpack/sql/proto/StringUtils.java | 40 +- ...Exception.java => SqlClientException.java} | 14 +- .../sql/SqlIllegalArgumentException.java | 4 +- ...Exception.java => SqlServerException.java} | 14 +- .../xpack/sql/analysis/AnalysisException.java | 8 +- .../xpack/sql/analysis/analyzer/Analyzer.java | 88 +-- .../sql/analysis/analyzer/PreAnalyzer.java | 4 +- .../sql/analysis/analyzer/TableInfo.java | 2 +- .../analyzer/VerificationException.java | 4 +- .../xpack/sql/analysis/analyzer/Verifier.java | 79 +- .../xpack/sql/execution/PlanExecutor.java | 7 +- .../execution/search/CompositeAggCursor.java | 6 +- .../execution/search/CompositeAggRowSet.java | 2 +- .../sql/execution/search/PivotCursor.java | 4 +- .../sql/execution/search/PivotRowSet.java | 4 +- .../xpack/sql/execution/search/Querier.java | 108 ++- .../search/SchemaCompositeAggRowSet.java | 4 +- .../search/SchemaDelegatingRowSet.java | 2 +- .../search/SchemaSearchHitRowSet.java | 4 +- .../sql/execution/search/ScrollCursor.java | 4 +- .../sql/execution/search/SearchHitRowSet.java | 2 +- .../sql/execution/search/SourceGenerator.java | 15 +- .../extractor/CompositeKeyExtractor.java | 1 + .../search/extractor/FieldHitExtractor.java | 339 ++------ .../search/extractor/MetricAggExtractor.java | 3 +- .../search/extractor/PivotExtractor.java | 1 + .../search/extractor/ScoreExtractor.java | 1 + ...tractors.java => SqlBucketExtractors.java} | 13 +- .../search/extractor/SqlHitExtractors.java | 31 + .../search/extractor/TopHitsAggExtractor.java | 12 +- .../xpack/sql/expression/Exists.java | 14 +- .../xpack/sql/expression/Foldables.java | 24 +- .../xpack/sql/expression/ScalarSubquery.java | 10 +- .../sql/expression/SqlTypeResolutions.java | 41 + .../sql/expression/SubQueryExpression.java | 6 +- .../expression/function/FunctionRegistry.java | 653 ---------------- .../sql/expression/function/FunctionType.java | 37 - .../xpack/sql/expression/function/Score.java | 16 +- .../function/SqlFunctionRegistry.java | 265 +++++++ .../function/SqlFunctionTypeRegistry.java | 40 + .../expression/function/aggregate/Avg.java | 12 +- .../aggregate/CompoundNumericAggregate.java | 7 +- .../function/aggregate/ExtendedStats.java | 7 +- .../aggregate/ExtendedStatsEnclosed.java | 2 + .../expression/function/aggregate/First.java | 6 +- .../function/aggregate/Kurtosis.java | 7 +- .../expression/function/aggregate/Last.java | 6 +- .../function/aggregate/MatrixStats.java | 7 +- .../aggregate/MatrixStatsEnclosed.java | 2 + .../expression/function/aggregate/Max.java | 18 +- .../aggregate/MedianAbsoluteDeviation.java | 11 +- .../expression/function/aggregate/Min.java | 18 +- .../function/aggregate/NumericAggregate.java | 14 +- .../function/aggregate/Percentile.java | 18 +- .../function/aggregate/PercentileRank.java | 19 +- .../function/aggregate/PercentileRanks.java | 7 +- .../function/aggregate/Percentiles.java | 7 +- .../function/aggregate/Skewness.java | 7 +- .../expression/function/aggregate/Stats.java | 7 +- .../function/aggregate/StddevPop.java | 7 +- .../expression/function/aggregate/Sum.java | 10 +- .../function/aggregate/SumOfSquares.java | 7 +- .../function/aggregate/TopHits.java | 16 +- .../expression/function/aggregate/VarPop.java | 7 +- .../function/grouping/Histogram.java | 24 +- .../sql/expression/function/scalar/Cast.java | 31 +- .../function/scalar/CastProcessor.java | 16 +- .../scalar/ConfigurationFunction.java | 13 +- .../expression/function/scalar/Database.java | 10 +- .../function/scalar/Processors.java | 54 +- .../function/scalar/ScalarFunction.java | 38 - .../sql/expression/function/scalar/User.java | 10 +- .../scalar/datetime/BaseDateTimeFunction.java | 12 +- .../datetime/BaseDateTimeProcessor.java | 2 +- .../datetime/BinaryDateTimeFunction.java | 18 +- .../scalar/datetime/BinaryDateTimePipe.java | 10 +- .../datetime/BinaryDateTimeProcessor.java | 4 +- .../function/scalar/datetime/CurrentDate.java | 10 +- .../scalar/datetime/CurrentDateTime.java | 12 +- .../scalar/datetime/CurrentFunction.java | 6 +- .../function/scalar/datetime/CurrentTime.java | 12 +- .../function/scalar/datetime/DateAdd.java | 21 +- .../function/scalar/datetime/DateAddPipe.java | 10 +- .../scalar/datetime/DateAddProcessor.java | 2 +- .../function/scalar/datetime/DateDiff.java | 21 +- .../scalar/datetime/DateDiffPipe.java | 10 +- .../scalar/datetime/DateDiffProcessor.java | 2 +- .../function/scalar/datetime/DatePart.java | 18 +- .../scalar/datetime/DatePartPipe.java | 10 +- .../scalar/datetime/DatePartProcessor.java | 5 +- .../scalar/datetime/DateTimeField.java | 2 +- .../scalar/datetime/DateTimeFunction.java | 17 +- .../datetime/DateTimeHistogramFunction.java | 4 +- .../function/scalar/datetime/DateTrunc.java | 15 +- .../scalar/datetime/DateTruncPipe.java | 10 +- .../scalar/datetime/DateTruncProcessor.java | 5 +- .../function/scalar/datetime/DayName.java | 6 +- .../function/scalar/datetime/DayOfMonth.java | 6 +- .../function/scalar/datetime/DayOfWeek.java | 6 +- .../function/scalar/datetime/DayOfYear.java | 8 +- .../function/scalar/datetime/HourOfDay.java | 6 +- .../scalar/datetime/IsoDayOfWeek.java | 6 +- .../scalar/datetime/IsoWeekOfYear.java | 6 +- .../function/scalar/datetime/MinuteOfDay.java | 6 +- .../scalar/datetime/MinuteOfHour.java | 6 +- .../function/scalar/datetime/MonthName.java | 6 +- .../function/scalar/datetime/MonthOfYear.java | 6 +- .../datetime/NamedDateTimeFunction.java | 19 +- .../datetime/NonIsoDateTimeFunction.java | 19 +- .../function/scalar/datetime/Quarter.java | 19 +- .../scalar/datetime/SecondOfMinute.java | 6 +- .../datetime/ThreeArgsDateTimeFunction.java | 14 +- .../datetime/ThreeArgsDateTimePipe.java | 8 +- .../datetime/ThreeArgsDateTimeProcessor.java | 2 +- .../scalar/datetime/TimeFunction.java | 10 +- .../function/scalar/datetime/WeekOfYear.java | 6 +- .../function/scalar/datetime/Year.java | 6 +- .../function/scalar/geo/GeoProcessor.java | 3 +- .../function/scalar/geo/StAswkt.java | 11 +- .../function/scalar/geo/StDistance.java | 25 +- .../scalar/geo/StDistanceFunction.java | 2 +- .../function/scalar/geo/StDistancePipe.java | 10 +- .../scalar/geo/StDistanceProcessor.java | 5 +- .../function/scalar/geo/StGeometryType.java | 11 +- .../function/scalar/geo/StWkttosql.java | 24 +- .../scalar/geo/StWkttosqlProcessor.java | 3 +- .../expression/function/scalar/geo/StX.java | 11 +- .../expression/function/scalar/geo/StY.java | 11 +- .../expression/function/scalar/geo/StZ.java | 11 +- .../function/scalar/geo/UnaryGeoFunction.java | 20 +- .../expression/function/scalar/math/ACos.java | 6 +- .../expression/function/scalar/math/ASin.java | 6 +- .../expression/function/scalar/math/ATan.java | 6 +- .../function/scalar/math/ATan2.java | 6 +- .../expression/function/scalar/math/Abs.java | 8 +- .../function/scalar/math/BinaryMathPipe.java | 10 +- .../scalar/math/BinaryMathProcessor.java | 8 +- .../scalar/math/BinaryNumericFunction.java | 19 +- .../scalar/math/BinaryOptionalMathPipe.java | 12 +- .../math/BinaryOptionalMathProcessor.java | 2 +- .../math/BinaryOptionalNumericFunction.java | 25 +- .../expression/function/scalar/math/Cbrt.java | 6 +- .../expression/function/scalar/math/Ceil.java | 14 +- .../expression/function/scalar/math/Cos.java | 6 +- .../expression/function/scalar/math/Cosh.java | 6 +- .../expression/function/scalar/math/Cot.java | 6 +- .../function/scalar/math/Degrees.java | 6 +- .../expression/function/scalar/math/E.java | 18 +- .../expression/function/scalar/math/Exp.java | 6 +- .../function/scalar/math/Expm1.java | 6 +- .../function/scalar/math/Floor.java | 14 +- .../expression/function/scalar/math/Log.java | 6 +- .../function/scalar/math/Log10.java | 6 +- .../function/scalar/math/MathFunction.java | 17 +- .../function/scalar/math/MathProcessor.java | 69 +- .../expression/function/scalar/math/Pi.java | 18 +- .../function/scalar/math/Power.java | 6 +- .../function/scalar/math/Radians.java | 6 +- .../function/scalar/math/Random.java | 6 +- .../function/scalar/math/Round.java | 9 +- .../expression/function/scalar/math/Sign.java | 11 +- .../expression/function/scalar/math/Sin.java | 6 +- .../expression/function/scalar/math/Sinh.java | 6 +- .../expression/function/scalar/math/Sqrt.java | 6 +- .../expression/function/scalar/math/Tan.java | 6 +- .../function/scalar/math/Truncate.java | 9 +- .../function/scalar/string/Ascii.java | 11 +- .../scalar/string/BinaryStringFunction.java | 16 +- .../string/BinaryStringNumericFunction.java | 15 +- .../string/BinaryStringNumericPipe.java | 10 +- .../string/BinaryStringNumericProcessor.java | 6 +- .../string/BinaryStringStringFunction.java | 13 +- .../scalar/string/BinaryStringStringPipe.java | 10 +- .../string/BinaryStringStringProcessor.java | 6 +- .../function/scalar/string/BitLength.java | 11 +- .../function/scalar/string/Char.java | 11 +- .../function/scalar/string/CharLength.java | 11 +- .../function/scalar/string/Concat.java | 29 +- .../scalar/string/ConcatFunctionPipe.java | 10 +- .../string/ConcatFunctionProcessor.java | 6 +- .../function/scalar/string/Insert.java | 29 +- .../scalar/string/InsertFunctionPipe.java | 12 +- .../string/InsertFunctionProcessor.java | 2 +- .../function/scalar/string/LCase.java | 11 +- .../function/scalar/string/LTrim.java | 11 +- .../function/scalar/string/Left.java | 6 +- .../function/scalar/string/Length.java | 11 +- .../function/scalar/string/Locate.java | 32 +- .../scalar/string/LocateFunctionPipe.java | 12 +- .../string/LocateFunctionProcessor.java | 2 +- .../function/scalar/string/OctetLength.java | 11 +- .../function/scalar/string/Position.java | 10 +- .../function/scalar/string/RTrim.java | 11 +- .../function/scalar/string/Repeat.java | 6 +- .../function/scalar/string/Replace.java | 27 +- .../scalar/string/ReplaceFunctionPipe.java | 12 +- .../string/ReplaceFunctionProcessor.java | 2 +- .../function/scalar/string/Right.java | 6 +- .../function/scalar/string/Space.java | 11 +- .../scalar/string/StringProcessor.java | 2 +- .../function/scalar/string/Substring.java | 29 +- .../scalar/string/SubstringFunctionPipe.java | 12 +- .../string/SubstringFunctionProcessor.java | 2 +- .../function/scalar/string/UCase.java | 11 +- .../scalar/string/UnaryStringFunction.java | 20 +- .../scalar/string/UnaryStringIntFunction.java | 18 +- .../scalar/whitelist/InternalScriptUtils.java | 11 + .../whitelist/InternalSqlScriptUtils.java | 159 ++-- .../expression/gen/pipeline/ScorePipe.java | 15 +- .../expression/gen/script/ScriptWeaver.java | 149 ---- .../sql/expression/literal/Literals.java | 11 +- .../scalar => literal}/geo/GeoShape.java | 20 +- .../literal/{ => interval}/Interval.java | 23 +- .../literal/interval/IntervalArithmetics.java | 72 ++ .../{ => interval}/IntervalDayTime.java | 21 +- .../{ => interval}/IntervalYearMonth.java | 25 +- .../literal/{ => interval}/Intervals.java | 140 +++- .../ArbitraryConditionalFunction.java | 14 +- .../predicate/conditional/Case.java | 50 +- .../predicate/conditional/CasePipe.java | 12 +- .../predicate/conditional/CaseProcessor.java | 2 +- .../predicate/conditional/Coalesce.java | 6 +- .../conditional/ConditionalFunction.java | 33 +- .../conditional/ConditionalPipe.java | 12 +- .../conditional/ConditionalProcessor.java | 2 +- .../predicate/conditional/Conditionals.java | 4 +- .../predicate/conditional/Greatest.java | 8 +- .../predicate/conditional/IfConditional.java | 10 +- .../predicate/conditional/IfNull.java | 6 +- .../expression/predicate/conditional/Iif.java | 27 +- .../predicate/conditional/Least.java | 8 +- .../predicate/conditional/NullIf.java | 16 +- .../predicate/conditional/NullIfPipe.java | 12 +- .../conditional/NullIfProcessor.java | 4 +- .../predicate/nulls/CheckNullProcessor.java | 2 +- .../expression/predicate/nulls/IsNotNull.java | 23 +- .../expression/predicate/nulls/IsNull.java | 23 +- .../predicate/operator/arithmetic/Add.java | 9 +- .../arithmetic/BinaryArithmeticProcessor.java | 186 ----- .../DateTimeArithmeticOperation.java | 21 +- .../predicate/operator/arithmetic/Div.java | 17 +- .../predicate/operator/arithmetic/Mod.java | 11 +- .../predicate/operator/arithmetic/Mul.java | 21 +- .../arithmetic/SqlArithmeticOperation.java | 31 + .../SqlBinaryArithmeticOperation.java | 154 ++++ .../predicate/operator/arithmetic/Sub.java | 14 +- .../predicate/operator/comparison/In.java | 42 +- .../predicate/operator/comparison/InPipe.java | 12 +- .../operator/comparison/InProcessor.java | 23 +- .../xpack/sql/optimizer/Optimizer.java | 162 ++-- .../elasticsearch/xpack/sql/package-info.java | 10 +- .../xpack/sql/parser/AbstractBuilder.java | 6 +- .../xpack/sql/parser/AstBuilder.java | 2 +- .../xpack/sql/parser/CommandBuilder.java | 10 +- .../xpack/sql/parser/ExpressionBuilder.java | 115 +-- .../xpack/sql/parser/IdentifierBuilder.java | 4 +- .../xpack/sql/parser/LogicalPlanBuilder.java | 36 +- .../xpack/sql/parser/ParsingException.java | 6 +- .../xpack/sql/parser/SqlParser.java | 4 +- .../xpack/sql/plan/logical/Distinct.java | 6 +- .../xpack/sql/plan/logical/Join.java | 18 +- .../xpack/sql/plan/logical/LocalRelation.java | 11 +- .../xpack/sql/plan/logical/Pivot.java | 26 +- .../xpack/sql/plan/logical/SubQueryAlias.java | 8 +- .../xpack/sql/plan/logical/With.java | 8 +- .../sql/plan/logical/command/Command.java | 16 +- .../xpack/sql/plan/logical/command/Debug.java | 24 +- .../sql/plan/logical/command/Explain.java | 16 +- .../sql/plan/logical/command/ShowColumns.java | 19 +- .../plan/logical/command/ShowFunctions.java | 20 +- .../sql/plan/logical/command/ShowSchemas.java | 10 +- .../sql/plan/logical/command/ShowTables.java | 10 +- .../plan/logical/command/sys/SysColumns.java | 48 +- .../plan/logical/command/sys/SysTables.java | 16 +- .../plan/logical/command/sys/SysTypes.java | 47 +- .../sql/plan/physical/AggregateExec.java | 13 +- .../xpack/sql/plan/physical/BinaryExec.java | 4 +- .../xpack/sql/plan/physical/CommandExec.java | 6 +- .../xpack/sql/plan/physical/EsQueryExec.java | 6 +- .../xpack/sql/plan/physical/FilterExec.java | 10 +- .../xpack/sql/plan/physical/LeafExec.java | 18 +- .../xpack/sql/plan/physical/LimitExec.java | 8 +- .../xpack/sql/plan/physical/LocalExec.java | 6 +- .../xpack/sql/plan/physical/OrderExec.java | 8 +- .../xpack/sql/plan/physical/PhysicalPlan.java | 10 +- .../xpack/sql/plan/physical/PivotExec.java | 6 +- .../xpack/sql/plan/physical/ProjectExec.java | 12 +- .../xpack/sql/plan/physical/UnaryExec.java | 11 +- .../xpack/sql/plan/physical/Unexecutable.java | 4 +- .../sql/plan/physical/UnplannedExec.java | 19 +- .../xpack/sql/planner/FoldingException.java | 8 +- .../xpack/sql/planner/Mapper.java | 22 +- .../xpack/sql/planner/Planner.java | 4 +- .../xpack/sql/planner/PlanningException.java | 6 +- .../xpack/sql/planner/QueryFolder.java | 77 +- .../xpack/sql/planner/QueryTranslator.java | 72 +- .../xpack/sql/planner/Verifier.java | 4 +- .../xpack/sql/plugin/SqlPlugin.java | 5 +- .../xpack/sql/plugin/TextFormat.java | 2 +- .../plugin/TransportSqlClearCursorAction.java | 2 +- .../sql/plugin/TransportSqlQueryAction.java | 7 +- .../plugin/TransportSqlTranslateAction.java | 2 +- .../xpack/sql/querydsl/agg/AggFilter.java | 4 +- .../xpack/sql/querydsl/agg/Aggs.java | 6 +- .../xpack/sql/querydsl/agg/AndAggFilter.java | 2 +- .../querydsl/agg/GroupByDateHistogram.java | 2 +- .../xpack/sql/querydsl/agg/GroupByKey.java | 22 +- .../querydsl/agg/GroupByNumericHistogram.java | 2 +- .../xpack/sql/querydsl/agg/GroupByValue.java | 2 +- .../xpack/sql/querydsl/agg/OrAggFilter.java | 2 +- .../xpack/sql/querydsl/agg/TopHitsAgg.java | 9 +- .../sql/querydsl/container/AggregateSort.java | 2 +- .../sql/querydsl/container/AttributeSort.java | 2 +- .../sql/querydsl/container/ComputedRef.java | 8 +- .../querydsl/container/FieldReference.java | 2 +- .../querydsl/container/GlobalCountRef.java | 2 +- .../sql/querydsl/container/GroupByRef.java | 2 +- .../sql/querydsl/container/MetricAggRef.java | 2 +- .../querydsl/container/PivotColumnRef.java | 4 +- .../querydsl/container/QueryContainer.java | 37 +- .../querydsl/container/ScriptFieldRef.java | 6 +- .../sql/querydsl/container/ScriptSort.java | 4 +- .../querydsl/container/SearchHitFieldRef.java | 12 +- .../xpack/sql/querydsl/container/Sort.java | 4 +- .../sql/querydsl/container/TopHitsAggRef.java | 6 +- .../xpack/sql/querydsl/query/BoolQuery.java | 2 +- .../xpack/sql/querydsl/query/ExistsQuery.java | 2 +- .../sql/querydsl/query/GeoDistanceQuery.java | 2 +- .../xpack/sql/querydsl/query/LeafQuery.java | 2 +- .../xpack/sql/querydsl/query/MatchAll.java | 2 +- .../xpack/sql/querydsl/query/MatchQuery.java | 4 +- .../sql/querydsl/query/MultiMatchQuery.java | 4 +- .../xpack/sql/querydsl/query/NestedQuery.java | 2 +- .../xpack/sql/querydsl/query/NotQuery.java | 2 +- .../xpack/sql/querydsl/query/Query.java | 2 +- .../sql/querydsl/query/QueryStringQuery.java | 4 +- .../xpack/sql/querydsl/query/RangeQuery.java | 6 +- .../xpack/sql/querydsl/query/RegexQuery.java | 6 +- .../xpack/sql/querydsl/query/ScriptQuery.java | 6 +- .../xpack/sql/querydsl/query/TermQuery.java | 6 +- .../xpack/sql/querydsl/query/TermsQuery.java | 7 +- .../sql/querydsl/query/WildcardQuery.java | 6 +- .../xpack/sql/session/Configuration.java | 31 +- .../xpack/sql/session/Cursors.java | 10 +- .../xpack/sql/session/EmptyExecutable.java | 4 +- .../xpack/sql/session/EmptyRowSet.java | 2 +- .../xpack/sql/session/Executable.java | 5 +- .../xpack/sql/session/ListCursor.java | 2 +- .../xpack/sql/session/ListRowSet.java | 2 +- .../elasticsearch/xpack/sql/session/Rows.java | 6 +- .../xpack/sql/session/SchemaRowSet.java | 2 +- .../xpack/sql/session/Session.java | 11 + .../sql/session/SingletonExecutable.java | 4 +- .../xpack/sql/session/SingletonRowSet.java | 2 +- .../xpack/sql/session/SqlExecutable.java | 19 + .../xpack/sql/session/SqlSession.java | 16 +- .../xpack/sql/stats/QueryMetric.java | 1 + .../xpack/sql/type/DataType.java | 345 --------- .../xpack/sql/type/DataTypeConversion.java | 702 ----------------- .../xpack/sql/type/DataTypes.java | 218 ------ .../xpack/sql/type/SqlDataTypeConverter.java | 453 +++++++++++ .../xpack/sql/type/SqlDataTypeRegistry.java | 56 ++ .../xpack/sql/type/SqlDataTypes.java | 727 ++++++++++++++++++ .../xpack/sql/util/DateUtils.java | 3 +- .../xpack/sql/plugin/sql_whitelist.txt | 59 +- .../sql/{TestUtils.java => SqlTestUtils.java} | 18 +- .../analyzer/FieldAttributeTests.java | 48 +- .../analysis/analyzer/PreAnalyzerTests.java | 2 +- .../analyzer/VerifierErrorMessagesTests.java | 33 +- .../analysis/index/IndexResolverTests.java | 133 ++-- .../CompositeAggregationCursorTests.java | 4 +- .../execution/search/ScrollCursorTests.java | 4 +- .../search/SourceGeneratorTests.java | 14 +- .../search/SqlSourceBuilderTests.java | 3 +- .../extractor/CompositeKeyExtractorTests.java | 1 + .../extractor/ComputingExtractorTests.java | 19 +- .../extractor/FieldHitExtractorTests.java | 60 +- .../extractor/MetricAggExtractorTests.java | 8 +- .../extractor/TopHitsAggExtractorTests.java | 15 +- .../xpack/sql/expression/ProcessorTests.java | 23 +- ...ionTests.java => TypeResolutionTests.java} | 21 +- .../function/scalar/CastProcessorTests.java | 15 +- .../scalar/DatabaseFunctionTests.java | 18 +- .../function/scalar/UserFunctionTests.java | 18 +- .../scalar/datetime/CurrentDateTests.java | 12 +- .../scalar/datetime/CurrentDateTimeTests.java | 50 +- .../scalar/datetime/CurrentTimeTests.java | 50 +- .../scalar/datetime/DateAddPipeTests.java | 22 +- .../datetime/DateAddProcessorTests.java | 14 +- .../scalar/datetime/DateDiffPipeTests.java | 20 +- .../datetime/DateDiffProcessorTests.java | 12 +- .../scalar/datetime/DatePartPipeTests.java | 22 +- .../datetime/DatePartProcessorTests.java | 12 +- .../scalar/datetime/DateTimeTestUtils.java | 4 - .../scalar/datetime/DateTruncPipeTests.java | 22 +- .../datetime/DateTruncProcessorTests.java | 12 +- .../scalar/datetime/DayOfYearTests.java | 8 +- .../scalar/geo/GeoProcessorTests.java | 1 + .../scalar/geo/StDistanceProcessorTests.java | 17 +- .../scalar/geo/StWkttosqlProcessorTests.java | 11 +- .../scalar/math/BinaryMathProcessorTests.java | 11 +- .../scalar/math/MathOperationTests.java | 38 + .../string/BinaryStringNumericPipeTests.java | 18 +- .../BinaryStringNumericProcessorTests.java | 6 +- .../string/BinaryStringStringPipeTests.java | 16 +- .../BinaryStringStringProcessorTests.java | 6 +- .../string/ConcatFunctionPipeTests.java | 16 +- .../scalar/string/ConcatProcessorTests.java | 6 +- .../string/InsertFunctionPipeTests.java | 18 +- .../scalar/string/InsertProcessorTests.java | 6 +- .../string/LocateFunctionPipeTests.java | 18 +- .../scalar/string/LocateProcessorTests.java | 6 +- .../string/ReplaceFunctionPipeTests.java | 16 +- .../scalar/string/ReplaceProcessorTests.java | 6 +- .../string/SubstringFunctionPipeTests.java | 18 +- .../string/SubstringProcessorTests.java | 6 +- .../{ => interval}/IntervalsTests.java | 40 +- .../{ => parser}/ParameterTests.java | 27 +- .../expression/{ => parser}/QuotingTests.java | 14 +- .../predicate/conditional/CaseTests.java | 53 +- .../predicate/conditional/IifTests.java | 30 +- .../nulls/CheckNullProcessorTests.java | 9 +- ...sts.java => SqlBinaryArithmeticTests.java} | 45 +- .../operator/comparison/InProcessorTests.java | 15 +- .../operator/comparison/InTests.java | 10 +- .../sql/optimizer/OptimizerRunTests.java | 18 +- .../xpack/sql/optimizer/OptimizerTests.java | 204 ++--- .../sql/parser/EscapedFunctionsTests.java | 41 +- .../xpack/sql/parser/ExpressionTests.java | 119 +-- .../sql/parser/LikeEscapingParsingTests.java | 10 +- .../xpack/sql/parser/SqlParserTests.java | 30 +- .../plan/logical/UnresolvedRelationTests.java | 7 +- .../logical/command/ShowFunctionsTests.java | 32 + .../logical/command/sys/SysColumnsTests.java | 30 +- .../logical/command/sys/SysTablesTests.java | 28 +- .../logical/command/sys/SysTypesTests.java | 37 +- .../planner/PostOptimizerVerifierTests.java | 16 +- .../xpack/sql/planner/QueryFolderTests.java | 20 +- .../sql/planner/QueryTranslatorTests.java | 131 ++-- .../xpack/sql/plugin/CursorTests.java | 11 +- .../container/QueryContainerTests.java | 20 +- .../sql/querydsl/query/BoolQueryTests.java | 6 +- .../sql/querydsl/query/LeafQueryTests.java | 6 +- .../sql/querydsl/query/MatchQueryTests.java | 20 +- .../querydsl/query/MultiMatchQueryTests.java | 6 +- .../sql/querydsl/query/NestedQueryTests.java | 6 +- .../querydsl/query/QueryStringQueryTests.java | 6 +- .../xpack/sql/stats/VerifierMetricsTests.java | 18 +- .../xpack/sql/tree/SqlNodeSubclassTests.java | 95 +++ ...ts.java => SqlDataTypeConverterTests.java} | 332 ++++---- ...TypesTests.java => SqlDataTypesTests.java} | 94 ++- .../xpack/sql/types/SqlTypesTests.java | 84 ++ .../xpack/sql/util/LikeConversionTests.java | 6 +- 701 files changed, 10786 insertions(+), 7211 deletions(-) create mode 100644 x-pack/plugin/ql/build.gradle create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/ParsingException.java create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/QlClientException.java rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql/SqlException.java => ql/src/main/java/org/elasticsearch/xpack/ql/QlException.java} (53%) create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/QlIllegalArgumentException.java create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/QlServerException.java rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/capabilities/Resolvable.java (85%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/capabilities/Resolvables.java (91%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/capabilities/Unresolvable.java (89%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/capabilities/UnresolvedException.java (75%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/execution/search/AggRef.java (82%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/execution/search/FieldExtraction.java (88%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/SqlSourceBuilder.java => ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/QlSourceBuilder.java} (84%) create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/extractor/AbstractFieldHitExtractor.java rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/execution/search/extractor/BucketExtractor.java (89%) create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/extractor/BucketExtractors.java rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/execution/search/extractor/ComputingExtractor.java (90%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/execution/search/extractor/ConstantExtractor.java (96%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/execution/search/extractor/HitExtractor.java (91%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/execution/search/extractor/HitExtractors.java (78%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/Alias.java (93%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/Attribute.java (97%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/AttributeMap.java (99%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/AttributeSet.java (98%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/Expression.java (84%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/ExpressionSet.java (98%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/Expressions.java (89%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/FieldAttribute.java (89%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/LeafExpression.java (88%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/Literal.java (67%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/NameId.java (96%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/NamedExpression.java (95%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/Nullability.java (96%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/Order.java (90%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/ReferenceAttribute.java (87%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/TypeResolutions.java (71%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/TypedAttribute.java (87%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/UnaryExpression.java (92%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/UnresolvedAlias.java (90%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/UnresolvedAttribute.java (90%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/UnresolvedNamedExpression.java (78%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/UnresolvedStar.java (91%) create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/DefaultFunctionTypeRegistry.java rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/function/Function.java (81%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/function/FunctionDefinition.java (72%) create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/FunctionRegistry.java rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql/expression/NullIntolerant.java => ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/FunctionTypeRegistry.java} (57%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/function/Functions.java (63%) create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/OptionalArgument.java rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/function/UnresolvedFunction.java (91%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/function/aggregate/AggregateFunction.java (73%) create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/aggregate/CompoundAggregate.java rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/function/aggregate/Count.java (82%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/function/aggregate/EnclosedAgg.java (85%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/function/aggregate/InnerAggregate.java (78%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/function/grouping/GroupingFunction.java (73%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/function/scalar/BinaryScalarFunction.java (85%) create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/scalar/IntervalScripting.java create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/scalar/ScalarFunction.java rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/function/scalar/UnaryScalarFunction.java (76%) create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/scalar/whitelist/InternalQlScriptUtils.java rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/pipeline/AggExtractorInput.java (63%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/pipeline/AggNameInput.java (78%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/pipeline/AggPathInput.java (84%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/pipeline/AttributeInput.java (71%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/pipeline/BinaryPipe.java (88%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/pipeline/CommonNonExecutableInput.java (59%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/pipeline/ConstantInput.java (65%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/pipeline/HitExtractorInput.java (62%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/pipeline/LeafInput.java (89%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/pipeline/MultiPipe.java (76%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/pipeline/NonExecutableInput.java (59%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/pipeline/Pipe.java (75%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/pipeline/ReferenceInput.java (67%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/pipeline/UnaryPipe.java (83%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/processor/BinaryProcessor.java (96%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/processor/BucketExtractorProcessor.java (86%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/processor/ChainingProcessor.java (96%) create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/ConstantNamedWriteable.java rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/processor/ConstantProcessor.java (77%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/processor/FunctionalBinaryProcessor.java (82%) create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/FunctionalEnumBinaryProcessor.java rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/processor/HitExtractorProcessor.java (86%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/processor/Processor.java (91%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/processor/UnaryProcessor.java (96%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/script/Agg.java (74%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/script/Grouping.java (78%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/script/Param.java (94%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/script/Params.java (95%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/script/ParamsBuilder.java (82%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/script/Script.java (87%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/script/ScriptTemplate.java (89%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/script/Scripts.java (78%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/gen/script/Var.java (87%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/BinaryOperator.java (80%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/BinaryPredicate.java (89%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/Negatable.java (70%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/PredicateBiFunction.java (92%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/Predicates.java (88%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/Range.java (79%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/fulltext/FullTextPredicate.java (84%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/fulltext/FullTextUtils.java (91%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/fulltext/MatchQueryPredicate.java (87%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/fulltext/MultiMatchQueryPredicate.java (88%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/fulltext/StringQueryPredicate.java (83%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/logical/And.java (71%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/logical/BinaryLogic.java (59%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/logical/BinaryLogicPipe.java (75%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/logical/BinaryLogicProcessor.java (79%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/logical/Not.java (64%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/logical/NotProcessor.java (82%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/logical/Or.java (71%) create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/Add.java rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/operator/arithmetic/ArithmeticOperation.java (59%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/operator/arithmetic/Arithmetics.java (69%) create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/BinaryArithmeticOperation.java rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/operator/arithmetic/BinaryArithmeticPipe.java (72%) create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/BinaryArithmeticProcessor.java create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/DateTimeArithmeticOperation.java create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/DefaultBinaryArithmeticOperation.java create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/Div.java create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/Mod.java create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/Mul.java rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/operator/arithmetic/Neg.java (62%) create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/Sub.java rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/operator/arithmetic/UnaryArithmeticProcessor.java (85%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/operator/comparison/BinaryComparison.java (64%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/operator/comparison/BinaryComparisonPipe.java (75%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/operator/comparison/BinaryComparisonProcessor.java (79%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/operator/comparison/Comparisons.java (97%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/operator/comparison/Equals.java (69%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/operator/comparison/GreaterThan.java (70%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/operator/comparison/GreaterThanOrEqual.java (71%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/operator/comparison/LessThan.java (70%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/operator/comparison/LessThanOrEqual.java (71%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/operator/comparison/NotEquals.java (70%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/operator/comparison/NullEquals.java (70%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/regex/Like.java (71%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/regex/LikePattern.java (94%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/regex/RLike.java (70%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/regex/RegexMatch.java (70%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/expression/predicate/regex/RegexProcessor.java (94%) create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/processor/Processors.java rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql/analysis => ql/src/main/java/org/elasticsearch/xpack/ql}/index/EsIndex.java (88%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql/analysis => ql/src/main/java/org/elasticsearch/xpack/ql}/index/IndexResolution.java (97%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql/analysis => ql/src/main/java/org/elasticsearch/xpack/ql}/index/IndexResolver.java (85%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql/analysis => ql/src/main/java/org/elasticsearch/xpack/ql}/index/MappingException.java (77%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/plan/QueryPlan.java (92%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/plan/TableIdentifier.java (94%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/plan/logical/Aggregate.java (81%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/plan/logical/BinaryPlan.java (77%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/plan/logical/EsRelation.java (90%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/plan/logical/Filter.java (88%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/plan/logical/LeafPlan.java (86%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/plan/logical/Limit.java (86%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/plan/logical/LogicalPlan.java (88%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/plan/logical/OrderBy.java (84%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/plan/logical/Project.java (80%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/plan/logical/UnaryPlan.java (88%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/plan/logical/UnresolvedRelation.java (89%) create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plugin/QlPlugin.java rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/rule/Rule.java (90%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/rule/RuleExecutionException.java (68%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/rule/RuleExecutor.java (97%) create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/session/Configuration.java rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/tree/Location.java (96%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/tree/Node.java (98%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/tree/NodeInfo.java (99%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/tree/NodeUtils.java (98%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/tree/Source.java (91%) create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/Converter.java create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/DataType.java create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/DataTypeConverter.java create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/DataTypeRegistry.java create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/DataTypes.java rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/type/DateEsField.java (81%) create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/DateUtils.java create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/DefaultDataTypeRegistry.java rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/type/EsField.java (86%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/type/InvalidMappedField.java (82%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/type/KeywordEsField.java (77%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/type/Schema.java (92%) create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/StringUtils.java rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/type/TextEsField.java (81%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/type/Types.java (58%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/type/UnsupportedEsField.java (94%) create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/util/Check.java rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/util/CollectionUtils.java (91%) create mode 100644 x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/util/DateUtils.java rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/util/Graphviz.java (99%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/util/Holder.java (93%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/util/ReflectionUtils.java (81%) rename x-pack/plugin/{sql/src/main/java/org/elasticsearch/xpack/sql => ql/src/main/java/org/elasticsearch/xpack/ql}/util/StringUtils.java (89%) create mode 100644 x-pack/plugin/ql/src/main/resources/file.txt create mode 100644 x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/TestUtils.java rename x-pack/plugin/{sql/src/test/java/org/elasticsearch/xpack/sql => ql/src/test/java/org/elasticsearch/xpack/ql}/execution/search/extractor/ConstantExtractorTests.java (96%) rename x-pack/plugin/{sql/src/test/java/org/elasticsearch/xpack/sql => ql/src/test/java/org/elasticsearch/xpack/ql}/expression/AttributeMapTests.java (98%) rename x-pack/plugin/{sql/src/test/java/org/elasticsearch/xpack/sql => ql/src/test/java/org/elasticsearch/xpack/ql}/expression/ExpressionIdTests.java (93%) rename x-pack/plugin/{sql/src/test/java/org/elasticsearch/xpack/sql => ql/src/test/java/org/elasticsearch/xpack/ql}/expression/LiteralTests.java (65%) rename x-pack/plugin/{sql/src/test/java/org/elasticsearch/xpack/sql => ql/src/test/java/org/elasticsearch/xpack/ql}/expression/NullabilityTests.java (81%) create mode 100644 x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/TyperResolutionTests.java rename x-pack/plugin/{sql/src/test/java/org/elasticsearch/xpack/sql => ql/src/test/java/org/elasticsearch/xpack/ql}/expression/UnresolvedAttributeTests.java (95%) rename x-pack/plugin/{sql/src/test/java/org/elasticsearch/xpack/sql => ql/src/test/java/org/elasticsearch/xpack/ql}/expression/function/FunctionRegistryTests.java (87%) rename x-pack/plugin/{sql/src/test/java/org/elasticsearch/xpack/sql => ql/src/test/java/org/elasticsearch/xpack/ql}/expression/function/NamedExpressionTests.java (58%) create mode 100644 x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/function/TestFunctionRegistry.java rename x-pack/plugin/{sql/src/test/java/org/elasticsearch/xpack/sql => ql/src/test/java/org/elasticsearch/xpack/ql}/expression/function/UnresolvedFunctionTests.java (93%) rename x-pack/plugin/{sql/src/test/java/org/elasticsearch/xpack/sql => ql/src/test/java/org/elasticsearch/xpack/ql}/expression/function/scalar/FunctionTestUtils.java (71%) rename x-pack/plugin/{sql/src/test/java/org/elasticsearch/xpack/sql => ql/src/test/java/org/elasticsearch/xpack/ql}/expression/gen/pipeline/AttributeInputTests.java (69%) rename x-pack/plugin/{sql/src/test/java/org/elasticsearch/xpack/sql => ql/src/test/java/org/elasticsearch/xpack/ql}/expression/gen/pipeline/BinaryPipesTests.java (85%) rename x-pack/plugin/{sql/src/test/java/org/elasticsearch/xpack/sql => ql/src/test/java/org/elasticsearch/xpack/ql}/expression/gen/pipeline/UnaryPipeTests.java (74%) rename x-pack/plugin/{sql/src/test/java/org/elasticsearch/xpack/sql => ql/src/test/java/org/elasticsearch/xpack/ql}/expression/gen/processor/ChainingProcessorTests.java (58%) rename x-pack/plugin/{sql/src/test/java/org/elasticsearch/xpack/sql => ql/src/test/java/org/elasticsearch/xpack/ql}/expression/gen/processor/ConstantProcessorTests.java (70%) rename x-pack/plugin/{sql/src/test/java/org/elasticsearch/xpack/sql => ql/src/test/java/org/elasticsearch/xpack/ql}/expression/predicate/fulltext/FullTextUtilsTests.java (83%) rename x-pack/plugin/{sql/src/test/java/org/elasticsearch/xpack/sql => ql/src/test/java/org/elasticsearch/xpack/ql}/expression/predicate/logical/BinaryLogicProcessorTests.java (93%) rename x-pack/plugin/{sql/src/test/java/org/elasticsearch/xpack/sql => ql/src/test/java/org/elasticsearch/xpack/ql}/expression/predicate/operator/arithmetic/BinaryArithmeticProcessorTests.java (73%) rename x-pack/plugin/{sql/src/test/java/org/elasticsearch/xpack/sql => ql/src/test/java/org/elasticsearch/xpack/ql}/expression/predicate/operator/comparison/BinaryComparisonProcessorTests.java (89%) rename x-pack/plugin/{sql/src/test/java/org/elasticsearch/xpack/sql => ql/src/test/java/org/elasticsearch/xpack/ql}/tree/AbstractNodeTestCase.java (97%) rename x-pack/plugin/{sql/src/test/java/org/elasticsearch/xpack/sql => ql/src/test/java/org/elasticsearch/xpack/ql}/tree/NodeSubclassTests.java (78%) rename x-pack/plugin/{sql/src/test/java/org/elasticsearch/xpack/sql => ql/src/test/java/org/elasticsearch/xpack/ql}/tree/NodeTests.java (97%) rename x-pack/plugin/{sql/src/test/java/org/elasticsearch/xpack/sql => ql/src/test/java/org/elasticsearch/xpack/ql}/tree/SourceTests.java (97%) create mode 100644 x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/tree/TestCompoundAggregate.java create mode 100644 x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/tree/TestEnclosedAgg.java create mode 100644 x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/type/DataTypeConversionTests.java rename x-pack/plugin/{sql/src/test/java/org/elasticsearch/xpack/sql => ql/src/test/java/org/elasticsearch/xpack/ql}/type/TypesTests.java (76%) rename x-pack/plugin/{sql => ql}/src/test/resources/mapping-basic-incompatible.json (100%) rename x-pack/plugin/{sql => ql}/src/test/resources/mapping-basic-nodocvalues.json (100%) rename x-pack/plugin/{sql => ql}/src/test/resources/mapping-basic.json (100%) rename x-pack/plugin/{sql => ql}/src/test/resources/mapping-date-multi.json (100%) rename x-pack/plugin/{sql => ql}/src/test/resources/mapping-date-no-format.json (100%) rename x-pack/plugin/{sql => ql}/src/test/resources/mapping-date.json (100%) rename x-pack/plugin/{sql => ql}/src/test/resources/mapping-default-string.json (100%) rename x-pack/plugin/{sql => ql}/src/test/resources/mapping-docvalues.json (100%) rename x-pack/plugin/{sql => ql}/src/test/resources/mapping-dotted-field.json (100%) rename x-pack/plugin/{sql => ql}/src/test/resources/mapping-geo.json (100%) rename x-pack/plugin/{sql => ql}/src/test/resources/mapping-ip.json (100%) rename x-pack/plugin/{sql => ql}/src/test/resources/mapping-keyword.json (100%) rename x-pack/plugin/{sql => ql}/src/test/resources/mapping-multi-field-options.json (100%) rename x-pack/plugin/{sql => ql}/src/test/resources/mapping-multi-field-variation.json (100%) rename x-pack/plugin/{sql => ql}/src/test/resources/mapping-multi-field-with-nested.json (100%) rename x-pack/plugin/{sql => ql}/src/test/resources/mapping-multi-field.json (100%) rename x-pack/plugin/{sql => ql}/src/test/resources/mapping-nested.json (100%) rename x-pack/plugin/{sql => ql}/src/test/resources/mapping-numeric.json (100%) rename x-pack/plugin/{sql => ql}/src/test/resources/mapping-object.json (100%) rename x-pack/plugin/{sql => ql}/src/test/resources/mapping-parent-child.json (100%) rename x-pack/plugin/{sql => ql}/src/test/resources/mapping-text.json (100%) rename x-pack/plugin/{sql => ql}/src/test/resources/mapping-unsupported.json (100%) rename x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/{ClientSqlException.java => SqlClientException.java} (57%) rename x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/{ServerSqlException.java => SqlServerException.java} (57%) rename x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/{BucketExtractors.java => SqlBucketExtractors.java} (80%) create mode 100644 x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/SqlHitExtractors.java create mode 100644 x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/SqlTypeResolutions.java delete mode 100644 x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/FunctionRegistry.java delete mode 100644 x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/FunctionType.java create mode 100644 x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/SqlFunctionRegistry.java create mode 100644 x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/SqlFunctionTypeRegistry.java delete mode 100644 x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/ScalarFunction.java create mode 100644 x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/whitelist/InternalScriptUtils.java delete mode 100644 x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/ScriptWeaver.java rename x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/{function/scalar => literal}/geo/GeoShape.java (90%) rename x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/{ => interval}/Interval.java (78%) create mode 100644 x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/interval/IntervalArithmetics.java rename x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/{ => interval}/IntervalDayTime.java (72%) rename x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/{ => interval}/IntervalYearMonth.java (70%) rename x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/{ => interval}/Intervals.java (71%) delete mode 100644 x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/BinaryArithmeticProcessor.java create mode 100644 x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/SqlArithmeticOperation.java create mode 100644 x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/SqlBinaryArithmeticOperation.java create mode 100644 x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/Session.java create mode 100644 x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/SqlExecutable.java delete mode 100644 x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/DataType.java delete mode 100644 x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/DataTypeConversion.java delete mode 100644 x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/DataTypes.java create mode 100644 x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/SqlDataTypeConverter.java create mode 100644 x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/SqlDataTypeRegistry.java create mode 100644 x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/SqlDataTypes.java rename x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/{TestUtils.java => SqlTestUtils.java} (86%) rename x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/{TyperResolutionTests.java => TypeResolutionTests.java} (63%) create mode 100644 x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/MathOperationTests.java rename x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/literal/{ => interval}/IntervalsTests.java (88%) rename x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/{ => parser}/ParameterTests.java (72%) rename x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/{ => parser}/QuotingTests.java (91%) rename x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/{BinaryArithmeticTests.java => SqlBinaryArithmeticTests.java} (86%) create mode 100644 x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/plan/logical/command/ShowFunctionsTests.java create mode 100644 x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/tree/SqlNodeSubclassTests.java rename x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/type/{DataTypeConversionTests.java => SqlDataTypeConverterTests.java} (67%) rename x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/type/{DataTypesTests.java => SqlDataTypesTests.java} (59%) create mode 100644 x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/types/SqlTypesTests.java diff --git a/x-pack/plugin/ql/build.gradle b/x-pack/plugin/ql/build.gradle new file mode 100644 index 0000000000000..c74b8a8bcb4a3 --- /dev/null +++ b/x-pack/plugin/ql/build.gradle @@ -0,0 +1,36 @@ +evaluationDependsOn(xpackModule('core')) + +apply plugin: 'elasticsearch.esplugin' +esplugin { + name 'x-pack-ql' + description 'Elasticsearch infrastructure plugin for EQL and SQL for Elasticsearch' + classname 'org.elasticsearch.xpack.ql.plugin.QlPlugin' + extendedPlugins = ['x-pack-core'] +} + +archivesBaseName = 'x-pack-ql' + +dependencies { + compileOnly project(path: xpackModule('core'), configuration: 'default') + testCompile project(':test:framework') + testCompile project(path: xpackModule('core'), configuration: 'testArtifacts') +} + +configurations { + testArtifacts.extendsFrom testRuntime +} + +task testJar(type: Jar) { + appendix 'test' + from sourceSets.test.output +} + +artifacts { + // normal es plugins do not publish the jar but we need to since users need it for extensions + archives jar + testArtifacts testJar +} + + +// disable integration tests for now +integTest.enabled = false diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/ParsingException.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/ParsingException.java new file mode 100644 index 0000000000000..d2ffd5fe21c00 --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/ParsingException.java @@ -0,0 +1,61 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.ql; + +import org.elasticsearch.rest.RestStatus; +import org.elasticsearch.xpack.ql.tree.Source; + +import static org.elasticsearch.common.logging.LoggerMessageFormat.format; + +public class ParsingException extends QlClientException { + private final int line; + private final int charPositionInLine; + + public ParsingException(String message, Exception cause, int line, int charPositionInLine) { + super(message, cause); + this.line = line; + this.charPositionInLine = charPositionInLine; + } + + public ParsingException(String message, Object... args) { + this(Source.EMPTY, message, args); + } + + public ParsingException(Source source, String message, Object... args) { + super(message, args); + this.line = source.source().getLineNumber(); + this.charPositionInLine = source.source().getColumnNumber(); + } + + public ParsingException(Exception cause, Source source, String message, Object... args) { + super(cause, message, args); + this.line = source.source().getLineNumber(); + this.charPositionInLine = source.source().getColumnNumber(); + } + + public int getLineNumber() { + return line; + } + + public int getColumnNumber() { + return charPositionInLine + 1; + } + + public String getErrorMessage() { + return super.getMessage(); + } + + @Override + public RestStatus status() { + return RestStatus.BAD_REQUEST; + } + + @Override + public String getMessage() { + return format("line {}:{}: {}", getLineNumber(), getColumnNumber(), getErrorMessage()); + } +} diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/QlClientException.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/QlClientException.java new file mode 100644 index 0000000000000..684091229be5a --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/QlClientException.java @@ -0,0 +1,29 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +package org.elasticsearch.xpack.ql; + +public abstract class QlClientException extends QlException { + + protected QlClientException(String message, Object... args) { + super(message, args); + } + + protected QlClientException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + + protected QlClientException(String message, Throwable cause) { + super(message, cause); + } + + protected QlClientException(Throwable cause, String message, Object... args) { + super(cause, message, args); + } + + protected QlClientException(Throwable cause) { + super(cause); + } +} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/SqlException.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/QlException.java similarity index 53% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/SqlException.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/QlException.java index 84b40b221d9ea..2262e6f414a5b 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/SqlException.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/QlException.java @@ -3,28 +3,28 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql; +package org.elasticsearch.xpack.ql; import org.elasticsearch.ElasticsearchException; -public abstract class SqlException extends ElasticsearchException { - public SqlException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { +public abstract class QlException extends ElasticsearchException { + public QlException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } - public SqlException(String message, Throwable cause) { + public QlException(String message, Throwable cause) { super(message, cause); } - public SqlException(String message, Object... args) { + public QlException(String message, Object... args) { super(message, args); } - public SqlException(Throwable cause, String message, Object... args) { + public QlException(Throwable cause, String message, Object... args) { super(message, cause, args); } - public SqlException(Throwable cause) { + public QlException(Throwable cause) { super(cause); } } diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/QlIllegalArgumentException.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/QlIllegalArgumentException.java new file mode 100644 index 0000000000000..2c7013422e8ed --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/QlIllegalArgumentException.java @@ -0,0 +1,32 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +package org.elasticsearch.xpack.ql; + +public class QlIllegalArgumentException extends QlServerException { + public QlIllegalArgumentException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + + public QlIllegalArgumentException(String message, Throwable cause) { + super(message, cause); + } + + public QlIllegalArgumentException(String message, Object... args) { + super(message, args); + } + + public QlIllegalArgumentException(Throwable cause, String message, Object... args) { + super(cause, message, args); + } + + public QlIllegalArgumentException(String message) { + super(message); + } + + public QlIllegalArgumentException(Throwable cause) { + super(cause); + } +} diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/QlServerException.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/QlServerException.java new file mode 100644 index 0000000000000..8ab942dc71e5d --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/QlServerException.java @@ -0,0 +1,29 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +package org.elasticsearch.xpack.ql; + +public abstract class QlServerException extends QlException { + + protected QlServerException(String message, Object... args) { + super(message, args); + } + + protected QlServerException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + + protected QlServerException(String message, Throwable cause) { + super(message, cause); + } + + protected QlServerException(Throwable cause, String message, Object... args) { + super(cause, message, args); + } + + protected QlServerException(Throwable cause) { + super(cause); + } +} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/capabilities/Resolvable.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/capabilities/Resolvable.java similarity index 85% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/capabilities/Resolvable.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/capabilities/Resolvable.java index a627f06165573..ba0edfb4ad195 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/capabilities/Resolvable.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/capabilities/Resolvable.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.capabilities; +package org.elasticsearch.xpack.ql.capabilities; public interface Resolvable { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/capabilities/Resolvables.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/capabilities/Resolvables.java similarity index 91% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/capabilities/Resolvables.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/capabilities/Resolvables.java index 222ba7a87c068..6e3ebc1a2081f 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/capabilities/Resolvables.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/capabilities/Resolvables.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.capabilities; +package org.elasticsearch.xpack.ql.capabilities; public abstract class Resolvables { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/capabilities/Unresolvable.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/capabilities/Unresolvable.java similarity index 89% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/capabilities/Unresolvable.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/capabilities/Unresolvable.java index 9cd2e6416974c..e9cda9c7cfa1e 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/capabilities/Unresolvable.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/capabilities/Unresolvable.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.capabilities; +package org.elasticsearch.xpack.ql.capabilities; public interface Unresolvable extends Resolvable { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/capabilities/UnresolvedException.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/capabilities/UnresolvedException.java similarity index 75% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/capabilities/UnresolvedException.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/capabilities/UnresolvedException.java index 0db87c6b944e4..4aad197aade3f 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/capabilities/UnresolvedException.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/capabilities/UnresolvedException.java @@ -3,15 +3,15 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.capabilities; +package org.elasticsearch.xpack.ql.capabilities; -import org.elasticsearch.xpack.sql.ServerSqlException; +import org.elasticsearch.xpack.ql.QlServerException; /** * Thrown when we accidentally attempt to resolve something on on an unresolved entity. Throwing this * is always a bug. */ -public class UnresolvedException extends ServerSqlException { +public class UnresolvedException extends QlServerException { public UnresolvedException(String action, Object target) { super("Invalid call to {} on an unresolved object {}", action, target); } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/AggRef.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/AggRef.java similarity index 82% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/AggRef.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/AggRef.java index 5c9ec6dc623e5..565d465fa25eb 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/AggRef.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/AggRef.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.execution.search; +package org.elasticsearch.xpack.ql.execution.search; /** * Reference to a ES aggregation (which can be either a GROUP BY or Metric agg). @@ -11,7 +11,7 @@ public abstract class AggRef implements FieldExtraction { @Override - public void collectFields(SqlSourceBuilder sourceBuilder) { + public void collectFields(QlSourceBuilder sourceBuilder) { // Aggregations do not need any special fields } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/FieldExtraction.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/FieldExtraction.java similarity index 88% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/FieldExtraction.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/FieldExtraction.java index 71e8db18d5094..a1756c7439a09 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/FieldExtraction.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/FieldExtraction.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.execution.search; +package org.elasticsearch.xpack.ql.execution.search; import org.elasticsearch.search.builder.SearchSourceBuilder; @@ -17,7 +17,7 @@ public interface FieldExtraction { * in order to fetch the field. This can include tracking the score, * {@code _source} fields, doc values fields, and script fields. */ - void collectFields(SqlSourceBuilder sourceBuilder); + void collectFields(QlSourceBuilder sourceBuilder); /** * Is this aggregation supported in an "aggregation only" query diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/SqlSourceBuilder.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/QlSourceBuilder.java similarity index 84% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/SqlSourceBuilder.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/QlSourceBuilder.java index 1872748c328fa..06bc216b812a7 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/SqlSourceBuilder.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/QlSourceBuilder.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.execution.search; +package org.elasticsearch.xpack.ql.execution.search; import org.elasticsearch.common.Strings; import org.elasticsearch.script.Script; @@ -20,15 +20,15 @@ * {@link FieldExtraction} that can "build" whatever needs to be extracted from * the resulting ES document as a field. */ -public class SqlSourceBuilder { +public class QlSourceBuilder { // The LinkedHashMaps preserve the order of the fields in the response - final Set sourceFields = new LinkedHashSet<>(); - final Set docFields = new LinkedHashSet<>(); - final Map scriptFields = new LinkedHashMap<>(); + private final Set sourceFields = new LinkedHashSet<>(); + private final Set docFields = new LinkedHashSet<>(); + private final Map scriptFields = new LinkedHashMap<>(); boolean trackScores = false; - public SqlSourceBuilder() { + public QlSourceBuilder() { } /** @@ -71,4 +71,8 @@ public void build(SearchSourceBuilder sourceBuilder) { docFields.forEach(field -> sourceBuilder.docValueField(field.field, field.format)); scriptFields.forEach(sourceBuilder::scriptField); } + + public boolean noSource() { + return sourceFields.isEmpty(); + } } diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/extractor/AbstractFieldHitExtractor.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/extractor/AbstractFieldHitExtractor.java new file mode 100644 index 0000000000000..cbb50605f72e2 --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/extractor/AbstractFieldHitExtractor.java @@ -0,0 +1,334 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +package org.elasticsearch.xpack.ql.execution.search.extractor; + +import org.elasticsearch.Version; +import org.elasticsearch.common.Strings; +import org.elasticsearch.common.collect.Tuple; +import org.elasticsearch.common.document.DocumentField; +import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.common.io.stream.StreamOutput; +import org.elasticsearch.index.mapper.IgnoredFieldMapper; +import org.elasticsearch.index.mapper.NumberFieldMapper.NumberType; +import org.elasticsearch.search.SearchHit; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; + +import java.io.IOException; +import java.time.ZoneId; +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.StringJoiner; + +import static org.elasticsearch.xpack.ql.type.DataTypes.DATETIME; +import static org.elasticsearch.xpack.ql.type.DataTypes.KEYWORD; +import static org.elasticsearch.xpack.ql.type.DataTypes.SCALED_FLOAT; +/** + * Extractor for ES fields. Works for both 'normal' fields but also nested ones (which require hitName to be set). + * The latter is used as metadata in assembling the results in the tabular response. + */ +public abstract class AbstractFieldHitExtractor implements HitExtractor { + + private static final Version SWITCHED_FROM_DOCVALUES_TO_SOURCE_EXTRACTION = Version.V_7_4_0; + + /** + * Source extraction requires only the (relative) field name, without its parent path. + */ + private static String[] sourcePath(String name, boolean useDocValue, String hitName) { + return useDocValue ? Strings.EMPTY_ARRAY : Strings + .tokenizeToStringArray(hitName == null ? name : name.substring(hitName.length() + 1), "."); + } + + private final String fieldName, hitName; + private final String fullFieldName; // used to look at the _ignored section of the query response for the actual full field name + private final DataType dataType; + private final ZoneId zoneId; + private final boolean useDocValue; + private final boolean arrayLeniency; + private final String[] path; + + protected AbstractFieldHitExtractor(String name, DataType dataType, ZoneId zoneId, boolean useDocValue) { + this(name, null, dataType, zoneId, useDocValue, null, false); + } + + protected AbstractFieldHitExtractor(String name, DataType dataType, ZoneId zoneId, boolean useDocValue, boolean arrayLeniency) { + this(name, null, dataType, zoneId, useDocValue, null, arrayLeniency); + } + + protected AbstractFieldHitExtractor(String name, String fullFieldName, DataType dataType, ZoneId zoneId, boolean useDocValue, + String hitName, boolean arrayLeniency) { + this.fieldName = name; + this.fullFieldName = fullFieldName; + this.dataType = dataType; + this.zoneId = zoneId; + this.useDocValue = useDocValue; + this.arrayLeniency = arrayLeniency; + this.hitName = hitName; + + if (hitName != null) { + if (!name.contains(hitName)) { + throw new QlIllegalArgumentException("Hitname [{}] specified but not part of the name [{}]", hitName, name); + } + } + + this.path = sourcePath(fieldName, useDocValue, hitName); + } + + protected AbstractFieldHitExtractor(StreamInput in) throws IOException { + fieldName = in.readString(); + if (in.getVersion().onOrAfter(SWITCHED_FROM_DOCVALUES_TO_SOURCE_EXTRACTION)) { + fullFieldName = in.readOptionalString(); + } else { + fullFieldName = null; + } + String typeName = in.readOptionalString(); + dataType = typeName != null ? loadTypeFromName(typeName) : null; + useDocValue = in.readBoolean(); + hitName = in.readOptionalString(); + arrayLeniency = in.readBoolean(); + path = sourcePath(fieldName, useDocValue, hitName); + zoneId = readZoneId(in); + } + + protected DataType loadTypeFromName(String typeName) { + return DataTypes.fromTypeName(typeName); + } + + protected abstract ZoneId readZoneId(StreamInput in) throws IOException; + + @Override + public void writeTo(StreamOutput out) throws IOException { + out.writeString(fieldName); + if (out.getVersion().onOrAfter(SWITCHED_FROM_DOCVALUES_TO_SOURCE_EXTRACTION)) { + out.writeOptionalString(fullFieldName); + } + out.writeOptionalString(dataType == null ? null : dataType.typeName()); + out.writeBoolean(useDocValue); + out.writeOptionalString(hitName); + out.writeBoolean(arrayLeniency); + } + + @Override + public Object extract(SearchHit hit) { + Object value = null; + if (useDocValue) { + DocumentField field = hit.field(fieldName); + if (field != null) { + value = unwrapMultiValue(field.getValues()); + } + } else { + // if the field was ignored because it was malformed and ignore_malformed was turned on + if (fullFieldName != null + && hit.getFields().containsKey(IgnoredFieldMapper.NAME) + && isFromDocValuesOnly(dataType) == false + && dataType.isNumeric()) { + /* + * ignore_malformed makes sense for extraction from _source for numeric fields only. + * And we check here that the data type is actually a numeric one to rule out + * any non-numeric sub-fields (for which the "parent" field should actually be extracted from _source). + * For example, in the case of a malformed number, a "byte" field with "ignore_malformed: true" + * with a "text" sub-field should return "null" for the "byte" parent field and the actual malformed + * data for the "text" sub-field. Also, the _ignored section of the response contains the full field + * name, thus the need to do the comparison with that and not only the field name. + */ + if (hit.getFields().get(IgnoredFieldMapper.NAME).getValues().contains(fullFieldName)) { + return null; + } + } + Map source = hit.getSourceAsMap(); + if (source != null) { + value = extractFromSource(source); + } + } + return value; + } + + protected Object unwrapMultiValue(Object values) { + if (values == null) { + return null; + } + if (values instanceof List) { + List list = (List) values; + if (list.isEmpty()) { + return null; + } else { + if (isPrimitive(list) == false) { + if (list.size() == 1 || arrayLeniency) { + return unwrapMultiValue(list.get(0)); + } else { + throw new QlIllegalArgumentException("Arrays (returned by [{}]) are not supported", fieldName); + } + } + } + } + + Object unwrapped = unwrapCustomValue(values); + if (unwrapped != null) { + return unwrapped; + } + + // The Jackson json parser can generate for numerics - Integers, Longs, BigIntegers (if Long is not enough) + // and BigDecimal (if Double is not enough) + if (values instanceof Number || values instanceof String || values instanceof Boolean) { + if (dataType == null) { + return values; + } + if (dataType.isNumeric() && isFromDocValuesOnly(dataType) == false) { + if (dataType == DataTypes.DOUBLE || dataType == DataTypes.FLOAT || dataType == DataTypes.HALF_FLOAT) { + Number result = null; + try { + result = numberType(dataType).parse(values, true); + } catch(IllegalArgumentException iae) { + return null; + } + // docvalue_fields is always returning a Double value even if the underlying floating point data type is not Double + // even if we don't extract from docvalue_fields anymore, the behavior should be consistent + return result.doubleValue(); + } else { + Number result = null; + try { + result = numberType(dataType).parse(values, true); + } catch(IllegalArgumentException iae) { + return null; + } + return result; + } + } else if (DataTypes.isString(dataType)) { + return values.toString(); + } else { + return values; + } + } + throw new QlIllegalArgumentException("Type {} (returned by [{}]) is not supported", values.getClass().getSimpleName(), fieldName); + } + + protected boolean isFromDocValuesOnly(DataType dataType) { + return dataType == KEYWORD // because of ignore_above. + || dataType == DATETIME + || dataType == SCALED_FLOAT; // because of scaling_factor + } + + private static NumberType numberType(DataType dataType) { + return NumberType.valueOf(dataType.esType().toUpperCase(Locale.ROOT)); + } + + protected abstract Object unwrapCustomValue(Object values); + + protected abstract boolean isPrimitive(List list); + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public Object extractFromSource(Map map) { + Object value = null; + + // Used to avoid recursive method calls + // Holds the sub-maps in the document hierarchy that are pending to be inspected along with the current index of the `path`. + Deque>> queue = new ArrayDeque<>(); + queue.add(new Tuple<>(-1, map)); + + while (!queue.isEmpty()) { + Tuple> tuple = queue.removeLast(); + int idx = tuple.v1(); + Map subMap = tuple.v2(); + + // Find all possible entries by examining all combinations under the current level ("idx") of the "path" + // e.g.: If the path == "a.b.c.d" and the idx == 0, we need to check the current subMap against the keys: + // "b", "b.c" and "b.c.d" + StringJoiner sj = new StringJoiner("."); + for (int i = idx + 1; i < path.length; i++) { + sj.add(path[i]); + Object node = subMap.get(sj.toString()); + + if (node instanceof List) { + List listOfValues = (List) node; + // we can only do this optimization until the last element of our pass since geo points are using arrays + // and we don't want to blindly ignore the second element of array if arrayLeniency is enabled + if ((i < path.length - 1) && (listOfValues.size() == 1 || arrayLeniency)) { + // this is a List with a size of 1 e.g.: {"a" : [{"b" : "value"}]} meaning the JSON is a list with one element + // or a list of values with one element e.g.: {"a": {"b" : ["value"]}} + // in case of being lenient about arrays, just extract the first value in the array + node = listOfValues.get(0); + } else { + // a List of elements with more than one value. Break early and let unwrapMultiValue deal with the list + return unwrapMultiValue(node); + } + } + + if (node instanceof Map) { + if (i < path.length - 1) { + // Add the sub-map to the queue along with the current path index + queue.add(new Tuple<>(i, (Map) node)); + } else { + // We exhausted the path and got a map + // If it is an object - it will be handled in the value extractor + value = node; + } + } else if (node != null) { + if (i < path.length - 1) { + // If we reach a concrete value without exhausting the full path, something is wrong with the mapping + // e.g.: map is {"a" : { "b" : "value }} and we are looking for a path: "a.b.c.d" + throw new QlIllegalArgumentException("Cannot extract value [{}] from source", fieldName); + } + if (value != null) { + // A value has already been found so this means that there are more than one + // values in the document for the same path but different hierarchy. + // e.g.: {"a" : {"b" : {"c" : "value"}}}, {"a.b" : {"c" : "value"}}, ... + throw new QlIllegalArgumentException("Multiple values (returned by [{}]) are not supported", fieldName); + } + value = node; + } + } + } + return unwrapMultiValue(value); + } + + @Override + public String hitName() { + return hitName; + } + + public String fieldName() { + return fieldName; + } + + public String fullFieldName() { + return fullFieldName; + } + + public ZoneId zoneId() { + return zoneId; + } + + public DataType dataType() { + return dataType; + } + + @Override + public String toString() { + return fieldName + "@" + hitName + "@" + zoneId; + } + + @Override + public boolean equals(Object obj) { + if (obj == null || obj.getClass() != getClass()) { + return false; + } + AbstractFieldHitExtractor other = (AbstractFieldHitExtractor) obj; + return fieldName.equals(other.fieldName) + && hitName.equals(other.hitName) + && useDocValue == other.useDocValue + && arrayLeniency == other.arrayLeniency; + } + + @Override + public int hashCode() { + return Objects.hash(fieldName, useDocValue, hitName, arrayLeniency); + } +} \ No newline at end of file diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/BucketExtractor.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/extractor/BucketExtractor.java similarity index 89% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/BucketExtractor.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/extractor/BucketExtractor.java index 230ad88eea59c..05c7446d9e7d4 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/BucketExtractor.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/extractor/BucketExtractor.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.execution.search.extractor; +package org.elasticsearch.xpack.ql.execution.search.extractor; import org.elasticsearch.common.io.stream.NamedWriteable; import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation.Bucket; diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/extractor/BucketExtractors.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/extractor/BucketExtractors.java new file mode 100644 index 0000000000000..18f0725fdaa94 --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/extractor/BucketExtractors.java @@ -0,0 +1,28 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +package org.elasticsearch.xpack.ql.execution.search.extractor; + +import org.elasticsearch.common.io.stream.NamedWriteableRegistry; +import org.elasticsearch.common.io.stream.NamedWriteableRegistry.Entry; + +import java.util.ArrayList; +import java.util.List; + +public final class BucketExtractors { + + private BucketExtractors() {} + + /** + * All of the named writeables needed to deserialize the instances of + * {@linkplain BucketExtractor}s. + */ + public static List getNamedWriteables() { + List entries = new ArrayList<>(); + entries.add(new Entry(BucketExtractor.class, ComputingExtractor.NAME, ComputingExtractor::new)); + entries.add(new Entry(BucketExtractor.class, ConstantExtractor.NAME, ConstantExtractor::new)); + return entries; + } +} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/ComputingExtractor.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/extractor/ComputingExtractor.java similarity index 90% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/ComputingExtractor.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/extractor/ComputingExtractor.java index 92f81b6ac4308..7ad48a30a047d 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/ComputingExtractor.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/extractor/ComputingExtractor.java @@ -3,14 +3,14 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.execution.search.extractor; +package org.elasticsearch.xpack.ql.execution.search.extractor; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation.Bucket; -import org.elasticsearch.xpack.sql.expression.gen.processor.HitExtractorProcessor; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.gen.processor.HitExtractorProcessor; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; import java.io.IOException; import java.util.Objects; @@ -44,7 +44,8 @@ public ComputingExtractor(Processor processor, String hitName) { this.hitName = hitName; } - ComputingExtractor(StreamInput in) throws IOException { + // Visibility required for tests + public ComputingExtractor(StreamInput in) throws IOException { processor = in.readNamedWriteable(Processor.class); hitName = in.readOptionalString(); } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/ConstantExtractor.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/extractor/ConstantExtractor.java similarity index 96% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/ConstantExtractor.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/extractor/ConstantExtractor.java index e9bd3b2a6768e..54b083eb583f7 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/ConstantExtractor.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/extractor/ConstantExtractor.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.execution.search.extractor; +package org.elasticsearch.xpack.ql.execution.search.extractor; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/HitExtractor.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/extractor/HitExtractor.java similarity index 91% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/HitExtractor.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/extractor/HitExtractor.java index c0de33c812819..db68d130e7dbb 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/HitExtractor.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/extractor/HitExtractor.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.execution.search.extractor; +package org.elasticsearch.xpack.ql.execution.search.extractor; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.io.stream.NamedWriteable; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/HitExtractors.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/extractor/HitExtractors.java similarity index 78% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/HitExtractors.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/extractor/HitExtractors.java index 1036829902e50..b43320160039c 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/HitExtractors.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/extractor/HitExtractors.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.execution.search.extractor; +package org.elasticsearch.xpack.ql.execution.search.extractor; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.NamedWriteableRegistry.Entry; @@ -22,9 +22,7 @@ private HitExtractors() {} public static List getNamedWriteables() { List entries = new ArrayList<>(); entries.add(new Entry(HitExtractor.class, ConstantExtractor.NAME, ConstantExtractor::new)); - entries.add(new Entry(HitExtractor.class, FieldHitExtractor.NAME, FieldHitExtractor::new)); entries.add(new Entry(HitExtractor.class, ComputingExtractor.NAME, ComputingExtractor::new)); - entries.add(new Entry(HitExtractor.class, ScoreExtractor.NAME, in -> ScoreExtractor.INSTANCE)); return entries; } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/Alias.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/Alias.java similarity index 93% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/Alias.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/Alias.java index ef8611b49690f..de31a7d82a2d7 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/Alias.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/Alias.java @@ -3,11 +3,11 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression; +package org.elasticsearch.xpack.ql.expression; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; import java.util.List; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/Attribute.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/Attribute.java similarity index 97% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/Attribute.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/Attribute.java index bda8287115e0f..2b5d1e4df1842 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/Attribute.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/Attribute.java @@ -3,10 +3,10 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression; +package org.elasticsearch.xpack.ql.expression; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; import java.util.List; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/AttributeMap.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/AttributeMap.java similarity index 99% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/AttributeMap.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/AttributeMap.java index c4c26729c6b19..bcbd2ae5595b9 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/AttributeMap.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/AttributeMap.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression; +package org.elasticsearch.xpack.ql.expression; import java.util.AbstractSet; import java.util.Collection; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/AttributeSet.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/AttributeSet.java similarity index 98% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/AttributeSet.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/AttributeSet.java index f8b89ac4b08fc..585d3d5da10c9 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/AttributeSet.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/AttributeSet.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression; +package org.elasticsearch.xpack.ql.expression; import java.util.Collection; import java.util.Iterator; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/Expression.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/Expression.java similarity index 84% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/Expression.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/Expression.java index 166ccd72f711f..c26661258410c 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/Expression.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/Expression.java @@ -3,15 +3,15 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression; +package org.elasticsearch.xpack.ql.expression; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.capabilities.Resolvable; -import org.elasticsearch.xpack.sql.capabilities.Resolvables; -import org.elasticsearch.xpack.sql.tree.Node; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.util.StringUtils; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.capabilities.Resolvable; +import org.elasticsearch.xpack.ql.capabilities.Resolvables; +import org.elasticsearch.xpack.ql.tree.Node; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.util.StringUtils; import java.util.List; @@ -46,12 +46,17 @@ public boolean unresolved() { } public boolean resolved() { - return !failed; + return failed == false; } public String message() { return message; } + + @Override + public String toString() { + return resolved() ? "" : message; + } } private TypeResolution lazyTypeResolution = null; @@ -69,7 +74,7 @@ public boolean foldable() { } public Object fold() { - throw new SqlIllegalArgumentException("Should not fold expression"); + throw new QlIllegalArgumentException("Should not fold expression"); } public abstract Nullability nullable(); diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/ExpressionSet.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/ExpressionSet.java similarity index 98% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/ExpressionSet.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/ExpressionSet.java index 3adea47c6b853..925e595cbed7c 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/ExpressionSet.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/ExpressionSet.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression; +package org.elasticsearch.xpack.ql.expression; import java.util.Collection; import java.util.Iterator; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/Expressions.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/Expressions.java similarity index 89% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/Expressions.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/Expressions.java index 92703f4768f70..dfb235ba7746e 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/Expressions.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/Expressions.java @@ -3,15 +3,14 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression; +package org.elasticsearch.xpack.ql.expression; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.function.Function; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.AttributeInput; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.ConstantInput; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.DataTypes; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.expression.function.Function; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.AttributeInput; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.ConstantInput; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.type.DataTypes; import java.util.ArrayList; import java.util.Collection; @@ -112,7 +111,7 @@ public static String name(Expression e) { } public static boolean isNull(Expression e) { - return e.dataType() == DataType.NULL || (e.foldable() && e.fold() == null); + return e.dataType() == DataTypes.NULL || (e.foldable() && e.fold() == null); } public static List names(Collection e) { @@ -165,7 +164,7 @@ public static List onlyPrimitiveFieldAttributes(Collection Set seenMultiFields = new LinkedHashSet<>(); for (Attribute a : attributes) { - if (!DataTypes.isUnsupported(a.dataType()) && a.dataType().isPrimitive()) { + if (DataTypes.isUnsupported(a.dataType()) == false && DataTypes.isPrimitive(a.dataType())) { if (a instanceof FieldAttribute) { FieldAttribute fa = (FieldAttribute) a; // skip nested fields and seen multi-fields @@ -192,7 +191,7 @@ public static Pipe pipe(Expression e) { if (e instanceof Function) { return ((Function) e).asPipe(); } - throw new SqlIllegalArgumentException("Cannot create pipe for {}", e); + throw new QlIllegalArgumentException("Cannot create pipe for {}", e); } public static List pipe(List expressions) { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/FieldAttribute.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/FieldAttribute.java similarity index 89% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/FieldAttribute.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/FieldAttribute.java index f802c9a940dd1..6511e244f8881 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/FieldAttribute.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/FieldAttribute.java @@ -3,14 +3,15 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression; +package org.elasticsearch.xpack.ql.expression; import org.elasticsearch.common.Strings; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.EsField; -import org.elasticsearch.xpack.sql.util.StringUtils; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; +import org.elasticsearch.xpack.ql.type.EsField; +import org.elasticsearch.xpack.ql.util.StringUtils; import java.util.Objects; @@ -53,7 +54,7 @@ public FieldAttribute(Source source, FieldAttribute parent, String name, DataTyp FieldAttribute nestedPar = null; if (parent != null) { nestedPar = parent.nestedParent; - if (parent.dataType() == DataType.NESTED) { + if (parent.dataType() == DataTypes.NESTED) { nestedPar = parent; } } @@ -103,7 +104,7 @@ private FieldAttribute innerField(EsField type) { } @Override - protected Attribute clone(Source source, String name, DataType type, String qualifier, Nullability nullability, NameId id, + protected Attribute clone(Source source, String name, DataType type, String qualifier, Nullability nullability, NameId id, boolean synthetic) { FieldAttribute qualifiedParent = parent != null ? (FieldAttribute) parent.withQualifier(qualifier) : null; return new FieldAttribute(source, qualifiedParent, name, field, qualifier, nullability, id, synthetic); diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/LeafExpression.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/LeafExpression.java similarity index 88% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/LeafExpression.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/LeafExpression.java index 16646452a31ad..15f30599d56ba 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/LeafExpression.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/LeafExpression.java @@ -3,9 +3,9 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression; +package org.elasticsearch.xpack.ql.expression; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.List; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/Literal.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/Literal.java similarity index 67% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/Literal.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/Literal.java index 315b1bb308eb7..82788601e2e61 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/Literal.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/Literal.java @@ -3,14 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression; +package org.elasticsearch.xpack.ql.expression; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.DataTypeConversion; -import org.elasticsearch.xpack.sql.type.DataTypes; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import java.util.Objects; @@ -19,9 +18,9 @@ */ public class Literal extends LeafExpression { - public static final Literal TRUE = Literal.of(Source.EMPTY, Boolean.TRUE); - public static final Literal FALSE = Literal.of(Source.EMPTY, Boolean.FALSE); - public static final Literal NULL = Literal.of(Source.EMPTY, null); + public static final Literal TRUE = new Literal(Source.EMPTY, Boolean.TRUE, DataTypes.BOOLEAN); + public static final Literal FALSE = new Literal(Source.EMPTY, Boolean.FALSE, DataTypes.BOOLEAN); + public static final Literal NULL = new Literal(Source.EMPTY, null, DataTypes.NULL); private final Object value; private final DataType dataType; @@ -29,7 +28,7 @@ public class Literal extends LeafExpression { public Literal(Source source, Object value, DataType dataType) { super(source); this.dataType = dataType; - this.value = DataTypeConversion.convert(value, dataType); + this.value = value; } @Override @@ -94,23 +93,13 @@ public String nodeString() { return toString() + "[" + dataType + "]"; } - /** - * Utility method for creating 'in-line' Literals (out of values instead of expressions). - */ - public static Literal of(Source source, Object value) { - if (value instanceof Literal) { - return (Literal) value; - } - return new Literal(source, value, DataTypes.fromJava(value)); - } - /** * Utility method for creating a literal out of a foldable expression. * Throws an exception if the expression is not foldable. */ public static Literal of(Expression foldable) { if (!foldable.foldable()) { - throw new SqlIllegalArgumentException("Foldable expression required for Literal creation; received unfoldable " + foldable); + throw new QlIllegalArgumentException("Foldable expression required for Literal creation; received unfoldable " + foldable); } if (foldable instanceof Literal) { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/NameId.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/NameId.java similarity index 96% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/NameId.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/NameId.java index bc74a506d77af..59a775742b798 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/NameId.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/NameId.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression; +package org.elasticsearch.xpack.ql.expression; import java.util.Objects; import java.util.concurrent.atomic.AtomicLong; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/NamedExpression.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/NamedExpression.java similarity index 95% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/NamedExpression.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/NamedExpression.java index 633e230393049..96680c39c7a84 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/NamedExpression.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/NamedExpression.java @@ -3,9 +3,9 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression; +package org.elasticsearch.xpack.ql.expression; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.List; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/Nullability.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/Nullability.java similarity index 96% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/Nullability.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/Nullability.java index ac46bdf2aa92b..6a6fd9eae2718 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/Nullability.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/Nullability.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression; +package org.elasticsearch.xpack.ql.expression; public enum Nullability { TRUE, // Whether the expression can become null diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/Order.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/Order.java similarity index 90% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/Order.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/Order.java index 3642ac94d8e79..19b198865d9b2 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/Order.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/Order.java @@ -3,17 +3,17 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression; +package org.elasticsearch.xpack.ql.expression; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; import java.util.List; import java.util.Objects; import static java.util.Collections.singletonList; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isExact; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isExact; public class Order extends Expression { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/ReferenceAttribute.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/ReferenceAttribute.java similarity index 87% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/ReferenceAttribute.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/ReferenceAttribute.java index 03330bc1148f5..6387c79194518 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/ReferenceAttribute.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/ReferenceAttribute.java @@ -3,11 +3,11 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression; +package org.elasticsearch.xpack.ql.expression; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; /** * Attribute based on a reference to an expression. diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/TypeResolutions.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/TypeResolutions.java similarity index 71% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/TypeResolutions.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/TypeResolutions.java index 30041ea12224b..01307d7ef84fc 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/TypeResolutions.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/TypeResolutions.java @@ -3,20 +3,22 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression; +package org.elasticsearch.xpack.ql.expression; -import org.elasticsearch.xpack.sql.expression.Expression.TypeResolution; -import org.elasticsearch.xpack.sql.expression.Expressions.ParamOrdinal; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.EsField; +import org.elasticsearch.xpack.ql.expression.Expression.TypeResolution; +import org.elasticsearch.xpack.ql.expression.Expressions.ParamOrdinal; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; +import org.elasticsearch.xpack.ql.type.EsField; import java.util.Locale; import java.util.StringJoiner; import java.util.function.Predicate; import static org.elasticsearch.common.logging.LoggerMessageFormat.format; -import static org.elasticsearch.xpack.sql.expression.Expressions.name; -import static org.elasticsearch.xpack.sql.type.DataType.BOOLEAN; +import static org.elasticsearch.xpack.ql.expression.Expressions.name; +import static org.elasticsearch.xpack.ql.type.DataTypes.BOOLEAN; +import static org.elasticsearch.xpack.ql.type.DataTypes.NULL; public final class TypeResolutions { @@ -35,36 +37,14 @@ public static TypeResolution isNumeric(Expression e, String operationName, Param } public static TypeResolution isString(Expression e, String operationName, ParamOrdinal paramOrd) { - return isType(e, DataType::isString, operationName, paramOrd, "string"); - } - - public static TypeResolution isDate(Expression e, String operationName, ParamOrdinal paramOrd) { - return isType(e, DataType::isDateBased, operationName, paramOrd, "date", "datetime"); - } - - public static TypeResolution isDateOrTime(Expression e, String operationName, ParamOrdinal paramOrd) { - return isType(e, DataType::isDateOrTimeBased, operationName, paramOrd, "date", "time", "datetime"); - } - - public static TypeResolution isNumericOrDate(Expression e, String operationName, ParamOrdinal paramOrd) { - return isType(e, dt -> dt.isNumeric() || dt.isDateBased(), operationName, paramOrd, - "date", "datetime", "numeric"); - } - - public static TypeResolution isNumericOrDateOrTime(Expression e, String operationName, ParamOrdinal paramOrd) { - return isType(e, dt -> dt.isNumeric() || dt.isDateOrTimeBased(), operationName, paramOrd, - "date", "time", "datetime", "numeric"); - } - - public static TypeResolution isGeo(Expression e, String operationName, ParamOrdinal paramOrd) { - return isType(e, DataType::isGeo, operationName, paramOrd, "geo_point", "geo_shape"); + return isType(e, DataTypes::isString, operationName, paramOrd, "string"); } public static TypeResolution isExact(Expression e, String message) { if (e instanceof FieldAttribute) { EsField.Exact exact = ((FieldAttribute) e).getExactInfo(); if (exact.hasExact() == false) { - return new TypeResolution(format(null, message, e.dataType().typeName, exact.errorMsg())); + return new TypeResolution(format(null, message, e.dataType().typeName(), exact.errorMsg())); } } return TypeResolution.TYPE_RESOLVED; @@ -78,7 +58,7 @@ public static TypeResolution isExact(Expression e, String operationName, ParamOr operationName, paramOrd == null || paramOrd == ParamOrdinal.DEFAULT ? "" : paramOrd.name().toLowerCase(Locale.ROOT) + " argument ", - e.dataType().typeName, exact.errorMsg())); + e.dataType().typeName(), exact.errorMsg())); } } return TypeResolution.TYPE_RESOLVED; @@ -118,14 +98,14 @@ public static TypeResolution isType(Expression e, String operationName, ParamOrdinal paramOrd, String... acceptedTypes) { - return predicate.test(e.dataType()) || e.dataType().isNull() ? + return predicate.test(e.dataType()) || e.dataType() == NULL ? TypeResolution.TYPE_RESOLVED : new TypeResolution(format(null, "{}argument of [{}] must be [{}], found value [{}] type [{}]", paramOrd == null || paramOrd == ParamOrdinal.DEFAULT ? "" : paramOrd.name().toLowerCase(Locale.ROOT) + " ", operationName, acceptedTypesForErrorMsg(acceptedTypes), name(e), - e.dataType().typeName)); + e.dataType().typeName())); } private static String acceptedTypesForErrorMsg(String... acceptedTypes) { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/TypedAttribute.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/TypedAttribute.java similarity index 87% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/TypedAttribute.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/TypedAttribute.java index 98f91d4dca158..613e030aed8f7 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/TypedAttribute.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/TypedAttribute.java @@ -3,10 +3,10 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression; +package org.elasticsearch.xpack.ql.expression; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/UnaryExpression.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/UnaryExpression.java similarity index 92% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/UnaryExpression.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/UnaryExpression.java index 69cb510704288..48c7b7bd11388 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/UnaryExpression.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/UnaryExpression.java @@ -3,10 +3,10 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression; +package org.elasticsearch.xpack.ql.expression; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; import java.util.List; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/UnresolvedAlias.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/UnresolvedAlias.java similarity index 90% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/UnresolvedAlias.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/UnresolvedAlias.java index 67bbee18b392e..b86d0d017176d 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/UnresolvedAlias.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/UnresolvedAlias.java @@ -3,11 +3,11 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression; +package org.elasticsearch.xpack.ql.expression; -import org.elasticsearch.xpack.sql.capabilities.UnresolvedException; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.capabilities.UnresolvedException; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.List; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/UnresolvedAttribute.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/UnresolvedAttribute.java similarity index 90% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/UnresolvedAttribute.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/UnresolvedAttribute.java index 34b8eca1c3551..3fb6be16ba82a 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/UnresolvedAttribute.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/UnresolvedAttribute.java @@ -3,14 +3,14 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression; - -import org.elasticsearch.xpack.sql.capabilities.Unresolvable; -import org.elasticsearch.xpack.sql.capabilities.UnresolvedException; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.util.CollectionUtils; +package org.elasticsearch.xpack.ql.expression; + +import org.elasticsearch.xpack.ql.capabilities.Unresolvable; +import org.elasticsearch.xpack.ql.capabilities.UnresolvedException; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.util.CollectionUtils; import java.util.List; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/UnresolvedNamedExpression.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/UnresolvedNamedExpression.java similarity index 78% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/UnresolvedNamedExpression.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/UnresolvedNamedExpression.java index 5e27180541dfa..b0d36a8d1cc48 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/UnresolvedNamedExpression.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/UnresolvedNamedExpression.java @@ -3,12 +3,12 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression; +package org.elasticsearch.xpack.ql.expression; -import org.elasticsearch.xpack.sql.capabilities.Unresolvable; -import org.elasticsearch.xpack.sql.capabilities.UnresolvedException; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.capabilities.Unresolvable; +import org.elasticsearch.xpack.ql.capabilities.UnresolvedException; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; import java.util.List; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/UnresolvedStar.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/UnresolvedStar.java similarity index 91% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/UnresolvedStar.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/UnresolvedStar.java index 0f38a12d7963a..c2d25dc31fcb8 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/UnresolvedStar.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/UnresolvedStar.java @@ -3,11 +3,11 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression; +package org.elasticsearch.xpack.ql.expression; -import org.elasticsearch.xpack.sql.capabilities.UnresolvedException; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.capabilities.UnresolvedException; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.List; import java.util.Objects; diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/DefaultFunctionTypeRegistry.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/DefaultFunctionTypeRegistry.java new file mode 100644 index 0000000000000..7f1e4789f096c --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/DefaultFunctionTypeRegistry.java @@ -0,0 +1,36 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +package org.elasticsearch.xpack.ql.expression.function; + +import org.elasticsearch.xpack.ql.expression.function.aggregate.AggregateFunction; +import org.elasticsearch.xpack.ql.expression.function.scalar.ScalarFunction; + + +public class DefaultFunctionTypeRegistry implements FunctionTypeRegistry { + + public static final DefaultFunctionTypeRegistry INSTANCE = new DefaultFunctionTypeRegistry(); + + private enum Types { + AGGREGATE(AggregateFunction.class), + SCALAR(ScalarFunction.class); + + private Class baseClass; + + Types(Class base) { + this.baseClass = base; + } + } + + @Override + public String type(Class clazz) { + for (Types type : Types.values()) { + if (type.baseClass.isAssignableFrom(clazz)) { + return type.name(); + } + } + return "UNKNOWN"; + } +} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/Function.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/Function.java similarity index 81% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/Function.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/Function.java index 47e160df57853..a3738f313d63d 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/Function.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/Function.java @@ -3,15 +3,15 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.function; - -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.Nullability; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.ConstantInput; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.tree.Source; +package org.elasticsearch.xpack.ql.expression.function; + +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.Nullability; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.ConstantInput; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.List; import java.util.Locale; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/FunctionDefinition.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/FunctionDefinition.java similarity index 72% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/FunctionDefinition.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/FunctionDefinition.java index 6811963d3d18a..dc7a2eee7ee4b 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/FunctionDefinition.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/FunctionDefinition.java @@ -3,14 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.function; +package org.elasticsearch.xpack.ql.expression.function; -import org.elasticsearch.xpack.sql.session.Configuration; +import org.elasticsearch.xpack.ql.session.Configuration; import java.util.List; -import java.util.Locale; -import static java.lang.String.format; +import static org.elasticsearch.common.logging.LoggerMessageFormat.format; public class FunctionDefinition { /** @@ -29,16 +28,13 @@ public interface Builder { */ private final boolean extractViable; private final Builder builder; - private final FunctionType type; - FunctionDefinition(String name, List aliases, Class clazz, - boolean datetime, Builder builder) { + FunctionDefinition(String name, List aliases, Class clazz, boolean datetime, Builder builder) { this.name = name; this.aliases = aliases; this.clazz = clazz; this.extractViable = datetime; this.builder = builder; - this.type = FunctionType.of(clazz); } public String name() { @@ -49,11 +45,7 @@ public List aliases() { return aliases; } - public FunctionType type() { - return type; - } - - Class clazz() { + public Class clazz() { return clazz; } @@ -70,6 +62,6 @@ boolean extractViable() { @Override public String toString() { - return format(Locale.ROOT, "%s(%s)", name, aliases.isEmpty() ? "" : aliases.size() == 1 ? aliases.get(0) : aliases ); + return format(null, "{}({})", name, aliases.isEmpty() ? "" : aliases.size() == 1 ? aliases.get(0) : aliases); } } diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/FunctionRegistry.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/FunctionRegistry.java new file mode 100644 index 0000000000000..04ecf703908d9 --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/FunctionRegistry.java @@ -0,0 +1,420 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +package org.elasticsearch.xpack.ql.expression.function; + +import org.elasticsearch.common.Strings; +import org.elasticsearch.xpack.ql.ParsingException; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.session.Configuration; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.util.Check; + +import java.time.ZoneId; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Map.Entry; +import java.util.function.BiFunction; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +import static java.util.Collections.emptyList; +import static java.util.Collections.unmodifiableList; +import static java.util.stream.Collectors.toList; + +public class FunctionRegistry { + + // list of functions grouped by type of functions (aggregate, statistics, math etc) and ordered alphabetically inside each group + // a single function will have one entry for itself with its name associated to its instance and, also, one entry for each alias + // it has with the alias name associated to the FunctionDefinition instance + private final Map defs = new LinkedHashMap<>(); + private final Map aliases = new HashMap<>(); + + public FunctionRegistry() {} + + /** + * Register the given function definitions with this registry. + */ + public FunctionRegistry(FunctionDefinition... functions) { + register(functions); + } + + public FunctionRegistry(FunctionDefinition[]... groupFunctions) { + for (FunctionDefinition[] group : groupFunctions) { + register(group); + } + } + + protected void register(FunctionDefinition... functions) { + // temporary map to hold [function_name/alias_name : function instance] + Map batchMap = new HashMap<>(); + for (FunctionDefinition f : functions) { + batchMap.put(f.name(), f); + for (String alias : f.aliases()) { + Object old = batchMap.put(alias, f); + if (old != null || defs.containsKey(alias)) { + throw new QlIllegalArgumentException("alias [" + alias + "] is used by " + + "[" + (old != null ? old : defs.get(alias).name()) + "] and [" + f.name() + "]"); + } + aliases.put(alias, f.name()); + } + } + // sort the temporary map by key name and add it to the global map of functions + defs.putAll(batchMap.entrySet().stream() + .sorted(Map.Entry.comparingByKey()) + .collect(Collectors., String, + FunctionDefinition, LinkedHashMap> toMap(Map.Entry::getKey, Map.Entry::getValue, + (oldValue, newValue) -> oldValue, LinkedHashMap::new))); + } + + public FunctionDefinition resolveFunction(String functionName) { + FunctionDefinition def = defs.get(functionName); + if (def == null) { + throw new QlIllegalArgumentException( + "Cannot find function {}; this should have been caught during analysis", + functionName); + } + return def; + } + + public String resolveAlias(String alias) { + String upperCase = alias.toUpperCase(Locale.ROOT); + return aliases.getOrDefault(upperCase, upperCase); + } + + public boolean functionExists(String functionName) { + return defs.containsKey(functionName); + } + + public Collection listFunctions() { + // It is worth double checking if we need this copy. These are immutable anyway. + return defs.values(); + } + + public Collection listFunctions(String pattern) { + // It is worth double checking if we need this copy. These are immutable anyway. + Pattern p = Strings.hasText(pattern) ? Pattern.compile(pattern.toUpperCase(Locale.ROOT)) : null; + return defs.entrySet().stream() + .filter(e -> p == null || p.matcher(e.getKey()).matches()) + .map(e -> new FunctionDefinition(e.getKey(), emptyList(), + e.getValue().clazz(), e.getValue().extractViable(), e.getValue().builder())) + .collect(toList()); + } + + /** + * Build a {@linkplain FunctionDefinition} for a no-argument function that + * is not aware of time zone and does not support {@code DISTINCT}. + */ + protected static FunctionDefinition def(Class function, + java.util.function.Function ctorRef, String... names) { + FunctionBuilder builder = (source, children, distinct, cfg) -> { + if (false == children.isEmpty()) { + throw new QlIllegalArgumentException("expects no arguments"); + } + if (distinct) { + throw new QlIllegalArgumentException("does not support DISTINCT yet it was specified"); + } + return ctorRef.apply(source); + }; + return def(function, builder, false, names); + } + + /** + * Build a {@linkplain FunctionDefinition} for a no-argument function that + * is not aware of time zone, does not support {@code DISTINCT} and needs + * the cluster name (DATABASE()) or the user name (USER()). + */ + @SuppressWarnings("overloads") + protected static FunctionDefinition def(Class function, + ConfigurationAwareFunctionBuilder ctorRef, String... names) { + FunctionBuilder builder = (source, children, distinct, cfg) -> { + if (false == children.isEmpty()) { + throw new QlIllegalArgumentException("expects no arguments"); + } + if (distinct) { + throw new QlIllegalArgumentException("does not support DISTINCT yet it was specified"); + } + return ctorRef.build(source, cfg); + }; + return def(function, builder, false, names); + } + + protected interface ConfigurationAwareFunctionBuilder { + T build(Source source, Configuration configuration); + } + + /** + * Build a {@linkplain FunctionDefinition} for a one-argument function that + * is not aware of time zone, does not support {@code DISTINCT} and needs + * the configuration object. + */ + @SuppressWarnings("overloads") + protected static FunctionDefinition def(Class function, + UnaryConfigurationAwareFunctionBuilder ctorRef, String... names) { + FunctionBuilder builder = (source, children, distinct, cfg) -> { + if (children.size() > 1) { + throw new QlIllegalArgumentException("expects exactly one argument"); + } + if (distinct) { + throw new QlIllegalArgumentException("does not support DISTINCT yet it was specified"); + } + Expression ex = children.size() == 1 ? children.get(0) : null; + return ctorRef.build(source, ex, cfg); + }; + return def(function, builder, false, names); + } + + protected interface UnaryConfigurationAwareFunctionBuilder { + T build(Source source, Expression exp, Configuration configuration); + } + + + /** + * Build a {@linkplain FunctionDefinition} for a unary function that is not + * aware of time zone and does not support {@code DISTINCT}. + */ + @SuppressWarnings("overloads") // These are ambiguous if you aren't using ctor references but we always do + protected static FunctionDefinition def(Class function, + BiFunction ctorRef, String... names) { + FunctionBuilder builder = (source, children, distinct, cfg) -> { + if (children.size() != 1) { + throw new QlIllegalArgumentException("expects exactly one argument"); + } + if (distinct) { + throw new QlIllegalArgumentException("does not support DISTINCT yet it was specified"); + } + return ctorRef.apply(source, children.get(0)); + }; + return def(function, builder, false, names); + } + + /** + * Build a {@linkplain FunctionDefinition} for multi-arg function that + * is not aware of time zone and does not support {@code DISTINCT}. + */ + @SuppressWarnings("overloads") // These are ambiguous if you aren't using ctor references but we always do + public static FunctionDefinition def(Class function, + MultiFunctionBuilder ctorRef, String... names) { + FunctionBuilder builder = (source, children, distinct, cfg) -> { + if (distinct) { + throw new QlIllegalArgumentException("does not support DISTINCT yet it was specified"); + } + return ctorRef.build(source, children); + }; + return def(function, builder, false, names); + } + + protected interface MultiFunctionBuilder { + T build(Source source, List children); + } + + /** + * Build a {@linkplain FunctionDefinition} for a unary function that is not + * aware of time zone but does support {@code DISTINCT}. + */ + @SuppressWarnings("overloads") // These are ambiguous if you aren't using ctor references but we always do + public static FunctionDefinition def(Class function, + DistinctAwareUnaryFunctionBuilder ctorRef, String... names) { + FunctionBuilder builder = (source, children, distinct, cfg) -> { + if (children.size() != 1) { + throw new QlIllegalArgumentException("expects exactly one argument"); + } + return ctorRef.build(source, children.get(0), distinct); + }; + return def(function, builder, false, names); + } + + protected interface DistinctAwareUnaryFunctionBuilder { + T build(Source source, Expression target, boolean distinct); + } + + /** + * Build a {@linkplain FunctionDefinition} for a unary function that + * operates on a datetime. + */ + @SuppressWarnings("overloads") // These are ambiguous if you aren't using ctor references but we always do + public static FunctionDefinition def(Class function, + DatetimeUnaryFunctionBuilder ctorRef, String... names) { + FunctionBuilder builder = (source, children, distinct, cfg) -> { + if (children.size() != 1) { + throw new QlIllegalArgumentException("expects exactly one argument"); + } + if (distinct) { + throw new QlIllegalArgumentException("does not support DISTINCT yet it was specified"); + } + return ctorRef.build(source, children.get(0), cfg.zoneId()); + }; + return def(function, builder, true, names); + } + + protected interface DatetimeUnaryFunctionBuilder { + T build(Source source, Expression target, ZoneId zi); + } + + /** + * Build a {@linkplain FunctionDefinition} for a binary function that + * requires a timezone. + */ + @SuppressWarnings("overloads") // These are ambiguous if you aren't using ctor references but we always do + public static FunctionDefinition def(Class function, DatetimeBinaryFunctionBuilder ctorRef, + String... names) { + FunctionBuilder builder = (source, children, distinct, cfg) -> { + if (children.size() != 2) { + throw new QlIllegalArgumentException("expects exactly two arguments"); + } + if (distinct) { + throw new QlIllegalArgumentException("does not support DISTINCT yet it was specified"); + } + return ctorRef.build(source, children.get(0), children.get(1), cfg.zoneId()); + }; + return def(function, builder, false, names); + } + + protected interface DatetimeBinaryFunctionBuilder { + T build(Source source, Expression lhs, Expression rhs, ZoneId zi); + } + + /** + * Build a {@linkplain FunctionDefinition} for a three-args function that + * requires a timezone. + */ + @SuppressWarnings("overloads") // These are ambiguous if you aren't using ctor references but we always do + public static FunctionDefinition def(Class function, DatetimeThreeArgsFunctionBuilder ctorRef, + String... names) { + FunctionBuilder builder = (source, children, distinct, cfg) -> { + if (children.size() != 3) { + throw new QlIllegalArgumentException("expects three arguments"); + } + if (distinct) { + throw new QlIllegalArgumentException("does not support DISTINCT yet it was specified"); + } + return ctorRef.build(source, children.get(0), children.get(1), children.get(2), cfg.zoneId()); + }; + return def(function, builder, false, names); + } + + protected interface DatetimeThreeArgsFunctionBuilder { + T build(Source source, Expression first, Expression second, Expression third, ZoneId zi); + } + + /** + * Build a {@linkplain FunctionDefinition} for a binary function that is + * not aware of time zone and does not support {@code DISTINCT}. + */ + @SuppressWarnings("overloads") // These are ambiguous if you aren't using ctor references but we always do + public static FunctionDefinition def(Class function, + BinaryFunctionBuilder ctorRef, String... names) { + FunctionBuilder builder = (source, children, distinct, cfg) -> { + boolean isBinaryOptionalParamFunction = OptionalArgument.class.isAssignableFrom(function); + if (isBinaryOptionalParamFunction && (children.size() > 2 || children.size() < 1)) { + throw new QlIllegalArgumentException("expects one or two arguments"); + } else if (!isBinaryOptionalParamFunction && children.size() != 2) { + throw new QlIllegalArgumentException("expects exactly two arguments"); + } + + if (distinct) { + throw new QlIllegalArgumentException("does not support DISTINCT yet it was specified"); + } + return ctorRef.build(source, children.get(0), children.size() == 2 ? children.get(1) : null); + }; + return def(function, builder, false, names); + } + + protected interface BinaryFunctionBuilder { + T build(Source source, Expression lhs, Expression rhs); + } + + /** + * Main method to register a function/ + * @param names Must always have at least one entry which is the method's primary name + * + */ + @SuppressWarnings("overloads") + public static FunctionDefinition def(Class function, FunctionBuilder builder, + boolean datetime, String... names) { + Check.isTrue(names.length > 0, "At least one name must be provided for the function"); + String primaryName = names[0]; + List aliases = Arrays.asList(names).subList(1, names.length); + FunctionDefinition.Builder realBuilder = (uf, distinct, cfg) -> { + try { + return builder.build(uf.source(), uf.children(), distinct, cfg); + } catch (QlIllegalArgumentException e) { + throw new ParsingException(uf.source(), "error building [" + primaryName + "]: " + e.getMessage(), e); + } + }; + return new FunctionDefinition(primaryName, unmodifiableList(aliases), function, datetime, realBuilder); + } + + protected interface FunctionBuilder { + Function build(Source source, List children, boolean distinct, Configuration cfg); + } + + @SuppressWarnings("overloads") // These are ambiguous if you aren't using ctor references but we always do + public static FunctionDefinition def(Class function, + ThreeParametersFunctionBuilder ctorRef, String... names) { + FunctionBuilder builder = (source, children, distinct, cfg) -> { + boolean hasMinimumTwo = OptionalArgument.class.isAssignableFrom(function); + if (hasMinimumTwo && (children.size() > 3 || children.size() < 2)) { + throw new QlIllegalArgumentException("expects two or three arguments"); + } else if (!hasMinimumTwo && children.size() != 3) { + throw new QlIllegalArgumentException("expects exactly three arguments"); + } + if (distinct) { + throw new QlIllegalArgumentException("does not support DISTINCT yet it was specified"); + } + return ctorRef.build(source, children.get(0), children.get(1), children.size() == 3 ? children.get(2) : null); + }; + return def(function, builder, false, names); + } + + protected interface ThreeParametersFunctionBuilder { + T build(Source source, Expression src, Expression exp1, Expression exp2); + } + + @SuppressWarnings("overloads") // These are ambiguous if you aren't using ctor references but we always do + public static FunctionDefinition def(Class function, + FourParametersFunctionBuilder ctorRef, String... names) { + FunctionBuilder builder = (source, children, distinct, cfg) -> { + if (children.size() != 4) { + throw new QlIllegalArgumentException("expects exactly four arguments"); + } + if (distinct) { + throw new QlIllegalArgumentException("does not support DISTINCT yet it was specified"); + } + return ctorRef.build(source, children.get(0), children.get(1), children.get(2), children.get(3)); + }; + return def(function, builder, false, names); + } + + protected interface FourParametersFunctionBuilder { + T build(Source source, Expression src, Expression exp1, Expression exp2, Expression exp3); + } + + /** + * Special method to create function definition for Cast as its + * signature is not compatible with {@link UnresolvedFunction} + * + * @return Cast function definition + */ + @SuppressWarnings("overloads") // These are ambiguous if you aren't using ctor references but we always do + public static FunctionDefinition def(Class function, + CastFunctionBuilder ctorRef, + String... names) { + FunctionBuilder builder = (source, children, distinct, cfg) -> + ctorRef.build(source, children.get(0), children.get(0).dataType()); + return def(function, builder, false, names); + } + + protected interface CastFunctionBuilder { + T build(Source source, Expression expression, DataType dataType); + } +} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/NullIntolerant.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/FunctionTypeRegistry.java similarity index 57% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/NullIntolerant.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/FunctionTypeRegistry.java index d3e62db81ad43..67729e90462d5 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/NullIntolerant.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/FunctionTypeRegistry.java @@ -3,10 +3,10 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression; -// marker interface for expressions that are do not support null -// and thus are eliminated by it -public interface NullIntolerant { +package org.elasticsearch.xpack.ql.expression.function; +public interface FunctionTypeRegistry { + + String type(Class clazz); } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/Functions.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/Functions.java similarity index 63% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/Functions.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/Functions.java index 47ca821f4b5b4..6da5f05303401 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/Functions.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/Functions.java @@ -3,11 +3,11 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.function; +package org.elasticsearch.xpack.ql.expression.function; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.function.aggregate.AggregateFunction; -import org.elasticsearch.xpack.sql.expression.function.grouping.GroupingFunction; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.function.aggregate.AggregateFunction; +import org.elasticsearch.xpack.ql.expression.function.grouping.GroupingFunction; public abstract class Functions { diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/OptionalArgument.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/OptionalArgument.java new file mode 100644 index 0000000000000..6a7e86345b4d9 --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/OptionalArgument.java @@ -0,0 +1,15 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.ql.expression.function; + +/** + * Marker interface indicating that a function accepts one optional argument (typically the last one). + * This is used by the {@link FunctionRegistry} to perform validation of function declaration. + */ +public interface OptionalArgument { + +} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/UnresolvedFunction.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/UnresolvedFunction.java similarity index 91% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/UnresolvedFunction.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/UnresolvedFunction.java index 920d030ddfd99..de3beb39e6d55 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/UnresolvedFunction.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/UnresolvedFunction.java @@ -3,20 +3,21 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.function; +package org.elasticsearch.xpack.ql.expression.function; -import org.elasticsearch.xpack.sql.capabilities.Unresolvable; -import org.elasticsearch.xpack.sql.capabilities.UnresolvedException; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.expression.Nullability; -import org.elasticsearch.xpack.sql.expression.function.aggregate.Count; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.session.Configuration; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.util.StringUtils; +import org.elasticsearch.xpack.ql.capabilities.Unresolvable; +import org.elasticsearch.xpack.ql.capabilities.UnresolvedException; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.Nullability; +import org.elasticsearch.xpack.ql.expression.function.aggregate.Count; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.session.Configuration; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; +import org.elasticsearch.xpack.ql.util.StringUtils; import java.util.LinkedHashSet; import java.util.List; @@ -195,7 +196,7 @@ public UnresolvedFunction preprocessStar(UnresolvedFunction uf) { // dedicated count optimization if (uf.name.toUpperCase(Locale.ROOT).equals("COUNT")) { return new UnresolvedFunction(uf.source(), uf.name(), uf.resolutionType, - singletonList(Literal.of(uf.arguments().get(0).source(), Integer.valueOf(1)))); + singletonList(new Literal(uf.arguments().get(0).source(), Integer.valueOf(1), DataTypes.INTEGER))); } return uf; } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/AggregateFunction.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/aggregate/AggregateFunction.java similarity index 73% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/AggregateFunction.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/aggregate/AggregateFunction.java index 91ac02dc83785..ba274f744bfe0 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/AggregateFunction.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/aggregate/AggregateFunction.java @@ -3,18 +3,18 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.function.aggregate; +package org.elasticsearch.xpack.ql.expression.function.aggregate; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.TypeResolutions; -import org.elasticsearch.xpack.sql.expression.function.Function; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.AggNameInput; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.util.CollectionUtils; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.TypeResolutions; +import org.elasticsearch.xpack.ql.expression.function.Function; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.AggNameInput; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.util.CollectionUtils; import java.util.List; import java.util.Objects; @@ -61,7 +61,7 @@ protected Pipe makePipe() { @Override public ScriptTemplate asScript() { - throw new SqlIllegalArgumentException("Aggregate functions cannot be scripted"); + throw new QlIllegalArgumentException("Aggregate functions cannot be scripted"); } @Override diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/aggregate/CompoundAggregate.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/aggregate/CompoundAggregate.java new file mode 100644 index 0000000000000..bab1cd7c3e3cf --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/aggregate/CompoundAggregate.java @@ -0,0 +1,21 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.ql.expression.function.aggregate; + +import org.elasticsearch.xpack.ql.expression.Expression; + +import java.util.List; + +/** + * Marker type for compound aggregates, that is an aggregate that provides multiple values (like Stats or Matrix) + */ +public interface CompoundAggregate { + + Expression field(); + + List arguments(); +} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Count.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/aggregate/Count.java similarity index 82% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Count.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/aggregate/Count.java index 951144f5b2eb6..aa03d9e32e2a9 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Count.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/aggregate/Count.java @@ -3,12 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.function.aggregate; +package org.elasticsearch.xpack.ql.expression.function.aggregate; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import java.util.List; import java.util.Objects; @@ -46,7 +47,7 @@ public boolean distinct() { @Override public DataType dataType() { - return DataType.LONG; + return DataTypes.LONG; } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/EnclosedAgg.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/aggregate/EnclosedAgg.java similarity index 85% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/EnclosedAgg.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/aggregate/EnclosedAgg.java index 146cc68ba14a4..4f74d18dd50aa 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/EnclosedAgg.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/aggregate/EnclosedAgg.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.function.aggregate; +package org.elasticsearch.xpack.ql.expression.function.aggregate; // Agg 'enclosed' by another agg. Used for agg that return multiple embedded aggs (like MatrixStats) public interface EnclosedAgg { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/InnerAggregate.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/aggregate/InnerAggregate.java similarity index 78% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/InnerAggregate.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/aggregate/InnerAggregate.java index c9d18b83c156d..45c647a099a2e 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/InnerAggregate.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/aggregate/InnerAggregate.java @@ -3,12 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.function.aggregate; +package org.elasticsearch.xpack.ql.expression.function.aggregate; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.util.Check; import java.util.List; import java.util.Objects; @@ -16,19 +17,21 @@ public class InnerAggregate extends AggregateFunction { private final AggregateFunction inner; - private final CompoundNumericAggregate outer; + private final CompoundAggregate outer; private final String innerName; // used when the result needs to be extracted from a map (like in MatrixAggs or Percentiles) private final Expression innerKey; - public InnerAggregate(AggregateFunction inner, CompoundNumericAggregate outer) { + public InnerAggregate(AggregateFunction inner, CompoundAggregate outer) { this(inner.source(), inner, outer, null); } - public InnerAggregate(Source source, AggregateFunction inner, CompoundNumericAggregate outer, Expression innerKey) { + public InnerAggregate(Source source, AggregateFunction inner, CompoundAggregate outer, Expression innerKey) { super(source, outer.field(), outer.arguments()); this.inner = inner; this.outer = outer; + Check.isTrue(inner instanceof EnclosedAgg, "Inner function is not marked as Enclosed"); + Check.isTrue(outer instanceof Expression, "CompoundAggregate is not an Expression"); this.innerName = ((EnclosedAgg) inner).innerName(); this.innerKey = innerKey; } @@ -51,7 +54,7 @@ public AggregateFunction inner() { return inner; } - public CompoundNumericAggregate outer() { + public CompoundAggregate outer() { return outer; } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/grouping/GroupingFunction.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/grouping/GroupingFunction.java similarity index 73% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/grouping/GroupingFunction.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/grouping/GroupingFunction.java index 327c4ef382db0..319954e3973c2 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/grouping/GroupingFunction.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/grouping/GroupingFunction.java @@ -3,16 +3,16 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.function.grouping; +package org.elasticsearch.xpack.ql.expression.function.grouping; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.function.Function; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.AggNameInput; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.util.CollectionUtils; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.function.Function; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.AggNameInput; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.util.CollectionUtils; import java.util.List; import java.util.Objects; @@ -54,7 +54,7 @@ protected Pipe makePipe() { @Override public ScriptTemplate asScript() { - throw new SqlIllegalArgumentException("Grouping functions cannot be scripted"); + throw new QlIllegalArgumentException("Grouping functions cannot be scripted"); } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/BinaryScalarFunction.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/scalar/BinaryScalarFunction.java similarity index 85% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/BinaryScalarFunction.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/scalar/BinaryScalarFunction.java index 0a21fa83606d1..c06a5060d829b 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/BinaryScalarFunction.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/scalar/BinaryScalarFunction.java @@ -3,12 +3,12 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.function.scalar; +package org.elasticsearch.xpack.ql.expression.function.scalar; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.expression.gen.script.Scripts; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.expression.gen.script.Scripts; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Arrays; import java.util.List; diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/scalar/IntervalScripting.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/scalar/IntervalScripting.java new file mode 100644 index 0000000000000..9216235471576 --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/scalar/IntervalScripting.java @@ -0,0 +1,18 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.ql.expression.function.scalar; + +// FIXME: accessor interface until making script generation pluggable +public interface IntervalScripting { + + String script(); + + String value(); + + String typeName(); + +} diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/scalar/ScalarFunction.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/scalar/ScalarFunction.java new file mode 100644 index 0000000000000..bcb3cbcabcaf9 --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/scalar/ScalarFunction.java @@ -0,0 +1,147 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +package org.elasticsearch.xpack.ql.expression.function.scalar; + +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.expression.function.Function; +import org.elasticsearch.xpack.ql.expression.function.aggregate.AggregateFunction; +import org.elasticsearch.xpack.ql.expression.function.grouping.GroupingFunction; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.expression.gen.script.Scripts; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.util.DateUtils; + +import java.time.OffsetTime; +import java.time.ZonedDateTime; +import java.util.List; + +import static java.util.Collections.emptyList; +import static org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder.paramsBuilder; + +/** + * A {@code ScalarFunction} is a {@code Function} that takes values from some + * operation and converts each to another value. An example would be + * {@code ABS()}, which takes one value at a time, applies a function to the + * value (abs) and returns a new value. + */ +public abstract class ScalarFunction extends Function { + + protected ScalarFunction(Source source) { + super(source, emptyList()); + } + + protected ScalarFunction(Source source, List fields) { + super(source, fields); + } + + // used if the function is monotonic and thus does not have to be computed for ordering purposes + // null means the script needs to be used; expression means the field/expression to be used instead + public Expression orderBy() { + return null; + } + + + // + // Script generation + // + + public ScriptTemplate asScript(Expression exp) { + if (exp.foldable()) { + return scriptWithFoldable(exp); + } + + if (exp instanceof FieldAttribute) { + return scriptWithField((FieldAttribute) exp); + } + + if (exp instanceof ScalarFunction) { + return scriptWithScalar((ScalarFunction) exp); + } + + if (exp instanceof AggregateFunction) { + return scriptWithAggregate((AggregateFunction) exp); + } + + if (exp instanceof GroupingFunction) { + return scriptWithGrouping((GroupingFunction) exp); + } + throw new QlIllegalArgumentException("Cannot evaluate script for expression {}", exp); + } + + + protected ScriptTemplate scriptWithFoldable(Expression foldable) { + Object fold = foldable.fold(); + + // FIXME: this needs to be refactored + // + // Custom type handling + // + + // wrap intervals with dedicated methods for serialization + if (fold instanceof ZonedDateTime) { + ZonedDateTime zdt = (ZonedDateTime) fold; + return new ScriptTemplate(processScript("{sql}.asDateTime({})"), paramsBuilder().variable(DateUtils.toString(zdt)).build(), + dataType()); + } + + if (fold instanceof IntervalScripting) { + IntervalScripting is = (IntervalScripting) fold; + return new ScriptTemplate(processScript(is.script()), paramsBuilder().variable(is.value()).variable(is.typeName()).build(), + dataType()); + } + + if (fold instanceof OffsetTime) { + OffsetTime ot = (OffsetTime) fold; + return new ScriptTemplate(processScript("{sql}.asTime({})"), paramsBuilder().variable(ot.toString()).build(), dataType()); + } + + if (fold != null && fold.getClass().getSimpleName().equals("GeoShape")) { + return new ScriptTemplate(processScript("{sql}.stWktToSql({})"), paramsBuilder().variable(fold.toString()).build(), dataType()); + } + + + return new ScriptTemplate(processScript("{}"), + paramsBuilder().variable(fold).build(), + dataType()); + } + + protected ScriptTemplate scriptWithScalar(ScalarFunction scalar) { + ScriptTemplate nested = scalar.asScript(); + return new ScriptTemplate(processScript(nested.template()), + paramsBuilder().script(nested.params()).build(), + dataType()); + } + + protected ScriptTemplate scriptWithAggregate(AggregateFunction aggregate) { + String template = "{}"; + return new ScriptTemplate(processScript(template), + paramsBuilder().agg(aggregate).build(), + dataType()); + } + + protected ScriptTemplate scriptWithGrouping(GroupingFunction grouping) { + String template = "{}"; + return new ScriptTemplate(processScript(template), + paramsBuilder().grouping(grouping).build(), + dataType()); + } + + protected ScriptTemplate scriptWithField(FieldAttribute field) { + return new ScriptTemplate(processScript("doc[{}].value"), + paramsBuilder().variable(field.name()).build(), + dataType()); + } + + protected String processScript(String script) { + return formatTemplate(script); + } + + protected String formatTemplate(String template) { + return Scripts.formatTemplate(template); + } +} \ No newline at end of file diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/UnaryScalarFunction.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/scalar/UnaryScalarFunction.java similarity index 76% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/UnaryScalarFunction.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/scalar/UnaryScalarFunction.java index d10d18b83a1dd..905359996132b 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/UnaryScalarFunction.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/scalar/UnaryScalarFunction.java @@ -3,15 +3,15 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.function.scalar; +package org.elasticsearch.xpack.ql.expression.function.scalar; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.UnaryPipe; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.UnaryPipe; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.List; diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/scalar/whitelist/InternalQlScriptUtils.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/scalar/whitelist/InternalQlScriptUtils.java new file mode 100644 index 0000000000000..26c4bea1cf592 --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/scalar/whitelist/InternalQlScriptUtils.java @@ -0,0 +1,93 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.ql.expression.function.scalar.whitelist; + +import org.elasticsearch.index.fielddata.ScriptDocValues; +import org.elasticsearch.xpack.ql.expression.predicate.logical.BinaryLogicProcessor.BinaryLogicOperation; +import org.elasticsearch.xpack.ql.expression.predicate.logical.NotProcessor; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.BinaryComparisonProcessor.BinaryComparisonOperation; +import org.elasticsearch.xpack.ql.util.StringUtils; + +import java.util.Map; + +public abstract class InternalQlScriptUtils { + + // + // Utilities + // + + // safe missing mapping/value extractor + public static Object docValue(Map> doc, String fieldName) { + if (doc.containsKey(fieldName)) { + ScriptDocValues docValues = doc.get(fieldName); + if (!docValues.isEmpty()) { + return docValues.get(0); + } + } + return null; + } + + public static boolean nullSafeFilter(Boolean filter) { + return filter == null ? false : filter.booleanValue(); + } + + public static double nullSafeSortNumeric(Number sort) { + return sort == null ? 0.0d : sort.doubleValue(); + } + + public static String nullSafeSortString(Object sort) { + return sort == null ? StringUtils.EMPTY : sort.toString(); + } + + + // + // Operators + // + + // + // Logical + // + public static Boolean eq(Object left, Object right) { + return BinaryComparisonOperation.EQ.apply(left, right); + } + + public static Boolean nulleq(Object left, Object right) { + return BinaryComparisonOperation.NULLEQ.apply(left, right); + } + + public static Boolean neq(Object left, Object right) { + return BinaryComparisonOperation.NEQ.apply(left, right); + } + + public static Boolean lt(Object left, Object right) { + return BinaryComparisonOperation.LT.apply(left, right); + } + + public static Boolean lte(Object left, Object right) { + return BinaryComparisonOperation.LTE.apply(left, right); + } + + public static Boolean gt(Object left, Object right) { + return BinaryComparisonOperation.GT.apply(left, right); + } + + public static Boolean gte(Object left, Object right) { + return BinaryComparisonOperation.GTE.apply(left, right); + } + + public static Boolean and(Boolean left, Boolean right) { + return BinaryLogicOperation.AND.apply(left, right); + } + + public static Boolean or(Boolean left, Boolean right) { + return BinaryLogicOperation.OR.apply(left, right); + } + + public static Boolean not(Boolean expression) { + return NotProcessor.apply(expression); + } +} \ No newline at end of file diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/AggExtractorInput.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/AggExtractorInput.java similarity index 63% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/AggExtractorInput.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/AggExtractorInput.java index 554b7d3e3c885..c676bf0e22444 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/AggExtractorInput.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/AggExtractorInput.java @@ -3,16 +3,16 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.pipeline; +package org.elasticsearch.xpack.ql.expression.gen.pipeline; -import org.elasticsearch.xpack.sql.execution.search.SqlSourceBuilder; -import org.elasticsearch.xpack.sql.execution.search.extractor.BucketExtractor; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.processor.BucketExtractorProcessor; -import org.elasticsearch.xpack.sql.expression.gen.processor.ChainingProcessor; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.execution.search.QlSourceBuilder; +import org.elasticsearch.xpack.ql.execution.search.extractor.BucketExtractor; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.processor.BucketExtractorProcessor; +import org.elasticsearch.xpack.ql.expression.gen.processor.ChainingProcessor; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; public class AggExtractorInput extends LeafInput { @@ -45,7 +45,7 @@ public Pipe resolveAttributes(AttributeResolver resolver) { } @Override - public final void collectFields(SqlSourceBuilder sourceBuilder) { + public final void collectFields(QlSourceBuilder sourceBuilder) { // Nothing to collect } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/AggNameInput.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/AggNameInput.java similarity index 78% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/AggNameInput.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/AggNameInput.java index 7f3a12b560cf2..3b32cca28d8a9 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/AggNameInput.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/AggNameInput.java @@ -3,11 +3,11 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.pipeline; +package org.elasticsearch.xpack.ql.expression.gen.pipeline; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; public class AggNameInput extends CommonNonExecutableInput { public AggNameInput(Source source, Expression expression, String context) { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/AggPathInput.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/AggPathInput.java similarity index 84% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/AggPathInput.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/AggPathInput.java index 30c0968b9ef23..4e82853d5bcf5 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/AggPathInput.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/AggPathInput.java @@ -3,13 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.pipeline; +package org.elasticsearch.xpack.ql.expression.gen.pipeline; -import org.elasticsearch.xpack.sql.execution.search.AggRef; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.execution.search.AggRef; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/AttributeInput.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/AttributeInput.java similarity index 71% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/AttributeInput.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/AttributeInput.java index 72f2396582894..dcbc3861a315f 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/AttributeInput.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/AttributeInput.java @@ -3,13 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.pipeline; +package org.elasticsearch.xpack.ql.expression.gen.pipeline; -import org.elasticsearch.xpack.sql.execution.search.SqlSourceBuilder; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.execution.search.QlSourceBuilder; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; /** * An input that must first be rewritten against the rest of the query @@ -36,7 +36,7 @@ public Pipe resolveAttributes(AttributeResolver resolver) { } @Override - public final void collectFields(SqlSourceBuilder sourceBuilder) { + public final void collectFields(QlSourceBuilder sourceBuilder) { // Nothing to extract } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/BinaryPipe.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/BinaryPipe.java similarity index 88% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/BinaryPipe.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/BinaryPipe.java index 64f81f4f5b3ad..4256f6491bffe 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/BinaryPipe.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/BinaryPipe.java @@ -3,11 +3,11 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.pipeline; +package org.elasticsearch.xpack.ql.expression.gen.pipeline; -import org.elasticsearch.xpack.sql.execution.search.SqlSourceBuilder; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.execution.search.QlSourceBuilder; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Arrays; import java.util.List; @@ -66,7 +66,7 @@ public boolean resolved() { } @Override - public final void collectFields(SqlSourceBuilder sourceBuilder) { + public final void collectFields(QlSourceBuilder sourceBuilder) { left.collectFields(sourceBuilder); right.collectFields(sourceBuilder); } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/CommonNonExecutableInput.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/CommonNonExecutableInput.java similarity index 59% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/CommonNonExecutableInput.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/CommonNonExecutableInput.java index cb1072bc6b884..bc8469fc9d7fa 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/CommonNonExecutableInput.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/CommonNonExecutableInput.java @@ -3,13 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.pipeline; +package org.elasticsearch.xpack.ql.expression.gen.pipeline; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.execution.search.SqlSourceBuilder; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.execution.search.QlSourceBuilder; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.tree.Source; /** * Implementation common to most subclasses of @@ -22,7 +22,7 @@ abstract class CommonNonExecutableInput extends NonExecutableInput { @Override public final Processor asProcessor() { - throw new SqlIllegalArgumentException("Unresolved input - needs resolving first"); + throw new QlIllegalArgumentException("Unresolved input - needs resolving first"); } @Override @@ -31,7 +31,7 @@ public final Pipe resolveAttributes(AttributeResolver resolver) { } @Override - public final void collectFields(SqlSourceBuilder sourceBuilder) { + public final void collectFields(QlSourceBuilder sourceBuilder) { // Nothing to extract } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/ConstantInput.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/ConstantInput.java similarity index 65% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/ConstantInput.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/ConstantInput.java index 21a8a86566881..49b6a16c598f5 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/ConstantInput.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/ConstantInput.java @@ -3,14 +3,14 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.pipeline; +package org.elasticsearch.xpack.ql.expression.gen.pipeline; -import org.elasticsearch.xpack.sql.execution.search.SqlSourceBuilder; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.processor.ConstantProcessor; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.execution.search.QlSourceBuilder; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.processor.ConstantProcessor; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; public class ConstantInput extends LeafInput { @@ -39,7 +39,7 @@ public Pipe resolveAttributes(AttributeResolver resolver) { } @Override - public final void collectFields(SqlSourceBuilder sourceBuilder) { + public final void collectFields(QlSourceBuilder sourceBuilder) { // Nothing to collect } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/HitExtractorInput.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/HitExtractorInput.java similarity index 62% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/HitExtractorInput.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/HitExtractorInput.java index e58c97e883717..3f977fbc3755c 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/HitExtractorInput.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/HitExtractorInput.java @@ -3,15 +3,15 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.pipeline; +package org.elasticsearch.xpack.ql.expression.gen.pipeline; -import org.elasticsearch.xpack.sql.execution.search.SqlSourceBuilder; -import org.elasticsearch.xpack.sql.execution.search.extractor.HitExtractor; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.processor.HitExtractorProcessor; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.execution.search.QlSourceBuilder; +import org.elasticsearch.xpack.ql.execution.search.extractor.HitExtractor; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.processor.HitExtractorProcessor; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; public class HitExtractorInput extends LeafInput { @@ -40,7 +40,7 @@ public Pipe resolveAttributes(AttributeResolver resolver) { } @Override - public final void collectFields(SqlSourceBuilder sourceBuilder) { + public final void collectFields(QlSourceBuilder sourceBuilder) { // No fields to collect } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/LeafInput.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/LeafInput.java similarity index 89% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/LeafInput.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/LeafInput.java index ff5ed1ced6d6b..b81b166a28fa7 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/LeafInput.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/LeafInput.java @@ -3,10 +3,10 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.pipeline; +package org.elasticsearch.xpack.ql.expression.gen.pipeline; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.List; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/MultiPipe.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/MultiPipe.java similarity index 76% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/MultiPipe.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/MultiPipe.java index f0fc3e075895b..be3e84d2ea044 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/MultiPipe.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/MultiPipe.java @@ -4,11 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.pipeline; +package org.elasticsearch.xpack.ql.expression.gen.pipeline; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.ArrayList; import java.util.List; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/NonExecutableInput.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/NonExecutableInput.java similarity index 59% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/NonExecutableInput.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/NonExecutableInput.java index eae0f56df7be4..cb34ee3ba6e95 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/NonExecutableInput.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/NonExecutableInput.java @@ -3,12 +3,12 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.pipeline; +package org.elasticsearch.xpack.ql.expression.gen.pipeline; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.tree.Source; public abstract class NonExecutableInput extends LeafInput { NonExecutableInput(Source source, Expression expression, T context) { @@ -22,6 +22,6 @@ public boolean resolved() { @Override public Processor asProcessor() { - throw new SqlIllegalArgumentException("Unresolved input - needs resolving first"); + throw new QlIllegalArgumentException("Unresolved input - needs resolving first"); } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/Pipe.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/Pipe.java similarity index 75% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/Pipe.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/Pipe.java index 675cde43c450d..8f6480435919c 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/Pipe.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/Pipe.java @@ -3,17 +3,17 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.pipeline; +package org.elasticsearch.xpack.ql.expression.gen.pipeline; -import org.elasticsearch.xpack.sql.capabilities.Resolvable; -import org.elasticsearch.xpack.sql.capabilities.Resolvables; -import org.elasticsearch.xpack.sql.execution.search.FieldExtraction; -import org.elasticsearch.xpack.sql.execution.search.SqlSourceBuilder; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.tree.Node; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.capabilities.Resolvable; +import org.elasticsearch.xpack.ql.capabilities.Resolvables; +import org.elasticsearch.xpack.ql.execution.search.FieldExtraction; +import org.elasticsearch.xpack.ql.execution.search.QlSourceBuilder; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.tree.Node; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.ArrayList; import java.util.List; @@ -47,7 +47,7 @@ public boolean resolved() { } @Override - public void collectFields(SqlSourceBuilder sourceBuilder) { + public void collectFields(QlSourceBuilder sourceBuilder) { children().forEach(c -> c.collectFields(sourceBuilder)); } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/ReferenceInput.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/ReferenceInput.java similarity index 67% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/ReferenceInput.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/ReferenceInput.java index d9bbdb8631b43..c54f4f7d48313 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/ReferenceInput.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/ReferenceInput.java @@ -3,13 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.pipeline; +package org.elasticsearch.xpack.ql.expression.gen.pipeline; -import org.elasticsearch.xpack.sql.execution.search.FieldExtraction; -import org.elasticsearch.xpack.sql.execution.search.SqlSourceBuilder; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.execution.search.FieldExtraction; +import org.elasticsearch.xpack.ql.execution.search.QlSourceBuilder; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; public class ReferenceInput extends NonExecutableInput { public ReferenceInput(Source source, Expression expression, FieldExtraction context) { @@ -32,7 +32,7 @@ public Pipe resolveAttributes(AttributeResolver resolver) { } @Override - public final void collectFields(SqlSourceBuilder sourceBuilder) { + public final void collectFields(QlSourceBuilder sourceBuilder) { context().collectFields(sourceBuilder); } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/UnaryPipe.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/UnaryPipe.java similarity index 83% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/UnaryPipe.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/UnaryPipe.java index 4920c3935bbb1..ef361e605cad2 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/UnaryPipe.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/UnaryPipe.java @@ -3,14 +3,14 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.pipeline; +package org.elasticsearch.xpack.ql.expression.gen.pipeline; -import org.elasticsearch.xpack.sql.execution.search.SqlSourceBuilder; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.processor.ChainingProcessor; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.execution.search.QlSourceBuilder; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.processor.ChainingProcessor; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.List; import java.util.Objects; @@ -74,7 +74,7 @@ public Pipe resolveAttributes(AttributeResolver resolver) { } @Override - public void collectFields(SqlSourceBuilder sourceBuilder) { + public void collectFields(QlSourceBuilder sourceBuilder) { child.collectFields(sourceBuilder); } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/processor/BinaryProcessor.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/BinaryProcessor.java similarity index 96% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/processor/BinaryProcessor.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/BinaryProcessor.java index b504c2072fec6..7fe911e4acad3 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/processor/BinaryProcessor.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/BinaryProcessor.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.processor; +package org.elasticsearch.xpack.ql.expression.gen.processor; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/processor/BucketExtractorProcessor.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/BucketExtractorProcessor.java similarity index 86% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/processor/BucketExtractorProcessor.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/BucketExtractorProcessor.java index e3e8a2c9c8313..8dccffb83f474 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/processor/BucketExtractorProcessor.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/BucketExtractorProcessor.java @@ -3,13 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.processor; +package org.elasticsearch.xpack.ql.expression.gen.processor; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation.Bucket; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.execution.search.extractor.BucketExtractor; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.execution.search.extractor.BucketExtractor; import java.io.IOException; import java.util.Objects; @@ -45,7 +45,7 @@ public String getWriteableName() { @Override public Object process(Object input) { if (!(input instanceof Bucket)) { - throw new SqlIllegalArgumentException("Expected an agg bucket but received {}", input); + throw new QlIllegalArgumentException("Expected an agg bucket but received {}", input); } return extractor.extract((Bucket) input); } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/processor/ChainingProcessor.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/ChainingProcessor.java similarity index 96% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/processor/ChainingProcessor.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/ChainingProcessor.java index e9c1385818364..05e54d3467575 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/processor/ChainingProcessor.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/ChainingProcessor.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.processor; +package org.elasticsearch.xpack.ql.expression.gen.processor; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/ConstantNamedWriteable.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/ConstantNamedWriteable.java new file mode 100644 index 0000000000000..e59078ac65eb6 --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/ConstantNamedWriteable.java @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.ql.expression.gen.processor; + +import org.elasticsearch.common.io.stream.NamedWriteable; + +/** + * Marker interface used by QL for pluggable constant serialization. + */ +public interface ConstantNamedWriteable extends NamedWriteable { + +} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/processor/ConstantProcessor.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/ConstantProcessor.java similarity index 77% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/processor/ConstantProcessor.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/ConstantProcessor.java index 826cf1816ae6b..cb7d60c831994 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/processor/ConstantProcessor.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/ConstantProcessor.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.processor; +package org.elasticsearch.xpack.ql.expression.gen.processor; import org.elasticsearch.common.io.stream.NamedWriteable; import org.elasticsearch.common.io.stream.StreamInput; @@ -18,26 +18,17 @@ public class ConstantProcessor implements Processor { private final Object constant; private final boolean namedWriteable; - private final Class clazz; public ConstantProcessor(Object value) { this.constant = value; this.namedWriteable = value instanceof NamedWriteable; - this.clazz = namedWriteable ? value.getClass() : null; } - @SuppressWarnings("unchecked") public ConstantProcessor(StreamInput in) throws IOException { namedWriteable = in.readBoolean(); if (namedWriteable) { - try { - clazz = ConstantProcessor.class.getClassLoader().loadClass(in.readString()); - } catch (ClassNotFoundException e) { - throw new IOException(e); - } - constant = in.readNamedWriteable((Class) clazz); + constant = in.readNamedWriteable(ConstantNamedWriteable.class); } else { - clazz = null; constant = in.readGenericValue(); } } @@ -46,7 +37,6 @@ public ConstantProcessor(StreamInput in) throws IOException { public void writeTo(StreamOutput out) throws IOException { out.writeBoolean(namedWriteable); if (namedWriteable) { - out.writeString(constant.getClass().getName()); out.writeNamedWriteable((NamedWriteable) constant); } else { out.writeGenericValue(constant); @@ -86,4 +76,4 @@ public boolean equals(Object obj) { public String toString() { return "^" + constant; } -} +} \ No newline at end of file diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/processor/FunctionalBinaryProcessor.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/FunctionalBinaryProcessor.java similarity index 82% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/processor/FunctionalBinaryProcessor.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/FunctionalBinaryProcessor.java index 7e5d3a6089ca5..b42753f7c1fbc 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/processor/FunctionalBinaryProcessor.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/FunctionalBinaryProcessor.java @@ -4,19 +4,18 @@ * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.processor; +package org.elasticsearch.xpack.ql.expression.gen.processor; import org.elasticsearch.common.io.stream.StreamInput; -import org.elasticsearch.common.io.stream.StreamOutput; import java.io.IOException; import java.util.Objects; import java.util.function.BiFunction; /** - * Base class for definition binary processors based on functions (for applying) defined as enums (for serialization purposes). + * Base class for definition binary processors based on functions (for applying). */ -public abstract class FunctionalBinaryProcessor & BiFunction> extends BinaryProcessor { +public abstract class FunctionalBinaryProcessor> extends BinaryProcessor { private final F function; @@ -34,11 +33,6 @@ public F function() { return function; } - @Override - protected void doWrite(StreamOutput out) throws IOException { - out.writeEnum(function()); - } - @SuppressWarnings("unchecked") @Override protected Object doProcess(Object left, Object right) { diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/FunctionalEnumBinaryProcessor.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/FunctionalEnumBinaryProcessor.java new file mode 100644 index 0000000000000..50828ff1ec01a --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/FunctionalEnumBinaryProcessor.java @@ -0,0 +1,33 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.ql.expression.gen.processor; + +import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.common.io.stream.StreamOutput; + +import java.io.IOException; +import java.util.function.BiFunction; + +/** + * Base class for definition binary processors based on functions (for applying) defined as enums (for serialization purposes). + */ +public abstract class FunctionalEnumBinaryProcessor & BiFunction> + extends FunctionalBinaryProcessor { + + protected FunctionalEnumBinaryProcessor(Processor left, Processor right, F function) { + super(left, right, function); + } + + protected FunctionalEnumBinaryProcessor(StreamInput in, Reader reader) throws IOException { + super(in, reader); + } + + @Override + protected void doWrite(StreamOutput out) throws IOException { + out.writeEnum(function()); + } +} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/processor/HitExtractorProcessor.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/HitExtractorProcessor.java similarity index 86% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/processor/HitExtractorProcessor.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/HitExtractorProcessor.java index 9f58b00898978..fe0dd638a9845 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/processor/HitExtractorProcessor.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/HitExtractorProcessor.java @@ -3,13 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.processor; +package org.elasticsearch.xpack.ql.expression.gen.processor; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.search.SearchHit; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.execution.search.extractor.HitExtractor; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.execution.search.extractor.HitExtractor; import java.io.IOException; import java.util.Objects; @@ -45,7 +45,7 @@ public String getWriteableName() { @Override public Object process(Object input) { if (!(input instanceof SearchHit)) { - throw new SqlIllegalArgumentException("Expected a SearchHit but received {}", input); + throw new QlIllegalArgumentException("Expected a SearchHit but received {}", input); } return extractor.extract((SearchHit) input); } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/processor/Processor.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/Processor.java similarity index 91% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/processor/Processor.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/Processor.java index 2b8433191e395..d95d0623670af 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/processor/Processor.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/Processor.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.processor; +package org.elasticsearch.xpack.ql.expression.gen.processor; import org.elasticsearch.common.io.stream.NamedWriteable; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/processor/UnaryProcessor.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/UnaryProcessor.java similarity index 96% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/processor/UnaryProcessor.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/UnaryProcessor.java index 7c1a5dd7d3594..9fc6d01bdb0f8 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/processor/UnaryProcessor.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/processor/UnaryProcessor.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.processor; +package org.elasticsearch.xpack.ql.expression.gen.processor; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/Agg.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/script/Agg.java similarity index 74% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/Agg.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/script/Agg.java index ad4ff617cce49..aabbd607b94e7 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/Agg.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/script/Agg.java @@ -3,12 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.script; +package org.elasticsearch.xpack.ql.expression.gen.script; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.function.aggregate.AggregateFunction; -import org.elasticsearch.xpack.sql.expression.function.aggregate.Count; -import org.elasticsearch.xpack.sql.expression.function.aggregate.InnerAggregate; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.function.aggregate.AggregateFunction; +import org.elasticsearch.xpack.ql.expression.function.aggregate.Count; +import org.elasticsearch.xpack.ql.expression.function.aggregate.InnerAggregate; class Agg extends Param { @@ -27,7 +28,7 @@ public String aggProperty() { if (agg instanceof InnerAggregate) { InnerAggregate inner = (InnerAggregate) agg; - return Expressions.id(inner.outer()) + "." + inner.innerName(); + return Expressions.id((Expression) inner.outer()) + "." + inner.innerName(); } // Count needs special handling since in most cases it is not a dedicated aggregation else if (agg instanceof Count) { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/Grouping.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/script/Grouping.java similarity index 78% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/Grouping.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/script/Grouping.java index f34e1c8798f9e..f7f6bfcd30fec 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/Grouping.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/script/Grouping.java @@ -3,9 +3,9 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.script; +package org.elasticsearch.xpack.ql.expression.gen.script; -import org.elasticsearch.xpack.sql.expression.function.grouping.GroupingFunction; +import org.elasticsearch.xpack.ql.expression.function.grouping.GroupingFunction; class Grouping extends Param { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/Param.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/script/Param.java similarity index 94% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/Param.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/script/Param.java index 63b92be20a3d6..a7725b4faa06c 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/Param.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/script/Param.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.script; +package org.elasticsearch.xpack.ql.expression.gen.script; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/Params.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/script/Params.java similarity index 95% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/Params.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/script/Params.java index 073df0329d9c8..cc57863a7d589 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/Params.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/script/Params.java @@ -3,9 +3,9 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.script; +package org.elasticsearch.xpack.ql.expression.gen.script; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; import java.util.ArrayList; import java.util.LinkedHashMap; @@ -113,7 +113,7 @@ else if (p instanceof Var) { flatten.add(p); } else { - throw new SqlIllegalArgumentException("Unsupported field {}", p); + throw new QlIllegalArgumentException("Unsupported field {}", p); } } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/ParamsBuilder.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/script/ParamsBuilder.java similarity index 82% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/ParamsBuilder.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/script/ParamsBuilder.java index 2e13682b70e7a..c869036da6b87 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/ParamsBuilder.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/script/ParamsBuilder.java @@ -3,10 +3,10 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.script; +package org.elasticsearch.xpack.ql.expression.gen.script; -import org.elasticsearch.xpack.sql.expression.function.aggregate.AggregateFunction; -import org.elasticsearch.xpack.sql.expression.function.grouping.GroupingFunction; +import org.elasticsearch.xpack.ql.expression.function.aggregate.AggregateFunction; +import org.elasticsearch.xpack.ql.expression.function.grouping.GroupingFunction; import java.util.ArrayList; import java.util.List; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/Script.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/script/Script.java similarity index 87% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/Script.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/script/Script.java index 85c436cf69ec8..006dc78b79494 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/Script.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/script/Script.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.script; +package org.elasticsearch.xpack.ql.expression.gen.script; class Script extends Param { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/ScriptTemplate.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/script/ScriptTemplate.java similarity index 89% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/ScriptTemplate.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/script/ScriptTemplate.java index aeefa5c78f0e3..e2a3a2bbbeafd 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/ScriptTemplate.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/script/ScriptTemplate.java @@ -3,12 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.script; +package org.elasticsearch.xpack.ql.expression.gen.script; import org.elasticsearch.script.Script; import org.elasticsearch.script.ScriptType; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.util.StringUtils; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; +import org.elasticsearch.xpack.ql.util.StringUtils; import java.util.List; import java.util.Locale; @@ -27,7 +28,7 @@ public class ScriptTemplate { private final DataType outputType; public ScriptTemplate(String template) { - this(template, Params.EMPTY, DataType.KEYWORD); + this(template, Params.EMPTY, DataTypes.KEYWORD); } public ScriptTemplate(String template, Params params, DataType outputType) { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/Scripts.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/script/Scripts.java similarity index 78% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/Scripts.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/script/Scripts.java index 21ac12e51da89..a743500337f45 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/Scripts.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/script/Scripts.java @@ -4,13 +4,12 @@ * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.script; +package org.elasticsearch.xpack.ql.expression.gen.script; -import org.elasticsearch.xpack.sql.expression.function.scalar.whitelist.InternalSqlScriptUtils; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import java.util.AbstractMap.SimpleEntry; -import java.util.Collections; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; @@ -19,20 +18,23 @@ import java.util.stream.Stream; import static java.lang.String.format; +import static java.util.Collections.unmodifiableMap; import static java.util.stream.Collectors.toMap; -import static org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder.paramsBuilder; +import static org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder.paramsBuilder; public final class Scripts { public static final String DOC_VALUE = "doc[{}].value"; public static final String SQL_SCRIPTS = "{sql}"; public static final String PARAM = "{}"; + // FIXME: this needs to be either renamed (drop Sql) or find a pluggable approach (through ScriptWeaver) + public static final String INTERNAL_SCRIPT_UTILS = "InternalSqlScriptUtils"; private Scripts() {} - private static final Map FORMATTING_PATTERNS = Collections.unmodifiableMap(Stream.of( + static final Map FORMATTING_PATTERNS = unmodifiableMap(Stream.of( new SimpleEntry<>(DOC_VALUE, SQL_SCRIPTS + ".docValue(doc,{})"), - new SimpleEntry<>(SQL_SCRIPTS, InternalSqlScriptUtils.class.getSimpleName()), + new SimpleEntry<>(SQL_SCRIPTS, INTERNAL_SCRIPT_UTILS), new SimpleEntry<>(PARAM, "params.%s")) .collect(toMap(e -> Pattern.compile(e.getKey(), Pattern.LITERAL), Map.Entry::getValue, (a, b) -> a, LinkedHashMap::new))); @@ -56,7 +58,7 @@ public static ScriptTemplate nullSafeFilter(ScriptTemplate script) { return new ScriptTemplate(formatTemplate( format(Locale.ROOT, "{sql}.nullSafeFilter(%s)", script.template())), script.params(), - DataType.BOOLEAN); + DataTypes.BOOLEAN); } public static ScriptTemplate nullSafeSort(ScriptTemplate script) { @@ -68,11 +70,11 @@ public static ScriptTemplate nullSafeSort(ScriptTemplate script) { } public static ScriptTemplate and(ScriptTemplate left, ScriptTemplate right) { - return binaryMethod("and", left, right, DataType.BOOLEAN); + return binaryMethod("and", left, right, DataTypes.BOOLEAN); } public static ScriptTemplate or(ScriptTemplate left, ScriptTemplate right) { - return binaryMethod("or", left, right, DataType.BOOLEAN); + return binaryMethod("or", left, right, DataTypes.BOOLEAN); } public static ScriptTemplate binaryMethod(String methodName, ScriptTemplate leftScript, ScriptTemplate rightScript, diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/Var.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/script/Var.java similarity index 87% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/Var.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/script/Var.java index f22e510fdc4e2..e359581026e0b 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/Var.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/gen/script/Var.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.script; +package org.elasticsearch.xpack.ql.expression.gen.script; class Var extends Param { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/BinaryOperator.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/BinaryOperator.java similarity index 80% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/BinaryOperator.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/BinaryOperator.java index 318cfd9b62475..6e9ac5ae371d7 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/BinaryOperator.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/BinaryOperator.java @@ -3,12 +3,12 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate; +package org.elasticsearch.xpack.ql.expression.predicate; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.Expressions.ParamOrdinal; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.Expressions.ParamOrdinal; +import org.elasticsearch.xpack.ql.tree.Source; /** * Operator is a specialized binary predicate where both sides have the compatible types diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/BinaryPredicate.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/BinaryPredicate.java similarity index 89% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/BinaryPredicate.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/BinaryPredicate.java index 8705f9c58e578..bd67f335c8fbe 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/BinaryPredicate.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/BinaryPredicate.java @@ -3,11 +3,11 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate; +package org.elasticsearch.xpack.ql.expression.predicate; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.function.scalar.BinaryScalarFunction; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.function.scalar.BinaryScalarFunction; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/Negatable.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/Negatable.java similarity index 70% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/Negatable.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/Negatable.java index 138f901d516f8..da46a0624479f 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/Negatable.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/Negatable.java @@ -3,9 +3,9 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate; +package org.elasticsearch.xpack.ql.expression.predicate; -import org.elasticsearch.xpack.sql.expression.function.scalar.ScalarFunction; +import org.elasticsearch.xpack.ql.expression.function.scalar.ScalarFunction; public interface Negatable { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/PredicateBiFunction.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/PredicateBiFunction.java similarity index 92% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/PredicateBiFunction.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/PredicateBiFunction.java index 4966d0c9ab659..7ca124f515203 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/PredicateBiFunction.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/PredicateBiFunction.java @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate; +package org.elasticsearch.xpack.ql.expression.predicate; import java.util.Locale; import java.util.function.BiFunction; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/Predicates.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/Predicates.java similarity index 88% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/Predicates.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/Predicates.java index 83a4b96f8295b..04582ff91a7f5 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/Predicates.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/Predicates.java @@ -3,12 +3,11 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate; +package org.elasticsearch.xpack.ql.expression.predicate; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.predicate.logical.And; -import org.elasticsearch.xpack.sql.expression.predicate.logical.Or; -import org.elasticsearch.xpack.sql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.predicate.logical.And; +import org.elasticsearch.xpack.ql.expression.predicate.logical.Or; import java.util.ArrayList; import java.util.List; @@ -113,9 +112,4 @@ public static List subtract(List from, List } return diff.isEmpty() ? emptyList() : diff; } - - - public static boolean canEvaluate(Expression exp, LogicalPlan plan) { - return exp.references().subsetOf(plan.outputSet()); - } } \ No newline at end of file diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/Range.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/Range.java similarity index 79% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/Range.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/Range.java index 8405b0b436ad4..35ccd1d06b334 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/Range.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/Range.java @@ -3,23 +3,24 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate; - -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.Nullability; -import org.elasticsearch.xpack.sql.expression.function.scalar.ScalarFunction; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.script.Params; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.expression.predicate.logical.BinaryLogicPipe; -import org.elasticsearch.xpack.sql.expression.predicate.logical.BinaryLogicProcessor.BinaryLogicOperation; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.BinaryComparison; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.BinaryComparisonPipe; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.BinaryComparisonProcessor.BinaryComparisonOperation; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +package org.elasticsearch.xpack.ql.expression.predicate; + +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.Nullability; +import org.elasticsearch.xpack.ql.expression.function.scalar.ScalarFunction; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.script.Params; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.expression.predicate.logical.BinaryLogicPipe; +import org.elasticsearch.xpack.ql.expression.predicate.logical.BinaryLogicProcessor.BinaryLogicOperation; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.BinaryComparison; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.BinaryComparisonPipe; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.BinaryComparisonProcessor.BinaryComparisonOperation; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import java.util.List; import java.util.Locale; @@ -27,7 +28,7 @@ import static java.lang.String.format; import static java.util.Arrays.asList; -import static org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder.paramsBuilder; +import static org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder.paramsBuilder; // BETWEEN or range - is a mix of gt(e) AND lt(e) public class Range extends ScalarFunction { @@ -118,7 +119,7 @@ public Nullability nullable() { @Override public DataType dataType() { - return DataType.BOOLEAN; + return DataTypes.BOOLEAN; } @Override @@ -144,7 +145,7 @@ public ScriptTemplate asScript() { .script(upperScript.params()) .build(); - return new ScriptTemplate(template, params, DataType.BOOLEAN); + return new ScriptTemplate(template, params, DataTypes.BOOLEAN); } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/fulltext/FullTextPredicate.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/fulltext/FullTextPredicate.java similarity index 84% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/fulltext/FullTextPredicate.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/fulltext/FullTextPredicate.java index 7af299b97f5d5..088c67443d92a 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/fulltext/FullTextPredicate.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/fulltext/FullTextPredicate.java @@ -3,12 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.fulltext; +package org.elasticsearch.xpack.ql.expression.predicate.fulltext; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Nullability; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Nullability; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import java.util.List; import java.util.Map; @@ -63,7 +64,7 @@ public Nullability nullable() { @Override public DataType dataType() { - return DataType.BOOLEAN; + return DataTypes.BOOLEAN; } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/fulltext/FullTextUtils.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/fulltext/FullTextUtils.java similarity index 91% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/fulltext/FullTextUtils.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/fulltext/FullTextUtils.java index f1191e07d3a06..8258ad87b4e9e 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/fulltext/FullTextUtils.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/fulltext/FullTextUtils.java @@ -3,12 +3,12 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.fulltext; +package org.elasticsearch.xpack.ql.expression.predicate.fulltext; import org.elasticsearch.common.Strings; -import org.elasticsearch.xpack.sql.expression.predicate.fulltext.FullTextPredicate.Operator; -import org.elasticsearch.xpack.sql.parser.ParsingException; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.ParsingException; +import org.elasticsearch.xpack.ql.expression.predicate.fulltext.FullTextPredicate.Operator; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.LinkedHashMap; import java.util.Locale; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/fulltext/MatchQueryPredicate.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/fulltext/MatchQueryPredicate.java similarity index 87% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/fulltext/MatchQueryPredicate.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/fulltext/MatchQueryPredicate.java index eaab089d98877..d2725088feab5 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/fulltext/MatchQueryPredicate.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/fulltext/MatchQueryPredicate.java @@ -3,18 +3,17 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.fulltext; +package org.elasticsearch.xpack.ql.expression.predicate.fulltext; -import java.util.Objects; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import java.util.List; +import java.util.Objects; import static java.util.Collections.singletonList; -import java.util.List; - public class MatchQueryPredicate extends FullTextPredicate { private final Expression field; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/fulltext/MultiMatchQueryPredicate.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/fulltext/MultiMatchQueryPredicate.java similarity index 88% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/fulltext/MultiMatchQueryPredicate.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/fulltext/MultiMatchQueryPredicate.java index 785cb4883334c..b75f32c222b5f 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/fulltext/MultiMatchQueryPredicate.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/fulltext/MultiMatchQueryPredicate.java @@ -3,19 +3,18 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.fulltext; +package org.elasticsearch.xpack.ql.expression.predicate.fulltext; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; + +import java.util.List; import java.util.Map; import java.util.Objects; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; - import static java.util.Collections.emptyList; -import java.util.List; - public class MultiMatchQueryPredicate extends FullTextPredicate { private final String fieldString; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/fulltext/StringQueryPredicate.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/fulltext/StringQueryPredicate.java similarity index 83% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/fulltext/StringQueryPredicate.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/fulltext/StringQueryPredicate.java index 02364f6f8b25f..8f3407a87c9eb 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/fulltext/StringQueryPredicate.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/fulltext/StringQueryPredicate.java @@ -3,14 +3,14 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.fulltext; +package org.elasticsearch.xpack.ql.expression.predicate.fulltext; -import java.util.Map; -import java.util.List; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import java.util.List; +import java.util.Map; import static java.util.Collections.emptyList; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/logical/And.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/logical/And.java similarity index 71% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/logical/And.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/logical/And.java index 1508cfab91cf8..f173dcc4cd8b2 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/logical/And.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/logical/And.java @@ -3,13 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.logical; +package org.elasticsearch.xpack.ql.expression.predicate.logical; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.predicate.Negatable; -import org.elasticsearch.xpack.sql.expression.predicate.logical.BinaryLogicProcessor.BinaryLogicOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.predicate.Negatable; +import org.elasticsearch.xpack.ql.expression.predicate.logical.BinaryLogicProcessor.BinaryLogicOperation; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; public class And extends BinaryLogic implements Negatable { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/logical/BinaryLogic.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/logical/BinaryLogic.java similarity index 59% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/logical/BinaryLogic.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/logical/BinaryLogic.java index dfc5232cddd2d..e40994a4cb84e 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/logical/BinaryLogic.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/logical/BinaryLogic.java @@ -3,18 +3,19 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.logical; +package org.elasticsearch.xpack.ql.expression.predicate.logical; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.Nullability; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.predicate.BinaryOperator; -import org.elasticsearch.xpack.sql.expression.predicate.logical.BinaryLogicProcessor.BinaryLogicOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.Nullability; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.predicate.BinaryOperator; +import org.elasticsearch.xpack.ql.expression.predicate.logical.BinaryLogicProcessor.BinaryLogicOperation; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isBoolean; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isBoolean; public abstract class BinaryLogic extends BinaryOperator { @@ -24,7 +25,7 @@ protected BinaryLogic(Source source, Expression left, Expression right, BinaryLo @Override public DataType dataType() { - return DataType.BOOLEAN; + return DataTypes.BOOLEAN; } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/logical/BinaryLogicPipe.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/logical/BinaryLogicPipe.java similarity index 75% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/logical/BinaryLogicPipe.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/logical/BinaryLogicPipe.java index 4dd51d6adea9f..a1b0c0737e994 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/logical/BinaryLogicPipe.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/logical/BinaryLogicPipe.java @@ -3,14 +3,14 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.logical; - -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.BinaryPipe; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.predicate.logical.BinaryLogicProcessor.BinaryLogicOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +package org.elasticsearch.xpack.ql.expression.predicate.logical; + +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.BinaryPipe; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.predicate.logical.BinaryLogicProcessor.BinaryLogicOperation; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/logical/BinaryLogicProcessor.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/logical/BinaryLogicProcessor.java similarity index 79% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/logical/BinaryLogicProcessor.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/logical/BinaryLogicProcessor.java index 15f024b4f539e..3b46a0a00075b 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/logical/BinaryLogicProcessor.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/logical/BinaryLogicProcessor.java @@ -3,19 +3,19 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.logical; +package org.elasticsearch.xpack.ql.expression.predicate.logical; import org.elasticsearch.common.io.stream.StreamInput; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.gen.processor.FunctionalBinaryProcessor; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.expression.predicate.PredicateBiFunction; -import org.elasticsearch.xpack.sql.expression.predicate.logical.BinaryLogicProcessor.BinaryLogicOperation; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.expression.gen.processor.FunctionalEnumBinaryProcessor; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.predicate.PredicateBiFunction; +import org.elasticsearch.xpack.ql.expression.predicate.logical.BinaryLogicProcessor.BinaryLogicOperation; import java.io.IOException; import java.util.function.BiFunction; -public class BinaryLogicProcessor extends FunctionalBinaryProcessor { +public class BinaryLogicProcessor extends FunctionalEnumBinaryProcessor { public enum BinaryLogicOperation implements PredicateBiFunction { @@ -85,7 +85,7 @@ public String getWriteableName() { @Override protected void checkParameter(Object param) { if (param != null && !(param instanceof Boolean)) { - throw new SqlIllegalArgumentException("A boolean is required; received {}", param); + throw new QlIllegalArgumentException("A boolean is required; received {}", param); } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/logical/Not.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/logical/Not.java similarity index 64% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/logical/Not.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/logical/Not.java index 88e20d187f343..9beec2870a2b8 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/logical/Not.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/logical/Not.java @@ -3,19 +3,20 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.logical; +package org.elasticsearch.xpack.ql.expression.predicate.logical; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions.ParamOrdinal; -import org.elasticsearch.xpack.sql.expression.function.scalar.UnaryScalarFunction; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.expression.gen.script.Scripts; -import org.elasticsearch.xpack.sql.expression.predicate.Negatable; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions.ParamOrdinal; +import org.elasticsearch.xpack.ql.expression.function.scalar.UnaryScalarFunction; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.gen.script.Scripts; +import org.elasticsearch.xpack.ql.expression.predicate.Negatable; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isBoolean; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isBoolean; public class Not extends UnaryScalarFunction { @@ -35,7 +36,7 @@ protected Not replaceChild(Expression newChild) { @Override protected TypeResolution resolveType() { - if (DataType.BOOLEAN == field().dataType()) { + if (DataTypes.BOOLEAN == field().dataType()) { return TypeResolution.TYPE_RESOLVED; } return isBoolean(field(), sourceText(), ParamOrdinal.DEFAULT); @@ -67,6 +68,6 @@ protected Expression canonicalize() { @Override public DataType dataType() { - return DataType.BOOLEAN; + return DataTypes.BOOLEAN; } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/logical/NotProcessor.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/logical/NotProcessor.java similarity index 82% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/logical/NotProcessor.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/logical/NotProcessor.java index 3480854d5015e..5691df019cbc5 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/logical/NotProcessor.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/logical/NotProcessor.java @@ -3,12 +3,12 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.logical; +package org.elasticsearch.xpack.ql.expression.predicate.logical; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; import java.io.IOException; @@ -41,7 +41,7 @@ public static Boolean apply(Object input) { } if (!(input instanceof Boolean)) { - throw new SqlIllegalArgumentException("A boolean is required; received {}", input); + throw new QlIllegalArgumentException("A boolean is required; received {}", input); } return ((Boolean) input).booleanValue() ? Boolean.FALSE : Boolean.TRUE; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/logical/Or.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/logical/Or.java similarity index 71% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/logical/Or.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/logical/Or.java index 01b85bf4a9b47..071af47ea59b2 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/logical/Or.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/logical/Or.java @@ -3,13 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.logical; +package org.elasticsearch.xpack.ql.expression.predicate.logical; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.predicate.Negatable; -import org.elasticsearch.xpack.sql.expression.predicate.logical.BinaryLogicProcessor.BinaryLogicOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.predicate.Negatable; +import org.elasticsearch.xpack.ql.expression.predicate.logical.BinaryLogicProcessor.BinaryLogicOperation; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; public class Or extends BinaryLogic implements Negatable { diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/Add.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/Add.java new file mode 100644 index 0000000000000..df18990f5401e --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/Add.java @@ -0,0 +1,29 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +package org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic; + +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; + +/** + * Addition function ({@code a + b}). + */ +public class Add extends DateTimeArithmeticOperation { + public Add(Source source, Expression left, Expression right) { + super(source, left, right, DefaultBinaryArithmeticOperation.ADD); + } + + @Override + protected NodeInfo info() { + return NodeInfo.create(this, Add::new, left(), right()); + } + + @Override + protected Add replaceChildren(Expression left, Expression right) { + return new Add(source(), left, right); + } +} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/ArithmeticOperation.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/ArithmeticOperation.java similarity index 59% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/ArithmeticOperation.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/ArithmeticOperation.java index 157f34dc404a2..c2105333daf3a 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/ArithmeticOperation.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/ArithmeticOperation.java @@ -3,18 +3,17 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic; +package org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.predicate.BinaryOperator; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.BinaryArithmeticProcessor.BinaryArithmeticOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.DataTypeConversion; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.predicate.BinaryOperator; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypeConverter; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isNumeric; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isNumeric; public abstract class ArithmeticOperation extends BinaryOperator { @@ -37,7 +36,7 @@ public ArithmeticOperation swapLeftAndRight() { @Override public DataType dataType() { if (dataType == null) { - dataType = DataTypeConversion.commonType(left().dataType(), right().dataType()); + dataType = DataTypeConverter.commonType(left().dataType(), right().dataType()); } return dataType; } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/Arithmetics.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/Arithmetics.java similarity index 69% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/Arithmetics.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/Arithmetics.java index 33a4f8c0e5603..b029ce96cf218 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/Arithmetics.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/Arithmetics.java @@ -3,14 +3,11 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic; +package org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic; -import java.time.Duration; -import java.time.OffsetTime; -import java.time.Period; -import java.time.temporal.Temporal; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; -import static org.elasticsearch.xpack.sql.util.DateUtils.DAY_IN_MILLIS; +import java.util.function.BiFunction; /** * Arithmetic operation using the type widening rules of the JLS 5.6.2 namely @@ -20,12 +17,21 @@ public final class Arithmetics { private Arithmetics() {} - private enum IntervalOperation { - ADD, - SUB + public interface NumericArithmetic extends BiFunction { + default Object wrap(Object l, Object r) { + if (!(l instanceof Number)) { + throw new QlIllegalArgumentException("A number is required; received {}", l); + } + + if (!(r instanceof Number)) { + throw new QlIllegalArgumentException("A number is required; received {}", r); + } + + return apply((Number) l, (Number) r); + } } - static Number add(Number l, Number r) { + public static Number add(Number l, Number r) { if (l == null || r == null) { return null; } @@ -43,15 +49,7 @@ static Number add(Number l, Number r) { return Integer.valueOf(Math.addExact(l.intValue(), r.intValue())); } - static Temporal add(Temporal l, Period r) { - return periodArithmetics(l, r, IntervalOperation.ADD); - } - - static Temporal add(Temporal l, Duration r) { - return durationArithmetics(l, r, IntervalOperation.ADD); - } - - static Number sub(Number l, Number r) { + public static Number sub(Number l, Number r) { if (l == null || r == null) { return null; } @@ -69,15 +67,7 @@ static Number sub(Number l, Number r) { return Integer.valueOf(Math.subtractExact(l.intValue(), r.intValue())); } - static Temporal sub(Temporal l, Period r) { - return periodArithmetics(l, r, IntervalOperation.SUB); - } - - static Temporal sub(Temporal l, Duration r) { - return durationArithmetics(l, r, IntervalOperation.SUB); - } - - static Number mul(Number l, Number r) { + public static Number mul(Number l, Number r) { if (l == null || r == null) { return null; } @@ -95,7 +85,7 @@ static Number mul(Number l, Number r) { return Integer.valueOf(Math.multiplyExact(l.intValue(), r.intValue())); } - static Number div(Number l, Number r) { + public static Number div(Number l, Number r) { if (l == null || r == null) { return null; } @@ -156,36 +146,4 @@ static Number negate(Number n) { return Integer.valueOf(Math.negateExact(n.intValue())); } - - private static Temporal periodArithmetics(Temporal l, Period r, IntervalOperation operation) { - if (l == null || r == null) { - return null; - } - - if (l instanceof OffsetTime) { - return l; - } - - if (operation == IntervalOperation.ADD) { - return l.plus(r); - } else { - return l.minus(r); - } - } - - private static Temporal durationArithmetics(Temporal l, Duration r, IntervalOperation operation) { - if (l == null || r == null) { - return null; - } - - if (l instanceof OffsetTime) { - r = Duration.ofMillis(r.toMillis() % DAY_IN_MILLIS); - } - - if (operation == IntervalOperation.ADD) { - return l.plus(r); - } else { - return l.minus(r); - } - } -} +} \ No newline at end of file diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/BinaryArithmeticOperation.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/BinaryArithmeticOperation.java new file mode 100644 index 0000000000000..83d832f6d65c1 --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/BinaryArithmeticOperation.java @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic; + +import org.elasticsearch.common.io.stream.NamedWriteable; +import org.elasticsearch.xpack.ql.expression.predicate.PredicateBiFunction; + +public interface BinaryArithmeticOperation extends PredicateBiFunction, NamedWriteable { + + @Override + String symbol(); +} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/BinaryArithmeticPipe.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/BinaryArithmeticPipe.java similarity index 72% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/BinaryArithmeticPipe.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/BinaryArithmeticPipe.java index 1a5b12229ff2e..9402d1717e805 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/BinaryArithmeticPipe.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/BinaryArithmeticPipe.java @@ -3,14 +3,14 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic; +package org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.BinaryPipe; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.BinaryArithmeticProcessor.BinaryArithmeticOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.BinaryPipe; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Objects; @@ -34,7 +34,7 @@ protected BinaryPipe replaceChildren(Pipe left, Pipe right) { } @Override - public BinaryArithmeticProcessor asProcessor() { + public Processor asProcessor() { return new BinaryArithmeticProcessor(left().asProcessor(), right().asProcessor(), operation); } diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/BinaryArithmeticProcessor.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/BinaryArithmeticProcessor.java new file mode 100644 index 0000000000000..efdf4823a6e6c --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/BinaryArithmeticProcessor.java @@ -0,0 +1,47 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +package org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic; + +import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.common.io.stream.StreamOutput; +import org.elasticsearch.xpack.ql.expression.gen.processor.FunctionalBinaryProcessor; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; + +import java.io.IOException; + +public final class BinaryArithmeticProcessor extends FunctionalBinaryProcessor { + + public static final String NAME = "abn"; + + public BinaryArithmeticProcessor(Processor left, Processor right, BinaryArithmeticOperation operation) { + super(left, right, operation); + } + + public BinaryArithmeticProcessor(StreamInput in) throws IOException { + super(in, i -> i.readNamedWriteable(BinaryArithmeticOperation.class)); + } + + @Override + protected void doWrite(StreamOutput out) throws IOException { + out.writeNamedWriteable(function()); + } + + @Override + public String getWriteableName() { + return NAME; + } + + @Override + protected Object doProcess(Object left, Object right) { + BinaryArithmeticOperation f = function(); + + if (left == null || right == null) { + return null; + } + + return f.apply(left, right); + } +} \ No newline at end of file diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/DateTimeArithmeticOperation.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/DateTimeArithmeticOperation.java new file mode 100644 index 0000000000000..c430b433171a2 --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/DateTimeArithmeticOperation.java @@ -0,0 +1,38 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic; + +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; + +abstract class DateTimeArithmeticOperation extends ArithmeticOperation { + + DateTimeArithmeticOperation(Source source, Expression left, Expression right, BinaryArithmeticOperation operation) { + super(source, left, right, operation); + } + + @Override + protected TypeResolution resolveType() { + if (!childrenResolved()) { + return new TypeResolution("Unresolved children"); + } + + // arithmetic operation can work on numbers in QL + + DataType l = left().dataType(); + DataType r = right().dataType(); + + // 1. both are numbers + if (l.isNumeric() && r.isNumeric()) { + return TypeResolution.TYPE_RESOLVED; + } + + // fall-back to default checks + return super.resolveType(); + } +} diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/DefaultBinaryArithmeticOperation.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/DefaultBinaryArithmeticOperation.java new file mode 100644 index 0000000000000..11a9522954087 --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/DefaultBinaryArithmeticOperation.java @@ -0,0 +1,66 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic; + +import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.common.io.stream.StreamOutput; +import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.Arithmetics.NumericArithmetic; + +import java.io.IOException; +import java.util.function.BiFunction; + +public enum DefaultBinaryArithmeticOperation implements BinaryArithmeticOperation { + + ADD(Arithmetics::add, "+"), + SUB(Arithmetics::sub, "-"), + MUL(Arithmetics::mul, "*"), + DIV(Arithmetics::div, "/"), + MOD(Arithmetics::mod, "%"); + + public static final String NAME = "abn-def"; + + private final BiFunction process; + private final String symbol; + + DefaultBinaryArithmeticOperation(BiFunction process, String symbol) { + this.process = process; + this.symbol = symbol; + } + + DefaultBinaryArithmeticOperation(NumericArithmetic process, String symbol) { + this(process::wrap, symbol); + } + + @Override + public String symbol() { + return symbol; + } + + @Override + public final Object doApply(Object left, Object right) { + return process.apply(left, right); + } + + @Override + public String toString() { + return symbol; + } + + @Override + public String getWriteableName() { + return NAME; + } + + @Override + public void writeTo(StreamOutput out) throws IOException { + out.writeEnum(this); + } + + public static DefaultBinaryArithmeticOperation read(StreamInput in) throws IOException { + return in.readEnum(DefaultBinaryArithmeticOperation.class); + } +} diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/Div.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/Div.java new file mode 100644 index 0000000000000..bf2538eee6441 --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/Div.java @@ -0,0 +1,37 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +package org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic; + +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypeConverter; + +/** + * Division function ({@code a / b}). + */ +public class Div extends ArithmeticOperation { + + public Div(Source source, Expression left, Expression right) { + super(source, left, right, DefaultBinaryArithmeticOperation.DIV); + } + + @Override + protected NodeInfo
info() { + return NodeInfo.create(this, Div::new, left(), right()); + } + + @Override + protected Div replaceChildren(Expression newLeft, Expression newRight) { + return new Div(source(), newLeft, newRight); + } + + @Override + public DataType dataType() { + return DataTypeConverter.commonType(left().dataType(), right().dataType()); + } +} diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/Mod.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/Mod.java new file mode 100644 index 0000000000000..1fec0758fedb3 --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/Mod.java @@ -0,0 +1,33 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +package org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic; + +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; + +/** + * Modulo + * function ({@code a % b}). + * + * Note this operator is also registered as a function (needed for ODBC/SQL) purposes. + */ +public class Mod extends ArithmeticOperation { + + public Mod(Source source, Expression left, Expression right) { + super(source, left, right, DefaultBinaryArithmeticOperation.MOD); + } + + @Override + protected NodeInfo info() { + return NodeInfo.create(this, Mod::new, left(), right()); + } + + @Override + protected Mod replaceChildren(Expression newLeft, Expression newRight) { + return new Mod(source(), newLeft, newRight); + } +} diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/Mul.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/Mul.java new file mode 100644 index 0000000000000..79dd648278dc4 --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/Mul.java @@ -0,0 +1,51 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +package org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic; + +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; + +import static org.elasticsearch.common.logging.LoggerMessageFormat.format; + +/** + * Multiplication function ({@code a * b}). + */ +public class Mul extends ArithmeticOperation { + + public Mul(Source source, Expression left, Expression right) { + super(source, left, right, DefaultBinaryArithmeticOperation.MUL); + } + + @Override + protected TypeResolution resolveType() { + if (!childrenResolved()) { + return new TypeResolution("Unresolved children"); + } + + DataType l = left().dataType(); + DataType r = right().dataType(); + + // 1. both are numbers + if (DataTypes.isNullOrNumeric(l) && DataTypes.isNullOrNumeric(r)) { + return TypeResolution.TYPE_RESOLVED; + } + + return new TypeResolution(format(null, "[{}] has arguments with incompatible types [{}] and [{}]", symbol(), l, r)); + } + + @Override + protected NodeInfo info() { + return NodeInfo.create(this, Mul::new, left(), right()); + } + + @Override + protected Mul replaceChildren(Expression newLeft, Expression newRight) { + return new Mul(source(), newLeft, newRight); + } +} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/Neg.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/Neg.java similarity index 62% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/Neg.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/Neg.java index a8c7f87d6380d..dc62f62122ab2 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/Neg.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/Neg.java @@ -3,19 +3,19 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic; - -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions.ParamOrdinal; -import org.elasticsearch.xpack.sql.expression.function.scalar.UnaryScalarFunction; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.expression.gen.script.Scripts; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.UnaryArithmeticProcessor.UnaryArithmeticOperation; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; - -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isNumeric; +package org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic; + +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions.ParamOrdinal; +import org.elasticsearch.xpack.ql.expression.function.scalar.UnaryScalarFunction; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.gen.script.Scripts; +import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.UnaryArithmeticProcessor.UnaryArithmeticOperation; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; + +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isNumeric; /** * Negation function (@{code -x}). diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/Sub.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/Sub.java new file mode 100644 index 0000000000000..c5d7fc920e843 --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/Sub.java @@ -0,0 +1,30 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +package org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic; + +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; + +/** + * Subtraction function ({@code a - b}). + */ +public class Sub extends DateTimeArithmeticOperation { + + public Sub(Source source, Expression left, Expression right) { + super(source, left, right, DefaultBinaryArithmeticOperation.SUB); + } + + @Override + protected NodeInfo info() { + return NodeInfo.create(this, Sub::new, left(), right()); + } + + @Override + protected Sub replaceChildren(Expression newLeft, Expression newRight) { + return new Sub(source(), newLeft, newRight); + } +} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/UnaryArithmeticProcessor.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/UnaryArithmeticProcessor.java similarity index 85% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/UnaryArithmeticProcessor.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/UnaryArithmeticProcessor.java index e75ca47b7f453..82726328782ff 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/UnaryArithmeticProcessor.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/UnaryArithmeticProcessor.java @@ -3,12 +3,12 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic; +package org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; import java.io.IOException; import java.util.function.Function; @@ -65,7 +65,7 @@ public Object process(Object input) { if (input instanceof Number) { return operation.apply((Number) input); } - throw new SqlIllegalArgumentException("A number is required; received {}", input); + throw new QlIllegalArgumentException("A number is required; received {}", input); } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/BinaryComparison.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/BinaryComparison.java similarity index 64% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/BinaryComparison.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/BinaryComparison.java index fdd33af077b40..49288c294b238 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/BinaryComparison.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/BinaryComparison.java @@ -3,16 +3,17 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.operator.comparison; - -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.TypeResolutions; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.predicate.BinaryOperator; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.BinaryComparisonProcessor.BinaryComparisonOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +package org.elasticsearch.xpack.ql.expression.predicate.operator.comparison; + +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.TypeResolutions; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.predicate.BinaryOperator; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.BinaryComparisonProcessor.BinaryComparisonOperation; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; // marker class to indicate operations that rely on values public abstract class BinaryComparison extends BinaryOperator { @@ -33,7 +34,7 @@ protected Expression canonicalize() { @Override public DataType dataType() { - return DataType.BOOLEAN; + return DataTypes.BOOLEAN; } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/BinaryComparisonPipe.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/BinaryComparisonPipe.java similarity index 75% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/BinaryComparisonPipe.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/BinaryComparisonPipe.java index 0ffebadff9e53..43f2c4956a495 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/BinaryComparisonPipe.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/BinaryComparisonPipe.java @@ -3,14 +3,14 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.operator.comparison; - -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.BinaryPipe; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.BinaryComparisonProcessor.BinaryComparisonOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +package org.elasticsearch.xpack.ql.expression.predicate.operator.comparison; + +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.BinaryPipe; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.BinaryComparisonProcessor.BinaryComparisonOperation; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/BinaryComparisonProcessor.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/BinaryComparisonProcessor.java similarity index 79% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/BinaryComparisonProcessor.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/BinaryComparisonProcessor.java index 7064562e65fb4..ed9d430617d44 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/BinaryComparisonProcessor.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/BinaryComparisonProcessor.java @@ -3,18 +3,18 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.operator.comparison; +package org.elasticsearch.xpack.ql.expression.predicate.operator.comparison; import org.elasticsearch.common.io.stream.StreamInput; -import org.elasticsearch.xpack.sql.expression.gen.processor.FunctionalBinaryProcessor; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.expression.predicate.PredicateBiFunction; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.BinaryComparisonProcessor.BinaryComparisonOperation; +import org.elasticsearch.xpack.ql.expression.gen.processor.FunctionalEnumBinaryProcessor; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.predicate.PredicateBiFunction; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.BinaryComparisonProcessor.BinaryComparisonOperation; import java.io.IOException; import java.util.function.BiFunction; -public class BinaryComparisonProcessor extends FunctionalBinaryProcessor { +public class BinaryComparisonProcessor extends FunctionalEnumBinaryProcessor { public enum BinaryComparisonOperation implements PredicateBiFunction { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/Comparisons.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/Comparisons.java similarity index 97% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/Comparisons.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/Comparisons.java index 37d6983d927b4..4a375252c99a3 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/Comparisons.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/Comparisons.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.operator.comparison; +package org.elasticsearch.xpack.ql.expression.predicate.operator.comparison; import java.util.Set; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/Equals.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/Equals.java similarity index 69% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/Equals.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/Equals.java index a8d609ac9020d..93c7f809d3179 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/Equals.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/Equals.java @@ -3,13 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.operator.comparison; +package org.elasticsearch.xpack.ql.expression.predicate.operator.comparison; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.predicate.Negatable; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.BinaryComparisonProcessor.BinaryComparisonOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.predicate.Negatable; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.BinaryComparisonProcessor.BinaryComparisonOperation; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; public class Equals extends BinaryComparison implements Negatable { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/GreaterThan.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/GreaterThan.java similarity index 70% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/GreaterThan.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/GreaterThan.java index 9388a26fe886f..996a3eb573fbd 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/GreaterThan.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/GreaterThan.java @@ -3,13 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.operator.comparison; +package org.elasticsearch.xpack.ql.expression.predicate.operator.comparison; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.predicate.Negatable; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.BinaryComparisonProcessor.BinaryComparisonOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.predicate.Negatable; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.BinaryComparisonProcessor.BinaryComparisonOperation; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; public class GreaterThan extends BinaryComparison implements Negatable { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/GreaterThanOrEqual.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/GreaterThanOrEqual.java similarity index 71% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/GreaterThanOrEqual.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/GreaterThanOrEqual.java index 51b5e926bef7d..b43727a99cf13 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/GreaterThanOrEqual.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/GreaterThanOrEqual.java @@ -3,13 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.operator.comparison; +package org.elasticsearch.xpack.ql.expression.predicate.operator.comparison; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.predicate.Negatable; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.BinaryComparisonProcessor.BinaryComparisonOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.predicate.Negatable; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.BinaryComparisonProcessor.BinaryComparisonOperation; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; public class GreaterThanOrEqual extends BinaryComparison implements Negatable { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/LessThan.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/LessThan.java similarity index 70% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/LessThan.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/LessThan.java index d1d7b414ea5fe..bbbf712ee27dc 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/LessThan.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/LessThan.java @@ -3,13 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.operator.comparison; +package org.elasticsearch.xpack.ql.expression.predicate.operator.comparison; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.predicate.Negatable; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.BinaryComparisonProcessor.BinaryComparisonOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.predicate.Negatable; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.BinaryComparisonProcessor.BinaryComparisonOperation; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; public class LessThan extends BinaryComparison implements Negatable { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/LessThanOrEqual.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/LessThanOrEqual.java similarity index 71% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/LessThanOrEqual.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/LessThanOrEqual.java index 00f4f01937eaa..0e136a5ca4648 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/LessThanOrEqual.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/LessThanOrEqual.java @@ -3,13 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.operator.comparison; +package org.elasticsearch.xpack.ql.expression.predicate.operator.comparison; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.predicate.Negatable; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.BinaryComparisonProcessor.BinaryComparisonOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.predicate.Negatable; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.BinaryComparisonProcessor.BinaryComparisonOperation; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; public class LessThanOrEqual extends BinaryComparison implements Negatable { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/NotEquals.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/NotEquals.java similarity index 70% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/NotEquals.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/NotEquals.java index 8d88e851dce86..330549b1d47e2 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/NotEquals.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/NotEquals.java @@ -3,13 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.operator.comparison; +package org.elasticsearch.xpack.ql.expression.predicate.operator.comparison; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.predicate.Negatable; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.BinaryComparisonProcessor.BinaryComparisonOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.predicate.Negatable; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.BinaryComparisonProcessor.BinaryComparisonOperation; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; public class NotEquals extends BinaryComparison implements Negatable { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/NullEquals.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/NullEquals.java similarity index 70% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/NullEquals.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/NullEquals.java index 70479e2d704e8..51b97fc5b0362 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/NullEquals.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/NullEquals.java @@ -3,13 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.operator.comparison; +package org.elasticsearch.xpack.ql.expression.predicate.operator.comparison; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Nullability; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.BinaryComparisonProcessor.BinaryComparisonOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Nullability; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.BinaryComparisonProcessor.BinaryComparisonOperation; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; /** * Implements the MySQL {@code <=>} operator diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/regex/Like.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/regex/Like.java similarity index 71% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/regex/Like.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/regex/Like.java index e67f4943445af..dbe751276be0d 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/regex/Like.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/regex/Like.java @@ -3,13 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.regex; +package org.elasticsearch.xpack.ql.expression.predicate.regex; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.expression.predicate.regex.RegexProcessor.RegexOperation; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.predicate.regex.RegexProcessor.RegexOperation; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; public class Like extends RegexMatch { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/regex/LikePattern.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/regex/LikePattern.java similarity index 94% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/regex/LikePattern.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/regex/LikePattern.java index d07df617df9f0..fd6663b4b5ac3 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/regex/LikePattern.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/regex/LikePattern.java @@ -3,9 +3,9 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.regex; +package org.elasticsearch.xpack.ql.expression.predicate.regex; -import org.elasticsearch.xpack.sql.util.StringUtils; +import org.elasticsearch.xpack.ql.util.StringUtils; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/regex/RLike.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/regex/RLike.java similarity index 70% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/regex/RLike.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/regex/RLike.java index 187eda3fdece1..9ec70bc79d1d8 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/regex/RLike.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/regex/RLike.java @@ -3,13 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.regex; +package org.elasticsearch.xpack.ql.expression.predicate.regex; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.expression.predicate.regex.RegexProcessor.RegexOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.predicate.regex.RegexProcessor.RegexOperation; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; public class RLike extends RegexMatch { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/regex/RegexMatch.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/regex/RegexMatch.java similarity index 70% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/regex/RegexMatch.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/regex/RegexMatch.java index 82c6d570f39f5..517c243992c24 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/regex/RegexMatch.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/regex/RegexMatch.java @@ -4,18 +4,19 @@ * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.regex; +package org.elasticsearch.xpack.ql.expression.predicate.regex; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.Nullability; -import org.elasticsearch.xpack.sql.expression.function.scalar.UnaryScalarFunction; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.Nullability; +import org.elasticsearch.xpack.ql.expression.function.scalar.UnaryScalarFunction; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import java.util.Objects; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isStringAndExact; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isStringAndExact; public abstract class RegexMatch extends UnaryScalarFunction { @@ -32,7 +33,7 @@ public T pattern() { @Override public DataType dataType() { - return DataType.BOOLEAN; + return DataTypes.BOOLEAN; } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/regex/RegexProcessor.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/regex/RegexProcessor.java similarity index 94% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/regex/RegexProcessor.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/regex/RegexProcessor.java index 7f9a2ed76235a..c23219a58e248 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/regex/RegexProcessor.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/regex/RegexProcessor.java @@ -3,11 +3,11 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.regex; +package org.elasticsearch.xpack.ql.expression.predicate.regex; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; import java.io.IOException; import java.util.Objects; diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/processor/Processors.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/processor/Processors.java new file mode 100644 index 0000000000000..4cf9b004a86ae --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/processor/Processors.java @@ -0,0 +1,65 @@ +/* +* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +package org.elasticsearch.xpack.ql.expression.processor; + +import org.elasticsearch.common.io.stream.NamedWriteableRegistry; +import org.elasticsearch.common.io.stream.NamedWriteableRegistry.Entry; +import org.elasticsearch.xpack.ql.expression.gen.processor.BucketExtractorProcessor; +import org.elasticsearch.xpack.ql.expression.gen.processor.ChainingProcessor; +import org.elasticsearch.xpack.ql.expression.gen.processor.ConstantProcessor; +import org.elasticsearch.xpack.ql.expression.gen.processor.HitExtractorProcessor; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.predicate.logical.BinaryLogicProcessor; +import org.elasticsearch.xpack.ql.expression.predicate.logical.NotProcessor; +import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.BinaryArithmeticOperation; +import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.BinaryArithmeticProcessor; +import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.DefaultBinaryArithmeticOperation; +import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.UnaryArithmeticProcessor; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.BinaryComparisonProcessor; +import org.elasticsearch.xpack.ql.expression.predicate.regex.RegexProcessor; +import org.elasticsearch.xpack.ql.type.Converter; +import org.elasticsearch.xpack.ql.type.DataTypeConverter.DefaultConverter; + +import java.util.ArrayList; +import java.util.List; + +public final class Processors { + + private Processors() {} + + /** + * All of the named writeables needed to deserialize the instances of + * {@linkplain Processors}. + */ + public static List getNamedWriteables() { + List entries = new ArrayList<>(); + + // base + entries.add(new Entry(Converter.class, DefaultConverter.NAME, DefaultConverter::read)); + + entries.add(new Entry(Processor.class, ConstantProcessor.NAME, ConstantProcessor::new)); + entries.add(new Entry(Processor.class, HitExtractorProcessor.NAME, HitExtractorProcessor::new)); + entries.add(new Entry(Processor.class, BucketExtractorProcessor.NAME, BucketExtractorProcessor::new)); + entries.add(new Entry(Processor.class, ChainingProcessor.NAME, ChainingProcessor::new)); + + // logical + entries.add(new Entry(Processor.class, BinaryLogicProcessor.NAME, BinaryLogicProcessor::new)); + entries.add(new Entry(Processor.class, NotProcessor.NAME, NotProcessor::new)); + + // arithmetic + // binary arithmetics are pluggable + entries.add( + new Entry(BinaryArithmeticOperation.class, DefaultBinaryArithmeticOperation.NAME, DefaultBinaryArithmeticOperation::read)); + entries.add(new Entry(Processor.class, BinaryArithmeticProcessor.NAME, BinaryArithmeticProcessor::new)); + entries.add(new Entry(Processor.class, UnaryArithmeticProcessor.NAME, UnaryArithmeticProcessor::new)); + // comparators + entries.add(new Entry(Processor.class, BinaryComparisonProcessor.NAME, BinaryComparisonProcessor::new)); + // regex + entries.add(new Entry(Processor.class, RegexProcessor.NAME, RegexProcessor::new)); + + return entries; + } +} \ No newline at end of file diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/index/EsIndex.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/index/EsIndex.java similarity index 88% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/index/EsIndex.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/index/EsIndex.java index 790bb67c22cf6..1481199cecf99 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/index/EsIndex.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/index/EsIndex.java @@ -3,9 +3,9 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.analysis.index; +package org.elasticsearch.xpack.ql.index; -import org.elasticsearch.xpack.sql.type.EsField; +import org.elasticsearch.xpack.ql.type.EsField; import java.util.Map; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/index/IndexResolution.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/index/IndexResolution.java similarity index 97% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/index/IndexResolution.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/index/IndexResolution.java index 4e796ecd8957a..9822c9633b7e8 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/index/IndexResolution.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/index/IndexResolution.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.analysis.index; +package org.elasticsearch.xpack.ql.index; import org.elasticsearch.common.Nullable; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/index/IndexResolver.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/index/IndexResolver.java similarity index 85% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/index/IndexResolver.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/index/IndexResolver.java index c52b6a3e81479..770fef089bba5 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/index/IndexResolver.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/index/IndexResolver.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.analysis.index; +package org.elasticsearch.xpack.ql.index; import com.carrotsearch.hppc.cursors.ObjectCursor; @@ -24,16 +24,17 @@ import org.elasticsearch.common.Strings; import org.elasticsearch.index.IndexNotFoundException; import org.elasticsearch.index.IndexSettings; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.DateEsField; -import org.elasticsearch.xpack.sql.type.EsField; -import org.elasticsearch.xpack.sql.type.InvalidMappedField; -import org.elasticsearch.xpack.sql.type.KeywordEsField; -import org.elasticsearch.xpack.sql.type.TextEsField; -import org.elasticsearch.xpack.sql.type.UnsupportedEsField; -import org.elasticsearch.xpack.sql.util.CollectionUtils; -import org.elasticsearch.xpack.sql.util.Holder; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypeRegistry; +import org.elasticsearch.xpack.ql.type.DateEsField; +import org.elasticsearch.xpack.ql.type.EsField; +import org.elasticsearch.xpack.ql.type.InvalidMappedField; +import org.elasticsearch.xpack.ql.type.KeywordEsField; +import org.elasticsearch.xpack.ql.type.TextEsField; +import org.elasticsearch.xpack.ql.type.UnsupportedEsField; +import org.elasticsearch.xpack.ql.util.CollectionUtils; +import org.elasticsearch.xpack.ql.util.Holder; import java.util.ArrayList; import java.util.Arrays; @@ -59,6 +60,11 @@ import static java.util.Collections.emptyMap; import static java.util.Collections.emptySet; import static org.elasticsearch.action.ActionListener.wrap; +import static org.elasticsearch.xpack.ql.type.DataTypes.DATETIME; +import static org.elasticsearch.xpack.ql.type.DataTypes.KEYWORD; +import static org.elasticsearch.xpack.ql.type.DataTypes.OBJECT; +import static org.elasticsearch.xpack.ql.type.DataTypes.TEXT; +import static org.elasticsearch.xpack.ql.type.DataTypes.UNSUPPORTED; public class IndexResolver { @@ -154,11 +160,13 @@ public boolean equals(Object obj) { private final Client client; private final String clusterName; + private final DataTypeRegistry typeRegistry; - public IndexResolver(Client client, String clusterName) { + public IndexResolver(Client client, String clusterName, DataTypeRegistry typeRegistry) { this.client = client; this.clusterName = clusterName; + this.typeRegistry = typeRegistry; } public String clusterName() { @@ -274,17 +282,19 @@ public void resolveAsMergedMapping(String indexWildcard, String javaRegex, boole FieldCapabilitiesRequest fieldRequest = createFieldCapsRequest(indexWildcard, includeFrozen); client.fieldCaps(fieldRequest, ActionListener.wrap( - response -> listener.onResponse(mergedMappings(indexWildcard, response.getIndices(), response.get())), + response -> listener.onResponse(mergedMappings(typeRegistry, indexWildcard, response.getIndices(), response.get())), listener::onFailure)); } - static IndexResolution mergedMappings(String indexPattern, String[] indexNames, Map> fieldCaps) { + public static IndexResolution mergedMappings(DataTypeRegistry typeRegistry, String indexPattern, String[] indexNames, + Map> fieldCaps) { + if (fieldCaps == null || fieldCaps.isEmpty()) { return IndexResolution.notFound(indexPattern); } // merge all indices onto the same one - List indices = buildIndices(indexNames, null, fieldCaps, i -> indexPattern, (n, types) -> { + List indices = buildIndices(typeRegistry, indexNames, null, fieldCaps, i -> indexPattern, (n, types) -> { StringBuilder errorMessage = new StringBuilder(); boolean hasUnmapped = types.containsKey(UNMAPPED); @@ -339,7 +349,7 @@ static IndexResolution mergedMappings(String indexPattern, String[] indexNames, }); if (indices.size() > 1) { - throw new SqlIllegalArgumentException( + throw new QlIllegalArgumentException( "Incorrect merging of mappings (likely due to a bug) - expect at most one but found [{}]", indices.size()); } @@ -347,7 +357,8 @@ static IndexResolution mergedMappings(String indexPattern, String[] indexNames, return IndexResolution.valid(indices.isEmpty() ? new EsIndex(indexNames[0], emptyMap()) : indices.get(0)); } - private static EsField createField(String fieldName, Map> globalCaps, + private static EsField createField(DataTypeRegistry typeRegistry, String fieldName, + Map> globalCaps, Map hierarchicalMapping, Map flattedMapping, Function field) { @@ -369,7 +380,7 @@ private static EsField createField(String fieldName, Map createField(s, DataType.OBJECT.name(), new TreeMap<>(), false, true); + fieldFunction = s -> createField(typeRegistry, s, OBJECT.esType(), new TreeMap<>(), false, true); } else { Iterator iterator = map.values().iterator(); FieldCapabilities parentCap = iterator.next(); @@ -377,10 +388,10 @@ private static EsField createField(String fieldName, Map createField(s, parentC.getType(), new TreeMap<>(), parentC.isAggregatable(), false); + fieldFunction = s -> createField(typeRegistry, s, parentC.getType(), new TreeMap<>(), parentC.isAggregatable(), false); } - parent = createField(parentName, globalCaps, hierarchicalMapping, flattedMapping, fieldFunction); + parent = createField(typeRegistry, parentName, globalCaps, hierarchicalMapping, flattedMapping, fieldFunction); } parentProps = parent.getProperties(); } @@ -408,24 +419,27 @@ private static EsField createField(String fieldName, Map props, + private static EsField createField(DataTypeRegistry typeRegistry, String fieldName, String typeName, Map props, boolean isAggregateable, boolean isAlias) { - DataType esType = DataType.fromTypeName(typeName); - switch (esType) { - case TEXT: - return new TextEsField(fieldName, props, false, isAlias); - case KEYWORD: - int length = DataType.KEYWORD.defaultPrecision; - // TODO: to check whether isSearchable/isAggregateable takes into account the presence of the normalizer - boolean normalized = false; - return new KeywordEsField(fieldName, props, isAggregateable, length, normalized, isAlias); - case DATETIME: - return new DateEsField(fieldName, props, isAggregateable); - case UNSUPPORTED: - return new UnsupportedEsField(fieldName, typeName, null, props); - default: - return new EsField(fieldName, esType, props, isAggregateable, isAlias); + DataType esType = typeRegistry.fromEs(typeName); + + if (esType == TEXT) { + return new TextEsField(fieldName, props, false, isAlias); + } + if (esType == KEYWORD) { + int length = Short.MAX_VALUE; + // TODO: to check whether isSearchable/isAggregateable takes into account the presence of the normalizer + boolean normalized = false; + return new KeywordEsField(fieldName, props, isAggregateable, length, normalized, isAlias); } + if (esType == DATETIME) { + return new DateEsField(fieldName, props, isAggregateable); + } + if (esType == UNSUPPORTED) { + return new UnsupportedEsField(fieldName, typeName, null, props); + } + + return new EsField(fieldName, esType, props, isAggregateable, isAlias); } private static FieldCapabilitiesRequest createFieldCapsRequest(String index, boolean includeFrozen) { @@ -446,14 +460,15 @@ public void resolveAsSeparateMappings(String indexWildcard, String javaRegex, bo FieldCapabilitiesRequest fieldRequest = createFieldCapsRequest(indexWildcard, includeFrozen); client.fieldCaps(fieldRequest, ActionListener.wrap( - response -> listener.onResponse(separateMappings(indexWildcard, javaRegex, response.getIndices(), response.get())), + response -> listener.onResponse( + separateMappings(typeRegistry, indexWildcard, javaRegex, response.getIndices(), response.get())), listener::onFailure)); } - static List separateMappings(String indexPattern, String javaRegex, String[] indexNames, + public static List separateMappings(DataTypeRegistry typeRegistry, String indexPattern, String javaRegex, String[] indexNames, Map> fieldCaps) { - return buildIndices(indexNames, javaRegex, fieldCaps, Function.identity(), (s, cap) -> null); + return buildIndices(typeRegistry, indexNames, javaRegex, fieldCaps, Function.identity(), (s, cap) -> null); } private static class Fields { @@ -465,7 +480,8 @@ private static class Fields { * Assemble an index-based mapping from the field caps (which is field based) by looking at the indices associated with * each field. */ - private static List buildIndices(String[] indexNames, String javaRegex, Map> fieldCaps, + private static List buildIndices(DataTypeRegistry typeRegistry, String[] indexNames, String javaRegex, + Map> fieldCaps, Function indexNameProcessor, BiFunction, InvalidMappedField> validityVerifier) { @@ -556,9 +572,10 @@ private static List buildIndices(String[] indexNames, String javaRegex, } } - createField(fieldName, fieldCaps, indexFields.hierarchicalMapping, indexFields.flattedMapping, - s -> invalidField != null ? invalidField : createField(s, typeCap.getType(), emptyMap(), - typeCap.isAggregatable(), isAlias.get())); + createField(typeRegistry, fieldName, fieldCaps, indexFields.hierarchicalMapping, indexFields.flattedMapping, + s -> invalidField != null ? invalidField : + createField(typeRegistry, s, typeCap.getType(), emptyMap(), typeCap.isAggregatable(), + isAlias.get())); } } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/index/MappingException.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/index/MappingException.java similarity index 77% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/index/MappingException.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/index/MappingException.java index b510aa0483093..e88c86d42ed43 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/index/MappingException.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/index/MappingException.java @@ -3,12 +3,12 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.analysis.index; +package org.elasticsearch.xpack.ql.index; import org.elasticsearch.rest.RestStatus; -import org.elasticsearch.xpack.sql.ClientSqlException; +import org.elasticsearch.xpack.ql.QlClientException; -public class MappingException extends ClientSqlException { +public class MappingException extends QlClientException { public MappingException(String message, Object... args) { super(message, args); diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/QueryPlan.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/QueryPlan.java similarity index 92% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/QueryPlan.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/QueryPlan.java index 35b85da028341..3e7c5c921593e 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/QueryPlan.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/QueryPlan.java @@ -3,14 +3,14 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.plan; - -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.expression.AttributeSet; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.Node; -import org.elasticsearch.xpack.sql.type.DataType; +package org.elasticsearch.xpack.ql.plan; + +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.AttributeSet; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.Node; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; import java.util.ArrayList; import java.util.Collection; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/TableIdentifier.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/TableIdentifier.java similarity index 94% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/TableIdentifier.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/TableIdentifier.java index 9d17d766c2f96..07ffac36a2081 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/TableIdentifier.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/TableIdentifier.java @@ -3,9 +3,9 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.plan; +package org.elasticsearch.xpack.ql.plan; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/Aggregate.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/Aggregate.java similarity index 81% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/Aggregate.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/Aggregate.java index 39fef8188b27d..7d5ec59e2b30b 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/Aggregate.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/Aggregate.java @@ -3,15 +3,15 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.plan.logical; +package org.elasticsearch.xpack.ql.plan.logical; -import org.elasticsearch.xpack.sql.capabilities.Resolvables; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.NamedExpression; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.capabilities.Resolvables; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.NamedExpression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.List; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/BinaryPlan.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/BinaryPlan.java similarity index 77% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/BinaryPlan.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/BinaryPlan.java index 8763336d3c671..ba576e0fe0cb6 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/BinaryPlan.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/BinaryPlan.java @@ -3,18 +3,18 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.plan.logical; +package org.elasticsearch.xpack.ql.plan.logical; + +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Arrays; import java.util.Objects; -import org.elasticsearch.xpack.sql.tree.Source; - -abstract class BinaryPlan extends LogicalPlan { +public abstract class BinaryPlan extends LogicalPlan { private final LogicalPlan left, right; - BinaryPlan(Source source, LogicalPlan left, LogicalPlan right) { + protected BinaryPlan(Source source, LogicalPlan left, LogicalPlan right) { super(source, Arrays.asList(left, right)); this.left = left; this.right = right; @@ -39,7 +39,7 @@ public boolean equals(Object obj) { BinaryPlan other = (BinaryPlan) obj; - return Objects.equals(left(), other.left()) + return Objects.equals(left(), other.left()) && Objects.equals(right(), other.right()); } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/EsRelation.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/EsRelation.java similarity index 90% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/EsRelation.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/EsRelation.java index 01a88ef06fcec..c16c5319da5e0 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/EsRelation.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/EsRelation.java @@ -3,14 +3,14 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.plan.logical; - -import org.elasticsearch.xpack.sql.analysis.index.EsIndex; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.EsField; +package org.elasticsearch.xpack.ql.plan.logical; + +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.index.EsIndex; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.EsField; import java.util.ArrayList; import java.util.Collection; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/Filter.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/Filter.java similarity index 88% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/Filter.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/Filter.java index beeb97c563f0a..94f17bb68d460 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/Filter.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/Filter.java @@ -3,13 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.plan.logical; +package org.elasticsearch.xpack.ql.plan.logical; -import java.util.Objects; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import java.util.Objects; /** * A {@code Filter} is a type of Plan that performs filtering of results. In diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/LeafPlan.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/LeafPlan.java similarity index 86% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/LeafPlan.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/LeafPlan.java index 9612d8786e3f7..8b1ef29c8755c 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/LeafPlan.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/LeafPlan.java @@ -3,13 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.plan.logical; +package org.elasticsearch.xpack.ql.plan.logical; + +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Collections; import java.util.List; -import org.elasticsearch.xpack.sql.tree.Source; - abstract class LeafPlan extends LogicalPlan { protected LeafPlan(Source source) { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/Limit.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/Limit.java similarity index 86% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/Limit.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/Limit.java index 85735a071e7d0..4d36def488d3d 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/Limit.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/Limit.java @@ -3,13 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.plan.logical; +package org.elasticsearch.xpack.ql.plan.logical; -import java.util.Objects; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import java.util.Objects; public class Limit extends UnaryPlan { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/LogicalPlan.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/LogicalPlan.java similarity index 88% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/LogicalPlan.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/LogicalPlan.java index 79614242012f7..bc8b2216ababd 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/LogicalPlan.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/LogicalPlan.java @@ -3,12 +3,12 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.plan.logical; +package org.elasticsearch.xpack.ql.plan.logical; -import org.elasticsearch.xpack.sql.capabilities.Resolvable; -import org.elasticsearch.xpack.sql.capabilities.Resolvables; -import org.elasticsearch.xpack.sql.plan.QueryPlan; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.capabilities.Resolvable; +import org.elasticsearch.xpack.ql.capabilities.Resolvables; +import org.elasticsearch.xpack.ql.plan.QueryPlan; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.List; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/OrderBy.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/OrderBy.java similarity index 84% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/OrderBy.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/OrderBy.java index a3e3d9576b0d5..93482a2d5b7f4 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/OrderBy.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/OrderBy.java @@ -3,16 +3,16 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.plan.logical; +package org.elasticsearch.xpack.ql.plan.logical; + +import org.elasticsearch.xpack.ql.capabilities.Resolvables; +import org.elasticsearch.xpack.ql.expression.Order; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.List; import java.util.Objects; -import org.elasticsearch.xpack.sql.capabilities.Resolvables; -import org.elasticsearch.xpack.sql.expression.Order; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; - public class OrderBy extends UnaryPlan { private final List order; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/Project.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/Project.java similarity index 80% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/Project.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/Project.java index e57b2cdce4657..45bf1533cfb9b 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/Project.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/Project.java @@ -3,19 +3,19 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.plan.logical; +package org.elasticsearch.xpack.ql.plan.logical; + +import org.elasticsearch.xpack.ql.capabilities.Resolvables; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.NamedExpression; +import org.elasticsearch.xpack.ql.expression.function.Functions; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.List; import java.util.Objects; -import org.elasticsearch.xpack.sql.capabilities.Resolvables; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.NamedExpression; -import org.elasticsearch.xpack.sql.expression.function.Functions; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; - /** * A {@code Project} is a {@code Plan} with one child. In {@code SELECT x FROM y}, the "SELECT" statement is a Project. */ diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/UnaryPlan.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/UnaryPlan.java similarity index 88% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/UnaryPlan.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/UnaryPlan.java index f81a48d64fd5b..44f59a9aff6c0 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/UnaryPlan.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/UnaryPlan.java @@ -3,15 +3,15 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.plan.logical; +package org.elasticsearch.xpack.ql.plan.logical; + +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Collections; import java.util.List; import java.util.Objects; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.tree.Source; - /** * A {@code UnaryPlan} is a {@code LogicalPlan} with exactly one child, for example, {@code WHERE x} in a * SQL statement is an {@code UnaryPlan}. @@ -20,7 +20,7 @@ public abstract class UnaryPlan extends LogicalPlan { private final LogicalPlan child; - UnaryPlan(Source source, LogicalPlan child) { + protected UnaryPlan(Source source, LogicalPlan child) { super(source, Collections.singletonList(child)); this.child = child; } @@ -32,6 +32,7 @@ public final UnaryPlan replaceChildren(List newChildren) { } return replaceChild(newChildren.get(0)); } + protected abstract UnaryPlan replaceChild(LogicalPlan newChild); public LogicalPlan child() { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/UnresolvedRelation.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/UnresolvedRelation.java similarity index 89% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/UnresolvedRelation.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/UnresolvedRelation.java index 09ce8023f25ba..e0c569af21b1b 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/UnresolvedRelation.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plan/logical/UnresolvedRelation.java @@ -3,13 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.plan.logical; +package org.elasticsearch.xpack.ql.plan.logical; -import org.elasticsearch.xpack.sql.capabilities.Unresolvable; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.plan.TableIdentifier; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.capabilities.Unresolvable; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.plan.TableIdentifier; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Collections; import java.util.List; diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plugin/QlPlugin.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plugin/QlPlugin.java new file mode 100644 index 0000000000000..110e5fbffc65c --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/plugin/QlPlugin.java @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.ql.plugin; + +import org.elasticsearch.plugins.ExtensiblePlugin; +import org.elasticsearch.plugins.Plugin; + +public class QlPlugin extends Plugin implements ExtensiblePlugin { + +} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/rule/Rule.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/rule/Rule.java similarity index 90% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/rule/Rule.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/rule/Rule.java index 5bdd74fefc3df..852f00952245e 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/rule/Rule.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/rule/Rule.java @@ -3,14 +3,14 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.rule; - -import java.util.function.UnaryOperator; +package org.elasticsearch.xpack.ql.rule; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.elasticsearch.xpack.sql.tree.Node; -import org.elasticsearch.xpack.sql.util.ReflectionUtils; +import org.elasticsearch.xpack.ql.tree.Node; +import org.elasticsearch.xpack.ql.util.ReflectionUtils; + +import java.util.function.UnaryOperator; /** * Rules that apply transformation to a tree. In addition, performs diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/rule/RuleExecutionException.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/rule/RuleExecutionException.java similarity index 68% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/rule/RuleExecutionException.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/rule/RuleExecutionException.java index ab5bf8ec4ce2d..5b26a537ad026 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/rule/RuleExecutionException.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/rule/RuleExecutionException.java @@ -3,11 +3,11 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.rule; +package org.elasticsearch.xpack.ql.rule; -import org.elasticsearch.xpack.sql.ServerSqlException; +import org.elasticsearch.xpack.ql.QlServerException; -public class RuleExecutionException extends ServerSqlException { +public class RuleExecutionException extends QlServerException { public RuleExecutionException(String message, Object... args) { super(message, args); diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/rule/RuleExecutor.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/rule/RuleExecutor.java similarity index 97% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/rule/RuleExecutor.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/rule/RuleExecutor.java index 689b0b338a99e..5280aad3d78b8 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/rule/RuleExecutor.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/rule/RuleExecutor.java @@ -3,13 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.rule; +package org.elasticsearch.xpack.ql.rule; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.elasticsearch.common.unit.TimeValue; -import org.elasticsearch.xpack.sql.tree.Node; -import org.elasticsearch.xpack.sql.tree.NodeUtils; +import org.elasticsearch.xpack.ql.tree.Node; +import org.elasticsearch.xpack.ql.tree.NodeUtils; import java.util.ArrayList; import java.util.LinkedHashMap; diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/session/Configuration.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/session/Configuration.java new file mode 100644 index 0000000000000..d5d0445898625 --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/session/Configuration.java @@ -0,0 +1,41 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.ql.session; + +import java.time.ZoneId; +import java.time.ZonedDateTime; + +public class Configuration { + + private final String clusterName; + private final String username; + private final ZonedDateTime now; + private final ZoneId zoneId; + + public Configuration(ZoneId zi, String username, String clusterName) { + this.zoneId = zi.normalized(); + this.now = ZonedDateTime.now(zoneId); + this.username = username; + this.clusterName = clusterName; + } + + public ZoneId zoneId() { + return zoneId; + } + + public ZonedDateTime now() { + return now; + } + + public String clusterName() { + return clusterName; + } + + public String username() { + return username; + } +} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/tree/Location.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/tree/Location.java similarity index 96% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/tree/Location.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/tree/Location.java index 6a5543a69db70..a621a007c7fcb 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/tree/Location.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/tree/Location.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.tree; +package org.elasticsearch.xpack.ql.tree; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/tree/Node.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/tree/Node.java similarity index 98% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/tree/Node.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/tree/Node.java index 0d686fc5cf16a..1d2a65d9a4a85 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/tree/Node.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/tree/Node.java @@ -3,9 +3,9 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.tree; +package org.elasticsearch.xpack.ql.tree; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; import java.util.ArrayList; import java.util.BitSet; @@ -41,7 +41,7 @@ public abstract class Node> { public Node(Source source, List children) { this.source = (source != null ? source : Source.EMPTY); if (children.contains(null)) { - throw new SqlIllegalArgumentException("Null children are not allowed"); + throw new QlIllegalArgumentException("Null children are not allowed"); } this.children = children; } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/tree/NodeInfo.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/tree/NodeInfo.java similarity index 99% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/tree/NodeInfo.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/tree/NodeInfo.java index d23c93b31beea..191150dba87f9 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/tree/NodeInfo.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/tree/NodeInfo.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.tree; +package org.elasticsearch.xpack.ql.tree; import java.util.Arrays; import java.util.List; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/tree/NodeUtils.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/tree/NodeUtils.java similarity index 98% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/tree/NodeUtils.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/tree/NodeUtils.java index f2cb74f6abcb4..3e2b67a9e79c8 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/tree/NodeUtils.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/tree/NodeUtils.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.tree; +package org.elasticsearch.xpack.ql.tree; public abstract class NodeUtils { public static , B extends Node> String diffString(A left, B right) { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/tree/Source.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/tree/Source.java similarity index 91% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/tree/Source.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/tree/Source.java index d689a7f31dd8e..459526ddab764 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/tree/Source.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/tree/Source.java @@ -4,15 +4,13 @@ * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.tree; - -import org.elasticsearch.xpack.sql.proto.StringUtils; +package org.elasticsearch.xpack.ql.tree; import java.util.Objects; public final class Source { - public static final Source EMPTY = new Source(Location.EMPTY, StringUtils.EMPTY); + public static final Source EMPTY = new Source(Location.EMPTY, ""); private final Location location; private final String text; diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/Converter.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/Converter.java new file mode 100644 index 0000000000000..d588605410d40 --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/Converter.java @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.ql.type; + +import org.elasticsearch.common.io.stream.NamedWriteable; + +public interface Converter extends NamedWriteable { + + Object convert(Object value); +} diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/DataType.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/DataType.java new file mode 100644 index 0000000000000..aa02d4b44a2eb --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/DataType.java @@ -0,0 +1,112 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.ql.type; + +import java.util.Locale; +import java.util.Objects; + +public class DataType { + + private final String typeName; + + private final String name; + + private final String esType; + + private final int size; + + /** + * True if the type represents an integer number + */ + private final boolean isInteger; + + /** + * True if the type represents a rational number + */ + private final boolean isRational; + + /** + * True if the type supports doc values by default + */ + private final boolean docValues; + + public DataType(String esName, int size, boolean isInteger, boolean isRational, boolean hasDocValues) { + this(null, esName, size, isInteger, isRational, hasDocValues); + } + + public DataType(String typeName, String esType, int size, boolean isInteger, boolean isRational, boolean hasDocValues) { + String typeString = typeName != null ? typeName : esType; + this.typeName = typeString.toLowerCase(Locale.ROOT); + this.name = typeString.toUpperCase(Locale.ROOT); + this.esType = esType; + this.size = size; + this.isInteger = isInteger; + this.isRational = isRational; + this.docValues = hasDocValues; + } + + public String name() { + return name; + } + + public String typeName() { + return typeName; + } + + public String esType() { + return esType; + } + + public boolean isInteger() { + return isInteger; + } + + public boolean isRational() { + return isRational; + } + + public boolean isNumeric() { + return isInteger || isRational; + } + + public int size() { + return size; + } + + public boolean hasDocValues() { + return docValues; + } + + @Override + public int hashCode() { + return Objects.hash(typeName, esType, size, isInteger, isRational, docValues); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + + if (obj == null || getClass() != obj.getClass()) { + return false; + } + + DataType other = (DataType) obj; + return Objects.equals(typeName, other.typeName) + && Objects.equals(esType, other.esType) + && size == other.size + && isInteger == other.isInteger + && isRational == other.isRational + && docValues == other.docValues; + } + + @Override + public String toString() { + return name; + } +} \ No newline at end of file diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/DataTypeConverter.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/DataTypeConverter.java new file mode 100644 index 0000000000000..5400659c75ab4 --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/DataTypeConverter.java @@ -0,0 +1,519 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +package org.elasticsearch.xpack.ql.type; + +import org.elasticsearch.common.Booleans; +import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.common.io.stream.StreamOutput; +import org.elasticsearch.common.network.InetAddresses; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; + +import java.io.IOException; +import java.time.ZonedDateTime; +import java.time.format.DateTimeParseException; +import java.util.Locale; +import java.util.function.DoubleFunction; +import java.util.function.Function; +import java.util.function.LongFunction; + +import static org.elasticsearch.xpack.ql.type.DataTypes.BOOLEAN; +import static org.elasticsearch.xpack.ql.type.DataTypes.BYTE; +import static org.elasticsearch.xpack.ql.type.DataTypes.DATETIME; +import static org.elasticsearch.xpack.ql.type.DataTypes.DOUBLE; +import static org.elasticsearch.xpack.ql.type.DataTypes.FLOAT; +import static org.elasticsearch.xpack.ql.type.DataTypes.INTEGER; +import static org.elasticsearch.xpack.ql.type.DataTypes.IP; +import static org.elasticsearch.xpack.ql.type.DataTypes.KEYWORD; +import static org.elasticsearch.xpack.ql.type.DataTypes.LONG; +import static org.elasticsearch.xpack.ql.type.DataTypes.NULL; +import static org.elasticsearch.xpack.ql.type.DataTypes.SHORT; +import static org.elasticsearch.xpack.ql.type.DataTypes.TEXT; +import static org.elasticsearch.xpack.ql.type.DataTypes.isPrimitive; +import static org.elasticsearch.xpack.ql.type.DataTypes.isString; + +/** + * Conversion utility from one Elasticsearch data type to another Elasticsearch data types. + */ +public final class DataTypeConverter { + + private DataTypeConverter() {} + + /** + * Returns the type compatible with both left and right types + *

+ * If one of the types is null - returns another type + * If both types are numeric - returns type with the highest precision int < long < float < double + * If one of the types is string and another numeric - returns numeric + */ + public static DataType commonType(DataType left, DataType right) { + if (left == right) { + return left; + } + if (left == NULL) { + return right; + } + if (right == NULL) { + return left; + } + if (isString(left) && isString(right)) { + if (left == TEXT) { + return TEXT; + } + return right; + } + if (left.isNumeric() && right.isNumeric()) { + // if one is int + if (left.isInteger()) { + // promote the highest int + if (right.isInteger()) { + return left.size() > right.size() ? left : right; + } + // promote the rational + return right; + } + // try the other side + if (right.isInteger()) { + return left; + } + // promote the highest rational + return left.size() > right.size() ? left : right; + } + if (isString(left)) { + if (right.isNumeric()) { + return right; + } + } + if (isString(right)) { + if (left.isNumeric()) { + return left; + } + } + + // none found + return null; + } + + /** + * Returns true if the from type can be converted to the to type, false - otherwise + */ + public static boolean canConvert(DataType from, DataType to) { + // Special handling for nulls and if conversion is not requires + if (from == to || from == NULL) { + return true; + } + // only primitives are supported so far + return isPrimitive(from) && isPrimitive(to) && converterFor(from, to) != null; + } + + /** + * Get the conversion from one type to another. + */ + public static Converter converterFor(DataType from, DataType to) { + // Special handling for nulls and if conversion is not requires + if (from == to) { + return DefaultConverter.IDENTITY; + } + if (to == NULL || from == NULL) { + return DefaultConverter.TO_NULL; + } + // proper converters + if (to == KEYWORD || to == TEXT) { + return conversionToString(from); + } + if (to == LONG) { + return conversionToLong(from); + } + if (to == INTEGER) { + return conversionToInt(from); + } + if (to == SHORT) { + return conversionToShort(from); + } + if (to == BYTE) { + return conversionToByte(from); + } + if (to == FLOAT) { + return conversionToFloat(from); + } + if (to == DOUBLE) { + return conversionToDouble(from); + } + if (to == DATETIME) { + return conversionToDateTime(from); + } + if (to == BOOLEAN) { + return conversionToBoolean(from); + } + if (to == IP) { + return conversionToIp(from); + } + return null; + } + + private static Converter conversionToString(DataType from) { + if (from == DATETIME) { + return DefaultConverter.DATETIME_TO_STRING; + } + return DefaultConverter.OTHER_TO_STRING; + } + + private static Converter conversionToIp(DataType from) { + if (isString(from)) { + return DefaultConverter.STRING_TO_IP; + } + return null; + } + + private static Converter conversionToLong(DataType from) { + if (from.isRational()) { + return DefaultConverter.RATIONAL_TO_LONG; + } + if (from.isInteger()) { + return DefaultConverter.INTEGER_TO_LONG; + } + if (from == BOOLEAN) { + return DefaultConverter.BOOL_TO_LONG; + } + if (isString(from)) { + return DefaultConverter.STRING_TO_LONG; + } + if (from == DATETIME) { + return DefaultConverter.DATETIME_TO_LONG; + } + return null; + } + + private static Converter conversionToInt(DataType from) { + if (from.isRational()) { + return DefaultConverter.RATIONAL_TO_INT; + } + if (from.isInteger()) { + return DefaultConverter.INTEGER_TO_INT; + } + if (from == BOOLEAN) { + return DefaultConverter.BOOL_TO_INT; + } + if (isString(from)) { + return DefaultConverter.STRING_TO_INT; + } + if (from == DATETIME) { + return DefaultConverter.DATETIME_TO_INT; + } + return null; + } + + private static Converter conversionToShort(DataType from) { + if (from.isRational()) { + return DefaultConverter.RATIONAL_TO_SHORT; + } + if (from.isInteger()) { + return DefaultConverter.INTEGER_TO_SHORT; + } + if (from == BOOLEAN) { + return DefaultConverter.BOOL_TO_SHORT; + } + if (isString(from)) { + return DefaultConverter.STRING_TO_SHORT; + } + if (from == DATETIME) { + return DefaultConverter.DATETIME_TO_SHORT; + } + return null; + } + + private static Converter conversionToByte(DataType from) { + if (from.isRational()) { + return DefaultConverter.RATIONAL_TO_BYTE; + } + if (from.isInteger()) { + return DefaultConverter.INTEGER_TO_BYTE; + } + if (from == BOOLEAN) { + return DefaultConverter.BOOL_TO_BYTE; + } + if (isString(from)) { + return DefaultConverter.STRING_TO_BYTE; + } + if (from == DATETIME) { + return DefaultConverter.DATETIME_TO_BYTE; + } + return null; + } + + private static DefaultConverter conversionToFloat(DataType from) { + if (from.isRational()) { + return DefaultConverter.RATIONAL_TO_FLOAT; + } + if (from.isInteger()) { + return DefaultConverter.INTEGER_TO_FLOAT; + } + if (from == BOOLEAN) { + return DefaultConverter.BOOL_TO_FLOAT; + } + if (isString(from)) { + return DefaultConverter.STRING_TO_FLOAT; + } + if (from == DATETIME) { + return DefaultConverter.DATETIME_TO_FLOAT; + } + return null; + } + + private static DefaultConverter conversionToDouble(DataType from) { + if (from.isRational()) { + return DefaultConverter.RATIONAL_TO_DOUBLE; + } + if (from.isInteger()) { + return DefaultConverter.INTEGER_TO_DOUBLE; + } + if (from == BOOLEAN) { + return DefaultConverter.BOOL_TO_DOUBLE; + } + if (isString(from)) { + return DefaultConverter.STRING_TO_DOUBLE; + } + if (from == DATETIME) { + return DefaultConverter.DATETIME_TO_DOUBLE; + } + return null; + } + + private static DefaultConverter conversionToDateTime(DataType from) { + if (from.isRational()) { + return DefaultConverter.RATIONAL_TO_DATETIME; + } + if (from.isInteger()) { + return DefaultConverter.INTEGER_TO_DATETIME; + } + if (from == BOOLEAN) { + return DefaultConverter.BOOL_TO_DATETIME; // We emit an int here which is ok because of Java's casting rules + } + if (isString(from)) { + return DefaultConverter.STRING_TO_DATETIME; + } + return null; + } + + private static DefaultConverter conversionToBoolean(DataType from) { + if (from.isNumeric()) { + return DefaultConverter.NUMERIC_TO_BOOLEAN; + } + if (isString(from)) { + return DefaultConverter.STRING_TO_BOOLEAN; + } + if (from == DATETIME) { + return DefaultConverter.DATETIME_TO_BOOLEAN; + } + return null; + } + + public static byte safeToByte(long x) { + if (x > Byte.MAX_VALUE || x < Byte.MIN_VALUE) { + throw new QlIllegalArgumentException("[" + x + "] out of [byte] range"); + } + return (byte) x; + } + + public static short safeToShort(long x) { + if (x > Short.MAX_VALUE || x < Short.MIN_VALUE) { + throw new QlIllegalArgumentException("[" + x + "] out of [short] range"); + } + return (short) x; + } + + public static int safeToInt(long x) { + if (x > Integer.MAX_VALUE || x < Integer.MIN_VALUE) { + throw new QlIllegalArgumentException("[" + x + "] out of [integer] range"); + } + return (int) x; + } + + public static long safeToLong(double x) { + if (x > Long.MAX_VALUE || x < Long.MIN_VALUE) { + throw new QlIllegalArgumentException("[" + x + "] out of [long] range"); + } + return Math.round(x); + } + + public static Number toInteger(double x, DataType dataType) { + long l = safeToLong(x); + + if (dataType == BYTE) { + return safeToByte(l); + } + if (dataType == SHORT) { + return safeToShort(l); + } + if (dataType == INTEGER) { + return safeToInt(l); + } + return l; + } + + public static boolean convertToBoolean(String val) { + String lowVal = val.toLowerCase(Locale.ROOT); + if (Booleans.isBoolean(lowVal) == false) { + throw new QlIllegalArgumentException("cannot cast [" + val + "] to [boolean]"); + } + return Booleans.parseBoolean(lowVal); + } + + /** + * Converts arbitrary object to the desired data type. + *

+ * Throws QlIllegalArgumentException if such conversion is not possible + */ + public static Object convert(Object value, DataType dataType) { + DataType detectedType = DataTypes.fromJava(value); + if (detectedType == dataType || value == null) { + return value; + } + Converter converter = converterFor(detectedType, dataType); + + if (converter == null) { + throw new QlIllegalArgumentException("cannot convert from [{}], type [{}] to [{}]", value, detectedType.typeName(), + dataType.typeName()); + } + + return converter.convert(value); + } + + /** + * Reference to a data type conversion that can be serialized. Note that the position in the enum + * is important because it is used for serialization. + */ + public enum DefaultConverter implements Converter { + IDENTITY(Function.identity()), + TO_NULL(value -> null), + + DATETIME_TO_STRING(o -> DateUtils.toString((ZonedDateTime) o)), + OTHER_TO_STRING(String::valueOf), + + RATIONAL_TO_LONG(fromDouble(DataTypeConverter::safeToLong)), + INTEGER_TO_LONG(fromLong(value -> value)), + STRING_TO_LONG(fromString(Long::valueOf, "long")), + DATETIME_TO_LONG(fromDateTime(value -> value)), + + RATIONAL_TO_INT(fromDouble(value -> safeToInt(safeToLong(value)))), + INTEGER_TO_INT(fromLong(DataTypeConverter::safeToInt)), + BOOL_TO_INT(fromBool(value -> value ? 1 : 0)), + STRING_TO_INT(fromString(Integer::valueOf, "integer")), + DATETIME_TO_INT(fromDateTime(DataTypeConverter::safeToInt)), + + RATIONAL_TO_SHORT(fromDouble(value -> safeToShort(safeToLong(value)))), + INTEGER_TO_SHORT(fromLong(DataTypeConverter::safeToShort)), + BOOL_TO_SHORT(fromBool(value -> value ? (short) 1 : (short) 0)), + STRING_TO_SHORT(fromString(Short::valueOf, "short")), + DATETIME_TO_SHORT(fromDateTime(DataTypeConverter::safeToShort)), + + RATIONAL_TO_BYTE(fromDouble(value -> safeToByte(safeToLong(value)))), + INTEGER_TO_BYTE(fromLong(DataTypeConverter::safeToByte)), + BOOL_TO_BYTE(fromBool(value -> value ? (byte) 1 : (byte) 0)), + STRING_TO_BYTE(fromString(Byte::valueOf, "byte")), + DATETIME_TO_BYTE(fromDateTime(DataTypeConverter::safeToByte)), + + // TODO floating point conversions are lossy but conversions to integer conversions are not. Are we ok with that? + RATIONAL_TO_FLOAT(fromDouble(value -> (float) value)), + INTEGER_TO_FLOAT(fromLong(value -> (float) value)), + BOOL_TO_FLOAT(fromBool(value -> value ? 1f : 0f)), + STRING_TO_FLOAT(fromString(Float::valueOf, "float")), + DATETIME_TO_FLOAT(fromDateTime(value -> (float) value)), + + RATIONAL_TO_DOUBLE(fromDouble(Double::valueOf)), + INTEGER_TO_DOUBLE(fromLong(Double::valueOf)), + BOOL_TO_DOUBLE(fromBool(value -> value ? 1d : 0d)), + STRING_TO_DOUBLE(fromString(Double::valueOf, "double")), + DATETIME_TO_DOUBLE(fromDateTime(Double::valueOf)), + + RATIONAL_TO_DATETIME(toDateTime(RATIONAL_TO_LONG)), + INTEGER_TO_DATETIME(toDateTime(INTEGER_TO_LONG)), + BOOL_TO_DATETIME(toDateTime(BOOL_TO_INT)), + STRING_TO_DATETIME(fromString(DateUtils::asDateTime, "datetime")), + + NUMERIC_TO_BOOLEAN(fromLong(value -> value != 0)), + STRING_TO_BOOLEAN(fromString(DataTypeConverter::convertToBoolean, "boolean")), + DATETIME_TO_BOOLEAN(fromDateTime(value -> value != 0)), + + BOOL_TO_LONG(fromBool(value -> value ? 1L : 0L)), + + STRING_TO_IP(o -> { + if (!InetAddresses.isInetAddress(o.toString())) { + throw new QlIllegalArgumentException("[" + o + "] is not a valid IPv4 or IPv6 address"); + } + return o; + }); + + public static final String NAME = "dtc-def"; + + private final Function converter; + + DefaultConverter(Function converter) { + this.converter = converter; + } + + private static Function fromDouble(DoubleFunction converter) { + return (Object l) -> converter.apply(((Number) l).doubleValue()); + } + + private static Function fromLong(LongFunction converter) { + return (Object l) -> converter.apply(((Number) l).longValue()); + } + + private static Function fromString(Function converter, String to) { + return (Object value) -> { + try { + return converter.apply(value.toString()); + } catch (NumberFormatException e) { + throw new QlIllegalArgumentException(e, "cannot cast [{}] to [{}]", value, to); + } catch (DateTimeParseException | IllegalArgumentException e) { + throw new QlIllegalArgumentException(e, "cannot cast [{}] to [{}]: {}", value, to, e.getMessage()); + } + }; + } + + private static Function fromBool(Function converter) { + return (Object l) -> converter.apply(((Boolean) l)); + } + + private static Function fromDateTime(Function converter) { + return l -> converter.apply(((ZonedDateTime) l).toInstant().toEpochMilli()); + } + + private static Function toDateTime(Converter conversion) { + return l -> DateUtils.asDateTime(((Number) conversion.convert(l)).longValue()); + } + + @Override + public Object convert(Object l) { + if (l == null) { + return null; + } + return converter.apply(l); + } + + @Override + public String getWriteableName() { + return NAME; + } + + @Override + public void writeTo(StreamOutput out) throws IOException { + out.writeEnum(this); + } + + public static Converter read(StreamInput in) throws IOException { + return in.readEnum(DefaultConverter.class); + } + } + + public static DataType asInteger(DataType dataType) { + if (!dataType.isNumeric()) { + return dataType; + } + + return dataType.isInteger() ? dataType : LONG; + } +} \ No newline at end of file diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/DataTypeRegistry.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/DataTypeRegistry.java new file mode 100644 index 0000000000000..714eef3586362 --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/DataTypeRegistry.java @@ -0,0 +1,35 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.ql.type; + +import java.util.Collection; + +/** + * Central class for {@link DataType} creation and conversion. + */ +public interface DataTypeRegistry { + + // + // Discovery + // + Collection dataTypes(); + + DataType fromEs(String typeName); + + DataType fromJava(Object value); + + boolean isUnsupported(DataType type); + + // + // Conversion methods + // + boolean canConvert(DataType from, DataType to); + + Object convert(Object value, DataType type); + + DataType commonType(DataType left, DataType right); +} diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/DataTypes.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/DataTypes.java new file mode 100644 index 0000000000000..a2c2547752d44 --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/DataTypes.java @@ -0,0 +1,167 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +package org.elasticsearch.xpack.ql.type; + +import java.time.ZonedDateTime; +import java.util.Arrays; +import java.util.Collection; +import java.util.Comparator; +import java.util.Locale; +import java.util.Map; + +import static java.util.Collections.unmodifiableList; +import static java.util.Collections.unmodifiableMap; +import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toMap; + +public final class DataTypes { + + // @formatter:off + public static final DataType UNSUPPORTED = new DataType("UNSUPPORTED", null, 0, false, false, false); + + public static final DataType NULL = new DataType("null", 0, false, false, false); + + public static final DataType BOOLEAN = new DataType("boolean", 1, false, false, false); + // integer numeric + public static final DataType BYTE = new DataType("byte", Byte.BYTES, true, false, true); + public static final DataType SHORT = new DataType("short", Short.BYTES, true, false, true); + public static final DataType INTEGER = new DataType("integer", Integer.BYTES, true, false, true); + public static final DataType LONG = new DataType("long", Long.BYTES, true, false, true); + // decimal numeric + public static final DataType DOUBLE = new DataType("double", Double.BYTES, false, true, true); + public static final DataType FLOAT = new DataType("float", Float.BYTES, false, true, true); + public static final DataType HALF_FLOAT = new DataType("half_float", Float.BYTES, false, true, true); + public static final DataType SCALED_FLOAT = new DataType("scaled_float", Long.BYTES, false, true, true); + // string + public static final DataType KEYWORD = new DataType("keyword", Integer.MAX_VALUE, false, false, true); + public static final DataType TEXT = new DataType("text", Integer.MAX_VALUE, false, false, false); + // date + public static final DataType DATETIME = new DataType("DATETIME", "date", Long.BYTES, false, false, true); + // ip + public static final DataType IP = new DataType("ip", 39, false, false, true); + // binary + public static final DataType BINARY = new DataType("binary", Integer.MAX_VALUE, false, false, true); + // complex types + public static final DataType OBJECT = new DataType("object", 0, false, false, false); + public static final DataType NESTED = new DataType("nested", 0, false, false, false); + //@formatter:on + + private static final Collection TYPES = unmodifiableList(Arrays.asList( + UNSUPPORTED, + NULL, + BOOLEAN, + BYTE, + SHORT, + INTEGER, + LONG, + DOUBLE, + FLOAT, + HALF_FLOAT, + SCALED_FLOAT, + KEYWORD, + TEXT, + DATETIME, + IP, + BINARY, + OBJECT, + NESTED) + .stream() + .sorted(Comparator.comparing(DataType::typeName)) + .collect(toList())); + + private static final Map NAME_TO_TYPE = unmodifiableMap(TYPES.stream() + .collect(toMap(DataType::typeName, t -> t))); + + private static final Map ES_TO_TYPE = unmodifiableMap(TYPES.stream() + .filter(e -> e.esType() != null) + .collect(toMap(DataType::esType, t -> t))); + + private DataTypes() {} + + public static Collection types() { + return TYPES; + } + + public static DataType fromTypeName(String name) { + return NAME_TO_TYPE.get(name.toLowerCase(Locale.ROOT)); + } + + public static DataType fromEs(String name) { + DataType type = ES_TO_TYPE.get(name); + return type != null ? type : UNSUPPORTED; + } + + public static DataType fromJava(Object value) { + if (value == null) { + return NULL; + } + if (value instanceof Integer) { + return INTEGER; + } + if (value instanceof Long) { + return LONG; + } + if (value instanceof Boolean) { + return BOOLEAN; + } + if (value instanceof Double) { + return DOUBLE; + } + if (value instanceof Float) { + return FLOAT; + } + if (value instanceof Byte) { + return BYTE; + } + if (value instanceof Short) { + return SHORT; + } + if (value instanceof ZonedDateTime) { + return DATETIME; + } + if (value instanceof String || value instanceof Character) { + return KEYWORD; + } + + return null; + } + + public static boolean isUnsupported(DataType from) { + return from == UNSUPPORTED; + } + + public static boolean isString(DataType t) { + return t == KEYWORD || t == TEXT; + } + + public static boolean isPrimitive(DataType t) { + return t != OBJECT && t != NESTED && t != UNSUPPORTED; + } + + public static boolean isNull(DataType t) { + return t == NULL; + } + + public static boolean isNullOrNumeric(DataType t) { + return t.isNumeric() || isNull(t); + } + + public static boolean isSigned(DataType t) { + return t.isNumeric(); + } + + public static boolean areCompatible(DataType left, DataType right) { + if (left == right) { + return true; + } else { + return + (left == NULL || right == NULL) + || (isString(left) && isString(right)) + || (left.isNumeric() && right.isNumeric()) + || (left == DATETIME && right == DATETIME); + } + } +} \ No newline at end of file diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/DateEsField.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/DateEsField.java similarity index 81% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/DateEsField.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/DateEsField.java index fc2d10448c152..69d03c0b7bc6b 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/DateEsField.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/DateEsField.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.type; +package org.elasticsearch.xpack.ql.type; import java.util.Map; @@ -13,6 +13,6 @@ public class DateEsField extends EsField { public DateEsField(String name, Map properties, boolean hasDocValues) { - super(name, DataType.DATETIME, properties, hasDocValues); + super(name, DataTypes.DATETIME, properties, hasDocValues); } } diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/DateUtils.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/DateUtils.java new file mode 100644 index 0000000000000..f0204a9dbfb1f --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/DateUtils.java @@ -0,0 +1,42 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.ql.type; + +import org.elasticsearch.common.time.DateFormatter; +import org.elasticsearch.common.time.DateFormatters; + +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZonedDateTime; + +//NB: Taken from sql-proto. +public final class DateUtils { + + public static final ZoneId UTC = ZoneId.of("Z"); + + private static final DateFormatter UTC_DATE_TIME_FORMATTER = DateFormatter.forPattern("date_optional_time").withZone(UTC); + + private DateUtils() {} + + /** + * Creates a datetime from the millis since epoch (thus the time-zone is UTC). + */ + public static ZonedDateTime asDateTime(long millis) { + return ZonedDateTime.ofInstant(Instant.ofEpochMilli(millis), UTC); + } + + /** + * Parses the given string into a DateTime using UTC as a default timezone. + */ + public static ZonedDateTime asDateTime(String dateFormat) { + return DateFormatters.from(UTC_DATE_TIME_FORMATTER.parse(dateFormat)).withZoneSameInstant(UTC); + } + + public static String toString(ZonedDateTime dateTime) { + return StringUtils.toString(dateTime); + } +} \ No newline at end of file diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/DefaultDataTypeRegistry.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/DefaultDataTypeRegistry.java new file mode 100644 index 0000000000000..4748e7f093ba5 --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/DefaultDataTypeRegistry.java @@ -0,0 +1,51 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.ql.type; + +import java.util.Collection; + +public class DefaultDataTypeRegistry implements DataTypeRegistry { + + public static final DataTypeRegistry INSTANCE = new DefaultDataTypeRegistry(); + + private DefaultDataTypeRegistry() {} + + @Override + public Collection dataTypes() { + return DataTypes.types(); + } + + @Override + public DataType fromEs(String typeName) { + return DataTypes.fromEs(typeName); + } + + @Override + public DataType fromJava(Object value) { + return DataTypes.fromJava(value); + } + + @Override + public boolean isUnsupported(DataType type) { + return DataTypes.isUnsupported(type); + } + + @Override + public boolean canConvert(DataType from, DataType to) { + return DataTypeConverter.canConvert(from, to); + } + + @Override + public Object convert(Object value, DataType type) { + return DataTypeConverter.convert(value, type); + } + + @Override + public DataType commonType(DataType left, DataType right) { + return DataTypeConverter.commonType(left, right); + } +} \ No newline at end of file diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/EsField.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/EsField.java similarity index 86% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/EsField.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/EsField.java index b54510e48642d..8c8cd4a153a22 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/EsField.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/EsField.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.type; +package org.elasticsearch.xpack.ql.type; import org.elasticsearch.common.Nullable; @@ -80,17 +80,6 @@ public EsField getExactField() { return this; } - /** - * Returns the precision of the field - *

- * Precision is the specified column size. For numeric data, this is the maximum precision. For character - * data, this is the length in characters. For datetime datatypes, this is the length in characters of the - * String representation (assuming the maximum allowed defaultPrecision of the fractional seconds component). - */ - public int getPrecision() { - return esDataType.defaultPrecision; - } - /** * Returns and {@link Exact} object with all the necessary info about the field: *

    @@ -104,7 +93,7 @@ public Exact getExactInfo() { @Override public String toString() { - return name + "@" + esDataType.name() + "=" + properties; + return name + "@" + esDataType.typeName() + "=" + properties; } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/InvalidMappedField.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/InvalidMappedField.java similarity index 82% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/InvalidMappedField.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/InvalidMappedField.java index 79f8eb1c20c1f..c69407a25598b 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/InvalidMappedField.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/InvalidMappedField.java @@ -4,9 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.type; +package org.elasticsearch.xpack.ql.type; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; import java.util.Objects; @@ -21,7 +21,7 @@ public class InvalidMappedField extends EsField { private final String errorMessage; public InvalidMappedField(String name, String errorMessage) { - super(name, DataType.UNSUPPORTED, emptyMap(), false); + super(name, DataTypes.UNSUPPORTED, emptyMap(), false); this.errorMessage = errorMessage; } @@ -46,7 +46,7 @@ public boolean equals(Object obj) { @Override public EsField getExactField() { - throw new SqlIllegalArgumentException("Field [" + getName() + "] is invalid, cannot access it"); + throw new QlIllegalArgumentException("Field [" + getName() + "] is invalid, cannot access it"); } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/KeywordEsField.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/KeywordEsField.java similarity index 77% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/KeywordEsField.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/KeywordEsField.java index f44c5de0adb0e..78d84946da4c9 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/KeywordEsField.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/KeywordEsField.java @@ -3,12 +3,14 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.type; +package org.elasticsearch.xpack.ql.type; import java.util.Collections; import java.util.Map; import java.util.Objects; +import static org.elasticsearch.xpack.ql.type.DataTypes.KEYWORD; + /** * SQL-related information about an index field with keyword type */ @@ -18,7 +20,7 @@ public class KeywordEsField extends EsField { private final boolean normalized; public KeywordEsField(String name) { - this(name, Collections.emptyMap(), true, DataType.KEYWORD.defaultPrecision, false); + this(name, Collections.emptyMap(), true, Short.MAX_VALUE, false); } public KeywordEsField(String name, Map properties, boolean hasDocValues, int precision, boolean normalized) { @@ -27,12 +29,11 @@ public KeywordEsField(String name, Map properties, boolean hasD public KeywordEsField(String name, Map properties, boolean hasDocValues, int precision, boolean normalized, boolean isAlias) { - super(name, DataType.KEYWORD, properties, hasDocValues, isAlias); + super(name, KEYWORD, properties, hasDocValues, isAlias); this.precision = precision; this.normalized = normalized; } - @Override public int getPrecision() { return precision; } @@ -44,9 +45,15 @@ public Exact getExactInfo() { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - if (!super.equals(o)) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + if (!super.equals(o)) { + return false; + } KeywordEsField that = (KeywordEsField) o; return precision == that.precision && normalized == that.normalized; @@ -54,7 +61,6 @@ public boolean equals(Object o) { @Override public int hashCode() { - return Objects.hash(super.hashCode(), precision, normalized); } -} +} \ No newline at end of file diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/Schema.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/Schema.java similarity index 92% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/Schema.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/Schema.java index 6faf2e5b224f4..5904920706287 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/Schema.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/Schema.java @@ -3,10 +3,9 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.type; +package org.elasticsearch.xpack.ql.type; -import org.elasticsearch.xpack.sql.type.Schema.Entry; -import org.elasticsearch.xpack.sql.util.Check; +import org.elasticsearch.xpack.ql.util.Check; import java.util.Iterator; import java.util.List; @@ -18,7 +17,7 @@ import static java.util.Collections.emptyList; -public class Schema implements Iterable { +public class Schema implements Iterable { public interface Entry { String name(); @@ -120,7 +119,7 @@ public String toString() { } sb.append(names.get(i)); sb.append(":"); - sb.append(types.get(i).typeName); + sb.append(types.get(i).typeName()); } sb.append("]"); return sb.toString(); diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/StringUtils.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/StringUtils.java new file mode 100644 index 0000000000000..c92026ed5b35d --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/StringUtils.java @@ -0,0 +1,145 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.ql.type; + +import java.sql.Timestamp; +import java.time.Duration; +import java.time.OffsetTime; +import java.time.Period; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeFormatterBuilder; +import java.util.Locale; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import static java.time.format.DateTimeFormatter.ISO_LOCAL_DATE; +import static java.time.temporal.ChronoField.HOUR_OF_DAY; +import static java.time.temporal.ChronoField.MILLI_OF_SECOND; +import static java.time.temporal.ChronoField.MINUTE_OF_HOUR; +import static java.time.temporal.ChronoField.NANO_OF_SECOND; +import static java.time.temporal.ChronoField.SECOND_OF_MINUTE; + +//FIXME: this class comes from sql-proto +// find a way to share it across or potentially just copy it over +final class StringUtils { + + public static final String EMPTY = ""; + + public static final DateTimeFormatter ISO_DATE_WITH_MILLIS = new DateTimeFormatterBuilder() + .parseCaseInsensitive() + .append(ISO_LOCAL_DATE) + .appendLiteral('T') + .appendValue(HOUR_OF_DAY, 2) + .appendLiteral(':') + .appendValue(MINUTE_OF_HOUR, 2) + .appendLiteral(':') + .appendValue(SECOND_OF_MINUTE, 2) + .appendFraction(MILLI_OF_SECOND, 3, 3, true) + .appendOffsetId() + .toFormatter(Locale.ROOT); + + public static final DateTimeFormatter ISO_DATE_WITH_NANOS = new DateTimeFormatterBuilder() + .parseCaseInsensitive() + .append(ISO_LOCAL_DATE) + .appendLiteral('T') + .appendValue(HOUR_OF_DAY, 2) + .appendLiteral(':') + .appendValue(MINUTE_OF_HOUR, 2) + .appendLiteral(':') + .appendValue(SECOND_OF_MINUTE, 2) + .appendFraction(NANO_OF_SECOND, 3, 9, true) + .appendOffsetId() + .toFormatter(Locale.ROOT); + + public static final DateTimeFormatter ISO_TIME_WITH_MILLIS = new DateTimeFormatterBuilder() + .parseCaseInsensitive() + .appendValue(HOUR_OF_DAY, 2) + .appendLiteral(':') + .appendValue(MINUTE_OF_HOUR, 2) + .appendLiteral(':') + .appendValue(SECOND_OF_MINUTE, 2) + .appendFraction(MILLI_OF_SECOND, 3, 3, true) + .appendOffsetId() + .toFormatter(Locale.ROOT); + + private static final int SECONDS_PER_MINUTE = 60; + private static final int SECONDS_PER_HOUR = SECONDS_PER_MINUTE * 60; + private static final int SECONDS_PER_DAY = SECONDS_PER_HOUR * 24; + + private StringUtils() {} + + public static String toString(Object value) { + if (value == null) { + return "null"; + } + + if (value instanceof ZonedDateTime) { + return ((ZonedDateTime) value).format(ISO_DATE_WITH_MILLIS); + } + if (value instanceof OffsetTime) { + return ((OffsetTime) value).format(ISO_TIME_WITH_MILLIS); + } + if (value instanceof Timestamp) { + Timestamp ts = (Timestamp) value; + return ts.toInstant().toString(); + } + + // handle intervals + // YEAR/MONTH/YEAR TO MONTH -> YEAR TO MONTH + if (value instanceof Period) { + // +yyy-mm - 7 chars + StringBuilder sb = new StringBuilder(7); + Period p = (Period) value; + if (p.isNegative()) { + sb.append("-"); + p = p.negated(); + } else { + sb.append("+"); + } + sb.append(p.getYears()); + sb.append("-"); + sb.append(p.getMonths()); + return sb.toString(); + } + + // DAY/HOUR/MINUTE/SECOND (and variations) -> DAY_TO_SECOND + if (value instanceof Duration) { + // +ddd hh:mm:ss.mmmmmmmmm - 23 chars + StringBuilder sb = new StringBuilder(23); + Duration d = (Duration) value; + if (d.isNegative()) { + sb.append("-"); + d = d.negated(); + } else { + sb.append("+"); + } + + long durationInSec = d.getSeconds(); + + sb.append(durationInSec / SECONDS_PER_DAY); + sb.append(" "); + durationInSec = durationInSec % SECONDS_PER_DAY; + sb.append(indent(durationInSec / SECONDS_PER_HOUR)); + sb.append(":"); + durationInSec = durationInSec % SECONDS_PER_HOUR; + sb.append(indent(durationInSec / SECONDS_PER_MINUTE)); + sb.append(":"); + durationInSec = durationInSec % SECONDS_PER_MINUTE; + sb.append(indent(durationInSec)); + sb.append("."); + sb.append(TimeUnit.NANOSECONDS.toMillis(d.getNano())); + return sb.toString(); + } + + return Objects.toString(value); + } + + private static String indent(long timeUnit) { + return timeUnit < 10 ? "0" + timeUnit : Long.toString(timeUnit); + } +} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/TextEsField.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/TextEsField.java similarity index 81% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/TextEsField.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/TextEsField.java index f74757137e3c2..e3e325be23f33 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/TextEsField.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/TextEsField.java @@ -3,14 +3,17 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.type; +package org.elasticsearch.xpack.ql.type; import org.elasticsearch.common.collect.Tuple; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; import java.util.Map; import java.util.function.Function; +import static org.elasticsearch.xpack.ql.type.DataTypes.KEYWORD; +import static org.elasticsearch.xpack.ql.type.DataTypes.TEXT; + /** * SQL-related information about an index field with text type */ @@ -21,14 +24,14 @@ public TextEsField(String name, Map properties, boolean hasDocV } public TextEsField(String name, Map properties, boolean hasDocValues, boolean isAlias) { - super(name, DataType.TEXT, properties, hasDocValues, isAlias); + super(name, TEXT, properties, hasDocValues, isAlias); } @Override public EsField getExactField() { Tuple findExact = findExact(); if (findExact.v1() == null) { - throw new SqlIllegalArgumentException(findExact.v2()); + throw new QlIllegalArgumentException(findExact.v2()); } return findExact.v1(); } @@ -41,7 +44,7 @@ public Exact getExactInfo() { private Tuple findExact() { EsField field = null; for (EsField property : getProperties().values()) { - if (property.getDataType() == DataType.KEYWORD && property.getExactInfo().hasExact()) { + if (property.getDataType() == KEYWORD && property.getExactInfo().hasExact()) { if (field != null) { return new Tuple<>(null, "Multiple exact keyword candidates available for [" + getName() + "]; specify which one to use"); diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/Types.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/Types.java similarity index 58% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/Types.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/Types.java index 5a28dfdd85e27..44202b006fcf6 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/Types.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/Types.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.type; +package org.elasticsearch.xpack.ql.type; import org.elasticsearch.common.Booleans; import org.elasticsearch.common.Strings; @@ -14,88 +14,89 @@ import java.util.Map.Entry; import static java.util.Collections.emptyMap; +import static org.elasticsearch.xpack.ql.type.DataTypes.DATETIME; +import static org.elasticsearch.xpack.ql.type.DataTypes.KEYWORD; +import static org.elasticsearch.xpack.ql.type.DataTypes.NESTED; +import static org.elasticsearch.xpack.ql.type.DataTypes.OBJECT; +import static org.elasticsearch.xpack.ql.type.DataTypes.TEXT; +import static org.elasticsearch.xpack.ql.type.DataTypes.UNSUPPORTED; public abstract class Types { @SuppressWarnings("unchecked") - public static Map fromEs(Map asMap) { + public static Map fromEs(DataTypeRegistry typeRegistry, Map asMap) { Map props = null; if (asMap != null && !asMap.isEmpty()) { props = (Map) asMap.get("properties"); } - return props == null || props.isEmpty() ? emptyMap() : startWalking(props); + return props == null || props.isEmpty() ? emptyMap() : startWalking(typeRegistry, props); } - private static Map startWalking(Map mapping) { + private static Map startWalking(DataTypeRegistry typeRegistry, Map mapping) { Map types = new LinkedHashMap<>(); if (mapping == null) { return emptyMap(); } for (Entry entry : mapping.entrySet()) { - walkMapping(entry.getKey(), entry.getValue(), types); + walkMapping(typeRegistry, entry.getKey(), entry.getValue(), types); } return types; } - private static DataType getType(Map content) { + private static DataType getType(DataTypeRegistry typeRegistry, Map content) { if (content.containsKey("type")) { try { - return DataType.fromTypeName(content.get("type").toString()); + return typeRegistry.fromEs(content.get("type").toString()); } catch (IllegalArgumentException ex) { - return DataType.UNSUPPORTED; + return UNSUPPORTED; } } else if (content.containsKey("properties")) { - return DataType.OBJECT; + return OBJECT; } else { - return DataType.UNSUPPORTED; + return UNSUPPORTED; } } @SuppressWarnings("unchecked") - private static void walkMapping(String name, Object value, Map mapping) { + private static void walkMapping(DataTypeRegistry typeRegistry, String name, Object value, Map mapping) { // object type - only root or nested docs supported if (value instanceof Map) { Map content = (Map) value; // extract field type - DataType esDataType = getType(content); + DataType esDataType = getType(typeRegistry, content); final Map properties; - if (esDataType == DataType.OBJECT || esDataType == DataType.NESTED) { - properties = fromEs(content); + if (esDataType == OBJECT || esDataType == NESTED) { + properties = fromEs(typeRegistry, content); } else if (content.containsKey("fields")) { // Check for multifields Object fields = content.get("fields"); if (fields instanceof Map) { - properties = startWalking((Map) fields); + properties = startWalking(typeRegistry, (Map) fields); } else { properties = Collections.emptyMap(); } } else { - properties = fromEs(content); + properties = fromEs(typeRegistry, content); } - boolean docValues = boolSetting(content.get("doc_values"), esDataType.defaultDocValues); + boolean docValues = boolSetting(content.get("doc_values"), esDataType.hasDocValues()); final EsField field; - switch (esDataType) { - case TEXT: - field = new TextEsField(name, properties, docValues); - break; - case KEYWORD: - int length = intSetting(content.get("ignore_above"), esDataType.defaultPrecision); - boolean normalized = Strings.hasText(textSetting(content.get("normalizer"), null)); - field = new KeywordEsField(name, properties, docValues, length, normalized); - break; - case DATETIME: - field = new DateEsField(name, properties, docValues); - break; - case UNSUPPORTED: - String type = content.get("type").toString(); - field = new UnsupportedEsField(name, type, null, properties); - propagateUnsupportedType(name, type, properties); - break; - default: - field = new EsField(name, esDataType, properties, docValues); + if (esDataType == TEXT) { + field = new TextEsField(name, properties, docValues); + } else if (esDataType == KEYWORD) { + int length = intSetting(content.get("ignore_above"), Short.MAX_VALUE); + boolean normalized = Strings.hasText(textSetting(content.get("normalizer"), null)); + field = new KeywordEsField(name, properties, docValues, length, normalized); + } else if (esDataType == DATETIME) { + field = new DateEsField(name, properties, docValues); + } else if (esDataType == UNSUPPORTED) { + String type = content.get("type").toString(); + field = new UnsupportedEsField(name, type, null, properties); + propagateUnsupportedType(name, type, properties); + } else { + field = new EsField(name, esDataType, properties, docValues); } mapping.put(name, field); } else { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/UnsupportedEsField.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/UnsupportedEsField.java similarity index 94% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/UnsupportedEsField.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/UnsupportedEsField.java index b087a76131706..5a6ba946f6647 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/UnsupportedEsField.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/type/UnsupportedEsField.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.type; +package org.elasticsearch.xpack.ql.type; import java.util.Map; import java.util.Objects; @@ -23,7 +23,7 @@ public UnsupportedEsField(String name, String originalType) { } public UnsupportedEsField(String name, String originalType, String inherited, Map properties) { - super(name, DataType.UNSUPPORTED, properties, false); + super(name, DataTypes.UNSUPPORTED, properties, false); this.originalType = originalType; this.inherited = inherited; } diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/util/Check.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/util/Check.java new file mode 100644 index 0000000000000..ae50379a47aca --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/util/Check.java @@ -0,0 +1,38 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +package org.elasticsearch.xpack.ql.util; + +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; + +/** + * Utility class used for checking various conditions at runtime, with minimum amount of code. + */ +public abstract class Check { + + public static void isTrue(boolean expression, String message, Object... values) { + if (!expression) { + throw new QlIllegalArgumentException(message, values); + } + } + + public static void isTrue(boolean expression, String message) { + if (!expression) { + throw new QlIllegalArgumentException(message); + } + } + + public static void notNull(Object object, String message) { + if (object == null) { + throw new QlIllegalArgumentException(message); + } + } + + public static void notNull(Object object, String message, Object... values) { + if (object == null) { + throw new QlIllegalArgumentException(message, values); + } + } +} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/util/CollectionUtils.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/util/CollectionUtils.java similarity index 91% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/util/CollectionUtils.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/util/CollectionUtils.java index 24ed7b979f63c..19443c55a4d9e 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/util/CollectionUtils.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/util/CollectionUtils.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.util; +package org.elasticsearch.xpack.ql.util; import java.util.ArrayList; import java.util.Collection; @@ -72,4 +72,11 @@ public static List combine(Collection left, T... entries) { } return list; } + + public static int mapSize(int size) { + if (size < 2) { + return size + 1; + } + return (int) (size / 0.75f + 1f); + } } \ No newline at end of file diff --git a/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/util/DateUtils.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/util/DateUtils.java new file mode 100644 index 0000000000000..934c6c8ca9208 --- /dev/null +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/util/DateUtils.java @@ -0,0 +1,150 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.ql.util; + +import java.sql.Timestamp; +import java.time.Duration; +import java.time.OffsetTime; +import java.time.Period; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeFormatterBuilder; +import java.util.Locale; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import static java.time.format.DateTimeFormatter.ISO_LOCAL_DATE; +import static java.time.temporal.ChronoField.HOUR_OF_DAY; +import static java.time.temporal.ChronoField.MILLI_OF_SECOND; +import static java.time.temporal.ChronoField.MINUTE_OF_HOUR; +import static java.time.temporal.ChronoField.NANO_OF_SECOND; +import static java.time.temporal.ChronoField.SECOND_OF_MINUTE; + + +//FIXME: Taken from sql-proto. +//Ideally it should be shared but the dependencies across projects and and SQL-client make it tricky. +// Maybe a gradle task would fix that... +public class DateUtils { + + public static final ZoneId UTC = ZoneId.of("Z"); + + public static final String EMPTY = ""; + + public static final DateTimeFormatter ISO_DATE_WITH_MILLIS = new DateTimeFormatterBuilder() + .parseCaseInsensitive() + .append(ISO_LOCAL_DATE) + .appendLiteral('T') + .appendValue(HOUR_OF_DAY, 2) + .appendLiteral(':') + .appendValue(MINUTE_OF_HOUR, 2) + .appendLiteral(':') + .appendValue(SECOND_OF_MINUTE, 2) + .appendFraction(MILLI_OF_SECOND, 3, 3, true) + .appendOffsetId() + .toFormatter(Locale.ROOT); + + public static final DateTimeFormatter ISO_DATE_WITH_NANOS = new DateTimeFormatterBuilder() + .parseCaseInsensitive() + .append(ISO_LOCAL_DATE) + .appendLiteral('T') + .appendValue(HOUR_OF_DAY, 2) + .appendLiteral(':') + .appendValue(MINUTE_OF_HOUR, 2) + .appendLiteral(':') + .appendValue(SECOND_OF_MINUTE, 2) + .appendFraction(NANO_OF_SECOND, 3, 9, true) + .appendOffsetId() + .toFormatter(Locale.ROOT); + + public static final DateTimeFormatter ISO_TIME_WITH_MILLIS = new DateTimeFormatterBuilder() + .parseCaseInsensitive() + .appendValue(HOUR_OF_DAY, 2) + .appendLiteral(':') + .appendValue(MINUTE_OF_HOUR, 2) + .appendLiteral(':') + .appendValue(SECOND_OF_MINUTE, 2) + .appendFraction(MILLI_OF_SECOND, 3, 3, true) + .appendOffsetId() + .toFormatter(Locale.ROOT); + + private static final int SECONDS_PER_MINUTE = 60; + private static final int SECONDS_PER_HOUR = SECONDS_PER_MINUTE * 60; + private static final int SECONDS_PER_DAY = SECONDS_PER_HOUR * 24; + + private DateUtils() {} + + public static String toString(Object value) { + if (value == null) { + return "null"; + } + + if (value instanceof ZonedDateTime) { + return ((ZonedDateTime) value).format(ISO_DATE_WITH_MILLIS); + } + if (value instanceof OffsetTime) { + return ((OffsetTime) value).format(ISO_TIME_WITH_MILLIS); + } + if (value instanceof Timestamp) { + Timestamp ts = (Timestamp) value; + return ts.toInstant().toString(); + } + + // handle intervals + // YEAR/MONTH/YEAR TO MONTH -> YEAR TO MONTH + if (value instanceof Period) { + // +yyy-mm - 7 chars + StringBuilder sb = new StringBuilder(7); + Period p = (Period) value; + if (p.isNegative()) { + sb.append("-"); + p = p.negated(); + } else { + sb.append("+"); + } + sb.append(p.getYears()); + sb.append("-"); + sb.append(p.getMonths()); + return sb.toString(); + } + + // DAY/HOUR/MINUTE/SECOND (and variations) -> DAY_TO_SECOND + if (value instanceof Duration) { + // +ddd hh:mm:ss.mmmmmmmmm - 23 chars + StringBuilder sb = new StringBuilder(23); + Duration d = (Duration) value; + if (d.isNegative()) { + sb.append("-"); + d = d.negated(); + } else { + sb.append("+"); + } + + long durationInSec = d.getSeconds(); + + sb.append(durationInSec / SECONDS_PER_DAY); + sb.append(" "); + durationInSec = durationInSec % SECONDS_PER_DAY; + sb.append(indent(durationInSec / SECONDS_PER_HOUR)); + sb.append(":"); + durationInSec = durationInSec % SECONDS_PER_HOUR; + sb.append(indent(durationInSec / SECONDS_PER_MINUTE)); + sb.append(":"); + durationInSec = durationInSec % SECONDS_PER_MINUTE; + sb.append(indent(durationInSec)); + sb.append("."); + sb.append(TimeUnit.NANOSECONDS.toMillis(d.getNano())); + return sb.toString(); + } + + return Objects.toString(value); + } + + private static String indent(long timeUnit) { + return timeUnit < 10 ? "0" + timeUnit : Long.toString(timeUnit); + } +} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/util/Graphviz.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/util/Graphviz.java similarity index 99% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/util/Graphviz.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/util/Graphviz.java index ad6a97f5862c9..96e2c0767b6cd 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/util/Graphviz.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/util/Graphviz.java @@ -3,7 +3,9 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.util; +package org.elasticsearch.xpack.ql.util; + +import org.elasticsearch.xpack.ql.tree.Node; import java.util.ArrayList; import java.util.Collection; @@ -12,8 +14,6 @@ import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicInteger; -import org.elasticsearch.xpack.sql.tree.Node; - // use the awesome http://mdaines.github.io/viz.js/ to visualize and play around with the various options public abstract class Graphviz { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/util/Holder.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/util/Holder.java similarity index 93% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/util/Holder.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/util/Holder.java index 85f34f4e1ea63..121b05dfe07d2 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/util/Holder.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/util/Holder.java @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.util; +package org.elasticsearch.xpack.ql.util; /** * Simply utility class used for setting a state, typically diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/util/ReflectionUtils.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/util/ReflectionUtils.java similarity index 81% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/util/ReflectionUtils.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/util/ReflectionUtils.java index 13a859d516105..1b79d6836b03d 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/util/ReflectionUtils.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/util/ReflectionUtils.java @@ -3,9 +3,9 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.util; +package org.elasticsearch.xpack.ql.util; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; @@ -20,7 +20,7 @@ public static Class detectSuperTypeForRuleLike(Class c) { if (type instanceof ParameterizedType) { Type[] typeArguments = ((ParameterizedType) type).getActualTypeArguments(); if (typeArguments.length != 2 && typeArguments.length != 1) { - throw new SqlIllegalArgumentException("Unexpected number of type arguments {} for {}", Arrays.toString(typeArguments), + throw new QlIllegalArgumentException("Unexpected number of type arguments {} for {}", Arrays.toString(typeArguments), c); } @@ -34,11 +34,11 @@ public static Class detectSuperTypeForRuleLike(Class c) { return (Class) rawType; } } - throw new SqlIllegalArgumentException("Unexpected class structure for class {}", c); + throw new QlIllegalArgumentException("Unexpected class structure for class {}", c); } clazz = clazz.getSuperclass(); } - throw new SqlIllegalArgumentException("Unexpected class structure for class {}", c); + throw new QlIllegalArgumentException("Unexpected class structure for class {}", c); } // remove packaging from the name - strategy used for naming rules by default diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/util/StringUtils.java b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/util/StringUtils.java similarity index 89% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/util/StringUtils.java rename to x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/util/StringUtils.java index adfd3996e9fb2..9dd3debccf7a8 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/util/StringUtils.java +++ b/x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/util/StringUtils.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.util; +package org.elasticsearch.xpack.ql.util; import org.apache.lucene.search.spell.LevenshteinDistance; import org.apache.lucene.util.CollectionUtil; @@ -13,7 +13,7 @@ import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.search.builder.SearchSourceBuilder; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; import java.io.IOException; import java.math.BigInteger; @@ -104,7 +104,7 @@ public static String likeToJavaPattern(String pattern, char escape) { if (!escaped && (curr == escape) && escape != 0) { escaped = true; if (i + 1 == pattern.length()) { - throw new SqlIllegalArgumentException( + throw new QlIllegalArgumentException( "Invalid sequence - escape character is not followed by special wildcard char"); } } @@ -118,7 +118,7 @@ public static String likeToJavaPattern(String pattern, char escape) { break; default: if (escaped) { - throw new SqlIllegalArgumentException( + throw new QlIllegalArgumentException( "Invalid sequence - escape character is not followed by special wildcard char"); } // escape special regex characters @@ -168,7 +168,7 @@ public static String likeToLuceneWildcard(String pattern, char escape) { if (!escaped && (curr == escape) && escape != 0) { if (i + 1 == pattern.length()) { - throw new SqlIllegalArgumentException("Invalid sequence - escape character is not followed by special wildcard char"); + throw new QlIllegalArgumentException("Invalid sequence - escape character is not followed by special wildcard char"); } escaped = true; } else { @@ -181,7 +181,7 @@ public static String likeToLuceneWildcard(String pattern, char escape) { break; default: if (escaped) { - throw new SqlIllegalArgumentException( + throw new QlIllegalArgumentException( "Invalid sequence - escape character is not followed by special wildcard char"); } // escape special regex characters @@ -214,7 +214,7 @@ public static String likeToIndexWildcard(String pattern, char escape) { if (!escaped && (curr == escape) && escape != 0) { if (i + 1 == pattern.length()) { - throw new SqlIllegalArgumentException("Invalid sequence - escape character is not followed by special wildcard char"); + throw new QlIllegalArgumentException("Invalid sequence - escape character is not followed by special wildcard char"); } escaped = true; } else { @@ -227,7 +227,7 @@ public static String likeToIndexWildcard(String pattern, char escape) { break; default: if (escaped) { - throw new SqlIllegalArgumentException( + throw new QlIllegalArgumentException( "Invalid sequence - escape character is not followed by special wildcard char"); } // the resolver doesn't support escaping... @@ -291,24 +291,24 @@ public static List findSimilar(String match, Iterable potentialM .collect(toList()); } - public static double parseDouble(String string) throws SqlIllegalArgumentException { + public static double parseDouble(String string) throws QlIllegalArgumentException { double value; try { value = Double.parseDouble(string); } catch (NumberFormatException nfe) { - throw new SqlIllegalArgumentException("Cannot parse number [{}]", string); + throw new QlIllegalArgumentException("Cannot parse number [{}]", string); } if (Double.isInfinite(value)) { - throw new SqlIllegalArgumentException("Number [{}] is too large", string); + throw new QlIllegalArgumentException("Number [{}] is too large", string); } if (Double.isNaN(value)) { - throw new SqlIllegalArgumentException("[{}] cannot be parsed as a number (NaN)", string); + throw new QlIllegalArgumentException("[{}] cannot be parsed as a number (NaN)", string); } return value; } - public static long parseLong(String string) throws SqlIllegalArgumentException { + public static long parseLong(String string) throws QlIllegalArgumentException { try { return Long.parseLong(string); } catch (NumberFormatException nfe) { @@ -317,12 +317,12 @@ public static long parseLong(String string) throws SqlIllegalArgumentException { try { bi.longValueExact(); } catch (ArithmeticException ae) { - throw new SqlIllegalArgumentException("Number [{}] is too large", string); + throw new QlIllegalArgumentException("Number [{}] is too large", string); } } catch (NumberFormatException ex) { // parsing fails, go through } - throw new SqlIllegalArgumentException("Cannot parse number [{}]", string); + throw new QlIllegalArgumentException("Cannot parse number [{}]", string); } } diff --git a/x-pack/plugin/ql/src/main/resources/file.txt b/x-pack/plugin/ql/src/main/resources/file.txt new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/TestUtils.java b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/TestUtils.java new file mode 100644 index 0000000000000..d59cda2e3ea3e --- /dev/null +++ b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/TestUtils.java @@ -0,0 +1,48 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.ql; + +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.session.Configuration; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataTypes; + +import java.time.ZoneId; + +import static org.elasticsearch.test.ESTestCase.randomAlphaOfLength; +import static org.elasticsearch.test.ESTestCase.randomZone; + +public final class TestUtils { + + public static final ZoneId UTC = ZoneId.of("Z"); + + public static final Configuration TEST_CFG = new Configuration(UTC, null, null); + + private TestUtils() {} + + public static Configuration randomConfiguration() { + return new Configuration(randomZone(), + randomAlphaOfLength(10), + randomAlphaOfLength(10)); + } + + public static Configuration randomConfiguration(ZoneId zoneId) { + return new Configuration(zoneId, + randomAlphaOfLength(10), + randomAlphaOfLength(10)); + } + + /** + * Utility method for creating 'in-line' Literals (out of values instead of expressions). + */ + public static Literal of(Source source, Object value) { + if (value instanceof Literal) { + return (Literal) value; + } + return new Literal(source, value, DataTypes.fromJava(value)); + } +} diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/extractor/ConstantExtractorTests.java b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/execution/search/extractor/ConstantExtractorTests.java similarity index 96% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/extractor/ConstantExtractorTests.java rename to x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/execution/search/extractor/ConstantExtractorTests.java index 7c1e5258b7655..78dcc0be4a3b8 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/extractor/ConstantExtractorTests.java +++ b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/execution/search/extractor/ConstantExtractorTests.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.execution.search.extractor; +package org.elasticsearch.xpack.ql.execution.search.extractor; import org.elasticsearch.common.io.stream.Writeable.Reader; import org.elasticsearch.search.SearchHit; diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/AttributeMapTests.java b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/AttributeMapTests.java similarity index 98% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/AttributeMapTests.java rename to x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/AttributeMapTests.java index ee977687d902d..f9cb180a2224d 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/AttributeMapTests.java +++ b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/AttributeMapTests.java @@ -3,10 +3,10 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression; +package org.elasticsearch.xpack.ql.expression; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Collection; import java.util.LinkedHashMap; diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/ExpressionIdTests.java b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/ExpressionIdTests.java similarity index 93% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/ExpressionIdTests.java rename to x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/ExpressionIdTests.java index dfbe34104342b..2d9c96057e969 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/ExpressionIdTests.java +++ b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/ExpressionIdTests.java @@ -3,9 +3,10 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression; +package org.elasticsearch.xpack.ql.expression; import org.elasticsearch.test.ESTestCase; + import java.util.concurrent.atomic.AtomicLong; public class ExpressionIdTests extends ESTestCase { diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/LiteralTests.java b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/LiteralTests.java similarity index 65% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/LiteralTests.java rename to x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/LiteralTests.java index cd5e736c47c40..abc9fee4d97db 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/LiteralTests.java +++ b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/LiteralTests.java @@ -3,14 +3,15 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression; +package org.elasticsearch.xpack.ql.expression; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.tree.AbstractNodeTestCase; -import org.elasticsearch.xpack.sql.tree.SourceTests; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.DataTypeConversion; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.tree.AbstractNodeTestCase; +import org.elasticsearch.xpack.ql.tree.SourceTests; +import org.elasticsearch.xpack.ql.type.Converter; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypeConverter; import java.util.ArrayList; import java.util.Arrays; @@ -19,6 +20,14 @@ import java.util.function.Supplier; import static java.util.Collections.emptyList; +import static org.elasticsearch.xpack.ql.type.DataTypes.BOOLEAN; +import static org.elasticsearch.xpack.ql.type.DataTypes.BYTE; +import static org.elasticsearch.xpack.ql.type.DataTypes.DOUBLE; +import static org.elasticsearch.xpack.ql.type.DataTypes.FLOAT; +import static org.elasticsearch.xpack.ql.type.DataTypes.INTEGER; +import static org.elasticsearch.xpack.ql.type.DataTypes.KEYWORD; +import static org.elasticsearch.xpack.ql.type.DataTypes.LONG; +import static org.elasticsearch.xpack.ql.type.DataTypes.SHORT; public class LiteralTests extends AbstractNodeTestCase { static class ValueAndCompatibleTypes { @@ -37,21 +46,19 @@ static class ValueAndCompatibleTypes { * after a generators is its "native" type. */ private static final List GENERATORS = Arrays.asList( - new ValueAndCompatibleTypes(() -> randomBoolean() ? randomBoolean() : randomFrom("true", "false"), DataType.BOOLEAN), - new ValueAndCompatibleTypes(ESTestCase::randomByte, DataType.BYTE, DataType.SHORT, DataType.INTEGER, DataType.LONG, - DataType.FLOAT, DataType.DOUBLE, DataType.BOOLEAN), - new ValueAndCompatibleTypes(ESTestCase::randomShort, DataType.SHORT, DataType.INTEGER, DataType.LONG, - DataType.FLOAT, DataType.DOUBLE, DataType.BOOLEAN), - new ValueAndCompatibleTypes(ESTestCase::randomInt, DataType.INTEGER, DataType.LONG, - DataType.FLOAT, DataType.DOUBLE, DataType.BOOLEAN), - new ValueAndCompatibleTypes(ESTestCase::randomLong, DataType.LONG, DataType.FLOAT, DataType.DOUBLE, DataType.BOOLEAN), - new ValueAndCompatibleTypes(ESTestCase::randomFloat, DataType.FLOAT, DataType.LONG, DataType.DOUBLE, DataType.BOOLEAN), - new ValueAndCompatibleTypes(ESTestCase::randomDouble, DataType.DOUBLE, DataType.LONG, DataType.FLOAT, DataType.BOOLEAN), - new ValueAndCompatibleTypes(() -> randomAlphaOfLength(5), DataType.KEYWORD)); + new ValueAndCompatibleTypes(() -> randomBoolean() ? randomBoolean() : randomFrom("true", "false"), BOOLEAN), + new ValueAndCompatibleTypes(ESTestCase::randomByte, BYTE, SHORT, INTEGER, LONG, FLOAT, DOUBLE, BOOLEAN), + new ValueAndCompatibleTypes(ESTestCase::randomShort, SHORT, INTEGER, LONG, FLOAT, DOUBLE, BOOLEAN), + new ValueAndCompatibleTypes(ESTestCase::randomInt, INTEGER, LONG, FLOAT, DOUBLE, BOOLEAN), + new ValueAndCompatibleTypes(ESTestCase::randomLong, LONG, FLOAT, DOUBLE, BOOLEAN), + new ValueAndCompatibleTypes(ESTestCase::randomFloat, FLOAT, LONG, DOUBLE, BOOLEAN), + new ValueAndCompatibleTypes(ESTestCase::randomDouble, DOUBLE, LONG, FLOAT, BOOLEAN), + new ValueAndCompatibleTypes(() -> randomAlphaOfLength(5), KEYWORD)); public static Literal randomLiteral() { ValueAndCompatibleTypes gen = randomFrom(GENERATORS); - return new Literal(SourceTests.randomSource(), gen.valueSupplier.get(), randomFrom(gen.validDataTypes)); + DataType dataType = randomFrom(gen.validDataTypes); + return new Literal(SourceTests.randomSource(), DataTypeConverter.convert(gen.valueSupplier.get(), dataType), dataType); } @Override @@ -92,7 +99,7 @@ public void testTransform() { if (validDataTypes.size() > 1) { DataType newDataType = randomValueOtherThan(literal.dataType(), () -> randomFrom(validDataTypes)); assertEquals(new Literal(literal.source(), literal.value(), newDataType), - literal.transformPropertiesOnly(p -> newDataType, DataType.class)); + literal.transformPropertiesOnly(p -> newDataType, DataType.class)); } } @@ -105,7 +112,7 @@ public void testReplaceChildren() { private Object randomValueOfTypeOtherThan(Object original, DataType type) { for (ValueAndCompatibleTypes gen : GENERATORS) { if (gen.validDataTypes.get(0) == type) { - return randomValueOtherThan(original, () -> DataTypeConversion.convert(gen.valueSupplier.get(), type)); + return randomValueOtherThan(original, () -> DataTypeConverter.convert(gen.valueSupplier.get(), type)); } } throw new IllegalArgumentException("No native generator for [" + type + "]"); @@ -113,14 +120,14 @@ private Object randomValueOfTypeOtherThan(Object original, DataType type) { private List validReplacementDataTypes(Object value, DataType type) { List validDataTypes = new ArrayList<>(); - List options = Arrays.asList(DataType.BYTE, DataType.SHORT, DataType.INTEGER, DataType.LONG, - DataType.FLOAT, DataType.DOUBLE, DataType.BOOLEAN); + List options = Arrays.asList(BYTE, SHORT, INTEGER, LONG, + FLOAT, DOUBLE, BOOLEAN); for (DataType candidate : options) { try { - DataTypeConversion.Conversion c = DataTypeConversion.conversionFor(type, candidate); + Converter c = DataTypeConverter.converterFor(type, candidate); c.convert(value); validDataTypes.add(candidate); - } catch (SqlIllegalArgumentException e) { + } catch (QlIllegalArgumentException e) { // invalid conversion then.... } } diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/NullabilityTests.java b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/NullabilityTests.java similarity index 81% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/NullabilityTests.java rename to x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/NullabilityTests.java index 1b493de6b4c1b..28f52faa48c94 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/NullabilityTests.java +++ b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/NullabilityTests.java @@ -3,13 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression; +package org.elasticsearch.xpack.ql.expression; import org.elasticsearch.test.ESTestCase; -import static org.elasticsearch.xpack.sql.expression.Nullability.FALSE; -import static org.elasticsearch.xpack.sql.expression.Nullability.TRUE; -import static org.elasticsearch.xpack.sql.expression.Nullability.UNKNOWN; +import static org.elasticsearch.xpack.ql.expression.Nullability.FALSE; +import static org.elasticsearch.xpack.ql.expression.Nullability.TRUE; +import static org.elasticsearch.xpack.ql.expression.Nullability.UNKNOWN; public class NullabilityTests extends ESTestCase { diff --git a/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/TyperResolutionTests.java b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/TyperResolutionTests.java new file mode 100644 index 0000000000000..b438270be30f2 --- /dev/null +++ b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/TyperResolutionTests.java @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.ql.expression; + +import org.elasticsearch.test.ESTestCase; +import org.elasticsearch.xpack.ql.TestUtils; +import org.elasticsearch.xpack.ql.expression.Expression.TypeResolution; +import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.Mul; + +import static org.elasticsearch.xpack.ql.tree.Source.EMPTY; + +public class TyperResolutionTests extends ESTestCase { + + public void testMulNumeric() { + Mul m = new Mul(EMPTY, L(1), L(2)); + assertEquals(TypeResolution.TYPE_RESOLVED, m.typeResolved()); + } + + private static Literal L(Object value) { + return TestUtils.of(EMPTY, value); + } +} diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/UnresolvedAttributeTests.java b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/UnresolvedAttributeTests.java similarity index 95% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/UnresolvedAttributeTests.java rename to x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/UnresolvedAttributeTests.java index a40e7661dc03d..515e40e953db6 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/UnresolvedAttributeTests.java +++ b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/UnresolvedAttributeTests.java @@ -3,11 +3,11 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression; +package org.elasticsearch.xpack.ql.expression; -import org.elasticsearch.xpack.sql.tree.AbstractNodeTestCase; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.SourceTests; +import org.elasticsearch.xpack.ql.tree.AbstractNodeTestCase; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.tree.SourceTests; import java.util.Arrays; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/FunctionRegistryTests.java b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/function/FunctionRegistryTests.java similarity index 87% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/FunctionRegistryTests.java rename to x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/function/FunctionRegistryTests.java index 56767d7e3195e..b3d82995cb7b9 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/FunctionRegistryTests.java +++ b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/function/FunctionRegistryTests.java @@ -3,31 +3,31 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.function; +package org.elasticsearch.xpack.ql.expression.function; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.function.scalar.ScalarFunction; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.parser.ParsingException; -import org.elasticsearch.xpack.sql.session.Configuration; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.SourceTests; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.ParsingException; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.function.scalar.ScalarFunction; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.session.Configuration; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.tree.SourceTests; +import org.elasticsearch.xpack.ql.type.DataType; import java.time.ZoneId; import java.util.Arrays; import java.util.List; import static java.util.Collections.emptyList; -import static org.elasticsearch.xpack.sql.TestUtils.randomConfiguration; -import static org.elasticsearch.xpack.sql.expression.function.FunctionRegistry.def; -import static org.elasticsearch.xpack.sql.expression.function.UnresolvedFunction.ResolutionType.DISTINCT; -import static org.elasticsearch.xpack.sql.expression.function.UnresolvedFunction.ResolutionType.EXTRACT; -import static org.elasticsearch.xpack.sql.expression.function.UnresolvedFunction.ResolutionType.STANDARD; +import static org.elasticsearch.xpack.ql.TestUtils.randomConfiguration; +import static org.elasticsearch.xpack.ql.expression.function.FunctionRegistry.def; +import static org.elasticsearch.xpack.ql.expression.function.UnresolvedFunction.ResolutionType.DISTINCT; +import static org.elasticsearch.xpack.ql.expression.function.UnresolvedFunction.ResolutionType.EXTRACT; +import static org.elasticsearch.xpack.ql.expression.function.UnresolvedFunction.ResolutionType.STANDARD; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.mock; @@ -165,13 +165,13 @@ public void testBinaryFunction() { public void testAliasNameIsTheSameAsAFunctionName() { FunctionRegistry r = new FunctionRegistry(def(DummyFunction.class, DummyFunction::new, "DUMMY_FUNCTION", "ALIAS")); - SqlIllegalArgumentException iae = expectThrows(SqlIllegalArgumentException.class, () -> - r.addToMap(def(DummyFunction2.class, DummyFunction2::new, "DUMMY_FUNCTION2", "DUMMY_FUNCTION"))); + QlIllegalArgumentException iae = expectThrows(QlIllegalArgumentException.class, () -> + r.register(def(DummyFunction2.class, DummyFunction2::new, "DUMMY_FUNCTION2", "DUMMY_FUNCTION"))); assertEquals("alias [DUMMY_FUNCTION] is used by [DUMMY_FUNCTION] and [DUMMY_FUNCTION2]", iae.getMessage()); } public void testDuplicateAliasInTwoDifferentFunctionsFromTheSameBatch() { - SqlIllegalArgumentException iae = expectThrows(SqlIllegalArgumentException.class, () -> + QlIllegalArgumentException iae = expectThrows(QlIllegalArgumentException.class, () -> new FunctionRegistry(def(DummyFunction.class, DummyFunction::new, "DUMMY_FUNCTION", "ALIAS"), def(DummyFunction2.class, DummyFunction2::new, "DUMMY_FUNCTION2", "ALIAS"))); assertEquals("alias [ALIAS] is used by [DUMMY_FUNCTION(ALIAS)] and [DUMMY_FUNCTION2]", iae.getMessage()); @@ -179,8 +179,8 @@ public void testDuplicateAliasInTwoDifferentFunctionsFromTheSameBatch() { public void testDuplicateAliasInTwoDifferentFunctionsFromTwoDifferentBatches() { FunctionRegistry r = new FunctionRegistry(def(DummyFunction.class, DummyFunction::new, "DUMMY_FUNCTION", "ALIAS")); - SqlIllegalArgumentException iae = expectThrows(SqlIllegalArgumentException.class, () -> - r.addToMap(def(DummyFunction2.class, DummyFunction2::new, "DUMMY_FUNCTION2", "ALIAS"))); + QlIllegalArgumentException iae = expectThrows(QlIllegalArgumentException.class, () -> + r.register(def(DummyFunction2.class, DummyFunction2::new, "DUMMY_FUNCTION2", "ALIAS"))); assertEquals("alias [ALIAS] is used by [DUMMY_FUNCTION] and [DUMMY_FUNCTION2]", iae.getMessage()); } @@ -215,12 +215,12 @@ public void testFunctionResolving() { assertEquals(ur.source(), ur.buildResolved(randomConfiguration(), def).source()); // Not resolved - SqlIllegalArgumentException e = expectThrows(SqlIllegalArgumentException.class, + QlIllegalArgumentException e = expectThrows(QlIllegalArgumentException.class, () -> r.resolveFunction(r.resolveAlias("DummyFunction"))); assertThat(e.getMessage(), is("Cannot find function DUMMYFUNCTION; this should have been caught during analysis")); - e = expectThrows(SqlIllegalArgumentException.class, + e = expectThrows(QlIllegalArgumentException.class, () -> r.resolveFunction(r.resolveAlias("dummyFunction"))); assertThat(e.getMessage(), is("Cannot find function DUMMYFUNCTION; this should have been caught during analysis")); diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/NamedExpressionTests.java b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/function/NamedExpressionTests.java similarity index 58% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/NamedExpressionTests.java rename to x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/function/NamedExpressionTests.java index 4ac4450620626..3e1d8185e2866 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/NamedExpressionTests.java +++ b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/function/NamedExpressionTests.java @@ -3,24 +3,25 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.function; +package org.elasticsearch.xpack.ql.expression.function; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Add; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Div; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Mod; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Mul; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Neg; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Sub; -import org.elasticsearch.xpack.sql.tree.Location; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.EsField; +import org.elasticsearch.xpack.ql.TestUtils; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.Add; +import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.Div; +import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.Mod; +import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.Mul; +import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.Neg; +import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.Sub; +import org.elasticsearch.xpack.ql.tree.Location; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataTypes; +import org.elasticsearch.xpack.ql.type.EsField; import static java.util.Collections.emptyMap; -import static org.elasticsearch.xpack.sql.tree.Source.EMPTY; +import static org.elasticsearch.xpack.ql.tree.Source.EMPTY; public class NamedExpressionTests extends ESTestCase { @@ -51,7 +52,7 @@ public void testArithmeticFunctionName() { } public void testNameForArithmeticFunctionAppliedOnTableColumn() { - FieldAttribute fa = new FieldAttribute(EMPTY, "myField", new EsField("myESField", DataType.INTEGER, emptyMap(), true)); + FieldAttribute fa = new FieldAttribute(EMPTY, "myField", new EsField("myESField", DataTypes.INTEGER, emptyMap(), true)); String e = "myField + 10"; Add add = new Add(s(e), fa, l(10)); assertEquals(e, add.sourceText()); @@ -62,6 +63,6 @@ private static Source s(String text) { } private static Literal l(Object value) { - return Literal.of(EMPTY, value); + return TestUtils.of(EMPTY, value); } } diff --git a/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/function/TestFunctionRegistry.java b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/function/TestFunctionRegistry.java new file mode 100644 index 0000000000000..88d5599db8617 --- /dev/null +++ b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/function/TestFunctionRegistry.java @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.ql.expression.function; + +public class TestFunctionRegistry extends FunctionRegistry { + + public TestFunctionRegistry(FunctionDefinition... definitions) { + super(definitions); + } +} diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/UnresolvedFunctionTests.java b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/function/UnresolvedFunctionTests.java similarity index 93% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/UnresolvedFunctionTests.java rename to x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/function/UnresolvedFunctionTests.java index a165694f00d91..3331b116bb7dc 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/UnresolvedFunctionTests.java +++ b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/function/UnresolvedFunctionTests.java @@ -3,11 +3,11 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.function; +package org.elasticsearch.xpack.ql.expression.function; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.AbstractNodeTestCase; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.AbstractNodeTestCase; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Arrays; import java.util.Collections; @@ -16,8 +16,8 @@ import java.util.function.Supplier; import static java.util.Collections.singletonList; -import static org.elasticsearch.xpack.sql.expression.UnresolvedAttributeTests.randomUnresolvedAttribute; -import static org.elasticsearch.xpack.sql.tree.SourceTests.randomSource; +import static org.elasticsearch.xpack.ql.expression.UnresolvedAttributeTests.randomUnresolvedAttribute; +import static org.elasticsearch.xpack.ql.tree.SourceTests.randomSource; public class UnresolvedFunctionTests extends AbstractNodeTestCase { public static UnresolvedFunction randomUnresolvedFunction() { diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/FunctionTestUtils.java b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/function/scalar/FunctionTestUtils.java similarity index 71% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/FunctionTestUtils.java rename to x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/function/scalar/FunctionTestUtils.java index 6ddae84009446..3db832f15c4b6 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/FunctionTestUtils.java +++ b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/function/scalar/FunctionTestUtils.java @@ -4,34 +4,43 @@ * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.function.scalar; +package org.elasticsearch.xpack.ql.expression.function.scalar; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import java.time.Instant; import java.time.ZonedDateTime; import java.util.BitSet; import java.util.Iterator; -import static org.elasticsearch.xpack.sql.tree.Source.EMPTY; +import static org.elasticsearch.xpack.ql.tree.Source.EMPTY; +import static org.elasticsearch.xpack.ql.type.DataTypes.DATETIME; +import static org.elasticsearch.xpack.ql.type.DataTypes.INTEGER; +import static org.elasticsearch.xpack.ql.type.DataTypes.KEYWORD; public final class FunctionTestUtils { public static Literal l(Object value) { - return Literal.of(EMPTY, value); + return new Literal(EMPTY, value, DataTypes.fromJava(value)); + } + + public static Literal l(Object value, DataType type) { + return new Literal(EMPTY, value, type); } public static Literal randomStringLiteral() { - return l(ESTestCase.randomRealisticUnicodeOfLength(1024)); + return l(ESTestCase.randomRealisticUnicodeOfLength(1024), KEYWORD); } public static Literal randomIntLiteral() { - return l(ESTestCase.randomInt()); + return l(ESTestCase.randomInt(), INTEGER); } public static Literal randomDatetimeLiteral() { - return l(ZonedDateTime.ofInstant(Instant.ofEpochMilli(ESTestCase.randomLong()), ESTestCase.randomZone())); + return l(ZonedDateTime.ofInstant(Instant.ofEpochMilli(ESTestCase.randomLong()), ESTestCase.randomZone()), DATETIME); } public static class Combinations implements Iterable { diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/AttributeInputTests.java b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/AttributeInputTests.java similarity index 69% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/AttributeInputTests.java rename to x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/AttributeInputTests.java index 19164d388de60..c9f05f53c9d00 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/AttributeInputTests.java +++ b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/AttributeInputTests.java @@ -3,14 +3,12 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.pipeline; +package org.elasticsearch.xpack.ql.expression.gen.pipeline; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.execution.search.FieldExtraction; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.AttributeInput; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.ReferenceInput; +import org.elasticsearch.xpack.ql.execution.search.FieldExtraction; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.Expression; import static org.mockito.Mockito.mock; diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/BinaryPipesTests.java b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/BinaryPipesTests.java similarity index 85% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/BinaryPipesTests.java rename to x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/BinaryPipesTests.java index a4b8a27f13e3c..22b73c97e6b27 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/BinaryPipesTests.java +++ b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/BinaryPipesTests.java @@ -3,20 +3,21 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.pipeline; +package org.elasticsearch.xpack.ql.expression.gen.pipeline; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.execution.search.SqlSourceBuilder; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe.AttributeResolver; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.execution.search.QlSourceBuilder; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe.AttributeResolver; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.List; import static java.util.Collections.emptyList; +import static org.elasticsearch.xpack.ql.type.DataTypes.KEYWORD; public class BinaryPipesTests extends ESTestCase { public void testSupportedByAggsOnlyQuery() { @@ -58,7 +59,7 @@ public Pipe resolveAttributes(AttributeResolver resolver) { public void testCollectFields() { DummyPipe wantsScore = new DummyPipe(randomBoolean()) { @Override - public void collectFields(SqlSourceBuilder sourceBuilder) { + public void collectFields(QlSourceBuilder sourceBuilder) { sourceBuilder.trackScores(); } }; @@ -71,10 +72,10 @@ public void collectFields(SqlSourceBuilder sourceBuilder) { /** * Returns {@code true} if the processor defintion builds a query that * tracks scores, {@code false} otherwise. Used for testing - * {@link Pipe#collectFields(SqlSourceBuilder)}. + * {@link Pipe#collectFields(QlSourceBuilder)}. */ static boolean tracksScores(Pipe d) { - SqlSourceBuilder b = new SqlSourceBuilder(); + QlSourceBuilder b = new QlSourceBuilder(); d.collectFields(b); SearchSourceBuilder source = new SearchSourceBuilder(); b.build(source); @@ -86,7 +87,7 @@ public static BinaryPipe randomBinaryPipe() { } public static Pipe randomUnaryPipe() { - return new ConstantInput(Source.EMPTY, Literal.of(Source.EMPTY, randomAlphaOfLength(16)), randomAlphaOfLength(16)); + return new ConstantInput(Source.EMPTY, new Literal(Source.EMPTY, randomAlphaOfLength(16), KEYWORD), randomAlphaOfLength(16)); } public static final class DummyBinaryPipe extends BinaryPipe { @@ -157,7 +158,7 @@ public Pipe resolveAttributes(AttributeResolver resolver) { } @Override - public void collectFields(SqlSourceBuilder sourceBuilder) { + public void collectFields(QlSourceBuilder sourceBuilder) { } } } \ No newline at end of file diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/UnaryPipeTests.java b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/UnaryPipeTests.java similarity index 74% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/UnaryPipeTests.java rename to x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/UnaryPipeTests.java index 9c927aed7f4b9..97d84a8318ff8 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/UnaryPipeTests.java +++ b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/gen/pipeline/UnaryPipeTests.java @@ -3,17 +3,15 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.pipeline; +package org.elasticsearch.xpack.ql.expression.gen.pipeline; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.execution.search.SqlSourceBuilder; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.UnaryPipe; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.BinaryPipesTests.DummyPipe; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe.AttributeResolver; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.execution.search.QlSourceBuilder; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.BinaryPipesTests.DummyPipe; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe.AttributeResolver; +import org.elasticsearch.xpack.ql.tree.Source; -import static org.elasticsearch.xpack.sql.expression.gen.pipeline.BinaryPipesTests.tracksScores; +import static org.elasticsearch.xpack.ql.expression.gen.pipeline.BinaryPipesTests.tracksScores; public class UnaryPipeTests extends ESTestCase { public void testSupportedByAggsOnlyQuery() { @@ -49,7 +47,7 @@ public Pipe resolveAttributes(AttributeResolver resolver) { public void testCollectFields() { DummyPipe wantsScore = new DummyPipe(randomBoolean()) { @Override - public void collectFields(SqlSourceBuilder sourceBuilder) { + public void collectFields(QlSourceBuilder sourceBuilder) { sourceBuilder.trackScores(); } }; diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/gen/processor/ChainingProcessorTests.java b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/gen/processor/ChainingProcessorTests.java similarity index 58% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/gen/processor/ChainingProcessorTests.java rename to x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/gen/processor/ChainingProcessorTests.java index fc7c59836d275..f9d557c5f9e84 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/gen/processor/ChainingProcessorTests.java +++ b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/gen/processor/ChainingProcessorTests.java @@ -3,19 +3,22 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.processor; +package org.elasticsearch.xpack.ql.expression.gen.processor; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.Writeable.Reader; -import org.elasticsearch.xpack.sql.AbstractSqlWireSerializingTestCase; -import org.elasticsearch.xpack.sql.expression.function.scalar.Processors; +import org.elasticsearch.test.AbstractWireSerializingTestCase; +import org.elasticsearch.xpack.ql.expression.predicate.logical.BinaryLogicProcessorTests; +import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.BinaryArithmeticProcessorTests; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.BinaryComparisonProcessorTests; +import org.elasticsearch.xpack.ql.expression.processor.Processors; import java.io.IOException; +import java.util.ArrayList; +import java.util.List; import java.util.function.Supplier; -import static org.elasticsearch.xpack.sql.execution.search.extractor.ComputingExtractorTests.randomProcessor; - -public class ChainingProcessorTests extends AbstractSqlWireSerializingTestCase { +public class ChainingProcessorTests extends AbstractWireSerializingTestCase { public static ChainingProcessor randomComposeProcessor() { return new ChainingProcessor(randomProcessor(), randomProcessor()); } @@ -45,4 +48,13 @@ protected ChainingProcessor mutateInstance(ChainingProcessor instance) throws IO randomValueOtherThan(instance.first(), () -> randomProcessor()), instance.second())); return supplier.get(); } + + public static Processor randomProcessor() { + List> options = new ArrayList<>(); + options.add(ChainingProcessorTests::randomComposeProcessor); + options.add(BinaryLogicProcessorTests::randomProcessor); + options.add(BinaryArithmeticProcessorTests::randomProcessor); + options.add(BinaryComparisonProcessorTests::randomProcessor); + return randomFrom(options).get(); + } } diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/gen/processor/ConstantProcessorTests.java b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/gen/processor/ConstantProcessorTests.java similarity index 70% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/gen/processor/ConstantProcessorTests.java rename to x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/gen/processor/ConstantProcessorTests.java index 06daed00a537c..d9b5331d93e24 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/gen/processor/ConstantProcessorTests.java +++ b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/gen/processor/ConstantProcessorTests.java @@ -3,16 +3,12 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.gen.processor; +package org.elasticsearch.xpack.ql.expression.gen.processor; import org.elasticsearch.common.io.stream.Writeable.Reader; import org.elasticsearch.test.AbstractWireSerializingTestCase; -import org.elasticsearch.xpack.sql.expression.literal.IntervalDayTime; -import org.elasticsearch.xpack.sql.type.DataType; import java.io.IOException; -import java.time.Duration; -import java.util.concurrent.TimeUnit; public class ConstantProcessorTests extends AbstractWireSerializingTestCase { public static ConstantProcessor randomConstantProcessor() { @@ -31,10 +27,7 @@ protected Reader instanceReader() { @Override protected ConstantProcessor mutateInstance(ConstantProcessor instance) throws IOException { - return new ConstantProcessor(randomValueOtherThan(instance.process(null), - () -> new IntervalDayTime(Duration.ofSeconds( - randomLongBetween(TimeUnit.SECONDS.convert(3, TimeUnit.HOURS), TimeUnit.SECONDS.convert(23, TimeUnit.HOURS))), - DataType.INTERVAL_DAY_TO_SECOND))); + return new ConstantProcessor(randomValueOtherThan(instance.process(null), () -> randomLong())); } public void testApply() { diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/fulltext/FullTextUtilsTests.java b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/predicate/fulltext/FullTextUtilsTests.java similarity index 83% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/fulltext/FullTextUtilsTests.java rename to x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/predicate/fulltext/FullTextUtilsTests.java index 8341abee22fac..fdbac0bf3c81d 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/fulltext/FullTextUtilsTests.java +++ b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/predicate/fulltext/FullTextUtilsTests.java @@ -3,13 +3,11 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.fulltext; - -import io.netty.util.internal.StringUtil; +package org.elasticsearch.xpack.ql.expression.predicate.fulltext; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.parser.ParsingException; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.ParsingException; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Map; @@ -18,7 +16,7 @@ public class FullTextUtilsTests extends ESTestCase { - private final Source source = new Source(1, 1, StringUtil.EMPTY_STRING); + private final Source source = new Source(1, 1, ""); public void testColonDelimited() { Map options = FullTextUtils.parseSettings("k1=v1;k2=v2", source); diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/logical/BinaryLogicProcessorTests.java b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/predicate/logical/BinaryLogicProcessorTests.java similarity index 93% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/logical/BinaryLogicProcessorTests.java rename to x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/predicate/logical/BinaryLogicProcessorTests.java index ec29e912a2c90..6cfda143982d6 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/logical/BinaryLogicProcessorTests.java +++ b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/predicate/logical/BinaryLogicProcessorTests.java @@ -3,14 +3,14 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.logical; +package org.elasticsearch.xpack.ql.expression.predicate.logical; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.Writeable.Reader; import org.elasticsearch.test.AbstractWireSerializingTestCase; -import org.elasticsearch.xpack.sql.expression.function.scalar.Processors; -import org.elasticsearch.xpack.sql.expression.gen.processor.ConstantProcessor; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.gen.processor.ConstantProcessor; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.processor.Processors; public class BinaryLogicProcessorTests extends AbstractWireSerializingTestCase { diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/BinaryArithmeticProcessorTests.java b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/BinaryArithmeticProcessorTests.java similarity index 73% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/BinaryArithmeticProcessorTests.java rename to x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/BinaryArithmeticProcessorTests.java index 03e1774c1fc52..dc5dbdbca9d77 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/BinaryArithmeticProcessorTests.java +++ b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/predicate/operator/arithmetic/BinaryArithmeticProcessorTests.java @@ -3,32 +3,26 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic; +package org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.Writeable.Reader; import org.elasticsearch.test.AbstractWireSerializingTestCase; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.expression.function.scalar.Processors; -import org.elasticsearch.xpack.sql.expression.gen.processor.ConstantProcessor; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Add; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.BinaryArithmeticProcessor; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Div; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Mod; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Mul; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Neg; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Sub; +import org.elasticsearch.xpack.ql.TestUtils; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.gen.processor.ConstantProcessor; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.processor.Processors; -import static org.elasticsearch.xpack.sql.tree.Source.EMPTY; +import static org.elasticsearch.xpack.ql.tree.Source.EMPTY; public class BinaryArithmeticProcessorTests extends AbstractWireSerializingTestCase { public static BinaryArithmeticProcessor randomProcessor() { return new BinaryArithmeticProcessor( new ConstantProcessor(randomLong()), new ConstantProcessor(randomLong()), - randomFrom(BinaryArithmeticProcessor.BinaryArithmeticOperation.values())); + randomFrom(DefaultBinaryArithmeticOperation.values())); } @Override @@ -100,6 +94,6 @@ public void testHandleNull() { } private static Literal l(Object value) { - return Literal.of(EMPTY, value); + return TestUtils.of(EMPTY, value); } } \ No newline at end of file diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/BinaryComparisonProcessorTests.java b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/BinaryComparisonProcessorTests.java similarity index 89% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/BinaryComparisonProcessorTests.java rename to x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/BinaryComparisonProcessorTests.java index d082fbd371f79..9e2bdbb9afc1c 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/BinaryComparisonProcessorTests.java +++ b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/expression/predicate/operator/comparison/BinaryComparisonProcessorTests.java @@ -3,17 +3,18 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.predicate.operator.comparison; +package org.elasticsearch.xpack.ql.expression.predicate.operator.comparison; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.Writeable.Reader; import org.elasticsearch.test.AbstractWireSerializingTestCase; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.expression.function.scalar.Processors; -import org.elasticsearch.xpack.sql.expression.gen.processor.ConstantProcessor; +import org.elasticsearch.xpack.ql.TestUtils; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.gen.processor.ConstantProcessor; +import org.elasticsearch.xpack.ql.expression.processor.Processors; -import static org.elasticsearch.xpack.sql.expression.Literal.NULL; -import static org.elasticsearch.xpack.sql.tree.Source.EMPTY; +import static org.elasticsearch.xpack.ql.expression.Literal.NULL; +import static org.elasticsearch.xpack.ql.tree.Source.EMPTY; public class BinaryComparisonProcessorTests extends AbstractWireSerializingTestCase { public static BinaryComparisonProcessor randomProcessor() { @@ -90,6 +91,6 @@ public void testHandleNull() { } private static Literal l(Object value) { - return Literal.of(EMPTY, value); + return TestUtils.of(EMPTY, value); } } diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/tree/AbstractNodeTestCase.java b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/tree/AbstractNodeTestCase.java similarity index 97% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/tree/AbstractNodeTestCase.java rename to x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/tree/AbstractNodeTestCase.java index b5b0adfb0e6a9..7fa9264091c13 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/tree/AbstractNodeTestCase.java +++ b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/tree/AbstractNodeTestCase.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.tree; +package org.elasticsearch.xpack.ql.tree; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.EqualsHashCodeTestUtils; diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/tree/NodeSubclassTests.java b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/tree/NodeSubclassTests.java similarity index 78% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/tree/NodeSubclassTests.java rename to x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/tree/NodeSubclassTests.java index d3a4870c24857..64c39eeacb8b3 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/tree/NodeSubclassTests.java +++ b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/tree/NodeSubclassTests.java @@ -3,42 +3,32 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.tree; +package org.elasticsearch.xpack.ql.tree; import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; + import org.elasticsearch.common.Strings; +import org.elasticsearch.common.SuppressForbidden; import org.elasticsearch.common.io.PathUtils; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.expression.LiteralTests; -import org.elasticsearch.xpack.sql.expression.UnresolvedAttributeTests; -import org.elasticsearch.xpack.sql.expression.function.Function; -import org.elasticsearch.xpack.sql.expression.function.aggregate.AggregateFunction; -import org.elasticsearch.xpack.sql.expression.function.aggregate.Avg; -import org.elasticsearch.xpack.sql.expression.function.aggregate.InnerAggregate; -import org.elasticsearch.xpack.sql.expression.function.aggregate.Percentile; -import org.elasticsearch.xpack.sql.expression.function.aggregate.PercentileRanks; -import org.elasticsearch.xpack.sql.expression.function.aggregate.Percentiles; -import org.elasticsearch.xpack.sql.expression.function.grouping.Histogram; -import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.CurrentDateTime; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.AggExtractorInput; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.BinaryPipesTests; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.processor.ConstantProcessor; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.expression.predicate.conditional.IfConditional; -import org.elasticsearch.xpack.sql.expression.predicate.conditional.IfNull; -import org.elasticsearch.xpack.sql.expression.predicate.conditional.Iif; -import org.elasticsearch.xpack.sql.expression.predicate.fulltext.FullTextPredicate; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.In; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.InPipe; -import org.elasticsearch.xpack.sql.expression.predicate.regex.Like; -import org.elasticsearch.xpack.sql.expression.predicate.regex.LikePattern; -import org.elasticsearch.xpack.sql.tree.NodeTests.ChildrenAreAProperty; -import org.elasticsearch.xpack.sql.tree.NodeTests.Dummy; -import org.elasticsearch.xpack.sql.tree.NodeTests.NoChildren; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.expression.UnresolvedAttributeTests; +import org.elasticsearch.xpack.ql.expression.function.Function; +import org.elasticsearch.xpack.ql.expression.function.aggregate.AggregateFunction; +import org.elasticsearch.xpack.ql.expression.function.aggregate.CompoundAggregate; +import org.elasticsearch.xpack.ql.expression.function.aggregate.InnerAggregate; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.AggExtractorInput; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.BinaryPipesTests; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.processor.ConstantProcessor; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.predicate.fulltext.FullTextPredicate; +import org.elasticsearch.xpack.ql.expression.predicate.regex.Like; +import org.elasticsearch.xpack.ql.expression.predicate.regex.LikePattern; +import org.elasticsearch.xpack.ql.tree.NodeTests.ChildrenAreAProperty; +import org.elasticsearch.xpack.ql.tree.NodeTests.Dummy; +import org.elasticsearch.xpack.ql.tree.NodeTests.NoChildren; import org.mockito.exceptions.base.MockitoException; import java.io.IOException; @@ -54,14 +44,17 @@ import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.EnumSet; import java.util.HashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Set; import java.util.function.Supplier; +import java.util.jar.JarEntry; +import java.util.jar.JarInputStream; import static java.util.Collections.emptyList; import static java.util.stream.Collectors.toList; @@ -93,9 +86,6 @@ */ public class NodeSubclassTests> extends ESTestCase { - private static final List> CLASSES_WITH_MIN_TWO_CHILDREN = Arrays.asList(Iif.class, IfConditional.class, - IfNull.class, In.class, InPipe.class, Percentile.class, Percentiles.class, PercentileRanks.class); - private final Class subclass; public NodeSubclassTests(Class subclass) { @@ -318,7 +308,7 @@ public static List nodeSubclasses() throws IOException { * {@code ctor} that make sense when {@code ctor} * builds subclasses of {@link Node}. */ - private static Object[] ctorArgs(Constructor> ctor) throws Exception { + private Object[] ctorArgs(Constructor> ctor) throws Exception { Type[] argTypes = ctor.getGenericParameterTypes(); Object[] args = new Object[argTypes.length]; for (int i = 0; i < argTypes.length; i++) { @@ -344,7 +334,7 @@ private static Object[] ctorArgs(Constructor> ctor) throws Exc /** * Make an argument to feed the {@link #subclass}'s ctor. */ - private Object makeArg(Type argType) { + protected Object makeArg(Type argType) { try { return makeArg(subclass, argType); } catch (Exception e) { @@ -357,7 +347,7 @@ private Object makeArg(Type argType) { * Make an argument to feed to the constructor for {@code toBuildClass}. */ @SuppressWarnings("unchecked") - private static Object makeArg(Class> toBuildClass, Type argType) throws Exception { + private Object makeArg(Class> toBuildClass, Type argType) throws Exception { if (argType instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) argType; @@ -416,11 +406,15 @@ public boolean equals(Object obj) { * so we have to hard code it here. */ if (toBuildClass == InnerAggregate.class) { - // InnerAggregate's AggregateFunction must be an EnclosedAgg. Avg is. + // InnerAggregate's AggregateFunction must be an EnclosedAgg. if (argClass == AggregateFunction.class) { - return makeNode(Avg.class); + return makeEnclosedAgg(); + } + else if (argClass == CompoundAggregate.class) { + return makeCompoundAgg(); } - } else if (toBuildClass == FieldAttribute.class) { + } + else if (toBuildClass == FieldAttribute.class) { // `parent` is nullable. if (argClass == FieldAttribute.class && randomBoolean()) { return null; @@ -455,13 +449,10 @@ public boolean equals(Object obj) { return new LikePattern(randomAlphaOfLength(16), randomFrom('\\', '|', '/', '`')); } - } else if (toBuildClass == Histogram.class) { - if (argClass == Expression.class) { - return LiteralTests.randomLiteral(); - } - } else if (toBuildClass == CurrentDateTime.class) { - if (argClass == Expression.class) { - return Literal.of(SourceTests.randomSource(), randomInt(9)); + } else { + Object postProcess = pluggableMakeArg(toBuildClass, argClass); + if (postProcess != null) { + return postProcess; } } if (Expression.class == argClass) { @@ -526,11 +517,23 @@ public boolean equals(Object obj) { } } - private static List makeList(Class> toBuildClass, ParameterizedType listType) throws Exception { + protected Object makeCompoundAgg() throws Exception { + return makeArg(TestCompoundAggregate.class); + } + + protected Object makeEnclosedAgg() throws Exception { + return makeArg(TestEnclosedAgg.class); + } + + protected Object pluggableMakeArg(Class> toBuildClass, Class argClass) { + return null; + } + + private List makeList(Class> toBuildClass, ParameterizedType listType) throws Exception { return makeList(toBuildClass, listType, randomSizeForCollection(toBuildClass)); } - private static List makeList(Class> toBuildClass, ParameterizedType listType, int size) throws Exception { + private List makeList(Class> toBuildClass, ParameterizedType listType, int size) throws Exception { List list = new ArrayList<>(); for (int i = 0; i < size; i++) { list.add(makeArg(toBuildClass, listType.getActualTypeArguments()[0])); @@ -538,7 +541,7 @@ private static List makeList(Class> toBuildClass, Parameter return list; } - private static Object makeMap(Class> toBuildClass, ParameterizedType pt) throws Exception { + private Object makeMap(Class> toBuildClass, ParameterizedType pt) throws Exception { Map map = new HashMap<>(); int size = randomSizeForCollection(toBuildClass); while (map.size() < size) { @@ -549,16 +552,20 @@ private static Object makeMap(Class> toBuildClass, Parameteriz return map; } - private static int randomSizeForCollection(Class> toBuildClass) { + private int randomSizeForCollection(Class> toBuildClass) { int minCollectionLength = 0; int maxCollectionLength = 10; - if (CLASSES_WITH_MIN_TWO_CHILDREN.stream().anyMatch(c -> c == toBuildClass)) { + if (hasAtLeastTwoChildren(toBuildClass)) { minCollectionLength = 2; } return between(minCollectionLength, maxCollectionLength); } + protected boolean hasAtLeastTwoChildren(Class> toBuildClass) { + return false; + } + private List makeListOfSameSizeOtherThan(Type listType, List original) throws Exception { if (original.isEmpty()) { throw new IllegalArgumentException("Can't make a different empty list"); @@ -573,7 +580,7 @@ private List makeListOfSameSizeOtherThan(Type listType, List original) thr } - public static > T makeNode(Class nodeClass) throws Exception { + public > T makeNode(Class nodeClass) throws Exception { if (Modifier.isAbstract(nodeClass.getModifiers())) { nodeClass = randomFrom(subclassesOf(nodeClass)); } @@ -592,60 +599,93 @@ public static > T makeNode(Class nodeClass) throw * Cache of subclasses. We use a cache because it significantly speeds up * the test. */ - private static final Map, List> subclassCache = new HashMap<>(); + private static final Map, Set> subclassCache = new HashMap<>(); + /** * Find all subclasses of a particular class. */ - public static List> subclassesOf(Class clazz) throws IOException { + public static Set> subclassesOf(Class clazz) throws IOException { @SuppressWarnings("unchecked") // The map is built this way - List> lookup = (List>) subclassCache.get(clazz); + Set> lookup = (Set>) subclassCache.get(clazz); if (lookup != null) { return lookup; } - List> results = new ArrayList<>(); + Set> results = new LinkedHashSet<>(); String[] paths = System.getProperty("java.class.path").split(System.getProperty("path.separator")); for (String path: paths) { Path root = PathUtils.get(path); int rootLength = root.toString().length() + 1; - Files.walkFileTree(root, new SimpleFileVisitor() { - - @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - if (Files.isRegularFile(file) && file.getFileName().toString().endsWith(".class")) { - String className = file.toString(); - // Chop off the root and file extension - className = className.substring(rootLength, className.length() - ".class".length()); - // Go from "path" style to class style - className = className.replace(PathUtils.getDefaultFileSystem().getSeparator(), "."); - - // filter the class that are not interested - // (and IDE folders like eclipse) - if (!className.startsWith("org.elasticsearch.xpack.sql")) { - return FileVisitResult.CONTINUE; - } - - Class c; - try { - c = Class.forName(className); - } catch (ClassNotFoundException e) { - throw new IOException("Couldn't find " + file, e); - } - if (false == Modifier.isAbstract(c.getModifiers()) - && false == c.isAnonymousClass() - && clazz.isAssignableFrom(c)) { - Class s = c.asSubclass(clazz); - results.add(s); + // load classes from jar files + // NIO FileSystem API is not used since it trips the SecurityManager + // https://bugs.openjdk.java.net/browse/JDK-8160798 + // so iterate the jar "by hand" + if (path.endsWith(".jar") && path.contains("x-pack-ql")) { + try (JarInputStream jar = jarStream(root)) { + JarEntry je = null; + while ((je = jar.getNextJarEntry()) != null) { + String name = je.getName(); + if (name.endsWith(".class")) { + String className = name.substring(0, name.length() - ".class".length()).replace("/", "."); + maybeLoadClass(clazz, className, root + "!/" + name, results); } } - return FileVisitResult.CONTINUE; } - }); + } + // for folders, just use the FileSystems API + else { + Files.walkFileTree(root, new SimpleFileVisitor() { + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + if (Files.isRegularFile(file) && file.getFileName().toString().endsWith(".class")) { + String fileName = file.toString(); + // Chop off the root and file extension + String className = fileName.substring(rootLength, fileName.length() - ".class".length()); + // Go from "path" style to class style + className = className.replace(PathUtils.getDefaultFileSystem().getSeparator(), "."); + maybeLoadClass(clazz, className, fileName, results); + } + return FileVisitResult.CONTINUE; + } + }); + } } subclassCache.put(clazz, results); return results; } + @SuppressForbidden(reason = "test reads from jar") + private static JarInputStream jarStream(Path path) throws IOException { + return new JarInputStream(path.toUri().toURL().openStream()); + } + + /** + * Load classes from predefined packages (hack to limit the scope) and if they match the hierarchy, add them to the cache + */ + private static void maybeLoadClass(Class clazz, String className, String location, Set> results) + throws IOException { + + // filter the class that are not interested + // (and IDE folders like eclipse) + if (className.startsWith("org.elasticsearch.xpack.ql") == false && className.startsWith("org.elasticsearch.xpack.sql") == false) { + return; + } + + Class c; + try { + c = Class.forName(className); + } catch (ClassNotFoundException e) { + throw new IOException("Couldn't load " + location, e); + } + + if (false == Modifier.isAbstract(c.getModifiers()) + && false == c.isAnonymousClass() + && clazz.isAssignableFrom(c)) { + Class s = c.asSubclass(clazz); + results.add(s); + } + } + /** * The test class for some subclass of node or {@code null} * if there isn't such a class or it doesn't extend diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/tree/NodeTests.java b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/tree/NodeTests.java similarity index 97% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/tree/NodeTests.java rename to x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/tree/NodeTests.java index f73597bc0c4f8..46e3751a751d6 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/tree/NodeTests.java +++ b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/tree/NodeTests.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.tree; +package org.elasticsearch.xpack.ql.tree; import org.elasticsearch.test.ESTestCase; @@ -13,7 +13,7 @@ import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; -import static org.elasticsearch.xpack.sql.tree.SourceTests.randomSource; +import static org.elasticsearch.xpack.ql.tree.SourceTests.randomSource; public class NodeTests extends ESTestCase { public void testToString() { diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/tree/SourceTests.java b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/tree/SourceTests.java similarity index 97% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/tree/SourceTests.java rename to x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/tree/SourceTests.java index bd9855377193c..f24636d34e06c 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/tree/SourceTests.java +++ b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/tree/SourceTests.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.tree; +package org.elasticsearch.xpack.ql.tree; import org.elasticsearch.test.ESTestCase; diff --git a/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/tree/TestCompoundAggregate.java b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/tree/TestCompoundAggregate.java new file mode 100644 index 0000000000000..d807e662662ee --- /dev/null +++ b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/tree/TestCompoundAggregate.java @@ -0,0 +1,40 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.ql.tree; + +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.function.aggregate.AggregateFunction; +import org.elasticsearch.xpack.ql.expression.function.aggregate.CompoundAggregate; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; + +import java.util.List; + +public class TestCompoundAggregate extends AggregateFunction implements CompoundAggregate { + + public TestCompoundAggregate(Source source, Expression field) { + super(source, field); + } + + @Override + protected NodeInfo info() { + return NodeInfo.create(this, TestCompoundAggregate::new, field()); + } + + @Override + public TestCompoundAggregate replaceChildren(List newChildren) { + if (newChildren.size() != 1) { + throw new IllegalArgumentException("expected [1] child but received [" + newChildren.size() + "]"); + } + return new TestCompoundAggregate(source(), newChildren.get(0)); + } + + @Override + public DataType dataType() { + return DataTypes.DOUBLE; + } +} diff --git a/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/tree/TestEnclosedAgg.java b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/tree/TestEnclosedAgg.java new file mode 100644 index 0000000000000..8bd041df82c70 --- /dev/null +++ b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/tree/TestEnclosedAgg.java @@ -0,0 +1,45 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.ql.tree; + +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.function.aggregate.AggregateFunction; +import org.elasticsearch.xpack.ql.expression.function.aggregate.EnclosedAgg; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; + +import java.util.List; + +public class TestEnclosedAgg extends AggregateFunction implements EnclosedAgg { + + public TestEnclosedAgg(Source source, Expression field) { + super(source, field); + } + + @Override + protected NodeInfo info() { + return NodeInfo.create(this, TestEnclosedAgg::new, field()); + } + + @Override + public TestEnclosedAgg replaceChildren(List newChildren) { + if (newChildren.size() != 1) { + throw new IllegalArgumentException("expected [1] child but received [" + newChildren.size() + "]"); + } + return new TestEnclosedAgg(source(), newChildren.get(0)); + } + + @Override + public String innerName() { + return "testEnclosed"; + } + + @Override + public DataType dataType() { + return DataTypes.DOUBLE; + } +} diff --git a/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/type/DataTypeConversionTests.java b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/type/DataTypeConversionTests.java new file mode 100644 index 0000000000000..5e6ca1d8ea840 --- /dev/null +++ b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/type/DataTypeConversionTests.java @@ -0,0 +1,401 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +package org.elasticsearch.xpack.ql.type; + +import org.elasticsearch.test.ESTestCase; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.tree.Location; +import org.elasticsearch.xpack.ql.tree.Source; + +import java.time.ZonedDateTime; + +import static org.elasticsearch.xpack.ql.type.DataTypeConverter.commonType; +import static org.elasticsearch.xpack.ql.type.DataTypeConverter.converterFor; +import static org.elasticsearch.xpack.ql.type.DataTypes.BOOLEAN; +import static org.elasticsearch.xpack.ql.type.DataTypes.BYTE; +import static org.elasticsearch.xpack.ql.type.DataTypes.DATETIME; +import static org.elasticsearch.xpack.ql.type.DataTypes.DOUBLE; +import static org.elasticsearch.xpack.ql.type.DataTypes.FLOAT; +import static org.elasticsearch.xpack.ql.type.DataTypes.INTEGER; +import static org.elasticsearch.xpack.ql.type.DataTypes.IP; +import static org.elasticsearch.xpack.ql.type.DataTypes.KEYWORD; +import static org.elasticsearch.xpack.ql.type.DataTypes.LONG; +import static org.elasticsearch.xpack.ql.type.DataTypes.NULL; +import static org.elasticsearch.xpack.ql.type.DataTypes.SHORT; +import static org.elasticsearch.xpack.ql.type.DataTypes.TEXT; +import static org.elasticsearch.xpack.ql.type.DataTypes.UNSUPPORTED; +import static org.elasticsearch.xpack.ql.type.DateUtils.asDateTime; + +public class DataTypeConversionTests extends ESTestCase { + + public void testConversionToString() { + DataType to = KEYWORD; + { + Converter conversion = converterFor(DOUBLE, to); + assertNull(conversion.convert(null)); + assertEquals("10.0", conversion.convert(10.0)); + } + { + Converter conversion = converterFor(DATETIME, to); + assertNull(conversion.convert(null)); + assertEquals("1973-11-29T21:33:09.101Z", conversion.convert(asDateTime(123456789101L))); + assertEquals("1966-02-02T02:26:50.899Z", conversion.convert(asDateTime(-123456789101L))); + } + } + + /** + * Test conversion to long. + */ + public void testConversionToLong() { + DataType to = LONG; + { + Converter conversion = converterFor(DOUBLE, to); + assertNull(conversion.convert(null)); + assertEquals(10L, conversion.convert(10.0)); + assertEquals(10L, conversion.convert(10.1)); + assertEquals(11L, conversion.convert(10.6)); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert(Double.MAX_VALUE)); + assertEquals("[" + Double.MAX_VALUE + "] out of [long] range", e.getMessage()); + } + { + Converter conversion = converterFor(INTEGER, to); + assertNull(conversion.convert(null)); + assertEquals(10L, conversion.convert(10)); + assertEquals(-134L, conversion.convert(-134)); + } + { + Converter conversion = converterFor(BOOLEAN, to); + assertNull(conversion.convert(null)); + assertEquals(1L, conversion.convert(true)); + assertEquals(0L, conversion.convert(false)); + } + { + Converter conversion = converterFor(DATETIME, to); + assertNull(conversion.convert(null)); + assertEquals(123456789101L, conversion.convert(asDateTime(123456789101L))); + assertEquals(-123456789101L, conversion.convert(asDateTime(-123456789101L))); + } + { + Converter conversion = converterFor(KEYWORD, to); + assertNull(conversion.convert(null)); + assertEquals(1L, conversion.convert("1")); + assertEquals(0L, conversion.convert("-0")); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert("0xff")); + assertEquals("cannot cast [0xff] to [long]", e.getMessage()); + } + } + + public void testConversionToDateTime() { + DataType to = DATETIME; + { + Converter conversion = converterFor(DOUBLE, to); + assertNull(conversion.convert(null)); + assertEquals(asDateTime(10L), conversion.convert(10.0)); + assertEquals(asDateTime(10L), conversion.convert(10.1)); + assertEquals(asDateTime(11L), conversion.convert(10.6)); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert(Double.MAX_VALUE)); + assertEquals("[" + Double.MAX_VALUE + "] out of [long] range", e.getMessage()); + } + { + Converter conversion = converterFor(INTEGER, to); + assertNull(conversion.convert(null)); + assertEquals(asDateTime(10L), conversion.convert(10)); + assertEquals(asDateTime(-134L), conversion.convert(-134)); + } + { + Converter conversion = converterFor(BOOLEAN, to); + assertNull(conversion.convert(null)); + assertEquals(asDateTime(1), conversion.convert(true)); + assertEquals(asDateTime(0), conversion.convert(false)); + } + { + Converter conversion = converterFor(KEYWORD, to); + assertNull(conversion.convert(null)); + + assertEquals(asDateTime(0L), conversion.convert("1970-01-01")); + assertEquals(asDateTime(1000L), conversion.convert("1970-01-01T00:00:01Z")); + assertEquals(asDateTime(1483228800000L), conversion.convert("2017-01-01T00:00:00Z")); + assertEquals(asDateTime(1483228800000L), conversion.convert("2017-01-01T00:00:00Z")); + assertEquals(asDateTime(18000000L), conversion.convert("1970-01-01T00:00:00-05:00")); + + // double check back and forth conversion + ZonedDateTime dt = org.elasticsearch.common.time.DateUtils.nowWithMillisResolution(); + Converter forward = converterFor(DATETIME, KEYWORD); + Converter back = converterFor(KEYWORD, DATETIME); + assertEquals(dt, back.convert(forward.convert(dt))); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert("0xff")); + assertEquals("cannot cast [0xff] to [datetime]: failed to parse date field [0xff] with format [date_optional_time]", + e.getMessage()); + } + } + + public void testConversionToFloat() { + DataType to = FLOAT; + { + Converter conversion = converterFor(DOUBLE, to); + assertNull(conversion.convert(null)); + assertEquals(10.0f, (float) conversion.convert(10.0d), 0.00001); + assertEquals(10.1f, (float) conversion.convert(10.1d), 0.00001); + assertEquals(10.6f, (float) conversion.convert(10.6d), 0.00001); + } + { + Converter conversion = converterFor(INTEGER, to); + assertNull(conversion.convert(null)); + assertEquals(10.0f, (float) conversion.convert(10), 0.00001); + assertEquals(-134.0f, (float) conversion.convert(-134), 0.00001); + } + { + Converter conversion = converterFor(BOOLEAN, to); + assertNull(conversion.convert(null)); + assertEquals(1.0f, (float) conversion.convert(true), 0); + assertEquals(0.0f, (float) conversion.convert(false), 0); + } + { + Converter conversion = converterFor(DATETIME, to); + assertNull(conversion.convert(null)); + assertEquals(1.23456789101E11f, (float) conversion.convert(asDateTime(123456789101L)), 0); + assertEquals(-1.23456789101E11f, (float) conversion.convert(asDateTime(-123456789101L)), 0); + } + { + Converter conversion = converterFor(KEYWORD, to); + assertNull(conversion.convert(null)); + assertEquals(1.0f, (float) conversion.convert("1"), 0); + assertEquals(0.0f, (float) conversion.convert("-0"), 0); + assertEquals(12.776f, (float) conversion.convert("12.776"), 0.00001); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert("0xff")); + assertEquals("cannot cast [0xff] to [float]", e.getMessage()); + } + } + + public void testConversionToDouble() { + DataType to = DOUBLE; + { + Converter conversion = converterFor(FLOAT, to); + assertNull(conversion.convert(null)); + assertEquals(10.0, (double) conversion.convert(10.0f), 0.00001); + assertEquals(10.1, (double) conversion.convert(10.1f), 0.00001); + assertEquals(10.6, (double) conversion.convert(10.6f), 0.00001); + } + { + Converter conversion = converterFor(INTEGER, to); + assertNull(conversion.convert(null)); + assertEquals(10.0, (double) conversion.convert(10), 0.00001); + assertEquals(-134.0, (double) conversion.convert(-134), 0.00001); + } + { + Converter conversion = converterFor(BOOLEAN, to); + assertNull(conversion.convert(null)); + assertEquals(1.0, (double) conversion.convert(true), 0); + assertEquals(0.0, (double) conversion.convert(false), 0); + } + { + Converter conversion = converterFor(DATETIME, to); + assertNull(conversion.convert(null)); + assertEquals(1.23456789101E11, (double) conversion.convert(asDateTime(123456789101L)), 0); + assertEquals(-1.23456789101E11, (double) conversion.convert(asDateTime(-123456789101L)), 0); + } + { + Converter conversion = converterFor(KEYWORD, to); + assertNull(conversion.convert(null)); + assertEquals(1.0, (double) conversion.convert("1"), 0); + assertEquals(0.0, (double) conversion.convert("-0"), 0); + assertEquals(12.776, (double) conversion.convert("12.776"), 0.00001); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert("0xff")); + assertEquals("cannot cast [0xff] to [double]", e.getMessage()); + } + } + + public void testConversionToBoolean() { + DataType to = BOOLEAN; + { + Converter conversion = converterFor(FLOAT, to); + assertNull(conversion.convert(null)); + assertEquals(true, conversion.convert(10.0f)); + assertEquals(true, conversion.convert(-10.0f)); + assertEquals(false, conversion.convert(0.0f)); + } + { + Converter conversion = converterFor(INTEGER, to); + assertNull(conversion.convert(null)); + assertEquals(true, conversion.convert(10)); + assertEquals(true, conversion.convert(-10)); + assertEquals(false, conversion.convert(0)); + } + { + Converter conversion = converterFor(LONG, to); + assertNull(conversion.convert(null)); + assertEquals(true, conversion.convert(10L)); + assertEquals(true, conversion.convert(-10L)); + assertEquals(false, conversion.convert(0L)); + } + { + Converter conversion = converterFor(DOUBLE, to); + assertNull(conversion.convert(null)); + assertEquals(true, conversion.convert(10.0d)); + assertEquals(true, conversion.convert(-10.0d)); + assertEquals(false, conversion.convert(0.0d)); + } + { + Converter conversion = converterFor(DATETIME, to); + assertNull(conversion.convert(null)); + assertEquals(true, conversion.convert(asDateTime(123456789101L))); + assertEquals(true, conversion.convert(asDateTime(-123456789101L))); + assertEquals(false, conversion.convert(asDateTime(0L))); + } + { + Converter conversion = converterFor(KEYWORD, to); + assertNull(conversion.convert(null)); + // We only handled upper and lower case true and false + assertEquals(true, conversion.convert("true")); + assertEquals(false, conversion.convert("false")); + assertEquals(true, conversion.convert("True")); + assertEquals(false, conversion.convert("fAlSe")); + // Everything else should fail + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert("10")); + assertEquals("cannot cast [10] to [boolean]", e.getMessage()); + e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert("-1")); + assertEquals("cannot cast [-1] to [boolean]", e.getMessage()); + e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert("0")); + assertEquals("cannot cast [0] to [boolean]", e.getMessage()); + e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert("blah")); + assertEquals("cannot cast [blah] to [boolean]", e.getMessage()); + e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert("Yes")); + assertEquals("cannot cast [Yes] to [boolean]", e.getMessage()); + e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert("nO")); + assertEquals("cannot cast [nO] to [boolean]", e.getMessage()); + } + } + + public void testConversionToInt() { + DataType to = INTEGER; + { + Converter conversion = converterFor(DOUBLE, to); + assertNull(conversion.convert(null)); + assertEquals(10, conversion.convert(10.0)); + assertEquals(10, conversion.convert(10.1)); + assertEquals(11, conversion.convert(10.6)); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert(Long.MAX_VALUE)); + assertEquals("[" + Long.MAX_VALUE + "] out of [integer] range", e.getMessage()); + } + { + Converter conversion = converterFor(DATETIME, to); + assertNull(conversion.convert(null)); + assertEquals(12345678, conversion.convert(asDateTime(12345678L))); + assertEquals(223456789, conversion.convert(asDateTime(223456789L))); + assertEquals(-123456789, conversion.convert(asDateTime(-123456789L))); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert(asDateTime(Long.MAX_VALUE))); + assertEquals("[" + Long.MAX_VALUE + "] out of [integer] range", e.getMessage()); + } + } + + public void testConversionToShort() { + DataType to = SHORT; + { + Converter conversion = converterFor(DOUBLE, to); + assertNull(conversion.convert(null)); + assertEquals((short) 10, conversion.convert(10.0)); + assertEquals((short) 10, conversion.convert(10.1)); + assertEquals((short) 11, conversion.convert(10.6)); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert(Integer.MAX_VALUE)); + assertEquals("[" + Integer.MAX_VALUE + "] out of [short] range", e.getMessage()); + } + { + Converter conversion = converterFor(DATETIME, to); + assertNull(conversion.convert(null)); + assertEquals((short) 12345, conversion.convert(asDateTime(12345L))); + assertEquals((short) -12345, conversion.convert(asDateTime(-12345L))); + Exception e = expectThrows(QlIllegalArgumentException.class, + () -> conversion.convert(asDateTime(Integer.MAX_VALUE))); + assertEquals("[" + Integer.MAX_VALUE + "] out of [short] range", e.getMessage()); + } + } + + public void testConversionToByte() { + DataType to = BYTE; + { + Converter conversion = converterFor(DOUBLE, to); + assertNull(conversion.convert(null)); + assertEquals((byte) 10, conversion.convert(10.0)); + assertEquals((byte) 10, conversion.convert(10.1)); + assertEquals((byte) 11, conversion.convert(10.6)); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert(Short.MAX_VALUE)); + assertEquals("[" + Short.MAX_VALUE + "] out of [byte] range", e.getMessage()); + } + { + Converter conversion = converterFor(DATETIME, to); + assertNull(conversion.convert(null)); + assertEquals((byte) 123, conversion.convert(asDateTime(123L))); + assertEquals((byte) -123, conversion.convert(asDateTime(-123L))); + Exception e = expectThrows(QlIllegalArgumentException.class, + () -> conversion.convert(asDateTime(Integer.MAX_VALUE))); + assertEquals("[" + Integer.MAX_VALUE + "] out of [byte] range", e.getMessage()); + } + } + + public void testConversionToNull() { + Converter conversion = converterFor(DOUBLE, NULL); + assertNull(conversion.convert(null)); + assertNull(conversion.convert(10.0)); + } + + public void testConversionFromNull() { + Converter conversion = converterFor(NULL, INTEGER); + assertNull(conversion.convert(null)); + assertNull(conversion.convert(10)); + } + + public void testConversionToIdentity() { + Converter conversion = converterFor(INTEGER, INTEGER); + assertNull(conversion.convert(null)); + assertEquals(10, conversion.convert(10)); + } + + public void testCommonType() { + assertEquals(BOOLEAN, commonType(BOOLEAN, NULL)); + assertEquals(BOOLEAN, commonType(NULL, BOOLEAN)); + assertEquals(BOOLEAN, commonType(BOOLEAN, BOOLEAN)); + assertEquals(NULL, commonType(NULL, NULL)); + assertEquals(INTEGER, commonType(INTEGER, KEYWORD)); + assertEquals(LONG, commonType(TEXT, LONG)); + assertEquals(SHORT, commonType(SHORT, BYTE)); + assertEquals(FLOAT, commonType(BYTE, FLOAT)); + assertEquals(FLOAT, commonType(FLOAT, INTEGER)); + assertEquals(DOUBLE, commonType(DOUBLE, FLOAT)); + + // strings + assertEquals(TEXT, commonType(TEXT, KEYWORD)); + assertEquals(TEXT, commonType(KEYWORD, TEXT)); + } + + public void testEsDataTypes() { + for (DataType type : DataTypes.types()) { + assertEquals(type, DataTypes.fromTypeName(type.typeName())); + } + } + + public void testConversionToUnsupported() { + Exception e = expectThrows(QlIllegalArgumentException.class, + () -> DataTypeConverter.convert(Integer.valueOf(1), UNSUPPORTED)); + assertEquals("cannot convert from [1], type [integer] to [unsupported]", e.getMessage()); + } + + public void testStringToIp() { + Converter conversion = converterFor(KEYWORD, IP); + assertNull(conversion.convert(null)); + assertEquals("192.168.1.1", conversion.convert("192.168.1.1")); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert("10.1.1.300")); + assertEquals("[10.1.1.300] is not a valid IPv4 or IPv6 address", e.getMessage()); + } + + public void testIpToString() { + Source s = new Source(Location.EMPTY, "10.0.0.1"); + Converter ipToString = converterFor(IP, KEYWORD); + assertEquals("10.0.0.1", ipToString.convert(new Literal(s, "10.0.0.1", IP))); + Converter stringToIp = converterFor(KEYWORD, IP); + assertEquals("10.0.0.1", ipToString.convert(stringToIp.convert(new Literal(s, "10.0.0.1", KEYWORD)))); + } +} \ No newline at end of file diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/type/TypesTests.java b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/type/TypesTests.java similarity index 76% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/type/TypesTests.java rename to x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/type/TypesTests.java index 184091c9cd37c..8057c1cd48348 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/type/TypesTests.java +++ b/x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/type/TypesTests.java @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.type; +package org.elasticsearch.xpack.ql.type; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.json.JsonXContent; @@ -13,24 +13,24 @@ import java.util.Map; import static java.util.Collections.emptyMap; -import static org.elasticsearch.xpack.sql.type.DataType.DATETIME; -import static org.elasticsearch.xpack.sql.type.DataType.INTEGER; -import static org.elasticsearch.xpack.sql.type.DataType.KEYWORD; -import static org.elasticsearch.xpack.sql.type.DataType.NESTED; -import static org.elasticsearch.xpack.sql.type.DataType.OBJECT; -import static org.elasticsearch.xpack.sql.type.DataType.TEXT; +import static org.elasticsearch.xpack.ql.type.DataTypes.DATETIME; +import static org.elasticsearch.xpack.ql.type.DataTypes.INTEGER; +import static org.elasticsearch.xpack.ql.type.DataTypes.KEYWORD; +import static org.elasticsearch.xpack.ql.type.DataTypes.NESTED; +import static org.elasticsearch.xpack.ql.type.DataTypes.OBJECT; +import static org.elasticsearch.xpack.ql.type.DataTypes.TEXT; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; public class TypesTests extends ESTestCase { public void testNullMap() { - Map fromEs = Types.fromEs(null); + Map fromEs = Types.fromEs(DefaultDataTypeRegistry.INSTANCE, null); assertThat(fromEs.isEmpty(), is(true)); } public void testEmptyMap() { - Map fromEs = Types.fromEs(emptyMap()); + Map fromEs = Types.fromEs(DefaultDataTypeRegistry.INSTANCE, emptyMap()); assertThat(fromEs.isEmpty(), is(true)); } @@ -60,7 +60,6 @@ public void testTextField() { assertThat(type, instanceOf(TextEsField.class)); assertThat(type.isAggregatable(), is(false)); TextEsField ttype = (TextEsField) type; - assertThat(type.getPrecision(), is(Integer.MAX_VALUE)); assertThat(ttype.isAggregatable(), is(false)); } @@ -71,7 +70,6 @@ public void testKeywordField() { EsField field = mapping.get("full_name"); assertThat(field, instanceOf(KeywordEsField.class)); assertThat(field.isAggregatable(), is(true)); - assertThat(field.getPrecision(), is(256)); } public void testDateField() { @@ -81,7 +79,6 @@ public void testDateField() { EsField field = mapping.get("date"); assertThat(field.getDataType(), is(DATETIME)); assertThat(field.isAggregatable(), is(true)); - assertThat(field.getPrecision(), is(3)); } public void testDateNoFormat() { @@ -110,7 +107,7 @@ public void testDocValueField() { assertThat(mapping.size(), is(1)); EsField field = mapping.get("session_id"); assertThat(field, instanceOf(KeywordEsField.class)); - assertThat(field.getPrecision(), is(15)); + //assertThat(field.getPrecision(), is(15)); assertThat(field.isAggregatable(), is(false)); } @@ -119,7 +116,7 @@ public void testDottedField() { assertThat(mapping.size(), is(2)); EsField field = mapping.get("manager"); - assertThat(field.getDataType().isPrimitive(), is(false)); + assertThat(DataTypes.isPrimitive(field.getDataType()), is(false)); assertThat(field.getDataType(), is(OBJECT)); Map children = field.getProperties(); assertThat(children.size(), is(2)); @@ -134,7 +131,7 @@ public void testMultiField() { assertThat(mapping.size(), is(1)); EsField field = mapping.get("text"); - assertThat(field.getDataType().isPrimitive(), is(true)); + assertThat(DataTypes.isPrimitive(field.getDataType()), is(true)); assertThat(field.getDataType(), is(TEXT)); Map fields = field.getProperties(); assertThat(fields.size(), is(2)); @@ -147,7 +144,7 @@ public void testMultiFieldTooManyOptions() { assertThat(mapping.size(), is(1)); EsField field = mapping.get("text"); - assertThat(field.getDataType().isPrimitive(), is(true)); + assertThat(DataTypes.isPrimitive(field.getDataType()), is(true)); assertThat(field, instanceOf(TextEsField.class)); Map fields = field.getProperties(); assertThat(fields.size(), is(2)); @@ -160,7 +157,7 @@ public void testNestedDoc() { assertThat(mapping.size(), is(1)); EsField field = mapping.get("dep"); - assertThat(field.getDataType().isPrimitive(), is(false)); + assertThat(DataTypes.isPrimitive(field.getDataType()), is(false)); assertThat(field.getDataType(), is(NESTED)); Map children = field.getProperties(); assertThat(children.size(), is(4)); @@ -168,41 +165,39 @@ public void testNestedDoc() { assertThat(children.get("start_date").getDataType(), is(DATETIME)); } - public void testGeoField() { - Map mapping = loadMapping("mapping-geo.json"); - assertThat(mapping.size(), is(2)); - EsField gp = mapping.get("location"); - assertThat(gp.getDataType().typeName, is("geo_point")); - EsField gs = mapping.get("site"); - assertThat(gs.getDataType().typeName, is("geo_shape")); - } - public void testIpField() { Map mapping = loadMapping("mapping-ip.json"); assertThat(mapping.size(), is(1)); EsField dt = mapping.get("ip_addr"); - assertThat(dt.getDataType().typeName, is("ip")); + assertThat(dt.getDataType().typeName(), is("ip")); } public void testUnsupportedTypes() { Map mapping = loadMapping("mapping-unsupported.json"); EsField dt = mapping.get("range"); - assertThat(dt.getDataType().typeName, is("unsupported")); + assertThat(dt.getDataType().typeName(), is("unsupported")); dt = mapping.get("time_frame"); - assertThat(dt.getDataType().typeName, is("unsupported")); + assertThat(dt.getDataType().typeName(), is("unsupported")); dt = mapping.get("flat"); - assertThat(dt.getDataType().typeName, is("unsupported")); + assertThat(dt.getDataType().typeName(), is("unsupported")); } public static Map loadMapping(String name) { - InputStream stream = TypesTests.class.getResourceAsStream("/" + name); - assertNotNull("Could not find mapping resource:" + name, stream); - return Types.fromEs(XContentHelper.convertToMap(JsonXContent.jsonXContent, stream, randomBoolean())); + return loadMapping(DefaultDataTypeRegistry.INSTANCE, name, null); } public static Map loadMapping(String name, boolean ordered) { + return loadMapping(DefaultDataTypeRegistry.INSTANCE, name, ordered); + } + + public static Map loadMapping(DataTypeRegistry registry, String name) { + return loadMapping(registry, name, null); + } + + public static Map loadMapping(DataTypeRegistry registry, String name, Boolean ordered) { + boolean order = ordered != null ? ordered.booleanValue() : randomBoolean(); InputStream stream = TypesTests.class.getResourceAsStream("/" + name); assertNotNull("Could not find mapping resource:" + name, stream); - return Types.fromEs(XContentHelper.convertToMap(JsonXContent.jsonXContent, stream, ordered)); + return Types.fromEs(registry, XContentHelper.convertToMap(JsonXContent.jsonXContent, stream, order)); } -} +} \ No newline at end of file diff --git a/x-pack/plugin/sql/src/test/resources/mapping-basic-incompatible.json b/x-pack/plugin/ql/src/test/resources/mapping-basic-incompatible.json similarity index 100% rename from x-pack/plugin/sql/src/test/resources/mapping-basic-incompatible.json rename to x-pack/plugin/ql/src/test/resources/mapping-basic-incompatible.json diff --git a/x-pack/plugin/sql/src/test/resources/mapping-basic-nodocvalues.json b/x-pack/plugin/ql/src/test/resources/mapping-basic-nodocvalues.json similarity index 100% rename from x-pack/plugin/sql/src/test/resources/mapping-basic-nodocvalues.json rename to x-pack/plugin/ql/src/test/resources/mapping-basic-nodocvalues.json diff --git a/x-pack/plugin/sql/src/test/resources/mapping-basic.json b/x-pack/plugin/ql/src/test/resources/mapping-basic.json similarity index 100% rename from x-pack/plugin/sql/src/test/resources/mapping-basic.json rename to x-pack/plugin/ql/src/test/resources/mapping-basic.json diff --git a/x-pack/plugin/sql/src/test/resources/mapping-date-multi.json b/x-pack/plugin/ql/src/test/resources/mapping-date-multi.json similarity index 100% rename from x-pack/plugin/sql/src/test/resources/mapping-date-multi.json rename to x-pack/plugin/ql/src/test/resources/mapping-date-multi.json diff --git a/x-pack/plugin/sql/src/test/resources/mapping-date-no-format.json b/x-pack/plugin/ql/src/test/resources/mapping-date-no-format.json similarity index 100% rename from x-pack/plugin/sql/src/test/resources/mapping-date-no-format.json rename to x-pack/plugin/ql/src/test/resources/mapping-date-no-format.json diff --git a/x-pack/plugin/sql/src/test/resources/mapping-date.json b/x-pack/plugin/ql/src/test/resources/mapping-date.json similarity index 100% rename from x-pack/plugin/sql/src/test/resources/mapping-date.json rename to x-pack/plugin/ql/src/test/resources/mapping-date.json diff --git a/x-pack/plugin/sql/src/test/resources/mapping-default-string.json b/x-pack/plugin/ql/src/test/resources/mapping-default-string.json similarity index 100% rename from x-pack/plugin/sql/src/test/resources/mapping-default-string.json rename to x-pack/plugin/ql/src/test/resources/mapping-default-string.json diff --git a/x-pack/plugin/sql/src/test/resources/mapping-docvalues.json b/x-pack/plugin/ql/src/test/resources/mapping-docvalues.json similarity index 100% rename from x-pack/plugin/sql/src/test/resources/mapping-docvalues.json rename to x-pack/plugin/ql/src/test/resources/mapping-docvalues.json diff --git a/x-pack/plugin/sql/src/test/resources/mapping-dotted-field.json b/x-pack/plugin/ql/src/test/resources/mapping-dotted-field.json similarity index 100% rename from x-pack/plugin/sql/src/test/resources/mapping-dotted-field.json rename to x-pack/plugin/ql/src/test/resources/mapping-dotted-field.json diff --git a/x-pack/plugin/sql/src/test/resources/mapping-geo.json b/x-pack/plugin/ql/src/test/resources/mapping-geo.json similarity index 100% rename from x-pack/plugin/sql/src/test/resources/mapping-geo.json rename to x-pack/plugin/ql/src/test/resources/mapping-geo.json diff --git a/x-pack/plugin/sql/src/test/resources/mapping-ip.json b/x-pack/plugin/ql/src/test/resources/mapping-ip.json similarity index 100% rename from x-pack/plugin/sql/src/test/resources/mapping-ip.json rename to x-pack/plugin/ql/src/test/resources/mapping-ip.json diff --git a/x-pack/plugin/sql/src/test/resources/mapping-keyword.json b/x-pack/plugin/ql/src/test/resources/mapping-keyword.json similarity index 100% rename from x-pack/plugin/sql/src/test/resources/mapping-keyword.json rename to x-pack/plugin/ql/src/test/resources/mapping-keyword.json diff --git a/x-pack/plugin/sql/src/test/resources/mapping-multi-field-options.json b/x-pack/plugin/ql/src/test/resources/mapping-multi-field-options.json similarity index 100% rename from x-pack/plugin/sql/src/test/resources/mapping-multi-field-options.json rename to x-pack/plugin/ql/src/test/resources/mapping-multi-field-options.json diff --git a/x-pack/plugin/sql/src/test/resources/mapping-multi-field-variation.json b/x-pack/plugin/ql/src/test/resources/mapping-multi-field-variation.json similarity index 100% rename from x-pack/plugin/sql/src/test/resources/mapping-multi-field-variation.json rename to x-pack/plugin/ql/src/test/resources/mapping-multi-field-variation.json diff --git a/x-pack/plugin/sql/src/test/resources/mapping-multi-field-with-nested.json b/x-pack/plugin/ql/src/test/resources/mapping-multi-field-with-nested.json similarity index 100% rename from x-pack/plugin/sql/src/test/resources/mapping-multi-field-with-nested.json rename to x-pack/plugin/ql/src/test/resources/mapping-multi-field-with-nested.json diff --git a/x-pack/plugin/sql/src/test/resources/mapping-multi-field.json b/x-pack/plugin/ql/src/test/resources/mapping-multi-field.json similarity index 100% rename from x-pack/plugin/sql/src/test/resources/mapping-multi-field.json rename to x-pack/plugin/ql/src/test/resources/mapping-multi-field.json diff --git a/x-pack/plugin/sql/src/test/resources/mapping-nested.json b/x-pack/plugin/ql/src/test/resources/mapping-nested.json similarity index 100% rename from x-pack/plugin/sql/src/test/resources/mapping-nested.json rename to x-pack/plugin/ql/src/test/resources/mapping-nested.json diff --git a/x-pack/plugin/sql/src/test/resources/mapping-numeric.json b/x-pack/plugin/ql/src/test/resources/mapping-numeric.json similarity index 100% rename from x-pack/plugin/sql/src/test/resources/mapping-numeric.json rename to x-pack/plugin/ql/src/test/resources/mapping-numeric.json diff --git a/x-pack/plugin/sql/src/test/resources/mapping-object.json b/x-pack/plugin/ql/src/test/resources/mapping-object.json similarity index 100% rename from x-pack/plugin/sql/src/test/resources/mapping-object.json rename to x-pack/plugin/ql/src/test/resources/mapping-object.json diff --git a/x-pack/plugin/sql/src/test/resources/mapping-parent-child.json b/x-pack/plugin/ql/src/test/resources/mapping-parent-child.json similarity index 100% rename from x-pack/plugin/sql/src/test/resources/mapping-parent-child.json rename to x-pack/plugin/ql/src/test/resources/mapping-parent-child.json diff --git a/x-pack/plugin/sql/src/test/resources/mapping-text.json b/x-pack/plugin/ql/src/test/resources/mapping-text.json similarity index 100% rename from x-pack/plugin/sql/src/test/resources/mapping-text.json rename to x-pack/plugin/ql/src/test/resources/mapping-text.json diff --git a/x-pack/plugin/sql/src/test/resources/mapping-unsupported.json b/x-pack/plugin/ql/src/test/resources/mapping-unsupported.json similarity index 100% rename from x-pack/plugin/sql/src/test/resources/mapping-unsupported.json rename to x-pack/plugin/ql/src/test/resources/mapping-unsupported.json diff --git a/x-pack/plugin/sql/build.gradle b/x-pack/plugin/sql/build.gradle index 48fd6aee64785..06d6087d88e0f 100644 --- a/x-pack/plugin/sql/build.gradle +++ b/x-pack/plugin/sql/build.gradle @@ -5,7 +5,7 @@ esplugin { name 'x-pack-sql' description 'The Elasticsearch plugin that powers SQL for Elasticsearch' classname 'org.elasticsearch.xpack.sql.plugin.SqlPlugin' - extendedPlugins = ['x-pack-core', 'lang-painless'] + extendedPlugins = ['x-pack-ql', 'lang-painless'] } ext { @@ -45,14 +45,15 @@ dependencies { } compile project('sql-action') compile project(':modules:aggs-matrix-stats') - compile "org.antlr:antlr4-runtime:4.5.3" + compile "org.antlr:antlr4-runtime:${antlrVersion}" + compileOnly project(path: xpackModule('ql'), configuration: 'default') testCompile project(':test:framework') testCompile project(path: xpackModule('core'), configuration: 'testArtifacts') testCompile project(path: xpackModule('security'), configuration: 'testArtifacts') + testCompile project(path: xpackModule('ql'), configuration: 'testArtifacts') testCompile project(path: ':modules:reindex', configuration: 'runtime') testCompile project(path: ':modules:parent-join', configuration: 'runtime') testCompile project(path: ':modules:analysis-common', configuration: 'runtime') - bin(project(path: xpackModule('sql:sql-cli'), configuration: 'shadow')) } diff --git a/x-pack/plugin/sql/qa/src/main/resources/conditionals.csv-spec b/x-pack/plugin/sql/qa/src/main/resources/conditionals.csv-spec index 9f424da2710e3..e6453ad1420e1 100644 --- a/x-pack/plugin/sql/qa/src/main/resources/conditionals.csv-spec +++ b/x-pack/plugin/sql/qa/src/main/resources/conditionals.csv-spec @@ -441,7 +441,7 @@ SELECT ISNULL(birth_date, INTERVAL '23:45' HOUR TO MINUTES + {d '2019-09-17'}) A c:ts | salary:i | birth_date:ts | hire_date:ts ------------------------+-----------------+------------------------+------------------------ 1956-12-13T00:00:00.000Z|74999 |1956-12-13T00:00:00.000Z|1985-11-20T00:00:00.000Z -2019-09-17T00:00:00.000Z|74970 |null |1989-09-02T00:00:00.000Z +2019-09-17T23:45:00.000Z|74970 |null |1989-09-02T00:00:00.000Z 1957-05-23T00:00:00.000Z|74572 |1957-05-23T00:00:00.000Z|1989-02-10T00:00:00.000Z 1962-07-10T00:00:00.000Z|73851 |1962-07-10T00:00:00.000Z|1989-07-07T00:00:00.000Z 1953-01-23T00:00:00.000Z|73717 |1953-01-23T00:00:00.000Z|1999-04-30T00:00:00.000Z diff --git a/x-pack/plugin/sql/sql-proto/src/main/java/org/elasticsearch/xpack/sql/proto/StringUtils.java b/x-pack/plugin/sql/sql-proto/src/main/java/org/elasticsearch/xpack/sql/proto/StringUtils.java index 780fce2604c04..d0c4c0f0b35ee 100644 --- a/x-pack/plugin/sql/sql-proto/src/main/java/org/elasticsearch/xpack/sql/proto/StringUtils.java +++ b/x-pack/plugin/sql/sql-proto/src/main/java/org/elasticsearch/xpack/sql/proto/StringUtils.java @@ -42,28 +42,28 @@ public final class StringUtils { .toFormatter(Locale.ROOT); public static final DateTimeFormatter ISO_DATE_WITH_NANOS = new DateTimeFormatterBuilder() - .parseCaseInsensitive() - .append(ISO_LOCAL_DATE) - .appendLiteral('T') - .appendValue(HOUR_OF_DAY, 2) - .appendLiteral(':') - .appendValue(MINUTE_OF_HOUR, 2) - .appendLiteral(':') - .appendValue(SECOND_OF_MINUTE, 2) - .appendFraction(NANO_OF_SECOND, 3, 9, true) - .appendOffsetId() - .toFormatter(Locale.ROOT); + .parseCaseInsensitive() + .append(ISO_LOCAL_DATE) + .appendLiteral('T') + .appendValue(HOUR_OF_DAY, 2) + .appendLiteral(':') + .appendValue(MINUTE_OF_HOUR, 2) + .appendLiteral(':') + .appendValue(SECOND_OF_MINUTE, 2) + .appendFraction(NANO_OF_SECOND, 3, 9, true) + .appendOffsetId() + .toFormatter(Locale.ROOT); public static final DateTimeFormatter ISO_TIME_WITH_MILLIS = new DateTimeFormatterBuilder() - .parseCaseInsensitive() - .appendValue(HOUR_OF_DAY, 2) - .appendLiteral(':') - .appendValue(MINUTE_OF_HOUR, 2) - .appendLiteral(':') - .appendValue(SECOND_OF_MINUTE, 2) - .appendFraction(MILLI_OF_SECOND, 3, 3, true) - .appendOffsetId() - .toFormatter(Locale.ROOT); + .parseCaseInsensitive() + .appendValue(HOUR_OF_DAY, 2) + .appendLiteral(':') + .appendValue(MINUTE_OF_HOUR, 2) + .appendLiteral(':') + .appendValue(SECOND_OF_MINUTE, 2) + .appendFraction(MILLI_OF_SECOND, 3, 3, true) + .appendOffsetId() + .toFormatter(Locale.ROOT); private static final int SECONDS_PER_MINUTE = 60; private static final int SECONDS_PER_HOUR = SECONDS_PER_MINUTE * 60; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/ClientSqlException.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/SqlClientException.java similarity index 57% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/ClientSqlException.java rename to x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/SqlClientException.java index accca2a6a45b6..0e177c4fd3d2a 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/ClientSqlException.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/SqlClientException.java @@ -5,25 +5,27 @@ */ package org.elasticsearch.xpack.sql; -public abstract class ClientSqlException extends SqlException { +import org.elasticsearch.xpack.ql.QlClientException; - protected ClientSqlException(String message, Object... args) { +public abstract class SqlClientException extends QlClientException { + + protected SqlClientException(String message, Object... args) { super(message, args); } - protected ClientSqlException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + protected SqlClientException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } - protected ClientSqlException(String message, Throwable cause) { + protected SqlClientException(String message, Throwable cause) { super(message, cause); } - protected ClientSqlException(Throwable cause, String message, Object... args) { + protected SqlClientException(Throwable cause, String message, Object... args) { super(cause, message, args); } - protected ClientSqlException(Throwable cause) { + protected SqlClientException(Throwable cause) { super(cause); } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/SqlIllegalArgumentException.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/SqlIllegalArgumentException.java index be121a0ace4df..27ad608c80f06 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/SqlIllegalArgumentException.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/SqlIllegalArgumentException.java @@ -5,7 +5,9 @@ */ package org.elasticsearch.xpack.sql; -public class SqlIllegalArgumentException extends ServerSqlException { +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; + +public class SqlIllegalArgumentException extends QlIllegalArgumentException { public SqlIllegalArgumentException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/ServerSqlException.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/SqlServerException.java similarity index 57% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/ServerSqlException.java rename to x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/SqlServerException.java index e8548ab7f93ce..319e2b065d9ff 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/ServerSqlException.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/SqlServerException.java @@ -5,25 +5,27 @@ */ package org.elasticsearch.xpack.sql; -public abstract class ServerSqlException extends SqlException { +import org.elasticsearch.xpack.ql.QlServerException; - protected ServerSqlException(String message, Object... args) { +public abstract class SqlServerException extends QlServerException { + + protected SqlServerException(String message, Object... args) { super(message, args); } - protected ServerSqlException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + protected SqlServerException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } - protected ServerSqlException(String message, Throwable cause) { + protected SqlServerException(String message, Throwable cause) { super(message, cause); } - protected ServerSqlException(Throwable cause, String message, Object... args) { + protected SqlServerException(Throwable cause, String message, Object... args) { super(cause, message, args); } - protected ServerSqlException(Throwable cause) { + protected SqlServerException(Throwable cause) { super(cause); } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/AnalysisException.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/AnalysisException.java index 262d62814e164..4d3a799467ea8 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/AnalysisException.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/AnalysisException.java @@ -6,13 +6,13 @@ package org.elasticsearch.xpack.sql.analysis; import org.elasticsearch.rest.RestStatus; -import org.elasticsearch.xpack.sql.ClientSqlException; -import org.elasticsearch.xpack.sql.tree.Location; -import org.elasticsearch.xpack.sql.tree.Node; +import org.elasticsearch.xpack.ql.tree.Location; +import org.elasticsearch.xpack.ql.tree.Node; +import org.elasticsearch.xpack.sql.SqlClientException; import static org.elasticsearch.common.logging.LoggerMessageFormat.format; -public class AnalysisException extends ClientSqlException { +public class AnalysisException extends SqlClientException { private final int line; private final int column; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/analyzer/Analyzer.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/analyzer/Analyzer.java index cd12efef66fb6..3be204c3a89a4 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/analyzer/Analyzer.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/analyzer/Analyzer.java @@ -6,55 +6,55 @@ package org.elasticsearch.xpack.sql.analysis.analyzer; import org.elasticsearch.common.logging.LoggerMessageFormat; +import org.elasticsearch.xpack.ql.capabilities.Resolvables; +import org.elasticsearch.xpack.ql.expression.Alias; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.AttributeMap; +import org.elasticsearch.xpack.ql.expression.AttributeSet; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.expression.NamedExpression; +import org.elasticsearch.xpack.ql.expression.Order; +import org.elasticsearch.xpack.ql.expression.ReferenceAttribute; +import org.elasticsearch.xpack.ql.expression.UnresolvedAlias; +import org.elasticsearch.xpack.ql.expression.UnresolvedAttribute; +import org.elasticsearch.xpack.ql.expression.UnresolvedStar; +import org.elasticsearch.xpack.ql.expression.function.Function; +import org.elasticsearch.xpack.ql.expression.function.FunctionDefinition; +import org.elasticsearch.xpack.ql.expression.function.FunctionRegistry; +import org.elasticsearch.xpack.ql.expression.function.Functions; +import org.elasticsearch.xpack.ql.expression.function.UnresolvedFunction; +import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.ArithmeticOperation; +import org.elasticsearch.xpack.ql.index.IndexResolution; +import org.elasticsearch.xpack.ql.plan.TableIdentifier; +import org.elasticsearch.xpack.ql.plan.logical.Aggregate; +import org.elasticsearch.xpack.ql.plan.logical.EsRelation; +import org.elasticsearch.xpack.ql.plan.logical.Filter; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.plan.logical.OrderBy; +import org.elasticsearch.xpack.ql.plan.logical.Project; +import org.elasticsearch.xpack.ql.plan.logical.UnaryPlan; +import org.elasticsearch.xpack.ql.plan.logical.UnresolvedRelation; +import org.elasticsearch.xpack.ql.rule.Rule; +import org.elasticsearch.xpack.ql.rule.RuleExecutor; +import org.elasticsearch.xpack.ql.session.Configuration; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; +import org.elasticsearch.xpack.ql.type.InvalidMappedField; +import org.elasticsearch.xpack.ql.type.UnsupportedEsField; +import org.elasticsearch.xpack.ql.util.CollectionUtils; +import org.elasticsearch.xpack.ql.util.Holder; import org.elasticsearch.xpack.sql.analysis.analyzer.Verifier.Failure; -import org.elasticsearch.xpack.sql.analysis.index.IndexResolution; -import org.elasticsearch.xpack.sql.capabilities.Resolvables; -import org.elasticsearch.xpack.sql.expression.Alias; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.expression.AttributeMap; -import org.elasticsearch.xpack.sql.expression.AttributeSet; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; import org.elasticsearch.xpack.sql.expression.Foldables; -import org.elasticsearch.xpack.sql.expression.NamedExpression; -import org.elasticsearch.xpack.sql.expression.Order; -import org.elasticsearch.xpack.sql.expression.ReferenceAttribute; import org.elasticsearch.xpack.sql.expression.SubQueryExpression; -import org.elasticsearch.xpack.sql.expression.UnresolvedAlias; -import org.elasticsearch.xpack.sql.expression.UnresolvedAttribute; -import org.elasticsearch.xpack.sql.expression.UnresolvedStar; -import org.elasticsearch.xpack.sql.expression.function.Function; -import org.elasticsearch.xpack.sql.expression.function.FunctionDefinition; -import org.elasticsearch.xpack.sql.expression.function.FunctionRegistry; -import org.elasticsearch.xpack.sql.expression.function.Functions; -import org.elasticsearch.xpack.sql.expression.function.UnresolvedFunction; import org.elasticsearch.xpack.sql.expression.function.scalar.Cast; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.ArithmeticOperation; -import org.elasticsearch.xpack.sql.plan.TableIdentifier; -import org.elasticsearch.xpack.sql.plan.logical.Aggregate; -import org.elasticsearch.xpack.sql.plan.logical.EsRelation; -import org.elasticsearch.xpack.sql.plan.logical.Filter; import org.elasticsearch.xpack.sql.plan.logical.Join; import org.elasticsearch.xpack.sql.plan.logical.LocalRelation; -import org.elasticsearch.xpack.sql.plan.logical.LogicalPlan; -import org.elasticsearch.xpack.sql.plan.logical.OrderBy; import org.elasticsearch.xpack.sql.plan.logical.Pivot; -import org.elasticsearch.xpack.sql.plan.logical.Project; import org.elasticsearch.xpack.sql.plan.logical.SubQueryAlias; -import org.elasticsearch.xpack.sql.plan.logical.UnaryPlan; -import org.elasticsearch.xpack.sql.plan.logical.UnresolvedRelation; import org.elasticsearch.xpack.sql.plan.logical.With; -import org.elasticsearch.xpack.sql.rule.Rule; -import org.elasticsearch.xpack.sql.rule.RuleExecutor; -import org.elasticsearch.xpack.sql.session.Configuration; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.DataTypeConversion; -import org.elasticsearch.xpack.sql.type.DataTypes; -import org.elasticsearch.xpack.sql.type.InvalidMappedField; -import org.elasticsearch.xpack.sql.type.UnsupportedEsField; -import org.elasticsearch.xpack.sql.util.CollectionUtils; -import org.elasticsearch.xpack.sql.util.Holder; +import org.elasticsearch.xpack.sql.type.SqlDataTypeConverter; import java.util.ArrayList; import java.util.Arrays; @@ -70,7 +70,7 @@ import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toList; -import static org.elasticsearch.xpack.sql.util.CollectionUtils.combine; +import static org.elasticsearch.xpack.ql.util.CollectionUtils.combine; public class Analyzer extends RuleExecutor { /** @@ -227,9 +227,9 @@ else if (DataTypes.isUnsupported(fa.dataType())) { } } // compound fields - else if (allowCompound == false && fa.dataType().isPrimitive() == false) { + else if (allowCompound == false && DataTypes.isPrimitive(fa.dataType()) == false) { named = u.withUnresolvedMessage( - "Cannot use field [" + fa.name() + "] type [" + fa.dataType().typeName + "] only its subfields"); + "Cannot use field [" + fa.name() + "] type [" + fa.dataType().typeName() + "] only its subfields"); } } return named; @@ -1188,7 +1188,7 @@ private Expression implicitCast(Expression e) { DataType l = left.dataType(); DataType r = right.dataType(); if (l != r) { - DataType common = DataTypeConversion.commonType(l, r); + DataType common = SqlDataTypeConverter.commonType(l, r); if (common == null) { return e; } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/analyzer/PreAnalyzer.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/analyzer/PreAnalyzer.java index 16e35cd8638a2..efe044f64f77d 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/analyzer/PreAnalyzer.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/analyzer/PreAnalyzer.java @@ -5,8 +5,8 @@ */ package org.elasticsearch.xpack.sql.analysis.analyzer; -import org.elasticsearch.xpack.sql.plan.logical.LogicalPlan; -import org.elasticsearch.xpack.sql.plan.logical.UnresolvedRelation; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.plan.logical.UnresolvedRelation; import java.util.ArrayList; import java.util.List; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/analyzer/TableInfo.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/analyzer/TableInfo.java index 479b094fad5bc..e12659c2c2ab7 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/analyzer/TableInfo.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/analyzer/TableInfo.java @@ -6,7 +6,7 @@ package org.elasticsearch.xpack.sql.analysis.analyzer; -import org.elasticsearch.xpack.sql.plan.TableIdentifier; +import org.elasticsearch.xpack.ql.plan.TableIdentifier; public class TableInfo { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/analyzer/VerificationException.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/analyzer/VerificationException.java index 14281a628b163..0eba4126ba850 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/analyzer/VerificationException.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/analyzer/VerificationException.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.analysis.analyzer; +import org.elasticsearch.xpack.ql.tree.Location; +import org.elasticsearch.xpack.ql.util.StringUtils; import org.elasticsearch.xpack.sql.analysis.AnalysisException; import org.elasticsearch.xpack.sql.analysis.analyzer.Verifier.Failure; -import org.elasticsearch.xpack.sql.tree.Location; -import org.elasticsearch.xpack.sql.util.StringUtils; import java.util.Collection; import java.util.stream.Collectors; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/analyzer/Verifier.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/analyzer/Verifier.java index 34def1238d00f..9026567025521 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/analyzer/Verifier.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/analyzer/Verifier.java @@ -5,46 +5,47 @@ */ package org.elasticsearch.xpack.sql.analysis.analyzer; -import org.elasticsearch.xpack.sql.capabilities.Unresolvable; -import org.elasticsearch.xpack.sql.expression.Alias; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.expression.AttributeMap; -import org.elasticsearch.xpack.sql.expression.AttributeSet; +import org.elasticsearch.xpack.ql.capabilities.Unresolvable; +import org.elasticsearch.xpack.ql.expression.Alias; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.AttributeMap; +import org.elasticsearch.xpack.ql.expression.AttributeSet; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.NamedExpression; +import org.elasticsearch.xpack.ql.expression.ReferenceAttribute; +import org.elasticsearch.xpack.ql.expression.UnresolvedAttribute; +import org.elasticsearch.xpack.ql.expression.function.Function; +import org.elasticsearch.xpack.ql.expression.function.Functions; +import org.elasticsearch.xpack.ql.expression.function.aggregate.AggregateFunction; +import org.elasticsearch.xpack.ql.expression.function.grouping.GroupingFunction; +import org.elasticsearch.xpack.ql.expression.function.scalar.ScalarFunction; +import org.elasticsearch.xpack.ql.plan.logical.Aggregate; +import org.elasticsearch.xpack.ql.plan.logical.Filter; +import org.elasticsearch.xpack.ql.plan.logical.Limit; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.plan.logical.OrderBy; +import org.elasticsearch.xpack.ql.plan.logical.Project; +import org.elasticsearch.xpack.ql.tree.Node; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; +import org.elasticsearch.xpack.ql.type.EsField; +import org.elasticsearch.xpack.ql.util.Holder; +import org.elasticsearch.xpack.ql.util.StringUtils; import org.elasticsearch.xpack.sql.expression.Exists; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.expression.NamedExpression; -import org.elasticsearch.xpack.sql.expression.ReferenceAttribute; -import org.elasticsearch.xpack.sql.expression.UnresolvedAttribute; -import org.elasticsearch.xpack.sql.expression.function.Function; -import org.elasticsearch.xpack.sql.expression.function.Functions; import org.elasticsearch.xpack.sql.expression.function.Score; -import org.elasticsearch.xpack.sql.expression.function.aggregate.AggregateFunction; import org.elasticsearch.xpack.sql.expression.function.aggregate.Max; import org.elasticsearch.xpack.sql.expression.function.aggregate.Min; import org.elasticsearch.xpack.sql.expression.function.aggregate.TopHits; -import org.elasticsearch.xpack.sql.expression.function.grouping.GroupingFunction; -import org.elasticsearch.xpack.sql.expression.function.scalar.ScalarFunction; -import org.elasticsearch.xpack.sql.plan.logical.Aggregate; import org.elasticsearch.xpack.sql.plan.logical.Distinct; -import org.elasticsearch.xpack.sql.plan.logical.Filter; -import org.elasticsearch.xpack.sql.plan.logical.Limit; import org.elasticsearch.xpack.sql.plan.logical.LocalRelation; -import org.elasticsearch.xpack.sql.plan.logical.LogicalPlan; -import org.elasticsearch.xpack.sql.plan.logical.OrderBy; import org.elasticsearch.xpack.sql.plan.logical.Pivot; -import org.elasticsearch.xpack.sql.plan.logical.Project; import org.elasticsearch.xpack.sql.plan.logical.command.Command; import org.elasticsearch.xpack.sql.stats.FeatureMetric; import org.elasticsearch.xpack.sql.stats.Metrics; -import org.elasticsearch.xpack.sql.tree.Node; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.DataTypes; -import org.elasticsearch.xpack.sql.type.EsField; -import org.elasticsearch.xpack.sql.util.Holder; -import org.elasticsearch.xpack.sql.util.StringUtils; +import org.elasticsearch.xpack.sql.type.SqlDataTypes; import java.util.ArrayList; import java.util.BitSet; @@ -60,6 +61,7 @@ import static java.util.stream.Collectors.toMap; import static org.elasticsearch.common.logging.LoggerMessageFormat.format; +import static org.elasticsearch.xpack.ql.util.CollectionUtils.combine; import static org.elasticsearch.xpack.sql.stats.FeatureMetric.COMMAND; import static org.elasticsearch.xpack.sql.stats.FeatureMetric.GROUPBY; import static org.elasticsearch.xpack.sql.stats.FeatureMetric.HAVING; @@ -67,9 +69,8 @@ import static org.elasticsearch.xpack.sql.stats.FeatureMetric.LOCAL; import static org.elasticsearch.xpack.sql.stats.FeatureMetric.ORDERBY; import static org.elasticsearch.xpack.sql.stats.FeatureMetric.WHERE; -import static org.elasticsearch.xpack.sql.type.DataType.GEO_SHAPE; -import static org.elasticsearch.xpack.sql.type.DataType.SHAPE; -import static org.elasticsearch.xpack.sql.util.CollectionUtils.combine; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.GEO_SHAPE; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.SHAPE; /** * The verifier has the role of checking the analyzed tree for failures and build a list of failures following this check. @@ -182,7 +183,7 @@ Collection verify(LogicalPlan plan) { for (Attribute a : p.inputSet()) { String nameCandidate = useQualifier ? a.qualifiedName() : a.name(); // add only primitives (object types would only result in another error) - if ((a.dataType() != DataType.UNSUPPORTED) && a.dataType().isPrimitive()) { + if (DataTypes.isUnsupported(a.dataType()) == false && DataTypes.isPrimitive(a.dataType())) { potentialMatches.add(nameCandidate); } } @@ -450,7 +451,7 @@ private static boolean checkGroupByHavingHasOnlyAggs(Expression e, Set expressions, Set localFailure // TIME data type is not allowed for grouping key // https://github.com/elastic/elasticsearch/issues/40639 a.groupings().forEach(f -> { - if (f.dataType().isTimeBased()) { - localFailures.add(fail(f, "Function [" + f.sourceText() + "] with data type [" + f.dataType().typeName + + if (f.dataType() == SqlDataTypes.TIME) { + localFailures.add(fail(f, "Function [" + f.sourceText() + "] with data type [" + f.dataType().typeName() + "] " + "cannot be used for grouping")); } }); @@ -810,9 +811,9 @@ else if (ex.foldable() && ex.fold() == null) { localFailures.add(fail(v, "Null not allowed as a PIVOT value", v.name())); } // and that their type is compatible with that of the column - else if (DataTypes.areTypesCompatible(colType, v.dataType()) == false) { + else if (SqlDataTypes.areCompatible(colType, v.dataType()) == false) { localFailures.add(fail(v, "Literal [{}] of type [{}] does not match type [{}] of PIVOT column [{}]", v.name(), - v.dataType().typeName, colType.typeName, pv.column().sourceText())); + v.dataType().typeName(), colType.typeName(), pv.column().sourceText())); } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/PlanExecutor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/PlanExecutor.java index ca394bf11d881..d43f43da39206 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/PlanExecutor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/PlanExecutor.java @@ -9,11 +9,12 @@ import org.elasticsearch.client.Client; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.search.builder.SearchSourceBuilder; +import org.elasticsearch.xpack.ql.expression.function.FunctionRegistry; +import org.elasticsearch.xpack.ql.index.IndexResolver; import org.elasticsearch.xpack.sql.analysis.analyzer.PreAnalyzer; import org.elasticsearch.xpack.sql.analysis.analyzer.Verifier; -import org.elasticsearch.xpack.sql.analysis.index.IndexResolver; import org.elasticsearch.xpack.sql.execution.search.SourceGenerator; -import org.elasticsearch.xpack.sql.expression.function.FunctionRegistry; +import org.elasticsearch.xpack.sql.expression.function.SqlFunctionRegistry; import org.elasticsearch.xpack.sql.optimizer.Optimizer; import org.elasticsearch.xpack.sql.plan.physical.CommandExec; import org.elasticsearch.xpack.sql.plan.physical.EsQueryExec; @@ -51,7 +52,7 @@ public PlanExecutor(Client client, IndexResolver indexResolver, NamedWriteableRe this.writableRegistry = writeableRegistry; this.indexResolver = indexResolver; - this.functionRegistry = new FunctionRegistry(); + this.functionRegistry = new SqlFunctionRegistry(); this.metrics = new Metrics(); diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/CompositeAggCursor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/CompositeAggCursor.java index 645d513ef5035..77b16883d02cc 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/CompositeAggCursor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/CompositeAggCursor.java @@ -22,14 +22,14 @@ import org.elasticsearch.search.aggregations.bucket.composite.CompositeAggregation; import org.elasticsearch.search.aggregations.bucket.composite.CompositeAggregationBuilder; import org.elasticsearch.search.builder.SearchSourceBuilder; +import org.elasticsearch.xpack.ql.execution.search.extractor.BucketExtractor; +import org.elasticsearch.xpack.ql.type.Schema; +import org.elasticsearch.xpack.ql.util.StringUtils; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.execution.search.extractor.BucketExtractor; import org.elasticsearch.xpack.sql.querydsl.agg.Aggs; import org.elasticsearch.xpack.sql.session.Configuration; import org.elasticsearch.xpack.sql.session.Cursor; import org.elasticsearch.xpack.sql.session.Rows; -import org.elasticsearch.xpack.sql.type.Schema; -import org.elasticsearch.xpack.sql.util.StringUtils; import java.io.IOException; import java.util.Arrays; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/CompositeAggRowSet.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/CompositeAggRowSet.java index 1262e80e06636..0385ba34de229 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/CompositeAggRowSet.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/CompositeAggRowSet.java @@ -7,7 +7,7 @@ import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.search.aggregations.bucket.composite.CompositeAggregation; -import org.elasticsearch.xpack.sql.execution.search.extractor.BucketExtractor; +import org.elasticsearch.xpack.ql.execution.search.extractor.BucketExtractor; import org.elasticsearch.xpack.sql.session.RowSet; import java.util.BitSet; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/PivotCursor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/PivotCursor.java index a815602d950bb..356f2bc4ad950 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/PivotCursor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/PivotCursor.java @@ -9,8 +9,8 @@ import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; -import org.elasticsearch.xpack.sql.execution.search.extractor.BucketExtractor; -import org.elasticsearch.xpack.sql.type.Schema; +import org.elasticsearch.xpack.ql.execution.search.extractor.BucketExtractor; +import org.elasticsearch.xpack.ql.type.Schema; import java.io.IOException; import java.util.Arrays; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/PivotRowSet.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/PivotRowSet.java index 3d7e12b3d9b09..082b9f920fd62 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/PivotRowSet.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/PivotRowSet.java @@ -8,8 +8,8 @@ import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.search.aggregations.bucket.composite.CompositeAggregation; -import org.elasticsearch.xpack.sql.execution.search.extractor.BucketExtractor; -import org.elasticsearch.xpack.sql.type.Schema; +import org.elasticsearch.xpack.ql.execution.search.extractor.BucketExtractor; +import org.elasticsearch.xpack.ql.type.Schema; import java.util.ArrayList; import java.util.BitSet; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/Querier.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/Querier.java index 0058726911964..03769f725c9ab 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/Querier.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/Querier.java @@ -26,24 +26,27 @@ import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation.Bucket; import org.elasticsearch.search.aggregations.bucket.filter.Filters; import org.elasticsearch.search.builder.SearchSourceBuilder; +import org.elasticsearch.xpack.ql.execution.search.FieldExtraction; +import org.elasticsearch.xpack.ql.execution.search.extractor.BucketExtractor; +import org.elasticsearch.xpack.ql.execution.search.extractor.ComputingExtractor; +import org.elasticsearch.xpack.ql.execution.search.extractor.ConstantExtractor; +import org.elasticsearch.xpack.ql.execution.search.extractor.HitExtractor; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.AggExtractorInput; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.AggPathInput; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.HitExtractorInput; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.ReferenceInput; +import org.elasticsearch.xpack.ql.index.IndexResolver; +import org.elasticsearch.xpack.ql.type.Schema; +import org.elasticsearch.xpack.ql.util.StringUtils; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.analysis.index.IndexResolver; import org.elasticsearch.xpack.sql.execution.PlanExecutor; -import org.elasticsearch.xpack.sql.execution.search.extractor.BucketExtractor; import org.elasticsearch.xpack.sql.execution.search.extractor.CompositeKeyExtractor; -import org.elasticsearch.xpack.sql.execution.search.extractor.ComputingExtractor; -import org.elasticsearch.xpack.sql.execution.search.extractor.ConstantExtractor; import org.elasticsearch.xpack.sql.execution.search.extractor.FieldHitExtractor; -import org.elasticsearch.xpack.sql.execution.search.extractor.HitExtractor; import org.elasticsearch.xpack.sql.execution.search.extractor.MetricAggExtractor; import org.elasticsearch.xpack.sql.execution.search.extractor.PivotExtractor; import org.elasticsearch.xpack.sql.execution.search.extractor.TopHitsAggExtractor; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.AggExtractorInput; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.AggPathInput; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.HitExtractorInput; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.ReferenceInput; import org.elasticsearch.xpack.sql.planner.PlanningException; import org.elasticsearch.xpack.sql.querydsl.agg.Aggs; import org.elasticsearch.xpack.sql.querydsl.container.ComputedRef; @@ -63,8 +66,6 @@ import org.elasticsearch.xpack.sql.session.Rows; import org.elasticsearch.xpack.sql.session.SchemaRowSet; import org.elasticsearch.xpack.sql.session.SqlSession; -import org.elasticsearch.xpack.sql.type.Schema; -import org.elasticsearch.xpack.sql.util.StringUtils; import java.io.IOException; import java.util.ArrayList; @@ -82,6 +83,7 @@ import static java.util.Collections.singletonList; import static org.elasticsearch.action.ActionListener.wrap; + // TODO: add retry/back-off public class Querier { @@ -139,14 +141,11 @@ public void query(List output, QueryContainer query, String index, Ac client.search(search, l); } - public static SearchRequest prepareRequest(Client client, SearchSourceBuilder source, TimeValue timeout, boolean includeFrozen, + public static SearchRequest prepareRequest(Client client, SearchSourceBuilder source, TimeValue timeout, boolean includeFrozen, String... indices) { return client.prepareSearch(indices) // always track total hits accurately - .setTrackTotalHits(true) - .setAllowPartialSearchResults(false) - .setSource(source) - .setTimeout(timeout) + .setTrackTotalHits(true).setAllowPartialSearchResults(false).setSource(source).setTimeout(timeout) .setIndicesOptions( includeFrozen ? IndexResolver.FIELD_CAPS_FROZEN_INDICES_OPTIONS : IndexResolver.FIELD_CAPS_INDICES_OPTIONS) .request(); @@ -250,7 +249,7 @@ private void consumeRowSet(RowSet rowSet) { // if the queue overflows and no limit was specified, throw an error if (data.insertWithOverflow(new Tuple<>(row, counter.getAndIncrement())) != null && noLimit) { onFailure(new SqlIllegalArgumentException( - "The default limit [{}] for aggregate sorting has been reached; please specify a LIMIT", MAXIMUM_SIZE)); + "The default limit [{}] for aggregate sorting has been reached; please specify a LIMIT", MAXIMUM_SIZE)); } } } @@ -347,7 +346,7 @@ private void handleBuckets(List buckets, SearchResponse respon } } - + /** * Dedicated listener for composite aggs/group-by results. */ @@ -355,8 +354,8 @@ static class CompositeActionListener extends BaseAggActionListener { private final boolean isPivot; - CompositeActionListener(ActionListener listener, Client client, Configuration cfg, - List output, QueryContainer query, SearchRequest request) { + CompositeActionListener(ActionListener listener, Client client, Configuration cfg, List output, + QueryContainer query, SearchRequest request) { super(listener, client, cfg, output, query, request); isPivot = query.fields().stream().anyMatch(t -> t.v1() instanceof PivotColumnRef); @@ -364,27 +363,19 @@ static class CompositeActionListener extends BaseAggActionListener { @Override protected void handleResponse(SearchResponse response, ActionListener listener) { - - Supplier makeRowSet = isPivot ? - () -> new PivotRowSet(schema, initBucketExtractors(response), mask, response, - query.sortingColumns().isEmpty() ? query.limit() : -1, null) : - () -> new SchemaCompositeAggRowSet(schema, initBucketExtractors(response), mask, response, - query.sortingColumns().isEmpty() ? query.limit() : -1); - - BiFunction makeCursor = isPivot ? - (q, r) -> { - Map lastAfterKey = r instanceof PivotRowSet ? ((PivotRowSet) r).lastAfterKey() : null; - return new PivotCursor(lastAfterKey, q, r.extractors(), r.mask(), r.remainingData(), query.shouldIncludeFrozen(), - request.indices()); - } : - (q, r) -> new CompositeAggCursor(q, r.extractors(), r.mask(), r.remainingData, query.shouldIncludeFrozen(), - request.indices()); - - CompositeAggCursor.handle(response, request.source(), - makeRowSet, - makeCursor, - () -> client.search(request, this), - listener, + + Supplier makeRowSet = isPivot ? () -> new PivotRowSet(schema, initBucketExtractors(response), mask, + response, query.sortingColumns().isEmpty() ? query.limit() : -1, null) : () -> new SchemaCompositeAggRowSet(schema, + initBucketExtractors(response), mask, response, query.sortingColumns().isEmpty() ? query.limit() : -1); + + BiFunction makeCursor = isPivot ? (q, r) -> { + Map lastAfterKey = r instanceof PivotRowSet ? ((PivotRowSet) r).lastAfterKey() : null; + return new PivotCursor(lastAfterKey, q, r.extractors(), r.mask(), r.remainingData(), query.shouldIncludeFrozen(), + request.indices()); + } : (q, r) -> new CompositeAggCursor(q, r.extractors(), r.mask(), r.remainingData, query.shouldIncludeFrozen(), + request.indices()); + + CompositeAggCursor.handle(response, request.source(), makeRowSet, makeCursor, () -> client.search(request, this), listener, schema); } } @@ -394,8 +385,8 @@ abstract static class BaseAggActionListener extends BaseActionListener { final SearchRequest request; final BitSet mask; - BaseAggActionListener(ActionListener listener, Client client, Configuration cfg, List output, - QueryContainer query, SearchRequest request) { + BaseAggActionListener(ActionListener listener, Client client, Configuration cfg, List output, QueryContainer query, + SearchRequest request) { super(listener, client, cfg, output); this.query = query; @@ -464,8 +455,8 @@ static class ScrollActionListener extends BaseActionListener { private final BitSet mask; private final boolean multiValueFieldLeniency; - ScrollActionListener(ActionListener listener, Client client, Configuration cfg, - List output, QueryContainer query) { + ScrollActionListener(ActionListener listener, Client client, Configuration cfg, List output, + QueryContainer query) { super(listener, client, cfg, output); this.query = query; this.mask = query.columnMask(output); @@ -484,15 +475,14 @@ protected void handleResponse(SearchResponse response, ActionListener list ScrollCursor.handle(response, () -> new SchemaSearchHitRowSet(schema, exts, mask, query.limit(), response), p -> listener.onResponse(p), - p -> clear(response.getScrollId(), wrap(success -> listener.onResponse(p), listener::onFailure)), - schema); + p -> clear(response.getScrollId(), wrap(success -> listener.onResponse(p), listener::onFailure)), schema); } private HitExtractor createExtractor(FieldExtraction ref) { if (ref instanceof SearchHitFieldRef) { SearchHitFieldRef f = (SearchHitFieldRef) ref; - return new FieldHitExtractor(f.name(), f.fullFieldName(), f.getDataType(), cfg.zoneId(), - f.useDocValue(), f.hitName(), multiValueFieldLeniency); + return new FieldHitExtractor(f.name(), f.fullFieldName(), f.getDataType(), cfg.zoneId(), f.useDocValue(), f.hitName(), + multiValueFieldLeniency); } if (ref instanceof ScriptFieldRef) { @@ -568,11 +558,11 @@ public void onResponse(final SearchResponse response) { protected final void cleanup(SearchResponse response, Exception ex) { if (response != null && response.getScrollId() != null) { client.prepareClearScroll().addScrollId(response.getScrollId()) - // in case of failure, report the initial exception instead of the one resulting from cleaning the scroll - .execute(ActionListener.wrap(r -> listener.onFailure(ex), e -> { - ex.addSuppressed(e); - listener.onFailure(ex); - })); + // in case of failure, report the initial exception instead of the one resulting from cleaning the scroll + .execute(ActionListener.wrap(r -> listener.onFailure(ex), e -> { + ex.addSuppressed(e); + listener.onFailure(ex); + })); } else { listener.onFailure(ex); } @@ -580,10 +570,8 @@ protected final void cleanup(SearchResponse response, Exception ex) { protected final void clear(String scrollId, ActionListener listener) { if (scrollId != null) { - client.prepareClearScroll().addScrollId(scrollId).execute( - ActionListener.wrap( - clearScrollResponse -> listener.onResponse(clearScrollResponse.isSucceeded()), - listener::onFailure)); + client.prepareClearScroll().addScrollId(scrollId).execute(ActionListener + .wrap(clearScrollResponse -> listener.onResponse(clearScrollResponse.isSucceeded()), listener::onFailure)); } else { listener.onResponse(false); } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/SchemaCompositeAggRowSet.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/SchemaCompositeAggRowSet.java index eb4d568f55707..40e3b5011b82a 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/SchemaCompositeAggRowSet.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/SchemaCompositeAggRowSet.java @@ -6,10 +6,10 @@ package org.elasticsearch.xpack.sql.execution.search; import org.elasticsearch.action.search.SearchResponse; -import org.elasticsearch.xpack.sql.execution.search.extractor.BucketExtractor; +import org.elasticsearch.xpack.ql.execution.search.extractor.BucketExtractor; +import org.elasticsearch.xpack.ql.type.Schema; import org.elasticsearch.xpack.sql.session.RowSet; import org.elasticsearch.xpack.sql.session.SchemaRowSet; -import org.elasticsearch.xpack.sql.type.Schema; import java.util.BitSet; import java.util.List; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/SchemaDelegatingRowSet.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/SchemaDelegatingRowSet.java index ccfe1ad55f25e..a1c39a3845c5e 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/SchemaDelegatingRowSet.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/SchemaDelegatingRowSet.java @@ -6,9 +6,9 @@ package org.elasticsearch.xpack.sql.execution.search; +import org.elasticsearch.xpack.ql.type.Schema; import org.elasticsearch.xpack.sql.session.RowSet; import org.elasticsearch.xpack.sql.session.SchemaRowSet; -import org.elasticsearch.xpack.sql.type.Schema; class SchemaDelegatingRowSet implements SchemaRowSet { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/SchemaSearchHitRowSet.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/SchemaSearchHitRowSet.java index 7ba7a06fd8a37..e142f8213bd3b 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/SchemaSearchHitRowSet.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/SchemaSearchHitRowSet.java @@ -6,9 +6,9 @@ package org.elasticsearch.xpack.sql.execution.search; import org.elasticsearch.action.search.SearchResponse; -import org.elasticsearch.xpack.sql.execution.search.extractor.HitExtractor; +import org.elasticsearch.xpack.ql.execution.search.extractor.HitExtractor; +import org.elasticsearch.xpack.ql.type.Schema; import org.elasticsearch.xpack.sql.session.SchemaRowSet; -import org.elasticsearch.xpack.sql.type.Schema; import java.util.BitSet; import java.util.List; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/ScrollCursor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/ScrollCursor.java index d1a8c3bbf1539..df6ad34384a96 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/ScrollCursor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/ScrollCursor.java @@ -19,11 +19,11 @@ import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.search.SearchHit; -import org.elasticsearch.xpack.sql.execution.search.extractor.HitExtractor; +import org.elasticsearch.xpack.ql.execution.search.extractor.HitExtractor; +import org.elasticsearch.xpack.ql.type.Schema; import org.elasticsearch.xpack.sql.session.Configuration; import org.elasticsearch.xpack.sql.session.Cursor; import org.elasticsearch.xpack.sql.session.Rows; -import org.elasticsearch.xpack.sql.type.Schema; import java.io.IOException; import java.util.BitSet; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/SearchHitRowSet.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/SearchHitRowSet.java index 95316e108d158..34c5ed430ce30 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/SearchHitRowSet.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/SearchHitRowSet.java @@ -10,8 +10,8 @@ import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; +import org.elasticsearch.xpack.ql.execution.search.extractor.HitExtractor; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.execution.search.extractor.HitExtractor; import java.util.ArrayList; import java.util.Arrays; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/SourceGenerator.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/SourceGenerator.java index 868dd2dcfffc0..453cdcde377ec 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/SourceGenerator.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/SourceGenerator.java @@ -15,8 +15,9 @@ import org.elasticsearch.search.sort.NestedSortBuilder; import org.elasticsearch.search.sort.ScriptSortBuilder.ScriptSortType; import org.elasticsearch.search.sort.SortBuilder; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.execution.search.QlSourceBuilder; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; import org.elasticsearch.xpack.sql.querydsl.container.AttributeSort; import org.elasticsearch.xpack.sql.querydsl.container.QueryContainer; import org.elasticsearch.xpack.sql.querydsl.container.ScoreSort; @@ -55,7 +56,7 @@ public static SearchSourceBuilder sourceBuilder(QueryContainer container, QueryB final SearchSourceBuilder source = new SearchSourceBuilder(); source.query(finalQuery); - SqlSourceBuilder sortBuilder = new SqlSourceBuilder(); + QlSourceBuilder sortBuilder = new QlSourceBuilder(); // Iterate through all the columns requested, collecting the fields that // need to be retrieved from the result documents @@ -122,12 +123,12 @@ private static void sorting(QueryContainer container, SearchSourceBuilder source sortBuilder = fieldSort(fa.name()) .missing(as.missing().position()) - .unmappedType(fa.dataType().esType); + .unmappedType(fa.dataType().esType()); if (fa.isNested()) { FieldSortBuilder fieldSort = fieldSort(fa.name()) .missing(as.missing().position()) - .unmappedType(fa.dataType().esType); + .unmappedType(fa.dataType().esType()); NestedSortBuilder newSort = new NestedSortBuilder(fa.nestedParent().name()); NestedSortBuilder nestedSort = fieldSort.getNestedSort(); @@ -164,8 +165,8 @@ private static void sorting(QueryContainer container, SearchSourceBuilder source } } - private static void optimize(SqlSourceBuilder sqlSource, SearchSourceBuilder builder) { - if (sqlSource.sourceFields.isEmpty()) { + private static void optimize(QlSourceBuilder sqlSource, SearchSourceBuilder builder) { + if (sqlSource.noSource()) { disableSource(builder); } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/CompositeKeyExtractor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/CompositeKeyExtractor.java index c4584eb80dc52..b70208c40ebd5 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/CompositeKeyExtractor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/CompositeKeyExtractor.java @@ -8,6 +8,7 @@ import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation.Bucket; +import org.elasticsearch.xpack.ql.execution.search.extractor.BucketExtractor; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; import org.elasticsearch.xpack.sql.common.io.SqlStreamInput; import org.elasticsearch.xpack.sql.querydsl.container.GroupByRef.Property; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/FieldHitExtractor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/FieldHitExtractor.java index 9f61775cedc2c..0a621eec44cd3 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/FieldHitExtractor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/FieldHitExtractor.java @@ -6,102 +6,65 @@ package org.elasticsearch.xpack.sql.execution.search.extractor; import org.elasticsearch.ElasticsearchParseException; -import org.elasticsearch.Version; -import org.elasticsearch.common.Strings; -import org.elasticsearch.common.collect.Tuple; -import org.elasticsearch.common.document.DocumentField; import org.elasticsearch.common.geo.GeoPoint; import org.elasticsearch.common.geo.GeoUtils; import org.elasticsearch.common.io.stream.StreamInput; -import org.elasticsearch.common.io.stream.StreamOutput; -import org.elasticsearch.index.mapper.IgnoredFieldMapper; -import org.elasticsearch.search.SearchHit; +import org.elasticsearch.xpack.ql.execution.search.extractor.AbstractFieldHitExtractor; +import org.elasticsearch.xpack.ql.execution.search.extractor.HitExtractor; +import org.elasticsearch.xpack.ql.type.DataType; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; import org.elasticsearch.xpack.sql.common.io.SqlStreamInput; -import org.elasticsearch.xpack.sql.expression.function.scalar.geo.GeoShape; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.sql.expression.literal.geo.GeoShape; +import org.elasticsearch.xpack.sql.type.SqlDataTypes; import org.elasticsearch.xpack.sql.util.DateUtils; import java.io.IOException; import java.time.ZoneId; -import java.util.ArrayDeque; -import java.util.Deque; import java.util.List; import java.util.Map; -import java.util.Objects; -import java.util.StringJoiner; + +import static org.elasticsearch.xpack.ql.type.DataTypes.DATETIME; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.GEO_POINT; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.GEO_SHAPE; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.SHAPE; /** * Extractor for ES fields. Works for both 'normal' fields but also nested ones (which require hitName to be set). * The latter is used as metadata in assembling the results in the tabular response. */ -public class FieldHitExtractor implements HitExtractor { +public class FieldHitExtractor extends AbstractFieldHitExtractor { - private static final Version SWITCHED_FROM_DOCVALUES_TO_SOURCE_EXTRACTION = Version.V_7_4_0; /** * Stands for {@code field}. We try to use short names for {@link HitExtractor}s * to save a few bytes when when we send them back to the user. */ static final String NAME = "f"; - /** - * Source extraction requires only the (relative) field name, without its parent path. - */ - private static String[] sourcePath(String name, boolean useDocValue, String hitName) { - return useDocValue ? Strings.EMPTY_ARRAY : Strings - .tokenizeToStringArray(hitName == null ? name : name.substring(hitName.length() + 1), "."); + public FieldHitExtractor(String name, DataType dataType, ZoneId zoneId, boolean useDocValue, boolean arrayLeniency) { + super(name, dataType, zoneId, useDocValue, arrayLeniency); } - private final String fieldName, hitName; - private final String fullFieldName; // used to look at the _ignored section of the query response for the actual full field name - private final DataType dataType; - private final ZoneId zoneId; - private final boolean useDocValue; - private final boolean arrayLeniency; - private final String[] path; - public FieldHitExtractor(String name, DataType dataType, ZoneId zoneId, boolean useDocValue) { - this(name, null, dataType, zoneId, useDocValue, null, false); - } - - public FieldHitExtractor(String name, DataType dataType, ZoneId zoneId, boolean useDocValue, boolean arrayLeniency) { - this(name, null, dataType, zoneId, useDocValue, null, arrayLeniency); + super(name, dataType, zoneId, useDocValue); } public FieldHitExtractor(String name, String fullFieldName, DataType dataType, ZoneId zoneId, boolean useDocValue, String hitName, boolean arrayLeniency) { - this.fieldName = name; - this.fullFieldName = fullFieldName; - this.dataType = dataType; - this.zoneId = zoneId; - this.useDocValue = useDocValue; - this.arrayLeniency = arrayLeniency; - this.hitName = hitName; - - if (hitName != null) { - if (!name.contains(hitName)) { - throw new SqlIllegalArgumentException("Hitname [{}] specified but not part of the name [{}]", hitName, name); - } - } + super(name, fullFieldName, dataType, zoneId, useDocValue, hitName, arrayLeniency); + } - this.path = sourcePath(fieldName, useDocValue, hitName); + public FieldHitExtractor(StreamInput in) throws IOException { + super(in); } - FieldHitExtractor(StreamInput in) throws IOException { - fieldName = in.readString(); - if (in.getVersion().onOrAfter(SWITCHED_FROM_DOCVALUES_TO_SOURCE_EXTRACTION)) { - fullFieldName = in.readOptionalString(); - } else { - fullFieldName = null; - } - String esType = in.readOptionalString(); - dataType = esType != null ? DataType.fromTypeName(esType) : null; - useDocValue = in.readBoolean(); - hitName = in.readOptionalString(); - arrayLeniency = in.readBoolean(); - path = sourcePath(fieldName, useDocValue, hitName); + @Override + protected DataType loadTypeFromName(String typeName) { + return SqlDataTypes.fromTypeName(typeName); + } - zoneId = SqlStreamInput.asSqlStream(in).zoneId(); + @Override + protected ZoneId readZoneId(StreamInput in) throws IOException { + return SqlStreamInput.asSqlStream(in).zoneId(); } @Override @@ -109,254 +72,64 @@ public String getWriteableName() { return NAME; } + // let's make sure first that we are not dealing with an geo_point represented as an array @Override - public void writeTo(StreamOutput out) throws IOException { - out.writeString(fieldName); - if (out.getVersion().onOrAfter(SWITCHED_FROM_DOCVALUES_TO_SOURCE_EXTRACTION)) { - out.writeOptionalString(fullFieldName); + protected boolean isPrimitive(List list) { + return isGeoPointArray(list); + } + + private boolean isGeoPointArray(List list) { + if (dataType() != GEO_POINT) { + return false; } - out.writeOptionalString(dataType == null ? null : dataType.typeName); - out.writeBoolean(useDocValue); - out.writeOptionalString(hitName); - out.writeBoolean(arrayLeniency); + // we expect the point in [lon lat] or [lon lat alt] formats + if (list.size() > 3 || list.size() < 1) { + return false; + } + return list.get(0) instanceof Number; } + @Override - public Object extract(SearchHit hit) { - Object value = null; - if (useDocValue) { - DocumentField field = hit.field(fieldName); - if (field != null) { - value = unwrapMultiValue(field.getValues()); - } - } else { - // if the field was ignored because it was malformed and ignore_malformed was turned on - if (fullFieldName != null - && hit.getFields().containsKey(IgnoredFieldMapper.NAME) - && dataType.isFromDocValuesOnly() == false - && dataType.isNumeric()) { - /* - * ignore_malformed makes sense for extraction from _source for numeric fields only. - * And we check here that the data type is actually a numeric one to rule out - * any non-numeric sub-fields (for which the "parent" field should actually be extracted from _source). - * For example, in the case of a malformed number, a "byte" field with "ignore_malformed: true" - * with a "text" sub-field should return "null" for the "byte" parent field and the actual malformed - * data for the "text" sub-field. Also, the _ignored section of the response contains the full field - * name, thus the need to do the comparison with that and not only the field name. - */ - if (hit.getFields().get(IgnoredFieldMapper.NAME).getValues().contains(fullFieldName)) { - return null; - } - } - Map source = hit.getSourceAsMap(); - if (source != null) { - value = extractFromSource(source); - } - } - return value; + protected boolean isFromDocValuesOnly(DataType dataType) { + return SqlDataTypes.isFromDocValuesOnly(dataType); } - private Object unwrapMultiValue(Object values) { - if (values == null) { - return null; - } - if (values instanceof List) { - List list = (List) values; - if (list.isEmpty()) { - return null; - } else { - // let's make sure first that we are not dealing with an geo_point represented as an array - if (isGeoPointArray(list) == false) { - if (list.size() == 1 || arrayLeniency) { - return unwrapMultiValue(list.get(0)); - } else { - throw new SqlIllegalArgumentException("Arrays (returned by [{}]) are not supported", fieldName); - } - } - } - } - if (dataType == DataType.GEO_POINT) { + @Override + protected Object unwrapCustomValue(Object values) { + DataType dataType = dataType(); + + if (dataType == GEO_POINT) { try { GeoPoint geoPoint = GeoUtils.parseGeoPoint(values, true); return new GeoShape(geoPoint.lon(), geoPoint.lat()); } catch (ElasticsearchParseException ex) { - throw new SqlIllegalArgumentException("Cannot parse geo_point value [{}] (returned by [{}])", values, fieldName); + throw new SqlIllegalArgumentException("Cannot parse geo_point value [{}] (returned by [{}])", values, fieldName()); } } - if (dataType == DataType.GEO_SHAPE) { + if (dataType == GEO_SHAPE) { try { return new GeoShape(values); } catch (IOException ex) { - throw new SqlIllegalArgumentException("Cannot read geo_shape value [{}] (returned by [{}])", values, fieldName); + throw new SqlIllegalArgumentException("Cannot read geo_shape value [{}] (returned by [{}])", values, fieldName()); } } - if (dataType == DataType.SHAPE) { + if (dataType == SHAPE) { try { return new GeoShape(values); } catch (IOException ex) { - throw new SqlIllegalArgumentException("Cannot read shape value [{}] (returned by [{}])", values, fieldName); + throw new SqlIllegalArgumentException("Cannot read shape value [{}] (returned by [{}])", values, fieldName()); } } if (values instanceof Map) { - throw new SqlIllegalArgumentException("Objects (returned by [{}]) are not supported", fieldName); + throw new SqlIllegalArgumentException("Objects (returned by [{}]) are not supported", fieldName()); } - if (dataType == DataType.DATETIME) { + if (dataType == DATETIME) { if (values instanceof String) { - return DateUtils.asDateTime(Long.parseLong(values.toString()), zoneId); - } - } - - // The Jackson json parser can generate for numerics - Integers, Longs, BigIntegers (if Long is not enough) - // and BigDecimal (if Double is not enough) - if (values instanceof Number || values instanceof String || values instanceof Boolean) { - if (dataType == null) { - return values; - } - if (dataType.isNumeric() && dataType.isFromDocValuesOnly() == false) { - if (dataType == DataType.DOUBLE || dataType == DataType.FLOAT || dataType == DataType.HALF_FLOAT) { - Number result = null; - try { - result = dataType.numberType().parse(values, true); - } catch(IllegalArgumentException iae) { - return null; - } - // docvalue_fields is always returning a Double value even if the underlying floating point data type is not Double - // even if we don't extract from docvalue_fields anymore, the behavior should be consistent - return result.doubleValue(); - } else { - Number result = null; - try { - result = dataType.numberType().parse(values, true); - } catch(IllegalArgumentException iae) { - return null; - } - return result; - } - } else if (dataType.isString()) { - return values.toString(); - } else { - return values; - } - } - throw new SqlIllegalArgumentException("Type {} (returned by [{}]) is not supported", values.getClass().getSimpleName(), fieldName); - } - - private boolean isGeoPointArray(List list) { - if (dataType != DataType.GEO_POINT) { - return false; - } - // we expect the point in [lon lat] or [lon lat alt] formats - if (list.size() > 3 || list.size() < 1) { - return false; - } - return list.get(0) instanceof Number; - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - Object extractFromSource(Map map) { - Object value = null; - - // Used to avoid recursive method calls - // Holds the sub-maps in the document hierarchy that are pending to be inspected along with the current index of the `path`. - Deque>> queue = new ArrayDeque<>(); - queue.add(new Tuple<>(-1, map)); - - while (!queue.isEmpty()) { - Tuple> tuple = queue.removeLast(); - int idx = tuple.v1(); - Map subMap = tuple.v2(); - - // Find all possible entries by examining all combinations under the current level ("idx") of the "path" - // e.g.: If the path == "a.b.c.d" and the idx == 0, we need to check the current subMap against the keys: - // "b", "b.c" and "b.c.d" - StringJoiner sj = new StringJoiner("."); - for (int i = idx + 1; i < path.length; i++) { - sj.add(path[i]); - Object node = subMap.get(sj.toString()); - - if (node instanceof List) { - List listOfValues = (List) node; - // we can only do this optimization until the last element of our pass since geo points are using arrays - // and we don't want to blindly ignore the second element of array if arrayLeniency is enabled - if ((i < path.length - 1) && (listOfValues.size() == 1 || arrayLeniency)) { - // this is a List with a size of 1 e.g.: {"a" : [{"b" : "value"}]} meaning the JSON is a list with one element - // or a list of values with one element e.g.: {"a": {"b" : ["value"]}} - // in case of being lenient about arrays, just extract the first value in the array - node = listOfValues.get(0); - } else { - // a List of elements with more than one value. Break early and let unwrapMultiValue deal with the list - return unwrapMultiValue(node); - } - } - - if (node instanceof Map) { - if (i < path.length - 1) { - // Add the sub-map to the queue along with the current path index - queue.add(new Tuple<>(i, (Map) node)); - } else { - // We exhausted the path and got a map - // If it is an object - it will be handled in the value extractor - value = node; - } - } else if (node != null) { - if (i < path.length - 1) { - // If we reach a concrete value without exhausting the full path, something is wrong with the mapping - // e.g.: map is {"a" : { "b" : "value }} and we are looking for a path: "a.b.c.d" - throw new SqlIllegalArgumentException("Cannot extract value [{}] from source", fieldName); - } - if (value != null) { - // A value has already been found so this means that there are more than one - // values in the document for the same path but different hierarchy. - // e.g.: {"a" : {"b" : {"c" : "value"}}}, {"a.b" : {"c" : "value"}}, ... - throw new SqlIllegalArgumentException("Multiple values (returned by [{}]) are not supported", fieldName); - } - value = node; - } + return DateUtils.asDateTime(Long.parseLong(values.toString()), zoneId()); } } - return unwrapMultiValue(value); - } - @Override - public String hitName() { - return hitName; - } - - public String fieldName() { - return fieldName; - } - - public String fullFieldName() { - return fullFieldName; - } - - public ZoneId zoneId() { - return zoneId; - } - - DataType dataType() { - return dataType; - } - - @Override - public String toString() { - return fieldName + "@" + hitName + "@" + zoneId; - } - - @Override - public boolean equals(Object obj) { - if (obj == null || obj.getClass() != getClass()) { - return false; - } - FieldHitExtractor other = (FieldHitExtractor) obj; - return fieldName.equals(other.fieldName) - && hitName.equals(other.hitName) - && useDocValue == other.useDocValue - && arrayLeniency == other.arrayLeniency; - } - - @Override - public int hashCode() { - return Objects.hash(fieldName, useDocValue, hitName, arrayLeniency); + return null; } -} +} \ No newline at end of file diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/MetricAggExtractor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/MetricAggExtractor.java index 007c7a26c4966..3b3eaaffa16a4 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/MetricAggExtractor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/MetricAggExtractor.java @@ -19,6 +19,7 @@ import org.elasticsearch.search.aggregations.metrics.InternalSum; import org.elasticsearch.search.aggregations.metrics.InternalTDigestPercentileRanks; import org.elasticsearch.search.aggregations.metrics.InternalTDigestPercentiles; +import org.elasticsearch.xpack.ql.execution.search.extractor.BucketExtractor; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; import org.elasticsearch.xpack.sql.common.io.SqlStreamInput; import org.elasticsearch.xpack.sql.querydsl.agg.Aggs; @@ -46,7 +47,7 @@ public MetricAggExtractor(String name, String property, String innerKey, ZoneId this.name = name; this.property = property; this.innerKey = innerKey; - this. isDateTimeBased =isDateTimeBased; + this.isDateTimeBased = isDateTimeBased; this.zoneId = zoneId; } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/PivotExtractor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/PivotExtractor.java index e7c1b8dfa302c..c3cb199c63dee 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/PivotExtractor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/PivotExtractor.java @@ -9,6 +9,7 @@ import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation.Bucket; +import org.elasticsearch.xpack.ql.execution.search.extractor.BucketExtractor; import java.io.IOException; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/ScoreExtractor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/ScoreExtractor.java index d46c543037f35..c37fb3dd35c63 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/ScoreExtractor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/ScoreExtractor.java @@ -7,6 +7,7 @@ import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.search.SearchHit; +import org.elasticsearch.xpack.ql.execution.search.extractor.HitExtractor; import java.io.IOException; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/BucketExtractors.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/SqlBucketExtractors.java similarity index 80% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/BucketExtractors.java rename to x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/SqlBucketExtractors.java index bcbbce8e4576a..8b711b87578ec 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/BucketExtractors.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/SqlBucketExtractors.java @@ -3,29 +3,30 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ + package org.elasticsearch.xpack.sql.execution.search.extractor; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.NamedWriteableRegistry.Entry; +import org.elasticsearch.xpack.ql.execution.search.extractor.BucketExtractor; +import org.elasticsearch.xpack.ql.execution.search.extractor.BucketExtractors; import java.util.ArrayList; import java.util.List; -public final class BucketExtractors { - - private BucketExtractors() {} +public class SqlBucketExtractors { + + private SqlBucketExtractors() {} /** * All of the named writeables needed to deserialize the instances of * {@linkplain BucketExtractor}s. */ public static List getNamedWriteables() { - List entries = new ArrayList<>(); + List entries = new ArrayList<>(BucketExtractors.getNamedWriteables()); entries.add(new Entry(BucketExtractor.class, CompositeKeyExtractor.NAME, CompositeKeyExtractor::new)); - entries.add(new Entry(BucketExtractor.class, ComputingExtractor.NAME, ComputingExtractor::new)); entries.add(new Entry(BucketExtractor.class, MetricAggExtractor.NAME, MetricAggExtractor::new)); entries.add(new Entry(BucketExtractor.class, TopHitsAggExtractor.NAME, TopHitsAggExtractor::new)); - entries.add(new Entry(BucketExtractor.class, ConstantExtractor.NAME, ConstantExtractor::new)); entries.add(new Entry(BucketExtractor.class, PivotExtractor.NAME, PivotExtractor::new)); return entries; } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/SqlHitExtractors.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/SqlHitExtractors.java new file mode 100644 index 0000000000000..d0938fa261f6c --- /dev/null +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/SqlHitExtractors.java @@ -0,0 +1,31 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.sql.execution.search.extractor; + +import org.elasticsearch.common.io.stream.NamedWriteableRegistry; +import org.elasticsearch.common.io.stream.NamedWriteableRegistry.Entry; +import org.elasticsearch.xpack.ql.execution.search.extractor.HitExtractor; +import org.elasticsearch.xpack.ql.execution.search.extractor.HitExtractors; + +import java.util.ArrayList; +import java.util.List; + +public final class SqlHitExtractors { + + private SqlHitExtractors() {} + + /** + * All of the named writeables needed to deserialize the instances of + * {@linkplain HitExtractor}. + */ + public static List getNamedWriteables() { + List entries = new ArrayList<>(HitExtractors.getNamedWriteables()); + entries.add(new Entry(HitExtractor.class, FieldHitExtractor.NAME, FieldHitExtractor::new)); + entries.add(new Entry(HitExtractor.class, ScoreExtractor.NAME, in -> ScoreExtractor.INSTANCE)); + return entries; + } +} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/TopHitsAggExtractor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/TopHitsAggExtractor.java index b315b4ce16b5a..0c746991d91e9 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/TopHitsAggExtractor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/execution/search/extractor/TopHitsAggExtractor.java @@ -9,9 +9,11 @@ import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation.Bucket; import org.elasticsearch.search.aggregations.metrics.InternalTopHits; +import org.elasticsearch.xpack.ql.execution.search.extractor.BucketExtractor; +import org.elasticsearch.xpack.ql.type.DataType; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; import org.elasticsearch.xpack.sql.common.io.SqlStreamInput; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.sql.type.SqlDataTypes; import org.elasticsearch.xpack.sql.util.DateUtils; import java.io.IOException; @@ -34,14 +36,14 @@ public TopHitsAggExtractor(String name, DataType fieldDataType, ZoneId zoneId) { TopHitsAggExtractor(StreamInput in) throws IOException { name = in.readString(); - fieldDataType = in.readEnum(DataType.class); + fieldDataType = SqlDataTypes.fromTypeName(in.readString()); zoneId = SqlStreamInput.asSqlStream(in).zoneId(); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(name); - out.writeEnum(fieldDataType); + out.writeString(fieldDataType.typeName()); } String name() { @@ -73,9 +75,9 @@ public Object extract(Bucket bucket) { } Object value = agg.getHits().getAt(0).getFields().values().iterator().next().getValue(); - if (fieldDataType.isDateBased()) { + if (SqlDataTypes.isDateBased(fieldDataType)) { return DateUtils.asDateTime(Long.parseLong(value.toString()), zoneId); - } else if (fieldDataType.isTimeBased()) { + } else if (SqlDataTypes.isTimeBased(fieldDataType)) { return DateUtils.asTimeOnly(Long.parseLong(value.toString()), zoneId); } else { return value; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/Exists.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/Exists.java index d481d8e115fd3..a115b9f2b8eec 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/Exists.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/Exists.java @@ -5,10 +5,14 @@ */ package org.elasticsearch.xpack.sql.expression; -import org.elasticsearch.xpack.sql.plan.logical.LogicalPlan; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.NameId; +import org.elasticsearch.xpack.ql.expression.Nullability; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; + +import static org.elasticsearch.xpack.ql.type.DataTypes.BOOLEAN; public class Exists extends SubQueryExpression { @@ -32,7 +36,7 @@ protected SubQueryExpression clone(LogicalPlan newQuery) { @Override public DataType dataType() { - return DataType.BOOLEAN; + return BOOLEAN; } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/Foldables.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/Foldables.java index c7297edb126ad..067b85ae30d7c 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/Foldables.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/Foldables.java @@ -5,9 +5,11 @@ */ package org.elasticsearch.xpack.sql.expression; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.DataTypeConversion; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; +import org.elasticsearch.xpack.sql.type.SqlDataTypeConverter; import java.util.ArrayList; import java.util.Collection; @@ -18,33 +20,33 @@ public abstract class Foldables { @SuppressWarnings("unchecked") - public static T valueOf(Expression e, DataType to) { + private static T valueOf(Expression e, DataType to) { if (e.foldable()) { - return (T) DataTypeConversion.conversionFor(e.dataType(), to).convert(e.fold()); + return (T) SqlDataTypeConverter.convert(e.fold(), to); } - throw new SqlIllegalArgumentException("Cannot determine value for {}", e); + throw new QlIllegalArgumentException("Cannot determine value for {}", e); } public static Object valueOf(Expression e) { if (e.foldable()) { return e.fold(); } - throw new SqlIllegalArgumentException("Cannot determine value for {}", e); + throw new QlIllegalArgumentException("Cannot determine value for {}", e); } public static Integer intValueOf(Expression e) { - return valueOf(e, DataType.INTEGER); + return valueOf(e, DataTypes.INTEGER); } public static double doubleValueOf(Expression e) { - return valueOf(e, DataType.DOUBLE); + return valueOf(e, DataTypes.DOUBLE); } public static List valuesOf(List list, DataType to) { return foldTo(list, to, new ArrayList<>(list.size())); } - public static Set valuesOfNoDuplicates(List list, DataType to) { + public static Set valuesUnique(List list, DataType to) { return foldTo(list, to, new LinkedHashSet<>(list.size())); } @@ -56,6 +58,6 @@ private static > C foldTo(Collection expr } public static List doubleValuesOf(List list) { - return valuesOf(list, DataType.DOUBLE); + return valuesOf(list, DataTypes.DOUBLE); } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/ScalarSubquery.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/ScalarSubquery.java index cba61814e8f51..36fa3d3ffa019 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/ScalarSubquery.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/ScalarSubquery.java @@ -5,10 +5,12 @@ */ package org.elasticsearch.xpack.sql.expression; -import org.elasticsearch.xpack.sql.plan.logical.LogicalPlan; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.NameId; +import org.elasticsearch.xpack.ql.expression.Nullability; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; public class ScalarSubquery extends SubQueryExpression { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/SqlTypeResolutions.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/SqlTypeResolutions.java new file mode 100644 index 0000000000000..1d5af2446fb05 --- /dev/null +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/SqlTypeResolutions.java @@ -0,0 +1,41 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.sql.expression; + +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression.TypeResolution; +import org.elasticsearch.xpack.ql.expression.Expressions.ParamOrdinal; +import org.elasticsearch.xpack.sql.type.SqlDataTypes; + +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isType; + +public final class SqlTypeResolutions { + + private SqlTypeResolutions() {} + + public static TypeResolution isDate(Expression e, String operationName, ParamOrdinal paramOrd) { + return isType(e, SqlDataTypes::isDateBased, operationName, paramOrd, "date", "datetime"); + } + + public static TypeResolution isDateOrTime(Expression e, String operationName, ParamOrdinal paramOrd) { + return isType(e, SqlDataTypes::isDateOrTimeBased, operationName, paramOrd, "date", "time", "datetime"); + } + + public static TypeResolution isNumericOrDate(Expression e, String operationName, ParamOrdinal paramOrd) { + return isType(e, dt -> dt.isNumeric() || SqlDataTypes.isDateBased(dt), operationName, paramOrd, + "date", "datetime", "numeric"); + } + + public static TypeResolution isNumericOrDateOrTime(Expression e, String operationName, ParamOrdinal paramOrd) { + return isType(e, dt -> dt.isNumeric() || SqlDataTypes.isDateOrTimeBased(dt), operationName, paramOrd, + "date", "time", "datetime", "numeric"); + } + + public static TypeResolution isGeo(Expression e, String operationName, ParamOrdinal paramOrd) { + return isType(e, SqlDataTypes::isGeo, operationName, paramOrd, "geo_point", "geo_shape"); + } +} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/SubQueryExpression.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/SubQueryExpression.java index 250e5de721846..6ac29ff493d0d 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/SubQueryExpression.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/SubQueryExpression.java @@ -5,8 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression; -import org.elasticsearch.xpack.sql.plan.logical.LogicalPlan; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.NameId; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Collections; import java.util.List; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/FunctionRegistry.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/FunctionRegistry.java deleted file mode 100644 index cff6fd13a0733..0000000000000 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/FunctionRegistry.java +++ /dev/null @@ -1,653 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -package org.elasticsearch.xpack.sql.expression.function; - -import org.elasticsearch.common.Strings; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.function.aggregate.Avg; -import org.elasticsearch.xpack.sql.expression.function.aggregate.Count; -import org.elasticsearch.xpack.sql.expression.function.aggregate.First; -import org.elasticsearch.xpack.sql.expression.function.aggregate.Kurtosis; -import org.elasticsearch.xpack.sql.expression.function.aggregate.Last; -import org.elasticsearch.xpack.sql.expression.function.aggregate.Max; -import org.elasticsearch.xpack.sql.expression.function.aggregate.MedianAbsoluteDeviation; -import org.elasticsearch.xpack.sql.expression.function.aggregate.Min; -import org.elasticsearch.xpack.sql.expression.function.aggregate.Percentile; -import org.elasticsearch.xpack.sql.expression.function.aggregate.PercentileRank; -import org.elasticsearch.xpack.sql.expression.function.aggregate.Skewness; -import org.elasticsearch.xpack.sql.expression.function.aggregate.StddevPop; -import org.elasticsearch.xpack.sql.expression.function.aggregate.Sum; -import org.elasticsearch.xpack.sql.expression.function.aggregate.SumOfSquares; -import org.elasticsearch.xpack.sql.expression.function.aggregate.TopHits; -import org.elasticsearch.xpack.sql.expression.function.aggregate.VarPop; -import org.elasticsearch.xpack.sql.expression.function.grouping.Histogram; -import org.elasticsearch.xpack.sql.expression.function.scalar.Cast; -import org.elasticsearch.xpack.sql.expression.function.scalar.Database; -import org.elasticsearch.xpack.sql.expression.function.scalar.User; -import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.CurrentDate; -import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.CurrentDateTime; -import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.CurrentTime; -import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateAdd; -import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateDiff; -import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DatePart; -import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTrunc; -import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DayName; -import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DayOfMonth; -import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DayOfWeek; -import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DayOfYear; -import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.HourOfDay; -import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.IsoDayOfWeek; -import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.IsoWeekOfYear; -import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.MinuteOfDay; -import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.MinuteOfHour; -import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.MonthName; -import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.MonthOfYear; -import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.Quarter; -import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.SecondOfMinute; -import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.WeekOfYear; -import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.Year; -import org.elasticsearch.xpack.sql.expression.function.scalar.geo.StAswkt; -import org.elasticsearch.xpack.sql.expression.function.scalar.geo.StDistance; -import org.elasticsearch.xpack.sql.expression.function.scalar.geo.StGeometryType; -import org.elasticsearch.xpack.sql.expression.function.scalar.geo.StWkttosql; -import org.elasticsearch.xpack.sql.expression.function.scalar.geo.StX; -import org.elasticsearch.xpack.sql.expression.function.scalar.geo.StY; -import org.elasticsearch.xpack.sql.expression.function.scalar.geo.StZ; -import org.elasticsearch.xpack.sql.expression.function.scalar.math.ACos; -import org.elasticsearch.xpack.sql.expression.function.scalar.math.ASin; -import org.elasticsearch.xpack.sql.expression.function.scalar.math.ATan; -import org.elasticsearch.xpack.sql.expression.function.scalar.math.ATan2; -import org.elasticsearch.xpack.sql.expression.function.scalar.math.Abs; -import org.elasticsearch.xpack.sql.expression.function.scalar.math.Cbrt; -import org.elasticsearch.xpack.sql.expression.function.scalar.math.Ceil; -import org.elasticsearch.xpack.sql.expression.function.scalar.math.Cos; -import org.elasticsearch.xpack.sql.expression.function.scalar.math.Cosh; -import org.elasticsearch.xpack.sql.expression.function.scalar.math.Cot; -import org.elasticsearch.xpack.sql.expression.function.scalar.math.Degrees; -import org.elasticsearch.xpack.sql.expression.function.scalar.math.E; -import org.elasticsearch.xpack.sql.expression.function.scalar.math.Exp; -import org.elasticsearch.xpack.sql.expression.function.scalar.math.Expm1; -import org.elasticsearch.xpack.sql.expression.function.scalar.math.Floor; -import org.elasticsearch.xpack.sql.expression.function.scalar.math.Log; -import org.elasticsearch.xpack.sql.expression.function.scalar.math.Log10; -import org.elasticsearch.xpack.sql.expression.function.scalar.math.Pi; -import org.elasticsearch.xpack.sql.expression.function.scalar.math.Power; -import org.elasticsearch.xpack.sql.expression.function.scalar.math.Radians; -import org.elasticsearch.xpack.sql.expression.function.scalar.math.Random; -import org.elasticsearch.xpack.sql.expression.function.scalar.math.Round; -import org.elasticsearch.xpack.sql.expression.function.scalar.math.Sign; -import org.elasticsearch.xpack.sql.expression.function.scalar.math.Sin; -import org.elasticsearch.xpack.sql.expression.function.scalar.math.Sinh; -import org.elasticsearch.xpack.sql.expression.function.scalar.math.Sqrt; -import org.elasticsearch.xpack.sql.expression.function.scalar.math.Tan; -import org.elasticsearch.xpack.sql.expression.function.scalar.math.Truncate; -import org.elasticsearch.xpack.sql.expression.function.scalar.string.Ascii; -import org.elasticsearch.xpack.sql.expression.function.scalar.string.BitLength; -import org.elasticsearch.xpack.sql.expression.function.scalar.string.Char; -import org.elasticsearch.xpack.sql.expression.function.scalar.string.CharLength; -import org.elasticsearch.xpack.sql.expression.function.scalar.string.Concat; -import org.elasticsearch.xpack.sql.expression.function.scalar.string.Insert; -import org.elasticsearch.xpack.sql.expression.function.scalar.string.LCase; -import org.elasticsearch.xpack.sql.expression.function.scalar.string.LTrim; -import org.elasticsearch.xpack.sql.expression.function.scalar.string.Left; -import org.elasticsearch.xpack.sql.expression.function.scalar.string.Length; -import org.elasticsearch.xpack.sql.expression.function.scalar.string.Locate; -import org.elasticsearch.xpack.sql.expression.function.scalar.string.OctetLength; -import org.elasticsearch.xpack.sql.expression.function.scalar.string.Position; -import org.elasticsearch.xpack.sql.expression.function.scalar.string.RTrim; -import org.elasticsearch.xpack.sql.expression.function.scalar.string.Repeat; -import org.elasticsearch.xpack.sql.expression.function.scalar.string.Replace; -import org.elasticsearch.xpack.sql.expression.function.scalar.string.Right; -import org.elasticsearch.xpack.sql.expression.function.scalar.string.Space; -import org.elasticsearch.xpack.sql.expression.function.scalar.string.Substring; -import org.elasticsearch.xpack.sql.expression.function.scalar.string.UCase; -import org.elasticsearch.xpack.sql.expression.predicate.conditional.Case; -import org.elasticsearch.xpack.sql.expression.predicate.conditional.Coalesce; -import org.elasticsearch.xpack.sql.expression.predicate.conditional.Greatest; -import org.elasticsearch.xpack.sql.expression.predicate.conditional.IfNull; -import org.elasticsearch.xpack.sql.expression.predicate.conditional.Iif; -import org.elasticsearch.xpack.sql.expression.predicate.conditional.Least; -import org.elasticsearch.xpack.sql.expression.predicate.conditional.NullIf; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Mod; -import org.elasticsearch.xpack.sql.parser.ParsingException; -import org.elasticsearch.xpack.sql.session.Configuration; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.util.Check; - -import java.time.ZoneId; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Map.Entry; -import java.util.function.BiFunction; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - -import static java.util.Collections.emptyList; -import static java.util.Collections.unmodifiableList; -import static java.util.stream.Collectors.toList; - -public class FunctionRegistry { - - // list of functions grouped by type of functions (aggregate, statistics, math etc) and ordered alphabetically inside each group - // a single function will have one entry for itself with its name associated to its instance and, also, one entry for each alias - // it has with the alias name associated to the FunctionDefinition instance - private final Map defs = new LinkedHashMap<>(); - private final Map aliases = new HashMap<>(); - - /** - * Constructor to build with the default list of functions. - */ - public FunctionRegistry() { - defineDefaultFunctions(); - } - - /** - * Constructor specifying alternate functions for testing. - */ - FunctionRegistry(FunctionDefinition... functions) { - addToMap(functions); - } - - private void defineDefaultFunctions() { - // Aggregate functions - addToMap(def(Avg.class, Avg::new, "AVG"), - def(Count.class, Count::new, "COUNT"), - def(First.class, First::new, "FIRST", "FIRST_VALUE"), - def(Last.class, Last::new, "LAST", "LAST_VALUE"), - def(Max.class, Max::new, "MAX"), - def(Min.class, Min::new, "MIN"), - def(Sum.class, Sum::new, "SUM")); - // Statistics - addToMap( - def(Kurtosis.class, Kurtosis::new, "KURTOSIS"), - def(MedianAbsoluteDeviation.class, MedianAbsoluteDeviation::new, "MAD"), - def(Percentile.class, Percentile::new, "PERCENTILE"), - def(PercentileRank.class, PercentileRank::new, "PERCENTILE_RANK"), - def(Skewness.class, Skewness::new, "SKEWNESS"), - def(StddevPop.class, StddevPop::new, "STDDEV_POP"), - def(SumOfSquares.class, SumOfSquares::new, "SUM_OF_SQUARES"), - def(VarPop.class, VarPop::new,"VAR_POP") - ); - // histogram - addToMap(def(Histogram.class, Histogram::new, "HISTOGRAM")); - // Scalar functions - // Conditional - addToMap(def(Case.class, Case::new, "CASE"), - def(Coalesce.class, Coalesce::new, "COALESCE"), - def(Iif.class, Iif::new, "IIF"), - def(IfNull.class, IfNull::new, "IFNULL", "ISNULL", "NVL"), - def(NullIf.class, NullIf::new, "NULLIF"), - def(Greatest.class, Greatest::new, "GREATEST"), - def(Least.class, Least::new, "LEAST")); - // Date - addToMap(def(CurrentDate.class, CurrentDate::new, "CURRENT_DATE", "CURDATE", "TODAY"), - def(CurrentTime.class, CurrentTime::new, "CURRENT_TIME", "CURTIME"), - def(CurrentDateTime.class, CurrentDateTime::new, "CURRENT_TIMESTAMP", "NOW"), - def(DayName.class, DayName::new, "DAY_NAME", "DAYNAME"), - def(DayOfMonth.class, DayOfMonth::new, "DAY_OF_MONTH", "DAYOFMONTH", "DAY", "DOM"), - def(DayOfWeek.class, DayOfWeek::new, "DAY_OF_WEEK", "DAYOFWEEK", "DOW"), - def(DayOfYear.class, DayOfYear::new, "DAY_OF_YEAR", "DAYOFYEAR", "DOY"), - def(DateAdd.class, DateAdd::new, "DATEADD", "DATE_ADD", "TIMESTAMPADD", "TIMESTAMP_ADD"), - def(DateDiff.class, DateDiff::new, "DATEDIFF", "DATE_DIFF", "TIMESTAMPDIFF", "TIMESTAMP_DIFF"), - def(DatePart.class, DatePart::new, "DATEPART", "DATE_PART"), - def(DateTrunc.class, DateTrunc::new, "DATETRUNC", "DATE_TRUNC"), - def(HourOfDay.class, HourOfDay::new, "HOUR_OF_DAY", "HOUR"), - def(IsoDayOfWeek.class, IsoDayOfWeek::new, "ISO_DAY_OF_WEEK", "ISODAYOFWEEK", "ISODOW", "IDOW"), - def(IsoWeekOfYear.class, IsoWeekOfYear::new, "ISO_WEEK_OF_YEAR", "ISOWEEKOFYEAR", "ISOWEEK", "IWOY", "IW"), - def(MinuteOfDay.class, MinuteOfDay::new, "MINUTE_OF_DAY"), - def(MinuteOfHour.class, MinuteOfHour::new, "MINUTE_OF_HOUR", "MINUTE"), - def(MonthName.class, MonthName::new, "MONTH_NAME", "MONTHNAME"), - def(MonthOfYear.class, MonthOfYear::new, "MONTH_OF_YEAR", "MONTH"), - def(SecondOfMinute.class, SecondOfMinute::new, "SECOND_OF_MINUTE", "SECOND"), - def(Quarter.class, Quarter::new, "QUARTER"), - def(Year.class, Year::new, "YEAR"), - def(WeekOfYear.class, WeekOfYear::new, "WEEK_OF_YEAR", "WEEK")); - // Math - addToMap(def(Abs.class, Abs::new, "ABS"), - def(ACos.class, ACos::new, "ACOS"), - def(ASin.class, ASin::new, "ASIN"), - def(ATan.class, ATan::new, "ATAN"), - def(ATan2.class, ATan2::new, "ATAN2"), - def(Cbrt.class, Cbrt::new, "CBRT"), - def(Ceil.class, Ceil::new, "CEIL", "CEILING"), - def(Cos.class, Cos::new, "COS"), - def(Cosh.class, Cosh::new, "COSH"), - def(Cot.class, Cot::new, "COT"), - def(Degrees.class, Degrees::new, "DEGREES"), - def(E.class, E::new, "E"), - def(Exp.class, Exp::new, "EXP"), - def(Expm1.class, Expm1::new, "EXPM1"), - def(Floor.class, Floor::new, "FLOOR"), - def(Log.class, Log::new, "LOG"), - def(Log10.class, Log10::new, "LOG10"), - // SQL and ODBC require MOD as a _function_ - def(Mod.class, Mod::new, "MOD"), - def(Pi.class, Pi::new, "PI"), - def(Power.class, Power::new, "POWER"), - def(Radians.class, Radians::new, "RADIANS"), - def(Random.class, Random::new, "RANDOM", "RAND"), - def(Round.class, Round::new, "ROUND"), - def(Sign.class, Sign::new, "SIGN", "SIGNUM"), - def(Sin.class, Sin::new, "SIN"), - def(Sinh.class, Sinh::new, "SINH"), - def(Sqrt.class, Sqrt::new, "SQRT"), - def(Tan.class, Tan::new, "TAN"), - def(Truncate.class, Truncate::new, "TRUNCATE", "TRUNC")); - // String - addToMap(def(Ascii.class, Ascii::new, "ASCII"), - def(BitLength.class, BitLength::new, "BIT_LENGTH"), - def(Char.class, Char::new, "CHAR"), - def(CharLength.class, CharLength::new, "CHAR_LENGTH", "CHARACTER_LENGTH"), - def(Concat.class, Concat::new, "CONCAT"), - def(Insert.class, Insert::new, "INSERT"), - def(LCase.class, LCase::new, "LCASE"), - def(Left.class, Left::new, "LEFT"), - def(Length.class, Length::new, "LENGTH"), - def(Locate.class, Locate::new, "LOCATE"), - def(LTrim.class, LTrim::new, "LTRIM"), - def(OctetLength.class, OctetLength::new, "OCTET_LENGTH"), - def(Position.class, Position::new, "POSITION"), - def(Repeat.class, Repeat::new, "REPEAT"), - def(Replace.class, Replace::new, "REPLACE"), - def(Right.class, Right::new, "RIGHT"), - def(RTrim.class, RTrim::new, "RTRIM"), - def(Space.class, Space::new, "SPACE"), - def(Substring.class, Substring::new, "SUBSTRING"), - def(UCase.class, UCase::new, "UCASE")); - - // DataType conversion - addToMap(def(Cast.class, Cast::new, "CAST", "CONVERT")); - // Scalar "meta" functions - addToMap(def(Database.class, Database::new, "DATABASE"), - def(User.class, User::new, "USER")); - - // Geo Functions - addToMap(def(StAswkt.class, StAswkt::new, "ST_ASWKT", "ST_ASTEXT"), - def(StDistance.class, StDistance::new, "ST_DISTANCE"), - def(StWkttosql.class, StWkttosql::new, "ST_WKTTOSQL", "ST_GEOMFROMTEXT"), - def(StGeometryType.class, StGeometryType::new, "ST_GEOMETRYTYPE"), - def(StX.class, StX::new, "ST_X"), - def(StY.class, StY::new, "ST_Y"), - def(StZ.class, StZ::new, "ST_Z") - ); - - // Special - addToMap(def(Score.class, Score::new, "SCORE")); - } - - void addToMap(FunctionDefinition...functions) { - // temporary map to hold [function_name/alias_name : function instance] - Map batchMap = new HashMap<>(); - for (FunctionDefinition f : functions) { - batchMap.put(f.name(), f); - for (String alias : f.aliases()) { - Object old = batchMap.put(alias, f); - if (old != null || defs.containsKey(alias)) { - throw new SqlIllegalArgumentException("alias [" + alias + "] is used by " - + "[" + (old != null ? old : defs.get(alias).name()) + "] and [" + f.name() + "]"); - } - aliases.put(alias, f.name()); - } - } - // sort the temporary map by key name and add it to the global map of functions - defs.putAll(batchMap.entrySet().stream() - .sorted(Map.Entry.comparingByKey()) - .collect(Collectors., String, - FunctionDefinition, LinkedHashMap> toMap(Map.Entry::getKey, Map.Entry::getValue, - (oldValue, newValue) -> oldValue, LinkedHashMap::new))); - } - - public FunctionDefinition resolveFunction(String functionName) { - FunctionDefinition def = defs.get(functionName); - if (def == null) { - throw new SqlIllegalArgumentException( - "Cannot find function {}; this should have been caught during analysis", - functionName); - } - return def; - } - - public String resolveAlias(String alias) { - String upperCase = alias.toUpperCase(Locale.ROOT); - return aliases.getOrDefault(upperCase, upperCase); - } - - public boolean functionExists(String functionName) { - return defs.containsKey(functionName); - } - - public Collection listFunctions() { - // It is worth double checking if we need this copy. These are immutable anyway. - return defs.entrySet().stream() - .map(e -> new FunctionDefinition(e.getKey(), emptyList(), - e.getValue().clazz(), e.getValue().extractViable(), e.getValue().builder())) - .collect(toList()); - } - - public Collection listFunctions(String pattern) { - // It is worth double checking if we need this copy. These are immutable anyway. - Pattern p = Strings.hasText(pattern) ? Pattern.compile(pattern.toUpperCase(Locale.ROOT)) : null; - return defs.entrySet().stream() - .filter(e -> p == null || p.matcher(e.getKey()).matches()) - .map(e -> new FunctionDefinition(e.getKey(), emptyList(), - e.getValue().clazz(), e.getValue().extractViable(), e.getValue().builder())) - .collect(toList()); - } - - /** - * Build a {@linkplain FunctionDefinition} for a no-argument function that - * is not aware of time zone and does not support {@code DISTINCT}. - */ - static FunctionDefinition def(Class function, - java.util.function.Function ctorRef, String... names) { - FunctionBuilder builder = (source, children, distinct, cfg) -> { - if (false == children.isEmpty()) { - throw new SqlIllegalArgumentException("expects no arguments"); - } - if (distinct) { - throw new SqlIllegalArgumentException("does not support DISTINCT yet it was specified"); - } - return ctorRef.apply(source); - }; - return def(function, builder, false, names); - } - - /** - * Build a {@linkplain FunctionDefinition} for a no-argument function that - * is not aware of time zone, does not support {@code DISTINCT} and needs - * the cluster name (DATABASE()) or the user name (USER()). - */ - @SuppressWarnings("overloads") - static FunctionDefinition def(Class function, - ConfigurationAwareFunctionBuilder ctorRef, String... names) { - FunctionBuilder builder = (source, children, distinct, cfg) -> { - if (false == children.isEmpty()) { - throw new SqlIllegalArgumentException("expects no arguments"); - } - if (distinct) { - throw new SqlIllegalArgumentException("does not support DISTINCT yet it was specified"); - } - return ctorRef.build(source, cfg); - }; - return def(function, builder, false, names); - } - - interface ConfigurationAwareFunctionBuilder { - T build(Source source, Configuration configuration); - } - - /** - * Build a {@linkplain FunctionDefinition} for a one-argument function that - * is not aware of time zone, does not support {@code DISTINCT} and needs - * the configuration object. - */ - @SuppressWarnings("overloads") - static FunctionDefinition def(Class function, - UnaryConfigurationAwareFunctionBuilder ctorRef, String... names) { - FunctionBuilder builder = (source, children, distinct, cfg) -> { - if (children.size() > 1) { - throw new SqlIllegalArgumentException("expects exactly one argument"); - } - if (distinct) { - throw new SqlIllegalArgumentException("does not support DISTINCT yet it was specified"); - } - Expression ex = children.size() == 1 ? children.get(0) : null; - return ctorRef.build(source, ex, cfg); - }; - return def(function, builder, false, names); - } - - interface UnaryConfigurationAwareFunctionBuilder { - T build(Source source, Expression exp, Configuration configuration); - } - - - /** - * Build a {@linkplain FunctionDefinition} for a unary function that is not - * aware of time zone and does not support {@code DISTINCT}. - */ - @SuppressWarnings("overloads") // These are ambiguous if you aren't using ctor references but we always do - static FunctionDefinition def(Class function, - BiFunction ctorRef, String... names) { - FunctionBuilder builder = (source, children, distinct, cfg) -> { - if (children.size() != 1) { - throw new SqlIllegalArgumentException("expects exactly one argument"); - } - if (distinct) { - throw new SqlIllegalArgumentException("does not support DISTINCT yet it was specified"); - } - return ctorRef.apply(source, children.get(0)); - }; - return def(function, builder, false, names); - } - - /** - * Build a {@linkplain FunctionDefinition} for multi-arg function that - * is not aware of time zone and does not support {@code DISTINCT}. - */ - @SuppressWarnings("overloads") // These are ambiguous if you aren't using ctor references but we always do - static FunctionDefinition def(Class function, - MultiFunctionBuilder ctorRef, String... names) { - FunctionBuilder builder = (source, children, distinct, cfg) -> { - if (distinct) { - throw new SqlIllegalArgumentException("does not support DISTINCT yet it was specified"); - } - return ctorRef.build(source, children); - }; - return def(function, builder, false, names); - } - - interface MultiFunctionBuilder { - T build(Source source, List children); - } - - /** - * Build a {@linkplain FunctionDefinition} for a unary function that is not - * aware of time zone but does support {@code DISTINCT}. - */ - @SuppressWarnings("overloads") // These are ambiguous if you aren't using ctor references but we always do - static FunctionDefinition def(Class function, - DistinctAwareUnaryFunctionBuilder ctorRef, String... names) { - FunctionBuilder builder = (source, children, distinct, cfg) -> { - if (children.size() != 1) { - throw new SqlIllegalArgumentException("expects exactly one argument"); - } - return ctorRef.build(source, children.get(0), distinct); - }; - return def(function, builder, false, names); - } - - interface DistinctAwareUnaryFunctionBuilder { - T build(Source source, Expression target, boolean distinct); - } - - /** - * Build a {@linkplain FunctionDefinition} for a unary function that - * operates on a datetime. - */ - @SuppressWarnings("overloads") // These are ambiguous if you aren't using ctor references but we always do - static FunctionDefinition def(Class function, - DatetimeUnaryFunctionBuilder ctorRef, String... names) { - FunctionBuilder builder = (source, children, distinct, cfg) -> { - if (children.size() != 1) { - throw new SqlIllegalArgumentException("expects exactly one argument"); - } - if (distinct) { - throw new SqlIllegalArgumentException("does not support DISTINCT yet it was specified"); - } - return ctorRef.build(source, children.get(0), cfg.zoneId()); - }; - return def(function, builder, true, names); - } - - interface DatetimeUnaryFunctionBuilder { - T build(Source source, Expression target, ZoneId zi); - } - - /** - * Build a {@linkplain FunctionDefinition} for a binary function that - * requires a timezone. - */ - @SuppressWarnings("overloads") // These are ambiguous if you aren't using ctor references but we always do - static FunctionDefinition def(Class function, DatetimeBinaryFunctionBuilder ctorRef, String... names) { - FunctionBuilder builder = (source, children, distinct, cfg) -> { - if (children.size() != 2) { - throw new SqlIllegalArgumentException("expects exactly two arguments"); - } - if (distinct) { - throw new SqlIllegalArgumentException("does not support DISTINCT yet it was specified"); - } - return ctorRef.build(source, children.get(0), children.get(1), cfg.zoneId()); - }; - return def(function, builder, false, names); - } - - interface DatetimeBinaryFunctionBuilder { - T build(Source source, Expression lhs, Expression rhs, ZoneId zi); - } - - /** - * Build a {@linkplain FunctionDefinition} for a three-args function that - * requires a timezone. - */ - @SuppressWarnings("overloads") // These are ambiguous if you aren't using ctor references but we always do - static FunctionDefinition def(Class function, DatetimeThreeArgsFunctionBuilder ctorRef, String... names) { - FunctionBuilder builder = (source, children, distinct, cfg) -> { - if (children.size() != 3) { - throw new SqlIllegalArgumentException("expects three arguments"); - } - if (distinct) { - throw new SqlIllegalArgumentException("does not support DISTINCT yet it was specified"); - } - return ctorRef.build(source, children.get(0), children.get(1), children.get(2), cfg.zoneId()); - }; - return def(function, builder, false, names); - } - - interface DatetimeThreeArgsFunctionBuilder { - T build(Source source, Expression first, Expression second, Expression third, ZoneId zi); - } - - /** - * Build a {@linkplain FunctionDefinition} for a binary function that is - * not aware of time zone and does not support {@code DISTINCT}. - */ - @SuppressWarnings("overloads") // These are ambiguous if you aren't using ctor references but we always do - static FunctionDefinition def(Class function, - BinaryFunctionBuilder ctorRef, String... names) { - FunctionBuilder builder = (source, children, distinct, cfg) -> { - boolean isBinaryOptionalParamFunction = function.isAssignableFrom(Round.class) || function.isAssignableFrom(Truncate.class) - || TopHits.class.isAssignableFrom(function); - if (isBinaryOptionalParamFunction && (children.size() > 2 || children.size() < 1)) { - throw new SqlIllegalArgumentException("expects one or two arguments"); - } else if (!isBinaryOptionalParamFunction && children.size() != 2) { - throw new SqlIllegalArgumentException("expects exactly two arguments"); - } - - if (distinct) { - throw new SqlIllegalArgumentException("does not support DISTINCT yet it was specified"); - } - return ctorRef.build(source, children.get(0), children.size() == 2 ? children.get(1) : null); - }; - return def(function, builder, false, names); - } - - interface BinaryFunctionBuilder { - T build(Source source, Expression lhs, Expression rhs); - } - - /** - * Main method to register a function/ - * @param names Must always have at least one entry which is the method's primary name - * - */ - @SuppressWarnings("overloads") - private static FunctionDefinition def(Class function, FunctionBuilder builder, - boolean datetime, String... names) { - Check.isTrue(names.length > 0, "At least one name must be provided for the function"); - String primaryName = names[0]; - List aliases = Arrays.asList(names).subList(1, names.length); - FunctionDefinition.Builder realBuilder = (uf, distinct, cfg) -> { - try { - return builder.build(uf.source(), uf.children(), distinct, cfg); - } catch (SqlIllegalArgumentException e) { - throw new ParsingException(uf.source(), "error building [" + primaryName + "]: " + e.getMessage(), e); - } - }; - return new FunctionDefinition(primaryName, unmodifiableList(aliases), function, datetime, realBuilder); - } - - private interface FunctionBuilder { - Function build(Source source, List children, boolean distinct, Configuration cfg); - } - - @SuppressWarnings("overloads") // These are ambiguous if you aren't using ctor references but we always do - static FunctionDefinition def(Class function, - ThreeParametersFunctionBuilder ctorRef, String... names) { - FunctionBuilder builder = (source, children, distinct, cfg) -> { - boolean hasMinimumTwo = function.isAssignableFrom(Locate.class) || function.isAssignableFrom(Iif.class); - if (hasMinimumTwo && (children.size() > 3 || children.size() < 2)) { - throw new SqlIllegalArgumentException("expects two or three arguments"); - } else if (!hasMinimumTwo && children.size() != 3) { - throw new SqlIllegalArgumentException("expects exactly three arguments"); - } - if (distinct) { - throw new SqlIllegalArgumentException("does not support DISTINCT yet it was specified"); - } - return ctorRef.build(source, children.get(0), children.get(1), children.size() == 3 ? children.get(2) : null); - }; - return def(function, builder, false, names); - } - - interface ThreeParametersFunctionBuilder { - T build(Source source, Expression src, Expression exp1, Expression exp2); - } - - @SuppressWarnings("overloads") // These are ambiguous if you aren't using ctor references but we always do - static FunctionDefinition def(Class function, - FourParametersFunctionBuilder ctorRef, String... names) { - FunctionBuilder builder = (source, children, distinct, cfg) -> { - if (children.size() != 4) { - throw new SqlIllegalArgumentException("expects exactly four arguments"); - } - if (distinct) { - throw new SqlIllegalArgumentException("does not support DISTINCT yet it was specified"); - } - return ctorRef.build(source, children.get(0), children.get(1), children.get(2), children.get(3)); - }; - return def(function, builder, false, names); - } - - interface FourParametersFunctionBuilder { - T build(Source source, Expression src, Expression exp1, Expression exp2, Expression exp3); - } - - /** - * Special method to create function definition for {@link Cast} as its - * signature is not compatible with {@link UnresolvedFunction} - * - * @return Cast function definition - */ - @SuppressWarnings("overloads") // These are ambiguous if you aren't using ctor references but we always do - private static FunctionDefinition def(Class function, - CastFunctionBuilder ctorRef, - String... names) { - FunctionBuilder builder = (source, children, distinct, cfg) -> - ctorRef.build(source, children.get(0), children.get(0).dataType()); - return def(function, builder, false, names); - } - - private interface CastFunctionBuilder { - T build(Source source, Expression expression, DataType dataType); - } -} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/FunctionType.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/FunctionType.java deleted file mode 100644 index 22b6a50d8ee21..0000000000000 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/FunctionType.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -package org.elasticsearch.xpack.sql.expression.function; - -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.function.aggregate.AggregateFunction; -import org.elasticsearch.xpack.sql.expression.function.grouping.GroupingFunction; -import org.elasticsearch.xpack.sql.expression.function.scalar.ScalarFunction; -import org.elasticsearch.xpack.sql.expression.predicate.conditional.ConditionalFunction; - - -public enum FunctionType { - - AGGREGATE(AggregateFunction.class), - CONDITIONAL(ConditionalFunction.class), - GROUPING(GroupingFunction.class), - SCALAR(ScalarFunction.class), - SCORE(Score.class); - - private final Class baseClass; - - FunctionType(Class base) { - this.baseClass = base; - } - - public static FunctionType of(Class clazz) { - for (FunctionType type : values()) { - if (type.baseClass.isAssignableFrom(clazz)) { - return type; - } - } - throw new SqlIllegalArgumentException("Cannot identify the function type for {}", clazz); - } -} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/Score.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/Score.java index d5cee6449807d..cbe02fb675497 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/Score.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/Score.java @@ -5,13 +5,15 @@ */ package org.elasticsearch.xpack.sql.expression.function; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.function.Function; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; import java.util.List; @@ -39,7 +41,7 @@ public Expression replaceChildren(List newChildren) { @Override public DataType dataType() { - return DataType.FLOAT; + return DataTypes.FLOAT; } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/SqlFunctionRegistry.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/SqlFunctionRegistry.java new file mode 100644 index 0000000000000..ec1656f0dad54 --- /dev/null +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/SqlFunctionRegistry.java @@ -0,0 +1,265 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +package org.elasticsearch.xpack.sql.expression.function; + +import org.elasticsearch.xpack.ql.expression.function.FunctionDefinition; +import org.elasticsearch.xpack.ql.expression.function.FunctionRegistry; +import org.elasticsearch.xpack.ql.expression.function.aggregate.Count; +import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.Mod; +import org.elasticsearch.xpack.sql.expression.function.aggregate.Avg; +import org.elasticsearch.xpack.sql.expression.function.aggregate.First; +import org.elasticsearch.xpack.sql.expression.function.aggregate.Kurtosis; +import org.elasticsearch.xpack.sql.expression.function.aggregate.Last; +import org.elasticsearch.xpack.sql.expression.function.aggregate.Max; +import org.elasticsearch.xpack.sql.expression.function.aggregate.MedianAbsoluteDeviation; +import org.elasticsearch.xpack.sql.expression.function.aggregate.Min; +import org.elasticsearch.xpack.sql.expression.function.aggregate.Percentile; +import org.elasticsearch.xpack.sql.expression.function.aggregate.PercentileRank; +import org.elasticsearch.xpack.sql.expression.function.aggregate.Skewness; +import org.elasticsearch.xpack.sql.expression.function.aggregate.StddevPop; +import org.elasticsearch.xpack.sql.expression.function.aggregate.Sum; +import org.elasticsearch.xpack.sql.expression.function.aggregate.SumOfSquares; +import org.elasticsearch.xpack.sql.expression.function.aggregate.VarPop; +import org.elasticsearch.xpack.sql.expression.function.grouping.Histogram; +import org.elasticsearch.xpack.sql.expression.function.scalar.Cast; +import org.elasticsearch.xpack.sql.expression.function.scalar.Database; +import org.elasticsearch.xpack.sql.expression.function.scalar.User; +import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.CurrentDate; +import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.CurrentDateTime; +import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.CurrentTime; +import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateAdd; +import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateDiff; +import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DatePart; +import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTrunc; +import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DayName; +import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DayOfMonth; +import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DayOfWeek; +import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DayOfYear; +import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.HourOfDay; +import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.IsoDayOfWeek; +import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.IsoWeekOfYear; +import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.MinuteOfDay; +import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.MinuteOfHour; +import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.MonthName; +import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.MonthOfYear; +import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.Quarter; +import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.SecondOfMinute; +import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.WeekOfYear; +import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.Year; +import org.elasticsearch.xpack.sql.expression.function.scalar.geo.StAswkt; +import org.elasticsearch.xpack.sql.expression.function.scalar.geo.StDistance; +import org.elasticsearch.xpack.sql.expression.function.scalar.geo.StGeometryType; +import org.elasticsearch.xpack.sql.expression.function.scalar.geo.StWkttosql; +import org.elasticsearch.xpack.sql.expression.function.scalar.geo.StX; +import org.elasticsearch.xpack.sql.expression.function.scalar.geo.StY; +import org.elasticsearch.xpack.sql.expression.function.scalar.geo.StZ; +import org.elasticsearch.xpack.sql.expression.function.scalar.math.ACos; +import org.elasticsearch.xpack.sql.expression.function.scalar.math.ASin; +import org.elasticsearch.xpack.sql.expression.function.scalar.math.ATan; +import org.elasticsearch.xpack.sql.expression.function.scalar.math.ATan2; +import org.elasticsearch.xpack.sql.expression.function.scalar.math.Abs; +import org.elasticsearch.xpack.sql.expression.function.scalar.math.Cbrt; +import org.elasticsearch.xpack.sql.expression.function.scalar.math.Ceil; +import org.elasticsearch.xpack.sql.expression.function.scalar.math.Cos; +import org.elasticsearch.xpack.sql.expression.function.scalar.math.Cosh; +import org.elasticsearch.xpack.sql.expression.function.scalar.math.Cot; +import org.elasticsearch.xpack.sql.expression.function.scalar.math.Degrees; +import org.elasticsearch.xpack.sql.expression.function.scalar.math.E; +import org.elasticsearch.xpack.sql.expression.function.scalar.math.Exp; +import org.elasticsearch.xpack.sql.expression.function.scalar.math.Expm1; +import org.elasticsearch.xpack.sql.expression.function.scalar.math.Floor; +import org.elasticsearch.xpack.sql.expression.function.scalar.math.Log; +import org.elasticsearch.xpack.sql.expression.function.scalar.math.Log10; +import org.elasticsearch.xpack.sql.expression.function.scalar.math.Pi; +import org.elasticsearch.xpack.sql.expression.function.scalar.math.Power; +import org.elasticsearch.xpack.sql.expression.function.scalar.math.Radians; +import org.elasticsearch.xpack.sql.expression.function.scalar.math.Random; +import org.elasticsearch.xpack.sql.expression.function.scalar.math.Round; +import org.elasticsearch.xpack.sql.expression.function.scalar.math.Sign; +import org.elasticsearch.xpack.sql.expression.function.scalar.math.Sin; +import org.elasticsearch.xpack.sql.expression.function.scalar.math.Sinh; +import org.elasticsearch.xpack.sql.expression.function.scalar.math.Sqrt; +import org.elasticsearch.xpack.sql.expression.function.scalar.math.Tan; +import org.elasticsearch.xpack.sql.expression.function.scalar.math.Truncate; +import org.elasticsearch.xpack.sql.expression.function.scalar.string.Ascii; +import org.elasticsearch.xpack.sql.expression.function.scalar.string.BitLength; +import org.elasticsearch.xpack.sql.expression.function.scalar.string.Char; +import org.elasticsearch.xpack.sql.expression.function.scalar.string.CharLength; +import org.elasticsearch.xpack.sql.expression.function.scalar.string.Concat; +import org.elasticsearch.xpack.sql.expression.function.scalar.string.Insert; +import org.elasticsearch.xpack.sql.expression.function.scalar.string.LCase; +import org.elasticsearch.xpack.sql.expression.function.scalar.string.LTrim; +import org.elasticsearch.xpack.sql.expression.function.scalar.string.Left; +import org.elasticsearch.xpack.sql.expression.function.scalar.string.Length; +import org.elasticsearch.xpack.sql.expression.function.scalar.string.Locate; +import org.elasticsearch.xpack.sql.expression.function.scalar.string.OctetLength; +import org.elasticsearch.xpack.sql.expression.function.scalar.string.Position; +import org.elasticsearch.xpack.sql.expression.function.scalar.string.RTrim; +import org.elasticsearch.xpack.sql.expression.function.scalar.string.Repeat; +import org.elasticsearch.xpack.sql.expression.function.scalar.string.Replace; +import org.elasticsearch.xpack.sql.expression.function.scalar.string.Right; +import org.elasticsearch.xpack.sql.expression.function.scalar.string.Space; +import org.elasticsearch.xpack.sql.expression.function.scalar.string.Substring; +import org.elasticsearch.xpack.sql.expression.function.scalar.string.UCase; +import org.elasticsearch.xpack.sql.expression.predicate.conditional.Case; +import org.elasticsearch.xpack.sql.expression.predicate.conditional.Coalesce; +import org.elasticsearch.xpack.sql.expression.predicate.conditional.Greatest; +import org.elasticsearch.xpack.sql.expression.predicate.conditional.IfNull; +import org.elasticsearch.xpack.sql.expression.predicate.conditional.Iif; +import org.elasticsearch.xpack.sql.expression.predicate.conditional.Least; +import org.elasticsearch.xpack.sql.expression.predicate.conditional.NullIf; + +public class SqlFunctionRegistry extends FunctionRegistry { + + public SqlFunctionRegistry() { + super(functions()); + } + + private static FunctionDefinition[][] functions() { + return new FunctionDefinition[][] { + // Aggregate functions + new FunctionDefinition[] { + def(Avg.class, Avg::new, "AVG"), + def(Count.class, Count::new, "COUNT"), + def(First.class, First::new, "FIRST", "FIRST_VALUE"), + def(Last.class, Last::new, "LAST", "LAST_VALUE"), + def(Max.class, Max::new, "MAX"), + def(Min.class, Min::new, "MIN"), + def(Sum.class, Sum::new, "SUM") + }, + // Statistics + new FunctionDefinition[] { + def(Kurtosis.class, Kurtosis::new, "KURTOSIS"), + def(MedianAbsoluteDeviation.class, MedianAbsoluteDeviation::new, "MAD"), + def(Percentile.class, Percentile::new, "PERCENTILE"), + def(PercentileRank.class, PercentileRank::new, "PERCENTILE_RANK"), + def(Skewness.class, Skewness::new, "SKEWNESS"), + def(StddevPop.class, StddevPop::new, "STDDEV_POP"), + def(SumOfSquares.class, SumOfSquares::new, "SUM_OF_SQUARES"), + def(VarPop.class, VarPop::new, "VAR_POP") + }, + // histogram + new FunctionDefinition[] { + def(Histogram.class, Histogram::new, "HISTOGRAM") + }, + // Scalar functions + // Conditional + new FunctionDefinition[] { + def(Case.class, Case::new, "CASE"), + def(Coalesce.class, Coalesce::new, "COALESCE"), + def(Iif.class, Iif::new, "IIF"), + def(IfNull.class, IfNull::new, "IFNULL", "ISNULL", "NVL"), + def(NullIf.class, NullIf::new, "NULLIF"), + def(Greatest.class, Greatest::new, "GREATEST"), + def(Least.class, Least::new, "LEAST") + }, + // Date + new FunctionDefinition[] { + def(CurrentDate.class, CurrentDate::new, "CURRENT_DATE", "CURDATE", "TODAY"), + def(CurrentTime.class, CurrentTime::new, "CURRENT_TIME", "CURTIME"), + def(CurrentDateTime.class, CurrentDateTime::new, "CURRENT_TIMESTAMP", "NOW"), + def(DayName.class, DayName::new, "DAY_NAME", "DAYNAME"), + def(DayOfMonth.class, DayOfMonth::new, "DAY_OF_MONTH", "DAYOFMONTH", "DAY", "DOM"), + def(DayOfWeek.class, DayOfWeek::new, "DAY_OF_WEEK", "DAYOFWEEK", "DOW"), + def(DayOfYear.class, DayOfYear::new, "DAY_OF_YEAR", "DAYOFYEAR", "DOY"), + def(DateAdd.class, DateAdd::new, "DATEADD", "DATE_ADD", "TIMESTAMPADD", "TIMESTAMP_ADD"), + def(DateDiff.class, DateDiff::new, "DATEDIFF", "DATE_DIFF", "TIMESTAMPDIFF", "TIMESTAMP_DIFF"), + def(DatePart.class, DatePart::new, "DATEPART", "DATE_PART"), + def(DateTrunc.class, DateTrunc::new, "DATETRUNC", "DATE_TRUNC"), + def(HourOfDay.class, HourOfDay::new, "HOUR_OF_DAY", "HOUR"), + def(IsoDayOfWeek.class, IsoDayOfWeek::new, "ISO_DAY_OF_WEEK", "ISODAYOFWEEK", "ISODOW", "IDOW"), + def(IsoWeekOfYear.class, IsoWeekOfYear::new, "ISO_WEEK_OF_YEAR", "ISOWEEKOFYEAR", "ISOWEEK", "IWOY", "IW"), + def(MinuteOfDay.class, MinuteOfDay::new, "MINUTE_OF_DAY"), + def(MinuteOfHour.class, MinuteOfHour::new, "MINUTE_OF_HOUR", "MINUTE"), + def(MonthName.class, MonthName::new, "MONTH_NAME", "MONTHNAME"), + def(MonthOfYear.class, MonthOfYear::new, "MONTH_OF_YEAR", "MONTH"), + def(SecondOfMinute.class, SecondOfMinute::new, "SECOND_OF_MINUTE", "SECOND"), + def(Quarter.class, Quarter::new, "QUARTER"), + def(Year.class, Year::new, "YEAR"), + def(WeekOfYear.class, WeekOfYear::new, "WEEK_OF_YEAR", "WEEK") + }, + // Math + new FunctionDefinition[] { + def(Abs.class, Abs::new, "ABS"), + def(ACos.class, ACos::new, "ACOS"), + def(ASin.class, ASin::new, "ASIN"), + def(ATan.class, ATan::new, "ATAN"), + def(ATan2.class, ATan2::new, "ATAN2"), + def(Cbrt.class, Cbrt::new, "CBRT"), + def(Ceil.class, Ceil::new, "CEIL", "CEILING"), + def(Cos.class, Cos::new, "COS"), + def(Cosh.class, Cosh::new, "COSH"), + def(Cot.class, Cot::new, "COT"), + def(Degrees.class, Degrees::new, "DEGREES"), + def(E.class, E::new, "E"), + def(Exp.class, Exp::new, "EXP"), + def(Expm1.class, Expm1::new, "EXPM1"), + def(Floor.class, Floor::new, "FLOOR"), + def(Log.class, Log::new, "LOG"), + def(Log10.class, Log10::new, "LOG10"), + // SQL and ODBC require MOD as a _function_ + def(Mod.class, Mod::new, "MOD"), + def(Pi.class, Pi::new, "PI"), + def(Power.class, Power::new, "POWER"), + def(Radians.class, Radians::new, "RADIANS"), + def(Random.class, Random::new, "RANDOM", "RAND"), + def(Round.class, Round::new, "ROUND"), + def(Sign.class, Sign::new, "SIGN", "SIGNUM"), + def(Sin.class, Sin::new, "SIN"), + def(Sinh.class, Sinh::new, "SINH"), + def(Sqrt.class, Sqrt::new, "SQRT"), + def(Tan.class, Tan::new, "TAN"), + def(Truncate.class, Truncate::new, "TRUNCATE", "TRUNC") + }, + // String + new FunctionDefinition[] { + def(Ascii.class, Ascii::new, "ASCII"), + def(BitLength.class, BitLength::new, "BIT_LENGTH"), + def(Char.class, Char::new, "CHAR"), + def(CharLength.class, CharLength::new, "CHAR_LENGTH", "CHARACTER_LENGTH"), + def(Concat.class, Concat::new, "CONCAT"), + def(Insert.class, Insert::new, "INSERT"), + def(LCase.class, LCase::new, "LCASE"), + def(Left.class, Left::new, "LEFT"), + def(Length.class, Length::new, "LENGTH"), + def(Locate.class, Locate::new, "LOCATE"), + def(LTrim.class, LTrim::new, "LTRIM"), + def(OctetLength.class, OctetLength::new, "OCTET_LENGTH"), + def(Position.class, Position::new, "POSITION"), + def(Repeat.class, Repeat::new, "REPEAT"), + def(Replace.class, Replace::new, "REPLACE"), + def(Right.class, Right::new, "RIGHT"), + def(RTrim.class, RTrim::new, "RTRIM"), + def(Space.class, Space::new, "SPACE"), + def(Substring.class, Substring::new, "SUBSTRING"), + def(UCase.class, UCase::new, "UCASE") + }, + // DataType conversion + new FunctionDefinition[] { + def(Cast.class, Cast::new, "CAST", "CONVERT") + }, + // Scalar "meta" functions + new FunctionDefinition[] { + def(Database.class, Database::new, "DATABASE"), + def(User.class, User::new, "USER") + }, + // Geo Functions + new FunctionDefinition[] { + def(StAswkt.class, StAswkt::new, "ST_ASWKT", "ST_ASTEXT"), + def(StDistance.class, StDistance::new, "ST_DISTANCE"), + def(StWkttosql.class, StWkttosql::new, "ST_WKTTOSQL", "ST_GEOMFROMTEXT"), + def(StGeometryType.class, StGeometryType::new, "ST_GEOMETRYTYPE"), + def(StX.class, StX::new, "ST_X"), + def(StY.class, StY::new, "ST_Y"), + def(StZ.class, StZ::new, "ST_Z") + }, + // Special + new FunctionDefinition[] { + def(Score.class, Score::new, "SCORE") + } + }; + } +} \ No newline at end of file diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/SqlFunctionTypeRegistry.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/SqlFunctionTypeRegistry.java new file mode 100644 index 0000000000000..98e51a0d302a7 --- /dev/null +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/SqlFunctionTypeRegistry.java @@ -0,0 +1,40 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.sql.expression.function; + +import org.elasticsearch.xpack.ql.expression.function.DefaultFunctionTypeRegistry; +import org.elasticsearch.xpack.ql.expression.function.Function; +import org.elasticsearch.xpack.ql.expression.function.grouping.GroupingFunction; +import org.elasticsearch.xpack.sql.expression.predicate.conditional.ConditionalFunction; + +public class SqlFunctionTypeRegistry extends DefaultFunctionTypeRegistry { + + public static final SqlFunctionTypeRegistry INSTANCE = new SqlFunctionTypeRegistry(); + + private enum Types { + CONDITIONAL(ConditionalFunction.class), + GROUPING(GroupingFunction.class), + SCORE(Score.class); + + private Class baseClass; + + Types(Class base) { + this.baseClass = base; + } + } + + @Override + public String type(Class clazz) { + for (Types type : Types.values()) { + if (type.baseClass.isAssignableFrom(clazz)) { + return type.name(); + } + } + return super.type(clazz); + } + +} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Avg.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Avg.java index b74be4810ed60..b4fe32e663a3f 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Avg.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Avg.java @@ -5,10 +5,12 @@ */ package org.elasticsearch.xpack.sql.expression.function.aggregate; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.function.aggregate.EnclosedAgg; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import java.util.List; @@ -41,6 +43,6 @@ public String innerName() { @Override public DataType dataType() { - return DataType.DOUBLE; + return DataTypes.DOUBLE; } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/CompoundNumericAggregate.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/CompoundNumericAggregate.java index 9585b55ce3b8d..4582a06e6311b 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/CompoundNumericAggregate.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/CompoundNumericAggregate.java @@ -5,14 +5,15 @@ */ package org.elasticsearch.xpack.sql.expression.function.aggregate; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.function.aggregate.CompoundAggregate; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.List; // marker type for compound aggregates, that is aggregate that provide multiple values (like Stats or Matrix) // and thus cannot be used directly in SQL and are mainly for internal use -public abstract class CompoundNumericAggregate extends NumericAggregate { +public abstract class CompoundNumericAggregate extends NumericAggregate implements CompoundAggregate { CompoundNumericAggregate(Source source, Expression field, List arguments) { super(source, field, arguments); diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/ExtendedStats.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/ExtendedStats.java index a1245104858f3..04589d1f4f2de 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/ExtendedStats.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/ExtendedStats.java @@ -5,10 +5,11 @@ */ package org.elasticsearch.xpack.sql.expression.function.aggregate; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; + import java.util.List; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; public class ExtendedStats extends CompoundNumericAggregate { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/ExtendedStatsEnclosed.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/ExtendedStatsEnclosed.java index 3e51fa4ef1adf..6ce0ad2084a47 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/ExtendedStatsEnclosed.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/ExtendedStatsEnclosed.java @@ -5,6 +5,8 @@ */ package org.elasticsearch.xpack.sql.expression.function.aggregate; +import org.elasticsearch.xpack.ql.expression.function.aggregate.EnclosedAgg; + public interface ExtendedStatsEnclosed extends StatsEnclosed, EnclosedAgg { } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/First.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/First.java index 527d299fa3c58..6ef0ffb12b07c 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/First.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/First.java @@ -5,9 +5,9 @@ */ package org.elasticsearch.xpack.sql.expression.function.aggregate; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.List; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Kurtosis.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Kurtosis.java index 29b09187b5dea..aef566f6dd7d4 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Kurtosis.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Kurtosis.java @@ -5,10 +5,11 @@ */ package org.elasticsearch.xpack.sql.expression.function.aggregate; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; + import java.util.List; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; public class Kurtosis extends NumericAggregate implements MatrixStatsEnclosed { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Last.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Last.java index 93b893e510ceb..77ca1adf5dba7 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Last.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Last.java @@ -5,9 +5,9 @@ */ package org.elasticsearch.xpack.sql.expression.function.aggregate; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.List; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/MatrixStats.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/MatrixStats.java index fb4d86501dbf1..d6a523dcab056 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/MatrixStats.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/MatrixStats.java @@ -5,10 +5,11 @@ */ package org.elasticsearch.xpack.sql.expression.function.aggregate; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; + import java.util.List; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; public class MatrixStats extends CompoundNumericAggregate { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/MatrixStatsEnclosed.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/MatrixStatsEnclosed.java index 67d60ae1a640e..c35eacb1618ac 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/MatrixStatsEnclosed.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/MatrixStatsEnclosed.java @@ -5,6 +5,8 @@ */ package org.elasticsearch.xpack.sql.expression.function.aggregate; +import org.elasticsearch.xpack.ql.expression.function.aggregate.EnclosedAgg; + public interface MatrixStatsEnclosed extends EnclosedAgg { } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Max.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Max.java index eaf2d798f6d2d..3a370c45be5f9 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Max.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Max.java @@ -5,16 +5,18 @@ */ package org.elasticsearch.xpack.sql.expression.function.aggregate; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions.ParamOrdinal; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions.ParamOrdinal; +import org.elasticsearch.xpack.ql.expression.function.aggregate.EnclosedAgg; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import java.util.List; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isExact; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isNumericOrDateOrTime; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isExact; +import static org.elasticsearch.xpack.sql.expression.SqlTypeResolutions.isNumericOrDateOrTime; /** * Find the maximum value in matching documents. @@ -47,7 +49,7 @@ public String innerName() { @Override protected TypeResolution resolveType() { - if (field().dataType().isString()) { + if (DataTypes.isString(field().dataType())) { return isExact(field(), sourceText(), ParamOrdinal.DEFAULT); } else { return isNumericOrDateOrTime(field(), sourceText(), ParamOrdinal.DEFAULT); diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/MedianAbsoluteDeviation.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/MedianAbsoluteDeviation.java index afdb7dd40fd3c..6fe9af2b7c8a1 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/MedianAbsoluteDeviation.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/MedianAbsoluteDeviation.java @@ -6,10 +6,11 @@ package org.elasticsearch.xpack.sql.expression.function.aggregate; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import java.util.List; @@ -21,7 +22,7 @@ public MedianAbsoluteDeviation(Source source, Expression field) { @Override public DataType dataType() { - return DataType.DOUBLE; + return DataTypes.DOUBLE; } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Min.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Min.java index f195517335883..30f38f21e42cc 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Min.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Min.java @@ -5,16 +5,18 @@ */ package org.elasticsearch.xpack.sql.expression.function.aggregate; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions.ParamOrdinal; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions.ParamOrdinal; +import org.elasticsearch.xpack.ql.expression.function.aggregate.EnclosedAgg; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import java.util.List; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isExact; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isNumericOrDateOrTime; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isExact; +import static org.elasticsearch.xpack.sql.expression.SqlTypeResolutions.isNumericOrDateOrTime; /** * Find the minimum value in matched documents. @@ -50,7 +52,7 @@ public String innerName() { @Override protected TypeResolution resolveType() { - if (field().dataType().isString()) { + if (DataTypes.isString(field().dataType())) { return isExact(field(), sourceText(), ParamOrdinal.DEFAULT); } else { return isNumericOrDateOrTime(field(), sourceText(), ParamOrdinal.DEFAULT); diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/NumericAggregate.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/NumericAggregate.java index 21d5c23d23a5a..d6e23fb619e97 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/NumericAggregate.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/NumericAggregate.java @@ -5,14 +5,16 @@ */ package org.elasticsearch.xpack.sql.expression.function.aggregate; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions.ParamOrdinal; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions.ParamOrdinal; +import org.elasticsearch.xpack.ql.expression.function.aggregate.AggregateFunction; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import java.util.List; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isNumeric; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isNumeric; abstract class NumericAggregate extends AggregateFunction { @@ -31,6 +33,6 @@ protected TypeResolution resolveType() { @Override public DataType dataType() { - return DataType.DOUBLE; + return DataTypes.DOUBLE; } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Percentile.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Percentile.java index a0585f4c02176..785cbb1a7a6be 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Percentile.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Percentile.java @@ -5,18 +5,20 @@ */ package org.elasticsearch.xpack.sql.expression.function.aggregate; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions.ParamOrdinal; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions.ParamOrdinal; +import org.elasticsearch.xpack.ql.expression.function.aggregate.EnclosedAgg; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.expression.Foldables; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; import java.util.List; import static java.util.Collections.singletonList; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isFoldable; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isNumeric; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isFoldable; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isNumeric; public class Percentile extends NumericAggregate implements EnclosedAgg { @@ -61,7 +63,7 @@ public Expression percent() { @Override public DataType dataType() { - return DataType.DOUBLE; + return DataTypes.DOUBLE; } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/PercentileRank.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/PercentileRank.java index da8c487ff31f9..be253aa461917 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/PercentileRank.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/PercentileRank.java @@ -5,18 +5,21 @@ */ package org.elasticsearch.xpack.sql.expression.function.aggregate; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions.ParamOrdinal; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions.ParamOrdinal; +import org.elasticsearch.xpack.ql.expression.function.aggregate.AggregateFunction; +import org.elasticsearch.xpack.ql.expression.function.aggregate.EnclosedAgg; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.expression.Foldables; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; import java.util.List; import static java.util.Collections.singletonList; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isFoldable; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isNumeric; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isFoldable; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isNumeric; public class PercentileRank extends AggregateFunction implements EnclosedAgg { @@ -61,7 +64,7 @@ public Expression value() { @Override public DataType dataType() { - return DataType.DOUBLE; + return DataTypes.DOUBLE; } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/PercentileRanks.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/PercentileRanks.java index 5cda86e7f1634..25cad378a1bcd 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/PercentileRanks.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/PercentileRanks.java @@ -5,9 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.aggregate; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; + import java.util.List; public class PercentileRanks extends CompoundNumericAggregate { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Percentiles.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Percentiles.java index e4238831536ff..6440c669f55c7 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Percentiles.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Percentiles.java @@ -5,9 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.aggregate; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; + import java.util.List; public class Percentiles extends CompoundNumericAggregate { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Skewness.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Skewness.java index 07e857f1eb8f5..dc4fb515d4f33 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Skewness.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Skewness.java @@ -5,10 +5,11 @@ */ package org.elasticsearch.xpack.sql.expression.function.aggregate; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; + import java.util.List; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; public class Skewness extends NumericAggregate implements MatrixStatsEnclosed { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Stats.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Stats.java index 4da3fdd2ac573..533cb7254e73a 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Stats.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Stats.java @@ -5,10 +5,11 @@ */ package org.elasticsearch.xpack.sql.expression.function.aggregate; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; + import java.util.List; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; public class Stats extends CompoundNumericAggregate { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/StddevPop.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/StddevPop.java index a0521b886153c..c9c0405c615a1 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/StddevPop.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/StddevPop.java @@ -5,10 +5,11 @@ */ package org.elasticsearch.xpack.sql.expression.function.aggregate; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; + import java.util.List; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; public class StddevPop extends NumericAggregate implements ExtendedStatsEnclosed { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Sum.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Sum.java index 271cda6630be7..9b0a2106d3496 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Sum.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/Sum.java @@ -5,11 +5,13 @@ */ package org.elasticsearch.xpack.sql.expression.function.aggregate; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.function.aggregate.EnclosedAgg; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; + import java.util.List; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.type.DataType; /** * Sum all values of a field in matching documents. diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/SumOfSquares.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/SumOfSquares.java index c936d3472a7fd..757ad1c1fbf4c 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/SumOfSquares.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/SumOfSquares.java @@ -5,10 +5,11 @@ */ package org.elasticsearch.xpack.sql.expression.function.aggregate; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; + import java.util.List; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; public class SumOfSquares extends NumericAggregate implements ExtendedStatsEnclosed { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/TopHits.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/TopHits.java index 9364f5f4fc53f..fcbb7c120ef26 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/TopHits.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/TopHits.java @@ -5,21 +5,23 @@ */ package org.elasticsearch.xpack.sql.expression.function.aggregate; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.TypeResolutions; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions.ParamOrdinal; +import org.elasticsearch.xpack.ql.expression.TypeResolutions; +import org.elasticsearch.xpack.ql.expression.function.OptionalArgument; +import org.elasticsearch.xpack.ql.expression.function.aggregate.AggregateFunction; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; import java.util.Collections; -import static org.elasticsearch.xpack.sql.expression.Expressions.ParamOrdinal; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isNotFoldable; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isNotFoldable; /** * Super class of Aggregation functions on field types other than numeric, that need to be * translated into an ES {@link org.elasticsearch.search.aggregations.metrics.TopHits} aggregation. */ -public abstract class TopHits extends AggregateFunction { +public abstract class TopHits extends AggregateFunction implements OptionalArgument { TopHits(Source source, Expression field, Expression sortField) { super(source, field, sortField != null ? Collections.singletonList(sortField) : Collections.emptyList()); diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/VarPop.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/VarPop.java index eec44e828db9c..81a2ed5dd24b8 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/VarPop.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/VarPop.java @@ -5,10 +5,11 @@ */ package org.elasticsearch.xpack.sql.expression.function.aggregate; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; + import java.util.List; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; public class VarPop extends NumericAggregate implements ExtendedStatsEnclosed { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/grouping/Histogram.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/grouping/Histogram.java index 38ded7cb09152..b7ec8c1d5e561 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/grouping/Histogram.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/grouping/Histogram.java @@ -6,21 +6,23 @@ package org.elasticsearch.xpack.sql.expression.function.grouping; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions.ParamOrdinal; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions.ParamOrdinal; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.function.grouping.GroupingFunction; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.sql.type.SqlDataTypes; import java.time.ZoneId; import java.util.Collections; import java.util.List; import java.util.Objects; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isNumeric; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isNumericOrDate; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isType; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isNumeric; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isType; +import static org.elasticsearch.xpack.sql.expression.SqlTypeResolutions.isNumericOrDate; public class Histogram extends GroupingFunction { @@ -46,8 +48,8 @@ protected TypeResolution resolveType() { TypeResolution resolution = isNumericOrDate(field(), "HISTOGRAM", ParamOrdinal.FIRST); if (resolution == TypeResolution.TYPE_RESOLVED) { // interval must be Literal interval - if (field().dataType().isDateBased()) { - resolution = isType(interval, DataType::isInterval, "(Date) HISTOGRAM", ParamOrdinal.SECOND, "interval"); + if (SqlDataTypes.isDateBased(field().dataType())) { + resolution = isType(interval, SqlDataTypes::isInterval, "(Date) HISTOGRAM", ParamOrdinal.SECOND, "interval"); } else { resolution = isNumeric(interval, "(Numeric) HISTOGRAM", ParamOrdinal.SECOND); } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/Cast.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/Cast.java index 35bc87eabd7b2..461f0ea93e4ec 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/Cast.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/Cast.java @@ -5,19 +5,21 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Nullability; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.DataTypeConversion; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.Nullability; +import org.elasticsearch.xpack.ql.expression.function.scalar.UnaryScalarFunction; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.sql.type.SqlDataTypeConverter; import java.util.Objects; import static org.elasticsearch.common.logging.LoggerMessageFormat.format; -import static org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder.paramsBuilder; +import static org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder.paramsBuilder; public class Cast extends UnaryScalarFunction { @@ -58,27 +60,24 @@ public boolean foldable() { @Override public Object fold() { - return DataTypeConversion.convert(field().fold(), dataType); + return SqlDataTypeConverter.convert(field().fold(), dataType); } @Override public Nullability nullable() { - if (from().isNull()) { - return Nullability.TRUE; - } - return Nullability.UNKNOWN; + return Expressions.isNull(field()) ? Nullability.TRUE : Nullability.UNKNOWN; } @Override protected TypeResolution resolveType() { - return DataTypeConversion.canConvert(from(), to()) ? + return SqlDataTypeConverter.canConvert(from(), to()) ? TypeResolution.TYPE_RESOLVED : new TypeResolution("Cannot cast [" + from() + "] to [" + to()+ "]"); } @Override protected Processor makeProcessor() { - return new CastProcessor(DataTypeConversion.conversionFor(from(), to())); + return new CastProcessor(SqlDataTypeConverter.converterFor(from(), to())); } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/CastProcessor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/CastProcessor.java index 6d0173c23b8f5..d8f85fbb7fd99 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/CastProcessor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/CastProcessor.java @@ -7,8 +7,8 @@ import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.type.DataTypeConversion.Conversion; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.type.Converter; import java.io.IOException; import java.util.Objects; @@ -17,14 +17,14 @@ public class CastProcessor implements Processor { public static final String NAME = "ca"; - private final Conversion conversion; + private final Converter conversion; - public CastProcessor(Conversion conversion) { + public CastProcessor(Converter conversion) { this.conversion = conversion; } public CastProcessor(StreamInput in) throws IOException { - conversion = in.readEnum(Conversion.class); + conversion = in.readNamedWriteable(Converter.class); } @Override @@ -34,7 +34,7 @@ public String getWriteableName() { @Override public void writeTo(StreamOutput out) throws IOException { - out.writeEnum(conversion); + out.writeNamedWriteable(conversion); } @Override @@ -42,7 +42,7 @@ public Object process(Object input) { return conversion.convert(input); } - Conversion converter() { + Converter converter() { return conversion; } @@ -67,6 +67,6 @@ public int hashCode() { @Override public String toString() { - return conversion.name(); + return conversion.getClass().getSimpleName(); } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/ConfigurationFunction.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/ConfigurationFunction.java index dc49d2a950a63..d68f40ccfff6d 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/ConfigurationFunction.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/ConfigurationFunction.java @@ -6,12 +6,13 @@ package org.elasticsearch.xpack.sql.expression.function.scalar; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Nullability; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.session.Configuration; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Nullability; +import org.elasticsearch.xpack.ql.expression.function.scalar.ScalarFunction; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.session.Configuration; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; import java.util.List; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/Database.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/Database.java index 4a6836d4856e9..3acd89bc0d7de 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/Database.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/Database.java @@ -6,15 +6,15 @@ package org.elasticsearch.xpack.sql.expression.function.scalar; -import org.elasticsearch.xpack.sql.session.Configuration; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.session.Configuration; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataTypes; public class Database extends ConfigurationFunction { public Database(Source source, Configuration configuration) { - super(source, configuration, DataType.KEYWORD); + super(source, configuration, DataTypes.KEYWORD); } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/Processors.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/Processors.java index 64958b0cdbaaf..e842a3f25eca8 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/Processors.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/Processors.java @@ -7,6 +7,9 @@ import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.NamedWriteableRegistry.Entry; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.BinaryArithmeticOperation; +import org.elasticsearch.xpack.ql.type.Converter; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateAddProcessor; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateDiffProcessor; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DatePartProcessor; @@ -30,22 +33,13 @@ import org.elasticsearch.xpack.sql.expression.function.scalar.string.ReplaceFunctionProcessor; import org.elasticsearch.xpack.sql.expression.function.scalar.string.StringProcessor; import org.elasticsearch.xpack.sql.expression.function.scalar.string.SubstringFunctionProcessor; -import org.elasticsearch.xpack.sql.expression.gen.processor.BucketExtractorProcessor; -import org.elasticsearch.xpack.sql.expression.gen.processor.ChainingProcessor; -import org.elasticsearch.xpack.sql.expression.gen.processor.ConstantProcessor; -import org.elasticsearch.xpack.sql.expression.gen.processor.HitExtractorProcessor; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; import org.elasticsearch.xpack.sql.expression.predicate.conditional.CaseProcessor; import org.elasticsearch.xpack.sql.expression.predicate.conditional.ConditionalProcessor; import org.elasticsearch.xpack.sql.expression.predicate.conditional.NullIfProcessor; -import org.elasticsearch.xpack.sql.expression.predicate.logical.BinaryLogicProcessor; -import org.elasticsearch.xpack.sql.expression.predicate.logical.NotProcessor; import org.elasticsearch.xpack.sql.expression.predicate.nulls.CheckNullProcessor; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.BinaryArithmeticProcessor; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.UnaryArithmeticProcessor; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.BinaryComparisonProcessor; +import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.SqlBinaryArithmeticOperation; import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.InProcessor; -import org.elasticsearch.xpack.sql.expression.predicate.regex.RegexProcessor; +import org.elasticsearch.xpack.sql.type.SqlDataTypeConverter.SqlConverter; import java.util.ArrayList; import java.util.List; @@ -60,32 +54,26 @@ private Processors() {} */ public static List getNamedWriteables() { List entries = new ArrayList<>(); + + entries.addAll(org.elasticsearch.xpack.ql.expression.processor.Processors.getNamedWriteables()); + // base - entries.add(new Entry(Processor.class, ConstantProcessor.NAME, ConstantProcessor::new)); - entries.add(new Entry(Processor.class, HitExtractorProcessor.NAME, HitExtractorProcessor::new)); - entries.add(new Entry(Processor.class, BucketExtractorProcessor.NAME, BucketExtractorProcessor::new)); entries.add(new Entry(Processor.class, CastProcessor.NAME, CastProcessor::new)); - entries.add(new Entry(Processor.class, ChainingProcessor.NAME, ChainingProcessor::new)); + entries.add(new Entry(Converter.class, SqlConverter.NAME, SqlConverter::read)); + + // arithmetic + // binary arithmetics are pluggable + entries.add(new Entry(BinaryArithmeticOperation.class, SqlBinaryArithmeticOperation.NAME, SqlBinaryArithmeticOperation::read)); + + // comparators + entries.add(new Entry(Processor.class, InProcessor.NAME, InProcessor::new)); - // logical - entries.add(new Entry(Processor.class, BinaryLogicProcessor.NAME, BinaryLogicProcessor::new)); - entries.add(new Entry(Processor.class, NotProcessor.NAME, NotProcessor::new)); // conditionals entries.add(new Entry(Processor.class, CaseProcessor.NAME, CaseProcessor::new)); entries.add(new Entry(Processor.class, CheckNullProcessor.NAME, CheckNullProcessor::new)); entries.add(new Entry(Processor.class, ConditionalProcessor.NAME, ConditionalProcessor::new)); entries.add(new Entry(Processor.class, NullIfProcessor.NAME, NullIfProcessor::new)); - // arithmetic - entries.add(new Entry(Processor.class, BinaryArithmeticProcessor.NAME, BinaryArithmeticProcessor::new)); - entries.add(new Entry(Processor.class, UnaryArithmeticProcessor.NAME, UnaryArithmeticProcessor::new)); - // comparators - entries.add(new Entry(Processor.class, BinaryComparisonProcessor.NAME, BinaryComparisonProcessor::new)); - entries.add(new Entry(Processor.class, InProcessor.NAME, InProcessor::new)); - // regex - entries.add(new Entry(Processor.class, RegexProcessor.NAME, RegexProcessor::new)); - - // datetime entries.add(new Entry(Processor.class, DateTimeProcessor.NAME, DateTimeProcessor::new)); entries.add(new Entry(Processor.class, TimeProcessor.NAME, TimeProcessor::new)); @@ -115,12 +103,4 @@ public static List getNamedWriteables() { entries.add(new Entry(Processor.class, StDistanceProcessor.NAME, StDistanceProcessor::new)); return entries; } - - public static List process(List processors, Object input) { - List values = new ArrayList<>(processors.size()); - for (Processor p : processors) { - values.add(p.process(input)); - } - return values; - } -} +} \ No newline at end of file diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/ScalarFunction.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/ScalarFunction.java deleted file mode 100644 index b764b4b0a6ac8..0000000000000 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/ScalarFunction.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -package org.elasticsearch.xpack.sql.expression.function.scalar; - -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.function.Function; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptWeaver; -import org.elasticsearch.xpack.sql.tree.Source; - -import java.util.List; - -import static java.util.Collections.emptyList; - -/** - * A {@code ScalarFunction} is a {@code Function} that takes values from some - * operation and converts each to another value. An example would be - * {@code ABS()}, which takes one value at a time, applies a function to the - * value (abs) and returns a new value. - */ -public abstract class ScalarFunction extends Function implements ScriptWeaver { - - protected ScalarFunction(Source source) { - super(source, emptyList()); - } - - protected ScalarFunction(Source source, List fields) { - super(source, fields); - } - - // used if the function is monotonic and thus does not have to be computed for ordering purposes - // null means the script needs to be used; expression means the field/expression to be used instead - public Expression orderBy() { - return null; - } -} \ No newline at end of file diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/User.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/User.java index f8b3beb1d8f52..dd2c24950298c 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/User.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/User.java @@ -6,15 +6,15 @@ package org.elasticsearch.xpack.sql.expression.function.scalar; -import org.elasticsearch.xpack.sql.session.Configuration; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.session.Configuration; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataTypes; public class User extends ConfigurationFunction { public User(Source source, Configuration configuration) { - super(source, configuration, DataType.KEYWORD); + super(source, configuration, DataTypes.KEYWORD); } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/BaseDateTimeFunction.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/BaseDateTimeFunction.java index 0cce7521a2992..eaa0a43d05153 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/BaseDateTimeFunction.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/BaseDateTimeFunction.java @@ -6,16 +6,16 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions.ParamOrdinal; -import org.elasticsearch.xpack.sql.expression.function.scalar.UnaryScalarFunction; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions.ParamOrdinal; +import org.elasticsearch.xpack.ql.expression.function.scalar.UnaryScalarFunction; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.time.ZoneId; import java.util.Objects; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isDate; +import static org.elasticsearch.xpack.sql.expression.SqlTypeResolutions.isDate; abstract class BaseDateTimeFunction extends UnaryScalarFunction { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/BaseDateTimeProcessor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/BaseDateTimeProcessor.java index 3a4a5709e4f5f..a4a755aff4420 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/BaseDateTimeProcessor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/BaseDateTimeProcessor.java @@ -7,9 +7,9 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; import org.elasticsearch.xpack.sql.common.io.SqlStreamInput; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; import java.io.IOException; import java.time.ZoneId; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/BinaryDateTimeFunction.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/BinaryDateTimeFunction.java index f0583f57a5e21..c6855eccee8cd 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/BinaryDateTimeFunction.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/BinaryDateTimeFunction.java @@ -5,21 +5,21 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.function.scalar.BinaryScalarFunction; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.function.scalar.BinaryScalarFunction; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.tree.Source; import java.time.ZoneId; import java.util.List; import java.util.Objects; import static org.elasticsearch.common.logging.LoggerMessageFormat.format; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isDate; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isString; -import static org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder.paramsBuilder; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isString; +import static org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder.paramsBuilder; +import static org.elasticsearch.xpack.sql.expression.SqlTypeResolutions.isDate; public abstract class BinaryDateTimeFunction extends BinaryScalarFunction { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/BinaryDateTimePipe.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/BinaryDateTimePipe.java index 86209e593653c..3cc4722e2d17f 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/BinaryDateTimePipe.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/BinaryDateTimePipe.java @@ -5,11 +5,11 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.BinaryPipe; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.BinaryPipe; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.tree.Source; import java.time.ZoneId; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/BinaryDateTimeProcessor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/BinaryDateTimeProcessor.java index 2cd7b5e2de1ac..7731aba48b930 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/BinaryDateTimeProcessor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/BinaryDateTimeProcessor.java @@ -7,9 +7,9 @@ import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; +import org.elasticsearch.xpack.ql.expression.gen.processor.BinaryProcessor; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; import org.elasticsearch.xpack.sql.common.io.SqlStreamInput; -import org.elasticsearch.xpack.sql.expression.gen.processor.BinaryProcessor; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; import java.io.IOException; import java.time.ZoneId; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/CurrentDate.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/CurrentDate.java index 544788da245cf..5265932b16155 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/CurrentDate.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/CurrentDate.java @@ -6,10 +6,10 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.session.Configuration; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.session.Configuration; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.sql.type.SqlDataTypes; import org.elasticsearch.xpack.sql.util.DateUtils; import java.time.ZonedDateTime; @@ -17,7 +17,7 @@ public class CurrentDate extends CurrentFunction { public CurrentDate(Source source, Configuration configuration) { - super(source, configuration, DateUtils.asDateOnly(configuration.now()), DataType.DATE); + super(source, configuration, DateUtils.asDateOnly(configuration.now()), SqlDataTypes.DATE); } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/CurrentDateTime.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/CurrentDateTime.java index 16791421eb69b..1ff640d7915c4 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/CurrentDateTime.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/CurrentDateTime.java @@ -6,11 +6,11 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.session.Configuration; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.session.Configuration; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataTypes; import java.time.ZonedDateTime; @@ -21,7 +21,7 @@ public class CurrentDateTime extends CurrentFunction { private final Expression precision; public CurrentDateTime(Source source, Expression precision, Configuration configuration) { - super(source, configuration, nanoPrecision(configuration.now(), precision), DataType.DATETIME); + super(source, configuration, nanoPrecision(configuration.now(), precision), DataTypes.DATETIME); this.precision = precision; } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/CurrentFunction.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/CurrentFunction.java index 198ff03a9e6cd..30b18548ef341 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/CurrentFunction.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/CurrentFunction.java @@ -6,10 +6,10 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; +import org.elasticsearch.xpack.ql.session.Configuration; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; import org.elasticsearch.xpack.sql.expression.function.scalar.ConfigurationFunction; -import org.elasticsearch.xpack.sql.session.Configuration; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; import java.time.temporal.Temporal; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/CurrentTime.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/CurrentTime.java index dac8216e0c5af..a09d7149f4f56 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/CurrentTime.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/CurrentTime.java @@ -6,11 +6,11 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.session.Configuration; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.session.Configuration; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.sql.type.SqlDataTypes; import java.time.OffsetTime; @@ -22,7 +22,7 @@ public class CurrentTime extends CurrentFunction { public CurrentTime(Source source, Expression precision, Configuration configuration) { super(source, configuration, nanoPrecision(configuration.now().toOffsetDateTime().toOffsetTime(), precision), - DataType.TIME); + SqlDataTypes.TIME); this.precision = precision; } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateAdd.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateAdd.java index e29c234704ea8..c083c9209ba29 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateAdd.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateAdd.java @@ -5,12 +5,13 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import java.time.ZoneId; import java.time.ZonedDateTime; @@ -23,9 +24,9 @@ import java.util.function.BiFunction; import static org.elasticsearch.common.logging.LoggerMessageFormat.format; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isDate; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isInteger; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isString; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isInteger; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isString; +import static org.elasticsearch.xpack.sql.expression.SqlTypeResolutions.isDate; public class DateAdd extends ThreeArgsDateTimeFunction { @@ -122,7 +123,7 @@ protected TypeResolution resolveType() { @Override public DataType dataType() { - return DataType.DATETIME; + return DataTypes.DATETIME; } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateAddPipe.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateAddPipe.java index 6dbda129ecde0..fa8701c4b9d42 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateAddPipe.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateAddPipe.java @@ -5,11 +5,11 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.time.ZoneId; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateAddProcessor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateAddProcessor.java index dba298aad2b99..d4ef925bfc33e 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateAddProcessor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateAddProcessor.java @@ -6,9 +6,9 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateAdd.Part; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; import java.io.IOException; import java.time.ZoneId; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateDiff.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateDiff.java index 4c7def3d1b5cf..b34446bfd5029 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateDiff.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateDiff.java @@ -5,14 +5,15 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.Nullability; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.Nullability; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; import java.time.ZoneId; import java.time.ZonedDateTime; @@ -25,8 +26,8 @@ import java.util.function.BiFunction; import static org.elasticsearch.common.logging.LoggerMessageFormat.format; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isDate; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isString; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isString; +import static org.elasticsearch.xpack.sql.expression.SqlTypeResolutions.isDate; import static org.elasticsearch.xpack.sql.util.DateUtils.DAY_IN_MILLIS; import static org.elasticsearch.xpack.sql.util.DateUtils.UTC; @@ -170,7 +171,7 @@ protected TypeResolution resolveType() { @Override public DataType dataType() { - return DataType.INTEGER; + return DataTypes.INTEGER; } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateDiffPipe.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateDiffPipe.java index 7f12eecb9063c..d8e168a1b8057 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateDiffPipe.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateDiffPipe.java @@ -5,11 +5,11 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.time.ZoneId; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateDiffProcessor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateDiffProcessor.java index 2479148b1435f..f01fb093353ff 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateDiffProcessor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateDiffProcessor.java @@ -6,9 +6,9 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateDiff.Part; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; import java.io.IOException; import java.time.ZoneId; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DatePart.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DatePart.java index 73e0809d25973..3fcf7b7e6bd38 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DatePart.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DatePart.java @@ -5,13 +5,15 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.function.scalar.BinaryScalarFunction; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.function.scalar.BinaryScalarFunction; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTimeProcessor.DateTimeExtractor; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.NonIsoDateTimeProcessor.NonIsoDateTimeExtractor; import java.time.ZoneId; import java.time.ZonedDateTime; @@ -23,8 +25,6 @@ import java.util.Set; import java.util.function.ToIntFunction; -import static org.elasticsearch.xpack.sql.expression.function.scalar.datetime.NonIsoDateTimeProcessor.NonIsoDateTimeExtractor; - public class DatePart extends BinaryDateTimeFunction { public enum Part implements DateTimeField { @@ -83,7 +83,7 @@ public DatePart(Source source, Expression dateTimePart, Expression timestamp, Zo @Override public DataType dataType() { - return DataType.INTEGER; + return DataTypes.INTEGER; } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DatePartPipe.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DatePartPipe.java index 9eca90f845bf9..3279ba67202b1 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DatePartPipe.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DatePartPipe.java @@ -5,11 +5,11 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.time.ZoneId; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DatePartProcessor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DatePartProcessor.java index 616e953588f8d..80c86fdea44c7 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DatePartProcessor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DatePartProcessor.java @@ -6,16 +6,15 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DatePart.Part; import java.io.IOException; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.List; -import static org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DatePart.Part; - public class DatePartProcessor extends BinaryDateTimeProcessor { public static final String NAME = "dtpart"; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTimeField.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTimeField.java index 9cbb6ab7f2020..f6232e80df39b 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTimeField.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTimeField.java @@ -5,7 +5,7 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.util.StringUtils; +import org.elasticsearch.xpack.ql.util.StringUtils; import java.util.Arrays; import java.util.Collections; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTimeFunction.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTimeFunction.java index f4cccb9e7fd58..7ec72d7061e6d 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTimeFunction.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTimeFunction.java @@ -5,20 +5,21 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTimeProcessor.DateTimeExtractor; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.temporal.ChronoField; import java.time.temporal.Temporal; -import static org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder.paramsBuilder; +import static org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder.paramsBuilder; public abstract class DateTimeFunction extends BaseDateTimeFunction { @@ -58,7 +59,7 @@ protected Processor makeProcessor() { @Override public DataType dataType() { - return DataType.INTEGER; + return DataTypes.INTEGER; } // used for applying ranges diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTimeHistogramFunction.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTimeHistogramFunction.java index 0cf95169d38f9..f7aeecc2d0af6 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTimeHistogramFunction.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTimeHistogramFunction.java @@ -5,9 +5,9 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTimeProcessor.DateTimeExtractor; -import org.elasticsearch.xpack.sql.tree.Source; import java.time.ZoneId; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTrunc.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTrunc.java index df101a01fd8a1..c0a8b8d1eb18c 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTrunc.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTrunc.java @@ -5,12 +5,13 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.function.scalar.BinaryScalarFunction; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.function.scalar.BinaryScalarFunction; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import java.time.ZoneId; import java.time.ZonedDateTime; @@ -139,7 +140,7 @@ public DateTrunc(Source source, Expression truncateTo, Expression timestamp, Zon @Override public DataType dataType() { - return DataType.DATETIME; + return DataTypes.DATETIME; } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTruncPipe.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTruncPipe.java index 3a51f25ab63f9..b06b76c15327e 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTruncPipe.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTruncPipe.java @@ -5,11 +5,11 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.time.ZoneId; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTruncProcessor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTruncProcessor.java index 447e2ca410c3b..23cc096878ef5 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTruncProcessor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTruncProcessor.java @@ -6,16 +6,15 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTrunc.Part; import java.io.IOException; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.List; -import static org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTrunc.Part; - public class DateTruncProcessor extends BinaryDateTimeProcessor { public static final String NAME = "dtrunc"; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DayName.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DayName.java index 28972eb241844..00df7e0618dc1 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DayName.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DayName.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo.NodeCtor2; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.NamedDateTimeProcessor.NameExtractor; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo.NodeCtor2; import java.time.ZoneId; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DayOfMonth.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DayOfMonth.java index a228f4fe79bde..3230a721c8ac1 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DayOfMonth.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DayOfMonth.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo.NodeCtor2; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTimeProcessor.DateTimeExtractor; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo.NodeCtor2; import java.time.ZoneId; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DayOfWeek.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DayOfWeek.java index c8c0a1d568d2b..d22624192dfbc 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DayOfWeek.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DayOfWeek.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo.NodeCtor2; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.NonIsoDateTimeProcessor.NonIsoDateTimeExtractor; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo.NodeCtor2; import java.time.ZoneId; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DayOfYear.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DayOfYear.java index 6a54b53802a61..436dcd5e1d7fc 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DayOfYear.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DayOfYear.java @@ -5,11 +5,11 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.function.scalar.UnaryScalarFunction; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.function.scalar.UnaryScalarFunction; +import org.elasticsearch.xpack.ql.tree.NodeInfo.NodeCtor2; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTimeProcessor.DateTimeExtractor; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo.NodeCtor2; import java.time.ZoneId; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/HourOfDay.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/HourOfDay.java index c15a730e25b3f..038e14d868b45 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/HourOfDay.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/HourOfDay.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo.NodeCtor2; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTimeProcessor.DateTimeExtractor; -import org.elasticsearch.xpack.sql.tree.NodeInfo.NodeCtor2; -import org.elasticsearch.xpack.sql.tree.Source; import java.time.ZoneId; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/IsoDayOfWeek.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/IsoDayOfWeek.java index 8bc5903834a0e..b18d2a45a8522 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/IsoDayOfWeek.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/IsoDayOfWeek.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo.NodeCtor2; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTimeProcessor.DateTimeExtractor; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo.NodeCtor2; import java.time.ZoneId; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/IsoWeekOfYear.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/IsoWeekOfYear.java index 04a45b1732693..d1deeca0ecf24 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/IsoWeekOfYear.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/IsoWeekOfYear.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo.NodeCtor2; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTimeProcessor.DateTimeExtractor; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo.NodeCtor2; import java.time.ZoneId; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/MinuteOfDay.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/MinuteOfDay.java index 823de40034feb..e5c1bddb6931f 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/MinuteOfDay.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/MinuteOfDay.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo.NodeCtor2; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTimeProcessor.DateTimeExtractor; -import org.elasticsearch.xpack.sql.tree.NodeInfo.NodeCtor2; -import org.elasticsearch.xpack.sql.tree.Source; import java.time.ZoneId; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/MinuteOfHour.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/MinuteOfHour.java index 1136b858a7227..e72033491e96c 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/MinuteOfHour.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/MinuteOfHour.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo.NodeCtor2; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTimeProcessor.DateTimeExtractor; -import org.elasticsearch.xpack.sql.tree.NodeInfo.NodeCtor2; -import org.elasticsearch.xpack.sql.tree.Source; import java.time.ZoneId; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/MonthName.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/MonthName.java index 17fbe374aacc3..b85c0e976753b 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/MonthName.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/MonthName.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo.NodeCtor2; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.NamedDateTimeProcessor.NameExtractor; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo.NodeCtor2; import java.time.ZoneId; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/MonthOfYear.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/MonthOfYear.java index 8265dedb7ba2e..c8c99dfa762a7 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/MonthOfYear.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/MonthOfYear.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo.NodeCtor2; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTimeProcessor.DateTimeExtractor; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo.NodeCtor2; import java.time.ZoneId; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/NamedDateTimeFunction.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/NamedDateTimeFunction.java index 0dada3f3c0e19..920d5a85afc49 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/NamedDateTimeFunction.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/NamedDateTimeFunction.java @@ -5,18 +5,19 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; +import org.elasticsearch.xpack.ql.util.StringUtils; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.NamedDateTimeProcessor.NameExtractor; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.util.StringUtils; import java.time.ZoneId; -import static org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder.paramsBuilder; +import static org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder.paramsBuilder; /* * Base class for "named" date/time functions like month_name and day_name @@ -48,6 +49,6 @@ protected Processor makeProcessor() { @Override public DataType dataType() { - return DataType.KEYWORD; + return DataTypes.KEYWORD; } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/NonIsoDateTimeFunction.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/NonIsoDateTimeFunction.java index 576ed6bc9ab92..a558dfed724d7 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/NonIsoDateTimeFunction.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/NonIsoDateTimeFunction.java @@ -5,18 +5,19 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; +import org.elasticsearch.xpack.ql.util.StringUtils; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.NonIsoDateTimeProcessor.NonIsoDateTimeExtractor; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.util.StringUtils; import java.time.ZoneId; -import static org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder.paramsBuilder; +import static org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder.paramsBuilder; /* * Base class for date/time functions that behave differently in a non-ISO format @@ -48,6 +49,6 @@ protected Processor makeProcessor() { @Override public DataType dataType() { - return DataType.INTEGER; + return DataTypes.INTEGER; } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/Quarter.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/Quarter.java index f23082c7e0358..3b981a689a0f2 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/Quarter.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/Quarter.java @@ -6,17 +6,18 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.tree.NodeInfo.NodeCtor2; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.tree.NodeInfo.NodeCtor2; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import java.time.ZoneId; -import static org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder.paramsBuilder; +import static org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder.paramsBuilder; public class Quarter extends BaseDateTimeFunction { @@ -51,6 +52,6 @@ protected Processor makeProcessor() { @Override public DataType dataType() { - return DataType.INTEGER; + return DataTypes.INTEGER; } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/SecondOfMinute.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/SecondOfMinute.java index fb83191f5bcbd..ff0f53bc891c3 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/SecondOfMinute.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/SecondOfMinute.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo.NodeCtor2; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTimeProcessor.DateTimeExtractor; -import org.elasticsearch.xpack.sql.tree.NodeInfo.NodeCtor2; -import org.elasticsearch.xpack.sql.tree.Source; import java.time.ZoneId; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/ThreeArgsDateTimeFunction.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/ThreeArgsDateTimeFunction.java index 6b7c0c30ae7bc..ff58acfe8fbe7 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/ThreeArgsDateTimeFunction.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/ThreeArgsDateTimeFunction.java @@ -5,12 +5,12 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.function.scalar.ScalarFunction; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.function.scalar.ScalarFunction; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.tree.Source; import java.time.ZoneId; import java.util.Arrays; @@ -18,7 +18,7 @@ import java.util.Locale; import java.util.Objects; -import static org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder.paramsBuilder; +import static org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder.paramsBuilder; public abstract class ThreeArgsDateTimeFunction extends ScalarFunction { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/ThreeArgsDateTimePipe.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/ThreeArgsDateTimePipe.java index e1d60b1232b3d..2b0d951b2a261 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/ThreeArgsDateTimePipe.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/ThreeArgsDateTimePipe.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.tree.Source; import java.time.ZoneId; import java.util.Arrays; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/ThreeArgsDateTimeProcessor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/ThreeArgsDateTimeProcessor.java index bc22c83c325b5..3caa68b4bbd9a 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/ThreeArgsDateTimeProcessor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/ThreeArgsDateTimeProcessor.java @@ -7,8 +7,8 @@ import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; import org.elasticsearch.xpack.sql.common.io.SqlStreamInput; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; import java.io.IOException; import java.time.ZoneId; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/TimeFunction.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/TimeFunction.java index 857d8fada5bd4..887959b5966ad 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/TimeFunction.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/TimeFunction.java @@ -5,17 +5,17 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTimeProcessor.DateTimeExtractor; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.tree.Source; import java.time.OffsetTime; import java.time.ZoneId; import java.time.temporal.ChronoField; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isDateOrTime; +import static org.elasticsearch.xpack.sql.expression.SqlTypeResolutions.isDateOrTime; import static org.elasticsearch.xpack.sql.util.DateUtils.asTimeAtZone; public abstract class TimeFunction extends DateTimeFunction { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/WeekOfYear.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/WeekOfYear.java index 566d3c4443c5e..c17f7285860ea 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/WeekOfYear.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/WeekOfYear.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo.NodeCtor2; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.NonIsoDateTimeProcessor.NonIsoDateTimeExtractor; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo.NodeCtor2; import java.time.ZoneId; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/Year.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/Year.java index 0720706de226d..e97689c6b9e22 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/Year.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/Year.java @@ -6,10 +6,10 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo.NodeCtor2; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTimeProcessor.DateTimeExtractor; -import org.elasticsearch.xpack.sql.tree.NodeInfo.NodeCtor2; -import org.elasticsearch.xpack.sql.tree.Source; import java.time.ZoneId; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/GeoProcessor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/GeoProcessor.java index 519e4c0c74092..d9b188a6a96d6 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/GeoProcessor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/GeoProcessor.java @@ -7,8 +7,9 @@ import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.sql.expression.literal.geo.GeoShape; import java.io.IOException; import java.util.function.Function; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StAswkt.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StAswkt.java index 5c4b6edbe87eb..ee45b3b646518 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StAswkt.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StAswkt.java @@ -7,11 +7,12 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.geo; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.expression.function.scalar.geo.GeoProcessor.GeoOperation; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; /** * ST_AsWKT function that takes a geometry and returns its Well Known Text representation @@ -39,7 +40,7 @@ protected GeoOperation operation() { @Override public DataType dataType() { - return DataType.KEYWORD; + return DataTypes.KEYWORD; } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StDistance.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StDistance.java index fd14e90dd9d93..1dc7f2efbfbf5 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StDistance.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StDistance.java @@ -6,18 +6,19 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.geo; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.expression.predicate.BinaryOperator; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.expression.predicate.BinaryOperator; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isGeo; -import static org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder.paramsBuilder; +import static org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder.paramsBuilder; +import static org.elasticsearch.xpack.sql.expression.SqlTypeResolutions.isGeo; /** * Calculates the distance between two points @@ -37,7 +38,7 @@ protected StDistance replaceChildren(Expression newLeft, Expression newRight) { @Override public DataType dataType() { - return DataType.DOUBLE; + return DataTypes.DOUBLE; } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StDistanceFunction.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StDistanceFunction.java index d1c15c1e2a1b2..bc4def54930fd 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StDistanceFunction.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StDistanceFunction.java @@ -6,7 +6,7 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.geo; -import org.elasticsearch.xpack.sql.expression.predicate.PredicateBiFunction; +import org.elasticsearch.xpack.ql.expression.predicate.PredicateBiFunction; class StDistanceFunction implements PredicateBiFunction { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StDistancePipe.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StDistancePipe.java index c944266482651..27c1d0c8e7c16 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StDistancePipe.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StDistancePipe.java @@ -5,11 +5,11 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.geo; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.BinaryPipe; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.BinaryPipe; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StDistanceProcessor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StDistanceProcessor.java index d6c9026b982d9..86e9068643bd4 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StDistanceProcessor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StDistanceProcessor.java @@ -8,9 +8,10 @@ import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; +import org.elasticsearch.xpack.ql.expression.gen.processor.BinaryProcessor; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.gen.processor.BinaryProcessor; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.sql.expression.literal.geo.GeoShape; import java.io.IOException; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StGeometryType.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StGeometryType.java index 15215bd9201de..d3c49931906cb 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StGeometryType.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StGeometryType.java @@ -7,11 +7,12 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.geo; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.expression.function.scalar.geo.GeoProcessor.GeoOperation; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; /** * ST_GEOMETRY_TYPE function that takes a geometry and returns its type @@ -39,7 +40,7 @@ protected GeoOperation operation() { @Override public DataType dataType() { - return DataType.KEYWORD; + return DataTypes.KEYWORD; } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StWkttosql.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StWkttosql.java index 04006d4a28b51..fc3c026c5fa46 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StWkttosql.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StWkttosql.java @@ -6,16 +6,18 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.geo; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.function.scalar.UnaryScalarFunction; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.expression.gen.script.Scripts; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.function.scalar.UnaryScalarFunction; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.gen.script.Scripts; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; +import org.elasticsearch.xpack.sql.type.SqlDataTypes; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isString; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isString; /** * Constructs geometric objects from their WTK representations @@ -33,7 +35,7 @@ protected StWkttosql replaceChild(Expression newChild) { @Override protected TypeResolution resolveType() { - if (field().dataType().isString()) { + if (DataTypes.isString(field().dataType())) { return TypeResolution.TYPE_RESOLVED; } return isString(field(), sourceText(), Expressions.ParamOrdinal.DEFAULT); @@ -46,7 +48,7 @@ protected Processor makeProcessor() { @Override public DataType dataType() { - return DataType.GEO_SHAPE; + return SqlDataTypes.GEO_SHAPE; } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StWkttosqlProcessor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StWkttosqlProcessor.java index f17ee2315befe..2057e8eb2ace2 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StWkttosqlProcessor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StWkttosqlProcessor.java @@ -9,8 +9,9 @@ import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.sql.expression.literal.geo.GeoShape; import java.io.IOException; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StX.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StX.java index f3cdafbe70dab..7f2d78c132490 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StX.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StX.java @@ -7,11 +7,12 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.geo; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.expression.function.scalar.geo.GeoProcessor.GeoOperation; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; /** * ST_X function that takes a geometry and returns the X coordinate of its first point @@ -39,7 +40,7 @@ protected GeoOperation operation() { @Override public DataType dataType() { - return DataType.DOUBLE; + return DataTypes.DOUBLE; } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StY.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StY.java index 0a9bc3aa1a40b..a727427010f04 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StY.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StY.java @@ -7,11 +7,12 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.geo; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.expression.function.scalar.geo.GeoProcessor.GeoOperation; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; /** * ST_Y function that takes a geometry and returns the Y coordinate of its first point @@ -39,7 +40,7 @@ protected GeoOperation operation() { @Override public DataType dataType() { - return DataType.DOUBLE; + return DataTypes.DOUBLE; } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StZ.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StZ.java index b6c0c9466bbe1..85d5b9271acb3 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StZ.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StZ.java @@ -7,11 +7,12 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.geo; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.expression.function.scalar.geo.GeoProcessor.GeoOperation; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; /** * ST_Z function that takes a geometry and returns the Z coordinate of its first point @@ -39,7 +40,7 @@ protected GeoOperation operation() { @Override public DataType dataType() { - return DataType.DOUBLE; + return DataTypes.DOUBLE; } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/UnaryGeoFunction.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/UnaryGeoFunction.java index 50c05b7fbedb7..fa15209773ba6 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/UnaryGeoFunction.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/UnaryGeoFunction.java @@ -6,21 +6,21 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.geo; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; -import org.elasticsearch.xpack.sql.expression.function.scalar.UnaryScalarFunction; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.util.StringUtils; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.expression.function.scalar.UnaryScalarFunction; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.util.StringUtils; import java.util.Locale; import java.util.Objects; import static java.lang.String.format; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isGeo; -import static org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder.paramsBuilder; +import static org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder.paramsBuilder; +import static org.elasticsearch.xpack.sql.expression.SqlTypeResolutions.isGeo; /** * Base class for functions that get a single geo shape or geo point as an argument diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/ACos.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/ACos.java index 692535019e229..0d9b750cd8c47 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/ACos.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/ACos.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; /** diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/ASin.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/ASin.java index b4698bad48cc7..f642c57d0d6c4 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/ASin.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/ASin.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; /** * Arc sine diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/ATan.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/ATan.java index 06f5f140ac27b..5e2ff129b16d0 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/ATan.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/ATan.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; /** * Arc tangent diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/ATan2.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/ATan2.java index 9b15b2a67b470..16c3a5f235c8c 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/ATan2.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/ATan2.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.math.BinaryMathProcessor.BinaryMathOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; /** * Multi-valued inverse tangent diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Abs.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Abs.java index d0c889db66f4c..9a192b0a67e96 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Abs.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Abs.java @@ -5,11 +5,11 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.type.DataType; /** * Absolute value diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/BinaryMathPipe.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/BinaryMathPipe.java index 5e266639d0d6b..fbbdbf6b061c3 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/BinaryMathPipe.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/BinaryMathPipe.java @@ -5,12 +5,12 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.BinaryPipe; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.math.BinaryMathProcessor.BinaryMathOperation; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.BinaryPipe; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/BinaryMathProcessor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/BinaryMathProcessor.java index f66dcf185fcb7..413f77ff28aea 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/BinaryMathProcessor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/BinaryMathProcessor.java @@ -6,12 +6,12 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.math; import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.xpack.ql.expression.gen.processor.FunctionalEnumBinaryProcessor; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.Arithmetics; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; import org.elasticsearch.xpack.sql.expression.function.scalar.math.BinaryMathProcessor.BinaryMathOperation; import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation; -import org.elasticsearch.xpack.sql.expression.gen.processor.FunctionalBinaryProcessor; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Arithmetics; import java.io.IOException; import java.util.function.BiFunction; @@ -19,7 +19,7 @@ /** * Binary math operations. Sister class to {@link MathOperation}. */ -public class BinaryMathProcessor extends FunctionalBinaryProcessor { +public class BinaryMathProcessor extends FunctionalEnumBinaryProcessor { public enum BinaryMathOperation implements BiFunction { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/BinaryNumericFunction.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/BinaryNumericFunction.java index 98bb36d175d61..a799e240d5442 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/BinaryNumericFunction.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/BinaryNumericFunction.java @@ -5,18 +5,19 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.Expressions.ParamOrdinal; -import org.elasticsearch.xpack.sql.expression.function.scalar.BinaryScalarFunction; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.Expressions.ParamOrdinal; +import org.elasticsearch.xpack.ql.expression.function.scalar.BinaryScalarFunction; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.expression.function.scalar.math.BinaryMathProcessor.BinaryMathOperation; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; import java.util.Objects; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isNumeric; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isNumeric; public abstract class BinaryNumericFunction extends BinaryScalarFunction { @@ -29,7 +30,7 @@ public abstract class BinaryNumericFunction extends BinaryScalarFunction { @Override public DataType dataType() { - return DataType.DOUBLE; + return DataTypes.DOUBLE; } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/BinaryOptionalMathPipe.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/BinaryOptionalMathPipe.java index 0897050c97be3..d471950315c78 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/BinaryOptionalMathPipe.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/BinaryOptionalMathPipe.java @@ -6,12 +6,12 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.execution.search.SqlSourceBuilder; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.execution.search.QlSourceBuilder; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.math.BinaryOptionalMathProcessor.BinaryOptionalMathOperation; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; import java.util.Arrays; import java.util.List; @@ -63,7 +63,7 @@ protected Pipe replaceChildren(Pipe newLeft, Pipe newRight) { } @Override - public final void collectFields(SqlSourceBuilder sourceBuilder) { + public final void collectFields(QlSourceBuilder sourceBuilder) { left.collectFields(sourceBuilder); if (right != null) { right.collectFields(sourceBuilder); diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/BinaryOptionalMathProcessor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/BinaryOptionalMathProcessor.java index dc89b6ce5cff1..7ad197c8a1071 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/BinaryOptionalMathProcessor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/BinaryOptionalMathProcessor.java @@ -8,8 +8,8 @@ import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; import java.io.IOException; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/BinaryOptionalNumericFunction.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/BinaryOptionalNumericFunction.java index 8b6996ab64e26..b0f2d0f5c3a5f 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/BinaryOptionalNumericFunction.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/BinaryOptionalNumericFunction.java @@ -6,15 +6,16 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.Expressions.ParamOrdinal; -import org.elasticsearch.xpack.sql.expression.function.scalar.ScalarFunction; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.Expressions.ParamOrdinal; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.function.scalar.ScalarFunction; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; import org.elasticsearch.xpack.sql.expression.function.scalar.math.BinaryOptionalMathProcessor.BinaryOptionalMathOperation; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; import java.util.Arrays; import java.util.List; @@ -22,9 +23,9 @@ import java.util.Objects; import static java.lang.String.format; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isInteger; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isNumeric; -import static org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder.paramsBuilder; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isInteger; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isNumeric; +import static org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder.paramsBuilder; public abstract class BinaryOptionalNumericFunction extends ScalarFunction { @@ -88,7 +89,7 @@ public Expression replaceChildren(List newChildren) { @Override public ScriptTemplate asScript() { ScriptTemplate leftScript = asScript(left); - ScriptTemplate rightScript = asOptionalScript(right); + ScriptTemplate rightScript = asScript(right == null ? Literal.NULL : right); return asScriptFrom(leftScript, rightScript); } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Cbrt.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Cbrt.java index d6cc7e85dcedc..5b506d9fe7a27 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Cbrt.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Cbrt.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; /** * Cube root diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Ceil.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Ceil.java index 5c9438c677221..0727197f1e51e 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Ceil.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Ceil.java @@ -5,12 +5,12 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypeConverter; import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.DataTypeConversion; /** * Ceiling @@ -37,7 +37,7 @@ public Number fold() { if (result == null) { return null; } - return DataTypeConversion.toInteger((double) result, dataType()); + return DataTypeConverter.toInteger((double) result, dataType()); } @Override @@ -47,6 +47,6 @@ protected MathOperation operation() { @Override public DataType dataType() { - return DataTypeConversion.asInteger(field().dataType()); + return DataTypeConverter.asInteger(field().dataType()); } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Cos.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Cos.java index 48cb486121d44..f5e1c25ba2fba 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Cos.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Cos.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; /** * Cosine diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Cosh.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Cosh.java index ce5bd2bcc45ff..788a0d1da4b3a 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Cosh.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Cosh.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; /** * Hyperbolic cosine diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Cot.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Cot.java index 060702bd62d6a..2c9d585c03911 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Cot.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Cot.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; /** * Cotangent diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Degrees.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Degrees.java index f4b9ec6080e09..0015553965052 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Degrees.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Degrees.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; /** * Convert from radians diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/E.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/E.java index b1b731fe91be9..28a58f3a8717f 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/E.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/E.java @@ -6,21 +6,21 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.gen.script.Params; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation; -import org.elasticsearch.xpack.sql.expression.gen.script.Params; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; public class E extends MathFunction { - private static final ScriptTemplate TEMPLATE = new ScriptTemplate("Math.E", Params.EMPTY, DataType.DOUBLE); + private static final ScriptTemplate TEMPLATE = new ScriptTemplate("Math.E", Params.EMPTY, DataTypes.DOUBLE); public E(Source source) { - super(source, new Literal(source, Math.E, DataType.DOUBLE)); + super(source, new Literal(source, Math.E, DataTypes.DOUBLE)); } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Exp.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Exp.java index 8eab843d17028..95e67c80a55da 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Exp.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Exp.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; /** * ex diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Expm1.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Expm1.java index 6f362fe63b864..3a8928cee4975 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Expm1.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Expm1.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; /** * ex + 1 diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Floor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Floor.java index a77a4e497d31a..9e66623a0b1d4 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Floor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Floor.java @@ -5,12 +5,12 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypeConverter; import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.DataTypeConversion; /** * Floor @@ -37,7 +37,7 @@ public Object fold() { if (result == null) { return null; } - return DataTypeConversion.toInteger((double) result, dataType()); + return DataTypeConverter.toInteger((double) result, dataType()); } @Override @@ -47,6 +47,6 @@ protected MathOperation operation() { @Override public DataType dataType() { - return DataTypeConversion.asInteger(field().dataType()); + return DataTypeConverter.asInteger(field().dataType()); } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Log.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Log.java index 7c0f3e46bedb1..55eaaafc0784a 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Log.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Log.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; /** * Natural logarithm diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Log10.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Log10.java index e4583d1eb8ecf..2e8e4c255226b 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Log10.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Log10.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; /** * Logarithm diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/MathFunction.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/MathFunction.java index 4389e1ac814a9..0bbcf75dbb89f 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/MathFunction.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/MathFunction.java @@ -5,19 +5,20 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions.ParamOrdinal; -import org.elasticsearch.xpack.sql.expression.function.scalar.UnaryScalarFunction; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions.ParamOrdinal; +import org.elasticsearch.xpack.ql.expression.function.scalar.UnaryScalarFunction; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; import java.util.Locale; import java.util.Objects; import static java.lang.String.format; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isNumeric; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isNumeric; public abstract class MathFunction extends UnaryScalarFunction { @@ -47,7 +48,7 @@ public String processScript(String template) { @Override public DataType dataType() { - return DataType.DOUBLE; + return DataTypes.DOUBLE; } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/MathProcessor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/MathProcessor.java index 2f71f63484792..07acf3a43149c 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/MathProcessor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/MathProcessor.java @@ -8,8 +8,10 @@ import org.elasticsearch.common.Randomness; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.type.DataTypeConverter; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; import java.io.IOException; import java.util.Random; @@ -21,17 +23,38 @@ public class MathProcessor implements Processor { public enum MathOperation { ABS((Object l) -> { - if (l instanceof Float) { - return Double.valueOf(Math.abs(((Float) l).floatValue())); - } if (l instanceof Double) { return Math.abs(((Double) l).doubleValue()); } + if (l instanceof Float) { + return Math.abs(((Float) l).floatValue()); + } + + // fallback to integer long lo = ((Number) l).longValue(); - //handles the corner-case of Long.MIN_VALUE - return lo >= 0 ? lo : lo == Long.MIN_VALUE ? Double.valueOf(Long.MAX_VALUE) : -lo; - }), + if (lo == Long.MIN_VALUE) { + throw new QlIllegalArgumentException("[" + lo + "] cannot be negated since the result is outside the range"); + } + + lo = lo < 0 ? -lo : lo; + + if (l instanceof Integer) { + if ((int) lo == Integer.MIN_VALUE) { + throw new QlIllegalArgumentException("[" + lo + "] cannot be negated since the result is outside the range"); + } + return DataTypeConverter.safeToInt(lo); + } + + if (l instanceof Short) { + return DataTypeConverter.safeToShort(lo); + } + if (l instanceof Byte) { + return DataTypeConverter.safeToByte(lo); + } + + return lo; + }), ACOS(Math::acos), ASIN(Math::asin), ATAN(Math::atan), @@ -52,15 +75,37 @@ public enum MathOperation { RANDOM((Object l) -> l != null ? new Random(((Number) l).longValue()).nextDouble() : Randomness.get().nextDouble(), true), - SIGN((DoubleFunction) Math::signum), + SIGN((Object l) -> { + if (l instanceof Double) { + return Math.signum((Double) l); + } + if (l instanceof Float) { + return Math.signum((Float) l); + } + + long lo = Long.signum(((Number) l).longValue()); + + if (l instanceof Integer) { + return DataTypeConverter.safeToInt(lo); + } + if (l instanceof Short) { + return DataTypeConverter.safeToShort(lo); + } + if (l instanceof Byte) { + return DataTypeConverter.safeToByte(lo); + } + + //fallback to generic double + return lo; + }), SIN(Math::sin), SINH(Math::sinh), SQRT(Math::sqrt), TAN(Math::tan); - private final Function apply; + private final Function apply; - MathOperation(Function apply) { + MathOperation(Function apply) { this(apply, false); } @@ -69,7 +114,7 @@ public enum MathOperation { * If true, nulls are passed through, otherwise the function is short-circuited * and null returned. */ - MathOperation(Function apply, boolean nullAware) { + MathOperation(Function apply, boolean nullAware) { if (nullAware) { this.apply = apply; } else { @@ -85,7 +130,7 @@ public enum MathOperation { this.apply = l -> supplier.get(); } - public final Double apply(Object l) { + public final Number apply(Object l) { return apply.apply(l); } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Pi.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Pi.java index 79492bac3c12e..145f380d5bba2 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Pi.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Pi.java @@ -6,21 +6,21 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.gen.script.Params; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation; -import org.elasticsearch.xpack.sql.expression.gen.script.Params; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; public class Pi extends MathFunction { - private static final ScriptTemplate TEMPLATE = new ScriptTemplate("Math.PI", Params.EMPTY, DataType.DOUBLE); + private static final ScriptTemplate TEMPLATE = new ScriptTemplate("Math.PI", Params.EMPTY, DataTypes.DOUBLE); public Pi(Source source) { - super(source, new Literal(source, Math.PI, DataType.DOUBLE)); + super(source, new Literal(source, Math.PI, DataTypes.DOUBLE)); } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Power.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Power.java index ec4261d3f07a6..3f8acdeca0c57 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Power.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Power.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.math.BinaryMathProcessor.BinaryMathOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; public class Power extends BinaryNumericFunction { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Radians.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Radians.java index ee63bfa3b0332..f61ebadcea792 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Radians.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Radians.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; /** * Convert from degrees diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Random.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Random.java index 70dff7d1ccd44..11c4374024e79 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Random.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Random.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; /** * Returns a random double (using the given seed). diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Round.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Round.java index 98c2e75906ce0..9b353dfbe5776 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Round.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Round.java @@ -5,10 +5,11 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.function.OptionalArgument; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.math.BinaryOptionalMathProcessor.BinaryOptionalMathOperation; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; import java.util.List; @@ -18,7 +19,7 @@ * count digits after the decimal point. If negative, it will round the number till that paramter count * digits before the decimal point, starting at the decimal point. */ -public class Round extends BinaryOptionalNumericFunction { +public class Round extends BinaryOptionalNumericFunction implements OptionalArgument { public Round(Source source, Expression left, Expression right) { super(source, left, right); diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Sign.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Sign.java index d9ebe34e3594c..5167311c18844 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Sign.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Sign.java @@ -5,11 +5,12 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.type.DataType; /** * Returns the sign of the given expression: @@ -41,6 +42,6 @@ protected MathOperation operation() { @Override public DataType dataType() { - return DataType.INTEGER; + return DataTypes.INTEGER; } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Sin.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Sin.java index 8fff2be48b3a8..e4030ad4c44b2 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Sin.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Sin.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; /** * Sine diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Sinh.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Sinh.java index 80830af0d5cd3..0264f03224de6 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Sinh.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Sinh.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; /** * Hyperbolic sine diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Sqrt.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Sqrt.java index 30778a8f9791e..6eb559eeb87ca 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Sqrt.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Sqrt.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; /** * Square root diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Tan.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Tan.java index 2c8a7ef142f15..f71fec91da003 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Tan.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Tan.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; /** * Tangent diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Truncate.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Truncate.java index cf08c6c6eaa1f..dee6306f94bc1 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Truncate.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Truncate.java @@ -5,10 +5,11 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.math; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.function.OptionalArgument; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.math.BinaryOptionalMathProcessor.BinaryOptionalMathOperation; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; import java.util.List; @@ -18,7 +19,7 @@ * parameter count digits after the decimal point. If negative, it will truncate the number till that parameter * count digits before the decimal point, starting at the decimal point. */ -public class Truncate extends BinaryOptionalNumericFunction { +public class Truncate extends BinaryOptionalNumericFunction implements OptionalArgument { public Truncate(Source source, Expression left, Expression right) { super(source, left, right); diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Ascii.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Ascii.java index 65c173cb9035f..08b1d1b611e6b 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Ascii.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Ascii.java @@ -5,11 +5,12 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.expression.function.scalar.string.StringProcessor.StringOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.type.DataType; /** * Returns the ASCII code of the leftmost character of the given (char) expression. @@ -37,6 +38,6 @@ protected StringOperation operation() { @Override public DataType dataType() { - return DataType.INTEGER; + return DataTypes.INTEGER; } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringFunction.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringFunction.java index 611e86507ee5b..57a1abe58d077 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringFunction.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringFunction.java @@ -5,19 +5,19 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions.ParamOrdinal; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; -import org.elasticsearch.xpack.sql.expression.function.scalar.BinaryScalarFunction; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions.ParamOrdinal; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.expression.function.scalar.BinaryScalarFunction; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Locale; import java.util.Objects; import java.util.function.BiFunction; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isStringAndExact; -import static org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder.paramsBuilder; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isStringAndExact; +import static org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder.paramsBuilder; /** * Base class for binary functions that have the first parameter a string, the second parameter a number diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringNumericFunction.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringNumericFunction.java index fac0646c2c611..9508c6095d09a 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringNumericFunction.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringNumericFunction.java @@ -5,14 +5,15 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.expression.function.scalar.string.BinaryStringNumericProcessor.BinaryStringNumericOperation; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isNumeric; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isNumeric; /** * A binary string function with a numeric second parameter and a string result @@ -38,6 +39,6 @@ protected Pipe makePipe() { @Override public DataType dataType() { - return DataType.KEYWORD; + return DataTypes.KEYWORD; } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringNumericPipe.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringNumericPipe.java index f64dea2a8a081..05a8ce22b3c28 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringNumericPipe.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringNumericPipe.java @@ -5,12 +5,12 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.BinaryPipe; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.string.BinaryStringNumericProcessor.BinaryStringNumericOperation; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.BinaryPipe; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringNumericProcessor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringNumericProcessor.java index 2296b46c4b4a8..64e84351f9d85 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringNumericProcessor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringNumericProcessor.java @@ -6,10 +6,10 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.string; import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.xpack.ql.expression.gen.processor.FunctionalEnumBinaryProcessor; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; import org.elasticsearch.xpack.sql.expression.function.scalar.string.BinaryStringNumericProcessor.BinaryStringNumericOperation; -import org.elasticsearch.xpack.sql.expression.gen.processor.FunctionalBinaryProcessor; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; import java.io.IOException; import java.util.function.BiFunction; @@ -18,7 +18,7 @@ * Processor class covering string manipulating functions that have the first parameter as string, * second parameter as numeric and a string result. */ -public class BinaryStringNumericProcessor extends FunctionalBinaryProcessor { +public class BinaryStringNumericProcessor extends FunctionalEnumBinaryProcessor { public enum BinaryStringNumericOperation implements BiFunction { LEFT((s,c) -> { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringStringFunction.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringStringFunction.java index eaa6ac428c85f..d93553ce316bb 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringStringFunction.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringStringFunction.java @@ -5,12 +5,13 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isStringAndExact; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isStringAndExact; /** * A binary string function with two string parameters and a numeric result @@ -28,6 +29,6 @@ protected TypeResolution resolveSecondParameterInputType(Expression e) { @Override public DataType dataType() { - return DataType.INTEGER; + return DataTypes.INTEGER; } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringStringPipe.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringStringPipe.java index 23f3940d73d08..82d5956f4b27d 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringStringPipe.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringStringPipe.java @@ -5,12 +5,12 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.BinaryPipe; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.string.BinaryStringStringProcessor.BinaryStringStringOperation; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.BinaryPipe; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringStringProcessor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringStringProcessor.java index 00836d2c28441..ad2e1232cda05 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringStringProcessor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringStringProcessor.java @@ -6,10 +6,10 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.string; import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.xpack.ql.expression.gen.processor.FunctionalEnumBinaryProcessor; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; import org.elasticsearch.xpack.sql.expression.function.scalar.string.BinaryStringStringProcessor.BinaryStringStringOperation; -import org.elasticsearch.xpack.sql.expression.gen.processor.FunctionalBinaryProcessor; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; import java.io.IOException; import java.util.function.BiFunction; @@ -17,7 +17,7 @@ /** * Processor class covering string manipulating functions that have two string parameters and a numeric result. */ -public class BinaryStringStringProcessor extends FunctionalBinaryProcessor { +public class BinaryStringStringProcessor extends FunctionalEnumBinaryProcessor { public enum BinaryStringStringOperation implements BiFunction { POSITION((sub,str) -> { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BitLength.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BitLength.java index 11806d4ab9951..e9512d47fe576 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BitLength.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BitLength.java @@ -5,11 +5,12 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.expression.function.scalar.string.StringProcessor.StringOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.type.DataType; /** * Returns the number of bits contained within the value expression. @@ -38,6 +39,6 @@ protected StringOperation operation() { @Override public DataType dataType() { //TODO investigate if a data type Long (BIGINT) wouldn't be more appropriate here - return DataType.INTEGER; + return DataTypes.INTEGER; } } \ No newline at end of file diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Char.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Char.java index 2216d211cd264..b37d02dbbef26 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Char.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Char.java @@ -5,11 +5,12 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.expression.function.scalar.string.StringProcessor.StringOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.type.DataType; /** * Converts an int ASCII code to a character value. @@ -37,6 +38,6 @@ protected StringOperation operation() { @Override public DataType dataType() { - return DataType.KEYWORD; + return DataTypes.KEYWORD; } } \ No newline at end of file diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/CharLength.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/CharLength.java index 45f0c1e781a0a..a19039f79b3c9 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/CharLength.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/CharLength.java @@ -5,11 +5,12 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.expression.function.scalar.string.StringProcessor.StringOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.type.DataType; /** * Returns the length (in characters) of the string expression. @@ -37,6 +38,6 @@ protected StringOperation operation() { @Override public DataType dataType() { - return DataType.INTEGER; + return DataTypes.INTEGER; } } \ No newline at end of file diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Concat.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Concat.java index 15602bc53c880..f811de23e0f7c 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Concat.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Concat.java @@ -5,21 +5,22 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.Expressions.ParamOrdinal; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; -import org.elasticsearch.xpack.sql.expression.Nullability; -import org.elasticsearch.xpack.sql.expression.function.scalar.BinaryScalarFunction; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.Expressions.ParamOrdinal; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.expression.Nullability; +import org.elasticsearch.xpack.ql.expression.function.scalar.BinaryScalarFunction; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isStringAndExact; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isStringAndExact; +import static org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder.paramsBuilder; import static org.elasticsearch.xpack.sql.expression.function.scalar.string.ConcatFunctionProcessor.process; -import static org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder.paramsBuilder; /** * Returns a string that is the result of concatenating the two strings received as parameters. @@ -85,6 +86,6 @@ public ScriptTemplate scriptWithField(FieldAttribute field) { @Override public DataType dataType() { - return DataType.KEYWORD; + return DataTypes.KEYWORD; } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ConcatFunctionPipe.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ConcatFunctionPipe.java index 03be678709459..db2e83795bea0 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ConcatFunctionPipe.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ConcatFunctionPipe.java @@ -5,11 +5,11 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.BinaryPipe; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.BinaryPipe; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ConcatFunctionProcessor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ConcatFunctionProcessor.java index 55dc1ea213f45..0effd1e1f5441 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ConcatFunctionProcessor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ConcatFunctionProcessor.java @@ -7,10 +7,10 @@ import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; +import org.elasticsearch.xpack.ql.expression.gen.processor.BinaryProcessor; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.util.StringUtils; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.gen.processor.BinaryProcessor; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.util.StringUtils; import java.io.IOException; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Insert.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Insert.java index 8cff98d4c7c80..7b0ef796c0f4b 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Insert.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Insert.java @@ -5,26 +5,27 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.Expressions.ParamOrdinal; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; -import org.elasticsearch.xpack.sql.expression.function.scalar.ScalarFunction; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.Expressions.ParamOrdinal; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.expression.function.scalar.ScalarFunction; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import java.util.Arrays; import java.util.List; import java.util.Locale; import static java.lang.String.format; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isNumeric; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isStringAndExact; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isNumeric; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isStringAndExact; +import static org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder.paramsBuilder; import static org.elasticsearch.xpack.sql.expression.function.scalar.string.InsertFunctionProcessor.doProcess; -import static org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder.paramsBuilder; /** * Returns a character string where length characters have been deleted from the source string, beginning at start, @@ -127,7 +128,7 @@ public ScriptTemplate scriptWithField(FieldAttribute field) { @Override public DataType dataType() { - return DataType.KEYWORD; + return DataTypes.KEYWORD; } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/InsertFunctionPipe.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/InsertFunctionPipe.java index 592fbdafb5a26..764eacf757b59 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/InsertFunctionPipe.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/InsertFunctionPipe.java @@ -5,11 +5,11 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.execution.search.SqlSourceBuilder; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.execution.search.QlSourceBuilder; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Arrays; import java.util.List; @@ -73,7 +73,7 @@ protected Pipe replaceChildren(Pipe newSource, } @Override - public final void collectFields(SqlSourceBuilder sourceBuilder) { + public final void collectFields(QlSourceBuilder sourceBuilder) { source.collectFields(sourceBuilder); start.collectFields(sourceBuilder); length.collectFields(sourceBuilder); diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/InsertFunctionProcessor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/InsertFunctionProcessor.java index 5202ab64065ef..d40ea6177f2d3 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/InsertFunctionProcessor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/InsertFunctionProcessor.java @@ -7,8 +7,8 @@ import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; import java.io.IOException; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/LCase.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/LCase.java index 6648694929e07..e04a93d62186a 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/LCase.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/LCase.java @@ -5,11 +5,12 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.expression.function.scalar.string.StringProcessor.StringOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.type.DataType; /** * Lowercases all uppercase letters in a string. @@ -37,6 +38,6 @@ protected StringOperation operation() { @Override public DataType dataType() { - return DataType.KEYWORD; + return DataTypes.KEYWORD; } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/LTrim.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/LTrim.java index 92f05fa6783c3..c3c61443d9f44 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/LTrim.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/LTrim.java @@ -5,11 +5,12 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.expression.function.scalar.string.StringProcessor.StringOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.type.DataType; /** * Trims the leading whitespaces. @@ -37,7 +38,7 @@ protected StringOperation operation() { @Override public DataType dataType() { - return DataType.KEYWORD; + return DataTypes.KEYWORD; } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Left.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Left.java index 8db48e415f1a2..09f5cf9831cc8 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Left.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Left.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.string.BinaryStringNumericProcessor.BinaryStringNumericOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; /** * Returns the leftmost count characters of a string. diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Length.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Length.java index 193660e9fc4b6..adced21088c5a 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Length.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Length.java @@ -5,11 +5,12 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.expression.function.scalar.string.StringProcessor.StringOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.type.DataType; /** * Returns the length (number of characters) in a string, excluding the trailing blanks. @@ -37,7 +38,7 @@ protected StringOperation operation() { @Override public DataType dataType() { - return DataType.INTEGER; + return DataTypes.INTEGER; } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Locate.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Locate.java index 9d7f43a3e6c0b..f45bd075a9499 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Locate.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Locate.java @@ -5,26 +5,28 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.Expressions.ParamOrdinal; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; -import org.elasticsearch.xpack.sql.expression.function.scalar.ScalarFunction; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.Expressions.ParamOrdinal; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.expression.function.OptionalArgument; +import org.elasticsearch.xpack.ql.expression.function.scalar.ScalarFunction; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import java.util.Arrays; import java.util.List; import java.util.Locale; import static java.lang.String.format; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isNumeric; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isStringAndExact; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isNumeric; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isStringAndExact; +import static org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder.paramsBuilder; import static org.elasticsearch.xpack.sql.expression.function.scalar.string.LocateFunctionProcessor.doProcess; -import static org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder.paramsBuilder; /** * Returns the starting position of the first occurrence of the pattern within the source string. @@ -33,7 +35,7 @@ * position indicated by the value of start. The first character position in the source string is indicated by the value 1. * If the pattern is not found within the source string, the value 0 is returned. */ -public class Locate extends ScalarFunction { +public class Locate extends ScalarFunction implements OptionalArgument { private final Expression pattern, source, start; @@ -128,7 +130,7 @@ public ScriptTemplate scriptWithField(FieldAttribute field) { @Override public DataType dataType() { - return DataType.INTEGER; + return DataTypes.INTEGER; } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/LocateFunctionPipe.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/LocateFunctionPipe.java index b33138297a607..caa5b5cbb1958 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/LocateFunctionPipe.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/LocateFunctionPipe.java @@ -5,11 +5,11 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.execution.search.SqlSourceBuilder; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.execution.search.QlSourceBuilder; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Arrays; import java.util.List; @@ -64,7 +64,7 @@ protected Pipe replaceChildren(Pipe newPattern, Pipe newSource, } @Override - public final void collectFields(SqlSourceBuilder sourceBuilder) { + public final void collectFields(QlSourceBuilder sourceBuilder) { pattern.collectFields(sourceBuilder); source.collectFields(sourceBuilder); if (start != null) { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/LocateFunctionProcessor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/LocateFunctionProcessor.java index 0509efa04a766..7dd48dc1d1a6a 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/LocateFunctionProcessor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/LocateFunctionProcessor.java @@ -7,8 +7,8 @@ import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; import java.io.IOException; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/OctetLength.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/OctetLength.java index 63e2424708679..d594d60f85da5 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/OctetLength.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/OctetLength.java @@ -5,11 +5,12 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.expression.function.scalar.string.StringProcessor.StringOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.type.DataType; /** * Returns the number of bytes contained within the value expression. @@ -37,6 +38,6 @@ protected StringOperation operation() { @Override public DataType dataType() { - return DataType.INTEGER; + return DataTypes.INTEGER; } } \ No newline at end of file diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Position.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Position.java index 916328a2d0704..89356dbb96cd6 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Position.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Position.java @@ -5,12 +5,12 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.string.BinaryStringStringProcessor.BinaryStringStringOperation; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; import java.util.function.BiFunction; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/RTrim.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/RTrim.java index 8f1f3f3f552f6..1a6c90073aac2 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/RTrim.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/RTrim.java @@ -5,11 +5,12 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.expression.function.scalar.string.StringProcessor.StringOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.type.DataType; /** * Trims the trailing whitespaces. @@ -37,7 +38,7 @@ protected StringOperation operation() { @Override public DataType dataType() { - return DataType.KEYWORD; + return DataTypes.KEYWORD; } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Repeat.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Repeat.java index 956d2857bc6ac..f2d75bc19d0f5 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Repeat.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Repeat.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.string.BinaryStringNumericProcessor.BinaryStringNumericOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; /** * Creates a string composed of a string repeated count times. diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Replace.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Replace.java index a1150fc5d38af..05203aa2816d7 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Replace.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Replace.java @@ -5,25 +5,26 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.Expressions.ParamOrdinal; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; -import org.elasticsearch.xpack.sql.expression.function.scalar.ScalarFunction; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.Expressions.ParamOrdinal; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.expression.function.scalar.ScalarFunction; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import java.util.Arrays; import java.util.List; import java.util.Locale; import static java.lang.String.format; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isStringAndExact; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isStringAndExact; +import static org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder.paramsBuilder; import static org.elasticsearch.xpack.sql.expression.function.scalar.string.ReplaceFunctionProcessor.doProcess; -import static org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder.paramsBuilder; /** * Search the source string for occurrences of the pattern, and replace with the replacement string. @@ -114,7 +115,7 @@ public ScriptTemplate scriptWithField(FieldAttribute field) { @Override public DataType dataType() { - return DataType.KEYWORD; + return DataTypes.KEYWORD; } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ReplaceFunctionPipe.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ReplaceFunctionPipe.java index 087dfc0bb703a..4924d5ad47d9c 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ReplaceFunctionPipe.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ReplaceFunctionPipe.java @@ -5,11 +5,11 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.execution.search.SqlSourceBuilder; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.execution.search.QlSourceBuilder; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Arrays; import java.util.List; @@ -62,7 +62,7 @@ protected Pipe replaceChildren(Pipe newSource, Pipe newPattern, } @Override - public final void collectFields(SqlSourceBuilder sourceBuilder) { + public final void collectFields(QlSourceBuilder sourceBuilder) { source.collectFields(sourceBuilder); pattern.collectFields(sourceBuilder); replacement.collectFields(sourceBuilder); diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ReplaceFunctionProcessor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ReplaceFunctionProcessor.java index 1745874469fcd..630d0852fa1f6 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ReplaceFunctionProcessor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ReplaceFunctionProcessor.java @@ -8,8 +8,8 @@ import org.elasticsearch.common.Strings; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; import java.io.IOException; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Right.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Right.java index 3ab7c9c8dafe3..855033f7f32cb 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Right.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Right.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.string.BinaryStringNumericProcessor.BinaryStringNumericOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; /** * Returns the rightmost count characters of a string. diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Space.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Space.java index bad23a8ea526f..e48d828e93ecb 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Space.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Space.java @@ -5,11 +5,12 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.expression.function.scalar.string.StringProcessor.StringOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.type.DataType; /** * Generates a string consisting of count spaces. @@ -37,6 +38,6 @@ protected StringOperation operation() { @Override public DataType dataType() { - return DataType.KEYWORD; + return DataTypes.KEYWORD; } } \ No newline at end of file diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/StringProcessor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/StringProcessor.java index 6f8d7c93fc633..6767d4bc2085f 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/StringProcessor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/StringProcessor.java @@ -8,8 +8,8 @@ import org.apache.lucene.util.UnicodeUtil; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; import java.io.IOException; import java.util.Arrays; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Substring.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Substring.java index a341a6bb8c203..421281740948d 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Substring.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/Substring.java @@ -5,26 +5,27 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.Expressions.ParamOrdinal; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; -import org.elasticsearch.xpack.sql.expression.function.scalar.ScalarFunction; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.Expressions.ParamOrdinal; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.expression.function.scalar.ScalarFunction; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import java.util.Arrays; import java.util.List; import java.util.Locale; import static java.lang.String.format; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isInteger; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isStringAndExact; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isInteger; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isStringAndExact; +import static org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder.paramsBuilder; import static org.elasticsearch.xpack.sql.expression.function.scalar.string.SubstringFunctionProcessor.doProcess; -import static org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder.paramsBuilder; /** * Returns a character string that is derived from the source string, beginning at the character position specified by start @@ -115,7 +116,7 @@ public ScriptTemplate scriptWithField(FieldAttribute field) { @Override public DataType dataType() { - return DataType.KEYWORD; + return DataTypes.KEYWORD; } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/SubstringFunctionPipe.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/SubstringFunctionPipe.java index 0805e9e325f4c..db00060bb31fb 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/SubstringFunctionPipe.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/SubstringFunctionPipe.java @@ -5,11 +5,11 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.execution.search.SqlSourceBuilder; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.execution.search.QlSourceBuilder; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Arrays; import java.util.List; @@ -62,7 +62,7 @@ protected Pipe replaceChildren(Pipe newSource, Pipe newStart, } @Override - public final void collectFields(SqlSourceBuilder sourceBuilder) { + public final void collectFields(QlSourceBuilder sourceBuilder) { source.collectFields(sourceBuilder); start.collectFields(sourceBuilder); length.collectFields(sourceBuilder); diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/SubstringFunctionProcessor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/SubstringFunctionProcessor.java index ca30a7804c454..3501b1c18c81c 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/SubstringFunctionProcessor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/SubstringFunctionProcessor.java @@ -7,8 +7,8 @@ import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; import java.io.IOException; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/UCase.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/UCase.java index 1b0ad36ebf022..da34e041b9b0a 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/UCase.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/UCase.java @@ -5,11 +5,12 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.expression.function.scalar.string.StringProcessor.StringOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.type.DataType; /** * Uppercases all lowercase letters in a string. @@ -37,7 +38,7 @@ protected StringOperation operation() { @Override public DataType dataType() { - return DataType.KEYWORD; + return DataTypes.KEYWORD; } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/UnaryStringFunction.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/UnaryStringFunction.java index b2c72f0f5b6d7..e52874b5715ad 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/UnaryStringFunction.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/UnaryStringFunction.java @@ -5,22 +5,22 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions.ParamOrdinal; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; -import org.elasticsearch.xpack.sql.expression.function.scalar.UnaryScalarFunction; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions.ParamOrdinal; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.expression.function.scalar.UnaryScalarFunction; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.util.StringUtils; import org.elasticsearch.xpack.sql.expression.function.scalar.string.StringProcessor.StringOperation; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.util.StringUtils; import java.util.Locale; import java.util.Objects; import static java.lang.String.format; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isStringAndExact; -import static org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder.paramsBuilder; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isStringAndExact; +import static org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder.paramsBuilder; public abstract class UnaryStringFunction extends UnaryScalarFunction { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/UnaryStringIntFunction.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/UnaryStringIntFunction.java index 7d9a64e59cdc2..16709bf2dc3d4 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/UnaryStringIntFunction.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/UnaryStringIntFunction.java @@ -5,21 +5,21 @@ */ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions.ParamOrdinal; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; -import org.elasticsearch.xpack.sql.expression.function.scalar.UnaryScalarFunction; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions.ParamOrdinal; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.expression.function.scalar.UnaryScalarFunction; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.string.StringProcessor.StringOperation; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.tree.Source; import java.util.Locale; import java.util.Objects; import static java.lang.String.format; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isInteger; -import static org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder.paramsBuilder; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isInteger; +import static org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder.paramsBuilder; /** * Base unary function for text manipulating SQL functions that receive as parameter a number diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/whitelist/InternalScriptUtils.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/whitelist/InternalScriptUtils.java new file mode 100644 index 0000000000000..de404e5c30a5c --- /dev/null +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/whitelist/InternalScriptUtils.java @@ -0,0 +1,11 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.sql.expression.function.scalar.whitelist; + +public final class InternalScriptUtils extends InternalSqlScriptUtils { + +} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/whitelist/InternalSqlScriptUtils.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/whitelist/InternalSqlScriptUtils.java index 6b5b8c686eb1e..126c0323bea8f 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/whitelist/InternalSqlScriptUtils.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/whitelist/InternalSqlScriptUtils.java @@ -8,6 +8,9 @@ import org.elasticsearch.common.geo.GeoPoint; import org.elasticsearch.index.fielddata.ScriptDocValues; import org.elasticsearch.script.JodaCompatibleZonedDateTime; +import org.elasticsearch.xpack.ql.expression.function.scalar.whitelist.InternalQlScriptUtils; +import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.UnaryArithmeticProcessor.UnaryArithmeticOperation; +import org.elasticsearch.xpack.ql.expression.predicate.regex.RegexProcessor.RegexOperation; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateAddProcessor; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateDiffProcessor; @@ -19,7 +22,6 @@ import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.QuarterProcessor; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.TimeFunction; import org.elasticsearch.xpack.sql.expression.function.scalar.geo.GeoProcessor; -import org.elasticsearch.xpack.sql.expression.function.scalar.geo.GeoShape; import org.elasticsearch.xpack.sql.expression.function.scalar.geo.StDistanceProcessor; import org.elasticsearch.xpack.sql.expression.function.scalar.geo.StWkttosqlProcessor; import org.elasticsearch.xpack.sql.expression.function.scalar.math.BinaryMathProcessor.BinaryMathOperation; @@ -33,23 +35,18 @@ import org.elasticsearch.xpack.sql.expression.function.scalar.string.ReplaceFunctionProcessor; import org.elasticsearch.xpack.sql.expression.function.scalar.string.StringProcessor.StringOperation; import org.elasticsearch.xpack.sql.expression.function.scalar.string.SubstringFunctionProcessor; -import org.elasticsearch.xpack.sql.expression.literal.IntervalDayTime; -import org.elasticsearch.xpack.sql.expression.literal.IntervalYearMonth; +import org.elasticsearch.xpack.sql.expression.literal.geo.GeoShape; +import org.elasticsearch.xpack.sql.expression.literal.interval.IntervalDayTime; +import org.elasticsearch.xpack.sql.expression.literal.interval.IntervalYearMonth; import org.elasticsearch.xpack.sql.expression.predicate.conditional.CaseProcessor; import org.elasticsearch.xpack.sql.expression.predicate.conditional.ConditionalProcessor.ConditionalOperation; import org.elasticsearch.xpack.sql.expression.predicate.conditional.NullIfProcessor; -import org.elasticsearch.xpack.sql.expression.predicate.logical.BinaryLogicProcessor.BinaryLogicOperation; -import org.elasticsearch.xpack.sql.expression.predicate.logical.NotProcessor; import org.elasticsearch.xpack.sql.expression.predicate.nulls.CheckNullProcessor.CheckNullOperation; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.BinaryArithmeticProcessor.BinaryArithmeticOperation; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.UnaryArithmeticProcessor.UnaryArithmeticOperation; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.BinaryComparisonProcessor.BinaryComparisonOperation; +import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.SqlBinaryArithmeticOperation; import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.InProcessor; -import org.elasticsearch.xpack.sql.expression.predicate.regex.RegexProcessor.RegexOperation; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.DataTypeConversion; +import org.elasticsearch.xpack.sql.type.SqlDataTypeConverter; +import org.elasticsearch.xpack.sql.type.SqlDataTypes; import org.elasticsearch.xpack.sql.util.DateUtils; -import org.elasticsearch.xpack.sql.util.StringUtils; import java.time.Duration; import java.time.OffsetTime; @@ -65,84 +62,14 @@ * (to simplify the whitelist definition). */ @SuppressWarnings("unused") -public final class InternalSqlScriptUtils { +public class InternalSqlScriptUtils extends InternalQlScriptUtils { - private InternalSqlScriptUtils() {} - - // - // Utilities - // - - // safe missing mapping/value extractor - public static Object docValue(Map> doc, String fieldName) { - if (doc.containsKey(fieldName)) { - ScriptDocValues docValues = doc.get(fieldName); - if (!docValues.isEmpty()) { - return docValues.get(0); - } - } - return null; - } - - public static boolean nullSafeFilter(Boolean filter) { - return filter == null ? false : filter.booleanValue(); - } - - public static double nullSafeSortNumeric(Number sort) { - return sort == null ? 0.0d : sort.doubleValue(); - } - - public static String nullSafeSortString(Object sort) { - return sort == null ? StringUtils.EMPTY : sort.toString(); - } + InternalSqlScriptUtils() {} - // - // Operators - // - // // Logical // - public static Boolean eq(Object left, Object right) { - return BinaryComparisonOperation.EQ.apply(left, right); - } - - public static Boolean nulleq(Object left, Object right) { - return BinaryComparisonOperation.NULLEQ.apply(left, right); - } - - public static Boolean neq(Object left, Object right) { - return BinaryComparisonOperation.NEQ.apply(left, right); - } - - public static Boolean lt(Object left, Object right) { - return BinaryComparisonOperation.LT.apply(left, right); - } - - public static Boolean lte(Object left, Object right) { - return BinaryComparisonOperation.LTE.apply(left, right); - } - - public static Boolean gt(Object left, Object right) { - return BinaryComparisonOperation.GT.apply(left, right); - } - - public static Boolean gte(Object left, Object right) { - return BinaryComparisonOperation.GTE.apply(left, right); - } - - public static Boolean and(Boolean left, Boolean right) { - return BinaryLogicOperation.AND.apply(left, right); - } - - public static Boolean or(Boolean left, Boolean right) { - return BinaryLogicOperation.OR.apply(left, right); - } - - public static Boolean not(Boolean expression) { - return NotProcessor.apply(expression); - } public static Boolean isNull(Object expression) { return CheckNullOperation.IS_NULL.apply(expression); @@ -191,19 +118,19 @@ public static Boolean regex(String value, String pattern) { // Math // public static Object add(Object left, Object right) { - return BinaryArithmeticOperation.ADD.apply(left, right); + return SqlBinaryArithmeticOperation.ADD.apply(left, right); } public static Object div(Object left, Object right) { - return BinaryArithmeticOperation.DIV.apply(left, right); + return SqlBinaryArithmeticOperation.DIV.apply(left, right); } public static Object mod(Object left, Object right) { - return BinaryArithmeticOperation.MOD.apply(left, right); + return SqlBinaryArithmeticOperation.MOD.apply(left, right); } public static Object mul(Object left, Object right) { - return BinaryArithmeticOperation.MUL.apply(left, right); + return SqlBinaryArithmeticOperation.MUL.apply(left, right); } public static Number neg(Number value) { @@ -211,7 +138,7 @@ public static Number neg(Number value) { } public static Object sub(Object left, Object right) { - return BinaryArithmeticOperation.SUB.apply(left, right); + return SqlBinaryArithmeticOperation.SUB.apply(left, right); } public static Number round(Number v, Number s) { @@ -222,19 +149,19 @@ public static Number truncate(Number v, Number s) { return BinaryOptionalMathOperation.TRUNCATE.apply(v, s); } - public static Double abs(Number value) { + public static Number abs(Number value) { return MathOperation.ABS.apply(value); } - public static Double acos(Number value) { + public static Number acos(Number value) { return MathOperation.ACOS.apply(value); } - public static Double asin(Number value) { + public static Number asin(Number value) { return MathOperation.ASIN.apply(value); } - public static Double atan(Number value) { + public static Number atan(Number value) { return MathOperation.ATAN.apply(value); } @@ -242,55 +169,55 @@ public static Number atan2(Number left, Number right) { return BinaryMathOperation.ATAN2.apply(left, right); } - public static Double cbrt(Number value) { + public static Number cbrt(Number value) { return MathOperation.CBRT.apply(value); } - public static Double ceil(Number value) { + public static Number ceil(Number value) { return MathOperation.CEIL.apply(value); } - public static Double cos(Number value) { + public static Number cos(Number value) { return MathOperation.COS.apply(value); } - public static Double cosh(Number value) { + public static Number cosh(Number value) { return MathOperation.COSH.apply(value); } - public static Double cot(Number value) { + public static Number cot(Number value) { return MathOperation.COT.apply(value); } - public static Double degrees(Number value) { + public static Number degrees(Number value) { return MathOperation.DEGREES.apply(value); } - public static Double e(Number value) { + public static Number e(Number value) { return MathOperation.E.apply(value); } - public static Double exp(Number value) { + public static Number exp(Number value) { return MathOperation.EXP.apply(value); } - public static Double expm1(Number value) { + public static Number expm1(Number value) { return MathOperation.EXPM1.apply(value); } - public static Double floor(Number value) { + public static Number floor(Number value) { return MathOperation.FLOOR.apply(value); } - public static Double log(Number value) { + public static Number log(Number value) { return MathOperation.LOG.apply(value); } - public static Double log10(Number value) { + public static Number log10(Number value) { return MathOperation.LOG10.apply(value); } - public static Double pi(Number value) { + public static Number pi(Number value) { return MathOperation.PI.apply(value); } @@ -298,31 +225,31 @@ public static Number power(Number left, Number right) { return BinaryMathOperation.POWER.apply(left, right); } - public static Double radians(Number value) { + public static Number radians(Number value) { return MathOperation.RADIANS.apply(value); } - public static Double random(Number value) { + public static Number random(Number value) { return MathOperation.RANDOM.apply(value); } - public static Double sign(Number value) { + public static Number sign(Number value) { return MathOperation.SIGN.apply(value); } - public static Double sin(Number value) { + public static Number sin(Number value) { return MathOperation.SIN.apply(value); } - public static Double sinh(Number value) { + public static Number sinh(Number value) { return MathOperation.SINH.apply(value); } - public static Double sqrt(Number value) { + public static Number sqrt(Number value) { return MathOperation.SQRT.apply(value); } - public static Double tan(Number value) { + public static Number tan(Number value) { return MathOperation.TAN.apply(value); } @@ -421,7 +348,7 @@ public static IntervalDayTime intervalDayTime(String text, String typeName) { if (text == null || typeName == null) { return null; } - return new IntervalDayTime(Duration.parse(text), DataType.fromSqlOrEsType(typeName)); + return new IntervalDayTime(Duration.parse(text), SqlDataTypes.fromSqlOrEsType(typeName)); } public static IntervalYearMonth intervalYearMonth(String text, String typeName) { @@ -429,7 +356,7 @@ public static IntervalYearMonth intervalYearMonth(String text, String typeName) return null; } - return new IntervalYearMonth(Period.parse(text), DataType.fromSqlOrEsType(typeName)); + return new IntervalYearMonth(Period.parse(text), SqlDataTypes.fromSqlOrEsType(typeName)); } public static OffsetTime asTime(String time) { @@ -569,6 +496,6 @@ public static GeoShape geoDocValue(Map> doc, Stri public static Object cast(Object value, String typeName) { // we call asDateTime here to make sure we handle JodaCompatibleZonedDateTime properly, // since casting works for ZonedDateTime objects only - return DataTypeConversion.convert(asDateTime(value, true), DataType.fromSqlOrEsType(typeName)); + return SqlDataTypeConverter.convert(asDateTime(value, true), SqlDataTypes.fromSqlOrEsType(typeName)); } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/ScorePipe.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/ScorePipe.java index c8bf1463f10dd..aa2ce6f8a7ee8 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/ScorePipe.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/pipeline/ScorePipe.java @@ -5,13 +5,14 @@ */ package org.elasticsearch.xpack.sql.expression.gen.pipeline; -import org.elasticsearch.xpack.sql.execution.search.SqlSourceBuilder; +import org.elasticsearch.xpack.ql.execution.search.QlSourceBuilder; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.processor.HitExtractorProcessor; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.execution.search.extractor.ScoreExtractor; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.processor.HitExtractorProcessor; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; import java.util.List; @@ -53,7 +54,7 @@ public Pipe resolveAttributes(AttributeResolver resolver) { } @Override - public void collectFields(SqlSourceBuilder sourceBuilder) { + public void collectFields(QlSourceBuilder sourceBuilder) { sourceBuilder.trackScores(); } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/ScriptWeaver.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/ScriptWeaver.java deleted file mode 100644 index e468a2801ce6c..0000000000000 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/gen/script/ScriptWeaver.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -package org.elasticsearch.xpack.sql.expression.gen.script; - -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.expression.function.aggregate.AggregateFunction; -import org.elasticsearch.xpack.sql.expression.function.grouping.GroupingFunction; -import org.elasticsearch.xpack.sql.expression.function.scalar.ScalarFunction; -import org.elasticsearch.xpack.sql.expression.function.scalar.geo.GeoShape; -import org.elasticsearch.xpack.sql.expression.literal.IntervalDayTime; -import org.elasticsearch.xpack.sql.expression.literal.IntervalYearMonth; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.util.DateUtils; - -import java.time.OffsetTime; -import java.time.ZonedDateTime; - -import static org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder.paramsBuilder; - -/** - * Mixin-like interface for customizing the default script generation. - */ -public interface ScriptWeaver { - - default ScriptTemplate asScript(Expression exp) { - if (exp.foldable()) { - return scriptWithFoldable(exp); - } - - if (exp instanceof ScalarFunction) { - return scriptWithScalar((ScalarFunction) exp); - } - - if (exp instanceof AggregateFunction) { - return scriptWithAggregate((AggregateFunction) exp); - } - - if (exp instanceof GroupingFunction) { - return scriptWithGrouping((GroupingFunction) exp); - } - - if (exp instanceof FieldAttribute) { - return scriptWithField((FieldAttribute) exp); - } - throw new SqlIllegalArgumentException("Cannot evaluate script for expression {}", exp); - } - - /* - * To be used when the function has an optional parameter. - */ - default ScriptTemplate asOptionalScript(Expression exp) { - return exp == null ? asScript(Literal.NULL) : asScript(exp); - } - - DataType dataType(); - - default ScriptTemplate scriptWithFoldable(Expression foldable) { - Object fold = foldable.fold(); - - // - // Custom type handling - // - - // wrap intervals with dedicated methods for serialization - if (fold instanceof ZonedDateTime) { - ZonedDateTime zdt = (ZonedDateTime) fold; - return new ScriptTemplate(processScript("{sql}.asDateTime({})"), - paramsBuilder().variable(DateUtils.toString(zdt)).build(), dataType()); - } - - if (fold instanceof IntervalYearMonth) { - IntervalYearMonth iym = (IntervalYearMonth) fold; - return new ScriptTemplate(processScript("{sql}.intervalYearMonth({},{})"), - paramsBuilder().variable(iym.interval().toString()).variable(iym.dataType().name()).build(), - dataType()); - } - if (fold instanceof IntervalDayTime) { - IntervalDayTime idt = (IntervalDayTime) fold; - return new ScriptTemplate(processScript("{sql}.intervalDayTime({},{})"), - paramsBuilder().variable(idt.interval().toString()).variable(idt.dataType().name()).build(), - dataType()); - } - if (fold instanceof OffsetTime) { - OffsetTime ot = (OffsetTime) fold; - return new ScriptTemplate(processScript("{sql}.asTime({})"), - paramsBuilder().variable(ot.toString()).build(), - dataType()); - } - - if (fold instanceof GeoShape) { - GeoShape geoShape = (GeoShape) fold; - return new ScriptTemplate(processScript("{sql}.stWktToSql({})"), - paramsBuilder().variable(geoShape.toString()).build(), - dataType()); - } - - return new ScriptTemplate(processScript("{}"), - paramsBuilder().variable(fold).build(), - dataType()); - } - - default ScriptTemplate scriptWithScalar(ScalarFunction scalar) { - ScriptTemplate nested = scalar.asScript(); - return new ScriptTemplate(processScript(nested.template()), - paramsBuilder().script(nested.params()).build(), - dataType()); - } - - default ScriptTemplate scriptWithAggregate(AggregateFunction aggregate) { - String template = "{}"; - if (aggregate.dataType().isDateBased()) { - template = "{sql}.asDateTime({})"; - } - return new ScriptTemplate(processScript(template), - paramsBuilder().agg(aggregate).build(), - dataType()); - } - - default ScriptTemplate scriptWithGrouping(GroupingFunction grouping) { - String template = "{}"; - if (grouping.dataType().isDateBased()) { - template = "{sql}.asDateTime({})"; - } - return new ScriptTemplate(processScript(template), - paramsBuilder().grouping(grouping).build(), - dataType()); - } - - default ScriptTemplate scriptWithField(FieldAttribute field) { - return new ScriptTemplate(processScript("doc[{}].value"), - paramsBuilder().variable(field.name()).build(), - dataType()); - } - - default String processScript(String script) { - return formatTemplate(script); - } - - default String formatTemplate(String template) { - return Scripts.formatTemplate(template); - } -} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/Literals.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/Literals.java index d6bdeeb0fe46b..75c5b4eb3c25f 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/Literals.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/Literals.java @@ -7,7 +7,10 @@ package org.elasticsearch.xpack.sql.expression.literal; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; -import org.elasticsearch.xpack.sql.expression.function.scalar.geo.GeoShape; +import org.elasticsearch.xpack.ql.expression.gen.processor.ConstantNamedWriteable; +import org.elasticsearch.xpack.sql.expression.literal.geo.GeoShape; +import org.elasticsearch.xpack.sql.expression.literal.interval.IntervalDayTime; +import org.elasticsearch.xpack.sql.expression.literal.interval.IntervalYearMonth; import java.util.ArrayList; import java.util.Collection; @@ -29,9 +32,9 @@ private Literals() { public static Collection getNamedWriteables() { List entries = new ArrayList<>(); - entries.add(new NamedWriteableRegistry.Entry(IntervalDayTime.class, IntervalDayTime.NAME, IntervalDayTime::new)); - entries.add(new NamedWriteableRegistry.Entry(IntervalYearMonth.class, IntervalYearMonth.NAME, IntervalYearMonth::new)); - entries.add(new NamedWriteableRegistry.Entry(GeoShape.class, GeoShape.NAME, GeoShape::new)); + entries.add(new NamedWriteableRegistry.Entry(ConstantNamedWriteable.class, IntervalDayTime.NAME, IntervalDayTime::new)); + entries.add(new NamedWriteableRegistry.Entry(ConstantNamedWriteable.class, IntervalYearMonth.NAME, IntervalYearMonth::new)); + entries.add(new NamedWriteableRegistry.Entry(ConstantNamedWriteable.class, GeoShape.NAME, GeoShape::new)); return entries; } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/GeoShape.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/geo/GeoShape.java similarity index 90% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/GeoShape.java rename to x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/geo/GeoShape.java index a43ffe745d263..9335903254e0c 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/GeoShape.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/geo/GeoShape.java @@ -3,12 +3,11 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.function.scalar.geo; +package org.elasticsearch.xpack.sql.expression.literal.geo; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.geo.GeoUtils; import org.elasticsearch.common.geo.GeometryParser; -import org.elasticsearch.common.io.stream.NamedWriteable; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.xcontent.LoggingDeprecationHandler; @@ -29,10 +28,11 @@ import org.elasticsearch.geometry.Point; import org.elasticsearch.geometry.Polygon; import org.elasticsearch.geometry.Rectangle; -import org.elasticsearch.geometry.utils.StandardValidator; import org.elasticsearch.geometry.utils.GeometryValidator; +import org.elasticsearch.geometry.utils.StandardValidator; import org.elasticsearch.geometry.utils.WellKnownText; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.expression.gen.processor.ConstantNamedWriteable; import java.io.IOException; import java.io.InputStream; @@ -45,7 +45,7 @@ * It is required to override the XContent serialization. The ShapeBuilder serializes using GeoJSON by default, * but in SQL we need the serialization to be WKT-based. */ -public class GeoShape implements ToXContentFragment, NamedWriteable { +public class GeoShape implements ToXContentFragment, ConstantNamedWriteable { public static final String NAME = "geo"; @@ -65,7 +65,7 @@ public GeoShape(Object value) throws IOException { try { shape = parse(value); } catch (ParseException ex) { - throw new SqlIllegalArgumentException("Cannot parse [" + value + "] as a geo_shape or shape value", ex); + throw new QlIllegalArgumentException("Cannot parse [" + value + "] as a geo_shape or shape value", ex); } } @@ -74,7 +74,7 @@ public GeoShape(StreamInput in) throws IOException { try { shape = parse(value); } catch (ParseException ex) { - throw new SqlIllegalArgumentException("Cannot parse [" + value + "] as a geo_shape or shape value", ex); + throw new QlIllegalArgumentException("Cannot parse [" + value + "] as a geo_shape or shape value", ex); } } @@ -178,10 +178,10 @@ public String getGeometryType() { public static double distance(GeoShape shape1, GeoShape shape2) { if (shape1.shape instanceof Point == false) { - throw new SqlIllegalArgumentException("distance calculation is only supported for points; received [{}]", shape1); + throw new QlIllegalArgumentException("distance calculation is only supported for points; received [{}]", shape1); } if (shape2.shape instanceof Point == false) { - throw new SqlIllegalArgumentException("distance calculation is only supported for points; received [{}]", shape2); + throw new QlIllegalArgumentException("distance calculation is only supported for points; received [{}]", shape2); } double srcLat = ((Point) shape1.shape).getY(); double srcLon = ((Point) shape1.shape).getX(); @@ -227,4 +227,4 @@ private static Geometry parse(Object value) throws IOException, ParseException { return GEOMETRY_PARSER.parse(parser); } } -} +} \ No newline at end of file diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/Interval.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/interval/Interval.java similarity index 78% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/Interval.java rename to x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/interval/Interval.java index fe83b9b0099b4..6c53d5ccecc10 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/Interval.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/interval/Interval.java @@ -4,13 +4,14 @@ * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.literal; +package org.elasticsearch.xpack.sql.expression.literal.interval; -import org.elasticsearch.common.io.stream.NamedWriteable; import org.elasticsearch.common.xcontent.ToXContentObject; import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.xpack.sql.proto.StringUtils; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.function.scalar.IntervalScripting; +import org.elasticsearch.xpack.ql.expression.gen.processor.ConstantNamedWriteable; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.util.DateUtils; import java.io.IOException; import java.time.temporal.TemporalAmount; @@ -25,7 +26,7 @@ * Unfortunately because the SQL interval type is not preserved accurately by the JDK TemporalAmount class * in both cases, the data type needs to be carried around as it cannot be inferred. */ -public abstract class Interval implements NamedWriteable, ToXContentObject { +public abstract class Interval implements ConstantNamedWriteable, ToXContentObject, IntervalScripting { private final I interval; private final DataType intervalType; @@ -76,6 +77,16 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws @Override public String toString() { - return StringUtils.toString(interval); + return DateUtils.toString(interval); + } + + @Override + public String value() { + return interval().toString(); + } + + @Override + public String typeName() { + return dataType().toString(); } } \ No newline at end of file diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/interval/IntervalArithmetics.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/interval/IntervalArithmetics.java new file mode 100644 index 0000000000000..32056ed586403 --- /dev/null +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/interval/IntervalArithmetics.java @@ -0,0 +1,72 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.sql.expression.literal.interval; + +import java.time.Duration; +import java.time.OffsetTime; +import java.time.Period; +import java.time.temporal.Temporal; + +public final class IntervalArithmetics { + + private IntervalArithmetics() {} + + public static final long DAY_IN_MILLIS = 60 * 60 * 24 * 1000L; + + private enum IntervalOperation { + ADD, + SUB + } + + public static Temporal add(Temporal l, Period r) { + return periodArithmetics(l, r, IntervalOperation.ADD); + } + + public static Temporal add(Temporal l, Duration r) { + return durationArithmetics(l, r, IntervalOperation.ADD); + } + + public static Temporal sub(Temporal l, Period r) { + return periodArithmetics(l, r, IntervalOperation.SUB); + } + + public static Temporal sub(Temporal l, Duration r) { + return durationArithmetics(l, r, IntervalOperation.SUB); + } + + private static Temporal periodArithmetics(Temporal l, Period r, IntervalOperation operation) { + if (l == null || r == null) { + return null; + } + + if (l instanceof OffsetTime) { + return l; + } + + if (operation == IntervalOperation.ADD) { + return l.plus(r); + } else { + return l.minus(r); + } + } + + private static Temporal durationArithmetics(Temporal l, Duration r, IntervalOperation operation) { + if (l == null || r == null) { + return null; + } + + if (l instanceof OffsetTime) { + r = Duration.ofMillis(r.toMillis() % DAY_IN_MILLIS); + } + + if (operation == IntervalOperation.ADD) { + return l.plus(r); + } else { + return l.minus(r); + } + } +} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/IntervalDayTime.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/interval/IntervalDayTime.java similarity index 72% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/IntervalDayTime.java rename to x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/interval/IntervalDayTime.java index 4f370bc313fa0..842619701a5b0 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/IntervalDayTime.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/interval/IntervalDayTime.java @@ -4,12 +4,12 @@ * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.literal; +package org.elasticsearch.xpack.sql.expression.literal.interval; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.DataTypes; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.sql.type.SqlDataTypes; import java.io.IOException; import java.time.Duration; @@ -29,15 +29,15 @@ public IntervalDayTime(Duration interval, DataType intervalType) { super(interval, intervalType); } - IntervalDayTime(StreamInput in) throws IOException { - super(duration(in), in.readEnum(DataType.class)); + public IntervalDayTime(StreamInput in) throws IOException { + super(duration(in), SqlDataTypes.fromTypeName(in.readString())); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeVLong(interval().getSeconds()); out.writeVInt(interval().getNano()); - out.writeEnum(dataType()); + out.writeString(dataType().typeName()); } @Override @@ -47,16 +47,21 @@ public String getWriteableName() { @Override public IntervalDayTime add(Interval interval) { - return new IntervalDayTime(interval().plus(interval.interval()), DataTypes.compatibleInterval(dataType(), interval.dataType())); + return new IntervalDayTime(interval().plus(interval.interval()), Intervals.compatibleInterval(dataType(), interval.dataType())); } @Override public IntervalDayTime sub(Interval interval) { - return new IntervalDayTime(interval().minus(interval.interval()), DataTypes.compatibleInterval(dataType(), interval.dataType())); + return new IntervalDayTime(interval().minus(interval.interval()), Intervals.compatibleInterval(dataType(), interval.dataType())); } @Override public Interval mul(long mul) { return new IntervalDayTime(interval().multipliedBy(mul), dataType()); } + + @Override + public String script() { + return "{sql}.intervalDayTime({},{})"; + } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/IntervalYearMonth.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/interval/IntervalYearMonth.java similarity index 70% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/IntervalYearMonth.java rename to x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/interval/IntervalYearMonth.java index cb4346428ae70..2d64022e57cc3 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/IntervalYearMonth.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/interval/IntervalYearMonth.java @@ -4,13 +4,13 @@ * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.literal; +package org.elasticsearch.xpack.sql.expression.literal.interval; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.DataTypeConversion; -import org.elasticsearch.xpack.sql.type.DataTypes; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypeConverter; +import org.elasticsearch.xpack.sql.type.SqlDataTypes; import java.io.IOException; import java.time.Period; @@ -30,8 +30,8 @@ public IntervalYearMonth(Period interval, DataType intervalType) { super(interval, intervalType); } - IntervalYearMonth(StreamInput in) throws IOException { - super(period(in), in.readEnum(DataType.class)); + public IntervalYearMonth(StreamInput in) throws IOException { + super(period(in), SqlDataTypes.fromTypeName(in.readString())); } @Override @@ -40,7 +40,7 @@ public void writeTo(StreamOutput out) throws IOException { out.writeVInt(p.getYears()); out.writeVInt(p.getMonths()); out.writeVInt(p.getDays()); - out.writeEnum(dataType()); + out.writeString(dataType().typeName()); } @Override @@ -51,18 +51,23 @@ public String getWriteableName() { @Override public IntervalYearMonth add(Interval interval) { return new IntervalYearMonth(interval().plus(interval.interval()).normalized(), - DataTypes.compatibleInterval(dataType(), interval.dataType())); + Intervals.compatibleInterval(dataType(), interval.dataType())); } @Override public IntervalYearMonth sub(Interval interval) { return new IntervalYearMonth(interval().minus(interval.interval()).normalized(), - DataTypes.compatibleInterval(dataType(), interval.dataType())); + Intervals.compatibleInterval(dataType(), interval.dataType())); } @Override public Interval mul(long mul) { - int i = DataTypeConversion.safeToInt(mul); + int i = DataTypeConverter.safeToInt(mul); return new IntervalYearMonth(interval().multipliedBy(i), dataType()); } + + @Override + public String script() { + return "{sql}.intervalYearMonth({},{})"; + } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/Intervals.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/interval/Intervals.java similarity index 71% rename from x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/Intervals.java rename to x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/interval/Intervals.java index ed7dc9da77543..5b9d5a48ec849 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/Intervals.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/literal/interval/Intervals.java @@ -4,17 +4,17 @@ * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.literal; +package org.elasticsearch.xpack.sql.expression.literal.interval; import org.elasticsearch.common.Strings; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; +import org.elasticsearch.xpack.ql.ParsingException; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.util.Check; +import org.elasticsearch.xpack.ql.util.StringUtils; import org.elasticsearch.xpack.sql.expression.Foldables; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.parser.ParsingException; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.util.Check; -import org.elasticsearch.xpack.sql.util.StringUtils; import java.time.Duration; import java.time.Period; @@ -22,15 +22,25 @@ import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; import java.util.Map; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_DAY_TO_HOUR; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_DAY_TO_MINUTE; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_DAY_TO_SECOND; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_HOUR_TO_MINUTE; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_HOUR_TO_SECOND; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_MINUTE_TO_SECOND; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_YEAR_TO_MONTH; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_DAY; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_DAY_TO_HOUR; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_DAY_TO_MINUTE; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_DAY_TO_SECOND; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_HOUR; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_HOUR_TO_MINUTE; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_HOUR_TO_SECOND; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_MINUTE; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_MINUTE_TO_SECOND; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_MONTH; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_SECOND; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_YEAR; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_YEAR_TO_MONTH; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.fromTypeName; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.isDayTimeInterval; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.isYearMonthInterval; public final class Intervals { @@ -91,17 +101,17 @@ public static DataType intervalType(Source source, TimeUnit leading, TimeUnit tr if (trailing == null) { switch (leading) { case YEAR: - return DataType.INTERVAL_YEAR; + return INTERVAL_YEAR; case MONTH: - return DataType.INTERVAL_MONTH; + return INTERVAL_MONTH; case DAY: - return DataType.INTERVAL_DAY; + return INTERVAL_DAY; case HOUR: - return DataType.INTERVAL_HOUR; + return INTERVAL_HOUR; case MINUTE: - return DataType.INTERVAL_MINUTE; + return INTERVAL_MINUTE; case SECOND: - return DataType.INTERVAL_SECOND; + return INTERVAL_SECOND; default: throw new ParsingException(source, "Cannot determine datatype for [{}]", leading); } @@ -131,6 +141,64 @@ public static DataType intervalType(Source source, TimeUnit leading, TimeUnit tr } } + // return the compatible interval between the two - it is assumed the types are intervals + // YEAR and MONTH -> YEAR_TO_MONTH + // DAY... SECOND -> DAY_TIME + // YEAR_MONTH and DAY_SECOND are NOT compatible + public static DataType compatibleInterval(DataType left, DataType right) { + if (left == right) { + return left; + } + if (isYearMonthInterval(left) && isYearMonthInterval(right)) { + // no need to look at YEAR/YEAR or MONTH/MONTH as these are equal and already handled + return INTERVAL_YEAR_TO_MONTH; + } + if (isDayTimeInterval(left) && isDayTimeInterval(right)) { + int PREFIX = "INTERVAL_".length(); + // to avoid specifying the combinations, extract the leading and trailing unit from the name + // D > H > S > M which is also the alphabetical order + String lName = left.typeName().toUpperCase(Locale.ROOT).substring(PREFIX); + String rName = right.typeName().toUpperCase(Locale.ROOT).substring(PREFIX); + + char leading = lName.charAt(0); + if (rName.charAt(0) < leading) { + leading = rName.charAt(0); + } + // look at the trailing unit + if (lName.length() > 6) { + int indexOf = lName.indexOf("_TO_"); + lName = lName.substring(indexOf + 4); + } + if (rName.length() > 6) { + int indexOf = rName.indexOf("_TO_"); + rName = rName.substring(indexOf + 4); + } + char trailing = lName.charAt(0); + if (rName.charAt(0) > trailing) { + trailing = rName.charAt(0); + } + + return fromTypeName("INTERVAL_" + intervalUnit(leading) + "_TO_" + intervalUnit(trailing)); + } + return null; + } + + private static String intervalUnit(char unitChar) { + switch (unitChar) { + case 'D': + return "DAY"; + case 'H': + return "HOUR"; + case 'M': + return "MINUTE"; + case 'S': + return "SECOND"; + default: + throw new QlIllegalArgumentException("Unknown unit {}", unitChar); + } + } + + // // String parsers // @@ -146,7 +214,7 @@ private static class ParserBuilder { ParserBuilder(DataType dataType) { units = new ArrayList<>(10); tokens = new ArrayList<>(6); - name = dataType.name().replace('_', ' '); + name = dataType.typeName().replace('_', ' ').toUpperCase(Locale.ROOT); } ParserBuilder unit(TimeUnit unit) { @@ -274,7 +342,7 @@ TemporalAmount parse(Source source, String string) { v); } values[unitIndex++] = v; - } catch (SqlIllegalArgumentException siae) { + } catch (QlIllegalArgumentException siae) { throw new ParsingException(source, invalidIntervalMessage(string), siae.getMessage()); } startToken = endToken; @@ -336,31 +404,31 @@ public static TemporalAmount negate(TemporalAmount interval) { char MINUS = '-'; char COLON = ':'; - PARSERS.put(DataType.INTERVAL_YEAR, new ParserBuilder(DataType.INTERVAL_YEAR).unit(TimeUnit.YEAR).build()); - PARSERS.put(DataType.INTERVAL_MONTH, new ParserBuilder(DataType.INTERVAL_MONTH).unit(TimeUnit.MONTH).build()); - PARSERS.put(DataType.INTERVAL_DAY, new ParserBuilder(DataType.INTERVAL_DAY).unit(TimeUnit.DAY).build()); - PARSERS.put(DataType.INTERVAL_HOUR, new ParserBuilder(DataType.INTERVAL_HOUR).unit(TimeUnit.HOUR).build()); - PARSERS.put(DataType.INTERVAL_MINUTE, new ParserBuilder(DataType.INTERVAL_MINUTE).unit(TimeUnit.MINUTE).build()); - PARSERS.put(DataType.INTERVAL_SECOND, new ParserBuilder(DataType.INTERVAL_SECOND) + PARSERS.put(INTERVAL_YEAR, new ParserBuilder(INTERVAL_YEAR).unit(TimeUnit.YEAR).build()); + PARSERS.put(INTERVAL_MONTH, new ParserBuilder(INTERVAL_MONTH).unit(TimeUnit.MONTH).build()); + PARSERS.put(INTERVAL_DAY, new ParserBuilder(INTERVAL_DAY).unit(TimeUnit.DAY).build()); + PARSERS.put(INTERVAL_HOUR, new ParserBuilder(INTERVAL_HOUR).unit(TimeUnit.HOUR).build()); + PARSERS.put(INTERVAL_MINUTE, new ParserBuilder(INTERVAL_MINUTE).unit(TimeUnit.MINUTE).build()); + PARSERS.put(INTERVAL_SECOND, new ParserBuilder(INTERVAL_SECOND) .unit(TimeUnit.SECOND) .optional() .separator(DOT).unit(TimeUnit.MILLISECOND, MAX_MILLI) .build()); // patterns - PARSERS.put(DataType.INTERVAL_YEAR_TO_MONTH, new ParserBuilder(DataType.INTERVAL_YEAR_TO_MONTH) + PARSERS.put(INTERVAL_YEAR_TO_MONTH, new ParserBuilder(INTERVAL_YEAR_TO_MONTH) .unit(TimeUnit.YEAR) .separator(MINUS) .unit(TimeUnit.MONTH, MAX_MONTH) .build()); - PARSERS.put(DataType.INTERVAL_DAY_TO_HOUR, new ParserBuilder(DataType.INTERVAL_DAY_TO_HOUR) + PARSERS.put(INTERVAL_DAY_TO_HOUR, new ParserBuilder(INTERVAL_DAY_TO_HOUR) .unit(TimeUnit.DAY) .separator(SPACE) .unit(TimeUnit.HOUR, MAX_HOUR) .build()); - PARSERS.put(DataType.INTERVAL_DAY_TO_MINUTE, new ParserBuilder(DataType.INTERVAL_DAY_TO_MINUTE) + PARSERS.put(INTERVAL_DAY_TO_MINUTE, new ParserBuilder(INTERVAL_DAY_TO_MINUTE) .unit(TimeUnit.DAY) .separator(SPACE) .unit(TimeUnit.HOUR, MAX_HOUR) @@ -368,7 +436,7 @@ public static TemporalAmount negate(TemporalAmount interval) { .unit(TimeUnit.MINUTE, MAX_MINUTE) .build()); - PARSERS.put(DataType.INTERVAL_DAY_TO_SECOND, new ParserBuilder(DataType.INTERVAL_DAY_TO_SECOND) + PARSERS.put(INTERVAL_DAY_TO_SECOND, new ParserBuilder(INTERVAL_DAY_TO_SECOND) .unit(TimeUnit.DAY) .separator(SPACE) .unit(TimeUnit.HOUR, MAX_HOUR) @@ -380,13 +448,13 @@ public static TemporalAmount negate(TemporalAmount interval) { .separator(DOT).unit(TimeUnit.MILLISECOND, MAX_MILLI) .build()); - PARSERS.put(DataType.INTERVAL_HOUR_TO_MINUTE, new ParserBuilder(DataType.INTERVAL_HOUR_TO_MINUTE) + PARSERS.put(INTERVAL_HOUR_TO_MINUTE, new ParserBuilder(INTERVAL_HOUR_TO_MINUTE) .unit(TimeUnit.HOUR) .separator(COLON) .unit(TimeUnit.MINUTE, MAX_MINUTE) .build()); - PARSERS.put(DataType.INTERVAL_HOUR_TO_SECOND, new ParserBuilder(DataType.INTERVAL_HOUR_TO_SECOND) + PARSERS.put(INTERVAL_HOUR_TO_SECOND, new ParserBuilder(INTERVAL_HOUR_TO_SECOND) .unit(TimeUnit.HOUR) .separator(COLON) .unit(TimeUnit.MINUTE, MAX_MINUTE) @@ -396,7 +464,7 @@ public static TemporalAmount negate(TemporalAmount interval) { .separator(DOT).unit(TimeUnit.MILLISECOND, MAX_MILLI) .build()); - PARSERS.put(DataType.INTERVAL_MINUTE_TO_SECOND, new ParserBuilder(DataType.INTERVAL_MINUTE_TO_SECOND) + PARSERS.put(INTERVAL_MINUTE_TO_SECOND, new ParserBuilder(INTERVAL_MINUTE_TO_SECOND) .unit(TimeUnit.MINUTE) .separator(COLON) .unit(TimeUnit.SECOND, MAX_SECOND) diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/ArbitraryConditionalFunction.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/ArbitraryConditionalFunction.java index b2bea979acda7..72a14a22934c4 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/ArbitraryConditionalFunction.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/ArbitraryConditionalFunction.java @@ -6,19 +6,19 @@ package org.elasticsearch.xpack.sql.expression.predicate.conditional; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.predicate.conditional.ConditionalProcessor.ConditionalOperation; -import org.elasticsearch.xpack.sql.tree.Source; import java.util.ArrayList; import java.util.List; import java.util.StringJoiner; -import static org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder.paramsBuilder; +import static org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder.paramsBuilder; /** * Base class for conditional predicates with arbitrary number of arguments diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/Case.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/Case.java index 84f17283e061e..362d14b2df0f2 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/Case.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/Case.java @@ -5,24 +5,24 @@ */ package org.elasticsearch.xpack.sql.expression.predicate.conditional; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.optimizer.Optimizer; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.DataTypeConversion; -import org.elasticsearch.xpack.sql.type.DataTypes; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; +import org.elasticsearch.xpack.sql.type.SqlDataTypeConverter; +import org.elasticsearch.xpack.sql.type.SqlDataTypes; import java.util.ArrayList; import java.util.List; import java.util.StringJoiner; import static org.elasticsearch.common.logging.LoggerMessageFormat.format; -import static org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder.paramsBuilder; +import static org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder.paramsBuilder; /** * Implements the CASE WHEN ... THEN ... ELSE ... END expression @@ -53,12 +53,12 @@ public DataType dataType() { if (conditions.isEmpty()) { dataType = elseResult().dataType(); } else { - dataType = DataType.NULL; + dataType = DataTypes.NULL; for (IfConditional conditional : conditions) { - dataType = DataTypeConversion.commonType(dataType, conditional.dataType()); + dataType = SqlDataTypeConverter.commonType(dataType, conditional.dataType()); } - dataType = DataTypeConversion.commonType(dataType, elseResult.dataType()); + dataType = SqlDataTypeConverter.commonType(dataType, elseResult.dataType()); } } return dataType; @@ -78,7 +78,7 @@ protected NodeInfo info() { protected TypeResolution resolveType() { DataType expectedResultDataType = null; for (IfConditional ifConditional : conditions) { - if (ifConditional.result().dataType().isNull() == false) { + if (DataTypes.isNull(ifConditional.result().dataType()) == false) { expectedResultDataType = ifConditional.result().dataType(); break; } @@ -88,27 +88,27 @@ protected TypeResolution resolveType() { } for (IfConditional conditional : conditions) { - if (conditional.condition().dataType() != DataType.BOOLEAN) { + if (conditional.condition().dataType() != DataTypes.BOOLEAN) { return new TypeResolution(format(null, "condition of [{}] must be [boolean], found value [{}] type [{}]", conditional.sourceText(), Expressions.name(conditional.condition()), - conditional.condition().dataType().typeName)); + conditional.condition().dataType().typeName())); } - if (DataTypes.areTypesCompatible(expectedResultDataType, conditional.dataType()) == false) { + if (SqlDataTypes.areCompatible(expectedResultDataType, conditional.dataType()) == false) { return new TypeResolution(format(null, "result of [{}] must be [{}], found value [{}] type [{}]", conditional.sourceText(), - expectedResultDataType.typeName, + expectedResultDataType.typeName(), Expressions.name(conditional.result()), - conditional.dataType().typeName)); + conditional.dataType().typeName())); } } - if (DataTypes.areTypesCompatible(expectedResultDataType, elseResult.dataType()) == false) { + if (SqlDataTypes.areCompatible(expectedResultDataType, elseResult.dataType()) == false) { return new TypeResolution(format(null, "ELSE clause of [{}] must be [{}], found value [{}] type [{}]", elseResult.sourceText(), - expectedResultDataType.typeName, + expectedResultDataType.typeName(), Expressions.name(elseResult), - elseResult.dataType().typeName)); + elseResult.dataType().typeName())); } return TypeResolution.TYPE_RESOLVED; @@ -116,7 +116,7 @@ protected TypeResolution resolveType() { /** * All foldable conditions that fold to FALSE should have - * been removed by the {@link Optimizer}#SimplifyCase. + * been removed by the Optimizer. */ @Override public boolean foldable() { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/CasePipe.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/CasePipe.java index f3beb755c347b..7f316a480b384 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/CasePipe.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/CasePipe.java @@ -6,12 +6,12 @@ package org.elasticsearch.xpack.sql.expression.predicate.conditional; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.MultiPipe; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.MultiPipe; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.List; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/CaseProcessor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/CaseProcessor.java index 269faba3dc9e1..dc4d083d53c17 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/CaseProcessor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/CaseProcessor.java @@ -7,7 +7,7 @@ import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; import java.io.IOException; import java.util.List; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/Coalesce.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/Coalesce.java index faaa6ec1802da..04f04ce3da535 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/Coalesce.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/Coalesce.java @@ -6,9 +6,9 @@ package org.elasticsearch.xpack.sql.expression.predicate.conditional; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.List; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/ConditionalFunction.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/ConditionalFunction.java index 79c3f906b4045..284433cdb122a 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/ConditionalFunction.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/ConditionalFunction.java @@ -6,20 +6,21 @@ package org.elasticsearch.xpack.sql.expression.predicate.conditional; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.Nullability; -import org.elasticsearch.xpack.sql.expression.function.scalar.ScalarFunction; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.DataTypeConversion; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.Nullability; +import org.elasticsearch.xpack.ql.expression.function.scalar.ScalarFunction; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; +import org.elasticsearch.xpack.sql.type.SqlDataTypeConverter; +import org.elasticsearch.xpack.sql.type.SqlDataTypes; import java.util.List; import java.util.Objects; import static org.elasticsearch.common.logging.LoggerMessageFormat.format; -import static org.elasticsearch.xpack.sql.type.DataTypes.areTypesCompatible; -import static org.elasticsearch.xpack.sql.util.StringUtils.ordinal; +import static org.elasticsearch.xpack.ql.util.StringUtils.ordinal; /** * Base class for conditional predicates. @@ -35,9 +36,9 @@ public abstract class ConditionalFunction extends ScalarFunction { @Override public DataType dataType() { if (dataType == null) { - dataType = DataType.NULL; + dataType = DataTypes.NULL; for (Expression exp : children()) { - dataType = DataTypeConversion.commonType(dataType, exp.dataType()); + dataType = SqlDataTypeConverter.commonType(dataType, exp.dataType()); } } return dataType; @@ -50,22 +51,22 @@ public boolean foldable() { @Override protected TypeResolution resolveType() { - DataType dt = DataType.NULL; + DataType dt = DataTypes.NULL; for (int i = 0; i < children().size(); i++) { Expression child = children().get(i); - if (dt == DataType.NULL) { + if (dt == DataTypes.NULL) { if (Expressions.isNull(child) == false) { dt = child.dataType(); } } else { - if (areTypesCompatible(dt, child.dataType()) == false) { + if (SqlDataTypes.areCompatible(dt, child.dataType()) == false) { return new TypeResolution(format(null, "{} argument of [{}] must be [{}], found value [{}] type [{}]", ordinal(i + 1), sourceText(), - dt.typeName, + dt.typeName(), Expressions.name(child), - child.dataType().typeName)); + child.dataType().typeName())); } } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/ConditionalPipe.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/ConditionalPipe.java index d543a87aef083..776f151f9286a 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/ConditionalPipe.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/ConditionalPipe.java @@ -6,13 +6,13 @@ package org.elasticsearch.xpack.sql.expression.predicate.conditional; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.MultiPipe; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.MultiPipe; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.predicate.conditional.ConditionalProcessor.ConditionalOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; import java.util.List; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/ConditionalProcessor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/ConditionalProcessor.java index 82b3b4b5c3852..83f27eade4db2 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/ConditionalProcessor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/ConditionalProcessor.java @@ -7,7 +7,7 @@ import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; import java.io.IOException; import java.util.Collection; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/Conditionals.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/Conditionals.java index cf2576a3780eb..34648d63cee15 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/Conditionals.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/Conditionals.java @@ -6,8 +6,8 @@ package org.elasticsearch.xpack.sql.expression.predicate.conditional; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.Comparisons; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.Comparisons; import java.util.ArrayList; import java.util.Collection; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/Greatest.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/Greatest.java index 60df99e27e05f..13b740261ca51 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/Greatest.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/Greatest.java @@ -6,10 +6,10 @@ package org.elasticsearch.xpack.sql.expression.predicate.conditional; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.Foldables; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; import java.util.ArrayList; import java.util.LinkedHashSet; @@ -35,6 +35,6 @@ public Expression replaceChildren(List newChildren) { @Override public Object fold() { - return GREATEST.apply(Foldables.valuesOfNoDuplicates(children(), dataType)); + return GREATEST.apply(Foldables.valuesUnique(children(), dataType)); } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/IfConditional.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/IfConditional.java index 96d40f094a168..1e5c4edfcc8b6 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/IfConditional.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/IfConditional.java @@ -5,11 +5,11 @@ */ package org.elasticsearch.xpack.sql.expression.predicate.conditional; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Nullability; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Nullability; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; import java.util.Arrays; import java.util.List; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/IfNull.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/IfNull.java index 2133a6b421336..9014c6c8c1bb5 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/IfNull.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/IfNull.java @@ -6,9 +6,9 @@ package org.elasticsearch.xpack.sql.expression.predicate.conditional; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Arrays; import java.util.List; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/Iif.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/Iif.java index ac6a7d342939b..b270d29c63712 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/Iif.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/Iif.java @@ -5,22 +5,23 @@ */ package org.elasticsearch.xpack.sql.expression.predicate.conditional; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.DataTypes; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.function.OptionalArgument; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.sql.type.SqlDataTypes; import java.util.Arrays; import java.util.List; import static org.elasticsearch.common.logging.LoggerMessageFormat.format; -import static org.elasticsearch.xpack.sql.expression.TypeResolutions.isBoolean; -import static org.elasticsearch.xpack.sql.util.CollectionUtils.combine; +import static org.elasticsearch.xpack.ql.expression.TypeResolutions.isBoolean; +import static org.elasticsearch.xpack.ql.util.CollectionUtils.combine; -public class Iif extends Case { +public class Iif extends Case implements OptionalArgument { public Iif(Source source, Expression condition, Expression thenResult, Expression elseResult) { super(source, Arrays.asList(new IfConditional(source, condition, thenResult), elseResult != null ? elseResult : Literal.NULL)); @@ -52,12 +53,12 @@ protected TypeResolution resolveType() { } DataType resultDataType = conditions().get(0).dataType(); - if (DataTypes.areTypesCompatible(resultDataType, elseResult().dataType()) == false) { + if (SqlDataTypes.areCompatible(resultDataType, elseResult().dataType()) == false) { return new TypeResolution(format(null, "third argument of [{}] must be [{}], found value [{}] type [{}]", sourceText(), - resultDataType.typeName, + resultDataType.typeName(), Expressions.name(elseResult()), - elseResult().dataType().typeName)); + elseResult().dataType().typeName())); } return TypeResolution.TYPE_RESOLVED; } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/Least.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/Least.java index 7eec55b265f91..b9d2470d5a17c 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/Least.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/Least.java @@ -6,10 +6,10 @@ package org.elasticsearch.xpack.sql.expression.predicate.conditional; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.Foldables; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; import java.util.ArrayList; import java.util.LinkedHashSet; @@ -35,6 +35,6 @@ public Expression replaceChildren(List newChildren) { @Override public Object fold() { - return LEAST.apply(Foldables.valuesOfNoDuplicates(children(), dataType)); + return LEAST.apply(Foldables.valuesUnique(children(), dataType)); } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/NullIf.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/NullIf.java index 50692edb40e39..1b8b02b89e540 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/NullIf.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/NullIf.java @@ -6,18 +6,18 @@ package org.elasticsearch.xpack.sql.expression.predicate.conditional; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Arrays; import java.util.List; -import static org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder.paramsBuilder; +import static org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder.paramsBuilder; /** * Accepts 2 arguments of any data type and returns null if they are equal, diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/NullIfPipe.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/NullIfPipe.java index 3d52d232e1262..ffd7516a2b629 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/NullIfPipe.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/NullIfPipe.java @@ -6,12 +6,12 @@ package org.elasticsearch.xpack.sql.expression.predicate.conditional; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.BinaryPipe; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.BinaryPipe; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; public class NullIfPipe extends BinaryPipe { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/NullIfProcessor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/NullIfProcessor.java index 06bc04eae2469..f1b334a678b8f 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/NullIfProcessor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/NullIfProcessor.java @@ -7,12 +7,12 @@ import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; import java.io.IOException; import java.util.Objects; -import static org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.BinaryComparisonProcessor.BinaryComparisonOperation.EQ; +import static org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.BinaryComparisonProcessor.BinaryComparisonOperation.EQ; public class NullIfProcessor implements Processor { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/nulls/CheckNullProcessor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/nulls/CheckNullProcessor.java index 73fff2c9c475f..c37f6cf274676 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/nulls/CheckNullProcessor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/nulls/CheckNullProcessor.java @@ -7,7 +7,7 @@ import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; import java.io.IOException; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/nulls/IsNotNull.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/nulls/IsNotNull.java index 53bf9bcc80504..f17a533e159c3 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/nulls/IsNotNull.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/nulls/IsNotNull.java @@ -5,16 +5,17 @@ */ package org.elasticsearch.xpack.sql.expression.predicate.nulls; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Nullability; -import org.elasticsearch.xpack.sql.expression.function.scalar.UnaryScalarFunction; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.expression.gen.script.Scripts; -import org.elasticsearch.xpack.sql.expression.predicate.Negatable; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Nullability; +import org.elasticsearch.xpack.ql.expression.function.scalar.UnaryScalarFunction; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.gen.script.Scripts; +import org.elasticsearch.xpack.ql.expression.predicate.Negatable; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.expression.predicate.nulls.CheckNullProcessor.CheckNullOperation; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; public class IsNotNull extends UnaryScalarFunction implements Negatable { @@ -34,7 +35,7 @@ protected IsNotNull replaceChild(Expression newChild) { @Override public Object fold() { - return field().fold() != null && !field().dataType().isNull(); + return field().fold() != null && DataTypes.isNull(field().dataType()) == false; } @Override @@ -54,7 +55,7 @@ public Nullability nullable() { @Override public DataType dataType() { - return DataType.BOOLEAN; + return DataTypes.BOOLEAN; } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/nulls/IsNull.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/nulls/IsNull.java index c1d98dbe1b5c5..5bc8bfc6718bc 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/nulls/IsNull.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/nulls/IsNull.java @@ -5,16 +5,17 @@ */ package org.elasticsearch.xpack.sql.expression.predicate.nulls; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Nullability; -import org.elasticsearch.xpack.sql.expression.function.scalar.UnaryScalarFunction; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.expression.gen.script.Scripts; -import org.elasticsearch.xpack.sql.expression.predicate.Negatable; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Nullability; +import org.elasticsearch.xpack.ql.expression.function.scalar.UnaryScalarFunction; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.gen.script.Scripts; +import org.elasticsearch.xpack.ql.expression.predicate.Negatable; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.expression.predicate.nulls.CheckNullProcessor.CheckNullOperation; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; public class IsNull extends UnaryScalarFunction implements Negatable { @@ -34,7 +35,7 @@ protected IsNull replaceChild(Expression newChild) { @Override public Object fold() { - return field().fold() == null || field().dataType().isNull(); + return field().fold() == null || DataTypes.isNull(field().dataType()); } @Override @@ -54,7 +55,7 @@ public Nullability nullable() { @Override public DataType dataType() { - return DataType.BOOLEAN; + return DataTypes.BOOLEAN; } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/Add.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/Add.java index 85b468b9a5b30..2b3b535c9b960 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/Add.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/Add.java @@ -5,17 +5,16 @@ */ package org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.BinaryArithmeticProcessor.BinaryArithmeticOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; /** * Addition function ({@code a + b}). */ public class Add extends DateTimeArithmeticOperation { public Add(Source source, Expression left, Expression right) { - super(source, left, right, BinaryArithmeticOperation.ADD); + super(source, left, right, SqlBinaryArithmeticOperation.ADD); } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/BinaryArithmeticProcessor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/BinaryArithmeticProcessor.java deleted file mode 100644 index 5705bb4d85ab4..0000000000000 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/BinaryArithmeticProcessor.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -package org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic; - -import org.elasticsearch.common.io.stream.StreamInput; -import org.elasticsearch.script.JodaCompatibleZonedDateTime; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.gen.processor.FunctionalBinaryProcessor; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.expression.literal.Interval; -import org.elasticsearch.xpack.sql.expression.literal.IntervalDayTime; -import org.elasticsearch.xpack.sql.expression.literal.IntervalYearMonth; -import org.elasticsearch.xpack.sql.expression.predicate.PredicateBiFunction; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.BinaryArithmeticProcessor.BinaryArithmeticOperation; - -import java.io.IOException; -import java.time.OffsetTime; -import java.time.ZonedDateTime; -import java.time.temporal.Temporal; -import java.util.function.BiFunction; - -public class BinaryArithmeticProcessor extends FunctionalBinaryProcessor { - - private interface NumericArithmetic extends BiFunction { - default Object wrap(Object l, Object r) { - return apply((Number) l, (Number) r); - } - } - - public enum BinaryArithmeticOperation implements PredicateBiFunction { - ADD((Object l, Object r) -> { - if (l instanceof Number) { - return Arithmetics.add((Number) l, (Number) r); - } - if (l instanceof IntervalYearMonth && r instanceof IntervalYearMonth) { - return ((IntervalYearMonth) l).add((IntervalYearMonth) r); - } - if (l instanceof IntervalDayTime && r instanceof IntervalDayTime) { - return ((IntervalDayTime) l).add((IntervalDayTime) r); - } - l = unwrapJodaTime(l); - r = unwrapJodaTime(r); - if ((l instanceof ZonedDateTime || l instanceof OffsetTime) && r instanceof IntervalYearMonth) { - return Arithmetics.add((Temporal) l, ((IntervalYearMonth) r).interval()); - } - if ((l instanceof ZonedDateTime || l instanceof OffsetTime) && r instanceof IntervalDayTime) { - return Arithmetics.add((Temporal) l, ((IntervalDayTime) r).interval()); - } - if ((r instanceof ZonedDateTime || r instanceof OffsetTime) && l instanceof IntervalYearMonth) { - return Arithmetics.add((Temporal) r, ((IntervalYearMonth) l).interval()); - } - if ((r instanceof ZonedDateTime || r instanceof OffsetTime) && l instanceof IntervalDayTime) { - return Arithmetics.add((Temporal) r, ((IntervalDayTime) l).interval()); - } - - throw new SqlIllegalArgumentException("Cannot compute [+] between [{}] [{}]", l.getClass().getSimpleName(), - r.getClass().getSimpleName()); - }, "+"), - SUB((Object l, Object r) -> { - if (l instanceof Number) { - return Arithmetics.sub((Number) l, (Number) r); - } - if (l instanceof IntervalYearMonth && r instanceof IntervalYearMonth) { - return ((IntervalYearMonth) l).sub((IntervalYearMonth) r); - } - if (l instanceof IntervalDayTime && r instanceof IntervalDayTime) { - return ((IntervalDayTime) l).sub((IntervalDayTime) r); - } - l = unwrapJodaTime(l); - r = unwrapJodaTime(r); - if ((l instanceof ZonedDateTime || l instanceof OffsetTime) && r instanceof IntervalYearMonth) { - return Arithmetics.sub((Temporal) l, ((IntervalYearMonth) r).interval()); - } - if ((l instanceof ZonedDateTime || l instanceof OffsetTime) && r instanceof IntervalDayTime) { - return Arithmetics.sub((Temporal) l, ((IntervalDayTime) r).interval()); - } - if ((r instanceof ZonedDateTime || r instanceof OffsetTime) && l instanceof Interval) { - throw new SqlIllegalArgumentException("Cannot subtract a date from an interval; do you mean the reverse?"); - } - - throw new SqlIllegalArgumentException("Cannot compute [-] between [{}] [{}]", l.getClass().getSimpleName(), - r.getClass().getSimpleName()); - }, "-"), - MUL((Object l, Object r) -> { - if (l instanceof Number && r instanceof Number) { - return Arithmetics.mul((Number) l, (Number) r); - } - l = unwrapJodaTime(l); - r = unwrapJodaTime(r); - if (l instanceof Number && r instanceof IntervalYearMonth) { - return ((IntervalYearMonth) r).mul(((Number) l).intValue()); - } - if (r instanceof Number && l instanceof IntervalYearMonth) { - return ((IntervalYearMonth) l).mul(((Number) r).intValue()); - } - if (l instanceof Number && r instanceof IntervalDayTime) { - return ((IntervalDayTime) r).mul(((Number) l).longValue()); - } - if (r instanceof Number && l instanceof IntervalDayTime) { - return ((IntervalDayTime) l).mul(((Number) r).longValue()); - } - - throw new SqlIllegalArgumentException("Cannot compute [*] between [{}] [{}]", l.getClass().getSimpleName(), - r.getClass().getSimpleName()); - }, "*"), - DIV(Arithmetics::div, "/"), - MOD(Arithmetics::mod, "%"); - - private final BiFunction process; - private final String symbol; - - BinaryArithmeticOperation(BiFunction process, String symbol) { - this.process = process; - this.symbol = symbol; - } - - BinaryArithmeticOperation(NumericArithmetic process, String symbol) { - this(process::wrap, symbol); - } - - @Override - public String symbol() { - return symbol; - } - - @Override - public final Object doApply(Object left, Object right) { - return process.apply(left, right); - } - - @Override - public String toString() { - return symbol; - } - - private static Object unwrapJodaTime(Object o) { - return o instanceof JodaCompatibleZonedDateTime ? ((JodaCompatibleZonedDateTime) o).getZonedDateTime() : o; - } - } - - public static final String NAME = "abn"; - - public BinaryArithmeticProcessor(Processor left, Processor right, BinaryArithmeticOperation operation) { - super(left, right, operation); - } - - public BinaryArithmeticProcessor(StreamInput in) throws IOException { - super(in, i -> i.readEnum(BinaryArithmeticOperation.class)); - } - - @Override - public String getWriteableName() { - return NAME; - } - - @Override - protected Object doProcess(Object left, Object right) { - BinaryArithmeticOperation f = function(); - - if (left == null || right == null) { - return null; - } - - if (f == BinaryArithmeticOperation.DIV || f == BinaryArithmeticOperation.MOD) { - if (!(left instanceof Number)) { - throw new SqlIllegalArgumentException("A number is required; received {}", left); - } - - if (!(right instanceof Number)) { - throw new SqlIllegalArgumentException("A number is required; received {}", right); - } - - return f.apply(left, right); - } - - if (f == BinaryArithmeticOperation.ADD || f == BinaryArithmeticOperation.SUB || f == BinaryArithmeticOperation.MUL) { - return f.apply(left, right); - } - - // this should not occur - throw new SqlIllegalArgumentException("Cannot perform arithmetic operation due to arguments"); - } -} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/DateTimeArithmeticOperation.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/DateTimeArithmeticOperation.java index 39797a7351627..f0eb11f6f6d20 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/DateTimeArithmeticOperation.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/DateTimeArithmeticOperation.java @@ -6,15 +6,17 @@ package org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.BinaryArithmeticProcessor.BinaryArithmeticOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.DataTypeConversion; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.BinaryArithmeticOperation; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; +import org.elasticsearch.xpack.sql.type.SqlDataTypeConverter; +import org.elasticsearch.xpack.sql.type.SqlDataTypes; import static org.elasticsearch.common.logging.LoggerMessageFormat.format; -abstract class DateTimeArithmeticOperation extends ArithmeticOperation { +abstract class DateTimeArithmeticOperation extends SqlArithmeticOperation { DateTimeArithmeticOperation(Source source, Expression left, Expression right, BinaryArithmeticOperation operation) { super(source, left, right, operation); @@ -40,8 +42,8 @@ protected TypeResolution resolveType() { return TypeResolution.TYPE_RESOLVED; } // 2. 3. 4. intervals - if (l.isInterval() || r.isInterval()) { - if (DataTypeConversion.commonType(l, r) == null) { + if (SqlDataTypes.isInterval(l) || SqlDataTypes.isInterval(r)) { + if (SqlDataTypeConverter.commonType(l, r) == null) { return new TypeResolution(format(null, "[{}] has arguments with incompatible types [{}] and [{}]", symbol(), l, r)); } else { return resolveWithIntervals(); @@ -56,7 +58,8 @@ protected TypeResolution resolveWithIntervals() { DataType l = left().dataType(); DataType r = right().dataType(); - if (!(r.isDateOrTimeBased() || r.isInterval() || r.isNull())|| !(l.isDateOrTimeBased() || l.isInterval() || l.isNull())) { + if ((SqlDataTypes.isDateOrTimeBased(r) || SqlDataTypes.isInterval(r) || DataTypes.isNull(r)) == false + || (SqlDataTypes.isDateOrTimeBased(l) || SqlDataTypes.isInterval(l) || DataTypes.isNull(l)) == false) { return new TypeResolution(format(null, "[{}] has arguments with incompatible types [{}] and [{}]", symbol(), l, r)); } return TypeResolution.TYPE_RESOLVED; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/Div.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/Div.java index c0431f268ba56..67da39f46eaf3 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/Div.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/Div.java @@ -5,20 +5,19 @@ */ package org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.BinaryArithmeticProcessor.BinaryArithmeticOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.DataTypeConversion; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.sql.type.SqlDataTypeConverter; /** * Division function ({@code a / b}). */ -public class Div extends ArithmeticOperation { +public class Div extends SqlArithmeticOperation { public Div(Source source, Expression left, Expression right) { - super(source, left, right, BinaryArithmeticOperation.DIV); + super(source, left, right, SqlBinaryArithmeticOperation.DIV); } @Override @@ -33,6 +32,6 @@ protected Div replaceChildren(Expression newLeft, Expression newRight) { @Override public DataType dataType() { - return DataTypeConversion.commonType(left().dataType(), right().dataType()); + return SqlDataTypeConverter.commonType(left().dataType(), right().dataType()); } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/Mod.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/Mod.java index 907ef1dab4f19..1d828d51cb7c4 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/Mod.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/Mod.java @@ -5,10 +5,9 @@ */ package org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.BinaryArithmeticProcessor.BinaryArithmeticOperation; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; /** * Modulo @@ -16,10 +15,10 @@ * * Note this operator is also registered as a function (needed for ODBC/SQL) purposes. */ -public class Mod extends ArithmeticOperation { +public class Mod extends SqlArithmeticOperation { public Mod(Source source, Expression left, Expression right) { - super(source, left, right, BinaryArithmeticOperation.MOD); + super(source, left, right, SqlBinaryArithmeticOperation.MOD); } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/Mul.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/Mul.java index f1e90c2dbd668..1b5a3f49ddedb 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/Mul.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/Mul.java @@ -5,23 +5,24 @@ */ package org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.BinaryArithmeticProcessor.BinaryArithmeticOperation; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; +import org.elasticsearch.xpack.sql.type.SqlDataTypes; import static org.elasticsearch.common.logging.LoggerMessageFormat.format; /** * Multiplication function ({@code a * b}). */ -public class Mul extends ArithmeticOperation { +public class Mul extends SqlArithmeticOperation { private DataType dataType; public Mul(Source source, Expression left, Expression right) { - super(source, left, right, BinaryArithmeticOperation.MUL); + super(source, left, right, SqlBinaryArithmeticOperation.MUL); } @Override @@ -34,14 +35,14 @@ protected TypeResolution resolveType() { DataType r = right().dataType(); // 1. both are numbers - if (l.isNullOrNumeric() && r.isNullOrNumeric()) { + if (DataTypes.isNullOrNumeric(l) && DataTypes.isNullOrNumeric(r)) { return TypeResolution.TYPE_RESOLVED; } - if (l.isNullOrInterval() && (r.isInteger() || r.isNull())) { + if (SqlDataTypes.isNullOrInterval(l) && (r.isInteger() || DataTypes.isNull(r))) { dataType = l; return TypeResolution.TYPE_RESOLVED; - } else if (r.isNullOrInterval() && (l.isInteger() || l.isNull())) { + } else if (SqlDataTypes.isNullOrInterval(r) && (l.isInteger() || DataTypes.isNull(l))) { dataType = r; return TypeResolution.TYPE_RESOLVED; } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/SqlArithmeticOperation.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/SqlArithmeticOperation.java new file mode 100644 index 0000000000000..8635f7e35b96a --- /dev/null +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/SqlArithmeticOperation.java @@ -0,0 +1,31 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic; + +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.ArithmeticOperation; +import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.BinaryArithmeticOperation; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.sql.type.SqlDataTypeConverter; + +public abstract class SqlArithmeticOperation extends ArithmeticOperation { + + private DataType dataType; + + public SqlArithmeticOperation(Source source, Expression left, Expression right, BinaryArithmeticOperation operation) { + super(source, left, right, operation); + } + + @Override + public DataType dataType() { + if (dataType == null) { + dataType = SqlDataTypeConverter.commonType(left().dataType(), right().dataType()); + } + return dataType; + } +} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/SqlBinaryArithmeticOperation.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/SqlBinaryArithmeticOperation.java new file mode 100644 index 0000000000000..04be1399a1115 --- /dev/null +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/SqlBinaryArithmeticOperation.java @@ -0,0 +1,154 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic; + +import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.common.io.stream.StreamOutput; +import org.elasticsearch.script.JodaCompatibleZonedDateTime; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.Arithmetics; +import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.Arithmetics.NumericArithmetic; +import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.BinaryArithmeticOperation; +import org.elasticsearch.xpack.sql.expression.literal.interval.Interval; +import org.elasticsearch.xpack.sql.expression.literal.interval.IntervalArithmetics; +import org.elasticsearch.xpack.sql.expression.literal.interval.IntervalDayTime; +import org.elasticsearch.xpack.sql.expression.literal.interval.IntervalYearMonth; + +import java.io.IOException; +import java.time.OffsetTime; +import java.time.ZonedDateTime; +import java.time.temporal.Temporal; +import java.util.function.BiFunction; + + +public enum SqlBinaryArithmeticOperation implements BinaryArithmeticOperation { + + ADD((Object l, Object r) -> { + if (l instanceof Number) { + return Arithmetics.add((Number) l, (Number) r); + } + if (l instanceof IntervalYearMonth && r instanceof IntervalYearMonth) { + return ((IntervalYearMonth) l).add((IntervalYearMonth) r); + } + if (l instanceof IntervalDayTime && r instanceof IntervalDayTime) { + return ((IntervalDayTime) l).add((IntervalDayTime) r); + } + l = unwrapJodaTime(l); + r = unwrapJodaTime(r); + if ((l instanceof ZonedDateTime || l instanceof OffsetTime) && r instanceof IntervalYearMonth) { + return IntervalArithmetics.add((Temporal) l, ((IntervalYearMonth) r).interval()); + } + if ((l instanceof ZonedDateTime || l instanceof OffsetTime) && r instanceof IntervalDayTime) { + return IntervalArithmetics.add((Temporal) l, ((IntervalDayTime) r).interval()); + } + if ((r instanceof ZonedDateTime || r instanceof OffsetTime) && l instanceof IntervalYearMonth) { + return IntervalArithmetics.add((Temporal) r, ((IntervalYearMonth) l).interval()); + } + if ((r instanceof ZonedDateTime || r instanceof OffsetTime) && l instanceof IntervalDayTime) { + return IntervalArithmetics.add((Temporal) r, ((IntervalDayTime) l).interval()); + } + + throw new QlIllegalArgumentException("Cannot compute [+] between [{}] [{}]", l.getClass().getSimpleName(), + r.getClass().getSimpleName()); + }, "+"), + SUB((Object l, Object r) -> { + if (l instanceof Number) { + return Arithmetics.sub((Number) l, (Number) r); + } + if (l instanceof IntervalYearMonth && r instanceof IntervalYearMonth) { + return ((IntervalYearMonth) l).sub((IntervalYearMonth) r); + } + if (l instanceof IntervalDayTime && r instanceof IntervalDayTime) { + return ((IntervalDayTime) l).sub((IntervalDayTime) r); + } + l = unwrapJodaTime(l); + r = unwrapJodaTime(r); + if ((l instanceof ZonedDateTime || l instanceof OffsetTime) && r instanceof IntervalYearMonth) { + return IntervalArithmetics.sub((Temporal) l, ((IntervalYearMonth) r).interval()); + } + if ((l instanceof ZonedDateTime || l instanceof OffsetTime) && r instanceof IntervalDayTime) { + return IntervalArithmetics.sub((Temporal) l, ((IntervalDayTime) r).interval()); + } + if ((r instanceof ZonedDateTime || r instanceof OffsetTime) && l instanceof Interval) { + throw new QlIllegalArgumentException("Cannot subtract a date from an interval; do you mean the reverse?"); + } + + throw new QlIllegalArgumentException("Cannot compute [-] between [{}] [{}]", l.getClass().getSimpleName(), + r.getClass().getSimpleName()); + }, "-"), + MUL((Object l, Object r) -> { + if (l instanceof Number && r instanceof Number) { + return Arithmetics.mul((Number) l, (Number) r); + } + l = unwrapJodaTime(l); + r = unwrapJodaTime(r); + if (l instanceof Number && r instanceof IntervalYearMonth) { + return ((IntervalYearMonth) r).mul(((Number) l).intValue()); + } + if (r instanceof Number && l instanceof IntervalYearMonth) { + return ((IntervalYearMonth) l).mul(((Number) r).intValue()); + } + if (l instanceof Number && r instanceof IntervalDayTime) { + return ((IntervalDayTime) r).mul(((Number) l).longValue()); + } + if (r instanceof Number && l instanceof IntervalDayTime) { + return ((IntervalDayTime) l).mul(((Number) r).longValue()); + } + + throw new QlIllegalArgumentException("Cannot compute [*] between [{}] [{}]", l.getClass().getSimpleName(), + r.getClass().getSimpleName()); + }, "*"), + DIV(Arithmetics::div, "/"), + MOD(Arithmetics::mod, "%"); + + public static final String NAME = "abn-sql"; + + private final BiFunction process; + private final String symbol; + + SqlBinaryArithmeticOperation(BiFunction process, String symbol) { + this.process = process; + this.symbol = symbol; + } + + SqlBinaryArithmeticOperation(NumericArithmetic process, String symbol) { + this(process::wrap, symbol); + } + + @Override + public String symbol() { + return symbol; + } + + @Override + public final Object doApply(Object left, Object right) { + return process.apply(left, right); + } + + @Override + public String toString() { + return symbol; + } + + @Override + public String getWriteableName() { + return NAME; + } + + @Override + public void writeTo(StreamOutput out) throws IOException { + out.writeEnum(this); + } + + public static SqlBinaryArithmeticOperation read(StreamInput in) throws IOException { + return in.readEnum(SqlBinaryArithmeticOperation.class); + } + + private static Object unwrapJodaTime(Object o) { + return o instanceof JodaCompatibleZonedDateTime ? ((JodaCompatibleZonedDateTime) o).getZonedDateTime() : o; + } +} \ No newline at end of file diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/Sub.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/Sub.java index affb02a4009c0..77f8eed05afa3 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/Sub.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/Sub.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.BinaryArithmeticProcessor.BinaryArithmeticOperation; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.sql.type.SqlDataTypes; import static org.elasticsearch.common.logging.LoggerMessageFormat.format; @@ -18,7 +18,7 @@ public class Sub extends DateTimeArithmeticOperation { public Sub(Source source, Expression left, Expression right) { - super(source, left, right, BinaryArithmeticOperation.SUB); + super(source, left, right, SqlBinaryArithmeticOperation.SUB); } @Override @@ -37,9 +37,9 @@ protected TypeResolution resolveWithIntervals() { if (resolution.unresolved()) { return resolution; } - if ((right().dataType().isDateOrTimeBased()) && left().dataType().isInterval()) { + if ((SqlDataTypes.isDateOrTimeBased(right().dataType())) && SqlDataTypes.isInterval(left().dataType())) { return new TypeResolution(format(null, "Cannot subtract a {}[{}] from an interval[{}]; do you mean the reverse?", - right().dataType().typeName, right().source().text(), left().source().text())); + right().dataType().typeName(), right().source().text(), left().source().text())); } return TypeResolution.TYPE_RESOLVED; } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/In.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/In.java index 4be6d76b8c8f9..5f075a8064cb4 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/In.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/In.java @@ -5,18 +5,20 @@ */ package org.elasticsearch.xpack.sql.expression.predicate.operator.comparison; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.Nullability; +import org.elasticsearch.xpack.ql.expression.TypeResolutions; +import org.elasticsearch.xpack.ql.expression.function.scalar.ScalarFunction; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; +import org.elasticsearch.xpack.ql.util.CollectionUtils; import org.elasticsearch.xpack.sql.expression.Foldables; -import org.elasticsearch.xpack.sql.expression.Nullability; -import org.elasticsearch.xpack.sql.expression.TypeResolutions; -import org.elasticsearch.xpack.sql.expression.function.scalar.ScalarFunction; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.util.CollectionUtils; +import org.elasticsearch.xpack.sql.type.SqlDataTypes; import java.util.ArrayList; import java.util.LinkedHashSet; @@ -25,9 +27,8 @@ import java.util.stream.Collectors; import static org.elasticsearch.common.logging.LoggerMessageFormat.format; -import static org.elasticsearch.xpack.sql.expression.gen.script.ParamsBuilder.paramsBuilder; -import static org.elasticsearch.xpack.sql.type.DataTypes.areTypesCompatible; -import static org.elasticsearch.xpack.sql.util.StringUtils.ordinal; +import static org.elasticsearch.xpack.ql.expression.gen.script.ParamsBuilder.paramsBuilder; +import static org.elasticsearch.xpack.ql.util.StringUtils.ordinal; public class In extends ScalarFunction { @@ -63,7 +64,7 @@ public List list() { @Override public DataType dataType() { - return DataType.BOOLEAN; + return DataTypes.BOOLEAN; } @Override @@ -74,14 +75,13 @@ public Nullability nullable() { @Override public boolean foldable() { return Expressions.foldable(children()) || - (Expressions.foldable(list) && list().stream().allMatch(e -> e.dataType() == DataType.NULL)); + (Expressions.foldable(list) && list().stream().allMatch(Expressions::isNull)); } @Override public Boolean fold() { // Optimization for early return and Query folding to LocalExec - if (value.dataType() == DataType.NULL || - list.size() == 1 && list.get(0).dataType() == DataType.NULL) { + if (Expressions.isNull(value) || list.size() == 1 && Expressions.isNull(list.get(0))) { return null; } return InProcessor.apply(value.fold(), Foldables.valuesOf(list, value.dataType())); @@ -126,13 +126,13 @@ protected TypeResolution resolveType() { DataType dt = value.dataType(); for (int i = 0; i < list.size(); i++) { Expression listValue = list.get(i); - if (areTypesCompatible(dt, listValue.dataType()) == false) { + if (SqlDataTypes.areCompatible(dt, listValue.dataType()) == false) { return new TypeResolution(format(null, "{} argument of [{}] must be [{}], found value [{}] type [{}]", ordinal(i + 1), sourceText(), - dt.typeName, + dt.typeName(), Expressions.name(listValue), - listValue.dataType().typeName)); + listValue.dataType().typeName())); } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/InPipe.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/InPipe.java index fa7c06a5e3f67..a586e5801cf4d 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/InPipe.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/InPipe.java @@ -5,12 +5,12 @@ */ package org.elasticsearch.xpack.sql.expression.predicate.operator.comparison; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.MultiPipe; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.MultiPipe; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.List; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/InProcessor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/InProcessor.java index 82233e250e364..a81634cddb95e 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/InProcessor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/InProcessor.java @@ -7,10 +7,11 @@ import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; -import org.elasticsearch.xpack.sql.expression.function.scalar.Processors; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.Comparisons; import java.io.IOException; +import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -41,7 +42,15 @@ public final void writeTo(StreamOutput out) throws IOException { @Override public Object process(Object input) { Object leftValue = processsors.get(processsors.size() - 1).process(input); - return apply(leftValue, Processors.process(processsors.subList(0, processsors.size() - 1), leftValue)); + return apply(leftValue, process(processsors.subList(0, processsors.size() - 1), leftValue)); + } + + private static List process(List processors, Object input) { + List values = new ArrayList<>(processors.size()); + for (Processor p : processors) { + values.add(p.process(input)); + } + return values; } public static Boolean apply(Object input, List values) { @@ -59,8 +68,12 @@ public static Boolean apply(Object input, List values) { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } InProcessor that = (InProcessor) o; return Objects.equals(processsors, that.processsors); } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/optimizer/Optimizer.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/optimizer/Optimizer.java index da7d60b15d4f2..610989c49d68a 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/optimizer/Optimizer.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/optimizer/Optimizer.java @@ -5,27 +5,57 @@ */ package org.elasticsearch.xpack.sql.optimizer; +import org.elasticsearch.xpack.ql.expression.Alias; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.AttributeMap; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.ExpressionSet; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.NamedExpression; +import org.elasticsearch.xpack.ql.expression.Nullability; +import org.elasticsearch.xpack.ql.expression.Order; +import org.elasticsearch.xpack.ql.expression.ReferenceAttribute; +import org.elasticsearch.xpack.ql.expression.UnresolvedAttribute; +import org.elasticsearch.xpack.ql.expression.function.Function; +import org.elasticsearch.xpack.ql.expression.function.aggregate.AggregateFunction; +import org.elasticsearch.xpack.ql.expression.function.aggregate.InnerAggregate; +import org.elasticsearch.xpack.ql.expression.predicate.BinaryOperator; +import org.elasticsearch.xpack.ql.expression.predicate.BinaryPredicate; +import org.elasticsearch.xpack.ql.expression.predicate.Negatable; +import org.elasticsearch.xpack.ql.expression.predicate.Predicates; +import org.elasticsearch.xpack.ql.expression.predicate.Range; +import org.elasticsearch.xpack.ql.expression.predicate.logical.And; +import org.elasticsearch.xpack.ql.expression.predicate.logical.Not; +import org.elasticsearch.xpack.ql.expression.predicate.logical.Or; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.BinaryComparison; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.Equals; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.GreaterThan; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.GreaterThanOrEqual; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.LessThan; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.LessThanOrEqual; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.NotEquals; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.NullEquals; +import org.elasticsearch.xpack.ql.plan.logical.Aggregate; +import org.elasticsearch.xpack.ql.plan.logical.EsRelation; +import org.elasticsearch.xpack.ql.plan.logical.Filter; +import org.elasticsearch.xpack.ql.plan.logical.Limit; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.plan.logical.OrderBy; +import org.elasticsearch.xpack.ql.plan.logical.Project; +import org.elasticsearch.xpack.ql.plan.logical.UnaryPlan; +import org.elasticsearch.xpack.ql.rule.Rule; +import org.elasticsearch.xpack.ql.rule.RuleExecutor; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataTypes; +import org.elasticsearch.xpack.ql.util.CollectionUtils; +import org.elasticsearch.xpack.ql.util.Holder; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; import org.elasticsearch.xpack.sql.analysis.analyzer.Analyzer.CleanAliases; -import org.elasticsearch.xpack.sql.expression.Alias; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.expression.AttributeMap; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.ExpressionSet; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.expression.NamedExpression; -import org.elasticsearch.xpack.sql.expression.Nullability; -import org.elasticsearch.xpack.sql.expression.Order; -import org.elasticsearch.xpack.sql.expression.ReferenceAttribute; -import org.elasticsearch.xpack.sql.expression.UnresolvedAttribute; -import org.elasticsearch.xpack.sql.expression.function.Function; -import org.elasticsearch.xpack.sql.expression.function.aggregate.AggregateFunction; import org.elasticsearch.xpack.sql.expression.function.aggregate.ExtendedStats; import org.elasticsearch.xpack.sql.expression.function.aggregate.ExtendedStatsEnclosed; import org.elasticsearch.xpack.sql.expression.function.aggregate.First; -import org.elasticsearch.xpack.sql.expression.function.aggregate.InnerAggregate; import org.elasticsearch.xpack.sql.expression.function.aggregate.Last; import org.elasticsearch.xpack.sql.expression.function.aggregate.MatrixStats; import org.elasticsearch.xpack.sql.expression.function.aggregate.MatrixStatsEnclosed; @@ -38,48 +68,18 @@ import org.elasticsearch.xpack.sql.expression.function.aggregate.Stats; import org.elasticsearch.xpack.sql.expression.function.aggregate.TopHits; import org.elasticsearch.xpack.sql.expression.function.scalar.Cast; -import org.elasticsearch.xpack.sql.expression.predicate.BinaryOperator; -import org.elasticsearch.xpack.sql.expression.predicate.BinaryPredicate; -import org.elasticsearch.xpack.sql.expression.predicate.Negatable; -import org.elasticsearch.xpack.sql.expression.predicate.Predicates; -import org.elasticsearch.xpack.sql.expression.predicate.Range; import org.elasticsearch.xpack.sql.expression.predicate.conditional.ArbitraryConditionalFunction; import org.elasticsearch.xpack.sql.expression.predicate.conditional.Case; import org.elasticsearch.xpack.sql.expression.predicate.conditional.Coalesce; import org.elasticsearch.xpack.sql.expression.predicate.conditional.IfConditional; -import org.elasticsearch.xpack.sql.expression.predicate.logical.And; -import org.elasticsearch.xpack.sql.expression.predicate.logical.Not; -import org.elasticsearch.xpack.sql.expression.predicate.logical.Or; import org.elasticsearch.xpack.sql.expression.predicate.nulls.IsNotNull; import org.elasticsearch.xpack.sql.expression.predicate.nulls.IsNull; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.BinaryComparison; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.Equals; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.GreaterThan; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.GreaterThanOrEqual; import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.In; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.LessThan; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.LessThanOrEqual; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.NotEquals; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.NullEquals; -import org.elasticsearch.xpack.sql.plan.logical.Aggregate; -import org.elasticsearch.xpack.sql.plan.logical.EsRelation; -import org.elasticsearch.xpack.sql.plan.logical.Filter; -import org.elasticsearch.xpack.sql.plan.logical.Limit; import org.elasticsearch.xpack.sql.plan.logical.LocalRelation; -import org.elasticsearch.xpack.sql.plan.logical.LogicalPlan; -import org.elasticsearch.xpack.sql.plan.logical.OrderBy; import org.elasticsearch.xpack.sql.plan.logical.Pivot; -import org.elasticsearch.xpack.sql.plan.logical.Project; import org.elasticsearch.xpack.sql.plan.logical.SubQueryAlias; -import org.elasticsearch.xpack.sql.plan.logical.UnaryPlan; -import org.elasticsearch.xpack.sql.rule.Rule; -import org.elasticsearch.xpack.sql.rule.RuleExecutor; import org.elasticsearch.xpack.sql.session.EmptyExecutable; import org.elasticsearch.xpack.sql.session.SingletonExecutable; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.util.CollectionUtils; -import org.elasticsearch.xpack.sql.util.Holder; import java.util.ArrayList; import java.util.Arrays; @@ -95,16 +95,16 @@ import java.util.function.Consumer; import static java.util.Collections.singletonList; -import static org.elasticsearch.xpack.sql.expression.Expressions.equalsAsAttribute; -import static org.elasticsearch.xpack.sql.expression.Literal.FALSE; -import static org.elasticsearch.xpack.sql.expression.Literal.TRUE; -import static org.elasticsearch.xpack.sql.expression.predicate.Predicates.combineAnd; -import static org.elasticsearch.xpack.sql.expression.predicate.Predicates.combineOr; -import static org.elasticsearch.xpack.sql.expression.predicate.Predicates.inCommon; -import static org.elasticsearch.xpack.sql.expression.predicate.Predicates.splitAnd; -import static org.elasticsearch.xpack.sql.expression.predicate.Predicates.splitOr; -import static org.elasticsearch.xpack.sql.expression.predicate.Predicates.subtract; -import static org.elasticsearch.xpack.sql.util.CollectionUtils.combine; +import static org.elasticsearch.xpack.ql.expression.Expressions.equalsAsAttribute; +import static org.elasticsearch.xpack.ql.expression.Literal.FALSE; +import static org.elasticsearch.xpack.ql.expression.Literal.TRUE; +import static org.elasticsearch.xpack.ql.expression.predicate.Predicates.combineAnd; +import static org.elasticsearch.xpack.ql.expression.predicate.Predicates.combineOr; +import static org.elasticsearch.xpack.ql.expression.predicate.Predicates.inCommon; +import static org.elasticsearch.xpack.ql.expression.predicate.Predicates.splitAnd; +import static org.elasticsearch.xpack.ql.expression.predicate.Predicates.splitOr; +import static org.elasticsearch.xpack.ql.expression.predicate.Predicates.subtract; +import static org.elasticsearch.xpack.ql.util.CollectionUtils.combine; public class Optimizer extends RuleExecutor { @@ -673,12 +673,12 @@ static class FoldNull extends OptimizerExpressionRule { protected Expression rule(Expression e) { if (e instanceof IsNotNull) { if (((IsNotNull) e).field().nullable() == Nullability.FALSE) { - return new Literal(e.source(), Boolean.TRUE, DataType.BOOLEAN); + return new Literal(e.source(), Boolean.TRUE, DataTypes.BOOLEAN); } } else if (e instanceof IsNull) { if (((IsNull) e).field().nullable() == Nullability.FALSE) { - return new Literal(e.source(), Boolean.FALSE, DataType.BOOLEAN); + return new Literal(e.source(), Boolean.FALSE, DataTypes.BOOLEAN); } } else if (e instanceof In) { @@ -705,7 +705,7 @@ static class ConstantFolding extends OptimizerExpressionRule { @Override protected Expression rule(Expression e) { - return e.foldable() && (e instanceof Literal == false) ? Literal.of(e) : e; + return e.foldable() ? Literal.of(e) : e; } } @@ -808,7 +808,7 @@ private Expression simplifyAndOr(BinaryPredicate bc) { } if (FALSE.equals(l) || FALSE.equals(r)) { - return FALSE; + return new Literal(bc.source(), Boolean.FALSE, DataTypes.BOOLEAN); } if (l.semanticEquals(r)) { return l; @@ -838,7 +838,7 @@ private Expression simplifyAndOr(BinaryPredicate bc) { if (bc instanceof Or) { if (TRUE.equals(l) || TRUE.equals(r)) { - return TRUE; + return new Literal(bc.source(), Boolean.TRUE, DataTypes.BOOLEAN); } if (FALSE.equals(l)) { @@ -883,10 +883,10 @@ private Expression simplifyNot(Not n) { Expression c = n.field(); if (TRUE.semanticEquals(c)) { - return FALSE; + return new Literal(n.source(), Boolean.FALSE, DataTypes.BOOLEAN); } if (FALSE.semanticEquals(c)) { - return TRUE; + return new Literal(n.source(), Boolean.TRUE, DataTypes.BOOLEAN); } if (c instanceof Negatable) { @@ -919,12 +919,12 @@ private Expression simplify(BinaryComparison bc) { // true for equality if (bc instanceof Equals || bc instanceof GreaterThanOrEqual || bc instanceof LessThanOrEqual) { if (l.nullable() == Nullability.FALSE && r.nullable() == Nullability.FALSE && l.semanticEquals(r)) { - return TRUE; + return new Literal(bc.source(), Boolean.TRUE, DataTypes.BOOLEAN); } } if (bc instanceof NullEquals) { if (l.semanticEquals(r)) { - return TRUE; + return new Literal(bc.source(), Boolean.TRUE, DataTypes.BOOLEAN); } if (Expressions.isNull(r)) { return new IsNull(bc.source(), l); @@ -934,7 +934,7 @@ private Expression simplify(BinaryComparison bc) { // false for equality if (bc instanceof NotEquals || bc instanceof GreaterThan || bc instanceof LessThan) { if (l.nullable() == Nullability.FALSE && r.nullable() == Nullability.FALSE && l.semanticEquals(r)) { - return FALSE; + return new Literal(bc.source(), Boolean.FALSE, DataTypes.BOOLEAN); } } @@ -1006,19 +1006,19 @@ private Expression propagate(And and) { if (otherEq.right().foldable()) { for (BinaryComparison eq : equals) { if (otherEq.left().semanticEquals(eq.left())) { - Integer comp = BinaryComparison.compare(eq.right().fold(), otherEq.right().fold()); - if (comp != null) { - // var cannot be equal to two different values at the same time - if (comp != 0) { - return FALSE; + Integer comp = BinaryComparison.compare(eq.right().fold(), otherEq.right().fold()); + if (comp != null) { + // var cannot be equal to two different values at the same time + if (comp != 0) { + return new Literal(and.source(), Boolean.FALSE, DataTypes.BOOLEAN); + } } } } - } equals.add(otherEq); } else { exps.add(otherEq); - } + } } else if (ex instanceof GreaterThan || ex instanceof GreaterThanOrEqual || ex instanceof LessThan || ex instanceof LessThanOrEqual) { BinaryComparison bc = (BinaryComparison) ex; @@ -1055,8 +1055,8 @@ private Expression propagate(And and) { compare > 0 || // eq matches the boundary but should not be included (compare == 0 && !range.includeLower())) - ) { - return FALSE; + ) { + return new Literal(and.source(), Boolean.FALSE, DataTypes.BOOLEAN); } } if (range.upper().foldable()) { @@ -1066,8 +1066,8 @@ private Expression propagate(And and) { compare < 0 || // eq matches the boundary but should not be included (compare == 0 && !range.includeUpper())) - ) { - return FALSE; + ) { + return new Literal(and.source(), Boolean.FALSE, DataTypes.BOOLEAN); } } @@ -1908,13 +1908,13 @@ protected LogicalPlan rule(LogicalPlan plan) { return plan.transformExpressionsDown(e -> { if (e instanceof Min) { Min min = (Min) e; - if (min.field().dataType().isString()) { + if (DataTypes.isString(min.field().dataType())) { return mins.computeIfAbsent(min.field(), k -> new First(min.source(), k, null)); } } if (e instanceof Max) { Max max = (Max) e; - if (max.field().dataType().isString()) { + if (DataTypes.isString(max.field().dataType())) { return maxs.computeIfAbsent(max.field(), k -> new Last(max.source(), k, null)); } } @@ -1950,7 +1950,7 @@ private static Expression foldBinaryLogic(Expression expression) { boolean nullLeft = Expressions.isNull(or.left()); boolean nullRight = Expressions.isNull(or.right()); if (nullLeft && nullRight) { - return Literal.NULL; + return new Literal(expression.source(), null, DataTypes.NULL); } if (nullLeft) { return or.right(); @@ -1962,7 +1962,7 @@ private static Expression foldBinaryLogic(Expression expression) { if (expression instanceof And) { And and = (And) expression; if (Expressions.isNull(and.left()) || Expressions.isNull(and.right())) { - return Literal.NULL; + return new Literal(expression.source(), null, DataTypes.NULL); } } return expression; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/package-info.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/package-info.java index 2a55be6e8163f..635af54eb0ef4 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/package-info.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/package-info.java @@ -56,9 +56,9 @@ *

    Concepts

    * * The building operation of the SQL engine is defined by an action, - * namely a rule (defined in {@link org.elasticsearch.xpack.sql.rule rule} + * namely a rule (defined in {@link org.elasticsearch.xpack.ql.rule rule} * package that accepts one immutable tree (defined in - * {@link org.elasticsearch.xpack.sql.tree tree} package) and transforms + * {@link org.elasticsearch.xpack.ql.tree tree} package) and transforms * it to another immutable tree. * Each rules looks for a certain pattern that it can identify and * then transform. @@ -118,9 +118,9 @@ * To implement the above concepts, several choices have been made in the * engine (which are not common in the rest of the XPack code base). In * particular the conventions/signatures of - * {@link org.elasticsearch.xpack.sql.tree.Node tree}s and usage of + * {@link org.elasticsearch.xpack.ql.tree.Node tree}s and usage of * {@code instanceof} inside - * {@link org.elasticsearch.xpack.sql.rule.Rule rule}s). + * {@link org.elasticsearch.xpack.ql.rule.Rule rule}s). * Java doesn't provide any utilities for tree abstractions or pattern * matching for that matter. Typically for tree traversal one would employ * the Visitor @@ -143,7 +143,7 @@ * {@code instanceof} checks. Which is how many rules are implemented in * the SQL engine as well. Where possible though, one can use typed * traversal by passing a {@code Class} token to the lambdas (i.e. - * {@link org.elasticsearch.xpack.sql.tree.Node#transformDown(java.util.function.Function, Class) + * {@link org.elasticsearch.xpack.ql.tree.Node#transformDown(java.util.function.Function, Class) * pre-order transformation}). * *

    Components

    diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/AbstractBuilder.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/AbstractBuilder.java index aa5af5389a796..734b0fa5c7f61 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/AbstractBuilder.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/AbstractBuilder.java @@ -10,9 +10,9 @@ import org.antlr.v4.runtime.misc.Interval; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.TerminalNode; -import org.elasticsearch.xpack.sql.plan.logical.LogicalPlan; -import org.elasticsearch.xpack.sql.tree.Location; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.tree.Location; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.util.Check; import java.util.ArrayList; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/AstBuilder.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/AstBuilder.java index 48aa2cf1fa79b..e61333989a65c 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/AstBuilder.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/AstBuilder.java @@ -6,8 +6,8 @@ package org.elasticsearch.xpack.sql.parser; import org.antlr.v4.runtime.Token; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; import org.elasticsearch.xpack.sql.parser.SqlBaseParser.SingleStatementContext; -import org.elasticsearch.xpack.sql.plan.logical.LogicalPlan; import org.elasticsearch.xpack.sql.proto.SqlTypedParamValue; import java.util.Map; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/CommandBuilder.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/CommandBuilder.java index 6de27b7776338..d64359128752a 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/CommandBuilder.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/CommandBuilder.java @@ -7,8 +7,11 @@ import org.antlr.v4.runtime.Token; import org.elasticsearch.common.Booleans; -import org.elasticsearch.xpack.sql.analysis.index.IndexResolver.IndexType; -import org.elasticsearch.xpack.sql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.index.IndexResolver.IndexType; +import org.elasticsearch.xpack.ql.plan.TableIdentifier; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.util.StringUtils; import org.elasticsearch.xpack.sql.parser.SqlBaseParser.DebugContext; import org.elasticsearch.xpack.sql.parser.SqlBaseParser.ExplainContext; import org.elasticsearch.xpack.sql.parser.SqlBaseParser.ShowColumnsContext; @@ -19,7 +22,6 @@ import org.elasticsearch.xpack.sql.parser.SqlBaseParser.SysColumnsContext; import org.elasticsearch.xpack.sql.parser.SqlBaseParser.SysTablesContext; import org.elasticsearch.xpack.sql.parser.SqlBaseParser.SysTypesContext; -import org.elasticsearch.xpack.sql.plan.TableIdentifier; import org.elasticsearch.xpack.sql.plan.logical.command.Command; import org.elasticsearch.xpack.sql.plan.logical.command.Debug; import org.elasticsearch.xpack.sql.plan.logical.command.Explain; @@ -31,8 +33,6 @@ import org.elasticsearch.xpack.sql.plan.logical.command.sys.SysTables; import org.elasticsearch.xpack.sql.plan.logical.command.sys.SysTypes; import org.elasticsearch.xpack.sql.proto.SqlTypedParamValue; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.util.StringUtils; import java.util.ArrayList; import java.util.EnumSet; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/ExpressionBuilder.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/ExpressionBuilder.java index 524d4e8b75a8e..df9453228c7a8 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/ExpressionBuilder.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/ExpressionBuilder.java @@ -12,54 +12,58 @@ import org.elasticsearch.common.Booleans; import org.elasticsearch.common.Strings; import org.elasticsearch.common.collect.Tuple; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.Alias; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.expression.Alias; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.Order; +import org.elasticsearch.xpack.ql.expression.Order.NullsPosition; +import org.elasticsearch.xpack.ql.expression.UnresolvedAlias; +import org.elasticsearch.xpack.ql.expression.UnresolvedAttribute; +import org.elasticsearch.xpack.ql.expression.UnresolvedStar; +import org.elasticsearch.xpack.ql.expression.function.Function; +import org.elasticsearch.xpack.ql.expression.function.UnresolvedFunction; +import org.elasticsearch.xpack.ql.expression.function.UnresolvedFunction.ResolutionType; +import org.elasticsearch.xpack.ql.expression.predicate.Range; +import org.elasticsearch.xpack.ql.expression.predicate.fulltext.MatchQueryPredicate; +import org.elasticsearch.xpack.ql.expression.predicate.fulltext.MultiMatchQueryPredicate; +import org.elasticsearch.xpack.ql.expression.predicate.fulltext.StringQueryPredicate; +import org.elasticsearch.xpack.ql.expression.predicate.logical.And; +import org.elasticsearch.xpack.ql.expression.predicate.logical.Not; +import org.elasticsearch.xpack.ql.expression.predicate.logical.Or; +import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.Neg; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.Equals; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.GreaterThan; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.GreaterThanOrEqual; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.LessThan; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.LessThanOrEqual; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.NotEquals; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.NullEquals; +import org.elasticsearch.xpack.ql.expression.predicate.regex.Like; +import org.elasticsearch.xpack.ql.expression.predicate.regex.LikePattern; +import org.elasticsearch.xpack.ql.expression.predicate.regex.RLike; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; +import org.elasticsearch.xpack.ql.util.StringUtils; import org.elasticsearch.xpack.sql.expression.Exists; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.expression.Order; -import org.elasticsearch.xpack.sql.expression.Order.NullsPosition; import org.elasticsearch.xpack.sql.expression.ScalarSubquery; -import org.elasticsearch.xpack.sql.expression.UnresolvedAlias; -import org.elasticsearch.xpack.sql.expression.UnresolvedAttribute; -import org.elasticsearch.xpack.sql.expression.UnresolvedStar; -import org.elasticsearch.xpack.sql.expression.function.Function; -import org.elasticsearch.xpack.sql.expression.function.UnresolvedFunction; -import org.elasticsearch.xpack.sql.expression.function.UnresolvedFunction.ResolutionType; import org.elasticsearch.xpack.sql.expression.function.scalar.Cast; -import org.elasticsearch.xpack.sql.expression.literal.Interval; -import org.elasticsearch.xpack.sql.expression.literal.IntervalDayTime; -import org.elasticsearch.xpack.sql.expression.literal.IntervalYearMonth; -import org.elasticsearch.xpack.sql.expression.literal.Intervals; -import org.elasticsearch.xpack.sql.expression.literal.Intervals.TimeUnit; -import org.elasticsearch.xpack.sql.expression.predicate.Range; +import org.elasticsearch.xpack.sql.expression.literal.interval.Interval; +import org.elasticsearch.xpack.sql.expression.literal.interval.IntervalDayTime; +import org.elasticsearch.xpack.sql.expression.literal.interval.IntervalYearMonth; +import org.elasticsearch.xpack.sql.expression.literal.interval.Intervals; +import org.elasticsearch.xpack.sql.expression.literal.interval.Intervals.TimeUnit; import org.elasticsearch.xpack.sql.expression.predicate.conditional.Case; import org.elasticsearch.xpack.sql.expression.predicate.conditional.IfConditional; -import org.elasticsearch.xpack.sql.expression.predicate.fulltext.MatchQueryPredicate; -import org.elasticsearch.xpack.sql.expression.predicate.fulltext.MultiMatchQueryPredicate; -import org.elasticsearch.xpack.sql.expression.predicate.fulltext.StringQueryPredicate; -import org.elasticsearch.xpack.sql.expression.predicate.logical.And; -import org.elasticsearch.xpack.sql.expression.predicate.logical.Not; -import org.elasticsearch.xpack.sql.expression.predicate.logical.Or; import org.elasticsearch.xpack.sql.expression.predicate.nulls.IsNotNull; import org.elasticsearch.xpack.sql.expression.predicate.nulls.IsNull; import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Add; import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Div; import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Mod; import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Mul; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Neg; import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Sub; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.Equals; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.GreaterThan; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.GreaterThanOrEqual; import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.In; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.LessThan; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.LessThanOrEqual; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.NotEquals; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.NullEquals; -import org.elasticsearch.xpack.sql.expression.predicate.regex.Like; -import org.elasticsearch.xpack.sql.expression.predicate.regex.LikePattern; -import org.elasticsearch.xpack.sql.expression.predicate.regex.RLike; import org.elasticsearch.xpack.sql.parser.SqlBaseParser.ArithmeticBinaryContext; import org.elasticsearch.xpack.sql.parser.SqlBaseParser.ArithmeticUnaryContext; import org.elasticsearch.xpack.sql.parser.SqlBaseParser.BooleanLiteralContext; @@ -110,10 +114,7 @@ import org.elasticsearch.xpack.sql.parser.SqlBaseParser.TimestampEscapedLiteralContext; import org.elasticsearch.xpack.sql.parser.SqlBaseParser.ValueExpressionDefaultContext; import org.elasticsearch.xpack.sql.proto.SqlTypedParamValue; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.DataTypes; -import org.elasticsearch.xpack.sql.util.StringUtils; +import org.elasticsearch.xpack.sql.type.SqlDataTypes; import java.time.Duration; import java.time.Period; @@ -128,7 +129,7 @@ import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; -import static org.elasticsearch.xpack.sql.type.DataTypeConversion.conversionFor; +import static org.elasticsearch.xpack.ql.type.DataTypeConverter.converterFor; import static org.elasticsearch.xpack.sql.util.DateUtils.asDateOnly; import static org.elasticsearch.xpack.sql.util.DateUtils.asTimeOnly; import static org.elasticsearch.xpack.sql.util.DateUtils.ofEscapedLiteral; @@ -407,7 +408,7 @@ public Cast visitCastExpression(CastExpressionContext ctx) { private static DataType dataType(Source ctx, String string) { String type = string.toUpperCase(Locale.ROOT); - DataType dataType = type.startsWith("SQL_") ? DataType.fromOdbcType(type) : DataType.fromSqlOrEsType(type); + DataType dataType = type.startsWith("SQL_") ? SqlDataTypes.fromOdbcType(type) : SqlDataTypes.fromSqlOrEsType(type); if (dataType == null) { throw new ParsingException(ctx, "Does not recognize type [{}]", string); } @@ -519,7 +520,7 @@ public Object visitLogicalBinary(LogicalBinaryContext ctx) { @Override public Expression visitNullLiteral(NullLiteralContext ctx) { - return new Literal(source(ctx), null, DataType.NULL); + return new Literal(source(ctx), null, DataTypes.NULL); } @Override @@ -650,7 +651,7 @@ public Expression visitBooleanLiteral(BooleanLiteralContext ctx) { } catch(IllegalArgumentException iae) { throw new ParsingException(source(ctx), iae.getMessage()); } - return new Literal(source(ctx), Boolean.valueOf(value), DataType.BOOLEAN); + return new Literal(source(ctx), Boolean.valueOf(value), DataTypes.BOOLEAN); } @Override @@ -659,7 +660,7 @@ public Expression visitStringLiteral(StringLiteralContext ctx) { for (TerminalNode node : ctx.STRING()) { sb.append(unquoteString(text(node))); } - return new Literal(source(ctx), sb.toString(), DataType.KEYWORD); + return new Literal(source(ctx), sb.toString(), DataTypes.KEYWORD); } @Override @@ -667,8 +668,8 @@ public Literal visitDecimalLiteral(DecimalLiteralContext ctx) { Tuple tuple = withMinus(ctx); try { - return new Literal(tuple.v1(), Double.valueOf(StringUtils.parseDouble(tuple.v2())), DataType.DOUBLE); - } catch (SqlIllegalArgumentException siae) { + return new Literal(tuple.v1(), Double.valueOf(StringUtils.parseDouble(tuple.v2())), DataTypes.DOUBLE); + } catch (QlIllegalArgumentException siae) { throw new ParsingException(tuple.v1(), siae.getMessage()); } } @@ -680,15 +681,15 @@ public Literal visitIntegerLiteral(IntegerLiteralContext ctx) { long value; try { value = Long.valueOf(StringUtils.parseLong(tuple.v2())); - } catch (SqlIllegalArgumentException siae) { + } catch (QlIllegalArgumentException siae) { throw new ParsingException(tuple.v1(), siae.getMessage()); } Object val = Long.valueOf(value); - DataType type = DataType.LONG; + DataType type = DataTypes.LONG; // try to downsize to int if possible (since that's the most common type) if ((int) value == value) { - type = DataType.INTEGER; + type = DataTypes.INTEGER; val = Integer.valueOf((int) value); } return new Literal(tuple.v1(), val, type); @@ -697,7 +698,7 @@ public Literal visitIntegerLiteral(IntegerLiteralContext ctx) { @Override public Literal visitParamLiteral(ParamLiteralContext ctx) { SqlTypedParamValue param = param(ctx.PARAM()); - DataType dataType = DataType.fromTypeName(param.type); + DataType dataType = SqlDataTypes.fromTypeName(param.type); Source source = source(ctx); if (param.value == null) { // no conversion is required for null values @@ -706,7 +707,7 @@ public Literal visitParamLiteral(ParamLiteralContext ctx) { final DataType sourceType; try { sourceType = DataTypes.fromJava(param.value); - } catch (SqlIllegalArgumentException ex) { + } catch (QlIllegalArgumentException ex) { throw new ParsingException(ex, source, "Unexpected actual parameter type [{}] for type [{}]", param.value.getClass().getName(), param.type); } @@ -716,8 +717,8 @@ public Literal visitParamLiteral(ParamLiteralContext ctx) { } // otherwise we need to make sure that xcontent-serialized value is converted to the correct type try { - return new Literal(source, conversionFor(sourceType, dataType).convert(param.value), dataType); - } catch (SqlIllegalArgumentException ex) { + return new Literal(source, converterFor(sourceType, dataType).convert(param.value), dataType); + } catch (QlIllegalArgumentException ex) { throw new ParsingException(ex, source, "Unexpected actual parameter type [{}] for type [{}]", sourceType, param.type); } } @@ -762,7 +763,7 @@ public Literal visitDateEscapedLiteral(DateEscapedLiteralContext ctx) { Source source = source(ctx); // parse yyyy-MM-dd try { - return new Literal(source, asDateOnly(string), DataType.DATE); + return new Literal(source, asDateOnly(string), SqlDataTypes.DATE); } catch(DateTimeParseException ex) { throw new ParsingException(source, "Invalid date received; {}", ex.getMessage()); } @@ -775,7 +776,7 @@ public Literal visitTimeEscapedLiteral(TimeEscapedLiteralContext ctx) { // parse HH:mm:ss try { - return new Literal(source, asTimeOnly(string), DataType.TIME); + return new Literal(source, asTimeOnly(string), SqlDataTypes.TIME); } catch (DateTimeParseException ex) { throw new ParsingException(source, "Invalid time received; {}", ex.getMessage()); } @@ -788,7 +789,7 @@ public Literal visitTimestampEscapedLiteral(TimestampEscapedLiteralContext ctx) Source source = source(ctx); // parse yyyy-mm-dd hh:mm:ss(.f...) try { - return new Literal(source, ofEscapedLiteral(string), DataType.DATETIME); + return new Literal(source, ofEscapedLiteral(string), DataTypes.DATETIME); } catch (DateTimeParseException ex) { throw new ParsingException(source, "Invalid timestamp received; {}", ex.getMessage()); } @@ -837,7 +838,7 @@ public Literal visitGuidEscapedLiteral(GuidEscapedLiteralContext ctx) { } } - return new Literal(source(ctx), string, DataType.KEYWORD); + return new Literal(source(ctx), string, DataTypes.KEYWORD); } /** diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/IdentifierBuilder.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/IdentifierBuilder.java index e391850dd1776..027b80bbe8bf7 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/IdentifierBuilder.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/IdentifierBuilder.java @@ -7,11 +7,11 @@ import org.antlr.v4.runtime.tree.ParseTree; import org.elasticsearch.common.Strings; +import org.elasticsearch.xpack.ql.plan.TableIdentifier; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.parser.SqlBaseParser.IdentifierContext; import org.elasticsearch.xpack.sql.parser.SqlBaseParser.QualifiedNameContext; import org.elasticsearch.xpack.sql.parser.SqlBaseParser.TableIdentifierContext; -import org.elasticsearch.xpack.sql.plan.TableIdentifier; -import org.elasticsearch.xpack.sql.tree.Source; abstract class IdentifierBuilder extends AbstractBuilder { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/LogicalPlanBuilder.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/LogicalPlanBuilder.java index 9a663994ccf16..9f377cd369e45 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/LogicalPlanBuilder.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/LogicalPlanBuilder.java @@ -8,13 +8,23 @@ import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.tree.TerminalNode; -import org.elasticsearch.xpack.sql.expression.Alias; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.expression.NamedExpression; -import org.elasticsearch.xpack.sql.expression.Order; -import org.elasticsearch.xpack.sql.expression.UnresolvedAlias; -import org.elasticsearch.xpack.sql.expression.UnresolvedAttribute; +import org.elasticsearch.xpack.ql.expression.Alias; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.NamedExpression; +import org.elasticsearch.xpack.ql.expression.Order; +import org.elasticsearch.xpack.ql.expression.UnresolvedAlias; +import org.elasticsearch.xpack.ql.expression.UnresolvedAttribute; +import org.elasticsearch.xpack.ql.plan.TableIdentifier; +import org.elasticsearch.xpack.ql.plan.logical.Aggregate; +import org.elasticsearch.xpack.ql.plan.logical.Filter; +import org.elasticsearch.xpack.ql.plan.logical.Limit; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.plan.logical.OrderBy; +import org.elasticsearch.xpack.ql.plan.logical.Project; +import org.elasticsearch.xpack.ql.plan.logical.UnresolvedRelation; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.parser.SqlBaseParser.AliasedQueryContext; import org.elasticsearch.xpack.sql.parser.SqlBaseParser.AliasedRelationContext; import org.elasticsearch.xpack.sql.parser.SqlBaseParser.FromClauseContext; @@ -35,24 +45,14 @@ import org.elasticsearch.xpack.sql.parser.SqlBaseParser.SetQuantifierContext; import org.elasticsearch.xpack.sql.parser.SqlBaseParser.SubqueryContext; import org.elasticsearch.xpack.sql.parser.SqlBaseParser.TableNameContext; -import org.elasticsearch.xpack.sql.plan.TableIdentifier; -import org.elasticsearch.xpack.sql.plan.logical.Aggregate; import org.elasticsearch.xpack.sql.plan.logical.Distinct; -import org.elasticsearch.xpack.sql.plan.logical.Filter; import org.elasticsearch.xpack.sql.plan.logical.Join; -import org.elasticsearch.xpack.sql.plan.logical.Limit; import org.elasticsearch.xpack.sql.plan.logical.LocalRelation; -import org.elasticsearch.xpack.sql.plan.logical.LogicalPlan; -import org.elasticsearch.xpack.sql.plan.logical.OrderBy; import org.elasticsearch.xpack.sql.plan.logical.Pivot; -import org.elasticsearch.xpack.sql.plan.logical.Project; import org.elasticsearch.xpack.sql.plan.logical.SubQueryAlias; -import org.elasticsearch.xpack.sql.plan.logical.UnresolvedRelation; import org.elasticsearch.xpack.sql.plan.logical.With; import org.elasticsearch.xpack.sql.proto.SqlTypedParamValue; import org.elasticsearch.xpack.sql.session.SingletonExecutable; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; import java.util.ArrayList; import java.util.LinkedHashMap; @@ -105,7 +105,7 @@ public LogicalPlan visitQueryNoWith(QueryNoWithContext ctx) { Token limit = limitClause.limit; if (limit != null && limitClause.INTEGER_VALUE() != null) { plan = new Limit(source(limitClause), new Literal(source(limitClause), - Integer.parseInt(limit.getText()), DataType.INTEGER), plan); + Integer.parseInt(limit.getText()), DataTypes.INTEGER), plan); } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/ParsingException.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/ParsingException.java index a4a2a8df94089..74f5e0a033266 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/ParsingException.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/ParsingException.java @@ -6,12 +6,12 @@ package org.elasticsearch.xpack.sql.parser; import org.elasticsearch.rest.RestStatus; -import org.elasticsearch.xpack.sql.ClientSqlException; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.sql.SqlClientException; import static org.elasticsearch.common.logging.LoggerMessageFormat.format; -public class ParsingException extends ClientSqlException { +public class ParsingException extends SqlClientException { private final int line; private final int charPositionInLine; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/SqlParser.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/SqlParser.java index 6166d87703ead..b61d07078eeca 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/SqlParser.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/SqlParser.java @@ -24,8 +24,8 @@ import org.antlr.v4.runtime.tree.TerminalNode; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; import org.elasticsearch.xpack.sql.proto.SqlTypedParamValue; import java.util.Arrays; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/Distinct.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/Distinct.java index 92282045f8a6c..d8a0eed8300b6 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/Distinct.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/Distinct.java @@ -5,8 +5,10 @@ */ package org.elasticsearch.xpack.sql.plan.logical; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.plan.logical.UnaryPlan; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; public class Distinct extends UnaryPlan { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/Join.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/Join.java index f09b43ec41ddb..85d917bc2c0b2 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/Join.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/Join.java @@ -5,18 +5,20 @@ */ package org.elasticsearch.xpack.sql.plan.logical; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Nullability; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Nullability; +import org.elasticsearch.xpack.ql.plan.logical.BinaryPlan; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataTypes; import java.util.List; import java.util.Objects; import static java.util.stream.Collectors.toList; -import static org.elasticsearch.xpack.sql.util.CollectionUtils.combine; +import static org.elasticsearch.xpack.ql.util.CollectionUtils.combine; public class Join extends BinaryPlan { @@ -100,7 +102,7 @@ public boolean resolved() { return childrenResolved() && duplicatesResolved() && expressionsResolved() && - (condition == null || DataType.BOOLEAN == condition.dataType()); + (condition == null || DataTypes.BOOLEAN == condition.dataType()); } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/LocalRelation.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/LocalRelation.java index 9abe6fef3d4bb..442ef99e3778b 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/LocalRelation.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/LocalRelation.java @@ -6,12 +6,13 @@ package org.elasticsearch.xpack.sql.plan.logical; import org.elasticsearch.action.ActionListener; -import org.elasticsearch.xpack.sql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.session.Cursor.Page; import org.elasticsearch.xpack.sql.session.Executable; -import org.elasticsearch.xpack.sql.session.SqlSession; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.sql.session.Session; import java.util.List; import java.util.Objects; @@ -52,7 +53,7 @@ public List output() { } @Override - public void execute(SqlSession session, ActionListener listener) { + public void execute(Session session, ActionListener listener) { executable.execute(session, listener); } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/Pivot.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/Pivot.java index 35447ecb40510..55cec8d80a6fd 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/Pivot.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/Pivot.java @@ -6,19 +6,21 @@ package org.elasticsearch.xpack.sql.plan.logical; +import org.elasticsearch.xpack.ql.capabilities.Resolvables; +import org.elasticsearch.xpack.ql.expression.Alias; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.AttributeMap; +import org.elasticsearch.xpack.ql.expression.AttributeSet; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.NamedExpression; +import org.elasticsearch.xpack.ql.expression.function.Function; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.plan.logical.UnaryPlan; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.capabilities.Resolvables; -import org.elasticsearch.xpack.sql.expression.Alias; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.expression.AttributeMap; -import org.elasticsearch.xpack.sql.expression.AttributeSet; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.expression.NamedExpression; -import org.elasticsearch.xpack.sql.expression.function.Function; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; import java.util.ArrayList; import java.util.LinkedHashMap; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/SubQueryAlias.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/SubQueryAlias.java index dd8fa5bec430e..f86051d986e64 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/SubQueryAlias.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/SubQueryAlias.java @@ -5,9 +5,11 @@ */ package org.elasticsearch.xpack.sql.plan.logical; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.plan.logical.UnaryPlan; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.List; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/With.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/With.java index 6c30aab11b994..f2167169fe232 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/With.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/With.java @@ -5,12 +5,14 @@ */ package org.elasticsearch.xpack.sql.plan.logical; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.plan.logical.UnaryPlan; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; + import java.util.Map; import java.util.Objects; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; - public class With extends UnaryPlan { private final Map subQueries; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/command/Command.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/command/Command.java index 0b9766345869d..30511f78f7714 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/command/Command.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/command/Command.java @@ -5,24 +5,24 @@ */ package org.elasticsearch.xpack.sql.plan.logical.command; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; -import org.elasticsearch.xpack.sql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.EsField; +import org.elasticsearch.xpack.ql.type.KeywordEsField; import org.elasticsearch.xpack.sql.session.Cursor.Page; -import org.elasticsearch.xpack.sql.session.Executable; import org.elasticsearch.xpack.sql.session.ListCursor; import org.elasticsearch.xpack.sql.session.Rows; +import org.elasticsearch.xpack.sql.session.SqlExecutable; import org.elasticsearch.xpack.sql.session.SqlSession; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.EsField; -import org.elasticsearch.xpack.sql.type.KeywordEsField; import java.util.List; import static java.util.Collections.emptyList; import static java.util.Collections.emptyMap; -public abstract class Command extends LogicalPlan implements Executable { +public abstract class Command extends LogicalPlan implements SqlExecutable { protected Command(Source source) { super(source, emptyList()); diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/command/Debug.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/command/Debug.java index eda730e8adbb0..a8ed20a1c6d6c 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/command/Debug.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/command/Debug.java @@ -6,21 +6,21 @@ package org.elasticsearch.xpack.sql.plan.logical.command; import org.elasticsearch.action.ActionListener; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; -import org.elasticsearch.xpack.sql.plan.logical.LogicalPlan; -import org.elasticsearch.xpack.sql.rule.RuleExecutor.Batch; -import org.elasticsearch.xpack.sql.rule.RuleExecutor.ExecutionInfo; -import org.elasticsearch.xpack.sql.rule.RuleExecutor.Transformation; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.rule.RuleExecutor.Batch; +import org.elasticsearch.xpack.ql.rule.RuleExecutor.ExecutionInfo; +import org.elasticsearch.xpack.ql.rule.RuleExecutor.Transformation; +import org.elasticsearch.xpack.ql.tree.Node; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.NodeUtils; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.KeywordEsField; +import org.elasticsearch.xpack.ql.util.Graphviz; import org.elasticsearch.xpack.sql.session.Cursor.Page; import org.elasticsearch.xpack.sql.session.Rows; import org.elasticsearch.xpack.sql.session.SqlSession; -import org.elasticsearch.xpack.sql.tree.Node; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.NodeUtils; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.KeywordEsField; -import org.elasticsearch.xpack.sql.util.Graphviz; import java.util.LinkedHashMap; import java.util.List; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/command/Explain.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/command/Explain.java index d3eac1cd6bbb3..7f7d5c9a0528f 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/command/Explain.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/command/Explain.java @@ -7,19 +7,19 @@ import org.elasticsearch.action.ActionListener; import org.elasticsearch.common.Strings; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; -import org.elasticsearch.xpack.sql.plan.QueryPlan; -import org.elasticsearch.xpack.sql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.plan.QueryPlan; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.KeywordEsField; +import org.elasticsearch.xpack.ql.util.Graphviz; import org.elasticsearch.xpack.sql.plan.physical.PhysicalPlan; import org.elasticsearch.xpack.sql.planner.Planner; import org.elasticsearch.xpack.sql.session.Cursor.Page; import org.elasticsearch.xpack.sql.session.Rows; import org.elasticsearch.xpack.sql.session.SqlSession; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.KeywordEsField; -import org.elasticsearch.xpack.sql.util.Graphviz; import java.util.HashMap; import java.util.List; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/command/ShowColumns.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/command/ShowColumns.java index 33643fa0f9ff0..d510e2c4926f8 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/command/ShowColumns.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/command/ShowColumns.java @@ -6,16 +6,17 @@ package org.elasticsearch.xpack.sql.plan.logical.command; import org.elasticsearch.action.ActionListener; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; -import org.elasticsearch.xpack.sql.expression.predicate.regex.LikePattern; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.expression.predicate.regex.LikePattern; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.EsField; +import org.elasticsearch.xpack.ql.type.KeywordEsField; import org.elasticsearch.xpack.sql.session.Cursor.Page; import org.elasticsearch.xpack.sql.session.SqlSession; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.EsField; -import org.elasticsearch.xpack.sql.type.KeywordEsField; +import org.elasticsearch.xpack.sql.type.SqlDataTypes; import java.util.ArrayList; import java.util.List; @@ -84,7 +85,7 @@ private void fillInRows(Map mapping, String prefix, List output() { public void execute(SqlSession session, ActionListener listener) { FunctionRegistry registry = session.functionRegistry(); Collection functions = registry.listFunctions(pattern != null ? pattern.asJavaRegex() : null); - listener.onResponse(of(session, functions.stream() - .map(f -> asList(f.name(), f.type().name())) + .map(f -> asList(f.name(), SqlFunctionTypeRegistry.INSTANCE.type(f.clazz()))) .collect(toList()))); } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/command/ShowSchemas.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/command/ShowSchemas.java index 6ebcfb2b16b20..c4d70301a5b2e 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/command/ShowSchemas.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/command/ShowSchemas.java @@ -6,14 +6,14 @@ package org.elasticsearch.xpack.sql.plan.logical.command; import org.elasticsearch.action.ActionListener; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.KeywordEsField; import org.elasticsearch.xpack.sql.session.Cursor.Page; import org.elasticsearch.xpack.sql.session.Rows; import org.elasticsearch.xpack.sql.session.SqlSession; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.KeywordEsField; import java.util.List; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/command/ShowTables.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/command/ShowTables.java index 4cdeae3ef5010..5f5f6498f2bed 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/command/ShowTables.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/command/ShowTables.java @@ -6,13 +6,13 @@ package org.elasticsearch.xpack.sql.plan.logical.command; import org.elasticsearch.action.ActionListener; -import org.elasticsearch.xpack.sql.analysis.index.IndexResolver.IndexType; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.expression.predicate.regex.LikePattern; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.predicate.regex.LikePattern; +import org.elasticsearch.xpack.ql.index.IndexResolver.IndexType; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.session.Cursor.Page; import org.elasticsearch.xpack.sql.session.SqlSession; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; import java.util.EnumSet; import java.util.List; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/command/sys/SysColumns.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/command/sys/SysColumns.java index a1bb62b00215f..87dcbfb436d2d 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/command/sys/SysColumns.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/logical/command/sys/SysColumns.java @@ -8,20 +8,19 @@ import org.apache.lucene.util.Counter; import org.elasticsearch.action.ActionListener; import org.elasticsearch.common.Strings; -import org.elasticsearch.xpack.sql.analysis.index.EsIndex; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.expression.predicate.regex.LikePattern; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.predicate.regex.LikePattern; +import org.elasticsearch.xpack.ql.index.EsIndex; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.EsField; +import org.elasticsearch.xpack.ql.util.StringUtils; import org.elasticsearch.xpack.sql.plan.logical.command.Command; import org.elasticsearch.xpack.sql.proto.Mode; import org.elasticsearch.xpack.sql.session.Cursor.Page; import org.elasticsearch.xpack.sql.session.Rows; import org.elasticsearch.xpack.sql.session.SqlSession; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.DataTypes; -import org.elasticsearch.xpack.sql.type.EsField; -import org.elasticsearch.xpack.sql.util.StringUtils; import java.sql.DatabaseMetaData; import java.util.ArrayList; @@ -31,8 +30,17 @@ import java.util.regex.Pattern; import static java.util.Arrays.asList; -import static org.elasticsearch.xpack.sql.type.DataType.INTEGER; -import static org.elasticsearch.xpack.sql.type.DataType.SHORT; +import static org.elasticsearch.xpack.ql.type.DataTypes.BINARY; +import static org.elasticsearch.xpack.ql.type.DataTypes.INTEGER; +import static org.elasticsearch.xpack.ql.type.DataTypes.NESTED; +import static org.elasticsearch.xpack.ql.type.DataTypes.SHORT; +import static org.elasticsearch.xpack.ql.type.DataTypes.isPrimitive; +import static org.elasticsearch.xpack.ql.type.DataTypes.isString; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.displaySize; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.metaSqlDataType; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.metaSqlDateTimeSub; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.metaSqlRadix; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.sqlType; /** * System command designed to be used by JDBC / ODBC for column metadata, such as @@ -160,21 +168,21 @@ private static void fillInRows(String clusterName, String indexName, Map output() { @Override public final void execute(SqlSession session, ActionListener listener) { - Stream values = Stream.of(DataType.values()); + Stream values = SqlDataTypes.types().stream(); if (type.intValue() != 0) { - values = values.filter(t -> type.equals(t.sqlType.getVendorTypeNumber())); + values = values.filter(t -> type.equals(sqlType(t).getVendorTypeNumber())); } List> rows = values // sort by SQL int type (that's what the JDBC/ODBC specs want) followed by name - .sorted(Comparator.comparing((DataType t) -> t.sqlType.getVendorTypeNumber()).thenComparing(DataType::sqlName)) + .sorted(Comparator.comparing((DataType t) -> sqlType(t).getVendorTypeNumber()) + .thenComparing((DataType t) -> sqlType(t).getName())) .map(t -> asList(t.toString(), - t.sqlType.getVendorTypeNumber(), - DataTypes.precision(t), + sqlType(t).getVendorTypeNumber(), precision(t), "'", "'", null, // don't be specific on nullable DatabaseMetaData.typeNullableUnknown, // all strings are case-sensitive - t.isString(), + isString(t), // everything is searchable, DatabaseMetaData.typeSearchable, // only numerics are signed - !t.isSigned(), + isSigned(t) == false, //no fixed precision scale SQL_FALSE Boolean.FALSE, // not auto-incremented Boolean.FALSE, null, - DataTypes.metaSqlMinimumScale(t), - DataTypes.metaSqlMaximumScale(t), + metaSqlMinimumScale(t), metaSqlMaximumScale(t), // SQL_DATA_TYPE - ODBC wants this to be not null - DataTypes.metaSqlDataType(t), - DataTypes.metaSqlDateTimeSub(t), + metaSqlDataType(t), metaSqlDateTimeSub(t), // Radix - DataTypes.metaSqlRadix(t), + metaSqlRadix(t), null )) .collect(toList()); diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/AggregateExec.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/AggregateExec.java index 763744f1abab0..ec3b04d36b95d 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/AggregateExec.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/AggregateExec.java @@ -5,12 +5,13 @@ */ package org.elasticsearch.xpack.sql.plan.physical; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.NamedExpression; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.NamedExpression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; + import java.util.List; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/BinaryExec.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/BinaryExec.java index 0510e840eea1d..923fff1385777 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/BinaryExec.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/BinaryExec.java @@ -5,12 +5,12 @@ */ package org.elasticsearch.xpack.sql.plan.physical; +import org.elasticsearch.xpack.ql.tree.Source; + import java.util.Arrays; import java.util.List; import java.util.Objects; -import org.elasticsearch.xpack.sql.tree.Source; - abstract class BinaryExec extends PhysicalPlan { private final PhysicalPlan left, right; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/CommandExec.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/CommandExec.java index 43a7bfac4628b..3da3949e09a16 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/CommandExec.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/CommandExec.java @@ -6,12 +6,12 @@ package org.elasticsearch.xpack.sql.plan.physical; import org.elasticsearch.action.ActionListener; -import org.elasticsearch.xpack.sql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.plan.logical.command.Command; import org.elasticsearch.xpack.sql.session.Cursor.Page; import org.elasticsearch.xpack.sql.session.SqlSession; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; import java.util.List; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/EsQueryExec.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/EsQueryExec.java index 6e132fb687110..a4b210c8b5af4 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/EsQueryExec.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/EsQueryExec.java @@ -6,13 +6,13 @@ package org.elasticsearch.xpack.sql.plan.physical; import org.elasticsearch.action.ActionListener; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.execution.search.Querier; -import org.elasticsearch.xpack.sql.expression.Attribute; import org.elasticsearch.xpack.sql.querydsl.container.QueryContainer; import org.elasticsearch.xpack.sql.session.Cursor.Page; import org.elasticsearch.xpack.sql.session.SqlSession; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; import java.util.List; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/FilterExec.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/FilterExec.java index f8ea6eac37c84..fd0fa82f895a1 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/FilterExec.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/FilterExec.java @@ -5,14 +5,14 @@ */ package org.elasticsearch.xpack.sql.plan.physical; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; + import java.util.List; import java.util.Objects; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; - public class FilterExec extends UnaryExec implements Unexecutable { private final Expression condition; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/LeafExec.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/LeafExec.java index 515915820d82f..6f3ad370ea214 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/LeafExec.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/LeafExec.java @@ -5,13 +5,18 @@ */ package org.elasticsearch.xpack.sql.plan.physical; +import org.elasticsearch.action.ActionListener; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.sql.session.Cursor.Page; +import org.elasticsearch.xpack.sql.session.Session; +import org.elasticsearch.xpack.sql.session.SqlSession; + import java.util.Collections; import java.util.List; -import org.elasticsearch.xpack.sql.tree.Source; +public abstract class LeafExec extends PhysicalPlan { -abstract class LeafExec extends PhysicalPlan { - LeafExec(Source source) { + protected LeafExec(Source source) { super(source, Collections.emptyList()); } @@ -19,4 +24,11 @@ abstract class LeafExec extends PhysicalPlan { public final LeafExec replaceChildren(List newChildren) { throw new UnsupportedOperationException("this type of node doesn't have any children to replace"); } + + @Override + public void execute(Session session, ActionListener listener) { + execute((SqlSession) session, listener); + } + + abstract void execute(SqlSession session, ActionListener listener); } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/LimitExec.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/LimitExec.java index 25795296d5ae0..cca353f5d522e 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/LimitExec.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/LimitExec.java @@ -5,11 +5,11 @@ */ package org.elasticsearch.xpack.sql.plan.physical; -import java.util.Objects; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; +import java.util.Objects; public class LimitExec extends UnaryExec implements Unexecutable { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/LocalExec.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/LocalExec.java index c0adb1a98659a..65de11cd9b53c 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/LocalExec.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/LocalExec.java @@ -6,13 +6,13 @@ package org.elasticsearch.xpack.sql.plan.physical; import org.elasticsearch.action.ActionListener; -import org.elasticsearch.xpack.sql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.session.Cursor.Page; import org.elasticsearch.xpack.sql.session.EmptyExecutable; import org.elasticsearch.xpack.sql.session.Executable; import org.elasticsearch.xpack.sql.session.SqlSession; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; import java.util.List; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/OrderExec.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/OrderExec.java index 5311ce21b9c31..e7c82c4f4651d 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/OrderExec.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/OrderExec.java @@ -5,13 +5,13 @@ */ package org.elasticsearch.xpack.sql.plan.physical; +import org.elasticsearch.xpack.ql.expression.Order; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; + import java.util.List; import java.util.Objects; -import org.elasticsearch.xpack.sql.expression.Order; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; - public class OrderExec extends UnaryExec implements Unexecutable { private final List order; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/PhysicalPlan.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/PhysicalPlan.java index e1cef71d36520..9df80ef5b7117 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/PhysicalPlan.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/PhysicalPlan.java @@ -5,13 +5,13 @@ */ package org.elasticsearch.xpack.sql.plan.physical; -import java.util.List; - -import org.elasticsearch.xpack.sql.plan.QueryPlan; +import org.elasticsearch.xpack.ql.plan.QueryPlan; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.Schema; import org.elasticsearch.xpack.sql.session.Executable; import org.elasticsearch.xpack.sql.session.Rows; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.Schema; + +import java.util.List; /** * A PhysicalPlan is "how" a LogicalPlan (the "what") actually gets translated into one or more queries. diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/PivotExec.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/PivotExec.java index 579a53696eec1..3133147020609 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/PivotExec.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/PivotExec.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.plan.physical; -import org.elasticsearch.xpack.sql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.plan.logical.Pivot; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; import java.util.List; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/ProjectExec.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/ProjectExec.java index bb498e0261224..caafe83660376 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/ProjectExec.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/ProjectExec.java @@ -5,15 +5,15 @@ */ package org.elasticsearch.xpack.sql.plan.physical; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.NamedExpression; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; + import java.util.List; import java.util.Objects; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.NamedExpression; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; - public class ProjectExec extends UnaryExec implements Unexecutable { private final List projections; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/UnaryExec.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/UnaryExec.java index b057c38f16e41..d474d55d773df 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/UnaryExec.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/UnaryExec.java @@ -5,18 +5,18 @@ */ package org.elasticsearch.xpack.sql.plan.physical; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.tree.Source; + import java.util.Collections; import java.util.List; import java.util.Objects; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.tree.Source; - -abstract class UnaryExec extends PhysicalPlan { +public abstract class UnaryExec extends PhysicalPlan { private final PhysicalPlan child; - UnaryExec(Source source, PhysicalPlan child) { + protected UnaryExec(Source source, PhysicalPlan child) { super(source, Collections.singletonList(child)); this.child = child; } @@ -28,6 +28,7 @@ public final PhysicalPlan replaceChildren(List newChildren) { } return replaceChild(newChildren.get(0)); } + protected abstract UnaryExec replaceChild(PhysicalPlan newChild); public PhysicalPlan child() { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/Unexecutable.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/Unexecutable.java index a32d2f889909c..3aa2441e6ef1b 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/Unexecutable.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/Unexecutable.java @@ -9,14 +9,14 @@ import org.elasticsearch.xpack.sql.planner.PlanningException; import org.elasticsearch.xpack.sql.session.Cursor.Page; import org.elasticsearch.xpack.sql.session.Executable; -import org.elasticsearch.xpack.sql.session.SqlSession; +import org.elasticsearch.xpack.sql.session.Session; // this is mainly a marker interface to validate a plan before being executed public interface Unexecutable extends Executable { @Override - default void execute(SqlSession session, ActionListener listener) { + default void execute(Session session, ActionListener listener) { throw new PlanningException("Current plan {} is not executable", this); } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/UnplannedExec.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/UnplannedExec.java index b8c909fc1c374..db0e7d05f4827 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/UnplannedExec.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plan/physical/UnplannedExec.java @@ -5,14 +5,18 @@ */ package org.elasticsearch.xpack.sql.plan.physical; +import org.elasticsearch.action.ActionListener; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.sql.planner.PlanningException; +import org.elasticsearch.xpack.sql.session.Cursor.Page; +import org.elasticsearch.xpack.sql.session.SqlSession; + import java.util.List; import java.util.Objects; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.plan.logical.LogicalPlan; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.NodeInfo; - public class UnplannedExec extends LeafExec implements Unexecutable { private final LogicalPlan plan; @@ -36,6 +40,11 @@ public List output() { return plan.output(); } + @Override + void execute(SqlSession session, ActionListener listener) { + throw new PlanningException("Current plan {} is not executable", this); + } + @Override public int hashCode() { return plan.hashCode(); diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/FoldingException.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/FoldingException.java index 7cdd26d540432..ce7b550dfe259 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/FoldingException.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/FoldingException.java @@ -6,13 +6,13 @@ package org.elasticsearch.xpack.sql.planner; import org.elasticsearch.rest.RestStatus; -import org.elasticsearch.xpack.sql.ClientSqlException; -import org.elasticsearch.xpack.sql.tree.Location; -import org.elasticsearch.xpack.sql.tree.Node; +import org.elasticsearch.xpack.ql.tree.Location; +import org.elasticsearch.xpack.ql.tree.Node; +import org.elasticsearch.xpack.sql.SqlClientException; import static org.elasticsearch.common.logging.LoggerMessageFormat.format; -public class FoldingException extends ClientSqlException { +public class FoldingException extends SqlClientException { private final int line; private final int column; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/Mapper.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/Mapper.java index 522d5a944dc50..b3a1f10317f6f 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/Mapper.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/Mapper.java @@ -5,17 +5,20 @@ */ package org.elasticsearch.xpack.sql.planner; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.plan.logical.Aggregate; -import org.elasticsearch.xpack.sql.plan.logical.EsRelation; -import org.elasticsearch.xpack.sql.plan.logical.Filter; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.plan.logical.Aggregate; +import org.elasticsearch.xpack.ql.plan.logical.EsRelation; +import org.elasticsearch.xpack.ql.plan.logical.Filter; +import org.elasticsearch.xpack.ql.plan.logical.Limit; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.plan.logical.OrderBy; +import org.elasticsearch.xpack.ql.plan.logical.Project; +import org.elasticsearch.xpack.ql.rule.Rule; +import org.elasticsearch.xpack.ql.rule.RuleExecutor; +import org.elasticsearch.xpack.ql.util.ReflectionUtils; import org.elasticsearch.xpack.sql.plan.logical.Join; -import org.elasticsearch.xpack.sql.plan.logical.Limit; import org.elasticsearch.xpack.sql.plan.logical.LocalRelation; -import org.elasticsearch.xpack.sql.plan.logical.LogicalPlan; -import org.elasticsearch.xpack.sql.plan.logical.OrderBy; import org.elasticsearch.xpack.sql.plan.logical.Pivot; -import org.elasticsearch.xpack.sql.plan.logical.Project; import org.elasticsearch.xpack.sql.plan.logical.With; import org.elasticsearch.xpack.sql.plan.logical.command.Command; import org.elasticsearch.xpack.sql.plan.physical.AggregateExec; @@ -30,9 +33,6 @@ import org.elasticsearch.xpack.sql.plan.physical.ProjectExec; import org.elasticsearch.xpack.sql.plan.physical.UnplannedExec; import org.elasticsearch.xpack.sql.querydsl.container.QueryContainer; -import org.elasticsearch.xpack.sql.rule.Rule; -import org.elasticsearch.xpack.sql.rule.RuleExecutor; -import org.elasticsearch.xpack.sql.util.ReflectionUtils; import java.util.Arrays; import java.util.List; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/Planner.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/Planner.java index b6651821a9b64..ac293fd3384d9 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/Planner.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/Planner.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.planner; -import org.elasticsearch.xpack.sql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.tree.Node; import org.elasticsearch.xpack.sql.plan.physical.PhysicalPlan; import org.elasticsearch.xpack.sql.planner.Verifier.Failure; -import org.elasticsearch.xpack.sql.tree.Node; import java.util.List; import java.util.Map; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/PlanningException.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/PlanningException.java index 8b5f282973c18..8a013fee2f951 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/PlanningException.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/PlanningException.java @@ -6,14 +6,14 @@ package org.elasticsearch.xpack.sql.planner; import org.elasticsearch.rest.RestStatus; -import org.elasticsearch.xpack.sql.ClientSqlException; +import org.elasticsearch.xpack.ql.tree.Location; +import org.elasticsearch.xpack.sql.SqlClientException; import org.elasticsearch.xpack.sql.planner.Verifier.Failure; -import org.elasticsearch.xpack.sql.tree.Location; import java.util.Collection; import java.util.stream.Collectors; -public class PlanningException extends ClientSqlException { +public class PlanningException extends SqlClientException { public PlanningException(String message, Object... args) { super(message, args); } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/QueryFolder.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/QueryFolder.java index 72e4ca380fd33..335df0603b148 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/QueryFolder.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/QueryFolder.java @@ -6,40 +6,42 @@ package org.elasticsearch.xpack.sql.planner; import org.elasticsearch.common.collect.Tuple; +import org.elasticsearch.xpack.ql.execution.search.AggRef; +import org.elasticsearch.xpack.ql.execution.search.FieldExtraction; +import org.elasticsearch.xpack.ql.expression.Alias; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.AttributeMap; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.NamedExpression; +import org.elasticsearch.xpack.ql.expression.Order; +import org.elasticsearch.xpack.ql.expression.ReferenceAttribute; +import org.elasticsearch.xpack.ql.expression.function.Function; +import org.elasticsearch.xpack.ql.expression.function.Functions; +import org.elasticsearch.xpack.ql.expression.function.aggregate.AggregateFunction; +import org.elasticsearch.xpack.ql.expression.function.aggregate.Count; +import org.elasticsearch.xpack.ql.expression.function.aggregate.InnerAggregate; +import org.elasticsearch.xpack.ql.expression.function.grouping.GroupingFunction; +import org.elasticsearch.xpack.ql.expression.function.scalar.ScalarFunction; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.AggPathInput; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.UnaryPipe; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.rule.Rule; +import org.elasticsearch.xpack.ql.rule.RuleExecutor; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.execution.search.AggRef; -import org.elasticsearch.xpack.sql.execution.search.FieldExtraction; -import org.elasticsearch.xpack.sql.expression.Alias; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.expression.AttributeMap; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; import org.elasticsearch.xpack.sql.expression.Foldables; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.expression.NamedExpression; -import org.elasticsearch.xpack.sql.expression.Order; -import org.elasticsearch.xpack.sql.expression.ReferenceAttribute; -import org.elasticsearch.xpack.sql.expression.function.Function; -import org.elasticsearch.xpack.sql.expression.function.Functions; import org.elasticsearch.xpack.sql.expression.function.Score; -import org.elasticsearch.xpack.sql.expression.function.aggregate.AggregateFunction; import org.elasticsearch.xpack.sql.expression.function.aggregate.CompoundNumericAggregate; -import org.elasticsearch.xpack.sql.expression.function.aggregate.Count; -import org.elasticsearch.xpack.sql.expression.function.aggregate.InnerAggregate; import org.elasticsearch.xpack.sql.expression.function.aggregate.TopHits; -import org.elasticsearch.xpack.sql.expression.function.grouping.GroupingFunction; import org.elasticsearch.xpack.sql.expression.function.grouping.Histogram; -import org.elasticsearch.xpack.sql.expression.function.scalar.ScalarFunction; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTimeHistogramFunction; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.Year; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.AggPathInput; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.UnaryPipe; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.expression.literal.IntervalYearMonth; -import org.elasticsearch.xpack.sql.expression.literal.Intervals; +import org.elasticsearch.xpack.sql.expression.literal.interval.IntervalYearMonth; +import org.elasticsearch.xpack.sql.expression.literal.interval.Intervals; import org.elasticsearch.xpack.sql.plan.logical.Pivot; import org.elasticsearch.xpack.sql.plan.physical.AggregateExec; import org.elasticsearch.xpack.sql.plan.physical.EsQueryExec; @@ -73,8 +75,6 @@ import org.elasticsearch.xpack.sql.querydsl.container.Sort.Missing; import org.elasticsearch.xpack.sql.querydsl.container.TopHitsAggRef; import org.elasticsearch.xpack.sql.querydsl.query.Query; -import org.elasticsearch.xpack.sql.rule.Rule; -import org.elasticsearch.xpack.sql.rule.RuleExecutor; import org.elasticsearch.xpack.sql.session.EmptyExecutable; import org.elasticsearch.xpack.sql.util.Check; import org.elasticsearch.xpack.sql.util.DateUtils; @@ -88,11 +88,12 @@ import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicReference; +import static org.elasticsearch.xpack.ql.util.CollectionUtils.combine; import static org.elasticsearch.xpack.sql.planner.QueryTranslator.and; import static org.elasticsearch.xpack.sql.planner.QueryTranslator.toAgg; import static org.elasticsearch.xpack.sql.planner.QueryTranslator.toQuery; -import static org.elasticsearch.xpack.sql.type.DataType.DATE; -import static org.elasticsearch.xpack.sql.util.CollectionUtils.combine; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.DATE; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.isDateBased; /** * Folds the PhysicalPlan into a {@link Query}. @@ -318,7 +319,7 @@ else if (exp instanceof GroupingFunction) { Expression field = h.field(); // date histogram - if (h.dataType().isDateBased()) { + if (isDateBased(h.dataType())) { Object value = h.interval().value(); // interval of exactly 1 year if (value instanceof IntervalYearMonth @@ -502,7 +503,7 @@ else if (target instanceof Function) { if (matchingGroup != null) { if (exp instanceof Attribute || exp instanceof ScalarFunction || exp instanceof GroupingFunction) { Processor action = null; - boolean isDateBased = exp.dataType().isDateBased(); + boolean isDateBased = isDateBased(exp.dataType()); /* * special handling of dates since aggs return the typed Date object which needs * extraction instead of handling this in the scroller, the folder handles this @@ -547,11 +548,11 @@ else if (target instanceof Function) { // attributes can only refer to declared groups if (target instanceof Attribute) { Check.notNull(matchingGroup, "Cannot find group [{}]", Expressions.name(target)); - queryC = queryC.addColumn(new GroupByRef(matchingGroup.id(), null, target.dataType().isDateBased()), id); + queryC = queryC.addColumn(new GroupByRef(matchingGroup.id(), null, isDateBased(target.dataType())), id); } // handle histogram else if (target instanceof GroupingFunction) { - queryC = queryC.addColumn(new GroupByRef(matchingGroup.id(), null, target.dataType().isDateBased()), id); + queryC = queryC.addColumn(new GroupByRef(matchingGroup.id(), null, isDateBased(target.dataType())), id); } // handle literal else if (target.foldable()) { @@ -577,7 +578,7 @@ else if (target.foldable()) { matchingGroup = groupingContext.groupFor(target); Check.notNull(matchingGroup, "Cannot find group [{}]", Expressions.name(ne)); - queryC = queryC.addColumn(new GroupByRef(matchingGroup.id(), null, ne.dataType().isDateBased()), id); + queryC = queryC.addColumn(new GroupByRef(matchingGroup.id(), null, isDateBased(ne.dataType())), id); } // fallback else { @@ -625,7 +626,7 @@ private static Tuple addAggFunction(GroupByKey gro if (f instanceof InnerAggregate) { InnerAggregate ia = (InnerAggregate) f; - CompoundNumericAggregate outer = ia.outer(); + CompoundNumericAggregate outer = (CompoundNumericAggregate) ia.outer(); String cAggPath = compoundAggMap.get(outer); // the compound agg hasn't been seen before so initialize it @@ -642,14 +643,14 @@ private static Tuple addAggFunction(GroupByKey gro aggInput = new AggPathInput(f, new MetricAggRef(cAggPath, ia.innerName(), ia.innerKey() != null ? QueryTranslator.nameOf(ia.innerKey()) : null, - ia.dataType().isDateBased())); + isDateBased(ia.dataType()))); } else { LeafAgg leafAgg = toAgg(functionId, f); if (f instanceof TopHits) { aggInput = new AggPathInput(f, new TopHitsAggRef(leafAgg.id(), f.dataType())); } else { - aggInput = new AggPathInput(f, new MetricAggRef(leafAgg.id(), f.dataType().isDateBased())); + aggInput = new AggPathInput(f, new MetricAggRef(leafAgg.id(), isDateBased(f.dataType()))); } queryC = queryC.with(queryC.aggs().addAgg(leafAgg)); } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/QueryTranslator.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/QueryTranslator.java index 149999a880214..4285e2b57ca9b 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/QueryTranslator.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/QueryTranslator.java @@ -9,17 +9,41 @@ import org.elasticsearch.geometry.Geometry; import org.elasticsearch.geometry.Point; import org.elasticsearch.search.sort.SortOrder; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.NamedExpression; +import org.elasticsearch.xpack.ql.expression.function.Function; +import org.elasticsearch.xpack.ql.expression.function.aggregate.AggregateFunction; +import org.elasticsearch.xpack.ql.expression.function.aggregate.Count; +import org.elasticsearch.xpack.ql.expression.function.scalar.ScalarFunction; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.expression.predicate.Range; +import org.elasticsearch.xpack.ql.expression.predicate.fulltext.MatchQueryPredicate; +import org.elasticsearch.xpack.ql.expression.predicate.fulltext.MultiMatchQueryPredicate; +import org.elasticsearch.xpack.ql.expression.predicate.fulltext.StringQueryPredicate; +import org.elasticsearch.xpack.ql.expression.predicate.logical.And; +import org.elasticsearch.xpack.ql.expression.predicate.logical.Not; +import org.elasticsearch.xpack.ql.expression.predicate.logical.Or; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.BinaryComparison; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.Equals; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.GreaterThan; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.GreaterThanOrEqual; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.LessThan; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.LessThanOrEqual; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.NotEquals; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.NullEquals; +import org.elasticsearch.xpack.ql.expression.predicate.regex.Like; +import org.elasticsearch.xpack.ql.expression.predicate.regex.LikePattern; +import org.elasticsearch.xpack.ql.expression.predicate.regex.RLike; +import org.elasticsearch.xpack.ql.expression.predicate.regex.RegexMatch; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.util.Holder; +import org.elasticsearch.xpack.ql.util.ReflectionUtils; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.expression.NamedExpression; -import org.elasticsearch.xpack.sql.expression.function.Function; -import org.elasticsearch.xpack.sql.expression.function.aggregate.AggregateFunction; import org.elasticsearch.xpack.sql.expression.function.aggregate.Avg; import org.elasticsearch.xpack.sql.expression.function.aggregate.CompoundNumericAggregate; -import org.elasticsearch.xpack.sql.expression.function.aggregate.Count; import org.elasticsearch.xpack.sql.expression.function.aggregate.ExtendedStats; import org.elasticsearch.xpack.sql.expression.function.aggregate.First; import org.elasticsearch.xpack.sql.expression.function.aggregate.Last; @@ -32,33 +56,12 @@ import org.elasticsearch.xpack.sql.expression.function.aggregate.Stats; import org.elasticsearch.xpack.sql.expression.function.aggregate.Sum; import org.elasticsearch.xpack.sql.expression.function.aggregate.TopHits; -import org.elasticsearch.xpack.sql.expression.function.scalar.ScalarFunction; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTimeFunction; -import org.elasticsearch.xpack.sql.expression.function.scalar.geo.GeoShape; import org.elasticsearch.xpack.sql.expression.function.scalar.geo.StDistance; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.expression.predicate.Range; -import org.elasticsearch.xpack.sql.expression.predicate.fulltext.MatchQueryPredicate; -import org.elasticsearch.xpack.sql.expression.predicate.fulltext.MultiMatchQueryPredicate; -import org.elasticsearch.xpack.sql.expression.predicate.fulltext.StringQueryPredicate; -import org.elasticsearch.xpack.sql.expression.predicate.logical.And; -import org.elasticsearch.xpack.sql.expression.predicate.logical.Not; -import org.elasticsearch.xpack.sql.expression.predicate.logical.Or; +import org.elasticsearch.xpack.sql.expression.literal.geo.GeoShape; import org.elasticsearch.xpack.sql.expression.predicate.nulls.IsNotNull; import org.elasticsearch.xpack.sql.expression.predicate.nulls.IsNull; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.BinaryComparison; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.Equals; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.GreaterThan; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.GreaterThanOrEqual; import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.In; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.LessThan; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.LessThanOrEqual; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.NotEquals; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.NullEquals; -import org.elasticsearch.xpack.sql.expression.predicate.regex.Like; -import org.elasticsearch.xpack.sql.expression.predicate.regex.LikePattern; -import org.elasticsearch.xpack.sql.expression.predicate.regex.RLike; -import org.elasticsearch.xpack.sql.expression.predicate.regex.RegexMatch; import org.elasticsearch.xpack.sql.querydsl.agg.AggFilter; import org.elasticsearch.xpack.sql.querydsl.agg.AndAggFilter; import org.elasticsearch.xpack.sql.querydsl.agg.AvgAgg; @@ -91,10 +94,7 @@ import org.elasticsearch.xpack.sql.querydsl.query.TermQuery; import org.elasticsearch.xpack.sql.querydsl.query.TermsQuery; import org.elasticsearch.xpack.sql.querydsl.query.WildcardQuery; -import org.elasticsearch.xpack.sql.tree.Source; import org.elasticsearch.xpack.sql.util.Check; -import org.elasticsearch.xpack.sql.util.Holder; -import org.elasticsearch.xpack.sql.util.ReflectionUtils; import java.time.OffsetTime; import java.time.ZonedDateTime; @@ -104,7 +104,7 @@ import java.util.function.Supplier; import static java.util.Collections.singletonList; -import static org.elasticsearch.xpack.sql.expression.Expressions.id; +import static org.elasticsearch.xpack.ql.expression.Expressions.id; import static org.elasticsearch.xpack.sql.expression.Foldables.doubleValuesOf; import static org.elasticsearch.xpack.sql.expression.Foldables.valueOf; @@ -373,10 +373,10 @@ protected QueryTranslation asQuery(MultiMatchQueryPredicate q, boolean onAggs) { } } - static class BinaryLogic extends ExpressionTranslator { + static class BinaryLogic extends ExpressionTranslator { @Override - protected QueryTranslation asQuery(org.elasticsearch.xpack.sql.expression.predicate.logical.BinaryLogic e, boolean onAggs) { + protected QueryTranslation asQuery(org.elasticsearch.xpack.ql.expression.predicate.logical.BinaryLogic e, boolean onAggs) { if (e instanceof And) { return and(e.source(), toQuery(e.left(), onAggs), toQuery(e.right(), onAggs)); } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/Verifier.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/Verifier.java index fe4ec05ab33a8..6b9683d439db1 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/Verifier.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/Verifier.java @@ -5,12 +5,12 @@ */ package org.elasticsearch.xpack.sql.planner; -import org.elasticsearch.xpack.sql.expression.function.aggregate.InnerAggregate; +import org.elasticsearch.xpack.ql.expression.function.aggregate.InnerAggregate; +import org.elasticsearch.xpack.ql.tree.Node; import org.elasticsearch.xpack.sql.plan.physical.PhysicalPlan; import org.elasticsearch.xpack.sql.plan.physical.PivotExec; import org.elasticsearch.xpack.sql.plan.physical.Unexecutable; import org.elasticsearch.xpack.sql.plan.physical.UnplannedExec; -import org.elasticsearch.xpack.sql.tree.Node; import java.util.ArrayList; import java.util.List; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plugin/SqlPlugin.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plugin/SqlPlugin.java index 4866acfde347c..fc184eff29a41 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plugin/SqlPlugin.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plugin/SqlPlugin.java @@ -32,12 +32,13 @@ import org.elasticsearch.xpack.core.XPackField; import org.elasticsearch.xpack.core.XPackPlugin; import org.elasticsearch.xpack.core.XPackSettings; +import org.elasticsearch.xpack.ql.index.IndexResolver; import org.elasticsearch.xpack.sql.SqlFeatureSet; import org.elasticsearch.xpack.sql.action.SqlClearCursorAction; import org.elasticsearch.xpack.sql.action.SqlQueryAction; import org.elasticsearch.xpack.sql.action.SqlTranslateAction; -import org.elasticsearch.xpack.sql.analysis.index.IndexResolver; import org.elasticsearch.xpack.sql.execution.PlanExecutor; +import org.elasticsearch.xpack.sql.type.SqlDataTypeRegistry; import java.util.ArrayList; import java.util.Arrays; @@ -99,7 +100,7 @@ Collection createComponents(Client client, String clusterName, NamedWrit if (false == enabled) { return emptyList(); } - IndexResolver indexResolver = new IndexResolver(client, clusterName); + IndexResolver indexResolver = new IndexResolver(client, clusterName, SqlDataTypeRegistry.INSTANCE); return Arrays.asList(sqlLicenseChecker, indexResolver, new PlanExecutor(client, indexResolver, namedWriteableRegistry)); } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plugin/TextFormat.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plugin/TextFormat.java index 5a415703bb785..dd837e65315aa 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plugin/TextFormat.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plugin/TextFormat.java @@ -8,6 +8,7 @@ import org.elasticsearch.common.Strings; import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.rest.RestRequest; +import org.elasticsearch.xpack.ql.util.StringUtils; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; import org.elasticsearch.xpack.sql.action.BasicFormatter; import org.elasticsearch.xpack.sql.action.SqlQueryResponse; @@ -15,7 +16,6 @@ import org.elasticsearch.xpack.sql.session.Cursor; import org.elasticsearch.xpack.sql.session.Cursors; import org.elasticsearch.xpack.sql.util.DateUtils; -import org.elasticsearch.xpack.sql.util.StringUtils; import java.time.ZoneId; import java.time.ZonedDateTime; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plugin/TransportSqlClearCursorAction.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plugin/TransportSqlClearCursorAction.java index 6d3802c341f1d..55224edbc8a2a 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plugin/TransportSqlClearCursorAction.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plugin/TransportSqlClearCursorAction.java @@ -11,6 +11,7 @@ import org.elasticsearch.common.inject.Inject; import org.elasticsearch.tasks.Task; import org.elasticsearch.transport.TransportService; +import org.elasticsearch.xpack.ql.util.StringUtils; import org.elasticsearch.xpack.sql.action.SqlClearCursorRequest; import org.elasticsearch.xpack.sql.action.SqlClearCursorResponse; import org.elasticsearch.xpack.sql.execution.PlanExecutor; @@ -19,7 +20,6 @@ import org.elasticsearch.xpack.sql.session.Cursor; import org.elasticsearch.xpack.sql.session.Cursors; import org.elasticsearch.xpack.sql.util.DateUtils; -import org.elasticsearch.xpack.sql.util.StringUtils; import static org.elasticsearch.xpack.sql.action.SqlClearCursorAction.NAME; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plugin/TransportSqlQueryAction.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plugin/TransportSqlQueryAction.java index 97da20902a0d3..cc0e8088dc522 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plugin/TransportSqlQueryAction.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plugin/TransportSqlQueryAction.java @@ -17,6 +17,7 @@ import org.elasticsearch.transport.TransportService; import org.elasticsearch.xpack.core.XPackSettings; import org.elasticsearch.xpack.core.security.SecurityContext; +import org.elasticsearch.xpack.ql.type.Schema; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; import org.elasticsearch.xpack.sql.action.SqlQueryAction; import org.elasticsearch.xpack.sql.action.SqlQueryRequest; @@ -29,7 +30,7 @@ import org.elasticsearch.xpack.sql.session.Cursors; import org.elasticsearch.xpack.sql.session.RowSet; import org.elasticsearch.xpack.sql.session.SchemaRowSet; -import org.elasticsearch.xpack.sql.type.Schema; +import org.elasticsearch.xpack.sql.type.SqlDataTypes; import java.util.ArrayList; import java.util.List; @@ -95,9 +96,9 @@ static SqlQueryResponse createResponseWithSchema(SqlQueryRequest request, Page p List columns = new ArrayList<>(rowSet.columnCount()); for (Schema.Entry entry : rowSet.schema()) { if (Mode.isDriver(request.mode())) { - columns.add(new ColumnInfo("", entry.name(), entry.type().typeName, entry.type().displaySize)); + columns.add(new ColumnInfo("", entry.name(), entry.type().typeName(), SqlDataTypes.displaySize(entry.type()))); } else { - columns.add(new ColumnInfo("", entry.name(), entry.type().typeName)); + columns.add(new ColumnInfo("", entry.name(), entry.type().typeName())); } } columns = unmodifiableList(columns); diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plugin/TransportSqlTranslateAction.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plugin/TransportSqlTranslateAction.java index b37c25fcab933..57f8fdefd45d0 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plugin/TransportSqlTranslateAction.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plugin/TransportSqlTranslateAction.java @@ -55,7 +55,7 @@ protected void doExecute(Task task, SqlTranslateRequest request, ActionListener< Configuration cfg = new Configuration(request.zoneId(), request.fetchSize(), request.requestTimeout(), request.pageTimeout(), request.filter(), request.mode(), request.clientId(), - username(securityContext), clusterName(clusterService), Protocol.FIELD_MULTI_VALUE_LENIENCY, + username(securityContext), clusterName(clusterService), Protocol.FIELD_MULTI_VALUE_LENIENCY, Protocol.INDEX_INCLUDE_FROZEN); planExecutor.searchSource(cfg, request.query(), request.params(), ActionListener.wrap( diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/AggFilter.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/AggFilter.java index 1f972989e3782..ca69d52a39964 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/AggFilter.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/AggFilter.java @@ -7,8 +7,8 @@ import org.elasticsearch.script.Script; import org.elasticsearch.search.aggregations.PipelineAggregationBuilder; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.expression.gen.script.Scripts; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.expression.gen.script.Scripts; import org.elasticsearch.xpack.sql.util.Check; import java.util.Map; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/Aggs.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/Aggs.java index 94f854c29f0b8..eb85965007895 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/Aggs.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/Aggs.java @@ -9,10 +9,10 @@ import org.elasticsearch.search.aggregations.bucket.composite.CompositeAggregationBuilder; import org.elasticsearch.search.aggregations.bucket.composite.CompositeValuesSourceBuilder; import org.elasticsearch.search.aggregations.bucket.filter.FiltersAggregationBuilder; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.util.StringUtils; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; import org.elasticsearch.xpack.sql.querydsl.container.Sort.Direction; -import org.elasticsearch.xpack.sql.util.StringUtils; import java.util.ArrayList; import java.util.Collection; @@ -21,7 +21,7 @@ import static java.util.Collections.emptyList; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; -import static org.elasticsearch.xpack.sql.util.CollectionUtils.combine; +import static org.elasticsearch.xpack.ql.util.CollectionUtils.combine; /** * SQL Aggregations associated with a query. diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/AndAggFilter.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/AndAggFilter.java index 503c88ea7fc0c..cf822a127fbcc 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/AndAggFilter.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/AndAggFilter.java @@ -5,7 +5,7 @@ */ package org.elasticsearch.xpack.sql.querydsl.agg; -import org.elasticsearch.xpack.sql.expression.gen.script.Scripts; +import org.elasticsearch.xpack.ql.expression.gen.script.Scripts; public class AndAggFilter extends AggFilter { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/GroupByDateHistogram.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/GroupByDateHistogram.java index 807df41387aab..31e727706753f 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/GroupByDateHistogram.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/GroupByDateHistogram.java @@ -8,8 +8,8 @@ import org.elasticsearch.search.aggregations.bucket.composite.CompositeValuesSourceBuilder; import org.elasticsearch.search.aggregations.bucket.composite.DateHistogramValuesSourceBuilder; import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; import org.elasticsearch.xpack.sql.querydsl.container.Sort.Direction; import java.time.ZoneId; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/GroupByKey.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/GroupByKey.java index df207269eec0f..69f6eea3acc37 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/GroupByKey.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/GroupByKey.java @@ -7,12 +7,18 @@ import org.elasticsearch.search.aggregations.bucket.composite.CompositeValuesSourceBuilder; import org.elasticsearch.search.aggregations.support.ValueType; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.querydsl.container.Sort.Direction; -import org.elasticsearch.xpack.sql.type.DataType; import java.util.Objects; +import static org.elasticsearch.xpack.ql.type.DataTypes.BOOLEAN; +import static org.elasticsearch.xpack.ql.type.DataTypes.DATETIME; +import static org.elasticsearch.xpack.ql.type.DataTypes.IP; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.DATE; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.TIME; + /** * A key for a SQL GroupBy which maps to value source for composite aggregation. */ @@ -37,17 +43,17 @@ public final CompositeValuesSourceBuilder asValueSource() { builder.valueType(ValueType.LONG); } else if (script.outputType().isRational()) { builder.valueType(ValueType.DOUBLE); - } else if (script.outputType().isString()) { + } else if (DataTypes.isString(script.outputType())) { builder.valueType(ValueType.STRING); - } else if (script.outputType() == DataType.DATE) { + } else if (script.outputType() == DATE) { builder.valueType(ValueType.LONG); - } else if (script.outputType() == DataType.TIME) { + } else if (script.outputType() == TIME) { builder.valueType(ValueType.LONG); - } else if (script.outputType() == DataType.DATETIME) { + } else if (script.outputType() == DATETIME) { builder.valueType(ValueType.LONG); - } else if (script.outputType() == DataType.BOOLEAN) { + } else if (script.outputType() == BOOLEAN) { builder.valueType(ValueType.BOOLEAN); - } else if (script.outputType() == DataType.IP) { + } else if (script.outputType() == IP) { builder.valueType(ValueType.IP); } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/GroupByNumericHistogram.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/GroupByNumericHistogram.java index a03faede75f37..e8b9a262da5a4 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/GroupByNumericHistogram.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/GroupByNumericHistogram.java @@ -7,7 +7,7 @@ import org.elasticsearch.search.aggregations.bucket.composite.CompositeValuesSourceBuilder; import org.elasticsearch.search.aggregations.bucket.composite.HistogramValuesSourceBuilder; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; import org.elasticsearch.xpack.sql.querydsl.container.Sort.Direction; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/GroupByValue.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/GroupByValue.java index 12e09dbc52d24..7612fa1d2ccbb 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/GroupByValue.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/GroupByValue.java @@ -7,7 +7,7 @@ import org.elasticsearch.search.aggregations.bucket.composite.CompositeValuesSourceBuilder; import org.elasticsearch.search.aggregations.bucket.composite.TermsValuesSourceBuilder; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; import org.elasticsearch.xpack.sql.querydsl.container.Sort.Direction; /** diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/OrAggFilter.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/OrAggFilter.java index 4c5ab50b2627e..ebc0c086c0a2d 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/OrAggFilter.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/OrAggFilter.java @@ -5,7 +5,7 @@ */ package org.elasticsearch.xpack.sql.querydsl.agg; -import org.elasticsearch.xpack.sql.expression.gen.script.Scripts; +import org.elasticsearch.xpack.ql.expression.gen.script.Scripts; public class OrAggFilter extends AggFilter { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/TopHitsAgg.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/TopHitsAgg.java index 741d83aab5123..7131e5f8a0d17 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/TopHitsAgg.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/TopHitsAgg.java @@ -9,7 +9,8 @@ import org.elasticsearch.search.sort.FieldSortBuilder; import org.elasticsearch.search.sort.SortBuilder; import org.elasticsearch.search.sort.SortOrder; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.sql.type.SqlDataTypes; import java.util.ArrayList; import java.util.List; @@ -44,15 +45,15 @@ AggregationBuilder toBuilder() { new FieldSortBuilder(sortField) .order(sortOrder) .missing(LAST.position()) - .unmappedType(sortFieldDataType.esType)); + .unmappedType(sortFieldDataType.esType())); } sortBuilderList.add( new FieldSortBuilder(fieldName()) .order(sortOrder) .missing(LAST.position()) - .unmappedType(fieldDataType.esType)); + .unmappedType(fieldDataType.esType())); - return topHits(id()).docValueField(fieldName(), fieldDataType.format()).sorts(sortBuilderList).size(1); + return topHits(id()).docValueField(fieldName(), SqlDataTypes.format(fieldDataType)).sorts(sortBuilderList).size(1); } @Override diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/AggregateSort.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/AggregateSort.java index 966f5c5079664..50eb7efb4b1bc 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/AggregateSort.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/AggregateSort.java @@ -6,7 +6,7 @@ package org.elasticsearch.xpack.sql.querydsl.container; -import org.elasticsearch.xpack.sql.expression.function.aggregate.AggregateFunction; +import org.elasticsearch.xpack.ql.expression.function.aggregate.AggregateFunction; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/AttributeSort.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/AttributeSort.java index d1dd2d17a94e4..cb6a42745b580 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/AttributeSort.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/AttributeSort.java @@ -5,7 +5,7 @@ */ package org.elasticsearch.xpack.sql.querydsl.container; -import org.elasticsearch.xpack.sql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.Attribute; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/ComputedRef.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/ComputedRef.java index e1aa6032c0501..6b109d39799cf 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/ComputedRef.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/ComputedRef.java @@ -5,9 +5,9 @@ */ package org.elasticsearch.xpack.sql.querydsl.container; -import org.elasticsearch.xpack.sql.execution.search.FieldExtraction; -import org.elasticsearch.xpack.sql.execution.search.SqlSourceBuilder; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.execution.search.FieldExtraction; +import org.elasticsearch.xpack.ql.execution.search.QlSourceBuilder; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; public class ComputedRef implements FieldExtraction { @@ -27,7 +27,7 @@ public boolean supportedByAggsOnlyQuery() { } @Override - public void collectFields(SqlSourceBuilder sourceBuilder) { + public void collectFields(QlSourceBuilder sourceBuilder) { processor.collectFields(sourceBuilder); } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/FieldReference.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/FieldReference.java index 271fbfd57d2fa..18fd5776b5a11 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/FieldReference.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/FieldReference.java @@ -5,7 +5,7 @@ */ package org.elasticsearch.xpack.sql.querydsl.container; -import org.elasticsearch.xpack.sql.execution.search.FieldExtraction; +import org.elasticsearch.xpack.ql.execution.search.FieldExtraction; public abstract class FieldReference implements FieldExtraction { /** diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/GlobalCountRef.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/GlobalCountRef.java index 8c16f6dd545f2..ebd484ea60678 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/GlobalCountRef.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/GlobalCountRef.java @@ -5,7 +5,7 @@ */ package org.elasticsearch.xpack.sql.querydsl.container; -import org.elasticsearch.xpack.sql.execution.search.AggRef; +import org.elasticsearch.xpack.ql.execution.search.AggRef; /** * Aggregation reference pointing to the (so called) global count, meaning diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/GroupByRef.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/GroupByRef.java index 1dc8d1ae60ad6..8c07200086341 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/GroupByRef.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/GroupByRef.java @@ -5,7 +5,7 @@ */ package org.elasticsearch.xpack.sql.querydsl.container; -import org.elasticsearch.xpack.sql.execution.search.AggRef; +import org.elasticsearch.xpack.ql.execution.search.AggRef; /** * Reference to a GROUP BY agg (typically this gets translated to a composite key). diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/MetricAggRef.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/MetricAggRef.java index f1602df4c0e79..fa91428e47f88 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/MetricAggRef.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/MetricAggRef.java @@ -5,7 +5,7 @@ */ package org.elasticsearch.xpack.sql.querydsl.container; -import org.elasticsearch.xpack.sql.execution.search.AggRef; +import org.elasticsearch.xpack.ql.execution.search.AggRef; import org.elasticsearch.xpack.sql.querydsl.agg.Aggs; /** diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/PivotColumnRef.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/PivotColumnRef.java index 60ee3b7409c09..5ab78c09cbdec 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/PivotColumnRef.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/PivotColumnRef.java @@ -6,8 +6,8 @@ package org.elasticsearch.xpack.sql.querydsl.container; -import org.elasticsearch.xpack.sql.execution.search.AggRef; -import org.elasticsearch.xpack.sql.execution.search.FieldExtraction; +import org.elasticsearch.xpack.ql.execution.search.AggRef; +import org.elasticsearch.xpack.ql.execution.search.FieldExtraction; public class PivotColumnRef extends AggRef { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/QueryContainer.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/QueryContainer.java index 2e388f94af3e5..0279dd49180e9 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/QueryContainer.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/QueryContainer.java @@ -11,19 +11,21 @@ import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.json.JsonXContent; +import org.elasticsearch.xpack.ql.execution.search.FieldExtraction; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.AttributeMap; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.expression.function.aggregate.AggregateFunction; +import org.elasticsearch.xpack.ql.expression.function.scalar.ScalarFunction; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.ConstantInput; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.execution.search.FieldExtraction; import org.elasticsearch.xpack.sql.execution.search.SourceGenerator; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.expression.AttributeMap; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; import org.elasticsearch.xpack.sql.expression.function.Score; -import org.elasticsearch.xpack.sql.expression.function.aggregate.AggregateFunction; -import org.elasticsearch.xpack.sql.expression.function.scalar.ScalarFunction; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.ConstantInput; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; import org.elasticsearch.xpack.sql.expression.gen.pipeline.ScorePipe; import org.elasticsearch.xpack.sql.querydsl.agg.Aggs; import org.elasticsearch.xpack.sql.querydsl.agg.GroupByKey; @@ -32,8 +34,7 @@ import org.elasticsearch.xpack.sql.querydsl.query.MatchAll; import org.elasticsearch.xpack.sql.querydsl.query.NestedQuery; import org.elasticsearch.xpack.sql.querydsl.query.Query; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.sql.type.SqlDataTypes; import java.io.IOException; import java.util.AbstractMap; @@ -52,7 +53,7 @@ import static java.util.Collections.emptyMap; import static java.util.Collections.emptySet; import static java.util.Collections.singletonMap; -import static org.elasticsearch.xpack.sql.util.CollectionUtils.combine; +import static org.elasticsearch.xpack.ql.util.CollectionUtils.combine; /** * Container for various references of the built ES query. @@ -348,9 +349,9 @@ private FieldExtraction topHitFieldRef(FieldAttribute fieldAttr) { */ if (fieldAttr.field().isAlias() == false) { while (actualField.parent() != null - && actualField.parent().field().getDataType() != DataType.OBJECT - && actualField.parent().field().getDataType() != DataType.NESTED - && actualField.field().getDataType().isFromDocValuesOnly() == false) { + && actualField.parent().field().getDataType() != DataTypes.OBJECT + && actualField.parent().field().getDataType() != DataTypes.NESTED + && SqlDataTypes.isFromDocValuesOnly(actualField.field().getDataType()) == false) { actualField = actualField.parent(); } } @@ -365,7 +366,9 @@ private FieldExtraction topHitFieldRef(FieldAttribute fieldAttr) { private Tuple nestedHitFieldRef(FieldAttribute attr) { String name = aliasName(attr); Query q = rewriteToContainNestedField(query, attr.source(), - attr.nestedParent().name(), name, attr.field().getDataType().format(), attr.field().getDataType().isFromDocValuesOnly()); + attr.nestedParent().name(), name, + SqlDataTypes.format(attr.field().getDataType()), + SqlDataTypes.isFromDocValuesOnly(attr.field().getDataType())); SearchHitFieldRef nestedFieldRef = new SearchHitFieldRef(name, null, attr.field().getDataType(), attr.field().isAggregatable(), false, attr.parent().name()); diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/ScriptFieldRef.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/ScriptFieldRef.java index c89b986a4f2bf..6b763690ef5f4 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/ScriptFieldRef.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/ScriptFieldRef.java @@ -5,8 +5,8 @@ */ package org.elasticsearch.xpack.sql.querydsl.container; -import org.elasticsearch.xpack.sql.execution.search.SqlSourceBuilder; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.execution.search.QlSourceBuilder; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; public class ScriptFieldRef extends FieldReference { @@ -28,7 +28,7 @@ public ScriptTemplate script() { } @Override - public void collectFields(SqlSourceBuilder sourceBuilder) { + public void collectFields(QlSourceBuilder sourceBuilder) { sourceBuilder.addScriptField(name, script.toPainless()); } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/ScriptSort.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/ScriptSort.java index 604bb3b8a0c61..284b60f1c1478 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/ScriptSort.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/ScriptSort.java @@ -5,8 +5,8 @@ */ package org.elasticsearch.xpack.sql.querydsl.container; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.expression.gen.script.Scripts; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.expression.gen.script.Scripts; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/SearchHitFieldRef.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/SearchHitFieldRef.java index 6ecf189d99a54..3c28c9129220a 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/SearchHitFieldRef.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/SearchHitFieldRef.java @@ -5,8 +5,9 @@ */ package org.elasticsearch.xpack.sql.querydsl.container; -import org.elasticsearch.xpack.sql.execution.search.SqlSourceBuilder; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.execution.search.QlSourceBuilder; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.sql.type.SqlDataTypes; public class SearchHitFieldRef extends FieldReference { private final String name; @@ -26,7 +27,8 @@ public SearchHitFieldRef(String name, String fullFieldName, DataType dataType, b this.dataType = dataType; // these field types can only be extracted from docvalue_fields (ie, values already computed by Elasticsearch) // because, for us to be able to extract them from _source, we would need the mapping of those fields (which we don't have) - this.docValue = isAlias ? useDocValueInsteadOfSource : (dataType.isFromDocValuesOnly() ? useDocValueInsteadOfSource : false); + this.docValue = isAlias ? useDocValueInsteadOfSource : + (SqlDataTypes.isFromDocValuesOnly(dataType) ? useDocValueInsteadOfSource : false); this.hitName = hitName; } @@ -52,13 +54,13 @@ public boolean useDocValue() { } @Override - public void collectFields(SqlSourceBuilder sourceBuilder) { + public void collectFields(QlSourceBuilder sourceBuilder) { // nested fields are handled by inner hits if (hitName != null) { return; } if (docValue) { - sourceBuilder.addDocField(name, dataType.format()); + sourceBuilder.addDocField(name, SqlDataTypes.format(dataType)); } else { sourceBuilder.addSourceField(name); } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/Sort.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/Sort.java index 33a9865b64f3c..c37677cb74f97 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/Sort.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/Sort.java @@ -6,8 +6,8 @@ package org.elasticsearch.xpack.sql.querydsl.container; import org.elasticsearch.search.sort.SortOrder; -import org.elasticsearch.xpack.sql.expression.Order.NullsPosition; -import org.elasticsearch.xpack.sql.expression.Order.OrderDirection; +import org.elasticsearch.xpack.ql.expression.Order.NullsPosition; +import org.elasticsearch.xpack.ql.expression.Order.OrderDirection; public abstract class Sort { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/TopHitsAggRef.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/TopHitsAggRef.java index 740c655c5069b..4d1e105c70011 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/TopHitsAggRef.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/container/TopHitsAggRef.java @@ -5,8 +5,8 @@ */ package org.elasticsearch.xpack.sql.querydsl.container; -import org.elasticsearch.xpack.sql.execution.search.AggRef; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.execution.search.AggRef; +import org.elasticsearch.xpack.ql.type.DataType; /** * Reference to a TopHits aggregation. @@ -33,6 +33,6 @@ public DataType fieldDataType() { @Override public String toString() { - return ">" + name + "[" + fieldDataType.typeName + "]"; + return ">" + name + "[" + fieldDataType.typeName() + "]"; } } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/BoolQuery.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/BoolQuery.java index 2b7033309cf85..446a7d12737f0 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/BoolQuery.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/BoolQuery.java @@ -8,7 +8,7 @@ import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.search.sort.NestedSortBuilder; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/ExistsQuery.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/ExistsQuery.java index 07aad6d260af3..e639e1cfe3a82 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/ExistsQuery.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/ExistsQuery.java @@ -6,7 +6,7 @@ package org.elasticsearch.xpack.sql.querydsl.query; import org.elasticsearch.index.query.QueryBuilder; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.tree.Source; import static org.elasticsearch.index.query.QueryBuilders.existsQuery; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/GeoDistanceQuery.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/GeoDistanceQuery.java index dd1a1171c1603..351bde8d9f182 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/GeoDistanceQuery.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/GeoDistanceQuery.java @@ -8,7 +8,7 @@ import org.elasticsearch.common.unit.DistanceUnit; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/LeafQuery.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/LeafQuery.java index f1252d90fa42e..c96d53c909c64 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/LeafQuery.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/LeafQuery.java @@ -6,7 +6,7 @@ package org.elasticsearch.xpack.sql.querydsl.query; import org.elasticsearch.search.sort.NestedSortBuilder; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.tree.Source; abstract class LeafQuery extends Query { LeafQuery(Source source) { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/MatchAll.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/MatchAll.java index 260bb34b27a89..82d5a12d23547 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/MatchAll.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/MatchAll.java @@ -6,7 +6,7 @@ package org.elasticsearch.xpack.sql.querydsl.query; import org.elasticsearch.index.query.QueryBuilder; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.tree.Source; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/MatchQuery.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/MatchQuery.java index 7bddacb86bf74..af454353af41e 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/MatchQuery.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/MatchQuery.java @@ -11,8 +11,8 @@ import org.elasticsearch.index.query.Operator; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; -import org.elasticsearch.xpack.sql.expression.predicate.fulltext.MatchQueryPredicate; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.predicate.fulltext.MatchQueryPredicate; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Collections; import java.util.HashMap; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/MultiMatchQuery.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/MultiMatchQuery.java index 2c6b47d7bdcc3..3ad9ae867a61f 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/MultiMatchQuery.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/MultiMatchQuery.java @@ -11,8 +11,8 @@ import org.elasticsearch.index.query.Operator; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; -import org.elasticsearch.xpack.sql.expression.predicate.fulltext.MultiMatchQueryPredicate; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.predicate.fulltext.MultiMatchQueryPredicate; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Collections; import java.util.HashMap; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/NestedQuery.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/NestedQuery.java index 59703da23abc4..91aa7211cdd93 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/NestedQuery.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/NestedQuery.java @@ -12,7 +12,7 @@ import org.elasticsearch.search.fetch.StoredFieldsContext; import org.elasticsearch.search.fetch.subphase.FetchSourceContext; import org.elasticsearch.search.sort.NestedSortBuilder; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.AbstractMap; import java.util.ArrayList; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/NotQuery.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/NotQuery.java index 3115ab26a07f8..19e978f6e89b1 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/NotQuery.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/NotQuery.java @@ -7,7 +7,7 @@ import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.search.sort.NestedSortBuilder; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/Query.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/Query.java index de7ff8e0f648c..6d35823b20bcb 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/Query.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/Query.java @@ -7,7 +7,7 @@ import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.search.sort.NestedSortBuilder; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.tree.Source; /** * Intermediate representation of queries that is rewritten to fetch diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/QueryStringQuery.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/QueryStringQuery.java index a6d8ff2dbf5fc..f13c506afdc17 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/QueryStringQuery.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/QueryStringQuery.java @@ -13,8 +13,8 @@ import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.QueryStringQueryBuilder; -import org.elasticsearch.xpack.sql.expression.predicate.fulltext.StringQueryPredicate; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.predicate.fulltext.StringQueryPredicate; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Collections; import java.util.HashMap; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/RangeQuery.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/RangeQuery.java index 3b7bc21bb0079..e64993c3202a5 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/RangeQuery.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/RangeQuery.java @@ -5,12 +5,12 @@ */ package org.elasticsearch.xpack.sql.querydsl.query; -import java.util.Objects; - import org.elasticsearch.common.Strings; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.RangeQueryBuilder; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.tree.Source; + +import java.util.Objects; import static org.elasticsearch.index.query.QueryBuilders.rangeQuery; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/RegexQuery.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/RegexQuery.java index c8459791eb404..eaa166aa3a10c 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/RegexQuery.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/RegexQuery.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.querydsl.query; -import java.util.Objects; - import org.elasticsearch.index.query.QueryBuilder; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.tree.Source; + +import java.util.Objects; import static org.elasticsearch.index.query.QueryBuilders.regexpQuery; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/ScriptQuery.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/ScriptQuery.java index 396ea283951e0..af1919efab391 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/ScriptQuery.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/ScriptQuery.java @@ -6,9 +6,9 @@ package org.elasticsearch.xpack.sql.querydsl.query; import org.elasticsearch.index.query.QueryBuilder; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; -import org.elasticsearch.xpack.sql.expression.gen.script.Scripts; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.expression.gen.script.Scripts; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.Objects; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/TermQuery.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/TermQuery.java index 5d488338b8642..2c10ae8d666a2 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/TermQuery.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/TermQuery.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.querydsl.query; -import java.util.Objects; - import org.elasticsearch.index.query.QueryBuilder; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.tree.Source; + +import java.util.Objects; import static org.elasticsearch.index.query.QueryBuilders.termQuery; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/TermsQuery.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/TermsQuery.java index 9b7f59c011ed5..6b12c83b4acb0 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/TermsQuery.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/TermsQuery.java @@ -6,9 +6,10 @@ package org.elasticsearch.xpack.sql.querydsl.query; import org.elasticsearch.index.query.QueryBuilder; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.expression.Foldables; -import org.elasticsearch.xpack.sql.tree.Source; import java.util.Collections; import java.util.LinkedHashSet; @@ -26,7 +27,7 @@ public class TermsQuery extends LeafQuery { public TermsQuery(Source source, String term, List values) { super(source); this.term = term; - values.removeIf(e -> e.dataType().isNull()); + values.removeIf(e -> DataTypes.isNull(e.dataType())); if (values.isEmpty()) { this.values = Collections.emptySet(); } else { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/WildcardQuery.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/WildcardQuery.java index 11b776e90fbef..337d3339614b6 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/WildcardQuery.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/query/WildcardQuery.java @@ -5,10 +5,10 @@ */ package org.elasticsearch.xpack.sql.querydsl.query; -import java.util.Objects; - import org.elasticsearch.index.query.QueryBuilder; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.tree.Source; + +import java.util.Objects; import static org.elasticsearch.index.query.QueryBuilders.wildcardQuery; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/Configuration.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/Configuration.java index 5b9901ccae447..39f1606624643 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/Configuration.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/Configuration.java @@ -11,20 +11,16 @@ import org.elasticsearch.xpack.sql.proto.Mode; import java.time.ZoneId; -import java.time.ZonedDateTime; // Typed object holding properties for a given query -public class Configuration { - private final ZoneId zoneId; +public class Configuration extends org.elasticsearch.xpack.ql.session.Configuration { + private final int pageSize; private final TimeValue requestTimeout; private final TimeValue pageTimeout; private final Mode mode; private final String clientId; - private final String username; - private final String clusterName; private final boolean multiValueFieldLeniency; - private final ZonedDateTime now; private final boolean includeFrozenIndices; @Nullable @@ -35,24 +31,19 @@ public Configuration(ZoneId zi, int pageSize, TimeValue requestTimeout, TimeValu String username, String clusterName, boolean multiValueFieldLeniency, boolean includeFrozen) { - this.zoneId = zi.normalized(); + + super(zi, username, clusterName); + this.pageSize = pageSize; this.requestTimeout = requestTimeout; this.pageTimeout = pageTimeout; this.filter = filter; this.mode = mode == null ? Mode.PLAIN : mode; this.clientId = clientId; - this.username = username; - this.clusterName = clusterName; this.multiValueFieldLeniency = multiValueFieldLeniency; - this.now = ZonedDateTime.now(zoneId); this.includeFrozenIndices = includeFrozen; } - public ZoneId zoneId() { - return zoneId; - } - public int pageSize() { return pageSize; } @@ -76,18 +67,6 @@ public String clientId() { return clientId; } - public String username() { - return username; - } - - public String clusterName() { - return clusterName; - } - - public ZonedDateTime now() { - return now; - } - public boolean multiValueFieldLeniency() { return multiValueFieldLeniency; } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/Cursors.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/Cursors.java index 6f1ee47f4da34..a5a3ad82dd178 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/Cursors.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/Cursors.java @@ -9,18 +9,18 @@ import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.io.stream.NamedWriteable; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; +import org.elasticsearch.xpack.ql.util.StringUtils; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; import org.elasticsearch.xpack.sql.common.io.SqlStreamInput; import org.elasticsearch.xpack.sql.common.io.SqlStreamOutput; import org.elasticsearch.xpack.sql.execution.search.CompositeAggCursor; import org.elasticsearch.xpack.sql.execution.search.PivotCursor; import org.elasticsearch.xpack.sql.execution.search.ScrollCursor; -import org.elasticsearch.xpack.sql.execution.search.extractor.BucketExtractors; -import org.elasticsearch.xpack.sql.execution.search.extractor.HitExtractors; +import org.elasticsearch.xpack.sql.execution.search.extractor.SqlBucketExtractors; +import org.elasticsearch.xpack.sql.execution.search.extractor.SqlHitExtractors; import org.elasticsearch.xpack.sql.expression.function.scalar.Processors; import org.elasticsearch.xpack.sql.expression.literal.Literals; import org.elasticsearch.xpack.sql.plugin.TextFormatterCursor; -import org.elasticsearch.xpack.sql.util.StringUtils; import java.io.IOException; import java.time.ZoneId; @@ -53,8 +53,8 @@ public static List getNamedWriteables() { // plus all their dependencies entries.addAll(Processors.getNamedWriteables()); - entries.addAll(HitExtractors.getNamedWriteables()); - entries.addAll(BucketExtractors.getNamedWriteables()); + entries.addAll(SqlHitExtractors.getNamedWriteables()); + entries.addAll(SqlBucketExtractors.getNamedWriteables()); // and custom types entries.addAll(Literals.getNamedWriteables()); diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/EmptyExecutable.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/EmptyExecutable.java index 93a7e51c39b74..b8da81fc8d873 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/EmptyExecutable.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/EmptyExecutable.java @@ -6,13 +6,13 @@ package org.elasticsearch.xpack.sql.session; import org.elasticsearch.action.ActionListener; -import org.elasticsearch.xpack.sql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.Attribute; import org.elasticsearch.xpack.sql.session.Cursor.Page; import java.util.List; import java.util.Objects; -public class EmptyExecutable implements Executable { +public class EmptyExecutable implements SqlExecutable { private final List output; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/EmptyRowSet.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/EmptyRowSet.java index 9b6fa2aa3a06a..2ef8e25660b9e 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/EmptyRowSet.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/EmptyRowSet.java @@ -5,7 +5,7 @@ */ package org.elasticsearch.xpack.sql.session; -import org.elasticsearch.xpack.sql.type.Schema; +import org.elasticsearch.xpack.ql.type.Schema; class EmptyRowSet extends AbstractRowSet implements SchemaRowSet { private final Schema schema; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/Executable.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/Executable.java index d1d78194ebe62..2654d06750415 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/Executable.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/Executable.java @@ -3,10 +3,11 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ + package org.elasticsearch.xpack.sql.session; import org.elasticsearch.action.ActionListener; -import org.elasticsearch.xpack.sql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.Attribute; import org.elasticsearch.xpack.sql.session.Cursor.Page; import java.util.List; @@ -15,5 +16,5 @@ public interface Executable { List output(); - void execute(SqlSession session, ActionListener listener); + void execute(Session session, ActionListener listener); } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/ListCursor.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/ListCursor.java index a07b7adfe37d5..927eeff8fa1d3 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/ListCursor.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/ListCursor.java @@ -11,7 +11,7 @@ import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; -import org.elasticsearch.xpack.sql.type.Schema; +import org.elasticsearch.xpack.ql.type.Schema; import java.io.IOException; import java.util.List; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/ListRowSet.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/ListRowSet.java index 6bbbbaa462d05..520e9b23423f3 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/ListRowSet.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/ListRowSet.java @@ -5,7 +5,7 @@ */ package org.elasticsearch.xpack.sql.session; -import org.elasticsearch.xpack.sql.type.Schema; +import org.elasticsearch.xpack.ql.type.Schema; import java.util.List; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/Rows.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/Rows.java index dac192318a209..19f56ba4a35d0 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/Rows.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/Rows.java @@ -5,9 +5,9 @@ */ package org.elasticsearch.xpack.sql.session; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.Schema; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.Schema; import org.elasticsearch.xpack.sql.util.Check; import java.util.ArrayList; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/SchemaRowSet.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/SchemaRowSet.java index fb12c6e6529b5..218e6d406997f 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/SchemaRowSet.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/SchemaRowSet.java @@ -5,7 +5,7 @@ */ package org.elasticsearch.xpack.sql.session; -import org.elasticsearch.xpack.sql.type.Schema; +import org.elasticsearch.xpack.ql.type.Schema; /** * A {@linkplain RowSet} with the {@link Schema} for the results diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/Session.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/Session.java new file mode 100644 index 0000000000000..2e80a20ea0047 --- /dev/null +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/Session.java @@ -0,0 +1,11 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.sql.session; + +public interface Session { + +} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/SingletonExecutable.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/SingletonExecutable.java index d86ac5fe00814..0f7531983f93b 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/SingletonExecutable.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/SingletonExecutable.java @@ -6,7 +6,7 @@ package org.elasticsearch.xpack.sql.session; import org.elasticsearch.action.ActionListener; -import org.elasticsearch.xpack.sql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.Attribute; import org.elasticsearch.xpack.sql.session.Cursor.Page; import org.elasticsearch.xpack.sql.util.Check; @@ -35,7 +35,7 @@ public List output() { } @Override - public void execute(SqlSession session, ActionListener listener) { + public void execute(Session session, ActionListener listener) { listener.onResponse(Page.last(Rows.singleton(output, values))); } diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/SingletonRowSet.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/SingletonRowSet.java index 649caafc9be2b..ebc5986feb737 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/SingletonRowSet.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/SingletonRowSet.java @@ -5,7 +5,7 @@ */ package org.elasticsearch.xpack.sql.session; -import org.elasticsearch.xpack.sql.type.Schema; +import org.elasticsearch.xpack.ql.type.Schema; //TODO is it worth keeping this when we have ListRowSet? class SingletonRowSet extends AbstractRowSet implements SchemaRowSet { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/SqlExecutable.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/SqlExecutable.java new file mode 100644 index 0000000000000..f815580dc6bd7 --- /dev/null +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/SqlExecutable.java @@ -0,0 +1,19 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +package org.elasticsearch.xpack.sql.session; + +import org.elasticsearch.action.ActionListener; +import org.elasticsearch.xpack.sql.session.Cursor.Page; + +public interface SqlExecutable extends Executable { + + void execute(SqlSession session, ActionListener listener); + + @Override + default void execute(Session session, ActionListener listener) { + execute((SqlSession) session, listener); + } +} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/SqlSession.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/SqlSession.java index 023b443850c16..4d6a772615686 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/SqlSession.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/session/SqlSession.java @@ -8,24 +8,24 @@ import org.elasticsearch.action.ActionListener; import org.elasticsearch.client.Client; import org.elasticsearch.common.Strings; +import org.elasticsearch.xpack.ql.expression.function.FunctionRegistry; +import org.elasticsearch.xpack.ql.index.IndexResolution; +import org.elasticsearch.xpack.ql.index.IndexResolver; +import org.elasticsearch.xpack.ql.index.MappingException; +import org.elasticsearch.xpack.ql.plan.TableIdentifier; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.rule.RuleExecutor; import org.elasticsearch.xpack.sql.analysis.analyzer.Analyzer; import org.elasticsearch.xpack.sql.analysis.analyzer.PreAnalyzer; import org.elasticsearch.xpack.sql.analysis.analyzer.PreAnalyzer.PreAnalysis; import org.elasticsearch.xpack.sql.analysis.analyzer.TableInfo; import org.elasticsearch.xpack.sql.analysis.analyzer.Verifier; -import org.elasticsearch.xpack.sql.analysis.index.IndexResolution; -import org.elasticsearch.xpack.sql.analysis.index.IndexResolver; -import org.elasticsearch.xpack.sql.analysis.index.MappingException; import org.elasticsearch.xpack.sql.execution.PlanExecutor; -import org.elasticsearch.xpack.sql.expression.function.FunctionRegistry; import org.elasticsearch.xpack.sql.optimizer.Optimizer; import org.elasticsearch.xpack.sql.parser.SqlParser; -import org.elasticsearch.xpack.sql.plan.TableIdentifier; -import org.elasticsearch.xpack.sql.plan.logical.LogicalPlan; import org.elasticsearch.xpack.sql.plan.physical.PhysicalPlan; import org.elasticsearch.xpack.sql.planner.Planner; import org.elasticsearch.xpack.sql.proto.SqlTypedParamValue; -import org.elasticsearch.xpack.sql.rule.RuleExecutor; import org.elasticsearch.xpack.sql.session.Cursor.Page; import java.util.List; @@ -33,7 +33,7 @@ import static org.elasticsearch.action.ActionListener.wrap; -public class SqlSession { +public class SqlSession implements Session { private final Client client; diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/stats/QueryMetric.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/stats/QueryMetric.java index c461254558425..26cd1bdb4ee14 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/stats/QueryMetric.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/stats/QueryMetric.java @@ -10,6 +10,7 @@ import org.elasticsearch.xpack.sql.proto.RequestInfo; import java.util.Locale; + import static org.elasticsearch.xpack.sql.proto.RequestInfo.ODBC_CLIENT_IDS; public enum QueryMetric { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/DataType.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/DataType.java deleted file mode 100644 index 19fda28f76ffd..0000000000000 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/DataType.java +++ /dev/null @@ -1,345 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -package org.elasticsearch.xpack.sql.type; - -import org.elasticsearch.index.mapper.NumberFieldMapper.NumberType; -import org.elasticsearch.xpack.sql.util.DateUtils; - -import java.sql.JDBCType; -import java.sql.SQLType; -import java.sql.Types; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.Map.Entry; - -/** - * Elasticsearch SQL data types. - * This class also implements JDBC {@link SQLType} for properly receiving and setting values. - * Where possible, please use the built-in, JDBC {@link Types} and {@link JDBCType} to avoid coupling - * to the API. - */ -public enum DataType { - - // @formatter:off - // esType jdbc type, size, defPrecision,dispSize, int, rat, docvals - NULL( "null", JDBCType.NULL, 0, 0, 0, false, false, false), - UNSUPPORTED( JDBCType.OTHER, 0, 0, 0, false, false, false), - BOOLEAN( "boolean", JDBCType.BOOLEAN, 1, 1, 1, false, false, false), - BYTE( "byte", JDBCType.TINYINT, Byte.BYTES, 3, 5, true, false, true), - SHORT( "short", JDBCType.SMALLINT, Short.BYTES, 5, 6, true, false, true), - INTEGER( "integer", JDBCType.INTEGER, Integer.BYTES, 10, 11, true, false, true), - LONG( "long", JDBCType.BIGINT, Long.BYTES, 19, 20, true, false, true), - // 53 bits defaultPrecision ~ 15(15.95) decimal digits (53log10(2)), - DOUBLE( "double", JDBCType.DOUBLE, Double.BYTES, 15, 25, false, true, true), - // 24 bits defaultPrecision - 24*log10(2) =~ 7 (7.22) - FLOAT( "float", JDBCType.REAL, Float.BYTES, 7, 15, false, true, true), - HALF_FLOAT( "half_float", JDBCType.FLOAT, Float.BYTES, 3, 25, false, true, true), - // precision is based on long - SCALED_FLOAT( "scaled_float", JDBCType.DOUBLE, Long.BYTES, 15, 25, false, true, true), - KEYWORD( "keyword", JDBCType.VARCHAR, Integer.MAX_VALUE, 32766, 32766, false, false, true), - TEXT( "text", JDBCType.VARCHAR, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, false, false, false), - OBJECT( "object", JDBCType.STRUCT, -1, 0, 0, false, false, false), - NESTED( "nested", JDBCType.STRUCT, -1, 0, 0, false, false, false), - BINARY( "binary", JDBCType.VARBINARY, -1, Integer.MAX_VALUE, Integer.MAX_VALUE, false, false, false), - // since ODBC and JDBC interpret precision for Date as display size - // the precision is 23 (number of chars in ISO8601 with millis) + 6 chars for the timezone (e.g.: +05:00) - // see https://github.com/elastic/elasticsearch/issues/30386#issuecomment-386807288 - DATE( JDBCType.DATE, Long.BYTES, 3, 29, false, false, true), - TIME( JDBCType.TIME, Long.BYTES, 3, 18, false, false, true), - DATETIME( "date", JDBCType.TIMESTAMP, Long.BYTES, 3, 29, false, false, true), - // - // specialized types - // - GEO_SHAPE( ExtTypes.GEOMETRY, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, false, false, false), - // display size = 2 doubles + len("POINT( )") - GEO_POINT( ExtTypes.GEOMETRY, Double.BYTES*2, Integer.MAX_VALUE, 25 * 2 + 8, false, false, false), - // IP can be v4 or v6. The latter has 2^128 addresses or 340,282,366,920,938,463,463,374,607,431,768,211,456 - // aka 39 chars - SHAPE( ExtTypes.GEOMETRY, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, false, false, false), - // display size = 2 doubles + len("POINT( )") - IP( "ip", JDBCType.VARCHAR, 39, 39, 0, false, false, true), - // - // INTERVALS - // the list is long as there are a lot of variations and that's what clients (ODBC) expect - // esType:null jdbc type, size, prec,disp, int, rat, docvals - INTERVAL_YEAR( ExtTypes.INTERVAL_YEAR, Integer.BYTES, 7, 7, false, false, false), - INTERVAL_MONTH( ExtTypes.INTERVAL_MONTH, Integer.BYTES, 7, 7, false, false, false), - INTERVAL_DAY( ExtTypes.INTERVAL_DAY, Long.BYTES, 23, 23, false, false, false), - INTERVAL_HOUR( ExtTypes.INTERVAL_HOUR, Long.BYTES, 23, 23, false, false, false), - INTERVAL_MINUTE( ExtTypes.INTERVAL_MINUTE, Long.BYTES, 23, 23, false, false, false), - INTERVAL_SECOND( ExtTypes.INTERVAL_SECOND, Long.BYTES, 23, 23, false, false, false), - INTERVAL_YEAR_TO_MONTH( ExtTypes.INTERVAL_YEAR_TO_MONTH, Integer.BYTES, 7, 7, false, false, false), - INTERVAL_DAY_TO_HOUR( ExtTypes.INTERVAL_DAY_TO_HOUR, Long.BYTES, 23, 23, false, false, false), - INTERVAL_DAY_TO_MINUTE( ExtTypes.INTERVAL_DAY_TO_MINUTE, Long.BYTES, 23, 23, false, false, false), - INTERVAL_DAY_TO_SECOND( ExtTypes.INTERVAL_DAY_TO_SECOND, Long.BYTES, 23, 23, false, false, false), - INTERVAL_HOUR_TO_MINUTE( ExtTypes.INTERVAL_HOUR_TO_MINUTE, Long.BYTES, 23, 23, false, false, false), - INTERVAL_HOUR_TO_SECOND( ExtTypes.INTERVAL_HOUR_TO_SECOND, Long.BYTES, 23, 23, false, false, false), - INTERVAL_MINUTE_TO_SECOND(ExtTypes.INTERVAL_MINUTE_TO_SECOND,Long.BYTES, 23, 23, false, false, false); - // @formatter:on - - private static final Map ODBC_TO_ES = new HashMap<>(36); - static { - // Numeric - ODBC_TO_ES.put("SQL_BIT", BOOLEAN); - ODBC_TO_ES.put("SQL_TINYINT", BYTE); - ODBC_TO_ES.put("SQL_SMALLINT", SHORT); - ODBC_TO_ES.put("SQL_INTEGER", INTEGER); - ODBC_TO_ES.put("SQL_BIGINT", LONG); - ODBC_TO_ES.put("SQL_REAL", FLOAT); - ODBC_TO_ES.put("SQL_FLOAT", DOUBLE); - ODBC_TO_ES.put("SQL_DOUBLE", DOUBLE); - ODBC_TO_ES.put("SQL_DECIMAL", DOUBLE); - ODBC_TO_ES.put("SQL_NUMERIC", DOUBLE); - - // String - ODBC_TO_ES.put("SQL_GUID", KEYWORD); - ODBC_TO_ES.put("SQL_CHAR", KEYWORD); - ODBC_TO_ES.put("SQL_WCHAR", KEYWORD); - ODBC_TO_ES.put("SQL_VARCHAR", TEXT); - ODBC_TO_ES.put("SQL_WVARCHAR", TEXT); - ODBC_TO_ES.put("SQL_LONGVARCHAR", TEXT); - ODBC_TO_ES.put("SQL_WLONGVARCHAR", TEXT); - - // Binary - ODBC_TO_ES.put("SQL_BINARY", BINARY); - ODBC_TO_ES.put("SQL_VARBINARY", BINARY); - ODBC_TO_ES.put("SQL_LONGVARBINARY", BINARY); - - // Date - ODBC_TO_ES.put("SQL_DATE", DATE); - ODBC_TO_ES.put("SQL_TIME", TIME); - ODBC_TO_ES.put("SQL_TIMESTAMP", DATETIME); - - // Intervals - ODBC_TO_ES.put("SQL_INTERVAL_HOUR_TO_MINUTE", INTERVAL_HOUR_TO_MINUTE); - ODBC_TO_ES.put("SQL_INTERVAL_HOUR_TO_SECOND", INTERVAL_HOUR_TO_SECOND); - ODBC_TO_ES.put("SQL_INTERVAL_MINUTE_TO_SECOND", INTERVAL_MINUTE_TO_SECOND); - ODBC_TO_ES.put("SQL_INTERVAL_MONTH", INTERVAL_MONTH); - ODBC_TO_ES.put("SQL_INTERVAL_YEAR", INTERVAL_YEAR); - ODBC_TO_ES.put("SQL_INTERVAL_YEAR_TO_MONTH", INTERVAL_YEAR_TO_MONTH); - ODBC_TO_ES.put("SQL_INTERVAL_DAY", INTERVAL_DAY); - ODBC_TO_ES.put("SQL_INTERVAL_HOUR", INTERVAL_HOUR); - ODBC_TO_ES.put("SQL_INTERVAL_MINUTE", INTERVAL_MINUTE); - ODBC_TO_ES.put("SQL_INTERVAL_SECOND", INTERVAL_SECOND); - ODBC_TO_ES.put("SQL_INTERVAL_DAY_TO_HOUR", INTERVAL_DAY_TO_HOUR); - ODBC_TO_ES.put("SQL_INTERVAL_DAY_TO_MINUTE", INTERVAL_DAY_TO_MINUTE); - ODBC_TO_ES.put("SQL_INTERVAL_DAY_TO_SECOND", INTERVAL_DAY_TO_SECOND); - } - - - private static final Map SQL_TO_ES = new HashMap<>(45); - static { - // first add ES types - for (DataType type : DataType.values()) { - if (type.isPrimitive()) { - SQL_TO_ES.put(type.name(), type); - } - } - - // reuse the ODBC definition (without SQL_) - // note that this will override existing types in particular FLOAT - for (Entry entry : ODBC_TO_ES.entrySet()) { - SQL_TO_ES.put(entry.getKey().substring(4), entry.getValue()); - } - - // special ones - SQL_TO_ES.put("BOOL", DataType.BOOLEAN); - SQL_TO_ES.put("INT", DataType.INTEGER); - SQL_TO_ES.put("STRING", DataType.KEYWORD); - } - - /** - * Type's name used for error messages and column info for the clients - */ - public final String typeName; - - /** - * Elasticsearch data type that it maps to - */ - public final String esType; - - /** - * Compatible JDBC type - */ - public final SQLType sqlType; - - /** - * Size of the type in bytes - *

    - * -1 if the size can vary - */ - public final int size; - - /** - * Precision - *

    - * Specified column size. For numeric data, this is the maximum precision. For character - * data, this is the length in characters. For datetime datatypes, this is the length in characters of the - * String representation (assuming the maximum allowed defaultPrecision of the fractional milliseconds component). - */ - public final int defaultPrecision; - - /** - * Display Size - *

    - * Normal maximum width in characters. - */ - public final int displaySize; - - /** - * True if the type represents an integer number - */ - private final boolean isInteger; - - /** - * True if the type represents a rational number - */ - private final boolean isRational; - - /** - * True if the type supports doc values by default - */ - public final boolean defaultDocValues; - - DataType(SQLType sqlType, int size, int defaultPrecision, int displaySize, boolean isInteger, - boolean isRational, boolean defaultDocValues) { - this(null, sqlType, size, defaultPrecision, displaySize, isInteger, isRational, defaultDocValues); - } - - DataType(String esType, SQLType sqlType, int size, int defaultPrecision, int displaySize, boolean isInteger, - boolean isRational, boolean defaultDocValues) { - this.typeName = name().toLowerCase(Locale.ROOT); - this.esType = esType; - this.sqlType = sqlType; - this.size = size; - this.defaultPrecision = defaultPrecision; - this.displaySize = displaySize; - this.isInteger = isInteger; - this.isRational = isRational; - this.defaultDocValues = defaultDocValues; - } - - public String sqlName() { - return sqlType.getName(); - } - - public boolean isInteger() { - return isInteger; - } - - public boolean isRational() { - return isRational; - } - - public boolean isNumeric() { - return isInteger || isRational; - } - - /** - * Returns true if value is signed, false otherwise (including if the type is not numeric) - */ - public boolean isSigned() { - // For now all numeric values that es supports are signed - return isNumeric(); - } - - public boolean isNull() { - return this == NULL; - } - - public boolean isNullOrNumeric() { - return isNull() || isNumeric(); - } - - public boolean isNullOrInterval() { - return isNull() || isInterval(); - } - - public boolean isString() { - return this == KEYWORD || this == TEXT; - } - - public boolean isPrimitive() { - return this != OBJECT && this != NESTED && this != UNSUPPORTED; - } - - public boolean isGeo() { - return this == GEO_POINT || this == GEO_SHAPE || this == SHAPE; - } - - public boolean isDateBased() { - return this == DATE || this == DATETIME; - } - - public boolean isTimeBased() { - return this == TIME; - } - - public boolean isDateOrTimeBased() { - return isDateBased() || isTimeBased(); - } - - public boolean isInterval() { - int ordinal = this.ordinal(); - return ordinal >= INTERVAL_YEAR.ordinal() && ordinal <= INTERVAL_MINUTE_TO_SECOND.ordinal(); - } - - public boolean isYearMonthInterval() { - return this == INTERVAL_YEAR || this == INTERVAL_MONTH || this == INTERVAL_YEAR_TO_MONTH; - } - - public boolean isDayTimeInterval() { - int ordinal = this.ordinal(); - return (ordinal >= INTERVAL_DAY.ordinal() && ordinal <= INTERVAL_SECOND.ordinal()) - || (ordinal >= INTERVAL_DAY_TO_HOUR.ordinal() && ordinal <= INTERVAL_MINUTE_TO_SECOND.ordinal()); - } - - // data type extract-able from _source or from docvalue_fields - public boolean isFromDocValuesOnly() { - return this == KEYWORD // because of ignore_above. Extracting this from _source wouldn't make sense if it wasn't indexed at all. - || this == DATE // because of date formats - || this == DATETIME - || this == SCALED_FLOAT // because of scaling_factor - || this == GEO_POINT - || this == GEO_SHAPE - || this == SHAPE; - } - - public static DataType fromOdbcType(String odbcType) { - return ODBC_TO_ES.get(odbcType); - } - - public static DataType fromSqlOrEsType(String typeName) { - return SQL_TO_ES.get(typeName.toUpperCase(Locale.ROOT)); - } - - /** - * Creates returns DataType enum corresponding to the specified es type - */ - public static DataType fromTypeName(String esType) { - String uppercase = esType.toUpperCase(Locale.ROOT); - if (uppercase.equals("DATE")) { - return DataType.DATETIME; - } - try { - return DataType.valueOf(uppercase); - } catch (IllegalArgumentException ex) { - return DataType.UNSUPPORTED; - } - } - - public String format() { - return isDateOrTimeBased() ? DateUtils.DATE_PARSE_FORMAT : null; - } - - /** - * Returns the appropriate NumberType enum corresponding to this es type - */ - public NumberType numberType() { - return NumberType.valueOf(esType.toUpperCase(Locale.ROOT)); - } -} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/DataTypeConversion.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/DataTypeConversion.java deleted file mode 100644 index 8e3158c3e6a8a..0000000000000 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/DataTypeConversion.java +++ /dev/null @@ -1,702 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -package org.elasticsearch.xpack.sql.type; - -import org.elasticsearch.common.Booleans; -import org.elasticsearch.common.network.InetAddresses; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.util.DateUtils; - -import java.time.OffsetTime; -import java.time.ZonedDateTime; -import java.time.format.DateTimeParseException; -import java.util.Locale; -import java.util.function.DoubleFunction; -import java.util.function.Function; -import java.util.function.LongFunction; - -import static org.elasticsearch.xpack.sql.type.DataType.BOOLEAN; -import static org.elasticsearch.xpack.sql.type.DataType.DATE; -import static org.elasticsearch.xpack.sql.type.DataType.DATETIME; -import static org.elasticsearch.xpack.sql.type.DataType.LONG; -import static org.elasticsearch.xpack.sql.type.DataType.NULL; -import static org.elasticsearch.xpack.sql.type.DataType.TEXT; -import static org.elasticsearch.xpack.sql.type.DataType.TIME; - -/** - * Conversions from one Elasticsearch data type to another Elasticsearch data types. - *

    - * This class throws {@link SqlIllegalArgumentException} to differentiate between validation - * errors inside SQL as oppose to the rest of ES. - */ -public abstract class DataTypeConversion { - - /** - * Returns the type compatible with both left and right types - *

    - * If one of the types is null - returns another type - * If both types are numeric - returns type with the highest precision int < long < float < double - * If one of the types is string and another numeric - returns numeric - */ - public static DataType commonType(DataType left, DataType right) { - if (left == right) { - return left; - } - if (left.isNull()) { - return right; - } - if (right.isNull()) { - return left; - } - if (left.isString() && right.isString()) { - if (left == TEXT) { - return TEXT; - } - return right; - } - if (left.isNumeric() && right.isNumeric()) { - // if one is int - if (left.isInteger()) { - // promote the highest int - if (right.isInteger()) { - return left.size > right.size ? left : right; - } - // promote the rational - return right; - } - // try the other side - if (right.isInteger()) { - return left; - } - // promote the highest rational - return left.size > right.size ? left : right; - } - if (left.isString()) { - if (right.isNumeric()) { - return right; - } - } - if (right.isString()) { - if (left.isNumeric()) { - return left; - } - } - - // interval and dates - if (left == DATE) { - if (right.isInterval()) { - return left; - } - } - if (right == DATE) { - if (left.isInterval()) { - return right; - } - } - if (left == TIME) { - if (right == DATE) { - return DATETIME; - } - if (right.isInterval()) { - return left; - } - } - if (right == TIME) { - if (left == DATE) { - return DATETIME; - } - if (left.isInterval()) { - return right; - } - } - if (left == DATETIME) { - if (right == DATE || right == TIME) { - return left; - } - if (right.isInterval()) { - return left; - } - } - if (right == DATETIME) { - if (left == DATE || left == TIME) { - return right; - } - if (left.isInterval()) { - return right; - } - } - // Interval * integer is a valid operation - if (left.isInterval()) { - if (right.isInteger()) { - return left; - } - } - if (right.isInterval()) { - if (left.isInteger()) { - return right; - } - } - if (left.isInterval()) { - // intervals widening - if (right.isInterval()) { - // null returned for incompatible intervals - return DataTypes.compatibleInterval(left, right); - } - } - - // none found - return null; - } - - /** - * Returns true if the from type can be converted to the to type, false - otherwise - */ - public static boolean canConvert(DataType from, DataType to) { - // Special handling for nulls and if conversion is not requires - if (from == to || from == NULL) { - return true; - } - // only primitives are supported so far - return from.isPrimitive() && to.isPrimitive() && conversion(from, to) != null; - } - - /** - * Get the conversion from one type to another. - */ - public static Conversion conversionFor(DataType from, DataType to) { - // Special handling for nulls and if conversion is not requires - if (from == to) { - return Conversion.IDENTITY; - } - if (to == NULL || from == NULL) { - return Conversion.NULL; - } - if (from == NULL) { - return Conversion.NULL; - } - - Conversion conversion = conversion(from, to); - if (conversion == null) { - throw new SqlIllegalArgumentException("cannot convert from [" + from.typeName + "] to [" + to.typeName + "]"); - } - return conversion; - } - - private static Conversion conversion(DataType from, DataType to) { - switch (to) { - case KEYWORD: - case TEXT: - return conversionToString(from); - case IP: - return conversionToIp(from); - case LONG: - return conversionToLong(from); - case INTEGER: - return conversionToInt(from); - case SHORT: - return conversionToShort(from); - case BYTE: - return conversionToByte(from); - case FLOAT: - return conversionToFloat(from); - case DOUBLE: - return conversionToDouble(from); - case DATE: - return conversionToDate(from); - case TIME: - return conversionToTime(from); - case DATETIME: - return conversionToDateTime(from); - case BOOLEAN: - return conversionToBoolean(from); - default: - return null; - } - - } - - private static Conversion conversionToString(DataType from) { - if (from == DATE) { - return Conversion.DATE_TO_STRING; - } - if (from == TIME) { - return Conversion.TIME_TO_STRING; - } - if (from == DATETIME) { - return Conversion.DATETIME_TO_STRING; - } - return Conversion.OTHER_TO_STRING; - } - - private static Conversion conversionToIp(DataType from) { - if (from.isString()) { - return Conversion.STRING_TO_IP; - } - return null; - } - - private static Conversion conversionToLong(DataType from) { - if (from.isRational()) { - return Conversion.RATIONAL_TO_LONG; - } - if (from.isInteger()) { - return Conversion.INTEGER_TO_LONG; - } - if (from == BOOLEAN) { - return Conversion.BOOL_TO_LONG; - } - if (from.isString()) { - return Conversion.STRING_TO_LONG; - } - if (from == DATE) { - return Conversion.DATE_TO_LONG; - } - if (from == TIME) { - return Conversion.TIME_TO_LONG; - } - if (from == DATETIME) { - return Conversion.DATETIME_TO_LONG; - } - return null; - } - - private static Conversion conversionToInt(DataType from) { - if (from.isRational()) { - return Conversion.RATIONAL_TO_INT; - } - if (from.isInteger()) { - return Conversion.INTEGER_TO_INT; - } - if (from == BOOLEAN) { - return Conversion.BOOL_TO_INT; - } - if (from.isString()) { - return Conversion.STRING_TO_INT; - } - if (from == DATE) { - return Conversion.DATE_TO_INT; - } - if (from == TIME) { - return Conversion.TIME_TO_INT; - } - if (from == DATETIME) { - return Conversion.DATETIME_TO_INT; - } - return null; - } - - private static Conversion conversionToShort(DataType from) { - if (from.isRational()) { - return Conversion.RATIONAL_TO_SHORT; - } - if (from.isInteger()) { - return Conversion.INTEGER_TO_SHORT; - } - if (from == BOOLEAN) { - return Conversion.BOOL_TO_SHORT; - } - if (from.isString()) { - return Conversion.STRING_TO_SHORT; - } - if (from == DATE) { - return Conversion.DATE_TO_SHORT; - } - if (from == TIME) { - return Conversion.TIME_TO_SHORT; - } - if (from == DATETIME) { - return Conversion.DATETIME_TO_SHORT; - } - return null; - } - - private static Conversion conversionToByte(DataType from) { - if (from.isRational()) { - return Conversion.RATIONAL_TO_BYTE; - } - if (from.isInteger()) { - return Conversion.INTEGER_TO_BYTE; - } - if (from == BOOLEAN) { - return Conversion.BOOL_TO_BYTE; - } - if (from.isString()) { - return Conversion.STRING_TO_BYTE; - } - if (from == DATE) { - return Conversion.DATE_TO_BYTE; - } - if (from == TIME) { - return Conversion.TIME_TO_BYTE; - } - if (from == DATETIME) { - return Conversion.DATETIME_TO_BYTE; - } - return null; - } - - private static Conversion conversionToFloat(DataType from) { - if (from.isRational()) { - return Conversion.RATIONAL_TO_FLOAT; - } - if (from.isInteger()) { - return Conversion.INTEGER_TO_FLOAT; - } - if (from == BOOLEAN) { - return Conversion.BOOL_TO_FLOAT; - } - if (from.isString()) { - return Conversion.STRING_TO_FLOAT; - } - if (from == DATE) { - return Conversion.DATE_TO_FLOAT; - } - if (from == TIME) { - return Conversion.TIME_TO_FLOAT; - } - if (from == DATETIME) { - return Conversion.DATETIME_TO_FLOAT; - } - return null; - } - - private static Conversion conversionToDouble(DataType from) { - if (from.isRational()) { - return Conversion.RATIONAL_TO_DOUBLE; - } - if (from.isInteger()) { - return Conversion.INTEGER_TO_DOUBLE; - } - if (from == BOOLEAN) { - return Conversion.BOOL_TO_DOUBLE; - } - if (from.isString()) { - return Conversion.STRING_TO_DOUBLE; - } - if (from == DATE) { - return Conversion.DATE_TO_DOUBLE; - } - if (from == TIME) { - return Conversion.TIME_TO_DOUBLE; - } - if (from == DATETIME) { - return Conversion.DATETIME_TO_DOUBLE; - } - return null; - } - - private static Conversion conversionToDate(DataType from) { - if (from.isRational()) { - return Conversion.RATIONAL_TO_DATE; - } - if (from.isInteger()) { - return Conversion.INTEGER_TO_DATE; - } - if (from == BOOLEAN) { - return Conversion.BOOL_TO_DATE; // We emit an int here which is ok because of Java's casting rules - } - if (from.isString()) { - return Conversion.STRING_TO_DATE; - } - if (from == DATETIME) { - return Conversion.DATETIME_TO_DATE; - } - return null; - } - - private static Conversion conversionToTime(DataType from) { - if (from.isRational()) { - return Conversion.RATIONAL_TO_TIME; - } - if (from.isInteger()) { - return Conversion.INTEGER_TO_TIME; - } - if (from == BOOLEAN) { - return Conversion.BOOL_TO_TIME; // We emit an int here which is ok because of Java's casting rules - } - if (from.isString()) { - return Conversion.STRING_TO_TIME; - } - if (from == DATE) { - return Conversion.DATE_TO_TIME; - } - if (from == DATETIME) { - return Conversion.DATETIME_TO_TIME; - } - return null; - } - - private static Conversion conversionToDateTime(DataType from) { - if (from.isRational()) { - return Conversion.RATIONAL_TO_DATETIME; - } - if (from.isInteger()) { - return Conversion.INTEGER_TO_DATETIME; - } - if (from == BOOLEAN) { - return Conversion.BOOL_TO_DATETIME; // We emit an int here which is ok because of Java's casting rules - } - if (from.isString()) { - return Conversion.STRING_TO_DATETIME; - } - if (from == DATE) { - return Conversion.DATE_TO_DATETIME; - } - return null; - } - - private static Conversion conversionToBoolean(DataType from) { - if (from.isNumeric()) { - return Conversion.NUMERIC_TO_BOOLEAN; - } - if (from.isString()) { - return Conversion.STRING_TO_BOOLEAN; - } - if (from == DATE) { - return Conversion.DATE_TO_BOOLEAN; - } - if (from == TIME) { - return Conversion.TIME_TO_BOOLEAN; - } - if (from == DATETIME) { - return Conversion.DATETIME_TO_BOOLEAN; - } - return null; - } - - public static byte safeToByte(long x) { - if (x > Byte.MAX_VALUE || x < Byte.MIN_VALUE) { - throw new SqlIllegalArgumentException("[" + x + "] out of [byte] range"); - } - return (byte) x; - } - - public static short safeToShort(long x) { - if (x > Short.MAX_VALUE || x < Short.MIN_VALUE) { - throw new SqlIllegalArgumentException("[" + x + "] out of [short] range"); - } - return (short) x; - } - - public static int safeToInt(long x) { - if (x > Integer.MAX_VALUE || x < Integer.MIN_VALUE) { - throw new SqlIllegalArgumentException("[" + x + "] out of [integer] range"); - } - return (int) x; - } - - public static long safeToLong(double x) { - if (x > Long.MAX_VALUE || x < Long.MIN_VALUE) { - throw new SqlIllegalArgumentException("[" + x + "] out of [long] range"); - } - return Math.round(x); - } - - public static Number toInteger(double x, DataType dataType) { - long l = safeToLong(x); - - switch (dataType) { - case BYTE: - return safeToByte(l); - case SHORT: - return safeToShort(l); - case INTEGER: - return safeToInt(l); - default: - return l; - } - } - - public static boolean convertToBoolean(String val) { - String lowVal = val.toLowerCase(Locale.ROOT); - if (Booleans.isBoolean(lowVal) == false) { - throw new SqlIllegalArgumentException("cannot cast [" + val + "] to [boolean]"); - } - return Booleans.parseBoolean(lowVal); - } - - /** - * Converts arbitrary object to the desired data type. - *

    - * Throws SqlIllegalArgumentException if such conversion is not possible - */ - public static Object convert(Object value, DataType dataType) { - DataType detectedType = DataTypes.fromJava(value); - if (detectedType == dataType || value == null) { - return value; - } - return conversionFor(detectedType, dataType).convert(value); - } - - /** - * Reference to a data type conversion that can be serialized. Note that the position in the enum - * is important because it is used for serialization. - */ - public enum Conversion { - IDENTITY(Function.identity()), - NULL(value -> null), - - DATE_TO_STRING(o -> DateUtils.toDateString((ZonedDateTime) o)), - TIME_TO_STRING(o -> DateUtils.toTimeString((OffsetTime) o)), - DATETIME_TO_STRING(o -> DateUtils.toString((ZonedDateTime) o)), - OTHER_TO_STRING(String::valueOf), - - RATIONAL_TO_LONG(fromDouble(DataTypeConversion::safeToLong)), - INTEGER_TO_LONG(fromLong(value -> value)), - STRING_TO_LONG(fromString(Long::valueOf, "long")), - DATE_TO_LONG(fromDateTime(value -> value)), - TIME_TO_LONG(fromTime(value -> value)), - DATETIME_TO_LONG(fromDateTime(value -> value)), - - RATIONAL_TO_INT(fromDouble(value -> safeToInt(safeToLong(value)))), - INTEGER_TO_INT(fromLong(DataTypeConversion::safeToInt)), - BOOL_TO_INT(fromBool(value -> value ? 1 : 0)), - STRING_TO_INT(fromString(Integer::valueOf, "integer")), - DATE_TO_INT(fromDateTime(DataTypeConversion::safeToInt)), - TIME_TO_INT(fromTime(DataTypeConversion::safeToInt)), - DATETIME_TO_INT(fromDateTime(DataTypeConversion::safeToInt)), - - RATIONAL_TO_SHORT(fromDouble(value -> safeToShort(safeToLong(value)))), - INTEGER_TO_SHORT(fromLong(DataTypeConversion::safeToShort)), - BOOL_TO_SHORT(fromBool(value -> value ? (short) 1 : (short) 0)), - STRING_TO_SHORT(fromString(Short::valueOf, "short")), - DATE_TO_SHORT(fromDateTime(DataTypeConversion::safeToShort)), - TIME_TO_SHORT(fromTime(DataTypeConversion::safeToShort)), - DATETIME_TO_SHORT(fromDateTime(DataTypeConversion::safeToShort)), - - RATIONAL_TO_BYTE(fromDouble(value -> safeToByte(safeToLong(value)))), - INTEGER_TO_BYTE(fromLong(DataTypeConversion::safeToByte)), - BOOL_TO_BYTE(fromBool(value -> value ? (byte) 1 : (byte) 0)), - STRING_TO_BYTE(fromString(Byte::valueOf, "byte")), - DATE_TO_BYTE(fromDateTime(DataTypeConversion::safeToByte)), - TIME_TO_BYTE(fromTime(DataTypeConversion::safeToByte)), - DATETIME_TO_BYTE(fromDateTime(DataTypeConversion::safeToByte)), - - // TODO floating point conversions are lossy but conversions to integer conversions are not. Are we ok with that? - RATIONAL_TO_FLOAT(fromDouble(value -> (float) value)), - INTEGER_TO_FLOAT(fromLong(value -> (float) value)), - BOOL_TO_FLOAT(fromBool(value -> value ? 1f : 0f)), - STRING_TO_FLOAT(fromString(Float::valueOf, "float")), - DATE_TO_FLOAT(fromDateTime(value -> (float) value)), - TIME_TO_FLOAT(fromTime(value -> (float) value)), - DATETIME_TO_FLOAT(fromDateTime(value -> (float) value)), - - RATIONAL_TO_DOUBLE(fromDouble(Double::valueOf)), - INTEGER_TO_DOUBLE(fromLong(Double::valueOf)), - BOOL_TO_DOUBLE(fromBool(value -> value ? 1d : 0d)), - STRING_TO_DOUBLE(fromString(Double::valueOf, "double")), - DATE_TO_DOUBLE(fromDateTime(Double::valueOf)), - TIME_TO_DOUBLE(fromTime(Double::valueOf)), - DATETIME_TO_DOUBLE(fromDateTime(Double::valueOf)), - - RATIONAL_TO_DATE(toDate(RATIONAL_TO_LONG)), - INTEGER_TO_DATE(toDate(INTEGER_TO_LONG)), - BOOL_TO_DATE(toDate(BOOL_TO_INT)), - STRING_TO_DATE(fromString(DateUtils::asDateOnly, "date")), - DATETIME_TO_DATE(fromDatetimeToDate()), - - RATIONAL_TO_TIME(toTime(RATIONAL_TO_LONG)), - INTEGER_TO_TIME(toTime(INTEGER_TO_LONG)), - BOOL_TO_TIME(toTime(BOOL_TO_INT)), - STRING_TO_TIME(fromString(DateUtils::asTimeOnly, "time")), - DATE_TO_TIME(fromDatetimeToTime()), - DATETIME_TO_TIME(fromDatetimeToTime()), - - RATIONAL_TO_DATETIME(toDateTime(RATIONAL_TO_LONG)), - INTEGER_TO_DATETIME(toDateTime(INTEGER_TO_LONG)), - BOOL_TO_DATETIME(toDateTime(BOOL_TO_INT)), - STRING_TO_DATETIME(fromString(DateUtils::asDateTime, "datetime")), - DATE_TO_DATETIME(value -> value), - - NUMERIC_TO_BOOLEAN(fromLong(value -> value != 0)), - STRING_TO_BOOLEAN(fromString(DataTypeConversion::convertToBoolean, "boolean")), - DATE_TO_BOOLEAN(fromDateTime(value -> value != 0)), - TIME_TO_BOOLEAN(fromTime(value -> value != 0)), - DATETIME_TO_BOOLEAN(fromDateTime(value -> value != 0)), - - BOOL_TO_LONG(fromBool(value -> value ? 1L : 0L)), - - STRING_TO_IP(o -> { - if (!InetAddresses.isInetAddress(o.toString())) { - throw new SqlIllegalArgumentException( "[" + o + "] is not a valid IPv4 or IPv6 address"); - } - return o; - }); - - private final Function converter; - - Conversion(Function converter) { - this.converter = converter; - } - - private static Function fromDouble(DoubleFunction converter) { - return (Object l) -> converter.apply(((Number) l).doubleValue()); - } - - private static Function fromLong(LongFunction converter) { - return (Object l) -> converter.apply(((Number) l).longValue()); - } - - private static Function fromString(Function converter, String to) { - return (Object value) -> { - try { - return converter.apply(value.toString()); - } catch (NumberFormatException e) { - throw new SqlIllegalArgumentException(e, "cannot cast [{}] to [{}]", value, to); - } catch (DateTimeParseException | IllegalArgumentException e) { - throw new SqlIllegalArgumentException(e, "cannot cast [{}] to [{}]: {}", value, to, e.getMessage()); - } - }; - } - - private static Function fromBool(Function converter) { - return (Object l) -> converter.apply(((Boolean) l)); - } - - private static Function fromTime(Function converter) { - return l -> converter.apply(((OffsetTime) l).atDate(DateUtils.EPOCH).toInstant().toEpochMilli()); - } - - private static Function fromDateTime(Function converter) { - return l -> converter.apply(((ZonedDateTime) l).toInstant().toEpochMilli()); - } - - private static Function toDate(Conversion conversion) { - return l -> DateUtils.asDateOnly(((Number) conversion.convert(l)).longValue()); - } - - private static Function toTime(Conversion conversion) { - return l -> DateUtils.asTimeOnly(((Number) conversion.convert(l)).longValue()); - } - - private static Function toDateTime(Conversion conversion) { - return l -> DateUtils.asDateTime(((Number) conversion.convert(l)).longValue()); - } - - private static Function fromDatetimeToDate() { - return l -> DateUtils.asDateOnly((ZonedDateTime) l); - } - - private static Function fromDatetimeToTime() { - return l -> ((ZonedDateTime) l).toOffsetDateTime().toOffsetTime(); - } - - public Object convert(Object l) { - if (l == null) { - return null; - } - return converter.apply(l); - } - } - - public static DataType asInteger(DataType dataType) { - if (!dataType.isNumeric()) { - return dataType; - } - - return dataType.isInteger() ? dataType : LONG; - } -} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/DataTypes.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/DataTypes.java deleted file mode 100644 index 1faf19e1d0996..0000000000000 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/DataTypes.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -package org.elasticsearch.xpack.sql.type; - -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.function.scalar.geo.GeoShape; -import org.elasticsearch.xpack.sql.expression.literal.Interval; - -import java.time.OffsetTime; -import java.time.ZonedDateTime; - -import static org.elasticsearch.xpack.sql.type.DataType.BOOLEAN; -import static org.elasticsearch.xpack.sql.type.DataType.BYTE; -import static org.elasticsearch.xpack.sql.type.DataType.DATETIME; -import static org.elasticsearch.xpack.sql.type.DataType.DOUBLE; -import static org.elasticsearch.xpack.sql.type.DataType.FLOAT; -import static org.elasticsearch.xpack.sql.type.DataType.INTEGER; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_YEAR_TO_MONTH; -import static org.elasticsearch.xpack.sql.type.DataType.KEYWORD; -import static org.elasticsearch.xpack.sql.type.DataType.LONG; -import static org.elasticsearch.xpack.sql.type.DataType.NULL; -import static org.elasticsearch.xpack.sql.type.DataType.SHORT; -import static org.elasticsearch.xpack.sql.type.DataType.TIME; -import static org.elasticsearch.xpack.sql.type.DataType.UNSUPPORTED; -import static org.elasticsearch.xpack.sql.type.DataType.fromTypeName; - -public final class DataTypes { - - private DataTypes() {} - - public static boolean isUnsupported(DataType from) { - return from == UNSUPPORTED; - } - - public static DataType fromJava(Object value) { - if (value == null) { - return NULL; - } - if (value instanceof Integer) { - return INTEGER; - } - if (value instanceof Long) { - return LONG; - } - if (value instanceof Boolean) { - return BOOLEAN; - } - if (value instanceof Double) { - return DOUBLE; - } - if (value instanceof Float) { - return FLOAT; - } - if (value instanceof Byte) { - return BYTE; - } - if (value instanceof Short) { - return SHORT; - } - if (value instanceof OffsetTime) { - return TIME; - } - if (value instanceof ZonedDateTime) { - return DATETIME; - } - if (value instanceof String || value instanceof Character) { - return KEYWORD; - } - if (value instanceof Interval) { - return ((Interval) value).dataType(); - } - if (value instanceof GeoShape) { - return DataType.GEO_SHAPE; - } - throw new SqlIllegalArgumentException("No idea what's the DataType for {}", value.getClass()); - } - - // return the compatible interval between the two - it is assumed the types are intervals - // YEAR and MONTH -> YEAR_TO_MONTH - // DAY... SECOND -> DAY_TIME - // YEAR_MONTH and DAY_SECOND are NOT compatible - public static DataType compatibleInterval(DataType left, DataType right) { - if (left == right) { - return left; - } - if (left.isYearMonthInterval() && right.isYearMonthInterval()) { - // no need to look at YEAR/YEAR or MONTH/MONTH as these are equal and already handled - return INTERVAL_YEAR_TO_MONTH; - } - if (left.isDayTimeInterval() && right.isDayTimeInterval()) { - // to avoid specifying the combinations, extract the leading and trailing unit from the name - // D > H > S > M which is also the alphabetical order - String lName = left.name().substring(9); - String rName = right.name().substring(9); - - char leading = lName.charAt(0); - if (rName.charAt(0) < leading) { - leading = rName.charAt(0); - } - // look at the trailing unit - if (lName.length() > 6) { - int indexOf = lName.indexOf("_TO_"); - lName = lName.substring(indexOf + 4); - } - if (rName.length() > 6) { - int indexOf = rName.indexOf("_TO_"); - rName = rName.substring(indexOf + 4); - } - char trailing = lName.charAt(0); - if (rName.charAt(0) > trailing) { - trailing = rName.charAt(0); - } - - return fromTypeName("INTERVAL_" + intervalUnit(leading) + "_TO_" + intervalUnit(trailing)); - } - return null; - } - - private static String intervalUnit(char unitChar) { - switch (unitChar) { - case 'D': - return "DAY"; - case 'H': - return "HOUR"; - case 'M': - return "MINUTE"; - case 'S': - return "SECOND"; - default: - throw new SqlIllegalArgumentException("Unknown unit {}", unitChar); - } - } - - // - // Metadata methods, mainly for ODBC. - // As these are fairly obscure and limited in use, there is no point to promote them as a full type methods - // hence why they appear here as utility methods. - // - - // https://docs.microsoft.com/en-us/sql/relational-databases/native-client-odbc-date-time/metadata-catalog - // https://github.com/elastic/elasticsearch/issues/30386 - public static Integer metaSqlDataType(DataType t) { - if (t == DATETIME) { - // ODBC SQL_DATETME - return Integer.valueOf(9); - } - // this is safe since the vendor SQL types are short despite the return value - return t.sqlType.getVendorTypeNumber(); - } - - // https://github.com/elastic/elasticsearch/issues/30386 - // https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/sqlgettypeinfo-function - public static Integer metaSqlDateTimeSub(DataType t) { - if (t == DATETIME) { - // ODBC SQL_CODE_TIMESTAMP - return Integer.valueOf(3); - } - // ODBC null - return 0; - } - - public static Short metaSqlMinimumScale(DataType t) { - return metaSqlSameScale(t); - } - - public static Short metaSqlMaximumScale(DataType t) { - return metaSqlSameScale(t); - } - - // https://docs.microsoft.com/en-us/sql/odbc/reference/appendixes/decimal-digits - // https://github.com/elastic/elasticsearch/issues/40357 - // since the scale is fixed, minimum and maximum should return the same value - // hence why this method exists - private static Short metaSqlSameScale(DataType t) { - // TODO: return info for SCALED_FLOATS (should be based on field not type) - if (t.isInteger()) { - return Short.valueOf((short) 0); - } - if (t.isDateBased() || t.isRational()) { - return Short.valueOf((short) t.defaultPrecision); - } - return null; - } - - // https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/sqlgettypeinfo-function - public static Integer metaSqlRadix(DataType t) { - // RADIX - Determines how numbers returned by COLUMN_SIZE and DECIMAL_DIGITS should be interpreted. - // 10 means they represent the number of decimal digits allowed for the column. - // 2 means they represent the number of bits allowed for the column. - // null means radix is not applicable for the given type. - return t.isInteger() ? Integer.valueOf(10) : (t.isRational() ? Integer.valueOf(2) : null); - } - - //https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/sqlgettypeinfo-function#comments - //https://docs.microsoft.com/en-us/sql/odbc/reference/appendixes/column-size - public static Integer precision(DataType t) { - if (t.isNumeric()) { - return t.defaultPrecision; - } - return t.displaySize; - } - - public static boolean areTypesCompatible(DataType left, DataType right) { - if (left == right) { - return true; - } else { - return - (left == DataType.NULL || right == DataType.NULL) - || (left.isString() && right.isString()) - || (left.isNumeric() && right.isNumeric()) - || (left.isDateBased() && right.isDateBased()) - || (left.isInterval() && right.isInterval() && compatibleInterval(left, right) != null); - } - } -} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/SqlDataTypeConverter.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/SqlDataTypeConverter.java new file mode 100644 index 0000000000000..e958ce1aa830d --- /dev/null +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/SqlDataTypeConverter.java @@ -0,0 +1,453 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.sql.type; + +import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.common.io.stream.StreamOutput; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.type.Converter; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypeConverter; +import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; +import org.elasticsearch.xpack.sql.expression.literal.interval.Intervals; +import org.elasticsearch.xpack.sql.util.DateUtils; + +import java.io.IOException; +import java.time.OffsetTime; +import java.time.ZonedDateTime; +import java.time.format.DateTimeParseException; +import java.util.function.Function; + +import static org.elasticsearch.xpack.ql.type.DataTypeConverter.DefaultConverter.BOOL_TO_INT; +import static org.elasticsearch.xpack.ql.type.DataTypeConverter.DefaultConverter.DATETIME_TO_BOOLEAN; +import static org.elasticsearch.xpack.ql.type.DataTypeConverter.DefaultConverter.DATETIME_TO_BYTE; +import static org.elasticsearch.xpack.ql.type.DataTypeConverter.DefaultConverter.DATETIME_TO_DOUBLE; +import static org.elasticsearch.xpack.ql.type.DataTypeConverter.DefaultConverter.DATETIME_TO_FLOAT; +import static org.elasticsearch.xpack.ql.type.DataTypeConverter.DefaultConverter.DATETIME_TO_INT; +import static org.elasticsearch.xpack.ql.type.DataTypeConverter.DefaultConverter.DATETIME_TO_LONG; +import static org.elasticsearch.xpack.ql.type.DataTypeConverter.DefaultConverter.DATETIME_TO_SHORT; +import static org.elasticsearch.xpack.ql.type.DataTypeConverter.DefaultConverter.IDENTITY; +import static org.elasticsearch.xpack.ql.type.DataTypeConverter.DefaultConverter.INTEGER_TO_LONG; +import static org.elasticsearch.xpack.ql.type.DataTypeConverter.DefaultConverter.RATIONAL_TO_LONG; +import static org.elasticsearch.xpack.ql.type.DataTypeConverter.DefaultConverter.TO_NULL; +import static org.elasticsearch.xpack.ql.type.DataTypes.BOOLEAN; +import static org.elasticsearch.xpack.ql.type.DataTypes.BYTE; +import static org.elasticsearch.xpack.ql.type.DataTypes.DATETIME; +import static org.elasticsearch.xpack.ql.type.DataTypes.DOUBLE; +import static org.elasticsearch.xpack.ql.type.DataTypes.FLOAT; +import static org.elasticsearch.xpack.ql.type.DataTypes.INTEGER; +import static org.elasticsearch.xpack.ql.type.DataTypes.KEYWORD; +import static org.elasticsearch.xpack.ql.type.DataTypes.LONG; +import static org.elasticsearch.xpack.ql.type.DataTypes.NULL; +import static org.elasticsearch.xpack.ql.type.DataTypes.SHORT; +import static org.elasticsearch.xpack.ql.type.DataTypes.TEXT; +import static org.elasticsearch.xpack.ql.type.DataTypes.isPrimitive; +import static org.elasticsearch.xpack.ql.type.DataTypes.isString; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.DATE; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.TIME; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.isInterval; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.isYearMonthInterval; + + +public final class SqlDataTypeConverter { + + private SqlDataTypeConverter() {} + + public static DataType commonType(DataType left, DataType right) { + DataType common = DataTypeConverter.commonType(left, right); + + if (common != null) { + return common; + } + + // interval and dates + if (left == DATE) { + if (isYearMonthInterval(right)) { + return left; + } + // promote + return DATETIME; + } + if (right == DATE) { + if (isYearMonthInterval(left)) { + return right; + } + // promote + return DATETIME; + } + if (left == TIME) { + if (right == DATE) { + return DATETIME; + } + if (isInterval(right)) { + return left; + } + } + if (right == TIME) { + if (left == DATE) { + return DATETIME; + } + if (isInterval(left)) { + return right; + } + } + if (left == DATETIME) { + if (right == DATE || right == TIME) { + return left; + } + if (isInterval(right)) { + return left; + } + } + if (right == DATETIME) { + if (left == DATE || left == TIME) { + return right; + } + if (isInterval(left)) { + return right; + } + } + // Interval * integer is a valid operation + if (isInterval(left)) { + if (right.isInteger()) { + return left; + } + } + if (isInterval(right)) { + if (left.isInteger()) { + return right; + } + } + if (isInterval(left)) { + // intervals widening + if (isInterval(right)) { + // null returned for incompatible intervals + return Intervals.compatibleInterval(left, right); + } + } + + return null; + } + + public static boolean canConvert(DataType from, DataType to) { + // Special handling for nulls and if conversion is not requires + if (from == to || from == NULL) { + return true; + } + // only primitives are supported so far + return isPrimitive(from) && isPrimitive(to) && converterFor(from, to) != null; + } + + public static Converter converterFor(DataType from, DataType to) { + // Special handling for nulls and if conversion is not requires + if (from == to) { + return IDENTITY; + } + if (to == NULL || from == NULL) { + return TO_NULL; + } + // proper converters + if (to == DATE) { + return conversionToDate(from); + } + if (to == TIME) { + return conversionToTime(from); + } + // extend the default converter with DATE and TIME + if (from == DATE || from == TIME) { + if (to == KEYWORD || to == TEXT) { + return conversionToString(from); + } + if (to == LONG) { + return conversionToLong(from); + } + if (to == INTEGER) { + return conversionToInt(from); + } + if (to == SHORT) { + return conversionToShort(from); + } + if (to == BYTE) { + return conversionToByte(from); + } + if (to == FLOAT) { + return conversionToFloat(from); + } + if (to == DOUBLE) { + return conversionToDouble(from); + } + if (to == DATETIME) { + return conversionToDateTime(from); + } + if (to == BOOLEAN) { + return conversionToBoolean(from); + } + } + // fallback to default + return DataTypeConverter.converterFor(from, to); + } + + private static Converter conversionToString(DataType from) { + if (from == DATE) { + return SqlConverter.DATE_TO_STRING; + } + if (from == TIME) { + return SqlConverter.TIME_TO_STRING; + } + return null; + } + + private static Converter conversionToLong(DataType from) { + if (from == DATE) { + return SqlConverter.DATE_TO_LONG; + } + if (from == TIME) { + return SqlConverter.TIME_TO_LONG; + } + return null; + } + + private static Converter conversionToInt(DataType from) { + if (from == DATE) { + return SqlConverter.DATE_TO_INT; + } + if (from == TIME) { + return SqlConverter.TIME_TO_INT; + } + return null; + } + + private static Converter conversionToShort(DataType from) { + if (from == DATE) { + return SqlConverter.DATE_TO_SHORT; + } + if (from == TIME) { + return SqlConverter.TIME_TO_SHORT; + } + return null; + } + + private static Converter conversionToByte(DataType from) { + if (from == DATE) { + return SqlConverter.DATE_TO_BYTE; + } + if (from == TIME) { + return SqlConverter.TIME_TO_BYTE; + } + return null; + } + + private static Converter conversionToFloat(DataType from) { + if (from == DATE) { + return SqlConverter.DATE_TO_FLOAT; + } + if (from == TIME) { + return SqlConverter.TIME_TO_FLOAT; + } + return null; + } + + private static Converter conversionToDouble(DataType from) { + if (from == DATE) { + return SqlConverter.DATE_TO_DOUBLE; + } + if (from == TIME) { + return SqlConverter.TIME_TO_DOUBLE; + } + return null; + } + + private static Converter conversionToDateTime(DataType from) { + if (from == DATE) { + return SqlConverter.DATE_TO_DATETIME; + } + + return DataTypeConverter.converterFor(from, DATETIME); + } + + private static Converter conversionToBoolean(DataType from) { + if (from == DATE) { + return SqlConverter.DATE_TO_BOOLEAN; + } + if (from == TIME) { + return SqlConverter.TIME_TO_BOOLEAN; + } + return null; + } + + private static Converter conversionToDate(DataType from) { + if (from.isRational()) { + return SqlConverter.RATIONAL_TO_DATE; + } + if (from.isInteger()) { + return SqlConverter.INTEGER_TO_DATE; + } + if (from == BOOLEAN) { + return SqlConverter.BOOL_TO_DATE; // We emit an int here which is ok because of Java's casting rules + } + if (isString(from)) { + return SqlConverter.STRING_TO_DATE; + } + if (from == DATETIME) { + return SqlConverter.DATETIME_TO_DATE; + } + return null; + } + + private static Converter conversionToTime(DataType from) { + if (from.isRational()) { + return SqlConverter.RATIONAL_TO_TIME; + } + if (from.isInteger()) { + return SqlConverter.INTEGER_TO_TIME; + } + if (from == BOOLEAN) { + return SqlConverter.BOOL_TO_TIME; // We emit an int here which is ok because of Java's casting rules + } + if (isString(from)) { + return SqlConverter.STRING_TO_TIME; + } + if (from == DATE) { + return SqlConverter.DATE_TO_TIME; + } + if (from == DATETIME) { + return SqlConverter.DATETIME_TO_TIME; + } + return null; + } + + public static Object convert(Object value, DataType dataType) { + DataType detectedType = SqlDataTypes.fromJava(value); + + if (detectedType == null) { + throw new SqlIllegalArgumentException("cannot detect datatype for [{}]", value); + } + + if (detectedType == dataType || value == null) { + return value; + } + + Converter converter = converterFor(detectedType, dataType); + + if (converter == null) { + throw new SqlIllegalArgumentException("cannot convert from [{}] to [{}]", value, dataType.typeName()); + } + + return converter.convert(value); + } + + /** + * Reference to a data type conversion that can be serialized. Note that the position in the enum + * is important because it is used for serialization. + */ + public enum SqlConverter implements Converter { + DATE_TO_STRING(o -> DateUtils.toDateString((ZonedDateTime) o)), + TIME_TO_STRING(o -> DateUtils.toTimeString((OffsetTime) o)), + + DATE_TO_LONG(delegate(DATETIME_TO_LONG)), + TIME_TO_LONG(fromTime(value -> value)), + + DATE_TO_INT(delegate(DATETIME_TO_INT)), + TIME_TO_INT(fromTime(DataTypeConverter::safeToInt)), + + DATE_TO_SHORT(delegate(DATETIME_TO_SHORT)), + TIME_TO_SHORT(fromTime(DataTypeConverter::safeToShort)), + + DATE_TO_BYTE(delegate(DATETIME_TO_BYTE)), + TIME_TO_BYTE(fromTime(DataTypeConverter::safeToByte)), + + DATE_TO_FLOAT(delegate(DATETIME_TO_FLOAT)), + TIME_TO_FLOAT(fromTime(value -> (float) value)), + + DATE_TO_DOUBLE(delegate(DATETIME_TO_DOUBLE)), + TIME_TO_DOUBLE(fromTime(Double::valueOf)), + + RATIONAL_TO_DATE(toDate(RATIONAL_TO_LONG)), + INTEGER_TO_DATE(toDate(INTEGER_TO_LONG)), + BOOL_TO_DATE(toDate(BOOL_TO_INT)), + STRING_TO_DATE(fromString(DateUtils::asDateOnly, "date")), + DATETIME_TO_DATE(fromDatetimeToDate()), + + RATIONAL_TO_TIME(toTime(RATIONAL_TO_LONG)), + INTEGER_TO_TIME(toTime(INTEGER_TO_LONG)), + BOOL_TO_TIME(toTime(BOOL_TO_INT)), + STRING_TO_TIME(fromString(DateUtils::asTimeOnly, "time")), + DATE_TO_TIME(fromDatetimeToTime()), + DATETIME_TO_TIME(fromDatetimeToTime()), + + DATE_TO_DATETIME(value -> value), + + DATE_TO_BOOLEAN(delegate(DATETIME_TO_BOOLEAN)), + TIME_TO_BOOLEAN(fromTime(value -> value != 0)); + + public static final String NAME = "dtc-sql"; + + private final Function converter; + + SqlConverter(Function converter) { + this.converter = converter; + } + + private static Function fromTime(Function converter) { + return l -> converter.apply(((OffsetTime) l).atDate(DateUtils.EPOCH).toInstant().toEpochMilli()); + } + + private static Function toDate(Converter conversion) { + return l -> DateUtils.asDateOnly(((Number) conversion.convert(l)).longValue()); + } + + private static Function toTime(Converter conversion) { + return l -> DateUtils.asTimeOnly(((Number) conversion.convert(l)).longValue()); + } + + private static Function fromDatetimeToDate() { + return l -> DateUtils.asDateOnly((ZonedDateTime) l); + } + + private static Function fromDatetimeToTime() { + return l -> ((ZonedDateTime) l).toOffsetDateTime().toOffsetTime(); + } + + private static Function delegate(Converter converter) { + return converter::convert; + } + + private static Function fromString(Function converter, String to) { + return (Object value) -> { + try { + return converter.apply(value.toString()); + } catch (NumberFormatException e) { + throw new QlIllegalArgumentException(e, "cannot cast [{}] to [{}]", value, to); + } catch (DateTimeParseException | IllegalArgumentException e) { + throw new QlIllegalArgumentException(e, "cannot cast [{}] to [{}]: {}", value, to, e.getMessage()); + } + }; + } + + @Override + public Object convert(Object l) { + if (l == null) { + return null; + } + return converter.apply(l); + } + + @Override + public String getWriteableName() { + return NAME; + } + + @Override + public void writeTo(StreamOutput out) throws IOException { + out.writeEnum(this); + } + + public static Converter read(StreamInput in) throws IOException { + return in.readEnum(SqlConverter.class); + } + } +} \ No newline at end of file diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/SqlDataTypeRegistry.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/SqlDataTypeRegistry.java new file mode 100644 index 0000000000000..12554a547bb9b --- /dev/null +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/SqlDataTypeRegistry.java @@ -0,0 +1,56 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.sql.type; + +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypeRegistry; +import org.elasticsearch.xpack.ql.type.DataTypes; + +import java.util.Collection; + +public class SqlDataTypeRegistry implements DataTypeRegistry { + + public static final DataTypeRegistry INSTANCE = new SqlDataTypeRegistry(); + + private SqlDataTypeRegistry() {} + + @Override + public Collection dataTypes() { + return SqlDataTypes.types(); + } + + @Override + public DataType fromEs(String typeName) { + return SqlDataTypes.fromEs(typeName); + } + + @Override + public DataType fromJava(Object value) { + return SqlDataTypes.fromJava(value); + } + + @Override + public boolean isUnsupported(DataType type) { + return DataTypes.isUnsupported(type); + } + + @Override + public boolean canConvert(DataType from, DataType to) { + return SqlDataTypeConverter.canConvert(from, to); + } + + @Override + public Object convert(Object value, DataType type) { + return SqlDataTypeConverter.convert(value, type); + } + + @Override + public DataType commonType(DataType left, DataType right) { + return SqlDataTypeConverter.commonType(left, right); + } + +} diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/SqlDataTypes.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/SqlDataTypes.java new file mode 100644 index 0000000000000..4e51b19e3d8f1 --- /dev/null +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/type/SqlDataTypes.java @@ -0,0 +1,727 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.sql.type; + +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; +import org.elasticsearch.xpack.sql.expression.literal.geo.GeoShape; +import org.elasticsearch.xpack.sql.expression.literal.interval.Interval; +import org.elasticsearch.xpack.sql.expression.literal.interval.Intervals; + +import java.sql.JDBCType; +import java.sql.SQLType; +import java.time.OffsetTime; +import java.util.Arrays; +import java.util.Collection; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.Map.Entry; +import java.util.stream.Stream; + +import static java.util.Collections.unmodifiableList; +import static java.util.Collections.unmodifiableMap; +import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toMap; +import static org.elasticsearch.xpack.ql.type.DataTypes.BINARY; +import static org.elasticsearch.xpack.ql.type.DataTypes.BOOLEAN; +import static org.elasticsearch.xpack.ql.type.DataTypes.BYTE; +import static org.elasticsearch.xpack.ql.type.DataTypes.DATETIME; +import static org.elasticsearch.xpack.ql.type.DataTypes.DOUBLE; +import static org.elasticsearch.xpack.ql.type.DataTypes.FLOAT; +import static org.elasticsearch.xpack.ql.type.DataTypes.HALF_FLOAT; +import static org.elasticsearch.xpack.ql.type.DataTypes.INTEGER; +import static org.elasticsearch.xpack.ql.type.DataTypes.IP; +import static org.elasticsearch.xpack.ql.type.DataTypes.KEYWORD; +import static org.elasticsearch.xpack.ql.type.DataTypes.LONG; +import static org.elasticsearch.xpack.ql.type.DataTypes.NESTED; +import static org.elasticsearch.xpack.ql.type.DataTypes.NULL; +import static org.elasticsearch.xpack.ql.type.DataTypes.OBJECT; +import static org.elasticsearch.xpack.ql.type.DataTypes.SCALED_FLOAT; +import static org.elasticsearch.xpack.ql.type.DataTypes.SHORT; +import static org.elasticsearch.xpack.ql.type.DataTypes.TEXT; +import static org.elasticsearch.xpack.ql.type.DataTypes.UNSUPPORTED; +import static org.elasticsearch.xpack.ql.util.CollectionUtils.mapSize; + +public class SqlDataTypes { + + // @formatter:off + // date-only, time-only + public static final DataType DATE = new DataType("DATE", null, Long.BYTES, false, false, true); + public static final DataType TIME = new DataType("TIME", null, Long.BYTES, false, false, true); + // interval + public static final DataType INTERVAL_YEAR = + new DataType("INTERVAL_YEAR", null, Integer.BYTES, false, false, false); + public static final DataType INTERVAL_MONTH = + new DataType("INTERVAL_MONTH", null, Integer.BYTES, false, false, false); + public static final DataType INTERVAL_DAY = + new DataType("INTERVAL_DAY", null, Long.BYTES, false, false, false); + public static final DataType INTERVAL_HOUR = + new DataType("INTERVAL_HOUR", null, Long.BYTES, false, false, false); + public static final DataType INTERVAL_MINUTE = + new DataType("INTERVAL_MINUTE", null, Long.BYTES, false, false, false); + public static final DataType INTERVAL_SECOND = + new DataType("INTERVAL_SECOND", null, Long.BYTES, false, false, false); + public static final DataType INTERVAL_YEAR_TO_MONTH = + new DataType("INTERVAL_YEAR_TO_MONTH", null, Integer.BYTES, false, false, false); + public static final DataType INTERVAL_DAY_TO_HOUR = + new DataType("INTERVAL_DAY_TO_HOUR", null, Long.BYTES, false, false, false); + public static final DataType INTERVAL_DAY_TO_MINUTE = + new DataType("INTERVAL_DAY_TO_MINUTE", null, Long.BYTES, false, false, false); + public static final DataType INTERVAL_DAY_TO_SECOND = + new DataType("INTERVAL_DAY_TO_SECOND", null, Long.BYTES, false, false, false); + public static final DataType INTERVAL_HOUR_TO_MINUTE = + new DataType("INTERVAL_HOUR_TO_MINUTE", null, Long.BYTES, false, false, false); + public static final DataType INTERVAL_HOUR_TO_SECOND = + new DataType("INTERVAL_HOUR_TO_SECOND", null, Long.BYTES, false, false, false); + public static final DataType INTERVAL_MINUTE_TO_SECOND = + new DataType("INTERVAL_MINUTE_TO_SECOND", null, Long.BYTES, false, false, false); + // geo + public static final DataType GEO_SHAPE = new DataType("geo_shape", Integer.MAX_VALUE, false, false, false); + public static final DataType GEO_POINT = new DataType("geo_point", Double.BYTES * 2, false, false, false); + public static final DataType SHAPE = new DataType("shape", Integer.MAX_VALUE, false, false, false); + // @formatter:on + + private static final Map ODBC_TO_ES = new HashMap<>(mapSize(38)); + + static { + // Numeric + ODBC_TO_ES.put("SQL_BIT", BOOLEAN); + ODBC_TO_ES.put("SQL_TINYINT", BYTE); + ODBC_TO_ES.put("SQL_SMALLINT", SHORT); + ODBC_TO_ES.put("SQL_INTEGER", INTEGER); + ODBC_TO_ES.put("SQL_BIGINT", LONG); + ODBC_TO_ES.put("SQL_REAL", FLOAT); + ODBC_TO_ES.put("SQL_FLOAT", DOUBLE); + ODBC_TO_ES.put("SQL_DOUBLE", DOUBLE); + ODBC_TO_ES.put("SQL_DECIMAL", DOUBLE); + ODBC_TO_ES.put("SQL_NUMERIC", DOUBLE); + + // String + ODBC_TO_ES.put("SQL_GUID", KEYWORD); + ODBC_TO_ES.put("SQL_CHAR", KEYWORD); + ODBC_TO_ES.put("SQL_WCHAR", KEYWORD); + ODBC_TO_ES.put("SQL_VARCHAR", TEXT); + ODBC_TO_ES.put("SQL_WVARCHAR", TEXT); + ODBC_TO_ES.put("SQL_LONGVARCHAR", TEXT); + ODBC_TO_ES.put("SQL_WLONGVARCHAR", TEXT); + + // Binary + ODBC_TO_ES.put("SQL_BINARY", BINARY); + ODBC_TO_ES.put("SQL_VARBINARY", BINARY); + ODBC_TO_ES.put("SQL_LONGVARBINARY", BINARY); + + // Date + ODBC_TO_ES.put("SQL_DATE", DATE); + ODBC_TO_ES.put("SQL_TIME", TIME); + ODBC_TO_ES.put("SQL_TIMESTAMP", DATETIME); + + // Intervals + ODBC_TO_ES.put("SQL_INTERVAL_YEAR", INTERVAL_YEAR); + ODBC_TO_ES.put("SQL_INTERVAL_MONTH", INTERVAL_MONTH); + ODBC_TO_ES.put("SQL_INTERVAL_DAY", INTERVAL_DAY); + ODBC_TO_ES.put("SQL_INTERVAL_HOUR", INTERVAL_HOUR); + ODBC_TO_ES.put("SQL_INTERVAL_MINUTE", INTERVAL_MINUTE); + ODBC_TO_ES.put("SQL_INTERVAL_SECOND", INTERVAL_SECOND); + ODBC_TO_ES.put("SQL_INTERVAL_YEAR_TO_MONTH", INTERVAL_YEAR_TO_MONTH); + ODBC_TO_ES.put("SQL_INTERVAL_DAY_TO_HOUR", INTERVAL_DAY_TO_HOUR); + ODBC_TO_ES.put("SQL_INTERVAL_DAY_TO_MINUTE", INTERVAL_DAY_TO_MINUTE); + ODBC_TO_ES.put("SQL_INTERVAL_DAY_TO_SECOND", INTERVAL_DAY_TO_SECOND); + ODBC_TO_ES.put("SQL_INTERVAL_HOUR_TO_MINUTE", INTERVAL_HOUR_TO_MINUTE); + ODBC_TO_ES.put("SQL_INTERVAL_HOUR_TO_SECOND", INTERVAL_HOUR_TO_SECOND); + ODBC_TO_ES.put("SQL_INTERVAL_MINUTE_TO_SECOND", INTERVAL_MINUTE_TO_SECOND); + } + + private static final Collection TYPES = unmodifiableList(Stream.concat(DataTypes.types().stream(), Arrays.asList( + DATE, + TIME, + INTERVAL_YEAR, + INTERVAL_MONTH, + INTERVAL_DAY, + INTERVAL_HOUR, + INTERVAL_MINUTE, + INTERVAL_SECOND, + INTERVAL_YEAR_TO_MONTH, + INTERVAL_DAY_TO_HOUR, + INTERVAL_DAY_TO_MINUTE, + INTERVAL_DAY_TO_SECOND, + INTERVAL_HOUR_TO_MINUTE, + INTERVAL_HOUR_TO_SECOND, + INTERVAL_MINUTE_TO_SECOND, + GEO_SHAPE, + GEO_POINT, + SHAPE) + .stream()) + .sorted(Comparator.comparing(DataType::typeName)) + .collect(toList())); + + private static final Map NAME_TO_TYPE = unmodifiableMap(TYPES.stream() + .collect(toMap(DataType::typeName, t -> t))); + + private static final Map ES_TO_TYPE = unmodifiableMap(TYPES.stream() + .filter(e -> e.esType() != null) + .collect(toMap(DataType::esType, t -> t))); + + private static final Map SQL_TO_ES; + + static { + Map sqlToEs = new HashMap<>(mapSize(45)); + // first add ES types + for (DataType type : SqlDataTypes.types()) { + if (type != OBJECT && type != NESTED) { + sqlToEs.put(type.typeName().toUpperCase(Locale.ROOT), type); + } + } + + // reuse the ODBC definition (without SQL_) + // note that this will override existing types in particular FLOAT + for (Entry entry : ODBC_TO_ES.entrySet()) { + sqlToEs.put(entry.getKey().substring(4), entry.getValue()); + } + + // special ones + sqlToEs.put("BOOL", BOOLEAN); + sqlToEs.put("INT", INTEGER); + sqlToEs.put("STRING", KEYWORD); + + SQL_TO_ES = unmodifiableMap(sqlToEs); + } + + private SqlDataTypes() {} + + public static Collection types() { + return TYPES; + } + + public static DataType fromTypeName(String name) { + return NAME_TO_TYPE.get(name.toLowerCase(Locale.ROOT)); + } + + public static DataType fromEs(String name) { + DataType type = ES_TO_TYPE.get(name); + return type != null ? type : UNSUPPORTED; + } + + public static DataType fromJava(Object value) { + DataType type = DataTypes.fromJava(value); + + if (type != null) { + return type; + } + if (value instanceof OffsetTime) { + return TIME; + } + if (value instanceof Interval) { + return ((Interval) value).dataType(); + } + if (value instanceof GeoShape) { + return GEO_SHAPE; + } + + return null; + } + + public static boolean isNullOrInterval(DataType type) { + return type == NULL || isInterval(type); + } + + public static boolean isInterval(DataType dataType) { + return isYearMonthInterval(dataType) || isDayTimeInterval(dataType); + } + + public static boolean isYearMonthInterval(DataType dataType) { + return dataType == INTERVAL_YEAR || dataType == INTERVAL_MONTH || dataType == INTERVAL_YEAR_TO_MONTH; + } + + public static boolean isDayTimeInterval(DataType dataType) { + return dataType == INTERVAL_DAY || dataType == INTERVAL_HOUR || dataType == INTERVAL_MINUTE || dataType == INTERVAL_SECOND + || dataType == INTERVAL_DAY_TO_HOUR || dataType == INTERVAL_DAY_TO_MINUTE || dataType == INTERVAL_DAY_TO_SECOND + || dataType == INTERVAL_HOUR_TO_MINUTE || dataType == INTERVAL_HOUR_TO_SECOND + || dataType == INTERVAL_MINUTE_TO_SECOND; + } + + public static boolean isDateBased(DataType type) { + return type == DATE || type == DATETIME; + } + + public static boolean isTimeBased(DataType type) { + return type == TIME; + } + + public static boolean isDateOrTimeBased(DataType type) { + return isDateBased(type) || isTimeBased(type); + } + + public static boolean isGeo(DataType type) { + return type == GEO_POINT || type == GEO_SHAPE || type == SHAPE; + } + + public static String format(DataType type) { + return isDateOrTimeBased(type) ? "epoch_millis" : null; + } + + + public static boolean isFromDocValuesOnly(DataType dataType) { + return dataType == KEYWORD // because of ignore_above. Extracting this from _source wouldn't make sense + || dataType == DATE // because of date formats + || dataType == DATETIME + || dataType == SCALED_FLOAT // because of scaling_factor + || dataType == GEO_POINT + || dataType == GEO_SHAPE + || dataType == SHAPE; + } + + public static boolean areCompatible(DataType left, DataType right) { + if (left == right) { + return true; + } else { + return (left == NULL || right == NULL) + || (DataTypes.isString(left) && DataTypes.isString(right)) + || (left.isNumeric() && right.isNumeric()) + || (isDateBased(left) && isDateBased(right)) + || (isInterval(left) && isInterval(right) && Intervals.compatibleInterval(left, right) != null); + } + } + + public static DataType fromOdbcType(String odbcType) { + return ODBC_TO_ES.get(odbcType); + } + + public static DataType fromSqlOrEsType(String typeName) { + return SQL_TO_ES.get(typeName.toUpperCase(Locale.ROOT)); + } + + public static SQLType sqlType(DataType dataType) { + if (dataType == UNSUPPORTED) { + return JDBCType.OTHER; + } + if (dataType == NULL) { + return JDBCType.NULL; + } + if (dataType == BOOLEAN) { + return JDBCType.BOOLEAN; + } + if (dataType == BYTE) { + return JDBCType.TINYINT; + } + if (dataType == SHORT) { + return JDBCType.SMALLINT; + } + if (dataType == INTEGER) { + return JDBCType.INTEGER; + } + if (dataType == LONG) { + return JDBCType.BIGINT; + } + if (dataType == DOUBLE) { + return JDBCType.DOUBLE; + } + if (dataType == FLOAT) { + return JDBCType.REAL; + } + if (dataType == HALF_FLOAT) { + return JDBCType.FLOAT; + } + if (dataType == SCALED_FLOAT) { + return JDBCType.DOUBLE; + } + if (dataType == KEYWORD) { + return JDBCType.VARCHAR; + } + if (dataType == TEXT) { + return JDBCType.VARCHAR; + } + if (dataType == DATETIME) { + return JDBCType.TIMESTAMP; + } + if (dataType == IP) { + return JDBCType.VARCHAR; + } + if (dataType == BINARY) { + return JDBCType.BINARY; + } + if (dataType == OBJECT) { + return JDBCType.STRUCT; + } + if (dataType == NESTED) { + return JDBCType.STRUCT; + } + // + // SQL specific + // + if (dataType == DATE) { + return JDBCType.DATE; + } + if (dataType == TIME) { + return JDBCType.TIME; + } + if (dataType == GEO_SHAPE) { + return ExtTypes.GEOMETRY; + } + if (dataType == GEO_POINT) { + return ExtTypes.GEOMETRY; + } + if (dataType == SHAPE) { + return ExtTypes.GEOMETRY; + } + if (dataType == INTERVAL_YEAR) { + return ExtTypes.INTERVAL_YEAR; + } + if (dataType == INTERVAL_MONTH) { + return ExtTypes.INTERVAL_MONTH; + } + if (dataType == INTERVAL_DAY) { + return ExtTypes.INTERVAL_DAY; + } + if (dataType == INTERVAL_HOUR) { + return ExtTypes.INTERVAL_HOUR; + } + if (dataType == INTERVAL_MINUTE) { + return ExtTypes.INTERVAL_MINUTE; + } + if (dataType == INTERVAL_SECOND) { + return ExtTypes.INTERVAL_SECOND; + } + if (dataType == INTERVAL_YEAR_TO_MONTH) { + return ExtTypes.INTERVAL_YEAR_TO_MONTH; + } + if (dataType == INTERVAL_DAY_TO_HOUR) { + return ExtTypes.INTERVAL_DAY_TO_HOUR; + } + if (dataType == INTERVAL_DAY_TO_MINUTE) { + return ExtTypes.INTERVAL_DAY_TO_MINUTE; + } + if (dataType == INTERVAL_DAY_TO_SECOND) { + return ExtTypes.INTERVAL_DAY_TO_SECOND; + } + if (dataType == INTERVAL_HOUR_TO_MINUTE) { + return ExtTypes.INTERVAL_HOUR_TO_MINUTE; + } + if (dataType == INTERVAL_HOUR_TO_SECOND) { + return ExtTypes.INTERVAL_HOUR_TO_SECOND; + } + if (dataType == INTERVAL_MINUTE_TO_SECOND) { + return ExtTypes.INTERVAL_MINUTE_TO_SECOND; + } + + return null; + } + + /** + * Returns the precision of the field + *

    + * Precision is the specified column size. For numeric data, this is the maximum precision. For character + * data, this is the length in characters. For datetime datatypes, this is the length in characters of the + * String representation (assuming the maximum allowed defaultPrecision of the fractional seconds component). + */ + public static int defaultPrecision(DataType dataType) { + if (dataType == UNSUPPORTED) { + return 0; + } + if (dataType == NULL) { + return 0; + } + if (dataType == BOOLEAN) { + return 1; + } + if (dataType == BYTE) { + return 3; + } + if (dataType == SHORT) { + return 5; + } + if (dataType == INTEGER) { + return 10; + } + if (dataType == LONG) { + return 19; + } + if (dataType == DOUBLE) { + return 15; + } + if (dataType == FLOAT) { + return 7; + } + if (dataType == HALF_FLOAT) { + return 3; + } + if (dataType == SCALED_FLOAT) { + return 15; + } + if (dataType == KEYWORD) { + return 15; + } + if (dataType == TEXT) { + return 32766; + } + if (dataType == DATETIME) { + return 3; + } + if (dataType == IP) { + return 39; + } + if (dataType == BINARY) { + return Integer.MAX_VALUE; + } + if (dataType == OBJECT) { + return 0; + } + if (dataType == NESTED) { + return 0; + } + // + // SQL specific + // + // since ODBC and JDBC interpret precision for Date as display size + // the precision is 23 (number of chars in ISO8601 with millis) + 6 chars for the timezone (e.g.: +05:00) + // see https://github.com/elastic/elasticsearch/issues/30386#issuecomment-386807288 + if (dataType == DATE) { + return 3; + } + if (dataType == TIME) { + return 3; + } + + if (dataType == GEO_SHAPE) { + return Integer.MAX_VALUE; + } + if (dataType == GEO_POINT) { + return Integer.MAX_VALUE; + } + if (dataType == SHAPE) { + return Integer.MAX_VALUE; + } + if (dataType == INTERVAL_YEAR) { + return 7; + } + if (dataType == INTERVAL_MONTH) { + return 7; + } + if (dataType == INTERVAL_DAY) { + return 23; + } + if (dataType == INTERVAL_HOUR) { + return 23; + } + if (dataType == INTERVAL_MINUTE) { + return 23; + } + if (dataType == INTERVAL_SECOND) { + return 23; + } + if (dataType == INTERVAL_YEAR_TO_MONTH) { + return 7; + } + if (dataType == INTERVAL_DAY_TO_HOUR) { + return 23; + } + if (dataType == INTERVAL_DAY_TO_MINUTE) { + return 23; + } + if (dataType == INTERVAL_DAY_TO_SECOND) { + return 23; + } + if (dataType == INTERVAL_HOUR_TO_MINUTE) { + return 23; + } + if (dataType == INTERVAL_HOUR_TO_SECOND) { + return 23; + } + if (dataType == INTERVAL_MINUTE_TO_SECOND) { + return 23; + } + + return 0; + } + + public static int displaySize(DataType dataType) { + if (dataType == UNSUPPORTED) { + return 0; + } + if (dataType == NULL) { + return 0; + } + if (dataType == BOOLEAN) { + return 1; + } + if (dataType == BYTE) { + return 5; + } + if (dataType == SHORT) { + return 6; + } + if (dataType == INTEGER) { + return 11; + } + if (dataType == LONG) { + return 20; + } + if (dataType == DOUBLE) { + return 25; + } + if (dataType == FLOAT) { + return 15; + } + if (dataType == HALF_FLOAT) { + return 25; + } + if (dataType == SCALED_FLOAT) { + return 25; + } + if (dataType == KEYWORD) { + return 32766; + } + if (dataType == TEXT) { + return Integer.MAX_VALUE; + } + if (dataType == DATETIME) { + return 29; + } + if (dataType == IP) { + return 0; + } + if (dataType == BINARY) { + return Integer.MAX_VALUE; + } + if (dataType == OBJECT) { + return 0; + } + if (dataType == NESTED) { + return 0; + } + // + // SQL specific + // + if (dataType == DATE) { + return 29; + } + if (dataType == TIME) { + return 18; + } + if (dataType == GEO_SHAPE) { + return Integer.MAX_VALUE; + } + if (dataType == GEO_POINT) { + //2 doubles + len("POINT( )") + return 25 * 2 + 8; + } + if (dataType == SHAPE) { + return Integer.MAX_VALUE; + } + if (dataType == INTERVAL_YEAR) { + return 7; + } + if (dataType == INTERVAL_MONTH) { + return 7; + } + if (dataType == INTERVAL_DAY) { + return 23; + } + if (dataType == INTERVAL_HOUR) { + return 23; + } + if (dataType == INTERVAL_MINUTE) { + return 23; + } + if (dataType == INTERVAL_SECOND) { + return 23; + } + if (dataType == INTERVAL_YEAR_TO_MONTH) { + return 7; + } + if (dataType == INTERVAL_DAY_TO_HOUR) { + return 23; + } + if (dataType == INTERVAL_DAY_TO_MINUTE) { + return 23; + } + if (dataType == INTERVAL_DAY_TO_SECOND) { + return 23; + } + if (dataType == INTERVAL_HOUR_TO_MINUTE) { + return 23; + } + if (dataType == INTERVAL_HOUR_TO_SECOND) { + return 23; + } + if (dataType == INTERVAL_MINUTE_TO_SECOND) { + return 23; + } + + return 0; + } + + // + // Metadata methods, mainly for ODBC. + // As these are fairly obscure and limited in use, there is no point to promote them as a full type methods + // hence why they appear here as utility methods. + // + + // https://docs.microsoft.com/en-us/sql/relational-databases/native-client-odbc-date-time/metadata-catalog + // https://github.com/elastic/elasticsearch/issues/30386 + public static Integer metaSqlDataType(DataType t) { + if (t == DATETIME) { + // ODBC SQL_DATETME + return Integer.valueOf(9); + } + // this is safe since the vendor SQL types are short despite the return value + return sqlType(t).getVendorTypeNumber(); + } + + // https://github.com/elastic/elasticsearch/issues/30386 + // https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/sqlgettypeinfo-function + public static Integer metaSqlDateTimeSub(DataType t) { + if (t == DATETIME) { + // ODBC SQL_CODE_TIMESTAMP + return Integer.valueOf(3); + } + // ODBC null + return 0; + } + + public static Short metaSqlMinimumScale(DataType t) { + return metaSqlSameScale(t); + } + + public static Short metaSqlMaximumScale(DataType t) { + return metaSqlSameScale(t); + } + + // https://docs.microsoft.com/en-us/sql/odbc/reference/appendixes/decimal-digits + // https://github.com/elastic/elasticsearch/issues/40357 + // since the scale is fixed, minimum and maximum should return the same value + // hence why this method exists + private static Short metaSqlSameScale(DataType t) { + // TODO: return info for SCALED_FLOATS (should be based on field not type) + if (t.isInteger()) { + return Short.valueOf((short) 0); + } + if (isDateBased(t) || t.isRational()) { + return Short.valueOf((short) defaultPrecision(t)); + } + return null; + } + + // https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/sqlgettypeinfo-function + public static Integer metaSqlRadix(DataType t) { + // RADIX - Determines how numbers returned by COLUMN_SIZE and DECIMAL_DIGITS should be interpreted. + // 10 means they represent the number of decimal digits allowed for the column. + // 2 means they represent the number of bits allowed for the column. + // null means radix is not applicable for the given type. + return t.isInteger() ? Integer.valueOf(10) : (t.isRational() ? Integer.valueOf(2) : null); + } + + //https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/sqlgettypeinfo-function#comments + //https://docs.microsoft.com/en-us/sql/odbc/reference/appendixes/column-size + public static Integer precision(DataType t) { + if (t.isNumeric()) { + return defaultPrecision(t); + } + return displaySize(t); + } +} \ No newline at end of file diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/util/DateUtils.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/util/DateUtils.java index 0f8afdd155215..448b6bc537602 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/util/DateUtils.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/util/DateUtils.java @@ -8,7 +8,7 @@ import org.elasticsearch.common.time.DateFormatter; import org.elasticsearch.common.time.DateFormatters; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; import org.elasticsearch.xpack.sql.expression.Foldables; import org.elasticsearch.xpack.sql.parser.ParsingException; import org.elasticsearch.xpack.sql.proto.StringUtils; @@ -28,7 +28,6 @@ public final class DateUtils { public static final ZoneId UTC = ZoneId.of("Z"); - public static final String DATE_PARSE_FORMAT = "epoch_millis"; // In Java 8 LocalDate.EPOCH is not available, introduced with later Java versions public static final LocalDate EPOCH = LocalDate.of(1970, 1, 1); public static final long DAY_IN_MILLIS = 60 * 60 * 24 * 1000L; diff --git a/x-pack/plugin/sql/src/main/resources/org/elasticsearch/xpack/sql/plugin/sql_whitelist.txt b/x-pack/plugin/sql/src/main/resources/org/elasticsearch/xpack/sql/plugin/sql_whitelist.txt index ae3472133aa1b..ea522a0e44084 100644 --- a/x-pack/plugin/sql/src/main/resources/org/elasticsearch/xpack/sql/plugin/sql_whitelist.txt +++ b/x-pack/plugin/sql/src/main/resources/org/elasticsearch/xpack/sql/plugin/sql_whitelist.txt @@ -8,20 +8,21 @@ #### Classes -class org.elasticsearch.xpack.sql.expression.function.scalar.geo.GeoShape { - +class org.elasticsearch.xpack.sql.expression.literal.geo.GeoShape { } - -class org.elasticsearch.xpack.sql.expression.literal.IntervalDayTime { +class org.elasticsearch.xpack.sql.expression.literal.interval.IntervalDayTime { } -class org.elasticsearch.xpack.sql.expression.literal.IntervalYearMonth { +class org.elasticsearch.xpack.sql.expression.literal.interval.IntervalYearMonth { } class java.time.OffsetTime { } +class org.elasticsearch.xpack.ql.expression.function.scalar.whitelist.InternalQlScriptUtils { +} + class org.elasticsearch.xpack.sql.expression.function.scalar.whitelist.InternalSqlScriptUtils { # @@ -81,30 +82,30 @@ class org.elasticsearch.xpack.sql.expression.function.scalar.whitelist.InternalS Number round(Number, Number) Number truncate(Number, Number) - Double abs(Number) - Double acos(Number) - Double asin(Number) - Double atan(Number) - Double cbrt(Number) - Double ceil(Number) - Double cos(Number) - Double cosh(Number) - Double cot(Number) - Double degrees(Number) - Double e(Number) - Double exp(Number) - Double expm1(Number) - Double floor(Number) - Double log(Number) - Double log10(Number) - Double pi(Number) - Double radians(Number) - Double random(Number) - Double sign(Number) - Double sin(Number) - Double sinh(Number) - Double sqrt(Number) - Double tan(Number) + Number abs(Number) + Number acos(Number) + Number asin(Number) + Number atan(Number) + Number cbrt(Number) + Number ceil(Number) + Number cos(Number) + Number cosh(Number) + Number cot(Number) + Number degrees(Number) + Number e(Number) + Number exp(Number) + Number expm1(Number) + Number floor(Number) + Number log(Number) + Number log10(Number) + Number pi(Number) + Number radians(Number) + Number random(Number) + Number sign(Number) + Number sin(Number) + Number sinh(Number) + Number sqrt(Number) + Number tan(Number) # # Date/Time functions diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/TestUtils.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/SqlTestUtils.java similarity index 86% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/TestUtils.java rename to x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/SqlTestUtils.java index 0d03573db05e2..d23f638f1f255 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/TestUtils.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/SqlTestUtils.java @@ -7,9 +7,12 @@ package org.elasticsearch.xpack.sql; import org.elasticsearch.common.unit.TimeValue; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.proto.Mode; import org.elasticsearch.xpack.sql.proto.Protocol; import org.elasticsearch.xpack.sql.session.Configuration; +import org.elasticsearch.xpack.sql.type.SqlDataTypes; import org.elasticsearch.xpack.sql.util.DateUtils; import java.time.Clock; @@ -27,9 +30,9 @@ import static org.elasticsearch.test.ESTestCase.randomZone; -public final class TestUtils { +public final class SqlTestUtils { - private TestUtils() {} + private SqlTestUtils() {} public static final Configuration TEST_CFG = new Configuration(DateUtils.UTC, Protocol.FETCH_SIZE, Protocol.REQUEST_TIMEOUT, Protocol.PAGE_TIMEOUT, null, Mode.PLAIN, @@ -83,5 +86,16 @@ public static String randomWhitespaces() { } return sj.toString(); } + + public static Literal literal(Object value) { + return literal(Source.EMPTY, value); + } + + public static Literal literal(Source source, Object value) { + if (value instanceof Literal) { + return (Literal) value; + } + return new Literal(source, value, SqlDataTypes.fromJava(value)); + } } diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/analysis/analyzer/FieldAttributeTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/analysis/analyzer/FieldAttributeTests.java index b36111ffac3bb..14b1da838259e 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/analysis/analyzer/FieldAttributeTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/analysis/analyzer/FieldAttributeTests.java @@ -6,28 +6,30 @@ package org.elasticsearch.xpack.sql.analysis.analyzer; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.TestUtils; -import org.elasticsearch.xpack.sql.analysis.index.EsIndex; -import org.elasticsearch.xpack.sql.analysis.index.IndexResolution; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; -import org.elasticsearch.xpack.sql.expression.NamedExpression; -import org.elasticsearch.xpack.sql.expression.function.FunctionRegistry; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.expression.NamedExpression; +import org.elasticsearch.xpack.ql.expression.function.FunctionRegistry; +import org.elasticsearch.xpack.ql.index.EsIndex; +import org.elasticsearch.xpack.ql.index.IndexResolution; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.plan.logical.Project; +import org.elasticsearch.xpack.ql.type.EsField; +import org.elasticsearch.xpack.ql.type.TypesTests; +import org.elasticsearch.xpack.sql.SqlTestUtils; +import org.elasticsearch.xpack.sql.expression.function.SqlFunctionRegistry; import org.elasticsearch.xpack.sql.parser.SqlParser; -import org.elasticsearch.xpack.sql.plan.logical.LogicalPlan; -import org.elasticsearch.xpack.sql.plan.logical.Project; import org.elasticsearch.xpack.sql.stats.Metrics; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.EsField; -import org.elasticsearch.xpack.sql.type.TypesTests; import java.util.List; import java.util.Map; -import static org.elasticsearch.xpack.sql.type.DataType.BOOLEAN; -import static org.elasticsearch.xpack.sql.type.DataType.KEYWORD; +import static org.elasticsearch.xpack.ql.type.DataTypes.BOOLEAN; +import static org.elasticsearch.xpack.ql.type.DataTypes.KEYWORD; +import static org.elasticsearch.xpack.ql.type.DataTypes.TEXT; +import static org.elasticsearch.xpack.sql.types.SqlTypesTests.loadMapping; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasItems; @@ -45,14 +47,14 @@ public class FieldAttributeTests extends ESTestCase { public FieldAttributeTests() { parser = new SqlParser(); - functionRegistry = new FunctionRegistry(); + functionRegistry = new SqlFunctionRegistry(); verifier = new Verifier(new Metrics()); - Map mapping = TypesTests.loadMapping("mapping-multi-field-variation.json"); + Map mapping = loadMapping("mapping-multi-field-variation.json"); EsIndex test = new EsIndex("test", mapping); getIndexResult = IndexResolution.valid(test); - analyzer = new Analyzer(TestUtils.TEST_CFG, functionRegistry, getIndexResult, verifier); + analyzer = new Analyzer(SqlTestUtils.TEST_CFG, functionRegistry, getIndexResult, verifier); } private LogicalPlan plan(String sql) { @@ -112,7 +114,7 @@ public void testExactKeyword() { FieldAttribute attr = attribute("some.string"); assertThat(attr.path(), is("some")); assertThat(attr.name(), is("some.string")); - assertThat(attr.dataType(), is(DataType.TEXT)); + assertThat(attr.dataType(), is(TEXT)); assertTrue(attr.getExactInfo().hasExact()); FieldAttribute exact = attr.exactAttribute(); assertTrue(exact.getExactInfo().hasExact()); @@ -124,11 +126,11 @@ public void testAmbiguousExactKeyword() { FieldAttribute attr = attribute("some.ambiguous"); assertThat(attr.path(), is("some")); assertThat(attr.name(), is("some.ambiguous")); - assertThat(attr.dataType(), is(DataType.TEXT)); + assertThat(attr.dataType(), is(TEXT)); assertFalse(attr.getExactInfo().hasExact()); assertThat(attr.getExactInfo().errorMsg(), is("Multiple exact keyword candidates available for [ambiguous]; specify which one to use")); - SqlIllegalArgumentException e = expectThrows(SqlIllegalArgumentException.class, () -> attr.exactAttribute()); + QlIllegalArgumentException e = expectThrows(QlIllegalArgumentException.class, () -> attr.exactAttribute()); assertThat(e.getMessage(), is("Multiple exact keyword candidates available for [ambiguous]; specify which one to use")); } @@ -171,7 +173,7 @@ public void testFieldAmbiguity() { EsIndex index = new EsIndex("test", mapping); getIndexResult = IndexResolution.valid(index); - analyzer = new Analyzer(TestUtils.TEST_CFG, functionRegistry, getIndexResult, verifier); + analyzer = new Analyzer(SqlTestUtils.TEST_CFG, functionRegistry, getIndexResult, verifier); VerificationException ex = expectThrows(VerificationException.class, () -> plan("SELECT test.bar FROM test")); assertEquals( diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/analysis/analyzer/PreAnalyzerTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/analysis/analyzer/PreAnalyzerTests.java index ca3b2f14ebc80..6ffdd600ab7c6 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/analysis/analyzer/PreAnalyzerTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/analysis/analyzer/PreAnalyzerTests.java @@ -6,9 +6,9 @@ package org.elasticsearch.xpack.sql.analysis.analyzer; import org.elasticsearch.test.ESTestCase; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; import org.elasticsearch.xpack.sql.analysis.analyzer.PreAnalyzer.PreAnalysis; import org.elasticsearch.xpack.sql.parser.SqlParser; -import org.elasticsearch.xpack.sql.plan.logical.LogicalPlan; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.Matchers.hasSize; diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/analysis/analyzer/VerifierErrorMessagesTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/analysis/analyzer/VerifierErrorMessagesTests.java index 7540878e9ffdc..413898ea290d3 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/analysis/analyzer/VerifierErrorMessagesTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/analysis/analyzer/VerifierErrorMessagesTests.java @@ -6,11 +6,13 @@ package org.elasticsearch.xpack.sql.analysis.analyzer; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.TestUtils; -import org.elasticsearch.xpack.sql.analysis.index.EsIndex; -import org.elasticsearch.xpack.sql.analysis.index.IndexResolution; +import org.elasticsearch.xpack.ql.index.EsIndex; +import org.elasticsearch.xpack.ql.index.IndexResolution; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.type.EsField; +import org.elasticsearch.xpack.sql.SqlTestUtils; import org.elasticsearch.xpack.sql.analysis.index.IndexResolverTests; -import org.elasticsearch.xpack.sql.expression.function.FunctionRegistry; +import org.elasticsearch.xpack.sql.expression.function.SqlFunctionRegistry; import org.elasticsearch.xpack.sql.expression.function.scalar.math.Round; import org.elasticsearch.xpack.sql.expression.function.scalar.math.Truncate; import org.elasticsearch.xpack.sql.expression.function.scalar.string.Char; @@ -21,11 +23,7 @@ import org.elasticsearch.xpack.sql.expression.predicate.conditional.Least; import org.elasticsearch.xpack.sql.expression.predicate.conditional.NullIf; import org.elasticsearch.xpack.sql.parser.SqlParser; -import org.elasticsearch.xpack.sql.plan.logical.LogicalPlan; import org.elasticsearch.xpack.sql.stats.Metrics; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.EsField; -import org.elasticsearch.xpack.sql.type.TypesTests; import java.util.Arrays; import java.util.LinkedHashMap; @@ -34,19 +32,23 @@ import static java.util.Collections.emptyMap; import static java.util.Collections.singletonMap; +import static org.elasticsearch.xpack.ql.type.DataTypes.KEYWORD; +import static org.elasticsearch.xpack.ql.type.DataTypes.OBJECT; +import static org.elasticsearch.xpack.sql.types.SqlTypesTests.loadMapping; + public class VerifierErrorMessagesTests extends ESTestCase { private SqlParser parser = new SqlParser(); private IndexResolution indexResolution = IndexResolution.valid(new EsIndex("test", - TypesTests.loadMapping("mapping-multi-field-with-nested.json"))); + loadMapping("mapping-multi-field-with-nested.json"))); private String error(String sql) { return error(indexResolution, sql); } private String error(IndexResolution getIndexResult, String sql) { - Analyzer analyzer = new Analyzer(TestUtils.TEST_CFG, new FunctionRegistry(), getIndexResult, new Verifier(new Metrics())); + Analyzer analyzer = new Analyzer(SqlTestUtils.TEST_CFG, new SqlFunctionRegistry(), getIndexResult, new Verifier(new Metrics())); VerificationException e = expectThrows(VerificationException.class, () -> analyzer.analyze(parser.createStatement(sql), true)); assertTrue(e.getMessage().startsWith("Found ")); String header = "Found 1 problem(s)\nline "; @@ -59,18 +61,18 @@ private LogicalPlan accept(String sql) { } private EsIndex getTestEsIndex() { - Map mapping = TypesTests.loadMapping("mapping-multi-field-with-nested.json"); + Map mapping = loadMapping("mapping-multi-field-with-nested.json"); return new EsIndex("test", mapping); } private LogicalPlan accept(IndexResolution resolution, String sql) { - Analyzer analyzer = new Analyzer(TestUtils.TEST_CFG, new FunctionRegistry(), resolution, new Verifier(new Metrics())); + Analyzer analyzer = new Analyzer(SqlTestUtils.TEST_CFG, new SqlFunctionRegistry(), resolution, new Verifier(new Metrics())); return analyzer.analyze(parser.createStatement(sql), true); } private IndexResolution incompatible() { - Map basicMapping = TypesTests.loadMapping("mapping-basic.json", true); - Map incompatible = TypesTests.loadMapping("mapping-basic-incompatible.json"); + Map basicMapping = loadMapping("mapping-basic.json", true); + Map incompatible = loadMapping("mapping-basic-incompatible.json"); assertNotEquals(basicMapping, incompatible); IndexResolution resolution = IndexResolverTests.merge(new EsIndex("basic", basicMapping), @@ -114,8 +116,7 @@ public void testColumnWithNoSubFields() { public void testFieldAliasTypeWithoutHierarchy() { Map mapping = new LinkedHashMap<>(); - mapping.put("field", new EsField("field", DataType.OBJECT, - singletonMap("alias", new EsField("alias", DataType.KEYWORD, emptyMap(), true)), false)); + mapping.put("field", new EsField("field", OBJECT, singletonMap("alias", new EsField("alias", KEYWORD, emptyMap(), true)), false)); IndexResolution resolution = IndexResolution.valid(new EsIndex("test", mapping)); diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/analysis/index/IndexResolverTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/analysis/index/IndexResolverTests.java index 7092ea2da8971..f29f373272a1e 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/analysis/index/IndexResolverTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/analysis/index/IndexResolverTests.java @@ -7,11 +7,14 @@ import org.elasticsearch.action.fieldcaps.FieldCapabilities; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.EsField; -import org.elasticsearch.xpack.sql.type.InvalidMappedField; -import org.elasticsearch.xpack.sql.type.KeywordEsField; -import org.elasticsearch.xpack.sql.type.TypesTests; +import org.elasticsearch.xpack.ql.index.EsIndex; +import org.elasticsearch.xpack.ql.index.IndexResolution; +import org.elasticsearch.xpack.ql.index.IndexResolver; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.EsField; +import org.elasticsearch.xpack.ql.type.InvalidMappedField; +import org.elasticsearch.xpack.ql.type.KeywordEsField; +import org.elasticsearch.xpack.sql.type.SqlDataTypeRegistry; import java.util.ArrayList; import java.util.Collections; @@ -23,12 +26,20 @@ import static java.util.Collections.singletonMap; import static org.elasticsearch.common.logging.LoggerMessageFormat.format; +import static org.elasticsearch.xpack.ql.type.DataTypes.DATETIME; +import static org.elasticsearch.xpack.ql.type.DataTypes.INTEGER; +import static org.elasticsearch.xpack.ql.type.DataTypes.KEYWORD; +import static org.elasticsearch.xpack.ql.type.DataTypes.OBJECT; +import static org.elasticsearch.xpack.ql.type.DataTypes.TEXT; +import static org.elasticsearch.xpack.ql.type.DataTypes.UNSUPPORTED; +import static org.elasticsearch.xpack.ql.type.DataTypes.isPrimitive; +import static org.elasticsearch.xpack.sql.types.SqlTypesTests.loadMapping; public class IndexResolverTests extends ESTestCase { public void testMergeSameMapping() throws Exception { - Map oneMapping = TypesTests.loadMapping("mapping-basic.json", true); - Map sameMapping = TypesTests.loadMapping("mapping-basic.json", true); + Map oneMapping = loadMapping("mapping-basic.json", true); + Map sameMapping = loadMapping("mapping-basic.json", true); assertNotSame(oneMapping, sameMapping); assertEquals(oneMapping, sameMapping); @@ -39,8 +50,8 @@ public void testMergeSameMapping() throws Exception { } public void testMergeCompatibleMapping() throws Exception { - Map basicMapping = TypesTests.loadMapping("mapping-basic.json", true); - Map numericMapping = TypesTests.loadMapping("mapping-numeric.json", true); + Map basicMapping = loadMapping("mapping-basic.json", true); + Map numericMapping = loadMapping("mapping-numeric.json", true); assertNotEquals(basicMapping, numericMapping); @@ -51,8 +62,8 @@ public void testMergeCompatibleMapping() throws Exception { } public void testMergeIncompatibleTypes() throws Exception { - Map basicMapping = TypesTests.loadMapping("mapping-basic.json", true); - Map incompatible = TypesTests.loadMapping("mapping-basic-incompatible.json"); + Map basicMapping = loadMapping("mapping-basic.json", true); + Map incompatible = loadMapping("mapping-basic-incompatible.json"); assertNotEquals(basicMapping, incompatible); @@ -72,8 +83,8 @@ public void testMergeIncompatibleTypes() throws Exception { } public void testMergeIncompatibleCapabilities() throws Exception { - Map basicMapping = TypesTests.loadMapping("mapping-basic.json", true); - Map incompatible = TypesTests.loadMapping("mapping-basic-nodocvalues.json", true); + Map basicMapping = loadMapping("mapping-basic.json", true); + Map incompatible = loadMapping("mapping-basic-nodocvalues.json", true); assertNotEquals(basicMapping, incompatible); @@ -90,7 +101,7 @@ public void testMergeIncompatibleCapabilities() throws Exception { } public void testMultiLevelObjectMappings() throws Exception { - Map dottedMapping = TypesTests.loadMapping("mapping-dotted-field.json", true); + Map dottedMapping = loadMapping("mapping-dotted-field.json", true); IndexResolution resolution = merge(new EsIndex("a", dottedMapping)); @@ -99,7 +110,7 @@ public void testMultiLevelObjectMappings() throws Exception { } public void testMultiLevelNestedMappings() throws Exception { - Map nestedMapping = TypesTests.loadMapping("mapping-nested.json", true); + Map nestedMapping = loadMapping("mapping-nested.json", true); IndexResolution resolution = merge(new EsIndex("a", nestedMapping)); @@ -115,15 +126,15 @@ public void testMetaFieldsAreIgnored() throws Exception { addFieldCaps(fieldCaps, "text", "keyword", true, true); String wildcard = "*"; - IndexResolution resolution = IndexResolver.mergedMappings(wildcard, new String[] { "index" }, fieldCaps); + IndexResolution resolution = mergedMappings(wildcard, new String[] { "index" }, fieldCaps); assertTrue(resolution.isValid()); EsIndex esIndex = resolution.get(); assertEquals(wildcard, esIndex.name()); assertNull(esIndex.mapping().get("_version")); assertNull(esIndex.mapping().get("_size")); - assertEquals(DataType.INTEGER, esIndex.mapping().get("_meta_field").getDataType()); - assertEquals(DataType.KEYWORD, esIndex.mapping().get("text").getDataType()); + assertEquals(INTEGER, esIndex.mapping().get("_meta_field").getDataType()); + assertEquals(KEYWORD, esIndex.mapping().get("text").getDataType()); } public void testFlattenedHiddenSubfield() throws Exception { @@ -138,20 +149,20 @@ public void testFlattenedHiddenSubfield() throws Exception { addFieldCaps(fieldCaps, "text", "keyword", true, true); String wildcard = "*"; - IndexResolution resolution = IndexResolver.mergedMappings(wildcard, new String[] { "index" }, fieldCaps); + IndexResolution resolution = mergedMappings(wildcard, new String[] { "index" }, fieldCaps); assertTrue(resolution.isValid()); EsIndex esIndex = resolution.get(); assertEquals(wildcard, esIndex.name()); - assertEquals(DataType.UNSUPPORTED, esIndex.mapping().get("some_field").getDataType()); - assertEquals(DataType.UNSUPPORTED, esIndex.mapping().get("some_field").getProperties().get("_keyed").getDataType()); - assertEquals(DataType.OBJECT, esIndex.mapping().get("nested_field").getDataType()); - assertEquals(DataType.UNSUPPORTED, esIndex.mapping().get("nested_field").getProperties().get("sub_field").getDataType()); - assertEquals(DataType.UNSUPPORTED, + assertEquals(UNSUPPORTED, esIndex.mapping().get("some_field").getDataType()); + assertEquals(UNSUPPORTED, esIndex.mapping().get("some_field").getProperties().get("_keyed").getDataType()); + assertEquals(OBJECT, esIndex.mapping().get("nested_field").getDataType()); + assertEquals(UNSUPPORTED, esIndex.mapping().get("nested_field").getProperties().get("sub_field").getDataType()); + assertEquals(UNSUPPORTED, esIndex.mapping().get("nested_field").getProperties().get("sub_field").getProperties().get("_keyed").getDataType()); - assertEquals(DataType.KEYWORD, esIndex.mapping().get("text").getDataType()); - assertEquals(DataType.OBJECT, esIndex.mapping().get("another_field").getDataType()); - assertEquals(DataType.KEYWORD, esIndex.mapping().get("another_field").getProperties().get("_keyed").getDataType()); + assertEquals(KEYWORD, esIndex.mapping().get("text").getDataType()); + assertEquals(OBJECT, esIndex.mapping().get("another_field").getDataType()); + assertEquals(KEYWORD, esIndex.mapping().get("another_field").getProperties().get("_keyed").getDataType()); } public void testPropagateUnsupportedTypeToSubFields() throws Exception { @@ -165,17 +176,17 @@ public void testPropagateUnsupportedTypeToSubFields() throws Exception { addFieldCaps(fieldCaps, "a.b.c.e", "foo", true, true); String wildcard = "*"; - IndexResolution resolution = IndexResolver.mergedMappings(wildcard, new String[] { "index" }, fieldCaps); + IndexResolution resolution = mergedMappings(wildcard, new String[] { "index" }, fieldCaps); assertTrue(resolution.isValid()); EsIndex esIndex = resolution.get(); assertEquals(wildcard, esIndex.name()); - assertEquals(DataType.TEXT, esIndex.mapping().get("a").getDataType()); - assertEquals(DataType.UNSUPPORTED, esIndex.mapping().get("a").getProperties().get("b").getDataType()); - assertEquals(DataType.UNSUPPORTED, esIndex.mapping().get("a").getProperties().get("b").getProperties().get("c").getDataType()); - assertEquals(DataType.UNSUPPORTED, esIndex.mapping().get("a").getProperties().get("b").getProperties().get("c") + assertEquals(TEXT, esIndex.mapping().get("a").getDataType()); + assertEquals(UNSUPPORTED, esIndex.mapping().get("a").getProperties().get("b").getDataType()); + assertEquals(UNSUPPORTED, esIndex.mapping().get("a").getProperties().get("b").getProperties().get("c").getDataType()); + assertEquals(UNSUPPORTED, esIndex.mapping().get("a").getProperties().get("b").getProperties().get("c") .getProperties().get("d").getDataType()); - assertEquals(DataType.UNSUPPORTED, esIndex.mapping().get("a").getProperties().get("b").getProperties().get("c") + assertEquals(UNSUPPORTED, esIndex.mapping().get("a").getProperties().get("b").getProperties().get("c") .getProperties().get("e").getDataType()); } @@ -196,22 +207,22 @@ public void testRandomMappingFieldTypeMappedAsUnsupported() throws Exception { addFieldCaps(fieldCaps, "text", "keyword", true, true); String wildcard = "*"; - IndexResolution resolution = IndexResolver.mergedMappings(wildcard, new String[] { "index" }, fieldCaps); + IndexResolution resolution = mergedMappings(wildcard, new String[] { "index" }, fieldCaps); assertTrue(resolution.isValid()); EsIndex esIndex = resolution.get(); assertEquals(wildcard, esIndex.name()); - assertEquals(DataType.UNSUPPORTED, esIndex.mapping().get("some_field").getDataType()); - assertEquals(DataType.OBJECT, esIndex.mapping().get("nested_field").getDataType()); - assertEquals(DataType.UNSUPPORTED, esIndex.mapping().get("nested_field").getProperties().get("sub_field1").getDataType()); - assertEquals(DataType.UNSUPPORTED, + assertEquals(UNSUPPORTED, esIndex.mapping().get("some_field").getDataType()); + assertEquals(OBJECT, esIndex.mapping().get("nested_field").getDataType()); + assertEquals(UNSUPPORTED, esIndex.mapping().get("nested_field").getProperties().get("sub_field1").getDataType()); + assertEquals(UNSUPPORTED, esIndex.mapping().get("nested_field").getProperties().get("sub_field1").getProperties().get("bar").getDataType()); - assertEquals(DataType.UNSUPPORTED, esIndex.mapping().get("nested_field").getProperties().get("sub_field2").getDataType()); - assertEquals(DataType.UNSUPPORTED, + assertEquals(UNSUPPORTED, esIndex.mapping().get("nested_field").getProperties().get("sub_field2").getDataType()); + assertEquals(UNSUPPORTED, esIndex.mapping().get("nested_field").getProperties().get("sub_field2").getProperties().get("bar").getDataType()); - assertEquals(DataType.KEYWORD, esIndex.mapping().get("text").getDataType()); - assertEquals(DataType.OBJECT, esIndex.mapping().get("another_field").getDataType()); - assertEquals(DataType.UNSUPPORTED, esIndex.mapping().get("another_field").getProperties().get("_foo").getDataType()); + assertEquals(KEYWORD, esIndex.mapping().get("text").getDataType()); + assertEquals(OBJECT, esIndex.mapping().get("another_field").getDataType()); + assertEquals(UNSUPPORTED, esIndex.mapping().get("another_field").getProperties().get("_foo").getDataType()); } public void testMergeIncompatibleCapabilitiesOfObjectFields() throws Exception { @@ -240,7 +251,7 @@ public void testMergeIncompatibleCapabilitiesOfObjectFields() throws Exception { String wildcard = "*"; - IndexResolution resolution = IndexResolver.mergedMappings(wildcard, new String[] { "one-index" }, fieldCaps); + IndexResolution resolution = mergedMappings(wildcard, new String[] { "one-index" }, fieldCaps); assertTrue(resolution.isValid()); @@ -258,8 +269,8 @@ public void testMergeIncompatibleCapabilitiesOfObjectFields() throws Exception { } public void testSeparateSameMappingDifferentIndices() throws Exception { - Map oneMapping = TypesTests.loadMapping("mapping-basic.json", true); - Map sameMapping = TypesTests.loadMapping("mapping-basic.json", true); + Map oneMapping = loadMapping("mapping-basic.json", true); + Map sameMapping = loadMapping("mapping-basic.json", true); assertNotSame(oneMapping, sameMapping); assertEquals(oneMapping, sameMapping); @@ -271,8 +282,8 @@ public void testSeparateSameMappingDifferentIndices() throws Exception { } public void testSeparateIncompatibleTypes() throws Exception { - Map basicMapping = TypesTests.loadMapping("mapping-basic.json", true); - Map incompatible = TypesTests.loadMapping("mapping-basic-incompatible.json"); + Map basicMapping = loadMapping("mapping-basic.json", true); + Map incompatible = loadMapping("mapping-basic-incompatible.json"); assertNotEquals(basicMapping, incompatible); @@ -307,15 +318,15 @@ public void testIndexWithNoMapping() { Map> versionFC = singletonMap("_version", singletonMap("_index", new FieldCapabilities("_version", "_version", false, false, Collections.emptyMap()))); - assertTrue(IndexResolver.mergedMappings("*", new String[] { "empty" }, versionFC).isValid()); + assertTrue(mergedMappings("*", new String[] { "empty" }, versionFC).isValid()); } public static IndexResolution merge(EsIndex... indices) { - return IndexResolver.mergedMappings("*", Stream.of(indices).map(EsIndex::name).toArray(String[]::new), fromMappings(indices)); + return mergedMappings("*", Stream.of(indices).map(EsIndex::name).toArray(String[]::new), fromMappings(indices)); } public static List separate(EsIndex... indices) { - return IndexResolver.separateMappings("*", null, Stream.of(indices).map(EsIndex::name).toArray(String[]::new), + return separateMappings("*", null, Stream.of(indices).map(EsIndex::name).toArray(String[]::new), fromMappings(indices)); } @@ -336,7 +347,7 @@ public static Map> fromMappings(EsIndex.. if (entry.getValue().size() > 1) { for (EsIndex index : indices) { EsField field = index.mapping().get(fieldName); - UpdateableFieldCapabilities fieldCaps = (UpdateableFieldCapabilities) caps.get(field.getDataType().typeName); + UpdateableFieldCapabilities fieldCaps = (UpdateableFieldCapabilities) caps.get(field.getDataType().esType()); fieldCaps.indices.add(index.name()); } //TODO: what about nonAgg/SearchIndices? @@ -353,7 +364,7 @@ private static void addFieldCaps(String parent, EsField field, String indexName, map = new HashMap<>(); merged.put(fieldName, map); } - FieldCapabilities caps = map.computeIfAbsent(field.getDataType().typeName, + FieldCapabilities caps = map.computeIfAbsent(field.getDataType().esType(), esType -> new UpdateableFieldCapabilities(fieldName, esType, isSearchable(field.getDataType()), isAggregatable(field.getDataType()))); @@ -368,11 +379,11 @@ private static void addFieldCaps(String parent, EsField field, String indexName, } private static boolean isSearchable(DataType type) { - return type.isPrimitive(); + return isPrimitive(type); } private static boolean isAggregatable(DataType type) { - return type.isNumeric() || type == DataType.KEYWORD || type == DataType.DATETIME; + return type.isNumeric() || type == KEYWORD || type == DATETIME; } private static class UpdateableFieldCapabilities extends FieldCapabilities { @@ -418,4 +429,14 @@ private void addFieldCaps(Map> fieldCaps, cap.put(type, new FieldCapabilities(name, type, isSearchable, isAggregatable, Collections.emptyMap())); fieldCaps.put(name, cap); } -} + + private static IndexResolution mergedMappings(String indexPattern, String[] indexNames, + Map> fieldCaps) { + return IndexResolver.mergedMappings(SqlDataTypeRegistry.INSTANCE, indexPattern, indexNames, fieldCaps); + } + + private static List separateMappings(String indexPattern, String javaRegex, String[] indexNames, + Map> fieldCaps) { + return IndexResolver.separateMappings(SqlDataTypeRegistry.INSTANCE, indexPattern, javaRegex, indexNames, fieldCaps); + } +} \ No newline at end of file diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/CompositeAggregationCursorTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/CompositeAggregationCursorTests.java index 195d11be434d7..ae17b00f3400f 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/CompositeAggregationCursorTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/CompositeAggregationCursorTests.java @@ -6,10 +6,10 @@ package org.elasticsearch.xpack.sql.execution.search; import org.elasticsearch.common.io.stream.Writeable.Reader; +import org.elasticsearch.xpack.ql.execution.search.extractor.BucketExtractor; +import org.elasticsearch.xpack.ql.execution.search.extractor.ConstantExtractorTests; import org.elasticsearch.xpack.sql.AbstractSqlWireSerializingTestCase; -import org.elasticsearch.xpack.sql.execution.search.extractor.BucketExtractor; import org.elasticsearch.xpack.sql.execution.search.extractor.CompositeKeyExtractorTests; -import org.elasticsearch.xpack.sql.execution.search.extractor.ConstantExtractorTests; import org.elasticsearch.xpack.sql.execution.search.extractor.MetricAggExtractorTests; import java.io.IOException; diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/ScrollCursorTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/ScrollCursorTests.java index ca135d5170fd4..e45e030054dc8 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/ScrollCursorTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/ScrollCursorTests.java @@ -8,10 +8,10 @@ import org.elasticsearch.Version; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.Writeable.Reader; +import org.elasticsearch.xpack.ql.execution.search.extractor.ConstantExtractorTests; +import org.elasticsearch.xpack.ql.execution.search.extractor.HitExtractor; import org.elasticsearch.xpack.sql.AbstractSqlWireSerializingTestCase; import org.elasticsearch.xpack.sql.execution.search.extractor.ComputingExtractorTests; -import org.elasticsearch.xpack.sql.execution.search.extractor.ConstantExtractorTests; -import org.elasticsearch.xpack.sql.execution.search.extractor.HitExtractor; import org.elasticsearch.xpack.sql.session.Cursors; import java.io.IOException; diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/SourceGeneratorTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/SourceGeneratorTests.java index 7efbea74241e0..3fc5d96765ad9 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/SourceGeneratorTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/SourceGeneratorTests.java @@ -14,11 +14,13 @@ import org.elasticsearch.search.sort.FieldSortBuilder; import org.elasticsearch.search.sort.SortOrder; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.expression.AttributeMap; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; -import org.elasticsearch.xpack.sql.expression.ReferenceAttribute; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.AttributeMap; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.expression.ReferenceAttribute; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.KeywordEsField; import org.elasticsearch.xpack.sql.expression.function.Score; import org.elasticsearch.xpack.sql.querydsl.agg.AvgAgg; import org.elasticsearch.xpack.sql.querydsl.agg.GroupByValue; @@ -28,8 +30,6 @@ import org.elasticsearch.xpack.sql.querydsl.container.Sort.Direction; import org.elasticsearch.xpack.sql.querydsl.container.Sort.Missing; import org.elasticsearch.xpack.sql.querydsl.query.MatchQuery; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.KeywordEsField; import java.util.LinkedHashMap; import java.util.Map; diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/SqlSourceBuilderTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/SqlSourceBuilderTests.java index 6ee843c2c6371..5851178b1d445 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/SqlSourceBuilderTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/SqlSourceBuilderTests.java @@ -9,6 +9,7 @@ import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.fetch.subphase.FetchSourceContext; import org.elasticsearch.test.ESTestCase; +import org.elasticsearch.xpack.ql.execution.search.QlSourceBuilder; import java.util.Arrays; import java.util.Map; @@ -19,7 +20,7 @@ public class SqlSourceBuilderTests extends ESTestCase { public void testSqlSourceBuilder() { - final SqlSourceBuilder ssb = new SqlSourceBuilder(); + final QlSourceBuilder ssb = new QlSourceBuilder(); final SearchSourceBuilder source = new SearchSourceBuilder(); ssb.trackScores(); ssb.addSourceField("foo"); diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/extractor/CompositeKeyExtractorTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/extractor/CompositeKeyExtractorTests.java index 0edf46c934553..bd8b427339b3e 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/extractor/CompositeKeyExtractorTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/extractor/CompositeKeyExtractorTests.java @@ -9,6 +9,7 @@ import org.elasticsearch.search.aggregations.Aggregations; import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation.Bucket; import org.elasticsearch.test.ESTestCase; +import org.elasticsearch.xpack.ql.execution.search.extractor.BucketExtractor; import org.elasticsearch.xpack.sql.AbstractSqlWireSerializingTestCase; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; import org.elasticsearch.xpack.sql.querydsl.container.GroupByRef.Property; diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/extractor/ComputingExtractorTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/extractor/ComputingExtractorTests.java index 909fdf831e13f..d81b31db5c95e 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/extractor/ComputingExtractorTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/extractor/ComputingExtractorTests.java @@ -9,6 +9,11 @@ import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.Writeable.Reader; import org.elasticsearch.search.SearchHit; +import org.elasticsearch.xpack.ql.execution.search.extractor.ComputingExtractor; +import org.elasticsearch.xpack.ql.expression.gen.processor.ChainingProcessor; +import org.elasticsearch.xpack.ql.expression.gen.processor.ChainingProcessorTests; +import org.elasticsearch.xpack.ql.expression.gen.processor.HitExtractorProcessor; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; import org.elasticsearch.xpack.sql.AbstractSqlWireSerializingTestCase; import org.elasticsearch.xpack.sql.expression.function.scalar.CastProcessorTests; import org.elasticsearch.xpack.sql.expression.function.scalar.Processors; @@ -16,11 +21,6 @@ import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathFunctionProcessorTests; import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor; import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation; -import org.elasticsearch.xpack.sql.expression.gen.processor.ChainingProcessor; -import org.elasticsearch.xpack.sql.expression.gen.processor.ChainingProcessorTests; -import org.elasticsearch.xpack.sql.expression.gen.processor.HitExtractorProcessor; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.type.DataType; import java.io.IOException; import java.util.ArrayList; @@ -29,7 +29,8 @@ import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; -import static org.elasticsearch.xpack.sql.util.CollectionUtils.combine; +import static org.elasticsearch.xpack.ql.type.DataTypes.DOUBLE; +import static org.elasticsearch.xpack.ql.util.CollectionUtils.combine; import static org.elasticsearch.xpack.sql.util.DateUtils.UTC; public class ComputingExtractorTests extends AbstractSqlWireSerializingTestCase { @@ -48,7 +49,7 @@ public static Processor randomProcessor() { @Override protected NamedWriteableRegistry getNamedWriteableRegistry() { - return new NamedWriteableRegistry(combine(Processors.getNamedWriteables(), HitExtractors.getNamedWriteables())); + return new NamedWriteableRegistry(combine(Processors.getNamedWriteables(), SqlHitExtractors.getNamedWriteables())); } @Override @@ -72,7 +73,7 @@ protected ComputingExtractor mutateInstance(ComputingExtractor instance) throws public void testGet() { String fieldName = randomAlphaOfLength(5); ChainingProcessor extractor = new ChainingProcessor( - new HitExtractorProcessor(new FieldHitExtractor(fieldName, DataType.DOUBLE, UTC, true, false)), + new HitExtractorProcessor(new FieldHitExtractor(fieldName, DOUBLE, UTC, true, false)), new MathProcessor(MathOperation.LOG)); int times = between(1, 1000); @@ -85,4 +86,4 @@ public void testGet() { assertEquals(expected, extractor.process(hit)); } } -} +} \ No newline at end of file diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/extractor/FieldHitExtractorTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/extractor/FieldHitExtractorTests.java index 2544a02926089..e52ef992d547f 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/extractor/FieldHitExtractorTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/extractor/FieldHitExtractorTests.java @@ -12,10 +12,10 @@ import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.search.SearchHit; import org.elasticsearch.test.ESTestCase; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; import org.elasticsearch.xpack.sql.AbstractSqlWireSerializingTestCase; -import org.elasticsearch.xpack.sql.SqlException; -import org.elasticsearch.xpack.sql.expression.function.scalar.geo.GeoShape; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.sql.expression.literal.geo.GeoShape; +import org.elasticsearch.xpack.sql.type.SqlDataTypes; import org.elasticsearch.xpack.sql.util.DateUtils; import java.io.IOException; @@ -34,6 +34,10 @@ import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; +import static org.elasticsearch.xpack.ql.type.DataTypes.DATETIME; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.GEO_POINT; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.GEO_SHAPE; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.SHAPE; import static org.elasticsearch.xpack.sql.util.DateUtils.UTC; import static org.hamcrest.Matchers.is; @@ -65,7 +69,7 @@ protected FieldHitExtractor mutateInstance(FieldHitExtractor instance) { return new FieldHitExtractor( instance.fieldName() + "mutated", instance.fullFieldName() + "mutated", - randomValueOtherThan(instance.dataType(), () -> randomFrom(DataType.values())), + randomValueOtherThan(instance.dataType(), () -> randomFrom(SqlDataTypes.types())), randomValueOtherThan(instance.zoneId(), ESTestCase::randomZone), randomBoolean(), instance.hitName() + "mutated", @@ -164,7 +168,7 @@ public void testGetDate() { SearchHit hit = new SearchHit(1); DocumentField field = new DocumentField("my_date_field", documentFieldValues); hit.fields(singletonMap("my_date_field", field)); - FieldHitExtractor extractor = new FieldHitExtractor("my_date_field", DataType.DATETIME, zoneId, true); + FieldHitExtractor extractor = new FieldHitExtractor("my_date_field", DATETIME, zoneId, true); assertEquals(DateUtils.asDateTime(millis, zoneId), extractor.extract(hit)); } @@ -194,7 +198,7 @@ public void testGetSource() throws IOException { public void testToString() { assertEquals("hit.field@hit@Europe/Berlin", - new FieldHitExtractor("hit.field", null, null, ZoneId.of("Europe/Berlin"), true, "hit", false).toString()); + new FieldHitExtractor("hit.field", null, null, ZoneId.of("Europe/Berlin"), true, "hit", false).toString()); } public void testMultiValuedDocValue() { @@ -203,7 +207,7 @@ public void testMultiValuedDocValue() { SearchHit hit = new SearchHit(1); DocumentField field = new DocumentField(fieldName, asList("a", "b")); hit.fields(singletonMap(fieldName, field)); - SqlException ex = expectThrows(SqlException.class, () -> fe.extract(hit)); + QlIllegalArgumentException ex = expectThrows(QlIllegalArgumentException.class, () -> fe.extract(hit)); assertThat(ex.getMessage(), is("Arrays (returned by [" + fieldName + "]) are not supported")); } @@ -218,7 +222,7 @@ public void testMultiValuedSourceValue() throws IOException { source.endObject(); BytesReference sourceRef = BytesReference.bytes(source); hit.sourceRef(sourceRef); - SqlException ex = expectThrows(SqlException.class, () -> fe.extract(hit)); + QlIllegalArgumentException ex = expectThrows(QlIllegalArgumentException.class, () -> fe.extract(hit)); assertThat(ex.getMessage(), is("Arrays (returned by [" + fieldName + "]) are not supported")); } @@ -248,7 +252,7 @@ public void testExtractSourceIncorrectPath() { FieldHitExtractor fe = getFieldHitExtractor("a.b.c.d", false); Object value = randomNonNullValue(); Map map = singletonMap("a", singletonMap("b", singletonMap("c", value))); - SqlException ex = expectThrows(SqlException.class, () -> fe.extractFromSource(map)); + QlIllegalArgumentException ex = expectThrows(QlIllegalArgumentException.class, () -> fe.extractFromSource(map)); assertThat(ex.getMessage(), is("Cannot extract value [a.b.c.d] from source")); } @@ -256,7 +260,7 @@ public void testMultiValuedSource() { FieldHitExtractor fe = getFieldHitExtractor("a", false); Object value = randomValue(); Map map = singletonMap("a", asList(value, value)); - SqlException ex = expectThrows(SqlException.class, () -> fe.extractFromSource(map)); + QlIllegalArgumentException ex = expectThrows(QlIllegalArgumentException.class, () -> fe.extractFromSource(map)); assertThat(ex.getMessage(), is("Arrays (returned by [a]) are not supported")); } @@ -352,7 +356,7 @@ public void testNestedFieldsWithDotsAndRandomHierarchy() { } else { // if we have an array with more than one value in it, check that we throw the correct exception and exception message final Map map2 = Collections.unmodifiableMap(map); - SqlException ex = expectThrows(SqlException.class, () -> fe.extractFromSource(map2)); + QlIllegalArgumentException ex = expectThrows(QlIllegalArgumentException.class, () -> fe.extractFromSource(map2)); assertThat(ex.getMessage(), is("Arrays (returned by [" + expected + "]) are not supported")); } } @@ -361,7 +365,7 @@ public void testExtractSourceIncorrectPathWithFieldWithDots() { FieldHitExtractor fe = getFieldHitExtractor("a.b.c.d.e", false); Object value = randomNonNullValue(); Map map = singletonMap("a", singletonMap("b.c", singletonMap("d", value))); - SqlException ex = expectThrows(SqlException.class, () -> fe.extractFromSource(map)); + QlIllegalArgumentException ex = expectThrows(QlIllegalArgumentException.class, () -> fe.extractFromSource(map)); assertThat(ex.getMessage(), is("Cannot extract value [a.b.c.d.e] from source")); } @@ -393,7 +397,7 @@ public void testFieldWithDotsAndSamePathButDifferentHierarchy() { Map map = new HashMap<>(); map.put("a.b", singletonMap("c", singletonMap("d.e", singletonMap("f.g", value)))); map.put("a", singletonMap("b.c", singletonMap("d.e", singletonMap("f", singletonMap("g", value))))); - SqlException ex = expectThrows(SqlException.class, () -> fe.extractFromSource(map)); + QlIllegalArgumentException ex = expectThrows(QlIllegalArgumentException.class, () -> fe.extractFromSource(map)); assertThat(ex.getMessage(), is("Multiple values (returned by [a.b.c.d.e.f.g]) are not supported")); } @@ -411,7 +415,7 @@ public void testFieldsWithMultiValueArrayAsSubfield() { Map map = new HashMap<>(); // "a" : [{"b" : "value1"}, {"b" : "value2"}] map.put("a", asList(singletonMap("b", randomNonNullValue()), singletonMap("b", randomNonNullValue()))); - SqlException ex = expectThrows(SqlException.class, () -> fe.extractFromSource(map)); + QlIllegalArgumentException ex = expectThrows(QlIllegalArgumentException.class, () -> fe.extractFromSource(map)); assertThat(ex.getMessage(), is("Arrays (returned by [a.b]) are not supported")); } @@ -429,7 +433,7 @@ public void testFieldsWithMultiValueArrayAsSubfield_ThreeNestedLists() { Map map = new HashMap<>(); // "a" : [{"b" : [{"c" : ["value1", "value2"]}]}] map.put("a", singletonList(singletonMap("b", singletonList(singletonMap("c", asList("value1", "value2")))))); - SqlException ex = expectThrows(SqlException.class, () -> fe.extractFromSource(map)); + QlIllegalArgumentException ex = expectThrows(QlIllegalArgumentException.class, () -> fe.extractFromSource(map)); assertThat(ex.getMessage(), is("Arrays (returned by [a.b.c]) are not supported")); } @@ -456,13 +460,13 @@ public void testObjectsForSourceValue() throws IOException { source.endObject(); BytesReference sourceRef = BytesReference.bytes(source); hit.sourceRef(sourceRef); - SqlException ex = expectThrows(SqlException.class, () -> fe.extract(hit)); + QlIllegalArgumentException ex = expectThrows(QlIllegalArgumentException.class, () -> fe.extract(hit)); assertThat(ex.getMessage(), is("Objects (returned by [" + fieldName + "]) are not supported")); } public void testGeoShapeExtraction() { String fieldName = randomAlphaOfLength(5); - FieldHitExtractor fe = new FieldHitExtractor(fieldName, randomBoolean() ? DataType.GEO_SHAPE : DataType.SHAPE, UTC, false); + FieldHitExtractor fe = new FieldHitExtractor(fieldName, randomBoolean() ? GEO_SHAPE : SHAPE, UTC, false); Map map = new HashMap<>(); map.put(fieldName, "POINT (1 2)"); assertEquals(new GeoShape(1, 2), fe.extractFromSource(map)); @@ -474,7 +478,7 @@ public void testGeoShapeExtraction() { public void testMultipleGeoShapeExtraction() { String fieldName = randomAlphaOfLength(5); - FieldHitExtractor fe = new FieldHitExtractor(fieldName, randomBoolean() ? DataType.GEO_SHAPE : DataType.SHAPE, UTC, false); + FieldHitExtractor fe = new FieldHitExtractor(fieldName, randomBoolean() ? GEO_SHAPE : SHAPE, UTC, false); Map map = new HashMap<>(); map.put(fieldName, "POINT (1 2)"); assertEquals(new GeoShape(1, 2), fe.extractFromSource(map)); @@ -484,11 +488,11 @@ public void testMultipleGeoShapeExtraction() { Map map2 = new HashMap<>(); map2.put(fieldName, Arrays.asList("POINT (1 2)", "POINT (3 4)")); - SqlException ex = expectThrows(SqlException.class, () -> fe.extractFromSource(map2)); + QlIllegalArgumentException ex = expectThrows(QlIllegalArgumentException.class, () -> fe.extractFromSource(map2)); assertThat(ex.getMessage(), is("Arrays (returned by [" + fieldName + "]) are not supported")); FieldHitExtractor lenientFe = new FieldHitExtractor(fieldName, - randomBoolean() ? DataType.GEO_SHAPE : DataType.SHAPE, UTC, false, true); + randomBoolean() ? GEO_SHAPE : SHAPE, UTC, false, true); assertEquals(new GeoShape(1, 2), lenientFe.extractFromSource(map2)); } @@ -525,7 +529,7 @@ public void testGeoPointExtractionFromSource() throws IOException { BytesReference sourceRef = BytesReference.bytes(source); hit.sourceRef(sourceRef); - FieldHitExtractor fe = new FieldHitExtractor(pathCombined, DataType.GEO_POINT, UTC, false); + FieldHitExtractor fe = new FieldHitExtractor(pathCombined, GEO_POINT, UTC, false); assertEquals(new GeoShape(lon, lat), fe.extract(hit)); } @@ -548,17 +552,17 @@ public void testMultipleGeoPointExtractionFromSource() throws IOException { BytesReference sourceRef = BytesReference.bytes(source); hit.sourceRef(sourceRef); - FieldHitExtractor fe = new FieldHitExtractor(fieldName, DataType.GEO_POINT, UTC, false); - SqlException ex = expectThrows(SqlException.class, () -> fe.extract(hit)); + FieldHitExtractor fe = new FieldHitExtractor(fieldName, GEO_POINT, UTC, false); + QlIllegalArgumentException ex = expectThrows(QlIllegalArgumentException.class, () -> fe.extract(hit)); assertThat(ex.getMessage(), is("Arrays (returned by [" + fieldName + "]) are not supported")); - FieldHitExtractor lenientFe = new FieldHitExtractor(fieldName, DataType.GEO_POINT, UTC, false, true); + FieldHitExtractor lenientFe = new FieldHitExtractor(fieldName, GEO_POINT, UTC, false, true); assertEquals(new GeoShape(lon, lat), lenientFe.extract(hit)); } public void testGeoPointExtractionFromDocValues() { String fieldName = randomAlphaOfLength(5); - FieldHitExtractor fe = new FieldHitExtractor(fieldName, DataType.GEO_POINT, UTC, true); + FieldHitExtractor fe = new FieldHitExtractor(fieldName, GEO_POINT, UTC, true); SearchHit hit = new SearchHit(1); DocumentField field = new DocumentField(fieldName, singletonList("2, 1")); hit.fields(singletonMap(fieldName, field)); @@ -570,13 +574,13 @@ public void testGeoPointExtractionFromDocValues() { public void testGeoPointExtractionFromMultipleDocValues() { String fieldName = randomAlphaOfLength(5); SearchHit hit = new SearchHit(1); - FieldHitExtractor fe = new FieldHitExtractor(fieldName, DataType.GEO_POINT, UTC, true); + FieldHitExtractor fe = new FieldHitExtractor(fieldName, GEO_POINT, UTC, true); hit.fields(singletonMap(fieldName, new DocumentField(fieldName, Arrays.asList("2,1", "3,4")))); - SqlException ex = expectThrows(SqlException.class, () -> fe.extract(hit)); + QlIllegalArgumentException ex = expectThrows(QlIllegalArgumentException.class, () -> fe.extract(hit)); assertThat(ex.getMessage(), is("Arrays (returned by [" + fieldName + "]) are not supported")); - FieldHitExtractor lenientFe = new FieldHitExtractor(fieldName, DataType.GEO_POINT, UTC, true, true); + FieldHitExtractor lenientFe = new FieldHitExtractor(fieldName, GEO_POINT, UTC, true, true); assertEquals(new GeoShape(1, 2), lenientFe.extract(hit)); } diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/extractor/MetricAggExtractorTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/extractor/MetricAggExtractorTests.java index 53e9fdc53664c..d4951b0f618a0 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/extractor/MetricAggExtractorTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/extractor/MetricAggExtractorTests.java @@ -10,8 +10,9 @@ import org.elasticsearch.search.aggregations.Aggregations; import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation.Bucket; import org.elasticsearch.test.ESTestCase; +import org.elasticsearch.xpack.ql.execution.search.extractor.BucketExtractor; import org.elasticsearch.xpack.sql.AbstractSqlWireSerializingTestCase; -import org.elasticsearch.xpack.sql.SqlException; +import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; import org.elasticsearch.xpack.sql.util.DateUtils; import java.io.IOException; @@ -54,14 +55,13 @@ protected MetricAggExtractor mutateInstance(MetricAggExtractor instance) throws instance.name() + "mutated", instance.property() + "mutated", instance.innerKey() + "mutated", - randomValueOtherThan(instance.zoneId(), - ESTestCase::randomZone), randomBoolean()); + randomValueOtherThan(instance.zoneId(), ESTestCase::randomZone), randomBoolean()); } public void testNoAggs() { Bucket bucket = new TestBucket(emptyMap(), 0, new Aggregations(emptyList())); MetricAggExtractor extractor = randomMetricAggExtractor(); - SqlException exception = expectThrows(SqlException.class, () -> extractor.extract(bucket)); + SqlIllegalArgumentException exception = expectThrows(SqlIllegalArgumentException.class, () -> extractor.extract(bucket)); assertEquals("Cannot find an aggregation named " + extractor.name(), exception.getMessage()); } diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/extractor/TopHitsAggExtractorTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/extractor/TopHitsAggExtractorTests.java index 0dacdb665e77e..dd4158080fea0 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/extractor/TopHitsAggExtractorTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/extractor/TopHitsAggExtractorTests.java @@ -15,9 +15,10 @@ import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation.Bucket; import org.elasticsearch.search.aggregations.metrics.InternalTopHits; import org.elasticsearch.test.ESTestCase; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.AbstractSqlWireSerializingTestCase; -import org.elasticsearch.xpack.sql.SqlException; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; +import org.elasticsearch.xpack.sql.type.SqlDataTypes; import org.elasticsearch.xpack.sql.util.DateUtils; import java.time.ZoneId; @@ -31,7 +32,7 @@ public class TopHitsAggExtractorTests extends AbstractSqlWireSerializingTestCase { public static TopHitsAggExtractor randomTopHitsAggExtractor() { - return new TopHitsAggExtractor(randomAlphaOfLength(16), randomFrom(DataType.values()), randomZone()); + return new TopHitsAggExtractor(randomAlphaOfLength(16), randomFrom(SqlDataTypes.types()), randomZone()); } @Override @@ -53,14 +54,14 @@ protected ZoneId instanceZoneId(TopHitsAggExtractor instance) { protected TopHitsAggExtractor mutateInstance(TopHitsAggExtractor instance) { return new TopHitsAggExtractor( instance.name() + "mutated", - randomValueOtherThan(instance.fieldDataType(), () -> randomFrom(DataType.values())), + randomValueOtherThan(instance.fieldDataType(), () -> randomFrom(SqlDataTypes.types())), randomValueOtherThan(instance.zoneId(), ESTestCase::randomZone)); } public void testNoAggs() { Bucket bucket = new TestBucket(emptyMap(), 0, new Aggregations(emptyList())); TopHitsAggExtractor extractor = randomTopHitsAggExtractor(); - SqlException exception = expectThrows(SqlException.class, () -> extractor.extract(bucket)); + SqlIllegalArgumentException exception = expectThrows(SqlIllegalArgumentException.class, () -> extractor.extract(bucket)); assertEquals("Cannot find an aggregation named " + extractor.name(), exception.getMessage()); } @@ -74,7 +75,7 @@ public void testZeroNullValue() { } public void testExtractValue() { - TopHitsAggExtractor extractor = new TopHitsAggExtractor("topHitsAgg", DataType.KEYWORD, UTC); + TopHitsAggExtractor extractor = new TopHitsAggExtractor("topHitsAgg", DataTypes.KEYWORD, UTC); String value = "Str_Value"; Aggregation agg = new InternalTopHits(extractor.name(), 0, 1, null, searchHitsOf(value), null, null); @@ -84,7 +85,7 @@ public void testExtractValue() { public void testExtractDateValue() { ZoneId zoneId = randomZone(); - TopHitsAggExtractor extractor = new TopHitsAggExtractor("topHitsAgg", DataType.DATETIME, zoneId); + TopHitsAggExtractor extractor = new TopHitsAggExtractor("topHitsAgg", DataTypes.DATETIME, zoneId); long value = 123456789L; Aggregation agg = new InternalTopHits(extractor.name(), 0, 1, null, searchHitsOf(value), null, null); diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/ProcessorTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/ProcessorTests.java index a01178fbc5b79..913565f681c7a 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/ProcessorTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/ProcessorTests.java @@ -8,30 +8,31 @@ import org.elasticsearch.common.io.stream.NamedWriteable; import org.elasticsearch.test.ESTestCase; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; import org.elasticsearch.xpack.sql.expression.function.scalar.Processors; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import org.elasticsearch.xpack.sql.tree.NodeSubclassTests; +import org.elasticsearch.xpack.sql.tree.SqlNodeSubclassTests; import org.junit.BeforeClass; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; +import java.util.Set; import static java.util.stream.Collectors.toCollection; - public class ProcessorTests extends ESTestCase { - private static List> processors; + private static Set> processors; @BeforeClass public static void init() throws Exception { - processors = NodeSubclassTests.subclassesOf(Processor.class); + processors = SqlNodeSubclassTests.subclassesOf(Processor.class); } public void testProcessorRegistration() throws Exception { LinkedHashSet registered = Processors.getNamedWriteables().stream() + .filter(e -> Processor.class == e.categoryClass) .map(e -> e.name) .collect(toCollection(LinkedHashSet::new)); @@ -39,6 +40,7 @@ public void testProcessorRegistration() throws Exception { int missing = processors.size() - registered.size(); List notRegistered = new ArrayList<>(); + Set processorNames = new LinkedHashSet<>(); for (Class proc : processors) { String procName = proc.getName(); assertTrue(procName + " does NOT implement NamedWriteable", NamedWriteable.class.isAssignableFrom(proc)); @@ -54,6 +56,7 @@ public void testProcessorRegistration() throws Exception { } catch (Exception ex) { fail(procName + " does NOT provide a static NAME field\n" + ex); } + processorNames.add(value); if (!registered.contains(value)) { notRegistered.add(procName); } @@ -61,10 +64,16 @@ public void testProcessorRegistration() throws Exception { assertEquals("Processor: " + proc + " doesn't override getWriteableName", proc, declaringClass); } - if (missing > 0) { + if (notRegistered.isEmpty() == false) { fail(missing + " processor(s) not registered : " + notRegistered); } else { - assertEquals("Detection failed: discovered more registered processors than classes", 0, missing); + // FIXME: the project split causes different behaviour between Gradle vs IDEs + // Eclipse considers classes from both projects, Gradle does not + // hence why this is disabled for now + registered.removeAll(processorNames); + if (registered.isEmpty() == false) { + fail("Detection failed: discovered more registered processors than actual classes; extra " + registered); + } } } } diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/TyperResolutionTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/TypeResolutionTests.java similarity index 63% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/TyperResolutionTests.java rename to x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/TypeResolutionTests.java index 1340332505444..e4c1a43410fe9 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/TyperResolutionTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/TypeResolutionTests.java @@ -7,21 +7,18 @@ package org.elasticsearch.xpack.sql.expression; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.expression.Expression.TypeResolution; -import org.elasticsearch.xpack.sql.expression.literal.IntervalYearMonth; +import org.elasticsearch.xpack.ql.expression.Expression.TypeResolution; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.sql.SqlTestUtils; +import org.elasticsearch.xpack.sql.expression.literal.interval.IntervalYearMonth; import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Mul; -import org.elasticsearch.xpack.sql.type.DataType; import java.time.Period; -import static org.elasticsearch.xpack.sql.tree.Source.EMPTY; +import static org.elasticsearch.xpack.ql.tree.Source.EMPTY; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_YEAR_TO_MONTH; -public class TyperResolutionTests extends ESTestCase { - - public void testMulNumeric() { - Mul m = new Mul(EMPTY, L(1), L(2)); - assertEquals(TypeResolution.TYPE_RESOLVED, m.typeResolved()); - } +public class TypeResolutionTests extends ESTestCase { public void testMulIntervalAndNumber() { Mul m = new Mul(EMPTY, L(1), randomYearInterval()); @@ -39,10 +36,10 @@ public void testMulTypeResolution() throws Exception { } private static Literal randomYearInterval() { - return Literal.of(EMPTY, new IntervalYearMonth(Period.ofMonths(randomInt(123)), DataType.INTERVAL_YEAR_TO_MONTH)); + return L(new IntervalYearMonth(Period.ofMonths(randomInt(123)), INTERVAL_YEAR_TO_MONTH)); } private static Literal L(Object value) { - return Literal.of(EMPTY, value); + return SqlTestUtils.literal(value); } } diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/CastProcessorTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/CastProcessorTests.java index 7e9cb64b01950..fb4441af3cec0 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/CastProcessorTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/CastProcessorTests.java @@ -8,14 +8,15 @@ import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.Writeable.Reader; import org.elasticsearch.test.AbstractWireSerializingTestCase; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.type.DataTypeConversion.Conversion; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.type.DataTypeConverter.DefaultConverter; +import org.elasticsearch.xpack.sql.type.SqlDataTypeConverter.SqlConverter; import java.io.IOException; public class CastProcessorTests extends AbstractWireSerializingTestCase { public static CastProcessor randomCastProcessor() { - return new CastProcessor(randomFrom(Conversion.values())); + return new CastProcessor(randomFrom(SqlConverter.values())); } @Override @@ -30,19 +31,19 @@ protected Reader instanceReader() { @Override protected CastProcessor mutateInstance(CastProcessor instance) throws IOException { - return new CastProcessor(randomValueOtherThan(instance.converter(), () -> randomFrom(Conversion.values()))); + return new CastProcessor(randomValueOtherThan(instance.converter(), () -> randomFrom(SqlConverter.values()))); } public void testApply() { { - CastProcessor proc = new CastProcessor(Conversion.STRING_TO_INT); + CastProcessor proc = new CastProcessor(DefaultConverter.STRING_TO_INT); assertEquals(null, proc.process(null)); assertEquals(1, proc.process("1")); - Exception e = expectThrows(SqlIllegalArgumentException.class, () -> proc.process("1.2")); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> proc.process("1.2")); assertEquals("cannot cast [1.2] to [integer]", e.getMessage()); } { - CastProcessor proc = new CastProcessor(Conversion.BOOL_TO_INT); + CastProcessor proc = new CastProcessor(DefaultConverter.BOOL_TO_INT); assertEquals(null, proc.process(null)); assertEquals(1, proc.process(true)); assertEquals(0, proc.process(false)); diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/DatabaseFunctionTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/DatabaseFunctionTests.java index 8ad04d83c4c45..706f1c2fc6b97 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/DatabaseFunctionTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/DatabaseFunctionTests.java @@ -7,20 +7,20 @@ package org.elasticsearch.xpack.sql.expression.function.scalar; import org.elasticsearch.test.ESTestCase; +import org.elasticsearch.xpack.ql.expression.Alias; +import org.elasticsearch.xpack.ql.expression.NamedExpression; +import org.elasticsearch.xpack.ql.index.EsIndex; +import org.elasticsearch.xpack.ql.index.IndexResolution; +import org.elasticsearch.xpack.ql.plan.logical.Project; import org.elasticsearch.xpack.sql.analysis.analyzer.Analyzer; import org.elasticsearch.xpack.sql.analysis.analyzer.Verifier; -import org.elasticsearch.xpack.sql.analysis.index.EsIndex; -import org.elasticsearch.xpack.sql.analysis.index.IndexResolution; -import org.elasticsearch.xpack.sql.expression.Alias; -import org.elasticsearch.xpack.sql.expression.NamedExpression; -import org.elasticsearch.xpack.sql.expression.function.FunctionRegistry; +import org.elasticsearch.xpack.sql.expression.function.SqlFunctionRegistry; import org.elasticsearch.xpack.sql.parser.SqlParser; -import org.elasticsearch.xpack.sql.plan.logical.Project; import org.elasticsearch.xpack.sql.proto.Mode; import org.elasticsearch.xpack.sql.proto.Protocol; import org.elasticsearch.xpack.sql.session.Configuration; import org.elasticsearch.xpack.sql.stats.Metrics; -import org.elasticsearch.xpack.sql.type.TypesTests; +import org.elasticsearch.xpack.sql.types.SqlTypesTests; import org.elasticsearch.xpack.sql.util.DateUtils; public class DatabaseFunctionTests extends ESTestCase { @@ -28,13 +28,13 @@ public class DatabaseFunctionTests extends ESTestCase { public void testDatabaseFunctionOutput() { String clusterName = randomAlphaOfLengthBetween(1, 15); SqlParser parser = new SqlParser(); - EsIndex test = new EsIndex("test", TypesTests.loadMapping("mapping-basic.json", true)); + EsIndex test = new EsIndex("test", SqlTypesTests.loadMapping("mapping-basic.json", true)); Analyzer analyzer = new Analyzer( new Configuration(DateUtils.UTC, Protocol.FETCH_SIZE, Protocol.REQUEST_TIMEOUT, Protocol.PAGE_TIMEOUT, null, randomFrom(Mode.values()), randomAlphaOfLength(10), null, clusterName, randomBoolean(), randomBoolean()), - new FunctionRegistry(), + new SqlFunctionRegistry(), IndexResolution.valid(test), new Verifier(new Metrics()) ); diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/UserFunctionTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/UserFunctionTests.java index a6e8d83a336f7..f3dcc1d402d0b 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/UserFunctionTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/UserFunctionTests.java @@ -7,34 +7,34 @@ package org.elasticsearch.xpack.sql.expression.function.scalar; import org.elasticsearch.test.ESTestCase; +import org.elasticsearch.xpack.ql.expression.Alias; +import org.elasticsearch.xpack.ql.expression.NamedExpression; +import org.elasticsearch.xpack.ql.index.EsIndex; +import org.elasticsearch.xpack.ql.index.IndexResolution; +import org.elasticsearch.xpack.ql.plan.logical.Project; import org.elasticsearch.xpack.sql.analysis.analyzer.Analyzer; import org.elasticsearch.xpack.sql.analysis.analyzer.Verifier; -import org.elasticsearch.xpack.sql.analysis.index.EsIndex; -import org.elasticsearch.xpack.sql.analysis.index.IndexResolution; -import org.elasticsearch.xpack.sql.expression.Alias; -import org.elasticsearch.xpack.sql.expression.NamedExpression; -import org.elasticsearch.xpack.sql.expression.function.FunctionRegistry; +import org.elasticsearch.xpack.sql.expression.function.SqlFunctionRegistry; import org.elasticsearch.xpack.sql.parser.SqlParser; -import org.elasticsearch.xpack.sql.plan.logical.Project; import org.elasticsearch.xpack.sql.proto.Mode; import org.elasticsearch.xpack.sql.proto.Protocol; import org.elasticsearch.xpack.sql.session.Configuration; import org.elasticsearch.xpack.sql.stats.Metrics; -import org.elasticsearch.xpack.sql.type.TypesTests; +import org.elasticsearch.xpack.sql.types.SqlTypesTests; import org.elasticsearch.xpack.sql.util.DateUtils; public class UserFunctionTests extends ESTestCase { public void testNoUsernameFunctionOutput() { SqlParser parser = new SqlParser(); - EsIndex test = new EsIndex("test", TypesTests.loadMapping("mapping-basic.json", true)); + EsIndex test = new EsIndex("test", SqlTypesTests.loadMapping("mapping-basic.json", true)); Analyzer analyzer = new Analyzer( new Configuration(DateUtils.UTC, Protocol.FETCH_SIZE, Protocol.REQUEST_TIMEOUT, Protocol.PAGE_TIMEOUT, null, randomFrom(Mode.values()), randomAlphaOfLength(10), null, randomAlphaOfLengthBetween(1, 15), randomBoolean(), randomBoolean()), - new FunctionRegistry(), + new SqlFunctionRegistry(), IndexResolution.valid(test), new Verifier(new Metrics()) ); diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/CurrentDateTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/CurrentDateTests.java index ff65414bf58ca..792fb2ddefa6d 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/CurrentDateTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/CurrentDateTests.java @@ -6,10 +6,10 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; -import org.elasticsearch.xpack.sql.TestUtils; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.tree.AbstractNodeTestCase; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.tree.AbstractNodeTestCase; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.sql.SqlTestUtils; import java.time.ZoneId; import java.time.ZonedDateTime; @@ -18,7 +18,7 @@ public class CurrentDateTests extends AbstractNodeTestCase { public static CurrentDate randomCurrentDate() { - return new CurrentDate(Source.EMPTY, TestUtils.randomConfiguration()); + return new CurrentDate(Source.EMPTY, SqlTestUtils.randomConfiguration()); } @Override @@ -36,7 +36,7 @@ protected CurrentDate mutate(CurrentDate instance) { ZonedDateTime now = instance.configuration().now(); ZoneId mutatedZoneId = randomValueOtherThanMany(o -> Objects.equals(now.getOffset(), o.getRules().getOffset(now.toInstant())), () -> randomZone()); - return new CurrentDate(instance.source(), TestUtils.randomConfiguration(mutatedZoneId)); + return new CurrentDate(instance.source(), SqlTestUtils.randomConfiguration(mutatedZoneId)); } @Override diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/CurrentDateTimeTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/CurrentDateTimeTests.java index 166490699bb97..ab6a182be36d9 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/CurrentDateTimeTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/CurrentDateTimeTests.java @@ -7,32 +7,32 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.TestUtils; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.index.EsIndex; +import org.elasticsearch.xpack.ql.index.IndexResolution; +import org.elasticsearch.xpack.ql.session.Configuration; +import org.elasticsearch.xpack.ql.tree.AbstractNodeTestCase; +import org.elasticsearch.xpack.sql.SqlTestUtils; import org.elasticsearch.xpack.sql.analysis.analyzer.Analyzer; import org.elasticsearch.xpack.sql.analysis.analyzer.Verifier; -import org.elasticsearch.xpack.sql.analysis.index.EsIndex; -import org.elasticsearch.xpack.sql.analysis.index.IndexResolution; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.expression.function.FunctionRegistry; +import org.elasticsearch.xpack.sql.expression.function.SqlFunctionRegistry; import org.elasticsearch.xpack.sql.parser.ParsingException; import org.elasticsearch.xpack.sql.parser.SqlParser; -import org.elasticsearch.xpack.sql.session.Configuration; import org.elasticsearch.xpack.sql.stats.Metrics; -import org.elasticsearch.xpack.sql.tree.AbstractNodeTestCase; -import org.elasticsearch.xpack.sql.type.TypesTests; +import org.elasticsearch.xpack.sql.types.SqlTypesTests; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.temporal.ChronoField; import java.util.Objects; -import static org.elasticsearch.xpack.sql.tree.Source.EMPTY; +import static org.elasticsearch.xpack.ql.tree.Source.EMPTY; +import static org.elasticsearch.xpack.sql.SqlTestUtils.literal; public class CurrentDateTimeTests extends AbstractNodeTestCase { public static CurrentDateTime randomCurrentDateTime() { - return new CurrentDateTime(EMPTY, Literal.of(EMPTY, randomInt(9)), TestUtils.randomConfiguration()); + return new CurrentDateTime(EMPTY, literal(randomInt(9)), SqlTestUtils.randomConfiguration()); } @Override @@ -50,7 +50,7 @@ protected CurrentDateTime mutate(CurrentDateTime instance) { ZonedDateTime now = instance.configuration().now(); ZoneId mutatedZoneId = randomValueOtherThanMany(o -> Objects.equals(now.getOffset(), o.getRules().getOffset(now.toInstant())), ESTestCase::randomZone); - return new CurrentDateTime(instance.source(), Literal.of(EMPTY, randomInt(9)), TestUtils.randomConfiguration(mutatedZoneId)); + return new CurrentDateTime(instance.source(), literal(randomInt(9)), SqlTestUtils.randomConfiguration(mutatedZoneId)); } @Override @@ -63,20 +63,20 @@ public void testReplaceChildren() { public void testNanoPrecision() { ZonedDateTime zdt = ZonedDateTime.parse("2018-01-23T12:34:45.123456789Z"); - assertEquals(000_000_000, CurrentDateTime.nanoPrecision(zdt, Literal.of(EMPTY, 0)).getNano()); - assertEquals(100_000_000, CurrentDateTime.nanoPrecision(zdt, Literal.of(EMPTY, 1)).getNano()); - assertEquals(120_000_000, CurrentDateTime.nanoPrecision(zdt, Literal.of(EMPTY, 2)).getNano()); - assertEquals(123_000_000, CurrentDateTime.nanoPrecision(zdt, Literal.of(EMPTY, 3)).getNano()); - assertEquals(123_400_000, CurrentDateTime.nanoPrecision(zdt, Literal.of(EMPTY, 4)).getNano()); - assertEquals(123_450_000, CurrentDateTime.nanoPrecision(zdt, Literal.of(EMPTY, 5)).getNano()); - assertEquals(123_456_000, CurrentDateTime.nanoPrecision(zdt, Literal.of(EMPTY, 6)).getNano()); - assertEquals(123_456_700, CurrentDateTime.nanoPrecision(zdt, Literal.of(EMPTY, 7)).getNano()); - assertEquals(123_456_780, CurrentDateTime.nanoPrecision(zdt, Literal.of(EMPTY, 8)).getNano()); - assertEquals(123_456_789, CurrentDateTime.nanoPrecision(zdt, Literal.of(EMPTY, 9)).getNano()); + assertEquals(000_000_000, CurrentDateTime.nanoPrecision(zdt, literal(0)).getNano()); + assertEquals(100_000_000, CurrentDateTime.nanoPrecision(zdt, literal(1)).getNano()); + assertEquals(120_000_000, CurrentDateTime.nanoPrecision(zdt, literal(2)).getNano()); + assertEquals(123_000_000, CurrentDateTime.nanoPrecision(zdt, literal(3)).getNano()); + assertEquals(123_400_000, CurrentDateTime.nanoPrecision(zdt, literal(4)).getNano()); + assertEquals(123_450_000, CurrentDateTime.nanoPrecision(zdt, literal(5)).getNano()); + assertEquals(123_456_000, CurrentDateTime.nanoPrecision(zdt, literal(6)).getNano()); + assertEquals(123_456_700, CurrentDateTime.nanoPrecision(zdt, literal(7)).getNano()); + assertEquals(123_456_780, CurrentDateTime.nanoPrecision(zdt, literal(8)).getNano()); + assertEquals(123_456_789, CurrentDateTime.nanoPrecision(zdt, literal(9)).getNano()); } public void testDefaultPrecision() { - Configuration configuration = TestUtils.randomConfiguration(); + Configuration configuration = SqlTestUtils.randomConfiguration(); // null precision means default precision CurrentDateTime cdt = new CurrentDateTime(EMPTY, null, configuration); ZonedDateTime now = configuration.now(); @@ -89,9 +89,9 @@ public void testDefaultPrecision() { public void testInvalidPrecision() { SqlParser parser = new SqlParser(); IndexResolution indexResolution = IndexResolution.valid(new EsIndex("test", - TypesTests.loadMapping("mapping-multi-field-with-nested.json"))); + SqlTypesTests.loadMapping("mapping-multi-field-with-nested.json"))); - Analyzer analyzer = new Analyzer(TestUtils.TEST_CFG, new FunctionRegistry(), indexResolution, new Verifier(new Metrics())); + Analyzer analyzer = new Analyzer(SqlTestUtils.TEST_CFG, new SqlFunctionRegistry(), indexResolution, new Verifier(new Metrics())); ParsingException e = expectThrows(ParsingException.class, () -> analyzer.analyze(parser.createStatement("SELECT CURRENT_TIMESTAMP(100000000000000)"), true)); assertEquals("line 1:27: invalid precision; [100000000000000] out of [integer] range", e.getMessage()); diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/CurrentTimeTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/CurrentTimeTests.java index 8603a3c6dd9c1..b1fc816974712 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/CurrentTimeTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/CurrentTimeTests.java @@ -7,20 +7,19 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.TestUtils; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.index.EsIndex; +import org.elasticsearch.xpack.ql.index.IndexResolution; +import org.elasticsearch.xpack.ql.session.Configuration; +import org.elasticsearch.xpack.ql.tree.AbstractNodeTestCase; +import org.elasticsearch.xpack.sql.SqlTestUtils; import org.elasticsearch.xpack.sql.analysis.analyzer.Analyzer; import org.elasticsearch.xpack.sql.analysis.analyzer.Verifier; -import org.elasticsearch.xpack.sql.analysis.index.EsIndex; -import org.elasticsearch.xpack.sql.analysis.index.IndexResolution; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.expression.function.FunctionRegistry; +import org.elasticsearch.xpack.sql.expression.function.SqlFunctionRegistry; import org.elasticsearch.xpack.sql.parser.ParsingException; import org.elasticsearch.xpack.sql.parser.SqlParser; -import org.elasticsearch.xpack.sql.session.Configuration; import org.elasticsearch.xpack.sql.stats.Metrics; -import org.elasticsearch.xpack.sql.tree.AbstractNodeTestCase; -import org.elasticsearch.xpack.sql.type.TypesTests; +import org.elasticsearch.xpack.sql.types.SqlTypesTests; import java.time.OffsetTime; import java.time.ZoneId; @@ -28,12 +27,13 @@ import java.time.temporal.ChronoField; import java.util.Objects; -import static org.elasticsearch.xpack.sql.tree.Source.EMPTY; +import static org.elasticsearch.xpack.ql.tree.Source.EMPTY; +import static org.elasticsearch.xpack.sql.SqlTestUtils.literal; public class CurrentTimeTests extends AbstractNodeTestCase { public static CurrentTime randomCurrentTime() { - return new CurrentTime(EMPTY, Literal.of(EMPTY, randomInt(9)), TestUtils.randomConfiguration()); + return new CurrentTime(EMPTY, literal(randomInt(9)), SqlTestUtils.randomConfiguration()); } @Override @@ -51,7 +51,7 @@ protected CurrentTime mutate(CurrentTime instance) { ZonedDateTime now = instance.configuration().now(); ZoneId mutatedZoneId = randomValueOtherThanMany(o -> Objects.equals(now.getOffset(), o.getRules().getOffset(now.toInstant())), ESTestCase::randomZone); - return new CurrentTime(instance.source(), Literal.of(EMPTY, randomInt(9)), TestUtils.randomConfiguration(mutatedZoneId)); + return new CurrentTime(instance.source(), literal(randomInt(9)), SqlTestUtils.randomConfiguration(mutatedZoneId)); } @Override @@ -64,20 +64,20 @@ public void testReplaceChildren() { public void testNanoPrecision() { OffsetTime ot = OffsetTime.parse("12:34:45.123456789Z"); - assertEquals(000_000_000, CurrentTime.nanoPrecision(ot, Literal.of(EMPTY, 0)).getNano()); - assertEquals(100_000_000, CurrentTime.nanoPrecision(ot, Literal.of(EMPTY, 1)).getNano()); - assertEquals(120_000_000, CurrentTime.nanoPrecision(ot, Literal.of(EMPTY, 2)).getNano()); - assertEquals(123_000_000, CurrentTime.nanoPrecision(ot, Literal.of(EMPTY, 3)).getNano()); - assertEquals(123_400_000, CurrentTime.nanoPrecision(ot, Literal.of(EMPTY, 4)).getNano()); - assertEquals(123_450_000, CurrentTime.nanoPrecision(ot, Literal.of(EMPTY, 5)).getNano()); - assertEquals(123_456_000, CurrentTime.nanoPrecision(ot, Literal.of(EMPTY, 6)).getNano()); - assertEquals(123_456_700, CurrentTime.nanoPrecision(ot, Literal.of(EMPTY, 7)).getNano()); - assertEquals(123_456_780, CurrentTime.nanoPrecision(ot, Literal.of(EMPTY, 8)).getNano()); - assertEquals(123_456_789, CurrentTime.nanoPrecision(ot, Literal.of(EMPTY, 9)).getNano()); + assertEquals(000_000_000, CurrentTime.nanoPrecision(ot, literal(0)).getNano()); + assertEquals(100_000_000, CurrentTime.nanoPrecision(ot, literal(1)).getNano()); + assertEquals(120_000_000, CurrentTime.nanoPrecision(ot, literal(2)).getNano()); + assertEquals(123_000_000, CurrentTime.nanoPrecision(ot, literal(3)).getNano()); + assertEquals(123_400_000, CurrentTime.nanoPrecision(ot, literal(4)).getNano()); + assertEquals(123_450_000, CurrentTime.nanoPrecision(ot, literal(5)).getNano()); + assertEquals(123_456_000, CurrentTime.nanoPrecision(ot, literal(6)).getNano()); + assertEquals(123_456_700, CurrentTime.nanoPrecision(ot, literal(7)).getNano()); + assertEquals(123_456_780, CurrentTime.nanoPrecision(ot, literal(8)).getNano()); + assertEquals(123_456_789, CurrentTime.nanoPrecision(ot, literal(9)).getNano()); } public void testDefaultPrecision() { - Configuration configuration = TestUtils.randomConfiguration(); + Configuration configuration = SqlTestUtils.randomConfiguration(); // null precision means default precision CurrentTime ct = new CurrentTime(EMPTY, null, configuration); ZonedDateTime now = configuration.now(); @@ -90,9 +90,9 @@ public void testDefaultPrecision() { public void testInvalidPrecision() { SqlParser parser = new SqlParser(); IndexResolution indexResolution = IndexResolution.valid(new EsIndex("test", - TypesTests.loadMapping("mapping-multi-field-with-nested.json"))); + SqlTypesTests.loadMapping("mapping-multi-field-with-nested.json"))); - Analyzer analyzer = new Analyzer(TestUtils.TEST_CFG, new FunctionRegistry(), indexResolution, new Verifier(new Metrics())); + Analyzer analyzer = new Analyzer(SqlTestUtils.TEST_CFG, new SqlFunctionRegistry(), indexResolution, new Verifier(new Metrics())); ParsingException e = expectThrows(ParsingException.class, () -> analyzer.analyze(parser.createStatement("SELECT CURRENT_TIME(100000000000000)"), true)); assertEquals("line 1:22: invalid precision; [100000000000000] out of [integer] range", e.getMessage()); diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateAddPipeTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateAddPipeTests.java index 6e2d2ca62dbf5..ed49dca2f884d 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateAddPipeTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateAddPipeTests.java @@ -7,12 +7,12 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.tree.AbstractNodeTestCase; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.SourceTests; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.tree.AbstractNodeTestCase; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.tree.SourceTests; import java.time.ZoneId; import java.util.ArrayList; @@ -20,11 +20,11 @@ import java.util.Objects; import java.util.function.Function; -import static org.elasticsearch.xpack.sql.expression.Expressions.pipe; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.randomDatetimeLiteral; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.randomIntLiteral; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.randomStringLiteral; -import static org.elasticsearch.xpack.sql.tree.SourceTests.randomSource; +import static org.elasticsearch.xpack.ql.expression.Expressions.pipe; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomDatetimeLiteral; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomIntLiteral; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomStringLiteral; +import static org.elasticsearch.xpack.ql.tree.SourceTests.randomSource; public class DateAddPipeTests extends AbstractNodeTestCase { diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateAddProcessorTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateAddProcessorTests.java index 1902c7f5953c5..81cce0585fe3f 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateAddProcessorTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateAddProcessorTests.java @@ -8,19 +8,19 @@ import org.elasticsearch.common.io.stream.Writeable.Reader; import org.elasticsearch.test.ESTestCase; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.gen.processor.ConstantProcessor; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.AbstractSqlWireSerializingTestCase; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.expression.gen.processor.ConstantProcessor; -import org.elasticsearch.xpack.sql.tree.Source; import java.time.ZoneId; import java.time.ZonedDateTime; -import static org.elasticsearch.xpack.sql.expression.Literal.NULL; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.l; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.randomDatetimeLiteral; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.randomIntLiteral; +import static org.elasticsearch.xpack.ql.expression.Literal.NULL; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.l; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomDatetimeLiteral; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomIntLiteral; import static org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTimeTestUtils.dateTime; import static org.elasticsearch.xpack.sql.proto.StringUtils.ISO_DATE_WITH_NANOS; diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateDiffPipeTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateDiffPipeTests.java index a80eb47b21db0..d95da899726b6 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateDiffPipeTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateDiffPipeTests.java @@ -7,12 +7,12 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.tree.AbstractNodeTestCase; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.SourceTests; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.tree.AbstractNodeTestCase; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.tree.SourceTests; import java.time.ZoneId; import java.util.ArrayList; @@ -20,10 +20,10 @@ import java.util.Objects; import java.util.function.Function; -import static org.elasticsearch.xpack.sql.expression.Expressions.pipe; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.randomDatetimeLiteral; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.randomStringLiteral; -import static org.elasticsearch.xpack.sql.tree.SourceTests.randomSource; +import static org.elasticsearch.xpack.ql.expression.Expressions.pipe; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomDatetimeLiteral; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomStringLiteral; +import static org.elasticsearch.xpack.ql.tree.SourceTests.randomSource; public class DateDiffPipeTests extends AbstractNodeTestCase { diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateDiffProcessorTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateDiffProcessorTests.java index 19d329cc42415..a2d3ab658154a 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateDiffProcessorTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateDiffProcessorTests.java @@ -8,17 +8,17 @@ import org.elasticsearch.common.io.stream.Writeable.Reader; import org.elasticsearch.test.ESTestCase; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.gen.processor.ConstantProcessor; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.AbstractSqlWireSerializingTestCase; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.expression.gen.processor.ConstantProcessor; -import org.elasticsearch.xpack.sql.tree.Source; import java.time.ZoneId; -import static org.elasticsearch.xpack.sql.expression.Literal.NULL; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.l; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.randomDatetimeLiteral; +import static org.elasticsearch.xpack.ql.expression.Literal.NULL; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.l; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomDatetimeLiteral; import static org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTimeTestUtils.dateTime; import static org.elasticsearch.xpack.sql.util.DateUtils.UTC; diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DatePartPipeTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DatePartPipeTests.java index e6a5b3c9d142b..16c5d259d0743 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DatePartPipeTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DatePartPipeTests.java @@ -7,13 +7,13 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.BinaryPipe; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.tree.AbstractNodeTestCase; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.SourceTests; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.BinaryPipe; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.tree.AbstractNodeTestCase; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.tree.SourceTests; import java.time.ZoneId; import java.util.ArrayList; @@ -21,10 +21,10 @@ import java.util.Objects; import java.util.function.Function; -import static org.elasticsearch.xpack.sql.expression.Expressions.pipe; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.randomDatetimeLiteral; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.randomStringLiteral; -import static org.elasticsearch.xpack.sql.tree.SourceTests.randomSource; +import static org.elasticsearch.xpack.ql.expression.Expressions.pipe; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomDatetimeLiteral; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomStringLiteral; +import static org.elasticsearch.xpack.ql.tree.SourceTests.randomSource; public class DatePartPipeTests extends AbstractNodeTestCase { diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DatePartProcessorTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DatePartProcessorTests.java index fca8c27cc8751..48dd62c034b13 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DatePartProcessorTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DatePartProcessorTests.java @@ -8,17 +8,17 @@ import org.elasticsearch.common.io.stream.Writeable.Reader; import org.elasticsearch.test.ESTestCase; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.gen.processor.ConstantProcessor; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.AbstractSqlWireSerializingTestCase; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.expression.gen.processor.ConstantProcessor; -import org.elasticsearch.xpack.sql.tree.Source; import java.time.ZoneId; -import static org.elasticsearch.xpack.sql.expression.Literal.NULL; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.l; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.randomDatetimeLiteral; +import static org.elasticsearch.xpack.ql.expression.Literal.NULL; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.l; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomDatetimeLiteral; import static org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTimeTestUtils.dateTime; public class DatePartProcessorTests extends AbstractSqlWireSerializingTestCase { diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTimeTestUtils.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTimeTestUtils.java index 6570e108666f4..515ac3ac826d5 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTimeTestUtils.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTimeTestUtils.java @@ -36,10 +36,6 @@ public static ZonedDateTime dateTime(long millisSinceEpoch) { return DateUtils.asDateTime(millisSinceEpoch); } - public static ZonedDateTime date(long millisSinceEpoch) { - return DateUtils.asDateOnly(millisSinceEpoch); - } - public static OffsetTime time(long millisSinceEpoch) { return DateUtils.asTimeOnly(millisSinceEpoch); } diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTruncPipeTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTruncPipeTests.java index 08836f98afc76..8b250c86d0ac5 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTruncPipeTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTruncPipeTests.java @@ -7,13 +7,13 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.BinaryPipe; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.tree.AbstractNodeTestCase; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.SourceTests; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.BinaryPipe; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.tree.AbstractNodeTestCase; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.tree.SourceTests; import java.time.ZoneId; import java.util.ArrayList; @@ -21,10 +21,10 @@ import java.util.Objects; import java.util.function.Function; -import static org.elasticsearch.xpack.sql.expression.Expressions.pipe; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.randomDatetimeLiteral; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.randomStringLiteral; -import static org.elasticsearch.xpack.sql.tree.SourceTests.randomSource; +import static org.elasticsearch.xpack.ql.expression.Expressions.pipe; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomDatetimeLiteral; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomStringLiteral; +import static org.elasticsearch.xpack.ql.tree.SourceTests.randomSource; public class DateTruncPipeTests extends AbstractNodeTestCase { diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTruncProcessorTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTruncProcessorTests.java index cbc76419c58c6..9c7f11499a9dd 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTruncProcessorTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTruncProcessorTests.java @@ -8,19 +8,19 @@ import org.elasticsearch.common.io.stream.Writeable.Reader; import org.elasticsearch.test.ESTestCase; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.gen.processor.ConstantProcessor; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.AbstractSqlWireSerializingTestCase; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.expression.gen.processor.ConstantProcessor; -import org.elasticsearch.xpack.sql.tree.Source; import org.elasticsearch.xpack.sql.util.DateUtils; import java.time.ZoneId; import java.time.ZonedDateTime; -import static org.elasticsearch.xpack.sql.expression.Literal.NULL; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.l; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.randomDatetimeLiteral; +import static org.elasticsearch.xpack.ql.expression.Literal.NULL; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.l; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomDatetimeLiteral; import static org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTimeTestUtils.dateTime; import static org.elasticsearch.xpack.sql.proto.StringUtils.ISO_DATE_WITH_NANOS; diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DayOfYearTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DayOfYearTests.java index 7168716b529ea..4a0abd148f8d6 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DayOfYearTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DayOfYearTests.java @@ -6,9 +6,9 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.datetime; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataTypes; import java.time.ZoneId; @@ -28,6 +28,6 @@ private Object extract(Object value, ZoneId zoneId) { } private DayOfYear build(Object value, ZoneId zoneId) { - return new DayOfYear(Source.EMPTY, new Literal(Source.EMPTY, value, DataType.DATETIME), zoneId); + return new DayOfYear(Source.EMPTY, new Literal(Source.EMPTY, value, DataTypes.DATETIME), zoneId); } } diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/GeoProcessorTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/GeoProcessorTests.java index b14a61945cf41..ba3f81ef538b1 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/GeoProcessorTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/GeoProcessorTests.java @@ -9,6 +9,7 @@ import org.elasticsearch.test.AbstractWireSerializingTestCase; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; import org.elasticsearch.xpack.sql.expression.function.scalar.geo.GeoProcessor.GeoOperation; +import org.elasticsearch.xpack.sql.expression.literal.geo.GeoShape; import java.io.IOException; diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StDistanceProcessorTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StDistanceProcessorTests.java index 9f78f8b3df43b..59f26970e64aa 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StDistanceProcessorTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StDistanceProcessorTests.java @@ -9,18 +9,21 @@ import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.test.AbstractWireSerializingTestCase; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.gen.processor.ChainingProcessor; +import org.elasticsearch.xpack.ql.expression.gen.processor.ConstantProcessor; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.type.DataTypes; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; import org.elasticsearch.xpack.sql.expression.function.scalar.Processors; -import org.elasticsearch.xpack.sql.expression.gen.processor.ChainingProcessor; -import org.elasticsearch.xpack.sql.expression.gen.processor.ConstantProcessor; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.sql.expression.literal.geo.GeoShape; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.l; -import static org.elasticsearch.xpack.sql.tree.Source.EMPTY; +import static org.elasticsearch.xpack.ql.tree.Source.EMPTY; import static org.hamcrest.Matchers.instanceOf; public class StDistanceProcessorTests extends AbstractWireSerializingTestCase { + @Override public StDistanceProcessor createTestInstance() { return new StDistanceProcessor( constantPoint(randomDoubleBetween(-180, 180, true), randomDoubleBetween(-90, 90, true)), @@ -44,6 +47,10 @@ public void testApply() { assertEquals(GeoUtils.arcDistance(20, 10, 40, 30), (double) result, 0.000001); } + public static Literal l(Object value) { + return new Literal(EMPTY, value, DataTypes.fromJava(value)); + } + public void testNullHandling() { assertNull(new StDistance(EMPTY, l(new GeoShape(1, 2)), l(null)).makePipe().asProcessor().process(null)); assertNull(new StDistance(EMPTY, l(null), l(new GeoShape(1, 2))).makePipe().asProcessor().process(null)); diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StWkttosqlProcessorTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StWkttosqlProcessorTests.java index 8c2d61ed80094..76e3ab5228356 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StWkttosqlProcessorTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/geo/StWkttosqlProcessorTests.java @@ -6,7 +6,8 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.geo; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.sql.expression.literal.geo.GeoShape; import static org.hamcrest.Matchers.instanceOf; @@ -26,17 +27,17 @@ public void testApply() { public void testTypeCheck() { StWkttosqlProcessor procPoint = new StWkttosqlProcessor(); - SqlIllegalArgumentException siae = expectThrows(SqlIllegalArgumentException.class, () -> procPoint.process(42)); + QlIllegalArgumentException siae = expectThrows(QlIllegalArgumentException.class, () -> procPoint.process(42)); assertEquals("A string is required; received [42]", siae.getMessage()); - siae = expectThrows(SqlIllegalArgumentException.class, () -> procPoint.process("some random string")); + siae = expectThrows(QlIllegalArgumentException.class, () -> procPoint.process("some random string")); assertEquals("Cannot parse [some random string] as a geo_shape value", siae.getMessage()); - siae = expectThrows(SqlIllegalArgumentException.class, () -> procPoint.process("point (foo bar)")); + siae = expectThrows(QlIllegalArgumentException.class, () -> procPoint.process("point (foo bar)")); assertEquals("Cannot parse [point (foo bar)] as a geo_shape or shape value", siae.getMessage()); - siae = expectThrows(SqlIllegalArgumentException.class, () -> procPoint.process("point (10 10")); + siae = expectThrows(QlIllegalArgumentException.class, () -> procPoint.process("point (10 10")); assertEquals("Cannot parse [point (10 10] as a geo_shape or shape value", siae.getMessage()); } diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/BinaryMathProcessorTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/BinaryMathProcessorTests.java index ab1a9bf1f5cea..c6314f28e272b 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/BinaryMathProcessorTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/BinaryMathProcessorTests.java @@ -8,13 +8,14 @@ import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.Writeable.Reader; import org.elasticsearch.test.AbstractWireSerializingTestCase; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.gen.processor.ConstantProcessor; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.Literal; +import org.elasticsearch.xpack.sql.SqlTestUtils; import org.elasticsearch.xpack.sql.expression.function.scalar.Processors; -import org.elasticsearch.xpack.sql.expression.gen.processor.ConstantProcessor; -import org.elasticsearch.xpack.sql.expression.gen.processor.Processor; -import static org.elasticsearch.xpack.sql.tree.Source.EMPTY; +import static org.elasticsearch.xpack.ql.tree.Source.EMPTY; public class BinaryMathProcessorTests extends AbstractWireSerializingTestCase { public static BinaryMathProcessor randomProcessor() { @@ -118,6 +119,6 @@ public void testHandleNull() { } private static Literal l(Object value) { - return Literal.of(EMPTY, value); + return SqlTestUtils.literal(value); } } \ No newline at end of file diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/MathOperationTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/MathOperationTests.java new file mode 100644 index 0000000000000..3c1c880a8b457 --- /dev/null +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/MathOperationTests.java @@ -0,0 +1,38 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.sql.expression.function.scalar.math; + +import org.elasticsearch.test.ESTestCase; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation; + +public class MathOperationTests extends ESTestCase { + + public void testAbsLongMax() { + QlIllegalArgumentException ex = expectThrows(QlIllegalArgumentException.class, () -> MathOperation.ABS.apply(Long.MIN_VALUE)); + assertTrue(ex.getMessage().contains("cannot be negated")); + } + + public void testAbsIntegerMax() { + QlIllegalArgumentException ex = expectThrows(QlIllegalArgumentException.class, () -> MathOperation.ABS.apply(Integer.MIN_VALUE)); + assertTrue(ex.getMessage().contains("cannot be negated")); + } + + public void testAbsShortMax() { + QlIllegalArgumentException ex = expectThrows(QlIllegalArgumentException.class, () -> MathOperation.ABS.apply(Short.MIN_VALUE)); + assertTrue(ex.getMessage().contains("out of")); + } + + public void testAbsPreservesType() { + assertEquals((byte) 42, MathOperation.ABS.apply((byte) -42)); + assertEquals((short) 42, MathOperation.ABS.apply((short) -42)); + assertEquals(42, MathOperation.ABS.apply(-42)); + assertEquals((long) 42, MathOperation.ABS.apply((long) -42)); + assertEquals(42f, MathOperation.ABS.apply(-42f)); + assertEquals(42d, MathOperation.ABS.apply(-42d)); + } +} diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringNumericPipeTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringNumericPipeTests.java index e35403eabbafe..e9e92126e9081 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringNumericPipeTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringNumericPipeTests.java @@ -6,22 +6,22 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.BinaryPipe; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.tree.AbstractNodeTestCase; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.expression.function.scalar.string.BinaryStringNumericProcessor.BinaryStringNumericOperation; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.BinaryPipe; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.tree.AbstractNodeTestCase; -import org.elasticsearch.xpack.sql.tree.Source; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.function.Function; -import static org.elasticsearch.xpack.sql.expression.Expressions.pipe; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.randomIntLiteral; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.randomStringLiteral; -import static org.elasticsearch.xpack.sql.tree.SourceTests.randomSource; +import static org.elasticsearch.xpack.ql.expression.Expressions.pipe; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomIntLiteral; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomStringLiteral; +import static org.elasticsearch.xpack.ql.tree.SourceTests.randomSource; public class BinaryStringNumericPipeTests extends AbstractNodeTestCase { diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringNumericProcessorTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringNumericProcessorTests.java index 42e6c4694255f..4b9f89016625f 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringNumericProcessorTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringNumericProcessorTests.java @@ -9,13 +9,13 @@ import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.Writeable.Reader; import org.elasticsearch.test.AbstractWireSerializingTestCase; +import org.elasticsearch.xpack.ql.expression.gen.processor.ConstantProcessor; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; import org.elasticsearch.xpack.sql.expression.function.scalar.Processors; import org.elasticsearch.xpack.sql.expression.function.scalar.string.BinaryStringNumericProcessor.BinaryStringNumericOperation; -import org.elasticsearch.xpack.sql.expression.gen.processor.ConstantProcessor; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.l; -import static org.elasticsearch.xpack.sql.tree.Source.EMPTY; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.l; +import static org.elasticsearch.xpack.ql.tree.Source.EMPTY; public class BinaryStringNumericProcessorTests extends AbstractWireSerializingTestCase { diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringStringPipeTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringStringPipeTests.java index ef878fce39550..a12f909754631 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringStringPipeTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringStringPipeTests.java @@ -6,20 +6,20 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.BinaryPipe; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.tree.AbstractNodeTestCase; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.BinaryPipe; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.tree.AbstractNodeTestCase; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.function.Function; -import static org.elasticsearch.xpack.sql.expression.Expressions.pipe; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.randomStringLiteral; -import static org.elasticsearch.xpack.sql.tree.SourceTests.randomSource; +import static org.elasticsearch.xpack.ql.expression.Expressions.pipe; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomStringLiteral; +import static org.elasticsearch.xpack.ql.tree.SourceTests.randomSource; public class BinaryStringStringPipeTests extends AbstractNodeTestCase { diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringStringProcessorTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringStringProcessorTests.java index 3422d5bddefc6..63778e3cf016f 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringStringProcessorTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringStringProcessorTests.java @@ -9,13 +9,13 @@ import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.Writeable.Reader; import org.elasticsearch.test.AbstractWireSerializingTestCase; +import org.elasticsearch.xpack.ql.expression.gen.processor.ConstantProcessor; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; import org.elasticsearch.xpack.sql.expression.function.scalar.Processors; import org.elasticsearch.xpack.sql.expression.function.scalar.string.BinaryStringStringProcessor.BinaryStringStringOperation; -import org.elasticsearch.xpack.sql.expression.gen.processor.ConstantProcessor; -import static org.elasticsearch.xpack.sql.tree.Source.EMPTY; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.l; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.l; +import static org.elasticsearch.xpack.ql.tree.Source.EMPTY; public class BinaryStringStringProcessorTests extends AbstractWireSerializingTestCase { diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ConcatFunctionPipeTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ConcatFunctionPipeTests.java index 931fd11b0340b..54e0c262cdbf9 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ConcatFunctionPipeTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ConcatFunctionPipeTests.java @@ -6,20 +6,20 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.BinaryPipe; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.tree.AbstractNodeTestCase; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.BinaryPipe; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.tree.AbstractNodeTestCase; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.function.Function; -import static org.elasticsearch.xpack.sql.expression.Expressions.pipe; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.randomStringLiteral; -import static org.elasticsearch.xpack.sql.tree.SourceTests.randomSource; +import static org.elasticsearch.xpack.ql.expression.Expressions.pipe; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomStringLiteral; +import static org.elasticsearch.xpack.ql.tree.SourceTests.randomSource; public class ConcatFunctionPipeTests extends AbstractNodeTestCase { diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ConcatProcessorTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ConcatProcessorTests.java index 891428587d19c..a0fb5607c9f50 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ConcatProcessorTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ConcatProcessorTests.java @@ -9,12 +9,12 @@ import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.Writeable.Reader; import org.elasticsearch.test.AbstractWireSerializingTestCase; +import org.elasticsearch.xpack.ql.expression.gen.processor.ConstantProcessor; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; import org.elasticsearch.xpack.sql.expression.function.scalar.Processors; -import org.elasticsearch.xpack.sql.expression.gen.processor.ConstantProcessor; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.l; -import static org.elasticsearch.xpack.sql.tree.Source.EMPTY; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.l; +import static org.elasticsearch.xpack.ql.tree.Source.EMPTY; public class ConcatProcessorTests extends AbstractWireSerializingTestCase { diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/InsertFunctionPipeTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/InsertFunctionPipeTests.java index fbb8c33061d93..cef922936796a 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/InsertFunctionPipeTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/InsertFunctionPipeTests.java @@ -6,11 +6,11 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.Combinations; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.tree.AbstractNodeTestCase; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.Combinations; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.tree.AbstractNodeTestCase; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.ArrayList; import java.util.BitSet; @@ -18,10 +18,10 @@ import java.util.Objects; import java.util.function.Function; -import static org.elasticsearch.xpack.sql.expression.Expressions.pipe; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.randomIntLiteral; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.randomStringLiteral; -import static org.elasticsearch.xpack.sql.tree.SourceTests.randomSource; +import static org.elasticsearch.xpack.ql.expression.Expressions.pipe; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomIntLiteral; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomStringLiteral; +import static org.elasticsearch.xpack.ql.tree.SourceTests.randomSource; public class InsertFunctionPipeTests extends AbstractNodeTestCase { diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/InsertProcessorTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/InsertProcessorTests.java index b9ffdf59e82fd..c617e5b435b01 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/InsertProcessorTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/InsertProcessorTests.java @@ -9,12 +9,12 @@ import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.Writeable.Reader; import org.elasticsearch.test.AbstractWireSerializingTestCase; +import org.elasticsearch.xpack.ql.expression.gen.processor.ConstantProcessor; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; import org.elasticsearch.xpack.sql.expression.function.scalar.Processors; -import org.elasticsearch.xpack.sql.expression.gen.processor.ConstantProcessor; -import static org.elasticsearch.xpack.sql.tree.Source.EMPTY; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.l; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.l; +import static org.elasticsearch.xpack.ql.tree.Source.EMPTY; public class InsertProcessorTests extends AbstractWireSerializingTestCase { diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/LocateFunctionPipeTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/LocateFunctionPipeTests.java index 3795aab2cd18f..8ee073a291205 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/LocateFunctionPipeTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/LocateFunctionPipeTests.java @@ -6,11 +6,11 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.Combinations; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.tree.AbstractNodeTestCase; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.Combinations; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.tree.AbstractNodeTestCase; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.ArrayList; import java.util.BitSet; @@ -18,10 +18,10 @@ import java.util.Objects; import java.util.function.Function; -import static org.elasticsearch.xpack.sql.expression.Expressions.pipe; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.randomIntLiteral; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.randomStringLiteral; -import static org.elasticsearch.xpack.sql.tree.SourceTests.randomSource; +import static org.elasticsearch.xpack.ql.expression.Expressions.pipe; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomIntLiteral; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomStringLiteral; +import static org.elasticsearch.xpack.ql.tree.SourceTests.randomSource; public class LocateFunctionPipeTests extends AbstractNodeTestCase { diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/LocateProcessorTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/LocateProcessorTests.java index 7a43dd8bf3824..ba7787b4727e9 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/LocateProcessorTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/LocateProcessorTests.java @@ -9,12 +9,12 @@ import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.Writeable.Reader; import org.elasticsearch.test.AbstractWireSerializingTestCase; +import org.elasticsearch.xpack.ql.expression.gen.processor.ConstantProcessor; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; import org.elasticsearch.xpack.sql.expression.function.scalar.Processors; -import org.elasticsearch.xpack.sql.expression.gen.processor.ConstantProcessor; -import static org.elasticsearch.xpack.sql.tree.Source.EMPTY; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.l; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.l; +import static org.elasticsearch.xpack.ql.tree.Source.EMPTY; public class LocateProcessorTests extends AbstractWireSerializingTestCase { diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ReplaceFunctionPipeTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ReplaceFunctionPipeTests.java index 3c352669a0637..b06f65ad3895f 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ReplaceFunctionPipeTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ReplaceFunctionPipeTests.java @@ -6,11 +6,11 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.Combinations; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.tree.AbstractNodeTestCase; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.Combinations; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.tree.AbstractNodeTestCase; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.ArrayList; import java.util.BitSet; @@ -18,9 +18,9 @@ import java.util.Objects; import java.util.function.Function; -import static org.elasticsearch.xpack.sql.expression.Expressions.pipe; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.randomStringLiteral; -import static org.elasticsearch.xpack.sql.tree.SourceTests.randomSource; +import static org.elasticsearch.xpack.ql.expression.Expressions.pipe; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomStringLiteral; +import static org.elasticsearch.xpack.ql.tree.SourceTests.randomSource; public class ReplaceFunctionPipeTests extends AbstractNodeTestCase { diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ReplaceProcessorTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ReplaceProcessorTests.java index 66b6af11d1f91..aae6f38ee925f 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ReplaceProcessorTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ReplaceProcessorTests.java @@ -9,12 +9,12 @@ import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.Writeable.Reader; import org.elasticsearch.test.AbstractWireSerializingTestCase; +import org.elasticsearch.xpack.ql.expression.gen.processor.ConstantProcessor; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; import org.elasticsearch.xpack.sql.expression.function.scalar.Processors; -import org.elasticsearch.xpack.sql.expression.gen.processor.ConstantProcessor; -import static org.elasticsearch.xpack.sql.tree.Source.EMPTY; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.l; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.l; +import static org.elasticsearch.xpack.ql.tree.Source.EMPTY; public class ReplaceProcessorTests extends AbstractWireSerializingTestCase { diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/SubstringFunctionPipeTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/SubstringFunctionPipeTests.java index 22199fab0b4d8..2bc69b33f1d82 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/SubstringFunctionPipeTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/SubstringFunctionPipeTests.java @@ -6,11 +6,11 @@ package org.elasticsearch.xpack.sql.expression.function.scalar.string; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.Combinations; -import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe; -import org.elasticsearch.xpack.sql.tree.AbstractNodeTestCase; -import org.elasticsearch.xpack.sql.tree.Source; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.Combinations; +import org.elasticsearch.xpack.ql.expression.gen.pipeline.Pipe; +import org.elasticsearch.xpack.ql.tree.AbstractNodeTestCase; +import org.elasticsearch.xpack.ql.tree.Source; import java.util.ArrayList; import java.util.BitSet; @@ -18,10 +18,10 @@ import java.util.Objects; import java.util.function.Function; -import static org.elasticsearch.xpack.sql.expression.Expressions.pipe; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.randomIntLiteral; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.randomStringLiteral; -import static org.elasticsearch.xpack.sql.tree.SourceTests.randomSource; +import static org.elasticsearch.xpack.ql.expression.Expressions.pipe; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomIntLiteral; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomStringLiteral; +import static org.elasticsearch.xpack.ql.tree.SourceTests.randomSource; public class SubstringFunctionPipeTests extends AbstractNodeTestCase { diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/SubstringProcessorTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/SubstringProcessorTests.java index 839817fb2103b..17a4a6e9261da 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/SubstringProcessorTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/SubstringProcessorTests.java @@ -9,12 +9,12 @@ import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.Writeable.Reader; import org.elasticsearch.test.AbstractWireSerializingTestCase; +import org.elasticsearch.xpack.ql.expression.gen.processor.ConstantProcessor; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; import org.elasticsearch.xpack.sql.expression.function.scalar.Processors; -import org.elasticsearch.xpack.sql.expression.gen.processor.ConstantProcessor; -import static org.elasticsearch.xpack.sql.tree.Source.EMPTY; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.l; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.l; +import static org.elasticsearch.xpack.ql.tree.Source.EMPTY; public class SubstringProcessorTests extends AbstractWireSerializingTestCase { diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/literal/IntervalsTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/literal/interval/IntervalsTests.java similarity index 88% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/literal/IntervalsTests.java rename to x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/literal/interval/IntervalsTests.java index 2140e27c8c2ff..3cb8143162ad1 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/literal/IntervalsTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/literal/interval/IntervalsTests.java @@ -4,13 +4,13 @@ * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression.literal; +package org.elasticsearch.xpack.sql.expression.literal.interval; import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.expression.literal.Intervals.TimeUnit; -import org.elasticsearch.xpack.sql.parser.ParsingException; +import org.elasticsearch.xpack.ql.ParsingException; +import org.elasticsearch.xpack.sql.expression.literal.interval.Intervals.TimeUnit; import java.time.Duration; import java.time.Period; @@ -20,23 +20,23 @@ import static java.lang.String.format; import static java.util.stream.Collectors.toList; -import static org.elasticsearch.xpack.sql.expression.literal.Intervals.intervalType; -import static org.elasticsearch.xpack.sql.expression.literal.Intervals.of; -import static org.elasticsearch.xpack.sql.expression.literal.Intervals.parseInterval; -import static org.elasticsearch.xpack.sql.tree.Source.EMPTY; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_DAY; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_DAY_TO_HOUR; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_DAY_TO_MINUTE; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_DAY_TO_SECOND; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_HOUR; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_HOUR_TO_MINUTE; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_HOUR_TO_SECOND; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_MINUTE; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_MINUTE_TO_SECOND; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_MONTH; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_SECOND; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_YEAR; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_YEAR_TO_MONTH; +import static org.elasticsearch.xpack.ql.tree.Source.EMPTY; +import static org.elasticsearch.xpack.sql.expression.literal.interval.Intervals.intervalType; +import static org.elasticsearch.xpack.sql.expression.literal.interval.Intervals.of; +import static org.elasticsearch.xpack.sql.expression.literal.interval.Intervals.parseInterval; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_DAY; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_DAY_TO_HOUR; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_DAY_TO_MINUTE; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_DAY_TO_SECOND; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_HOUR; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_HOUR_TO_MINUTE; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_HOUR_TO_SECOND; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_MINUTE; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_MINUTE_TO_SECOND; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_MONTH; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_SECOND; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_YEAR; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_YEAR_TO_MONTH; public class IntervalsTests extends ESTestCase { diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/ParameterTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/parser/ParameterTests.java similarity index 72% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/ParameterTests.java rename to x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/parser/ParameterTests.java index 97b7415786341..cb3784a1fa916 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/ParameterTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/parser/ParameterTests.java @@ -3,49 +3,49 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression; +package org.elasticsearch.xpack.sql.expression.parser; import org.elasticsearch.test.ESTestCase; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.Equals; import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Add; import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Mul; import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Sub; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.Equals; import org.elasticsearch.xpack.sql.parser.ParsingException; import org.elasticsearch.xpack.sql.parser.SqlParser; import org.elasticsearch.xpack.sql.proto.SqlTypedParamValue; -import org.elasticsearch.xpack.sql.type.DataType; import java.util.Arrays; import java.util.Collections; +import static org.elasticsearch.xpack.ql.type.DataTypes.KEYWORD; +import static org.elasticsearch.xpack.ql.type.DataTypes.LONG; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; - public class ParameterTests extends ESTestCase { public void testSingleParameter() { Expression expression = new SqlParser().createExpression("a = \n?", Collections.singletonList( - new SqlTypedParamValue(DataType.KEYWORD.typeName, "foo") + new SqlTypedParamValue(KEYWORD.typeName(), "foo") )); logger.info(expression); assertThat(expression, instanceOf(Equals.class)); Expression right = ((Equals) expression).right(); assertThat(right, instanceOf(Literal.class)); Literal param = (Literal) right; - assertThat(param.dataType(), equalTo(DataType.KEYWORD)); - assertThat(param.dataType(), equalTo(DataType.KEYWORD)); + assertThat(param.dataType(), equalTo(KEYWORD)); + assertThat(param.dataType(), equalTo(KEYWORD)); assertThat(param.value(), equalTo("foo")); } public void testMultipleParameters() { Expression expression = new SqlParser().createExpression("(? + ? * ?) - ?", Arrays.asList( - new SqlTypedParamValue(DataType.LONG.typeName, 1L), - new SqlTypedParamValue(DataType.LONG.typeName, 2L), - new SqlTypedParamValue(DataType.LONG.typeName, 3L), - new SqlTypedParamValue(DataType.LONG.typeName, 4L) + new SqlTypedParamValue(LONG.typeName(), 1L), new SqlTypedParamValue(LONG.typeName(), 2L), + new SqlTypedParamValue(LONG.typeName(), 3L), new SqlTypedParamValue(LONG.typeName(), 4L) )); assertThat(expression, instanceOf(Sub.class)); Sub sub = (Sub) expression; @@ -62,9 +62,8 @@ public void testMultipleParameters() { public void testNotEnoughParameters() { ParsingException ex = expectThrows(ParsingException.class, () -> new SqlParser().createExpression("(? + ? * ?) - ?", Arrays.asList( - new SqlTypedParamValue(DataType.LONG.typeName, 1L), - new SqlTypedParamValue(DataType.LONG.typeName, 2L), - new SqlTypedParamValue(DataType.LONG.typeName, 3L) + new SqlTypedParamValue(LONG.typeName(), 1L), new SqlTypedParamValue(LONG.typeName(), 2L), + new SqlTypedParamValue(LONG.typeName(), 3L) ))); assertThat(ex.getMessage(), containsString("Not enough actual parameters")); } diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/QuotingTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/parser/QuotingTests.java similarity index 91% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/QuotingTests.java rename to x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/parser/QuotingTests.java index a7cae7df4312b..aef9525058b3a 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/QuotingTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/parser/QuotingTests.java @@ -3,26 +3,28 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -package org.elasticsearch.xpack.sql.expression; +package org.elasticsearch.xpack.sql.expression.parser; import org.elasticsearch.test.ESTestCase; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.UnresolvedAttribute; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.plan.logical.OrderBy; +import org.elasticsearch.xpack.ql.tree.Source; import org.elasticsearch.xpack.sql.parser.ParsingException; import org.elasticsearch.xpack.sql.parser.SqlParser; -import org.elasticsearch.xpack.sql.plan.logical.LogicalPlan; -import org.elasticsearch.xpack.sql.plan.logical.OrderBy; -import org.elasticsearch.xpack.sql.tree.Source; import java.util.ArrayList; import java.util.List; +import static org.elasticsearch.common.logging.LoggerMessageFormat.format; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; -import static org.elasticsearch.common.logging.LoggerMessageFormat.format; - public class QuotingTests extends ESTestCase { private static UnresolvedAttribute from(String s) { diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/CaseTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/CaseTests.java index 899da8049b915..173650c66bfd2 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/CaseTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/CaseTests.java @@ -5,16 +5,15 @@ */ package org.elasticsearch.xpack.sql.expression.predicate.conditional; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expression.TypeResolution; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.Equals; -import org.elasticsearch.xpack.sql.tree.AbstractNodeTestCase; -import org.elasticsearch.xpack.sql.tree.NodeSubclassTests; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.SourceTests; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression.TypeResolution; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.Equals; +import org.elasticsearch.xpack.ql.tree.AbstractNodeTestCase; +import org.elasticsearch.xpack.ql.tree.NodeSubclassTests; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.tree.SourceTests; import java.util.ArrayList; import java.util.Arrays; @@ -22,10 +21,13 @@ import java.util.List; import java.util.Objects; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.randomIntLiteral; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.randomStringLiteral; -import static org.elasticsearch.xpack.sql.tree.Source.EMPTY; -import static org.elasticsearch.xpack.sql.tree.SourceTests.randomSource; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomIntLiteral; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomStringLiteral; +import static org.elasticsearch.xpack.ql.tree.Source.EMPTY; +import static org.elasticsearch.xpack.ql.tree.SourceTests.randomSource; +import static org.elasticsearch.xpack.ql.type.DataTypes.KEYWORD; +import static org.elasticsearch.xpack.ql.type.DataTypes.NULL; +import static org.elasticsearch.xpack.sql.SqlTestUtils.literal; /** * Needed to override tests in {@link NodeSubclassTests} as Case is special since its children are not usual @@ -84,40 +86,39 @@ public void testDataTypes() { // ELSE 'default' // END Case c = new Case(EMPTY, Arrays.asList( - new IfConditional(EMPTY, new Equals(EMPTY, Literal.of(EMPTY, 1), Literal.of(EMPTY, 1)), Literal.NULL), - Literal.of(EMPTY, "default"))); - assertEquals(DataType.KEYWORD, c.dataType()); + new IfConditional(EMPTY, new Equals(EMPTY, literal(1), literal(1)), Literal.NULL), literal("default"))); + assertEquals(KEYWORD, c.dataType()); // CASE WHEN 1 = 1 THEN 'foo' // ELSE NULL // END c = new Case(EMPTY, Arrays.asList( - new IfConditional(EMPTY, new Equals(EMPTY, Literal.of(EMPTY, 1), Literal.of(EMPTY, 1)), Literal.of(EMPTY, "foo")), + new IfConditional(EMPTY, new Equals(EMPTY, literal(1), literal(1)), literal("foo")), Literal.NULL)); - assertEquals(DataType.KEYWORD, c.dataType()); + assertEquals(KEYWORD, c.dataType()); // CASE WHEN 1 = 1 THEN NULL // ELSE NULL // END c = new Case(EMPTY, Arrays.asList( - new IfConditional(EMPTY, new Equals(EMPTY, Literal.of(EMPTY, 1), Literal.of(EMPTY, 1)), Literal.NULL), + new IfConditional(EMPTY, new Equals(EMPTY, literal(1), literal(1)), Literal.NULL), Literal.NULL)); - assertEquals(DataType.NULL, c.dataType()); + assertEquals(NULL, c.dataType()); // CASE WHEN 1 = 1 THEN NULL // WHEN 2 = 2 THEN 'foo' // ELSE NULL // END c = new Case(EMPTY, Arrays.asList( - new IfConditional(EMPTY, new Equals(EMPTY, Literal.of(EMPTY, 1), Literal.of(EMPTY, 1)), Literal.NULL), - new IfConditional(EMPTY, new Equals(EMPTY, Literal.of(EMPTY, 2), Literal.of(EMPTY, 2)), Literal.of(EMPTY, "foo")), + new IfConditional(EMPTY, new Equals(EMPTY, literal(1), literal(1)), Literal.NULL), + new IfConditional(EMPTY, new Equals(EMPTY, literal(2), literal(2)), literal("foo")), Literal.NULL)); - assertEquals(DataType.KEYWORD, c.dataType()); + assertEquals(KEYWORD, c.dataType()); } public void testAllConditionsFolded() { - Case c = new Case(EMPTY, Collections.singletonList(Literal.of(EMPTY, "foo"))); - assertEquals(DataType.KEYWORD, c.dataType()); + Case c = new Case(EMPTY, Collections.singletonList(literal("foo"))); + assertEquals(KEYWORD, c.dataType()); assertEquals(TypeResolution.TYPE_RESOLVED, c.typeResolved()); assertNotNull(c.info()); } diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/IifTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/IifTests.java index 6b468fcb8fbf2..e861dc0de9e25 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/IifTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/conditional/IifTests.java @@ -5,15 +5,15 @@ */ package org.elasticsearch.xpack.sql.expression.predicate.conditional; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.Equals; -import org.elasticsearch.xpack.sql.tree.AbstractNodeTestCase; -import org.elasticsearch.xpack.sql.tree.NodeSubclassTests; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.SourceTests; -import org.elasticsearch.xpack.sql.type.DataType; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.Equals; +import org.elasticsearch.xpack.ql.tree.AbstractNodeTestCase; +import org.elasticsearch.xpack.ql.tree.NodeSubclassTests; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.tree.SourceTests; +import org.elasticsearch.xpack.ql.type.DataTypes; +import org.elasticsearch.xpack.sql.SqlTestUtils; import java.util.ArrayList; import java.util.Arrays; @@ -21,10 +21,10 @@ import java.util.List; import java.util.Objects; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.randomIntLiteral; -import static org.elasticsearch.xpack.sql.expression.function.scalar.FunctionTestUtils.randomStringLiteral; -import static org.elasticsearch.xpack.sql.tree.Source.EMPTY; -import static org.elasticsearch.xpack.sql.tree.SourceTests.randomSource; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomIntLiteral; +import static org.elasticsearch.xpack.ql.expression.function.scalar.FunctionTestUtils.randomStringLiteral; +import static org.elasticsearch.xpack.ql.tree.Source.EMPTY; +import static org.elasticsearch.xpack.ql.tree.SourceTests.randomSource; /** * Needed to override tests in {@link NodeSubclassTests} as If is special since its children are not usual @@ -75,8 +75,8 @@ public void testReplaceChildren() { } public void testConditionFolded() { - Iif iif = new Iif(EMPTY, Collections.singletonList(Literal.of(EMPTY, "foo"))); - assertEquals(DataType.KEYWORD, iif.dataType()); + Iif iif = new Iif(EMPTY, Collections.singletonList(SqlTestUtils.literal("foo"))); + assertEquals(DataTypes.KEYWORD, iif.dataType()); assertEquals(Expression.TypeResolution.TYPE_RESOLVED, iif.typeResolved()); assertNotNull(iif.info()); } diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/nulls/CheckNullProcessorTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/nulls/CheckNullProcessorTests.java index 4ed35e2f9caa7..3a6a9c5f9ae12 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/nulls/CheckNullProcessorTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/nulls/CheckNullProcessorTests.java @@ -8,10 +8,17 @@ import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.Writeable.Reader; import org.elasticsearch.test.AbstractWireSerializingTestCase; -import org.elasticsearch.xpack.sql.expression.function.scalar.Processors; +import org.elasticsearch.xpack.ql.expression.gen.processor.ConstantProcessor; +import org.elasticsearch.xpack.ql.expression.gen.processor.Processor; +import org.elasticsearch.xpack.ql.expression.processor.Processors; +import org.elasticsearch.xpack.sql.expression.predicate.nulls.CheckNullProcessor; public class CheckNullProcessorTests extends AbstractWireSerializingTestCase { + private static final Processor FALSE = new ConstantProcessor(false); + private static final Processor TRUE = new ConstantProcessor(true); + private static final Processor NULL = new ConstantProcessor((Object) null); + public static CheckNullProcessor randomProcessor() { return new CheckNullProcessor(randomFrom(CheckNullProcessor.CheckNullOperation.values())); } diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/BinaryArithmeticTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/SqlBinaryArithmeticTests.java similarity index 86% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/BinaryArithmeticTests.java rename to x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/SqlBinaryArithmeticTests.java index 1b877cb75f377..3b3f6c003732f 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/BinaryArithmeticTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/SqlBinaryArithmeticTests.java @@ -7,12 +7,13 @@ package org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.expression.literal.IntervalDayTime; -import org.elasticsearch.xpack.sql.expression.literal.IntervalYearMonth; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.util.DateUtils; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.util.DateUtils; +import org.elasticsearch.xpack.sql.expression.literal.interval.IntervalDayTime; +import org.elasticsearch.xpack.sql.expression.literal.interval.IntervalYearMonth; +import org.elasticsearch.xpack.sql.type.SqlDataTypes; import java.time.Duration; import java.time.OffsetTime; @@ -20,16 +21,16 @@ import java.time.ZonedDateTime; import java.time.temporal.TemporalAmount; -import static org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Arithmetics.mod; -import static org.elasticsearch.xpack.sql.tree.Source.EMPTY; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_DAY; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_DAY_TO_HOUR; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_HOUR; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_MONTH; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_YEAR; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_YEAR_TO_MONTH; +import static org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.Arithmetics.mod; +import static org.elasticsearch.xpack.ql.tree.Source.EMPTY; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_DAY; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_DAY_TO_HOUR; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_HOUR; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_MONTH; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_YEAR; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_YEAR_TO_MONTH; -public class BinaryArithmeticTests extends ESTestCase { +public class SqlBinaryArithmeticTests extends ESTestCase { public void testAddNumbers() { assertEquals(Long.valueOf(3), add(1L, 2L)); @@ -134,7 +135,7 @@ public void testAddDayTimeIntervalToTimeReverse() { public void testAddNumberToIntervalIllegal() { Literal r = interval(Duration.ofHours(2), INTERVAL_HOUR); - SqlIllegalArgumentException expect = expectThrows(SqlIllegalArgumentException.class, () -> add(r, L(1))); + QlIllegalArgumentException expect = expectThrows(QlIllegalArgumentException.class, () -> add(r, L(1))); assertEquals("Cannot compute [+] between [IntervalDayTime] [Integer]", expect.getMessage()); } @@ -166,7 +167,7 @@ public void testSubYearMonthIntervalToDateTimeIllegal() { Literal l = L(now); TemporalAmount t = Period.ofYears(100).plusMonths(50); Literal r = interval(t, INTERVAL_HOUR); - SqlIllegalArgumentException ex = expectThrows(SqlIllegalArgumentException.class, () -> sub(r, l)); + QlIllegalArgumentException ex = expectThrows(QlIllegalArgumentException.class, () -> sub(r, l)); assertEquals("Cannot subtract a date from an interval; do you mean the reverse?", ex.getMessage()); } @@ -193,7 +194,7 @@ public void testSubYearMonthIntervalToTimeIllegal() { Literal l = L(now); TemporalAmount t = Period.ofYears(100).plusMonths(50); Literal r = interval(t, INTERVAL_HOUR); - SqlIllegalArgumentException ex = expectThrows(SqlIllegalArgumentException.class, () -> sub(r, l)); + QlIllegalArgumentException ex = expectThrows(QlIllegalArgumentException.class, () -> sub(r, l)); assertEquals("Cannot subtract a date from an interval; do you mean the reverse?", ex.getMessage()); } @@ -208,7 +209,7 @@ public void testSubDayTimeIntervalToTime() { public void testSubNumberFromIntervalIllegal() { Literal r = interval(Duration.ofHours(2), INTERVAL_HOUR); - SqlIllegalArgumentException expect = expectThrows(SqlIllegalArgumentException.class, () -> sub(r, L(1))); + QlIllegalArgumentException expect = expectThrows(QlIllegalArgumentException.class, () -> sub(r, L(1))); assertEquals("Cannot compute [-] between [IntervalDayTime] [Integer]", expect.getMessage()); } @@ -289,12 +290,12 @@ private static T mul(Object l, Object r) { } private static Literal L(Object value) { - return Literal.of(EMPTY, value); + return value instanceof Literal ? (Literal) value : new Literal(EMPTY, value, SqlDataTypes.fromJava(value)); } private static Literal interval(TemporalAmount value, DataType intervalType) { Object i = value instanceof Period ? new IntervalYearMonth((Period) value, intervalType) : new IntervalDayTime((Duration) value, intervalType); - return Literal.of(EMPTY, i); + return new Literal(EMPTY, i, SqlDataTypes.fromJava(i)); } -} +} \ No newline at end of file diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/InProcessorTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/InProcessorTests.java index e5b9bb23052bd..02233cc1f4c90 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/InProcessorTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/InProcessorTests.java @@ -8,14 +8,17 @@ import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.Writeable.Reader; import org.elasticsearch.test.AbstractWireSerializingTestCase; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.expression.function.scalar.Processors; -import org.elasticsearch.xpack.sql.expression.gen.processor.ConstantProcessor; +import org.elasticsearch.xpack.ql.TestUtils; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.gen.processor.ConstantProcessor; +import org.elasticsearch.xpack.ql.expression.processor.Processors; +import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.In; +import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.InProcessor; import java.util.Arrays; -import static org.elasticsearch.xpack.sql.expression.Literal.NULL; -import static org.elasticsearch.xpack.sql.tree.Source.EMPTY; +import static org.elasticsearch.xpack.ql.expression.Literal.NULL; +import static org.elasticsearch.xpack.ql.tree.Source.EMPTY; public class InProcessorTests extends AbstractWireSerializingTestCase { @@ -58,6 +61,6 @@ public void testHandleNullOnRightValue() { } private static Literal L(Object value) { - return Literal.of(EMPTY, value); + return TestUtils.of(EMPTY, value); } } diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/InTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/InTests.java index 49fa8bed9dd9c..4d437edd00b69 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/InTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/predicate/operator/comparison/InTests.java @@ -6,12 +6,14 @@ package org.elasticsearch.xpack.sql.expression.predicate.operator.comparison; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.expression.Literal; +import org.elasticsearch.xpack.ql.TestUtils; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.In; import java.util.Arrays; -import static org.elasticsearch.xpack.sql.expression.Literal.NULL; -import static org.elasticsearch.xpack.sql.tree.Source.EMPTY; +import static org.elasticsearch.xpack.ql.expression.Literal.NULL; +import static org.elasticsearch.xpack.ql.tree.Source.EMPTY; public class InTests extends ESTestCase { @@ -45,6 +47,6 @@ public void testHandleNullsOnRightValue() { } private static Literal L(Object value) { - return Literal.of(EMPTY, value); + return TestUtils.of(EMPTY, value); } } diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/optimizer/OptimizerRunTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/optimizer/OptimizerRunTests.java index bec0ddc9caff8..4a54a1e48b78b 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/optimizer/OptimizerRunTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/optimizer/OptimizerRunTests.java @@ -6,17 +6,17 @@ package org.elasticsearch.xpack.sql.optimizer; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.TestUtils; +import org.elasticsearch.xpack.ql.expression.function.FunctionRegistry; +import org.elasticsearch.xpack.ql.index.EsIndex; +import org.elasticsearch.xpack.ql.index.IndexResolution; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.type.EsField; +import org.elasticsearch.xpack.sql.SqlTestUtils; import org.elasticsearch.xpack.sql.analysis.analyzer.Analyzer; import org.elasticsearch.xpack.sql.analysis.analyzer.Verifier; -import org.elasticsearch.xpack.sql.analysis.index.EsIndex; -import org.elasticsearch.xpack.sql.analysis.index.IndexResolution; -import org.elasticsearch.xpack.sql.expression.function.FunctionRegistry; import org.elasticsearch.xpack.sql.parser.SqlParser; -import org.elasticsearch.xpack.sql.plan.logical.LogicalPlan; import org.elasticsearch.xpack.sql.stats.Metrics; -import org.elasticsearch.xpack.sql.type.EsField; -import org.elasticsearch.xpack.sql.type.TypesTests; +import org.elasticsearch.xpack.sql.types.SqlTypesTests; import java.util.Map; @@ -32,11 +32,11 @@ public OptimizerRunTests() { parser = new SqlParser(); functionRegistry = new FunctionRegistry(); - Map mapping = TypesTests.loadMapping("mapping-multi-field-variation.json"); + Map mapping = SqlTypesTests.loadMapping("mapping-multi-field-variation.json"); EsIndex test = new EsIndex("test", mapping); getIndexResult = IndexResolution.valid(test); - analyzer = new Analyzer(TestUtils.TEST_CFG, functionRegistry, getIndexResult, new Verifier(new Metrics())); + analyzer = new Analyzer(SqlTestUtils.TEST_CFG, functionRegistry, getIndexResult, new Verifier(new Metrics())); optimizer = new Optimizer(); } diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/optimizer/OptimizerTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/optimizer/OptimizerTests.java index 0ee0fab7f8595..f3e62ca4e69a3 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/optimizer/OptimizerTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/optimizer/OptimizerTests.java @@ -6,26 +6,60 @@ package org.elasticsearch.xpack.sql.optimizer; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.expression.Alias; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Expression.TypeResolution; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.NamedExpression; +import org.elasticsearch.xpack.ql.expression.Nullability; +import org.elasticsearch.xpack.ql.expression.Order; +import org.elasticsearch.xpack.ql.expression.Order.OrderDirection; +import org.elasticsearch.xpack.ql.expression.function.Function; +import org.elasticsearch.xpack.ql.expression.function.aggregate.AggregateFunction; +import org.elasticsearch.xpack.ql.expression.function.aggregate.InnerAggregate; +import org.elasticsearch.xpack.ql.expression.predicate.BinaryOperator; +import org.elasticsearch.xpack.ql.expression.predicate.Predicates; +import org.elasticsearch.xpack.ql.expression.predicate.Range; +import org.elasticsearch.xpack.ql.expression.predicate.fulltext.FullTextPredicate; +import org.elasticsearch.xpack.ql.expression.predicate.fulltext.MatchQueryPredicate; +import org.elasticsearch.xpack.ql.expression.predicate.fulltext.MultiMatchQueryPredicate; +import org.elasticsearch.xpack.ql.expression.predicate.fulltext.StringQueryPredicate; +import org.elasticsearch.xpack.ql.expression.predicate.logical.And; +import org.elasticsearch.xpack.ql.expression.predicate.logical.BinaryLogic; +import org.elasticsearch.xpack.ql.expression.predicate.logical.Not; +import org.elasticsearch.xpack.ql.expression.predicate.logical.Or; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.Equals; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.GreaterThan; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.GreaterThanOrEqual; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.LessThan; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.LessThanOrEqual; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.NotEquals; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.NullEquals; +import org.elasticsearch.xpack.ql.expression.predicate.regex.Like; +import org.elasticsearch.xpack.ql.expression.predicate.regex.LikePattern; +import org.elasticsearch.xpack.ql.expression.predicate.regex.RLike; +import org.elasticsearch.xpack.ql.index.EsIndex; +import org.elasticsearch.xpack.ql.plan.logical.Aggregate; +import org.elasticsearch.xpack.ql.plan.logical.EsRelation; +import org.elasticsearch.xpack.ql.plan.logical.Filter; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.plan.logical.OrderBy; +import org.elasticsearch.xpack.ql.plan.logical.Project; +import org.elasticsearch.xpack.ql.tree.NodeInfo; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; +import org.elasticsearch.xpack.ql.type.EsField; +import org.elasticsearch.xpack.ql.util.CollectionUtils; +import org.elasticsearch.xpack.ql.util.StringUtils; import org.elasticsearch.xpack.sql.analysis.analyzer.Analyzer.PruneSubqueryAliases; -import org.elasticsearch.xpack.sql.analysis.index.EsIndex; -import org.elasticsearch.xpack.sql.expression.Alias; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Expression.TypeResolution; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; import org.elasticsearch.xpack.sql.expression.Foldables; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.expression.NamedExpression; -import org.elasticsearch.xpack.sql.expression.Nullability; -import org.elasticsearch.xpack.sql.expression.Order; -import org.elasticsearch.xpack.sql.expression.Order.OrderDirection; -import org.elasticsearch.xpack.sql.expression.function.Function; -import org.elasticsearch.xpack.sql.expression.function.aggregate.AggregateFunction; import org.elasticsearch.xpack.sql.expression.function.aggregate.Avg; import org.elasticsearch.xpack.sql.expression.function.aggregate.ExtendedStats; import org.elasticsearch.xpack.sql.expression.function.aggregate.First; -import org.elasticsearch.xpack.sql.expression.function.aggregate.InnerAggregate; import org.elasticsearch.xpack.sql.expression.function.aggregate.Last; import org.elasticsearch.xpack.sql.expression.function.aggregate.Max; import org.elasticsearch.xpack.sql.expression.function.aggregate.Min; @@ -55,9 +89,6 @@ import org.elasticsearch.xpack.sql.expression.function.scalar.string.Ascii; import org.elasticsearch.xpack.sql.expression.function.scalar.string.Concat; import org.elasticsearch.xpack.sql.expression.function.scalar.string.Repeat; -import org.elasticsearch.xpack.sql.expression.predicate.BinaryOperator; -import org.elasticsearch.xpack.sql.expression.predicate.Predicates; -import org.elasticsearch.xpack.sql.expression.predicate.Range; import org.elasticsearch.xpack.sql.expression.predicate.conditional.ArbitraryConditionalFunction; import org.elasticsearch.xpack.sql.expression.predicate.conditional.Case; import org.elasticsearch.xpack.sql.expression.predicate.conditional.Coalesce; @@ -68,14 +99,6 @@ import org.elasticsearch.xpack.sql.expression.predicate.conditional.Iif; import org.elasticsearch.xpack.sql.expression.predicate.conditional.Least; import org.elasticsearch.xpack.sql.expression.predicate.conditional.NullIf; -import org.elasticsearch.xpack.sql.expression.predicate.fulltext.FullTextPredicate; -import org.elasticsearch.xpack.sql.expression.predicate.fulltext.MatchQueryPredicate; -import org.elasticsearch.xpack.sql.expression.predicate.fulltext.MultiMatchQueryPredicate; -import org.elasticsearch.xpack.sql.expression.predicate.fulltext.StringQueryPredicate; -import org.elasticsearch.xpack.sql.expression.predicate.logical.And; -import org.elasticsearch.xpack.sql.expression.predicate.logical.BinaryLogic; -import org.elasticsearch.xpack.sql.expression.predicate.logical.Not; -import org.elasticsearch.xpack.sql.expression.predicate.logical.Or; import org.elasticsearch.xpack.sql.expression.predicate.nulls.IsNotNull; import org.elasticsearch.xpack.sql.expression.predicate.nulls.IsNull; import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Add; @@ -83,17 +106,7 @@ import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Mod; import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Mul; import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Sub; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.Equals; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.GreaterThan; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.GreaterThanOrEqual; import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.In; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.LessThan; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.LessThanOrEqual; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.NotEquals; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.NullEquals; -import org.elasticsearch.xpack.sql.expression.predicate.regex.Like; -import org.elasticsearch.xpack.sql.expression.predicate.regex.LikePattern; -import org.elasticsearch.xpack.sql.expression.predicate.regex.RLike; import org.elasticsearch.xpack.sql.optimizer.Optimizer.BinaryComparisonSimplification; import org.elasticsearch.xpack.sql.optimizer.Optimizer.BooleanLiteralsOnTheRight; import org.elasticsearch.xpack.sql.optimizer.Optimizer.BooleanSimplification; @@ -111,23 +124,11 @@ import org.elasticsearch.xpack.sql.optimizer.Optimizer.SimplifyCase; import org.elasticsearch.xpack.sql.optimizer.Optimizer.SimplifyConditional; import org.elasticsearch.xpack.sql.optimizer.Optimizer.SortAggregateOnOrderBy; -import org.elasticsearch.xpack.sql.plan.logical.Aggregate; -import org.elasticsearch.xpack.sql.plan.logical.EsRelation; -import org.elasticsearch.xpack.sql.plan.logical.Filter; import org.elasticsearch.xpack.sql.plan.logical.LocalRelation; -import org.elasticsearch.xpack.sql.plan.logical.LogicalPlan; -import org.elasticsearch.xpack.sql.plan.logical.OrderBy; import org.elasticsearch.xpack.sql.plan.logical.Pivot; -import org.elasticsearch.xpack.sql.plan.logical.Project; import org.elasticsearch.xpack.sql.plan.logical.SubQueryAlias; import org.elasticsearch.xpack.sql.plan.logical.command.ShowTables; import org.elasticsearch.xpack.sql.session.EmptyExecutable; -import org.elasticsearch.xpack.sql.tree.NodeInfo; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.EsField; -import org.elasticsearch.xpack.sql.util.CollectionUtils; -import org.elasticsearch.xpack.sql.util.StringUtils; import java.lang.reflect.Constructor; import java.util.Arrays; @@ -138,11 +139,18 @@ import static java.util.Collections.emptyList; import static java.util.Collections.emptyMap; import static java.util.Collections.singletonList; -import static org.elasticsearch.xpack.sql.expression.Literal.FALSE; -import static org.elasticsearch.xpack.sql.expression.Literal.NULL; -import static org.elasticsearch.xpack.sql.expression.Literal.TRUE; -import static org.elasticsearch.xpack.sql.expression.Literal.of; -import static org.elasticsearch.xpack.sql.tree.Source.EMPTY; +import static org.elasticsearch.xpack.ql.expression.Literal.FALSE; +import static org.elasticsearch.xpack.ql.expression.Literal.NULL; +import static org.elasticsearch.xpack.ql.expression.Literal.TRUE; +import static org.elasticsearch.xpack.ql.tree.Source.EMPTY; +import static org.elasticsearch.xpack.ql.type.DataTypes.BOOLEAN; +import static org.elasticsearch.xpack.ql.type.DataTypes.BYTE; +import static org.elasticsearch.xpack.ql.type.DataTypes.DATETIME; +import static org.elasticsearch.xpack.ql.type.DataTypes.INTEGER; +import static org.elasticsearch.xpack.ql.type.DataTypes.KEYWORD; +import static org.elasticsearch.xpack.ql.type.DataTypes.TEXT; +import static org.elasticsearch.xpack.sql.SqlTestUtils.literal; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.DATE; import static org.elasticsearch.xpack.sql.util.DateUtils.UTC; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.is; @@ -184,7 +192,7 @@ public Nullability nullable() { @Override public DataType dataType() { - return DataType.BOOLEAN; + return BOOLEAN; } @Override @@ -208,7 +216,7 @@ private static LogicalPlan FROM() { } private static Literal L(Object value) { - return of(EMPTY, value); + return literal(value); } private static Alias a(String name, Expression e) { @@ -220,7 +228,7 @@ private static FieldAttribute getFieldAttribute() { } private static FieldAttribute getFieldAttribute(String name) { - return new FieldAttribute(EMPTY, name, new EsField(name + "f", DataType.INTEGER, emptyMap(), true)); + return new FieldAttribute(EMPTY, name, new EsField(name + "f", INTEGER, emptyMap(), true)); } public void testPruneSubqueryAliases() { @@ -359,21 +367,21 @@ public void testConstantNot() { public void testConstantFoldingLikes() { assertEquals(TRUE, - new ConstantFolding().rule(new Like(EMPTY, of(EMPTY, "test_emp"), new LikePattern("test%", (char) 0))) + new ConstantFolding().rule(new Like(EMPTY, literal("test_emp"), new LikePattern("test%", (char) 0))) .canonical()); assertEquals(TRUE, - new ConstantFolding().rule(new RLike(EMPTY, of(EMPTY, "test_emp"), "test.emp")).canonical()); + new ConstantFolding().rule(new RLike(EMPTY, literal("test_emp"), "test.emp")).canonical()); } public void testConstantFoldingDatetime() { - Expression cast = new Cast(EMPTY, of(EMPTY, "2018-01-19T10:23:27Z"), DataType.DATETIME); + Expression cast = new Cast(EMPTY, literal("2018-01-19T10:23:27Z"), DATETIME); assertEquals(2018, foldFunction(new Year(EMPTY, cast, UTC))); assertEquals(1, foldFunction(new MonthOfYear(EMPTY, cast, UTC))); assertEquals(19, foldFunction(new DayOfMonth(EMPTY, cast, UTC))); assertEquals(19, foldFunction(new DayOfYear(EMPTY, cast, UTC))); assertEquals(3, foldFunction(new IsoWeekOfYear(EMPTY, cast, UTC))); assertNull(foldFunction( - new IsoWeekOfYear(EMPTY, new Literal(EMPTY, null, DataType.NULL), UTC))); + new IsoWeekOfYear(EMPTY, new Literal(EMPTY, null, DataTypes.NULL), UTC))); } public void testConstantFoldingIn() { @@ -392,7 +400,7 @@ public void testConstantFoldingIn_LeftValueNotFoldable() { assertEquals(1, p.projections().size()); Alias a = (Alias) p.projections().get(0); In i = (In) a.child(); - assertThat(Foldables.valuesOf(i.list(), DataType.INTEGER), contains(1 ,2 ,3 ,4)); + assertThat(Foldables.valuesOf(i.list(), INTEGER), contains(1, 2, 3, 4)); } public void testConstantFoldingIn_RightValueIsNull() { @@ -443,16 +451,16 @@ public void testNullFoldingIsNull() { public void testNullFoldingIsNullWithCast() { FoldNull foldNull = new FoldNull(); - Cast cast = new Cast(EMPTY, L("foo"), DataType.DATE); + Cast cast = new Cast(EMPTY, L("foo"), DATE); IsNull isNull = new IsNull(EMPTY, cast); final IsNull isNullOpt = (IsNull) foldNull.rule(isNull); assertEquals(isNull, isNullOpt); - SqlIllegalArgumentException sqlIAE = - expectThrows(SqlIllegalArgumentException.class, () -> isNullOpt.asPipe().asProcessor().process(null)); + QlIllegalArgumentException sqlIAE = expectThrows(QlIllegalArgumentException.class, + () -> isNullOpt.asPipe().asProcessor().process(null)); assertEquals("cannot cast [foo] to [date]: Text 'foo' could not be parsed at index 0", sqlIAE.getMessage()); - isNull = new IsNull(EMPTY, new Cast(EMPTY, NULL, randomFrom(DataType.values()))); + isNull = new IsNull(EMPTY, new Cast(EMPTY, NULL, randomFrom(DataTypes.types()))); assertTrue((Boolean) ((IsNull) foldNull.rule(isNull)).asPipe().asProcessor().process(null)); } @@ -461,7 +469,7 @@ public void testNullFoldingIsNotNull() { assertEquals(true, foldNull.rule(new IsNotNull(EMPTY, TRUE)).fold()); assertEquals(false, foldNull.rule(new IsNotNull(EMPTY, NULL)).fold()); - Cast cast = new Cast(EMPTY, L("foo"), DataType.DATE); + Cast cast = new Cast(EMPTY, L("foo"), DATE); IsNotNull isNotNull = new IsNotNull(EMPTY, cast); assertEquals(isNotNull, foldNull.rule(isNotNull)); } @@ -469,16 +477,16 @@ public void testNullFoldingIsNotNull() { public void testNullFoldingIsNotNullWithCast() { FoldNull foldNull = new FoldNull(); - Cast cast = new Cast(EMPTY, L("foo"), DataType.DATE); + Cast cast = new Cast(EMPTY, L("foo"), DATE); IsNotNull isNotNull = new IsNotNull(EMPTY, cast); final IsNotNull isNotNullOpt = (IsNotNull) foldNull.rule(isNotNull); assertEquals(isNotNull, isNotNullOpt); - SqlIllegalArgumentException sqlIAE = - expectThrows(SqlIllegalArgumentException.class, () -> isNotNullOpt.asPipe().asProcessor().process(null)); + QlIllegalArgumentException sqlIAE = expectThrows(QlIllegalArgumentException.class, + () -> isNotNullOpt.asPipe().asProcessor().process(null)); assertEquals("cannot cast [foo] to [date]: Text 'foo' could not be parsed at index 0", sqlIAE.getMessage()); - isNotNull = new IsNotNull(EMPTY, new Cast(EMPTY, NULL, randomFrom(DataType.values()))); + isNotNull = new IsNotNull(EMPTY, new Cast(EMPTY, NULL, randomFrom(DataTypes.types()))); assertFalse((Boolean) ((IsNotNull) foldNull.rule(isNotNull)).asPipe().asProcessor().process(null)); } @@ -502,11 +510,11 @@ public void testGenericNullableExpression() { public void testNullFoldingOnCast() { FoldNull foldNull = new FoldNull(); - Cast cast = new Cast(EMPTY, NULL, randomFrom(DataType.values())); + Cast cast = new Cast(EMPTY, NULL, randomFrom(DataTypes.types())); assertEquals(Nullability.TRUE, cast.nullable()); assertNull(foldNull.rule(cast).fold()); - cast = new Cast(EMPTY, L("foo"), DataType.DATE); + cast = new Cast(EMPTY, L("foo"), DATE); assertEquals(Nullability.UNKNOWN, cast.nullable()); assertEquals(cast, foldNull.rule(cast)); } @@ -572,7 +580,7 @@ public void testSimplifyCoalesceRandomNullsWithValue() { randomListOfNulls()))); assertEquals(1, e.children().size()); assertEquals(TRUE, e.children().get(0)); - assertEquals(DataType.BOOLEAN, e.dataType()); + assertEquals(BOOLEAN, e.dataType()); } private List randomListOfNulls() { @@ -586,7 +594,7 @@ public void testSimplifyCoalesceFirstLiteral() { assertEquals(Coalesce.class, e.getClass()); assertEquals(1, e.children().size()); assertEquals(TRUE, e.children().get(0)); - assertEquals(DataType.BOOLEAN, e.dataType()); + assertEquals(BOOLEAN, e.dataType()); } public void testSimplifyIfNullNulls() { @@ -600,13 +608,13 @@ public void testSimplifyIfNullWithNullAndValue() { assertEquals(IfNull.class, e.getClass()); assertEquals(1, e.children().size()); assertEquals(ONE, e.children().get(0)); - assertEquals(DataType.INTEGER, e.dataType()); + assertEquals(INTEGER, e.dataType()); e = new SimplifyConditional().rule(new IfNull(EMPTY, ONE, NULL)); assertEquals(IfNull.class, e.getClass()); assertEquals(1, e.children().size()); assertEquals(ONE, e.children().get(0)); - assertEquals(DataType.INTEGER, e.dataType()); + assertEquals(INTEGER, e.dataType()); } public void testFoldNullNotAppliedOnNullIf() { @@ -634,7 +642,7 @@ public void testSimplifyGreatestRandomNullsWithValue() { assertEquals(2, e.children().size()); assertEquals(ONE, e.children().get(0)); assertEquals(TWO, e.children().get(1)); - assertEquals(DataType.INTEGER, e.dataType()); + assertEquals(INTEGER, e.dataType()); } public void testSimplifyLeastNulls() { @@ -656,7 +664,7 @@ public void testSimplifyLeastRandomNullsWithValue() { assertEquals(2, e.children().size()); assertEquals(ONE, e.children().get(0)); assertEquals(TWO, e.children().get(1)); - assertEquals(DataType.INTEGER, e.dataType()); + assertEquals(INTEGER, e.dataType()); } public void testConcatFoldingIsNotNull() { @@ -707,11 +715,10 @@ public void testSimplifyCaseConditionsFoldWhenFalse() { // END Case c = new Case(EMPTY, Arrays.asList( - new IfConditional(EMPTY, new Equals(EMPTY, getFieldAttribute(), ONE), Literal.of(EMPTY, "foo1")), - new IfConditional(EMPTY, new Equals(EMPTY, ONE, TWO), Literal.of(EMPTY, "bar1")), - new IfConditional(EMPTY, new Equals(EMPTY, TWO, ONE), Literal.of(EMPTY, "bar2")), - new IfConditional(EMPTY, new GreaterThan(EMPTY, getFieldAttribute(), ONE), Literal.of(EMPTY, "foo2")), - Literal.of(EMPTY, "default"))); + new IfConditional(EMPTY, new Equals(EMPTY, getFieldAttribute(), ONE), literal("foo1")), + new IfConditional(EMPTY, new Equals(EMPTY, ONE, TWO), literal("bar1")), + new IfConditional(EMPTY, new Equals(EMPTY, TWO, ONE), literal("bar2")), + new IfConditional(EMPTY, new GreaterThan(EMPTY, getFieldAttribute(), ONE), literal("foo2")), literal("default"))); assertFalse(c.foldable()); Expression e = new SimplifyCase().rule(c); assertEquals(Case.class, e.getClass()); @@ -734,9 +741,8 @@ public void testSimplifyCaseConditionsFoldCompletely_FoldableElse() { // 'foo2' Case c = new Case(EMPTY, Arrays.asList( - new IfConditional(EMPTY, new Equals(EMPTY, ONE, TWO), Literal.of(EMPTY, "foo1")), - new IfConditional(EMPTY, new Equals(EMPTY, ONE, ONE), Literal.of(EMPTY, "foo2")), - Literal.of(EMPTY, "default"))); + new IfConditional(EMPTY, new Equals(EMPTY, ONE, TWO), literal("foo1")), + new IfConditional(EMPTY, new Equals(EMPTY, ONE, ONE), literal("foo2")), literal("default"))); assertFalse(c.foldable()); SimplifyCase rule = new SimplifyCase(); @@ -760,7 +766,7 @@ public void testSimplifyCaseConditionsFoldCompletely_NonFoldableElse() { // myField (non-foldable) Case c = new Case(EMPTY, Arrays.asList( - new IfConditional(EMPTY, new Equals(EMPTY, ONE, TWO), Literal.of(EMPTY, "foo1")), + new IfConditional(EMPTY, new Equals(EMPTY, ONE, TWO), literal("foo1")), getFieldAttribute("myField"))); assertFalse(c.foldable()); @@ -775,7 +781,7 @@ public void testSimplifyCaseConditionsFoldCompletely_NonFoldableElse() { public void testSimplifyIif_ConditionTrue_FoldableResult() { SimplifyCase rule = new SimplifyCase(); - Iif iif = new Iif(EMPTY, new Equals(EMPTY, ONE, ONE), Literal.of(EMPTY, "foo"), Literal.of(EMPTY, "bar")); + Iif iif = new Iif(EMPTY, new Equals(EMPTY, ONE, ONE), literal("foo"), literal("bar")); assertTrue(iif.foldable()); Expression e = rule.rule(iif); @@ -789,7 +795,7 @@ public void testSimplifyIif_ConditionTrue_FoldableResult() { public void testSimplifyIif_ConditionTrue_NonFoldableResult() { SimplifyCase rule = new SimplifyCase(); - Iif iif = new Iif(EMPTY, new Equals(EMPTY, ONE, ONE), getFieldAttribute("myField"), Literal.of(EMPTY, "bar")); + Iif iif = new Iif(EMPTY, new Equals(EMPTY, ONE, ONE), getFieldAttribute("myField"), literal("bar")); assertFalse(iif.foldable()); Expression e = rule.rule(iif); @@ -804,7 +810,7 @@ public void testSimplifyIif_ConditionTrue_NonFoldableResult() { public void testSimplifyIif_ConditionFalse_FoldableResult() { SimplifyCase rule = new SimplifyCase(); - Iif iif = new Iif(EMPTY, new Equals(EMPTY, ONE, TWO), Literal.of(EMPTY, "foo"), Literal.of(EMPTY, "bar")); + Iif iif = new Iif(EMPTY, new Equals(EMPTY, ONE, TWO), literal("foo"), literal("bar")); assertTrue(iif.foldable()); Expression e = rule.rule(iif); @@ -818,7 +824,7 @@ public void testSimplifyIif_ConditionFalse_FoldableResult() { public void testSimplifyIif_ConditionFalse_NonFoldableResult() { SimplifyCase rule = new SimplifyCase(); - Iif iif = new Iif(EMPTY, new Equals(EMPTY, ONE, TWO), Literal.of(EMPTY, "foo"), getFieldAttribute("myField")); + Iif iif = new Iif(EMPTY, new Equals(EMPTY, ONE, TWO), literal("foo"), getFieldAttribute("myField")); assertFalse(iif.foldable()); Expression e = rule.rule(iif); @@ -1797,7 +1803,7 @@ public void testPropagateEquals_VarEq2OrVarRangeGt3Lt4OrVarGt2OrVarNe2() { } public void testTranslateMinToFirst() { - Min min1 = new Min(EMPTY, new FieldAttribute(EMPTY, "str", new EsField("str", DataType.KEYWORD, emptyMap(), true))); + Min min1 = new Min(EMPTY, new FieldAttribute(EMPTY, "str", new EsField("str", KEYWORD, emptyMap(), true))); Min min2 = new Min(EMPTY, getFieldAttribute()); OrderBy plan = new OrderBy(EMPTY, new Aggregate(EMPTY, FROM(), emptyList(), @@ -1823,7 +1829,7 @@ public void testTranslateMinToFirst() { } public void testTranslateMaxToLast() { - Max max1 = new Max(EMPTY, new FieldAttribute(EMPTY, "str", new EsField("str", DataType.KEYWORD, emptyMap(), true))); + Max max1 = new Max(EMPTY, new FieldAttribute(EMPTY, "str", new EsField("str", KEYWORD, emptyMap(), true))); Max max2 = new Max(EMPTY, getFieldAttribute()); OrderBy plan = new OrderBy(EMPTY, new Aggregate(EMPTY, FROM(), emptyList(), Arrays.asList(a("max1", max1), a("max2", max2))), @@ -1847,9 +1853,9 @@ public void testTranslateMaxToLast() { } public void testSortAggregateOnOrderByWithTwoFields() { - FieldAttribute firstField = new FieldAttribute(EMPTY, "first_field", new EsField("first_field", DataType.BYTE, emptyMap(), true)); + FieldAttribute firstField = new FieldAttribute(EMPTY, "first_field", new EsField("first_field", BYTE, emptyMap(), true)); FieldAttribute secondField = new FieldAttribute(EMPTY, "second_field", - new EsField("second_field", DataType.BYTE, emptyMap(), true)); + new EsField("second_field", BYTE, emptyMap(), true)); Alias firstAlias = new Alias(EMPTY, "first_alias", firstField); Alias secondAlias = new Alias(EMPTY, "second_alias", secondField); Order firstOrderBy = new Order(EMPTY, firstField, OrderDirection.ASC, Order.NullsPosition.LAST); @@ -1879,9 +1885,9 @@ public void testSortAggregateOnOrderByWithTwoFields() { } public void testSortAggregateOnOrderByOnlyAliases() { - FieldAttribute firstField = new FieldAttribute(EMPTY, "first_field", new EsField("first_field", DataType.BYTE, emptyMap(), true)); + FieldAttribute firstField = new FieldAttribute(EMPTY, "first_field", new EsField("first_field", BYTE, emptyMap(), true)); FieldAttribute secondField = new FieldAttribute(EMPTY, "second_field", - new EsField("second_field", DataType.BYTE, emptyMap(), true)); + new EsField("second_field", BYTE, emptyMap(), true)); Alias firstAlias = new Alias(EMPTY, "first_alias", firstField); Alias secondAlias = new Alias(EMPTY, "second_alias", secondField); Order firstOrderBy = new Order(EMPTY, firstAlias, OrderDirection.ASC, Order.NullsPosition.LAST); @@ -1934,8 +1940,8 @@ public void testPivotRewrite() { * or SELECT STDDEV_POP(agg_field), VAR_POP(agg_field) FROM table WHERE MATCH(match_field,'A') AND/OR QUERY('match_field:A') */ public void testAggregatesPromoteToStats_WithFullTextPredicatesConditions() { - FieldAttribute matchField = new FieldAttribute(EMPTY, "match_field", new EsField("match_field", DataType.TEXT, emptyMap(), true)); - FieldAttribute aggField = new FieldAttribute(EMPTY, "agg_field", new EsField("agg_field", DataType.INTEGER, emptyMap(), true)); + FieldAttribute matchField = new FieldAttribute(EMPTY, "match_field", new EsField("match_field", TEXT, emptyMap(), true)); + FieldAttribute aggField = new FieldAttribute(EMPTY, "agg_field", new EsField("agg_field", INTEGER, emptyMap(), true)); FullTextPredicate matchPredicate = new MatchQueryPredicate(EMPTY, matchField, "A", StringUtils.EMPTY); FullTextPredicate multiMatchPredicate = new MultiMatchQueryPredicate(EMPTY, "match_field", "A", StringUtils.EMPTY); diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/parser/EscapedFunctionsTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/parser/EscapedFunctionsTests.java index baf4de8641af0..2852619edb004 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/parser/EscapedFunctionsTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/parser/EscapedFunctionsTests.java @@ -6,18 +6,17 @@ package org.elasticsearch.xpack.sql.parser; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.expression.UnresolvedAttribute; -import org.elasticsearch.xpack.sql.expression.function.Function; -import org.elasticsearch.xpack.sql.expression.function.UnresolvedFunction; -import org.elasticsearch.xpack.sql.expression.predicate.regex.Like; -import org.elasticsearch.xpack.sql.expression.predicate.regex.LikePattern; -import org.elasticsearch.xpack.sql.plan.logical.Limit; -import org.elasticsearch.xpack.sql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.UnresolvedAttribute; +import org.elasticsearch.xpack.ql.expression.function.Function; +import org.elasticsearch.xpack.ql.expression.function.UnresolvedFunction; +import org.elasticsearch.xpack.ql.expression.predicate.regex.Like; +import org.elasticsearch.xpack.ql.expression.predicate.regex.LikePattern; +import org.elasticsearch.xpack.ql.plan.logical.Limit; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; import org.elasticsearch.xpack.sql.plan.logical.With; import org.elasticsearch.xpack.sql.proto.SqlTypedParamValue; -import org.elasticsearch.xpack.sql.type.DataType; import org.junit.Assert; import java.util.List; @@ -25,7 +24,12 @@ import static java.lang.String.format; import static java.util.Arrays.asList; -import static org.elasticsearch.xpack.sql.TestUtils.randomWhitespaces; +import static org.elasticsearch.xpack.ql.type.DataTypes.DATETIME; +import static org.elasticsearch.xpack.ql.type.DataTypes.KEYWORD; +import static org.elasticsearch.xpack.ql.type.DataTypes.LONG; +import static org.elasticsearch.xpack.sql.SqlTestUtils.randomWhitespaces; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.DATE; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.TIME; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; @@ -157,9 +161,8 @@ public void testFunctionWithFunctionWithArg() { public void testFunctionWithFunctionWithArgAndParams() { String e = "POWER(?, {fn POWER({fn ABS(?)}, {fN ABS(?)})})"; Function f = (Function) parser.createExpression(e, - asList(new SqlTypedParamValue(DataType.LONG.typeName, 1), - new SqlTypedParamValue(DataType.LONG.typeName, 1), - new SqlTypedParamValue(DataType.LONG.typeName, 1))); + asList(new SqlTypedParamValue(LONG.typeName(), 1), new SqlTypedParamValue(LONG.typeName(), 1), + new SqlTypedParamValue(LONG.typeName(), 1))); assertEquals(e, f.sourceText()); assertEquals(2, f.arguments().size()); @@ -183,7 +186,7 @@ public void testFunctionWithFunctionWithArgAndParams() { public void testDateLiteral() { Literal l = dateLiteral("2012-01-01"); - assertThat(l.dataType(), is(DataType.DATE)); + assertThat(l.dataType(), is(DATE)); } public void testDateLiteralValidation() { @@ -195,7 +198,7 @@ public void testDateLiteralValidation() { public void testTimeLiteral() { Literal l = timeLiteral("12:23:56"); - assertThat(l.dataType(), is(DataType.TIME)); + assertThat(l.dataType(), is(TIME)); } public void testTimeLiteralValidation() { @@ -207,7 +210,7 @@ public void testTimeLiteralValidation() { public void testTimestampLiteral() { Literal l = timestampLiteral("2012-01-01 10:01:02.3456"); - assertThat(l.dataType(), is(DataType.DATETIME)); + assertThat(l.dataType(), is(DATETIME)); } public void testTimestampLiteralValidation() { @@ -219,10 +222,10 @@ public void testTimestampLiteralValidation() { public void testGUID() { Literal l = guidLiteral("12345678-90ab-cdef-0123-456789abcdef"); - assertThat(l.dataType(), is(DataType.KEYWORD)); + assertThat(l.dataType(), is(KEYWORD)); l = guidLiteral("12345678-90AB-cdef-0123-456789ABCdef"); - assertThat(l.dataType(), is(DataType.KEYWORD)); + assertThat(l.dataType(), is(KEYWORD)); } public void testGUIDValidationHexa() { diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/parser/ExpressionTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/parser/ExpressionTests.java index 8d25901650b65..ab037f7a58f6a 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/parser/ExpressionTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/parser/ExpressionTests.java @@ -6,22 +6,21 @@ package org.elasticsearch.xpack.sql.parser; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.TestUtils; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.expression.function.UnresolvedFunction; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.function.UnresolvedFunction; +import org.elasticsearch.xpack.ql.expression.predicate.operator.arithmetic.Neg; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.Equals; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.NotEquals; +import org.elasticsearch.xpack.ql.expression.predicate.operator.comparison.NullEquals; +import org.elasticsearch.xpack.sql.SqlTestUtils; import org.elasticsearch.xpack.sql.expression.function.scalar.Cast; -import org.elasticsearch.xpack.sql.expression.literal.Interval; +import org.elasticsearch.xpack.sql.expression.literal.interval.Interval; import org.elasticsearch.xpack.sql.expression.predicate.conditional.Case; import org.elasticsearch.xpack.sql.expression.predicate.conditional.IfConditional; import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Add; import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Mul; -import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Neg; import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.Sub; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.Equals; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.NotEquals; -import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.NullEquals; -import org.elasticsearch.xpack.sql.type.DataType; import java.time.Duration; import java.time.Period; @@ -29,6 +28,10 @@ import java.util.Locale; import static java.lang.String.format; +import static org.elasticsearch.xpack.ql.type.DataTypes.BOOLEAN; +import static org.elasticsearch.xpack.ql.type.DataTypes.DOUBLE; +import static org.elasticsearch.xpack.ql.type.DataTypes.INTEGER; +import static org.elasticsearch.xpack.ql.type.DataTypes.LONG; import static org.hamcrest.Matchers.startsWith; public class ExpressionTests extends ESTestCase { @@ -47,7 +50,7 @@ public void testLiteralBoolean() { assertEquals(Literal.class, lt.getClass()); Literal l = (Literal) lt; assertEquals(Boolean.TRUE, l.value()); - assertEquals(DataType.BOOLEAN, l.dataType()); + assertEquals(BOOLEAN, l.dataType()); } public void testLiteralDouble() { @@ -55,7 +58,7 @@ public void testLiteralDouble() { assertEquals(Literal.class, lt.getClass()); Literal l = (Literal) lt; assertEquals(Double.MAX_VALUE, l.value()); - assertEquals(DataType.DOUBLE, l.dataType()); + assertEquals(DOUBLE, l.dataType()); } public void testLiteralDoubleNegative() { @@ -63,7 +66,7 @@ public void testLiteralDoubleNegative() { assertEquals(Literal.class, lt.getClass()); Literal l = (Literal) lt; assertEquals(Double.MIN_VALUE, l.value()); - assertEquals(DataType.DOUBLE, l.dataType()); + assertEquals(DOUBLE, l.dataType()); } public void testLiteralDoublePositive() { @@ -71,7 +74,7 @@ public void testLiteralDoublePositive() { assertEquals(Literal.class, lt.getClass()); Literal l = (Literal) lt; assertEquals(Double.MAX_VALUE, l.value()); - assertEquals(DataType.DOUBLE, l.dataType()); + assertEquals(DOUBLE, l.dataType()); } public void testLiteralLong() { @@ -79,14 +82,14 @@ public void testLiteralLong() { assertEquals(Literal.class, lt.getClass()); Literal l = (Literal) lt; assertEquals(Long.MAX_VALUE, l.value()); - assertEquals(DataType.LONG, l.dataType()); + assertEquals(LONG, l.dataType()); } public void testLiteralLongNegative() { Expression lt = parser.createExpression(String.valueOf(Long.MIN_VALUE)); assertTrue(lt.foldable()); assertEquals(Long.MIN_VALUE, lt.fold()); - assertEquals(DataType.LONG, lt.dataType()); + assertEquals(LONG, lt.dataType()); } public void testLiteralLongPositive() { @@ -94,7 +97,7 @@ public void testLiteralLongPositive() { assertEquals(Literal.class, lt.getClass()); Literal l = (Literal) lt; assertEquals(Long.MAX_VALUE, l.value()); - assertEquals(DataType.LONG, l.dataType()); + assertEquals(LONG, l.dataType()); } public void testLiteralInteger() { @@ -102,7 +105,7 @@ public void testLiteralInteger() { assertEquals(Literal.class, lt.getClass()); Literal l = (Literal) lt; assertEquals(Integer.MAX_VALUE, l.value()); - assertEquals(DataType.INTEGER, l.dataType()); + assertEquals(INTEGER, l.dataType()); } public void testLiteralIntegerWithShortValue() { @@ -110,7 +113,7 @@ public void testLiteralIntegerWithShortValue() { assertEquals(Literal.class, lt.getClass()); Literal l = (Literal) lt; assertEquals((int) Short.MAX_VALUE, l.value()); - assertEquals(DataType.INTEGER, l.dataType()); + assertEquals(INTEGER, l.dataType()); } public void testLiteralIntegerWithByteValue() { @@ -118,7 +121,7 @@ public void testLiteralIntegerWithByteValue() { assertEquals(Literal.class, lt.getClass()); Literal l = (Literal) lt; assertEquals((int) Byte.MAX_VALUE, l.value()); - assertEquals(DataType.INTEGER, l.dataType()); + assertEquals(INTEGER, l.dataType()); } public void testLiteralIntegerInvalid() { @@ -189,7 +192,7 @@ public void testLiteralTimesLiteral() { assertEquals(Mul.class, expr.getClass()); Mul mul = (Mul) expr; assertEquals("10 *2", mul.sourceText()); - assertEquals(DataType.INTEGER, mul.dataType()); + assertEquals(INTEGER, mul.dataType()); } public void testFunctionTimesLiteral() { @@ -219,13 +222,13 @@ public void testNegativeLiteral() { double value = randomDouble(); StringBuilder sb = new StringBuilder("-"); for (int i = 0; i < numberOfParentheses; i++) { - sb.append("(").append(TestUtils.randomWhitespaces()); + sb.append("(").append(SqlTestUtils.randomWhitespaces()); } sb.append(value); for (int i = 0; i < numberOfParentheses; i++) { sb.append(")"); if (i < numberOfParentheses - 1) { - sb.append(TestUtils.randomWhitespaces()); + sb.append(SqlTestUtils.randomWhitespaces()); } } expr = parser.createExpression(sb.toString()); @@ -288,26 +291,26 @@ public void testCastWithUnquotedDataType() { Expression expr = parser.createExpression("CAST(10* 2 AS long)"); assertEquals(Cast.class, expr.getClass()); Cast cast = (Cast) expr; - assertEquals(DataType.INTEGER, cast.from()); - assertEquals(DataType.LONG, cast.to()); - assertEquals(DataType.LONG, cast.dataType()); + assertEquals(INTEGER, cast.from()); + assertEquals(LONG, cast.to()); + assertEquals(LONG, cast.dataType()); assertEquals(Mul.class, cast.field().getClass()); Mul mul = (Mul) cast.field(); assertEquals("10* 2", mul.sourceText()); - assertEquals(DataType.INTEGER, mul.dataType()); + assertEquals(INTEGER, mul.dataType()); } public void testCastWithQuotedDataType() { Expression expr = parser.createExpression("CAST(10*2 AS \"LonG\")"); assertEquals(Cast.class, expr.getClass()); Cast cast = (Cast) expr; - assertEquals(DataType.INTEGER, cast.from()); - assertEquals(DataType.LONG, cast.to()); - assertEquals(DataType.LONG, cast.dataType()); + assertEquals(INTEGER, cast.from()); + assertEquals(LONG, cast.to()); + assertEquals(LONG, cast.dataType()); assertEquals(Mul.class, cast.field().getClass()); Mul mul = (Mul) cast.field(); assertEquals("10*2", mul.sourceText()); - assertEquals(DataType.INTEGER, mul.dataType()); + assertEquals(INTEGER, mul.dataType()); } public void testCastWithInvalidDataType() { @@ -319,39 +322,39 @@ public void testCastOperatorPrecedence() { Expression expr = parser.createExpression("(10* 2::long)"); assertEquals(Mul.class, expr.getClass()); Mul mul = (Mul) expr; - assertEquals(DataType.LONG, mul.dataType()); - assertEquals(DataType.INTEGER, mul.left().dataType()); + assertEquals(LONG, mul.dataType()); + assertEquals(INTEGER, mul.left().dataType()); assertEquals(Cast.class, mul.right().getClass()); Cast cast = (Cast) mul.right(); - assertEquals(DataType.INTEGER, cast.from()); - assertEquals(DataType.LONG, cast.to()); - assertEquals(DataType.LONG, cast.dataType()); + assertEquals(INTEGER, cast.from()); + assertEquals(LONG, cast.to()); + assertEquals(LONG, cast.dataType()); } public void testCastOperatorWithUnquotedDataType() { Expression expr = parser.createExpression("(10* 2)::long"); assertEquals(Cast.class, expr.getClass()); Cast cast = (Cast) expr; - assertEquals(DataType.INTEGER, cast.from()); - assertEquals(DataType.LONG, cast.to()); - assertEquals(DataType.LONG, cast.dataType()); + assertEquals(INTEGER, cast.from()); + assertEquals(LONG, cast.to()); + assertEquals(LONG, cast.dataType()); assertEquals(Mul.class, cast.field().getClass()); Mul mul = (Mul) cast.field(); assertEquals("10* 2", mul.sourceText()); - assertEquals(DataType.INTEGER, mul.dataType()); + assertEquals(INTEGER, mul.dataType()); } public void testCastOperatorWithQuotedDataType() { Expression expr = parser.createExpression("(10*2)::\"LonG\""); assertEquals(Cast.class, expr.getClass()); Cast cast = (Cast) expr; - assertEquals(DataType.INTEGER, cast.from()); - assertEquals(DataType.LONG, cast.to()); - assertEquals(DataType.LONG, cast.dataType()); + assertEquals(INTEGER, cast.from()); + assertEquals(LONG, cast.to()); + assertEquals(LONG, cast.dataType()); assertEquals(Mul.class, cast.field().getClass()); Mul mul = (Mul) cast.field(); assertEquals("10*2", mul.sourceText()); - assertEquals(DataType.INTEGER, mul.dataType()); + assertEquals(INTEGER, mul.dataType()); } public void testCastOperatorWithInvalidDataType() { @@ -363,13 +366,13 @@ public void testConvertWithUnquotedDataType() { Expression expr = parser.createExpression("CONVERT(10*2, long)"); assertEquals(Cast.class, expr.getClass()); Cast cast = (Cast) expr; - assertEquals(DataType.INTEGER, cast.from()); - assertEquals(DataType.LONG, cast.to()); - assertEquals(DataType.LONG, cast.dataType()); + assertEquals(INTEGER, cast.from()); + assertEquals(LONG, cast.to()); + assertEquals(LONG, cast.dataType()); assertEquals(Mul.class, cast.field().getClass()); Mul mul = (Mul) cast.field(); assertEquals("10*2", mul.sourceText()); - assertEquals(DataType.INTEGER, mul.dataType()); + assertEquals(INTEGER, mul.dataType()); } public void testConvertWithQuotedDataType() { @@ -378,31 +381,31 @@ public void testConvertWithQuotedDataType() { assertEquals(Cast.class, expr.getClass()); Cast cast = (Cast) expr; assertEquals(e, cast.sourceText()); - assertEquals(DataType.INTEGER, cast.from()); - assertEquals(DataType.LONG, cast.to()); - assertEquals(DataType.LONG, cast.dataType()); + assertEquals(INTEGER, cast.from()); + assertEquals(LONG, cast.to()); + assertEquals(LONG, cast.dataType()); assertEquals(Mul.class, cast.field().getClass()); Mul mul = (Mul) cast.field(); assertEquals("10*2", mul.sourceText()); - assertEquals(DataType.INTEGER, mul.dataType()); + assertEquals(INTEGER, mul.dataType()); } public void testConvertWithUnquotedODBCDataType() { Expression expr = parser.createExpression("CONVERT(1, Sql_BigInt)"); assertEquals(Cast.class, expr.getClass()); Cast cast = (Cast) expr; - assertEquals(DataType.INTEGER, cast.from()); - assertEquals(DataType.LONG, cast.to()); - assertEquals(DataType.LONG, cast.dataType()); + assertEquals(INTEGER, cast.from()); + assertEquals(LONG, cast.to()); + assertEquals(LONG, cast.dataType()); } public void testConvertWithQuotedODBCDataType() { Expression expr = parser.createExpression("CONVERT(1, \"sql_BIGint\")"); assertEquals(Cast.class, expr.getClass()); Cast cast = (Cast) expr; - assertEquals(DataType.INTEGER, cast.from()); - assertEquals(DataType.LONG, cast.to()); - assertEquals(DataType.LONG, cast.dataType()); + assertEquals(INTEGER, cast.from()); + assertEquals(LONG, cast.to()); + assertEquals(LONG, cast.dataType()); } public void testConvertWithInvalidODBCDataType() { diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/parser/LikeEscapingParsingTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/parser/LikeEscapingParsingTests.java index a9b9723c8cc1f..0072693a7b6d2 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/parser/LikeEscapingParsingTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/parser/LikeEscapingParsingTests.java @@ -6,14 +6,14 @@ package org.elasticsearch.xpack.sql.parser; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.predicate.regex.Like; -import org.elasticsearch.xpack.sql.expression.predicate.regex.LikePattern; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.predicate.regex.Like; +import org.elasticsearch.xpack.ql.expression.predicate.regex.LikePattern; import org.elasticsearch.xpack.sql.proto.SqlTypedParamValue; -import org.elasticsearch.xpack.sql.type.DataType; import static java.util.Collections.singletonList; import static org.elasticsearch.common.logging.LoggerMessageFormat.format; +import static org.elasticsearch.xpack.ql.type.DataTypes.KEYWORD; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; @@ -32,7 +32,7 @@ private LikePattern like(String pattern) { Expression exp = null; boolean parameterized = randomBoolean(); if (parameterized) { - exp = parser.createExpression("exp LIKE ?", singletonList(new SqlTypedParamValue(DataType.KEYWORD.typeName, pattern))); + exp = parser.createExpression("exp LIKE ?", singletonList(new SqlTypedParamValue(KEYWORD.typeName(), pattern))); } else { exp = parser.createExpression(format(null, "exp LIKE '{}'", pattern)); } diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/parser/SqlParserTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/parser/SqlParserTests.java index 1dc9567016ec5..a82144840b83d 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/parser/SqlParserTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/parser/SqlParserTests.java @@ -8,21 +8,21 @@ import com.google.common.base.Joiner; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.expression.Alias; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.expression.NamedExpression; -import org.elasticsearch.xpack.sql.expression.Order; -import org.elasticsearch.xpack.sql.expression.UnresolvedAlias; -import org.elasticsearch.xpack.sql.expression.UnresolvedAttribute; -import org.elasticsearch.xpack.sql.expression.function.UnresolvedFunction; -import org.elasticsearch.xpack.sql.expression.predicate.fulltext.MatchQueryPredicate; -import org.elasticsearch.xpack.sql.expression.predicate.fulltext.MultiMatchQueryPredicate; -import org.elasticsearch.xpack.sql.expression.predicate.fulltext.StringQueryPredicate; -import org.elasticsearch.xpack.sql.plan.logical.Filter; -import org.elasticsearch.xpack.sql.plan.logical.LogicalPlan; -import org.elasticsearch.xpack.sql.plan.logical.OrderBy; -import org.elasticsearch.xpack.sql.plan.logical.Project; -import org.elasticsearch.xpack.sql.plan.logical.UnresolvedRelation; +import org.elasticsearch.xpack.ql.expression.Alias; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.NamedExpression; +import org.elasticsearch.xpack.ql.expression.Order; +import org.elasticsearch.xpack.ql.expression.UnresolvedAlias; +import org.elasticsearch.xpack.ql.expression.UnresolvedAttribute; +import org.elasticsearch.xpack.ql.expression.function.UnresolvedFunction; +import org.elasticsearch.xpack.ql.expression.predicate.fulltext.MatchQueryPredicate; +import org.elasticsearch.xpack.ql.expression.predicate.fulltext.MultiMatchQueryPredicate; +import org.elasticsearch.xpack.ql.expression.predicate.fulltext.StringQueryPredicate; +import org.elasticsearch.xpack.ql.plan.logical.Filter; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.plan.logical.OrderBy; +import org.elasticsearch.xpack.ql.plan.logical.Project; +import org.elasticsearch.xpack.ql.plan.logical.UnresolvedRelation; import java.util.ArrayList; import java.util.List; diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/plan/logical/UnresolvedRelationTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/plan/logical/UnresolvedRelationTests.java index 8dda75b889576..51ea33ed22a86 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/plan/logical/UnresolvedRelationTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/plan/logical/UnresolvedRelationTests.java @@ -6,9 +6,10 @@ package org.elasticsearch.xpack.sql.plan.logical; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.plan.TableIdentifier; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.SourceTests; +import org.elasticsearch.xpack.ql.plan.TableIdentifier; +import org.elasticsearch.xpack.ql.plan.logical.UnresolvedRelation; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.tree.SourceTests; import java.util.ArrayList; import java.util.List; diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/plan/logical/command/ShowFunctionsTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/plan/logical/command/ShowFunctionsTests.java new file mode 100644 index 0000000000000..c7b06571a01e7 --- /dev/null +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/plan/logical/command/ShowFunctionsTests.java @@ -0,0 +1,32 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.sql.plan.logical.command; + +import org.elasticsearch.test.ESTestCase; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.sql.SqlTestUtils; +import org.elasticsearch.xpack.sql.expression.function.SqlFunctionRegistry; +import org.elasticsearch.xpack.sql.session.SchemaRowSet; +import org.elasticsearch.xpack.sql.session.SqlSession; + +import static org.elasticsearch.action.ActionListener.wrap; + +public class ShowFunctionsTests extends ESTestCase { + + public void testShowFunctions() throws Exception { + ShowFunctions showFunctions = new ShowFunctions(Source.EMPTY, null); + SqlSession session = new SqlSession(SqlTestUtils.TEST_CFG, null, new SqlFunctionRegistry(), null, null, null, null, null, null); + + showFunctions.execute(session, wrap(p -> { + SchemaRowSet r = (SchemaRowSet) p.rowSet(); + assertTrue(150 <= r.size()); + assertEquals(2, r.columnCount()); + assertEquals("AVG", r.column(0)); + assertEquals("AGGREGATE", r.column(1)); + }, ex -> fail(ex.getMessage()))); + } +} diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/plan/logical/command/sys/SysColumnsTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/plan/logical/command/sys/SysColumnsTests.java index 4eea3aec49174..8531cf3a901e8 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/plan/logical/command/sys/SysColumnsTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/plan/logical/command/sys/SysColumnsTests.java @@ -8,15 +8,16 @@ import org.elasticsearch.action.ActionListener; import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.TestUtils; +import org.elasticsearch.xpack.ql.expression.function.FunctionRegistry; +import org.elasticsearch.xpack.ql.index.EsIndex; +import org.elasticsearch.xpack.ql.index.IndexResolution; +import org.elasticsearch.xpack.ql.index.IndexResolver; +import org.elasticsearch.xpack.ql.index.IndexResolver.IndexInfo; +import org.elasticsearch.xpack.ql.index.IndexResolver.IndexType; +import org.elasticsearch.xpack.ql.type.EsField; +import org.elasticsearch.xpack.sql.SqlTestUtils; import org.elasticsearch.xpack.sql.analysis.analyzer.Analyzer; import org.elasticsearch.xpack.sql.analysis.analyzer.Verifier; -import org.elasticsearch.xpack.sql.analysis.index.EsIndex; -import org.elasticsearch.xpack.sql.analysis.index.IndexResolution; -import org.elasticsearch.xpack.sql.analysis.index.IndexResolver; -import org.elasticsearch.xpack.sql.analysis.index.IndexResolver.IndexInfo; -import org.elasticsearch.xpack.sql.analysis.index.IndexResolver.IndexType; -import org.elasticsearch.xpack.sql.expression.function.FunctionRegistry; import org.elasticsearch.xpack.sql.parser.SqlParser; import org.elasticsearch.xpack.sql.plan.logical.command.Command; import org.elasticsearch.xpack.sql.proto.Mode; @@ -24,8 +25,6 @@ import org.elasticsearch.xpack.sql.session.SchemaRowSet; import org.elasticsearch.xpack.sql.session.SqlSession; import org.elasticsearch.xpack.sql.stats.Metrics; -import org.elasticsearch.xpack.sql.type.EsField; -import org.elasticsearch.xpack.sql.type.TypesTests; import java.sql.Types; import java.util.ArrayList; @@ -36,6 +35,7 @@ import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.elasticsearch.action.ActionListener.wrap; +import static org.elasticsearch.xpack.sql.types.SqlTypesTests.loadMapping; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Mockito.doAnswer; @@ -47,14 +47,14 @@ public class SysColumnsTests extends ESTestCase { static final String CLUSTER_NAME = "cluster"; private final SqlParser parser = new SqlParser(); - private final Map mapping = TypesTests.loadMapping("mapping-multi-field-with-nested.json", true); + private final Map mapping = loadMapping("mapping-multi-field-with-nested.json", true); private final IndexInfo index = new IndexInfo("test_emp", IndexType.STANDARD_INDEX); private final IndexInfo alias = new IndexInfo("alias", IndexType.ALIAS); public void testSysColumns() { List> rows = new ArrayList<>(); - SysColumns.fillInRows("test", "index", TypesTests.loadMapping("mapping-multi-field-variation.json", true), null, rows, null, + SysColumns.fillInRows("test", "index", loadMapping("mapping-multi-field-variation.json", true), null, rows, null, randomValueOtherThanMany(Mode::isDriver, () -> randomFrom(Mode.values()))); // nested fields are ignored assertEquals(15, rows.size()); @@ -142,7 +142,7 @@ public void testSysColumns() { public void testSysColumnsInOdbcMode() { List> rows = new ArrayList<>(); - SysColumns.fillInRows("test", "index", TypesTests.loadMapping("mapping-multi-field-variation.json", true), null, rows, null, + SysColumns.fillInRows("test", "index", loadMapping("mapping-multi-field-variation.json", true), null, rows, null, Mode.ODBC); assertEquals(15, rows.size()); assertEquals(24, rows.get(0).size()); @@ -277,7 +277,7 @@ public void testSysColumnsInOdbcMode() { public void testSysColumnsInJdbcMode() { List> rows = new ArrayList<>(); - SysColumns.fillInRows("test", "index", TypesTests.loadMapping("mapping-multi-field-variation.json", true), null, rows, null, + SysColumns.fillInRows("test", "index", loadMapping("mapping-multi-field-variation.json", true), null, rows, null, Mode.JDBC); assertEquals(15, rows.size()); assertEquals(24, rows.get(0).size()); @@ -519,14 +519,14 @@ private void executeCommand(String sql, List params, Consume private Tuple sql(String sql, List params, Map mapping) { EsIndex test = new EsIndex("test", mapping); - Analyzer analyzer = new Analyzer(TestUtils.TEST_CFG, new FunctionRegistry(), IndexResolution.valid(test), + Analyzer analyzer = new Analyzer(SqlTestUtils.TEST_CFG, new FunctionRegistry(), IndexResolution.valid(test), new Verifier(new Metrics())); Command cmd = (Command) analyzer.analyze(parser.createStatement(sql, params), true); IndexResolver resolver = mock(IndexResolver.class); when(resolver.clusterName()).thenReturn(CLUSTER_NAME); - SqlSession session = new SqlSession(TestUtils.TEST_CFG, null, null, resolver, null, null, null, null, null); + SqlSession session = new SqlSession(SqlTestUtils.TEST_CFG, null, null, resolver, null, null, null, null, null); return new Tuple<>(cmd, session); } } diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/plan/logical/command/sys/SysTablesTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/plan/logical/command/sys/SysTablesTests.java index 834c5808b707f..5869aaeb09195 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/plan/logical/command/sys/SysTablesTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/plan/logical/command/sys/SysTablesTests.java @@ -8,15 +8,17 @@ import org.elasticsearch.action.ActionListener; import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.TestUtils; +import org.elasticsearch.xpack.ql.expression.function.FunctionRegistry; +import org.elasticsearch.xpack.ql.index.EsIndex; +import org.elasticsearch.xpack.ql.index.IndexResolution; +import org.elasticsearch.xpack.ql.index.IndexResolver; +import org.elasticsearch.xpack.ql.index.IndexResolver.IndexInfo; +import org.elasticsearch.xpack.ql.index.IndexResolver.IndexType; +import org.elasticsearch.xpack.ql.type.DataTypes; +import org.elasticsearch.xpack.ql.type.EsField; +import org.elasticsearch.xpack.sql.SqlTestUtils; import org.elasticsearch.xpack.sql.analysis.analyzer.Analyzer; import org.elasticsearch.xpack.sql.analysis.analyzer.Verifier; -import org.elasticsearch.xpack.sql.analysis.index.EsIndex; -import org.elasticsearch.xpack.sql.analysis.index.IndexResolution; -import org.elasticsearch.xpack.sql.analysis.index.IndexResolver; -import org.elasticsearch.xpack.sql.analysis.index.IndexResolver.IndexInfo; -import org.elasticsearch.xpack.sql.analysis.index.IndexResolver.IndexType; -import org.elasticsearch.xpack.sql.expression.function.FunctionRegistry; import org.elasticsearch.xpack.sql.parser.SqlParser; import org.elasticsearch.xpack.sql.plan.logical.command.Command; import org.elasticsearch.xpack.sql.proto.Mode; @@ -26,9 +28,7 @@ import org.elasticsearch.xpack.sql.session.SchemaRowSet; import org.elasticsearch.xpack.sql.session.SqlSession; import org.elasticsearch.xpack.sql.stats.Metrics; -import org.elasticsearch.xpack.sql.type.DataTypes; -import org.elasticsearch.xpack.sql.type.EsField; -import org.elasticsearch.xpack.sql.type.TypesTests; +import org.elasticsearch.xpack.sql.types.SqlTypesTests; import org.elasticsearch.xpack.sql.util.DateUtils; import java.util.Comparator; @@ -51,7 +51,7 @@ public class SysTablesTests extends ESTestCase { private static final String CLUSTER_NAME = "cluster"; private final SqlParser parser = new SqlParser(); - private final Map mapping = TypesTests.loadMapping("mapping-multi-field-with-nested.json", true); + private final Map mapping = SqlTypesTests.loadMapping("mapping-multi-field-with-nested.json", true); private final IndexInfo index = new IndexInfo("test", IndexType.STANDARD_INDEX); private final IndexInfo alias = new IndexInfo("alias", IndexType.ALIAS); private final IndexInfo frozen = new IndexInfo("frozen", IndexType.FROZEN_INDEX); @@ -345,12 +345,12 @@ public void testSysTablesWithInvalidType() throws Exception { private SqlTypedParamValue param(Object value) { - return new SqlTypedParamValue(DataTypes.fromJava(value).typeName, value); + return new SqlTypedParamValue(DataTypes.fromJava(value).typeName(), value); } private Tuple sql(String sql, List params, Configuration cfg) { EsIndex test = new EsIndex("test", mapping); - Analyzer analyzer = new Analyzer(TestUtils.TEST_CFG, new FunctionRegistry(), IndexResolution.valid(test), + Analyzer analyzer = new Analyzer(SqlTestUtils.TEST_CFG, new FunctionRegistry(), IndexResolution.valid(test), new Verifier(new Metrics())); Command cmd = (Command) analyzer.analyze(parser.createStatement(sql, params), true); @@ -371,7 +371,7 @@ private void executeCommand(String sql, Consumer consumer, Configu private void executeCommand(String sql, List params, Consumer consumer, IndexInfo... infos) throws Exception { - executeCommand(sql, params, consumer, TestUtils.TEST_CFG, infos); + executeCommand(sql, params, consumer, SqlTestUtils.TEST_CFG, infos); } @SuppressWarnings({ "unchecked", "rawtypes" }) diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/plan/logical/command/sys/SysTypesTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/plan/logical/command/sys/SysTypesTests.java index adf1ad5b4d1e6..17bc17bbec4b8 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/plan/logical/command/sys/SysTypesTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/plan/logical/command/sys/SysTypesTests.java @@ -7,18 +7,19 @@ import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.TestUtils; +import org.elasticsearch.xpack.ql.expression.function.FunctionRegistry; +import org.elasticsearch.xpack.ql.index.EsIndex; +import org.elasticsearch.xpack.ql.index.IndexResolution; +import org.elasticsearch.xpack.ql.index.IndexResolver; +import org.elasticsearch.xpack.ql.type.DataTypes; +import org.elasticsearch.xpack.sql.SqlTestUtils; import org.elasticsearch.xpack.sql.analysis.analyzer.Analyzer; -import org.elasticsearch.xpack.sql.analysis.index.EsIndex; -import org.elasticsearch.xpack.sql.analysis.index.IndexResolution; -import org.elasticsearch.xpack.sql.analysis.index.IndexResolver; -import org.elasticsearch.xpack.sql.expression.function.FunctionRegistry; import org.elasticsearch.xpack.sql.parser.SqlParser; import org.elasticsearch.xpack.sql.plan.logical.command.Command; import org.elasticsearch.xpack.sql.session.SchemaRowSet; import org.elasticsearch.xpack.sql.session.SqlSession; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.TypesTests; +import org.elasticsearch.xpack.sql.type.SqlDataTypes; +import org.elasticsearch.xpack.sql.types.SqlTypesTests; import java.sql.JDBCType; import java.util.List; @@ -32,12 +33,12 @@ public class SysTypesTests extends ESTestCase { private final SqlParser parser = new SqlParser(); private Tuple sql(String sql) { - EsIndex test = new EsIndex("test", TypesTests.loadMapping("mapping-multi-field-with-nested.json", true)); - Analyzer analyzer = new Analyzer(TestUtils.TEST_CFG, new FunctionRegistry(), IndexResolution.valid(test), null); + EsIndex test = new EsIndex("test", SqlTypesTests.loadMapping("mapping-multi-field-with-nested.json", true)); + Analyzer analyzer = new Analyzer(SqlTestUtils.TEST_CFG, new FunctionRegistry(), IndexResolution.valid(test), null); Command cmd = (Command) analyzer.analyze(parser.createStatement(sql), false); IndexResolver resolver = mock(IndexResolver.class); - SqlSession session = new SqlSession(TestUtils.TEST_CFG, null, null, resolver, null, null, null, null, null); + SqlSession session = new SqlSession(SqlTestUtils.TEST_CFG, null, null, resolver, null, null, null, null, null); return new Tuple<>(cmd, session); } @@ -45,17 +46,17 @@ public void testSysTypes() { Command cmd = sql("SYS TYPES").v1(); List names = asList("BYTE", "LONG", "BINARY", "NULL", "INTEGER", "SHORT", "HALF_FLOAT", "FLOAT", "DOUBLE", "SCALED_FLOAT", - "KEYWORD", "TEXT", "IP", "BOOLEAN", "DATE", "TIME", "DATETIME", + "IP", "KEYWORD", "TEXT", "BOOLEAN", "DATE", "TIME", "DATETIME", "INTERVAL_YEAR", "INTERVAL_MONTH", "INTERVAL_DAY", "INTERVAL_HOUR", "INTERVAL_MINUTE", "INTERVAL_SECOND", "INTERVAL_YEAR_TO_MONTH", "INTERVAL_DAY_TO_HOUR", "INTERVAL_DAY_TO_MINUTE", "INTERVAL_DAY_TO_SECOND", "INTERVAL_HOUR_TO_MINUTE", "INTERVAL_HOUR_TO_SECOND", "INTERVAL_MINUTE_TO_SECOND", - "GEO_SHAPE", "GEO_POINT", "SHAPE", "UNSUPPORTED", "OBJECT", "NESTED"); + "GEO_POINT", "GEO_SHAPE", "SHAPE", "UNSUPPORTED", "NESTED", "OBJECT"); cmd.execute(session(), wrap(p -> { SchemaRowSet r = (SchemaRowSet) p.rowSet(); assertEquals(19, r.columnCount()); - assertEquals(DataType.values().length, r.size()); - assertFalse(r.schema().types().contains(DataType.NULL)); + assertEquals(SqlDataTypes.types().size(), r.size()); + assertFalse(r.schema().types().contains(DataTypes.NULL)); // test numeric as signed assertFalse(r.column(9, Boolean.class)); // make sure precision is returned as boolean (not int) @@ -76,7 +77,7 @@ public void testSysTypesDefaultFiltering() { cmd.execute(session(), wrap(p -> { SchemaRowSet r = (SchemaRowSet) p.rowSet(); - assertEquals(DataType.values().length, r.size()); + assertEquals(SqlDataTypes.types().size(), r.size()); }, ex -> fail(ex.getMessage()))); } @@ -107,15 +108,15 @@ public void testSysTypesMultipleMatches() { cmd.execute(session(), wrap(p -> { SchemaRowSet r = (SchemaRowSet) p.rowSet(); assertEquals(3, r.size()); + assertEquals("IP", r.column(0)); + assertTrue(r.advanceRow()); assertEquals("KEYWORD", r.column(0)); assertTrue(r.advanceRow()); assertEquals("TEXT", r.column(0)); - assertTrue(r.advanceRow()); - assertEquals("IP", r.column(0)); }, ex -> fail(ex.getMessage()))); } private static SqlSession session() { - return new SqlSession(TestUtils.TEST_CFG, null, null, null, null, null, null, null, null); + return new SqlSession(SqlTestUtils.TEST_CFG, null, null, null, null, null, null, null, null); } } diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/planner/PostOptimizerVerifierTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/planner/PostOptimizerVerifierTests.java index 4e89fdb215445..dae2efb865b17 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/planner/PostOptimizerVerifierTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/planner/PostOptimizerVerifierTests.java @@ -7,18 +7,18 @@ package org.elasticsearch.xpack.sql.planner; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.TestUtils; +import org.elasticsearch.xpack.ql.index.EsIndex; +import org.elasticsearch.xpack.ql.index.IndexResolution; +import org.elasticsearch.xpack.ql.type.EsField; +import org.elasticsearch.xpack.sql.SqlTestUtils; import org.elasticsearch.xpack.sql.analysis.analyzer.Analyzer; import org.elasticsearch.xpack.sql.analysis.analyzer.Verifier; -import org.elasticsearch.xpack.sql.analysis.index.EsIndex; -import org.elasticsearch.xpack.sql.analysis.index.IndexResolution; -import org.elasticsearch.xpack.sql.expression.function.FunctionRegistry; +import org.elasticsearch.xpack.sql.expression.function.SqlFunctionRegistry; import org.elasticsearch.xpack.sql.optimizer.Optimizer; import org.elasticsearch.xpack.sql.parser.SqlParser; import org.elasticsearch.xpack.sql.plan.physical.PhysicalPlan; import org.elasticsearch.xpack.sql.stats.Metrics; -import org.elasticsearch.xpack.sql.type.EsField; -import org.elasticsearch.xpack.sql.type.TypesTests; +import org.elasticsearch.xpack.sql.types.SqlTypesTests; import org.junit.After; import org.junit.Before; @@ -36,10 +36,10 @@ public class PostOptimizerVerifierTests extends ESTestCase { public void init() { parser = new SqlParser(); - Map mapping = TypesTests.loadMapping("mapping-multi-field-variation.json"); + Map mapping = SqlTypesTests.loadMapping("mapping-multi-field-variation.json"); EsIndex test = new EsIndex("test", mapping); indexResolution = IndexResolution.valid(test); - analyzer = new Analyzer(TestUtils.TEST_CFG, new FunctionRegistry(), indexResolution, new Verifier(new Metrics())); + analyzer = new Analyzer(SqlTestUtils.TEST_CFG, new SqlFunctionRegistry(), indexResolution, new Verifier(new Metrics())); optimizer = new Optimizer(); planner = new Planner(); } diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/planner/QueryFolderTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/planner/QueryFolderTests.java index 18afb92b27361..6da981eba349b 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/planner/QueryFolderTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/planner/QueryFolderTests.java @@ -6,14 +6,15 @@ package org.elasticsearch.xpack.sql.planner; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.TestUtils; +import org.elasticsearch.xpack.ql.expression.Expressions; +import org.elasticsearch.xpack.ql.expression.ReferenceAttribute; +import org.elasticsearch.xpack.ql.index.EsIndex; +import org.elasticsearch.xpack.ql.index.IndexResolution; +import org.elasticsearch.xpack.ql.type.EsField; +import org.elasticsearch.xpack.sql.SqlTestUtils; import org.elasticsearch.xpack.sql.analysis.analyzer.Analyzer; import org.elasticsearch.xpack.sql.analysis.analyzer.Verifier; -import org.elasticsearch.xpack.sql.analysis.index.EsIndex; -import org.elasticsearch.xpack.sql.analysis.index.IndexResolution; -import org.elasticsearch.xpack.sql.expression.Expressions; -import org.elasticsearch.xpack.sql.expression.ReferenceAttribute; -import org.elasticsearch.xpack.sql.expression.function.FunctionRegistry; +import org.elasticsearch.xpack.sql.expression.function.SqlFunctionRegistry; import org.elasticsearch.xpack.sql.optimizer.Optimizer; import org.elasticsearch.xpack.sql.parser.SqlParser; import org.elasticsearch.xpack.sql.plan.physical.EsQueryExec; @@ -22,8 +23,7 @@ import org.elasticsearch.xpack.sql.session.EmptyExecutable; import org.elasticsearch.xpack.sql.session.SingletonExecutable; import org.elasticsearch.xpack.sql.stats.Metrics; -import org.elasticsearch.xpack.sql.type.EsField; -import org.elasticsearch.xpack.sql.type.TypesTests; +import org.elasticsearch.xpack.sql.types.SqlTypesTests; import org.junit.AfterClass; import org.junit.BeforeClass; @@ -45,10 +45,10 @@ public class QueryFolderTests extends ESTestCase { public static void init() { parser = new SqlParser(); - Map mapping = TypesTests.loadMapping("mapping-multi-field-variation.json"); + Map mapping = SqlTypesTests.loadMapping("mapping-multi-field-variation.json"); EsIndex test = new EsIndex("test", mapping); IndexResolution getIndexResult = IndexResolution.valid(test); - analyzer = new Analyzer(TestUtils.TEST_CFG, new FunctionRegistry(), getIndexResult, new Verifier(new Metrics())); + analyzer = new Analyzer(SqlTestUtils.TEST_CFG, new SqlFunctionRegistry(), getIndexResult, new Verifier(new Metrics())); optimizer = new Optimizer(); planner = new Planner(); } diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/planner/QueryTranslatorTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/planner/QueryTranslatorTests.java index 0007398fbb83a..53fce394ac6c2 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/planner/QueryTranslatorTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/planner/QueryTranslatorTests.java @@ -12,29 +12,30 @@ import org.elasticsearch.search.aggregations.metrics.AvgAggregationBuilder; import org.elasticsearch.search.aggregations.metrics.CardinalityAggregationBuilder; import org.elasticsearch.test.ESTestCase; +import org.elasticsearch.xpack.ql.expression.Alias; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.gen.script.ScriptTemplate; +import org.elasticsearch.xpack.ql.index.EsIndex; +import org.elasticsearch.xpack.ql.index.IndexResolution; +import org.elasticsearch.xpack.ql.plan.logical.Aggregate; +import org.elasticsearch.xpack.ql.plan.logical.Filter; +import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan; +import org.elasticsearch.xpack.ql.plan.logical.Project; +import org.elasticsearch.xpack.ql.type.EsField; import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.TestUtils; +import org.elasticsearch.xpack.sql.SqlTestUtils; import org.elasticsearch.xpack.sql.analysis.analyzer.Analyzer; import org.elasticsearch.xpack.sql.analysis.analyzer.Verifier; -import org.elasticsearch.xpack.sql.analysis.index.EsIndex; -import org.elasticsearch.xpack.sql.analysis.index.IndexResolution; -import org.elasticsearch.xpack.sql.expression.Alias; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.expression.function.FunctionRegistry; +import org.elasticsearch.xpack.sql.expression.function.SqlFunctionRegistry; import org.elasticsearch.xpack.sql.expression.function.grouping.Histogram; import org.elasticsearch.xpack.sql.expression.function.scalar.Cast; import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTimeProcessor.DateTimeExtractor; import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation; import org.elasticsearch.xpack.sql.expression.function.scalar.math.Round; -import org.elasticsearch.xpack.sql.expression.gen.script.ScriptTemplate; import org.elasticsearch.xpack.sql.optimizer.Optimizer; import org.elasticsearch.xpack.sql.parser.SqlParser; -import org.elasticsearch.xpack.sql.plan.logical.Aggregate; -import org.elasticsearch.xpack.sql.plan.logical.Filter; -import org.elasticsearch.xpack.sql.plan.logical.LogicalPlan; -import org.elasticsearch.xpack.sql.plan.logical.Project; import org.elasticsearch.xpack.sql.plan.physical.EsQueryExec; import org.elasticsearch.xpack.sql.plan.physical.PhysicalPlan; import org.elasticsearch.xpack.sql.planner.QueryFolder.FoldAggregate.GroupingContext; @@ -53,9 +54,7 @@ import org.elasticsearch.xpack.sql.querydsl.query.TermsQuery; import org.elasticsearch.xpack.sql.querydsl.query.WildcardQuery; import org.elasticsearch.xpack.sql.stats.Metrics; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.EsField; -import org.elasticsearch.xpack.sql.type.TypesTests; +import org.elasticsearch.xpack.sql.types.SqlTypesTests; import org.elasticsearch.xpack.sql.util.DateUtils; import org.junit.AfterClass; import org.junit.BeforeClass; @@ -67,10 +66,18 @@ import java.util.Map; import java.util.stream.Stream; +import static org.elasticsearch.xpack.ql.type.DataTypes.BOOLEAN; +import static org.elasticsearch.xpack.ql.type.DataTypes.DATETIME; +import static org.elasticsearch.xpack.ql.type.DataTypes.DOUBLE; +import static org.elasticsearch.xpack.ql.type.DataTypes.INTEGER; +import static org.elasticsearch.xpack.ql.type.DataTypes.KEYWORD; +import static org.elasticsearch.xpack.ql.type.DataTypes.LONG; +import static org.elasticsearch.xpack.ql.type.DataTypes.TEXT; import static org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation.E; import static org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor.MathOperation.PI; import static org.elasticsearch.xpack.sql.planner.QueryTranslator.DATE_FORMAT; import static org.elasticsearch.xpack.sql.planner.QueryTranslator.TIME_FORMAT; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.DATE; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.instanceOf; @@ -87,10 +94,10 @@ public class QueryTranslatorTests extends ESTestCase { public static void init() { parser = new SqlParser(); - Map mapping = TypesTests.loadMapping("mapping-multi-field-variation.json"); + Map mapping = SqlTypesTests.loadMapping("mapping-multi-field-variation.json"); EsIndex test = new EsIndex("test", mapping); IndexResolution getIndexResult = IndexResolution.valid(test); - analyzer = new Analyzer(TestUtils.TEST_CFG, new FunctionRegistry(), getIndexResult, new Verifier(new Metrics())); + analyzer = new Analyzer(SqlTestUtils.TEST_CFG, new SqlFunctionRegistry(), getIndexResult, new Verifier(new Metrics())); optimizer = new Optimizer(); planner = new Planner(); } @@ -240,38 +247,38 @@ public void testDateRangeCast() { } public void testDateRangeWithCurrentTimestamp() { - testDateRangeWithCurrentFunctions("CURRENT_TIMESTAMP()", DATE_FORMAT, TestUtils.TEST_CFG.now()); + testDateRangeWithCurrentFunctions("CURRENT_TIMESTAMP()", DATE_FORMAT, SqlTestUtils.TEST_CFG.now()); testDateRangeWithCurrentFunctions_AndRangeOptimization("CURRENT_TIMESTAMP()", DATE_FORMAT, - TestUtils.TEST_CFG.now().minusDays(1L).minusSeconds(1L), - TestUtils.TEST_CFG.now().plusDays(1L).plusSeconds(1L)); + SqlTestUtils.TEST_CFG.now().minusDays(1L).minusSeconds(1L), + SqlTestUtils.TEST_CFG.now().plusDays(1L).plusSeconds(1L)); } public void testDateRangeWithCurrentDate() { - testDateRangeWithCurrentFunctions("CURRENT_DATE()", DATE_FORMAT, DateUtils.asDateOnly(TestUtils.TEST_CFG.now())); + testDateRangeWithCurrentFunctions("CURRENT_DATE()", DATE_FORMAT, DateUtils.asDateOnly(SqlTestUtils.TEST_CFG.now())); testDateRangeWithCurrentFunctions_AndRangeOptimization("CURRENT_DATE()", DATE_FORMAT, - DateUtils.asDateOnly(TestUtils.TEST_CFG.now().minusDays(2L)), - DateUtils.asDateOnly(TestUtils.TEST_CFG.now().plusDays(1L))); + DateUtils.asDateOnly(SqlTestUtils.TEST_CFG.now().minusDays(1L)).minusSeconds(1), + DateUtils.asDateOnly(SqlTestUtils.TEST_CFG.now().plusDays(1L)).plusSeconds(1)); } public void testDateRangeWithToday() { - testDateRangeWithCurrentFunctions("TODAY()", DATE_FORMAT, DateUtils.asDateOnly(TestUtils.TEST_CFG.now())); + testDateRangeWithCurrentFunctions("TODAY()", DATE_FORMAT, DateUtils.asDateOnly(SqlTestUtils.TEST_CFG.now())); testDateRangeWithCurrentFunctions_AndRangeOptimization("TODAY()", DATE_FORMAT, - DateUtils.asDateOnly(TestUtils.TEST_CFG.now().minusDays(2L)), - DateUtils.asDateOnly(TestUtils.TEST_CFG.now().plusDays(1L))); + DateUtils.asDateOnly(SqlTestUtils.TEST_CFG.now().minusDays(1L)).minusSeconds(1), + DateUtils.asDateOnly(SqlTestUtils.TEST_CFG.now().plusDays(1L)).plusSeconds(1)); } public void testDateRangeWithNow() { - testDateRangeWithCurrentFunctions("NOW()", DATE_FORMAT, TestUtils.TEST_CFG.now()); + testDateRangeWithCurrentFunctions("NOW()", DATE_FORMAT, SqlTestUtils.TEST_CFG.now()); testDateRangeWithCurrentFunctions_AndRangeOptimization("NOW()", DATE_FORMAT, - TestUtils.TEST_CFG.now().minusDays(1L).minusSeconds(1L), - TestUtils.TEST_CFG.now().plusDays(1L).plusSeconds(1L)); + SqlTestUtils.TEST_CFG.now().minusDays(1L).minusSeconds(1L), + SqlTestUtils.TEST_CFG.now().plusDays(1L).plusSeconds(1L)); } public void testDateRangeWithCurrentTime() { - testDateRangeWithCurrentFunctions("CURRENT_TIME()", TIME_FORMAT, TestUtils.TEST_CFG.now()); + testDateRangeWithCurrentFunctions("CURRENT_TIME()", TIME_FORMAT, SqlTestUtils.TEST_CFG.now()); testDateRangeWithCurrentFunctions_AndRangeOptimization("CURRENT_TIME()", TIME_FORMAT, - TestUtils.TEST_CFG.now().minusDays(1L).minusSeconds(1L), - TestUtils.TEST_CFG.now().plusDays(1L).plusSeconds(1L)); + SqlTestUtils.TEST_CFG.now().minusDays(1L).minusSeconds(1L), + SqlTestUtils.TEST_CFG.now().plusDays(1L).plusSeconds(1L)); } private void testDateRangeWithCurrentFunctions(String function, String pattern, ZonedDateTime now) { @@ -323,7 +330,7 @@ private void testDateRangeWithCurrentFunctions_AndRangeOptimization(String funct EsQueryExec eqe = (EsQueryExec) p; assertEquals(1, eqe.output().size()); assertEquals("test.some.string", eqe.output().get(0).qualifiedName()); - assertEquals(DataType.TEXT, eqe.output().get(0).dataType()); + assertEquals(TEXT, eqe.output().get(0).dataType()); Query query = eqe.queryContainer().query(); // the range queries optimization should create a single "range" query with "from" and "to" populated with the values @@ -960,7 +967,7 @@ public void testGroupByDateHistogram() { assertEquals(1000, h.interval().fold()); Expression field = h.field(); assertEquals(FieldAttribute.class, field.getClass()); - assertEquals(DataType.INTEGER, field.dataType()); + assertEquals(INTEGER, field.dataType()); } public void testGroupByHistogram() { @@ -975,7 +982,7 @@ public void testGroupByHistogram() { assertEquals("+2-0", h.interval().fold().toString()); Expression field = h.field(); assertEquals(FieldAttribute.class, field.getClass()); - assertEquals(DataType.DATETIME, field.dataType()); + assertEquals(DATETIME, field.dataType()); } public void testGroupByHistogramQueryTranslator() { @@ -984,7 +991,7 @@ public void testGroupByHistogramQueryTranslator() { EsQueryExec eqe = (EsQueryExec) p; assertEquals(1, eqe.output().size()); assertEquals("MAX(int)", eqe.output().get(0).qualifiedName()); - assertEquals(DataType.INTEGER, eqe.output().get(0).dataType()); + assertEquals(INTEGER, eqe.output().get(0).dataType()); assertThat(eqe.queryContainer().aggs().asAggBuilder().toString().replaceAll("\\s+", ""), containsString("\"date_histogram\":{\"field\":\"date\",\"missing_bucket\":true,\"value_type\":\"date\",\"order\":\"asc\"," + "\"fixed_interval\":\"62208000000ms\",\"time_zone\":\"Z\"}}}]}")); @@ -996,7 +1003,7 @@ public void testGroupByYearQueryTranslator() { EsQueryExec eqe = (EsQueryExec) p; assertEquals(1, eqe.output().size()); assertEquals("YEAR(date)", eqe.output().get(0).qualifiedName()); - assertEquals(DataType.INTEGER, eqe.output().get(0).dataType()); + assertEquals(INTEGER, eqe.output().get(0).dataType()); assertThat(eqe.queryContainer().aggs().asAggBuilder().toString().replaceAll("\\s+", ""), endsWith("\"date_histogram\":{\"field\":\"date\",\"missing_bucket\":true,\"value_type\":\"date\",\"order\":\"asc\"," + "\"calendar_interval\":\"1y\",\"time_zone\":\"Z\"}}}]}}}")); @@ -1008,7 +1015,7 @@ public void testGroupByYearAndScalarsQueryTranslator() { EsQueryExec eqe = (EsQueryExec) p; assertEquals(1, eqe.output().size()); assertEquals("YEAR(CAST(date + INTERVAL 5 months AS DATE))", eqe.output().get(0).qualifiedName()); - assertEquals(DataType.INTEGER, eqe.output().get(0).dataType()); + assertEquals(INTEGER, eqe.output().get(0).dataType()); assertThat(eqe.queryContainer().aggs().asAggBuilder().toString().replaceAll("\\s+", ""), endsWith("\"date_histogram\":{\"script\":{\"source\":\"InternalSqlScriptUtils.cast(" + "InternalSqlScriptUtils.add(InternalSqlScriptUtils.docValue(doc,params.v0)," + @@ -1030,7 +1037,7 @@ public void testGroupByHistogramWithDate() { assertEquals("+0-2", h.interval().fold().toString()); Expression field = h.field(); assertEquals(Cast.class, field.getClass()); - assertEquals(DataType.DATE, field.dataType()); + assertEquals(DATE, field.dataType()); } public void testGroupByHistogramWithDateAndSmallInterval() { @@ -1157,7 +1164,7 @@ public void testGroupByCastScalar() { assertEquals(EsQueryExec.class, p.getClass()); assertEquals(1, p.output().size()); assertEquals("CAST(ABS(EXTRACT(YEAR FROM date)) AS BIGINT)", p.output().get(0).qualifiedName()); - assertEquals(DataType.LONG, p.output().get(0).dataType()); + assertEquals(LONG, p.output().get(0).dataType()); assertThat( ((EsQueryExec) p).queryContainer().aggs().asAggBuilder().toString() .replaceAll("\\s+", ""), @@ -1174,7 +1181,7 @@ public void testGroupByCastScalarWithAlias() { assertEquals(EsQueryExec.class, p.getClass()); assertEquals(1, p.output().size()); assertEquals("cast", p.output().get(0).qualifiedName()); - assertEquals(DataType.LONG, p.output().get(0).dataType()); + assertEquals(LONG, p.output().get(0).dataType()); assertThat( ((EsQueryExec) p).queryContainer().aggs().asAggBuilder().toString() .replaceAll("\\s+", ""), @@ -1191,7 +1198,7 @@ public void testGroupByCastScalarWithNumericRef() { assertEquals(EsQueryExec.class, p.getClass()); assertEquals(1, p.output().size()); assertEquals("CAST(ABS(EXTRACT(YEAR FROM date)) AS BIGINT)", p.output().get(0).qualifiedName()); - assertEquals(DataType.LONG, p.output().get(0).dataType()); + assertEquals(LONG, p.output().get(0).dataType()); assertThat( ((EsQueryExec) p).queryContainer().aggs().asAggBuilder().toString() .replaceAll("\\s+", ""), @@ -1210,7 +1217,7 @@ public void testGroupByConvertScalar() { assertEquals(EsQueryExec.class, p.getClass()); assertEquals(1, p.output().size()); assertEquals("CONVERT(ABS(EXTRACT(YEAR FROM date)), SQL_BIGINT)", p.output().get(0).qualifiedName()); - assertEquals(DataType.LONG, p.output().get(0).dataType()); + assertEquals(LONG, p.output().get(0).dataType()); assertThat( ((EsQueryExec) p).queryContainer().aggs().asAggBuilder().toString() .replaceAll("\\s+", ""), @@ -1226,7 +1233,7 @@ public void testGroupByConvertScalar() { assertEquals(EsQueryExec.class, p.getClass()); assertEquals(1, p.output().size()); assertEquals("EXTRACT(HOUR FROM CONVERT(date, SQL_TIMESTAMP))", p.output().get(0).qualifiedName()); - assertEquals(DataType.INTEGER, p.output().get(0).dataType()); + assertEquals(INTEGER, p.output().get(0).dataType()); assertThat( ((EsQueryExec) p).queryContainer().aggs().asAggBuilder().toString() .replaceAll("\\s+", ""), @@ -1245,7 +1252,7 @@ public void testGroupByConvertScalarWithAlias() { assertEquals(EsQueryExec.class, p.getClass()); assertEquals(1, p.output().size()); assertEquals("convert", p.output().get(0).qualifiedName()); - assertEquals(DataType.LONG, p.output().get(0).dataType()); + assertEquals(LONG, p.output().get(0).dataType()); assertThat( ((EsQueryExec) p).queryContainer().aggs().asAggBuilder().toString() .replaceAll("\\s+", ""), @@ -1260,7 +1267,7 @@ public void testGroupByConvertScalarWithAlias() { assertEquals(EsQueryExec.class, p.getClass()); assertEquals(1, p.output().size()); assertEquals("x", p.output().get(0).qualifiedName()); - assertEquals(DataType.INTEGER, p.output().get(0).dataType()); + assertEquals(INTEGER, p.output().get(0).dataType()); assertThat( ((EsQueryExec) p).queryContainer().aggs().asAggBuilder().toString() .replaceAll("\\s+", ""), @@ -1278,7 +1285,7 @@ public void testGroupByConvertScalarWithNumericRef() { assertEquals(EsQueryExec.class, p.getClass()); assertEquals(1, p.output().size()); assertEquals("CONVERT(ABS(EXTRACT(YEAR FROM date)), SQL_BIGINT)", p.output().get(0).qualifiedName()); - assertEquals(DataType.LONG, p.output().get(0).dataType()); + assertEquals(LONG, p.output().get(0).dataType()); assertThat( ((EsQueryExec) p).queryContainer().aggs().asAggBuilder().toString() .replaceAll("\\s+", ""), @@ -1295,7 +1302,7 @@ public void testGroupByConstantScalar() { assertEquals(EsQueryExec.class, p.getClass()); assertEquals(1, p.output().size()); assertEquals("PI() * int", p.output().get(0).qualifiedName()); - assertEquals(DataType.DOUBLE, p.output().get(0).dataType()); + assertEquals(DOUBLE, p.output().get(0).dataType()); assertThat( ((EsQueryExec) p).queryContainer().aggs().asAggBuilder().toString() .replaceAll("\\s+", ""), @@ -1312,7 +1319,7 @@ public void testGroupByConstantScalarWithAlias() { assertEquals(EsQueryExec.class, p.getClass()); assertEquals(1, p.output().size()); assertEquals("value", p.output().get(0).qualifiedName()); - assertEquals(DataType.DOUBLE, p.output().get(0).dataType()); + assertEquals(DOUBLE, p.output().get(0).dataType()); assertThat( ((EsQueryExec) p).queryContainer().aggs().asAggBuilder().toString() .replaceAll("\\s+", ""), @@ -1326,9 +1333,9 @@ public void testGroupByConstantScalarWithAlias() { assertEquals(EsQueryExec.class, p.getClass()); assertEquals(2, p.output().size()); assertEquals("multi_language", p.output().get(0).qualifiedName()); - assertEquals(DataType.BOOLEAN, p.output().get(0).dataType()); + assertEquals(BOOLEAN, p.output().get(0).dataType()); assertEquals("count(*)", p.output().get(1).qualifiedName()); - assertEquals(DataType.LONG, p.output().get(1).dataType()); + assertEquals(LONG, p.output().get(1).dataType()); assertThat( ((EsQueryExec) p).queryContainer().aggs().asAggBuilder().toString() .replaceAll("\\s+", ""), @@ -1346,7 +1353,7 @@ public void testGroupByConstantScalarWithNumericRef() { assertEquals(EsQueryExec.class, p.getClass()); assertEquals(1, p.output().size()); assertEquals("PI() * int", p.output().get(0).qualifiedName()); - assertEquals(DataType.DOUBLE, p.output().get(0).dataType()); + assertEquals(DOUBLE, p.output().get(0).dataType()); assertThat( ((EsQueryExec) p).queryContainer().aggs().asAggBuilder().toString() .replaceAll("\\s+", ""), @@ -1360,7 +1367,7 @@ public void testGroupByConstantScalarWithNumericRef() { assertEquals(EsQueryExec.class, p.getClass()); assertEquals(1, p.output().size()); assertEquals("PI() * int", p.output().get(0).qualifiedName()); - assertEquals(DataType.DOUBLE, p.output().get(0).dataType()); + assertEquals(DOUBLE, p.output().get(0).dataType()); assertThat( ((EsQueryExec) p).queryContainer().aggs().asAggBuilder().toString() .replaceAll("\\s+", ""), @@ -1374,7 +1381,7 @@ public void testGroupByConstantScalarWithNumericRef() { assertEquals(EsQueryExec.class, p.getClass()); assertEquals(1, p.output().size()); assertEquals("date + 1 * INTERVAL '1' DAY", p.output().get(0).qualifiedName()); - assertEquals(DataType.DATETIME, p.output().get(0).dataType()); + assertEquals(DATETIME, p.output().get(0).dataType()); assertThat( ((EsQueryExec) p).queryContainer().aggs().asAggBuilder().toString() .replaceAll("\\s+", ""), @@ -1391,7 +1398,7 @@ public void testOrderByWithCastWithMissingRefs() { assertEquals(EsQueryExec.class, p.getClass()); assertEquals(1, p.output().size()); assertEquals("test.keyword", p.output().get(0).qualifiedName()); - assertEquals(DataType.KEYWORD, p.output().get(0).dataType()); + assertEquals(KEYWORD, p.output().get(0).dataType()); assertThat( ((EsQueryExec) p).queryContainer().toString() .replaceAll("\\s+", ""), @@ -1409,7 +1416,7 @@ public void testTopHitsAggregationWithOneArg() { EsQueryExec eqe = (EsQueryExec) p; assertEquals(1, eqe.output().size()); assertEquals("FIRST(keyword)", eqe.output().get(0).qualifiedName()); - assertEquals(DataType.KEYWORD, eqe.output().get(0).dataType()); + assertEquals(KEYWORD, eqe.output().get(0).dataType()); assertThat(eqe.queryContainer().aggs().asAggBuilder().toString().replaceAll("\\s+", ""), endsWith("\"top_hits\":{\"from\":0,\"size\":1,\"version\":false,\"seq_no_primary_term\":false," + "\"explain\":false,\"docvalue_fields\":[{\"field\":\"keyword\"}]," + @@ -1421,7 +1428,7 @@ public void testTopHitsAggregationWithOneArg() { EsQueryExec eqe = (EsQueryExec) p; assertEquals(1, eqe.output().size()); assertEquals("MIN(keyword)", eqe.output().get(0).qualifiedName()); - assertEquals(DataType.KEYWORD, eqe.output().get(0).dataType()); + assertEquals(KEYWORD, eqe.output().get(0).dataType()); assertThat(eqe.queryContainer().aggs().asAggBuilder().toString().replaceAll("\\s+", ""), endsWith("\"top_hits\":{\"from\":0,\"size\":1,\"version\":false,\"seq_no_primary_term\":false," + "\"explain\":false,\"docvalue_fields\":[{\"field\":\"keyword\"}]," + @@ -1433,7 +1440,7 @@ public void testTopHitsAggregationWithOneArg() { EsQueryExec eqe = (EsQueryExec) p; assertEquals(1, eqe.output().size()); assertEquals("LAST(date)", eqe.output().get(0).qualifiedName()); - assertEquals(DataType.DATETIME, eqe.output().get(0).dataType()); + assertEquals(DATETIME, eqe.output().get(0).dataType()); assertThat(eqe.queryContainer().aggs().asAggBuilder().toString().replaceAll("\\s+", ""), endsWith("\"top_hits\":{\"from\":0,\"size\":1,\"version\":false,\"seq_no_primary_term\":false," + "\"explain\":false,\"docvalue_fields\":[{\"field\":\"date\",\"format\":\"epoch_millis\"}]," + @@ -1445,7 +1452,7 @@ public void testTopHitsAggregationWithOneArg() { EsQueryExec eqe = (EsQueryExec) p; assertEquals(1, eqe.output().size()); assertEquals("MAX(keyword)", eqe.output().get(0).qualifiedName()); - assertEquals(DataType.KEYWORD, eqe.output().get(0).dataType()); + assertEquals(KEYWORD, eqe.output().get(0).dataType()); assertThat(eqe.queryContainer().aggs().asAggBuilder().toString().replaceAll("\\s+", ""), endsWith("\"top_hits\":{\"from\":0,\"size\":1,\"version\":false,\"seq_no_primary_term\":false," + "\"explain\":false,\"docvalue_fields\":[{\"field\":\"keyword\"}]," + @@ -1460,7 +1467,7 @@ public void testTopHitsAggregationWithTwoArgs() { EsQueryExec eqe = (EsQueryExec) p; assertEquals(1, eqe.output().size()); assertEquals("FIRST(keyword, int)", eqe.output().get(0).qualifiedName()); - assertEquals(DataType.KEYWORD, eqe.output().get(0).dataType()); + assertEquals(KEYWORD, eqe.output().get(0).dataType()); assertThat(eqe.queryContainer().aggs().asAggBuilder().toString().replaceAll("\\s+", ""), endsWith("\"top_hits\":{\"from\":0,\"size\":1,\"version\":false,\"seq_no_primary_term\":false," + "\"explain\":false,\"docvalue_fields\":[{\"field\":\"keyword\"}]," + @@ -1474,7 +1481,7 @@ public void testTopHitsAggregationWithTwoArgs() { EsQueryExec eqe = (EsQueryExec) p; assertEquals(1, eqe.output().size()); assertEquals("LAST(date, int)", eqe.output().get(0).qualifiedName()); - assertEquals(DataType.DATETIME, eqe.output().get(0).dataType()); + assertEquals(DATETIME, eqe.output().get(0).dataType()); assertThat(eqe.queryContainer().aggs().asAggBuilder().toString().replaceAll("\\s+", ""), endsWith("\"top_hits\":{\"from\":0,\"size\":1,\"version\":false,\"seq_no_primary_term\":false," + "\"explain\":false,\"docvalue_fields\":[{\"field\":\"date\",\"format\":\"epoch_millis\"}]," + diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/plugin/CursorTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/plugin/CursorTests.java index 28d9c278ed163..dc08c5d552784 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/plugin/CursorTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/plugin/CursorTests.java @@ -12,8 +12,8 @@ import org.elasticsearch.client.Client; import org.elasticsearch.common.logging.LoggerMessageFormat; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.SqlException; -import org.elasticsearch.xpack.sql.TestUtils; +import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; +import org.elasticsearch.xpack.sql.SqlTestUtils; import org.elasticsearch.xpack.sql.action.BasicFormatter; import org.elasticsearch.xpack.sql.action.SqlQueryResponse; import org.elasticsearch.xpack.sql.execution.search.ScrollCursor; @@ -43,7 +43,7 @@ public void testEmptyCursorClearCursor() { Client clientMock = mock(Client.class); Cursor cursor = Cursor.EMPTY; PlainActionFuture future = newFuture(); - cursor.clear(TestUtils.TEST_CFG, clientMock, future); + cursor.clear(SqlTestUtils.TEST_CFG, clientMock, future); assertFalse(future.actionGet()); verifyZeroInteractions(clientMock); } @@ -55,7 +55,7 @@ public void testScrollCursorClearCursor() { String cursorString = randomAlphaOfLength(10); Cursor cursor = new ScrollCursor(cursorString, Collections.emptyList(), new BitSet(0), randomInt()); - cursor.clear(TestUtils.TEST_CFG, clientMock, listenerMock); + cursor.clear(SqlTestUtils.TEST_CFG, clientMock, listenerMock); ArgumentCaptor request = ArgumentCaptor.forClass(ClearScrollRequest.class); verify(clientMock).clearScroll(request.capture(), any(ActionListener.class)); @@ -109,7 +109,8 @@ public void testVersionHandling() { Version nextMinorVersion = Version.fromId(Version.CURRENT.id + 10000); String encodedWithWrongVersion = CursorsTestUtil.encodeToString(cursor, nextMinorVersion, randomZone()); - SqlException exception = expectThrows(SqlException.class, () -> Cursors.decodeFromString(encodedWithWrongVersion)); + SqlIllegalArgumentException exception = expectThrows(SqlIllegalArgumentException.class, + () -> Cursors.decodeFromString(encodedWithWrongVersion)); assertEquals(LoggerMessageFormat.format("Unsupported cursor version [{}], expected [{}]", nextMinorVersion, Version.CURRENT), exception.getMessage()); diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/querydsl/container/QueryContainerTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/querydsl/container/QueryContainerTests.java index 432be5fea4a8f..e35b38ff4ada5 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/querydsl/container/QueryContainerTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/querydsl/container/QueryContainerTests.java @@ -6,20 +6,19 @@ package org.elasticsearch.xpack.sql.querydsl.container; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.expression.Alias; -import org.elasticsearch.xpack.sql.expression.Attribute; -import org.elasticsearch.xpack.sql.expression.AttributeMap; -import org.elasticsearch.xpack.sql.expression.Expression; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.expression.Alias; +import org.elasticsearch.xpack.ql.expression.Attribute; +import org.elasticsearch.xpack.ql.expression.AttributeMap; +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.tree.SourceTests; +import org.elasticsearch.xpack.ql.type.EsField; import org.elasticsearch.xpack.sql.querydsl.query.BoolQuery; import org.elasticsearch.xpack.sql.querydsl.query.MatchAll; import org.elasticsearch.xpack.sql.querydsl.query.NestedQuery; import org.elasticsearch.xpack.sql.querydsl.query.Query; import org.elasticsearch.xpack.sql.querydsl.query.RangeQuery; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.SourceTests; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.EsField; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.Arrays; @@ -29,6 +28,7 @@ import static java.util.Collections.emptyMap; import static java.util.Collections.singletonMap; +import static org.elasticsearch.xpack.ql.type.DataTypes.TEXT; public class QueryContainerTests extends ESTestCase { private Source source = SourceTests.randomSource(); @@ -74,7 +74,7 @@ public void testRewriteToContainsNestedFieldWhenDoesNotContainNestedFieldAndCant public void testColumnMaskShouldDuplicateSameAttributes() { - EsField esField = new EsField("str", DataType.TEXT, emptyMap(), true); + EsField esField = new EsField("str", TEXT, emptyMap(), true); Attribute first = new FieldAttribute(Source.EMPTY, "first", esField); Attribute second = new FieldAttribute(Source.EMPTY, "second", esField); diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/querydsl/query/BoolQueryTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/querydsl/query/BoolQueryTests.java index ac6b85538805c..43f49630e4b2a 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/querydsl/query/BoolQueryTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/querydsl/query/BoolQueryTests.java @@ -7,9 +7,9 @@ import org.elasticsearch.search.sort.NestedSortBuilder; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.SourceTests; -import org.elasticsearch.xpack.sql.util.StringUtils; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.tree.SourceTests; +import org.elasticsearch.xpack.ql.util.StringUtils; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.Arrays; diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/querydsl/query/LeafQueryTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/querydsl/query/LeafQueryTests.java index 29ede49d98248..58bd29f8593fa 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/querydsl/query/LeafQueryTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/querydsl/query/LeafQueryTests.java @@ -8,9 +8,9 @@ import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.search.sort.NestedSortBuilder; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.SourceTests; -import org.elasticsearch.xpack.sql.util.StringUtils; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.tree.SourceTests; +import org.elasticsearch.xpack.ql.util.StringUtils; import static org.elasticsearch.test.EqualsHashCodeTestUtils.checkEqualsAndHashCode; diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/querydsl/query/MatchQueryTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/querydsl/query/MatchQueryTests.java index 1660ea3b8e8cb..2928ab3b98946 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/querydsl/query/MatchQueryTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/querydsl/query/MatchQueryTests.java @@ -8,13 +8,12 @@ import org.elasticsearch.index.query.MatchQueryBuilder; import org.elasticsearch.index.query.Operator; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.expression.FieldAttribute; -import org.elasticsearch.xpack.sql.expression.predicate.fulltext.MatchQueryPredicate; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.SourceTests; -import org.elasticsearch.xpack.sql.type.DataType; -import org.elasticsearch.xpack.sql.type.EsField; -import org.elasticsearch.xpack.sql.util.StringUtils; +import org.elasticsearch.xpack.ql.expression.FieldAttribute; +import org.elasticsearch.xpack.ql.expression.predicate.fulltext.MatchQueryPredicate; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.tree.SourceTests; +import org.elasticsearch.xpack.ql.type.EsField; +import org.elasticsearch.xpack.ql.util.StringUtils; import java.util.Arrays; import java.util.List; @@ -22,7 +21,8 @@ import static java.util.Collections.emptyMap; import static org.elasticsearch.test.EqualsHashCodeTestUtils.checkEqualsAndHashCode; -import static org.elasticsearch.xpack.sql.tree.Source.EMPTY; +import static org.elasticsearch.xpack.ql.tree.Source.EMPTY; +import static org.elasticsearch.xpack.ql.type.DataTypes.KEYWORD; import static org.hamcrest.Matchers.equalTo; public class MatchQueryTests extends ESTestCase { @@ -68,7 +68,7 @@ public void testQueryBuilding() { private static MatchQueryBuilder getBuilder(String options) { final Source source = new Source(1, 1, StringUtils.EMPTY); - FieldAttribute fa = new FieldAttribute(EMPTY, "a", new EsField("af", DataType.KEYWORD, emptyMap(), true)); + FieldAttribute fa = new FieldAttribute(EMPTY, "a", new EsField("af", KEYWORD, emptyMap(), true)); final MatchQueryPredicate mmqp = new MatchQueryPredicate(source, fa, "eggplant", options); final MatchQuery mmq = new MatchQuery(source, "eggplant", "foo", mmqp); return (MatchQueryBuilder) mmq.asBuilder(); @@ -76,7 +76,7 @@ private static MatchQueryBuilder getBuilder(String options) { public void testToString() { final Source source = new Source(1, 1, StringUtils.EMPTY); - FieldAttribute fa = new FieldAttribute(EMPTY, "a", new EsField("af", DataType.KEYWORD, emptyMap(), true)); + FieldAttribute fa = new FieldAttribute(EMPTY, "a", new EsField("af", KEYWORD, emptyMap(), true)); final MatchQueryPredicate mmqp = new MatchQueryPredicate(source, fa, "eggplant", ""); final MatchQuery mmq = new MatchQuery(source, "eggplant", "foo", mmqp); assertEquals("MatchQuery@1:2[eggplant:foo]", mmq.toString()); diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/querydsl/query/MultiMatchQueryTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/querydsl/query/MultiMatchQueryTests.java index fb9c8d805cd18..6fddc2eabc975 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/querydsl/query/MultiMatchQueryTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/querydsl/query/MultiMatchQueryTests.java @@ -8,9 +8,9 @@ import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.index.query.MultiMatchQueryBuilder; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.expression.predicate.fulltext.MultiMatchQueryPredicate; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.util.StringUtils; +import org.elasticsearch.xpack.ql.expression.predicate.fulltext.MultiMatchQueryPredicate; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.util.StringUtils; import java.util.HashMap; import java.util.Map; diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/querydsl/query/NestedQueryTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/querydsl/query/NestedQueryTests.java index a1d1c7c93f561..4975ac6326ec0 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/querydsl/query/NestedQueryTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/querydsl/query/NestedQueryTests.java @@ -7,9 +7,9 @@ import org.elasticsearch.search.sort.NestedSortBuilder; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.tree.SourceTests; -import org.elasticsearch.xpack.sql.util.StringUtils; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.tree.SourceTests; +import org.elasticsearch.xpack.ql.util.StringUtils; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.ArrayList; diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/querydsl/query/QueryStringQueryTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/querydsl/query/QueryStringQueryTests.java index 89e88b3e9af1f..c97e6b678d353 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/querydsl/query/QueryStringQueryTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/querydsl/query/QueryStringQueryTests.java @@ -9,9 +9,9 @@ import org.elasticsearch.index.query.Operator; import org.elasticsearch.index.query.QueryStringQueryBuilder; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.expression.predicate.fulltext.StringQueryPredicate; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.util.StringUtils; +import org.elasticsearch.xpack.ql.expression.predicate.fulltext.StringQueryPredicate; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.util.StringUtils; import java.util.Collections; diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/stats/VerifierMetricsTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/stats/VerifierMetricsTests.java index 5d263ec458523..55eb0c234f533 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/stats/VerifierMetricsTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/stats/VerifierMetricsTests.java @@ -8,15 +8,15 @@ import org.elasticsearch.test.ESTestCase; import org.elasticsearch.xpack.core.watcher.common.stats.Counters; -import org.elasticsearch.xpack.sql.TestUtils; +import org.elasticsearch.xpack.ql.index.EsIndex; +import org.elasticsearch.xpack.ql.index.IndexResolution; +import org.elasticsearch.xpack.ql.type.EsField; +import org.elasticsearch.xpack.sql.SqlTestUtils; import org.elasticsearch.xpack.sql.analysis.analyzer.Analyzer; import org.elasticsearch.xpack.sql.analysis.analyzer.Verifier; -import org.elasticsearch.xpack.sql.analysis.index.EsIndex; -import org.elasticsearch.xpack.sql.analysis.index.IndexResolution; -import org.elasticsearch.xpack.sql.expression.function.FunctionRegistry; +import org.elasticsearch.xpack.sql.expression.function.SqlFunctionRegistry; import org.elasticsearch.xpack.sql.parser.SqlParser; -import org.elasticsearch.xpack.sql.type.EsField; -import org.elasticsearch.xpack.sql.type.TypesTests; +import org.elasticsearch.xpack.sql.types.SqlTypesTests; import java.util.Map; @@ -229,7 +229,7 @@ private void sqlWithVerifier(String sql, Verifier verifier) { } private Counters sql(String sql, Verifier v) { - Map mapping = TypesTests.loadMapping("mapping-basic.json"); + Map mapping = SqlTypesTests.loadMapping("mapping-basic.json"); EsIndex test = new EsIndex("test", mapping); Verifier verifier = v; @@ -239,9 +239,9 @@ private Counters sql(String sql, Verifier v) { verifier = new Verifier(metrics); } - Analyzer analyzer = new Analyzer(TestUtils.TEST_CFG, new FunctionRegistry(), IndexResolution.valid(test), verifier); + Analyzer analyzer = new Analyzer(SqlTestUtils.TEST_CFG, new SqlFunctionRegistry(), IndexResolution.valid(test), verifier); analyzer.analyze(parser.createStatement(sql), true); return metrics == null ? null : metrics.stats(); } -} +} \ No newline at end of file diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/tree/SqlNodeSubclassTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/tree/SqlNodeSubclassTests.java new file mode 100644 index 0000000000000..abbfc98418609 --- /dev/null +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/tree/SqlNodeSubclassTests.java @@ -0,0 +1,95 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +package org.elasticsearch.xpack.sql.tree; + +import org.elasticsearch.xpack.ql.expression.Expression; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.expression.LiteralTests; +import org.elasticsearch.xpack.ql.tree.Node; +import org.elasticsearch.xpack.ql.tree.NodeSubclassTests; +import org.elasticsearch.xpack.ql.tree.SourceTests; +import org.elasticsearch.xpack.sql.expression.function.aggregate.Avg; +import org.elasticsearch.xpack.sql.expression.function.aggregate.CompoundNumericAggregate; +import org.elasticsearch.xpack.sql.expression.function.aggregate.Percentile; +import org.elasticsearch.xpack.sql.expression.function.aggregate.PercentileRanks; +import org.elasticsearch.xpack.sql.expression.function.aggregate.Percentiles; +import org.elasticsearch.xpack.sql.expression.function.grouping.Histogram; +import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.CurrentDateTime; +import org.elasticsearch.xpack.sql.expression.predicate.conditional.IfConditional; +import org.elasticsearch.xpack.sql.expression.predicate.conditional.IfNull; +import org.elasticsearch.xpack.sql.expression.predicate.conditional.Iif; +import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.In; +import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.InPipe; + +import java.util.List; + +import static java.util.Arrays.asList; +import static org.elasticsearch.xpack.ql.type.DataTypes.INTEGER; + +/** + * Looks for all subclasses of {@link Node} and verifies that they + * implement {@link Node#info()} and + * {@link Node#replaceChildren(List)} sanely. It'd be better if + * each subclass had its own test case that verified those methods + * and any other interesting things that that they do but we're a + * long way from that and this gets the job done for now. + *

    + * This test attempts to use reflection to create believeable nodes + * and manipulate them in believeable ways with as little knowledge + * of the actual subclasses as possible. This is problematic because + * it is possible, for example, for nodes to stackoverflow because + * they can contain themselves. So this class + * does have some {@link Node}-subclass-specific + * knowledge. As little as I could get away with though. + *

    + * When there are actual tests for a subclass of {@linkplain Node} + * then this class will do two things: + *

      + *
    • Skip running any tests for that subclass entirely. + *
    • Delegate to that test to build nodes of that type when a + * node of that type is called for. + *
    + */ +public class SqlNodeSubclassTests> extends NodeSubclassTests { + + private static final List> CLASSES_WITH_MIN_TWO_CHILDREN = asList(Percentile.class, Percentiles.class, PercentileRanks.class, + Iif.class, IfConditional.class, IfNull.class, In.class, InPipe.class); + + + public SqlNodeSubclassTests(Class subclass) { + super(subclass); + } + + @Override + protected boolean hasAtLeastTwoChildren(Class> toBuildClass) { + return CLASSES_WITH_MIN_TWO_CHILDREN.stream().anyMatch(toBuildClass::equals); + } + + @Override + protected Object makeCompoundAgg() throws Exception { + return makeNode(CompoundNumericAggregate.class); + } + + @Override + protected Object makeEnclosedAgg() { + return makeArg(Avg.class); + } + + @Override + protected Object pluggableMakeArg(Class> toBuildClass, Class argClass) { + if (toBuildClass == Histogram.class) { + if (argClass == Expression.class) { + return LiteralTests.randomLiteral(); + } + } else if (toBuildClass == CurrentDateTime.class) { + if (argClass == Expression.class) { + return new Literal(SourceTests.randomSource(), randomInt(9), INTEGER); + } + } + + return null; + } +} \ No newline at end of file diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/type/DataTypeConversionTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/type/SqlDataTypeConverterTests.java similarity index 67% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/type/DataTypeConversionTests.java rename to x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/type/SqlDataTypeConverterTests.java index 76c629ad1dc3d..9a2db21d6ec70 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/type/DataTypeConversionTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/type/SqlDataTypeConverterTests.java @@ -3,72 +3,69 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ + package org.elasticsearch.xpack.sql.type; import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.xpack.sql.SqlIllegalArgumentException; -import org.elasticsearch.xpack.sql.TestUtils; -import org.elasticsearch.xpack.sql.expression.Literal; -import org.elasticsearch.xpack.sql.tree.Location; -import org.elasticsearch.xpack.sql.tree.Source; -import org.elasticsearch.xpack.sql.type.DataTypeConversion.Conversion; +import org.elasticsearch.xpack.ql.QlIllegalArgumentException; +import org.elasticsearch.xpack.ql.expression.Literal; +import org.elasticsearch.xpack.ql.tree.Location; +import org.elasticsearch.xpack.ql.tree.Source; +import org.elasticsearch.xpack.ql.type.Converter; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.sql.util.DateUtils; import java.time.OffsetTime; import java.time.ZoneOffset; import java.time.ZonedDateTime; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import static org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTimeTestUtils.date; -import static org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTimeTestUtils.dateTime; -import static org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTimeTestUtils.time; -import static org.elasticsearch.xpack.sql.type.DataType.BOOLEAN; -import static org.elasticsearch.xpack.sql.type.DataType.BYTE; -import static org.elasticsearch.xpack.sql.type.DataType.DATE; -import static org.elasticsearch.xpack.sql.type.DataType.DATETIME; -import static org.elasticsearch.xpack.sql.type.DataType.DOUBLE; -import static org.elasticsearch.xpack.sql.type.DataType.FLOAT; -import static org.elasticsearch.xpack.sql.type.DataType.INTEGER; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_HOUR_TO_MINUTE; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_HOUR_TO_SECOND; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_MONTH; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_SECOND; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_YEAR; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_YEAR_TO_MONTH; -import static org.elasticsearch.xpack.sql.type.DataType.IP; -import static org.elasticsearch.xpack.sql.type.DataType.KEYWORD; -import static org.elasticsearch.xpack.sql.type.DataType.LONG; -import static org.elasticsearch.xpack.sql.type.DataType.NULL; -import static org.elasticsearch.xpack.sql.type.DataType.SHORT; -import static org.elasticsearch.xpack.sql.type.DataType.TEXT; -import static org.elasticsearch.xpack.sql.type.DataType.TIME; -import static org.elasticsearch.xpack.sql.type.DataType.UNSUPPORTED; -import static org.elasticsearch.xpack.sql.type.DataType.fromTypeName; -import static org.elasticsearch.xpack.sql.type.DataType.values; -import static org.elasticsearch.xpack.sql.type.DataTypeConversion.commonType; -import static org.elasticsearch.xpack.sql.type.DataTypeConversion.conversionFor; + +import static java.util.stream.Collectors.toList; +import static org.elasticsearch.xpack.ql.type.DataTypes.BOOLEAN; +import static org.elasticsearch.xpack.ql.type.DataTypes.BYTE; +import static org.elasticsearch.xpack.ql.type.DataTypes.DATETIME; +import static org.elasticsearch.xpack.ql.type.DataTypes.DOUBLE; +import static org.elasticsearch.xpack.ql.type.DataTypes.FLOAT; +import static org.elasticsearch.xpack.ql.type.DataTypes.INTEGER; +import static org.elasticsearch.xpack.ql.type.DataTypes.IP; +import static org.elasticsearch.xpack.ql.type.DataTypes.KEYWORD; +import static org.elasticsearch.xpack.ql.type.DataTypes.LONG; +import static org.elasticsearch.xpack.ql.type.DataTypes.NULL; +import static org.elasticsearch.xpack.ql.type.DataTypes.SHORT; +import static org.elasticsearch.xpack.ql.type.DataTypes.TEXT; +import static org.elasticsearch.xpack.ql.type.DataTypes.UNSUPPORTED; +import static org.elasticsearch.xpack.sql.type.SqlDataTypeConverter.commonType; +import static org.elasticsearch.xpack.sql.type.SqlDataTypeConverter.converterFor; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.DATE; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_HOUR_TO_MINUTE; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_HOUR_TO_SECOND; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_MONTH; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_SECOND; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_YEAR; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_YEAR_TO_MONTH; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.TIME; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.fromTypeName; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.types; import static org.elasticsearch.xpack.sql.util.DateUtils.asDateOnly; import static org.elasticsearch.xpack.sql.util.DateUtils.asDateTime; import static org.elasticsearch.xpack.sql.util.DateUtils.asTimeOnly; - -public class DataTypeConversionTests extends ESTestCase { +public class SqlDataTypeConverterTests extends ESTestCase { public void testConversionToString() { DataType to = KEYWORD; { - Conversion conversion = conversionFor(DOUBLE, to); + Converter conversion = converterFor(DOUBLE, to); assertNull(conversion.convert(null)); assertEquals("10.0", conversion.convert(10.0)); } { - Conversion conversion = conversionFor(DATE, to); + Converter conversion = converterFor(DATE, to); assertNull(conversion.convert(null)); assertEquals("1973-11-29", conversion.convert(asDateOnly(123456789101L))); assertEquals("1966-02-02", conversion.convert(asDateOnly(-123456789101L))); } { - Conversion conversion = conversionFor(TIME, to); + Converter conversion = converterFor(TIME, to); assertNull(conversion.convert(null)); assertEquals("00:02:03.456Z", conversion.convert(asTimeOnly(123456L))); assertEquals("21:33:09.101Z", conversion.convert(asTimeOnly(123456789101L))); @@ -76,7 +73,7 @@ public void testConversionToString() { assertEquals("02:26:50.899Z", conversion.convert(asTimeOnly(-123456789101L))); } { - Conversion conversion = conversionFor(DATETIME, to); + Converter conversion = converterFor(DATETIME, to); assertNull(conversion.convert(null)); assertEquals("1973-11-29T21:33:09.101Z", conversion.convert(asDateTime(123456789101L))); assertEquals("1966-02-02T02:26:50.899Z", conversion.convert(asDateTime(-123456789101L))); @@ -89,34 +86,34 @@ public void testConversionToString() { public void testConversionToLong() { DataType to = LONG; { - Conversion conversion = conversionFor(DOUBLE, to); + Converter conversion = converterFor(DOUBLE, to); assertNull(conversion.convert(null)); assertEquals(10L, conversion.convert(10.0)); assertEquals(10L, conversion.convert(10.1)); assertEquals(11L, conversion.convert(10.6)); - Exception e = expectThrows(SqlIllegalArgumentException.class, () -> conversion.convert(Double.MAX_VALUE)); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert(Double.MAX_VALUE)); assertEquals("[" + Double.MAX_VALUE + "] out of [long] range", e.getMessage()); } { - Conversion conversion = conversionFor(INTEGER, to); + Converter conversion = converterFor(INTEGER, to); assertNull(conversion.convert(null)); assertEquals(10L, conversion.convert(10)); assertEquals(-134L, conversion.convert(-134)); } { - Conversion conversion = conversionFor(BOOLEAN, to); + Converter conversion = converterFor(BOOLEAN, to); assertNull(conversion.convert(null)); assertEquals(1L, conversion.convert(true)); assertEquals(0L, conversion.convert(false)); } { - Conversion conversion = conversionFor(DATE, to); + Converter conversion = converterFor(DATE, to); assertNull(conversion.convert(null)); assertEquals(123379200000L, conversion.convert(asDateOnly(123456789101L))); assertEquals(-123465600000L, conversion.convert(asDateOnly(-123456789101L))); } { - Conversion conversion = conversionFor(TIME, to); + Converter conversion = converterFor(TIME, to); assertNull(conversion.convert(null)); assertEquals(123456L, conversion.convert(asTimeOnly(123456L))); assertEquals(77589101L, conversion.convert(asTimeOnly(123456789101L))); @@ -124,17 +121,17 @@ public void testConversionToLong() { assertEquals(8810899L, conversion.convert(asTimeOnly(-123456789101L))); } { - Conversion conversion = conversionFor(DATETIME, to); + Converter conversion = converterFor(DATETIME, to); assertNull(conversion.convert(null)); assertEquals(123456789101L, conversion.convert(asDateTime(123456789101L))); assertEquals(-123456789101L, conversion.convert(asDateTime(-123456789101L))); } { - Conversion conversion = conversionFor(KEYWORD, to); + Converter conversion = converterFor(KEYWORD, to); assertNull(conversion.convert(null)); assertEquals(1L, conversion.convert("1")); assertEquals(0L, conversion.convert("-0")); - Exception e = expectThrows(SqlIllegalArgumentException.class, () -> conversion.convert("0xff")); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert("0xff")); assertEquals("cannot cast [0xff] to [long]", e.getMessage()); } } @@ -142,38 +139,37 @@ public void testConversionToLong() { public void testConversionToDate() { DataType to = DATE; { - Conversion conversion = conversionFor(DOUBLE, to); + Converter conversion = converterFor(DOUBLE, to); assertNull(conversion.convert(null)); assertEquals(date(10L), conversion.convert(10.0)); assertEquals(date(10L), conversion.convert(10.1)); assertEquals(date(11L), conversion.convert(10.6)); - Exception e = expectThrows(SqlIllegalArgumentException.class, () -> conversion.convert(Double.MAX_VALUE)); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert(Double.MAX_VALUE)); assertEquals("[" + Double.MAX_VALUE + "] out of [long] range", e.getMessage()); } { - Conversion conversion = conversionFor(INTEGER, to); + Converter conversion = converterFor(INTEGER, to); assertNull(conversion.convert(null)); assertEquals(date(10L), conversion.convert(10)); assertEquals(date(-134L), conversion.convert(-134)); } { - Conversion conversion = conversionFor(BOOLEAN, to); + Converter conversion = converterFor(BOOLEAN, to); assertNull(conversion.convert(null)); assertEquals(date(1), conversion.convert(true)); assertEquals(date(0), conversion.convert(false)); } { - Exception e = expectThrows(SqlIllegalArgumentException.class, () -> conversionFor(TIME, to)); - assertEquals("cannot convert from [time] to [date]", e.getMessage()); + assertNull(converterFor(TIME, to)); } { - Conversion conversion = conversionFor(DATETIME, to); + Converter conversion = converterFor(DATETIME, to); assertNull(conversion.convert(null)); assertEquals(date(123456780000L), conversion.convert(asDateTime(123456789101L))); assertEquals(date(-123456789101L), conversion.convert(asDateTime(-123456789101L))); } { - Conversion conversion = conversionFor(KEYWORD, to); + Converter conversion = converterFor(KEYWORD, to); assertNull(conversion.convert(null)); assertEquals(date(0L), conversion.convert("1970-01-01")); @@ -182,11 +178,12 @@ public void testConversionToDate() { assertEquals(date(18000000L), conversion.convert("1970-01-01")); // double check back and forth conversion - ZonedDateTime zdt = TestUtils.now(); - Conversion forward = conversionFor(DATE, KEYWORD); - Conversion back = conversionFor(KEYWORD, DATE); + + ZonedDateTime zdt = org.elasticsearch.common.time.DateUtils.nowWithMillisResolution(); + Converter forward = converterFor(DATE, KEYWORD); + Converter back = converterFor(KEYWORD, DATE); assertEquals(asDateOnly(zdt), back.convert(forward.convert(zdt))); - Exception e = expectThrows(SqlIllegalArgumentException.class, () -> conversion.convert("0xff")); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert("0xff")); assertEquals("cannot cast [0xff] to [date]: Text '0xff' could not be parsed at index 0", e.getMessage()); } } @@ -194,40 +191,40 @@ public void testConversionToDate() { public void testConversionToTime() { DataType to = TIME; { - Conversion conversion = conversionFor(DOUBLE, to); + Converter conversion = converterFor(DOUBLE, to); assertNull(conversion.convert(null)); assertEquals(time(10L), conversion.convert(10.0)); assertEquals(time(10L), conversion.convert(10.1)); assertEquals(time(11L), conversion.convert(10.6)); - Exception e = expectThrows(SqlIllegalArgumentException.class, () -> conversion.convert(Double.MAX_VALUE)); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert(Double.MAX_VALUE)); assertEquals("[" + Double.MAX_VALUE + "] out of [long] range", e.getMessage()); } { - Conversion conversion = conversionFor(INTEGER, to); + Converter conversion = converterFor(INTEGER, to); assertNull(conversion.convert(null)); assertEquals(time(10L), conversion.convert(10)); assertEquals(time(-134L), conversion.convert(-134)); } { - Conversion conversion = conversionFor(BOOLEAN, to); + Converter conversion = converterFor(BOOLEAN, to); assertNull(conversion.convert(null)); assertEquals(time(1), conversion.convert(true)); assertEquals(time(0), conversion.convert(false)); } { - Conversion conversion = conversionFor(DATE, to); + Converter conversion = converterFor(DATE, to); assertNull(conversion.convert(null)); assertEquals(time(123379200000L), conversion.convert(asDateOnly(123456789101L))); assertEquals(time(-123465600000L), conversion.convert(asDateOnly(-123456789101L))); } { - Conversion conversion = conversionFor(DATETIME, to); + Converter conversion = converterFor(DATETIME, to); assertNull(conversion.convert(null)); assertEquals(time(77589101L), conversion.convert(asDateTime(123456789101L))); assertEquals(time(8810899L), conversion.convert(asDateTime(-123456789101L))); } { - Conversion conversion = conversionFor(KEYWORD, to); + Converter conversion = converterFor(KEYWORD, to); assertNull(conversion.convert(null)); assertEquals(time(0L), conversion.convert("00:00:00Z")); @@ -237,50 +234,48 @@ public void testConversionToTime() { // double check back and forth conversion OffsetTime ot = org.elasticsearch.common.time.DateUtils.nowWithMillisResolution().toOffsetDateTime().toOffsetTime(); - Conversion forward = conversionFor(TIME, KEYWORD); - Conversion back = conversionFor(KEYWORD, TIME); + Converter forward = converterFor(TIME, KEYWORD); + Converter back = converterFor(KEYWORD, TIME); assertEquals(ot, back.convert(forward.convert(ot))); - Exception e = expectThrows(SqlIllegalArgumentException.class, () -> conversion.convert("0xff")); - assertEquals("cannot cast [0xff] to [time]: Text '0xff' could not be parsed at index 0", - e.getMessage()); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert("0xff")); + assertEquals("cannot cast [0xff] to [time]: Text '0xff' could not be parsed at index 0", e.getMessage()); } } public void testConversionToDateTime() { DataType to = DATETIME; { - Conversion conversion = conversionFor(DOUBLE, to); + Converter conversion = converterFor(DOUBLE, to); assertNull(conversion.convert(null)); assertEquals(dateTime(10L), conversion.convert(10.0)); assertEquals(dateTime(10L), conversion.convert(10.1)); assertEquals(dateTime(11L), conversion.convert(10.6)); - Exception e = expectThrows(SqlIllegalArgumentException.class, () -> conversion.convert(Double.MAX_VALUE)); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert(Double.MAX_VALUE)); assertEquals("[" + Double.MAX_VALUE + "] out of [long] range", e.getMessage()); } { - Conversion conversion = conversionFor(INTEGER, to); + Converter conversion = converterFor(INTEGER, to); assertNull(conversion.convert(null)); assertEquals(dateTime(10L), conversion.convert(10)); assertEquals(dateTime(-134L), conversion.convert(-134)); } { - Conversion conversion = conversionFor(BOOLEAN, to); + Converter conversion = converterFor(BOOLEAN, to); assertNull(conversion.convert(null)); assertEquals(dateTime(1), conversion.convert(true)); assertEquals(dateTime(0), conversion.convert(false)); } { - Conversion conversion = conversionFor(DATE, to); + Converter conversion = converterFor(DATE, to); assertNull(conversion.convert(null)); assertEquals(dateTime(123379200000L), conversion.convert(asDateOnly(123456789101L))); assertEquals(dateTime(-123465600000L), conversion.convert(asDateOnly(-123456789101L))); } { - Exception e = expectThrows(SqlIllegalArgumentException.class, () -> conversionFor(TIME, to)); - assertEquals("cannot convert from [time] to [datetime]", e.getMessage()); + assertNull(converterFor(TIME, to)); } { - Conversion conversion = conversionFor(KEYWORD, to); + Converter conversion = converterFor(KEYWORD, to); assertNull(conversion.convert(null)); assertEquals(dateTime(0L), conversion.convert("1970-01-01")); @@ -290,45 +285,46 @@ public void testConversionToDateTime() { assertEquals(dateTime(18000000L), conversion.convert("1970-01-01T00:00:00-05:00")); // double check back and forth conversion - ZonedDateTime dt = TestUtils.now(); - Conversion forward = conversionFor(DATETIME, KEYWORD); - Conversion back = conversionFor(KEYWORD, DATETIME); + + ZonedDateTime dt = org.elasticsearch.common.time.DateUtils.nowWithMillisResolution(); + Converter forward = converterFor(DATETIME, KEYWORD); + Converter back = converterFor(KEYWORD, DATETIME); assertEquals(dt, back.convert(forward.convert(dt))); - Exception e = expectThrows(SqlIllegalArgumentException.class, () -> conversion.convert("0xff")); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert("0xff")); assertEquals("cannot cast [0xff] to [datetime]: failed to parse date field [0xff] with format [date_optional_time]", - e.getMessage()); + e.getMessage()); } } public void testConversionToFloat() { DataType to = FLOAT; { - Conversion conversion = conversionFor(DOUBLE, to); + Converter conversion = converterFor(DOUBLE, to); assertNull(conversion.convert(null)); assertEquals(10.0f, (float) conversion.convert(10.0d), 0.00001); assertEquals(10.1f, (float) conversion.convert(10.1d), 0.00001); assertEquals(10.6f, (float) conversion.convert(10.6d), 0.00001); } { - Conversion conversion = conversionFor(INTEGER, to); + Converter conversion = converterFor(INTEGER, to); assertNull(conversion.convert(null)); assertEquals(10.0f, (float) conversion.convert(10), 0.00001); assertEquals(-134.0f, (float) conversion.convert(-134), 0.00001); } { - Conversion conversion = conversionFor(BOOLEAN, to); + Converter conversion = converterFor(BOOLEAN, to); assertNull(conversion.convert(null)); assertEquals(1.0f, (float) conversion.convert(true), 0); assertEquals(0.0f, (float) conversion.convert(false), 0); } { - Conversion conversion = conversionFor(DATE, to); + Converter conversion = converterFor(DATE, to); assertNull(conversion.convert(null)); assertEquals(1.233792E11f, (float) conversion.convert(asDateOnly(123456789101L)), 0); assertEquals(-1.234656E11f, (float) conversion.convert(asDateOnly(-123456789101L)), 0); } { - Conversion conversion = conversionFor(TIME, to); + Converter conversion = converterFor(TIME, to); assertNull(conversion.convert(null)); assertEquals(123456.0f, (float) conversion.convert(asTimeOnly(123456L)), 0); assertEquals(7.7589104E7f, (float) conversion.convert(asTimeOnly(123456789101L)), 0); @@ -336,18 +332,18 @@ public void testConversionToFloat() { assertEquals(8810899.0f, (float) conversion.convert(asTimeOnly(-123456789101L)), 0); } { - Conversion conversion = conversionFor(DATETIME, to); + Converter conversion = converterFor(DATETIME, to); assertNull(conversion.convert(null)); assertEquals(1.23456789101E11f, (float) conversion.convert(asDateTime(123456789101L)), 0); assertEquals(-1.23456789101E11f, (float) conversion.convert(asDateTime(-123456789101L)), 0); } { - Conversion conversion = conversionFor(KEYWORD, to); + Converter conversion = converterFor(KEYWORD, to); assertNull(conversion.convert(null)); assertEquals(1.0f, (float) conversion.convert("1"), 0); assertEquals(0.0f, (float) conversion.convert("-0"), 0); assertEquals(12.776f, (float) conversion.convert("12.776"), 0.00001); - Exception e = expectThrows(SqlIllegalArgumentException.class, () -> conversion.convert("0xff")); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert("0xff")); assertEquals("cannot cast [0xff] to [float]", e.getMessage()); } } @@ -355,32 +351,32 @@ public void testConversionToFloat() { public void testConversionToDouble() { DataType to = DOUBLE; { - Conversion conversion = conversionFor(FLOAT, to); + Converter conversion = converterFor(FLOAT, to); assertNull(conversion.convert(null)); assertEquals(10.0, (double) conversion.convert(10.0f), 0.00001); assertEquals(10.1, (double) conversion.convert(10.1f), 0.00001); assertEquals(10.6, (double) conversion.convert(10.6f), 0.00001); } { - Conversion conversion = conversionFor(INTEGER, to); + Converter conversion = converterFor(INTEGER, to); assertNull(conversion.convert(null)); assertEquals(10.0, (double) conversion.convert(10), 0.00001); assertEquals(-134.0, (double) conversion.convert(-134), 0.00001); } { - Conversion conversion = conversionFor(BOOLEAN, to); + Converter conversion = converterFor(BOOLEAN, to); assertNull(conversion.convert(null)); assertEquals(1.0, (double) conversion.convert(true), 0); assertEquals(0.0, (double) conversion.convert(false), 0); } { - Conversion conversion = conversionFor(DATE, to); + Converter conversion = converterFor(DATE, to); assertNull(conversion.convert(null)); assertEquals(1.233792E11, (double) conversion.convert(asDateOnly(123456789101L)), 0); assertEquals(-1.234656E11, (double) conversion.convert(asDateOnly(-123456789101L)), 0); } { - Conversion conversion = conversionFor(TIME, to); + Converter conversion = converterFor(TIME, to); assertNull(conversion.convert(null)); assertEquals(123456.0, (double) conversion.convert(asTimeOnly(123456L)), 0); assertEquals(7.7589101E7, (double) conversion.convert(asTimeOnly(123456789101L)), 0); @@ -388,18 +384,18 @@ public void testConversionToDouble() { assertEquals(8810899.0, (double) conversion.convert(asTimeOnly(-123456789101L)), 0); } { - Conversion conversion = conversionFor(DATETIME, to); + Converter conversion = converterFor(DATETIME, to); assertNull(conversion.convert(null)); assertEquals(1.23456789101E11, (double) conversion.convert(asDateTime(123456789101L)), 0); assertEquals(-1.23456789101E11, (double) conversion.convert(asDateTime(-123456789101L)), 0); } { - Conversion conversion = conversionFor(KEYWORD, to); + Converter conversion = converterFor(KEYWORD, to); assertNull(conversion.convert(null)); assertEquals(1.0, (double) conversion.convert("1"), 0); assertEquals(0.0, (double) conversion.convert("-0"), 0); assertEquals(12.776, (double) conversion.convert("12.776"), 0.00001); - Exception e = expectThrows(SqlIllegalArgumentException.class, () -> conversion.convert("0xff")); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert("0xff")); assertEquals("cannot cast [0xff] to [double]", e.getMessage()); } } @@ -407,56 +403,56 @@ public void testConversionToDouble() { public void testConversionToBoolean() { DataType to = BOOLEAN; { - Conversion conversion = conversionFor(FLOAT, to); + Converter conversion = converterFor(FLOAT, to); assertNull(conversion.convert(null)); assertEquals(true, conversion.convert(10.0f)); assertEquals(true, conversion.convert(-10.0f)); assertEquals(false, conversion.convert(0.0f)); } { - Conversion conversion = conversionFor(INTEGER, to); + Converter conversion = converterFor(INTEGER, to); assertNull(conversion.convert(null)); assertEquals(true, conversion.convert(10)); assertEquals(true, conversion.convert(-10)); assertEquals(false, conversion.convert(0)); } { - Conversion conversion = conversionFor(LONG, to); + Converter conversion = converterFor(LONG, to); assertNull(conversion.convert(null)); assertEquals(true, conversion.convert(10L)); assertEquals(true, conversion.convert(-10L)); assertEquals(false, conversion.convert(0L)); } { - Conversion conversion = conversionFor(DOUBLE, to); + Converter conversion = converterFor(DOUBLE, to); assertNull(conversion.convert(null)); assertEquals(true, conversion.convert(10.0d)); assertEquals(true, conversion.convert(-10.0d)); assertEquals(false, conversion.convert(0.0d)); } { - Conversion conversion = conversionFor(DATE, to); + Converter conversion = converterFor(DATE, to); assertNull(conversion.convert(null)); assertEquals(true, conversion.convert(asDateOnly(123456789101L))); assertEquals(true, conversion.convert(asDateOnly(-123456789101L))); assertEquals(false, conversion.convert(asDateOnly(0L))); } { - Conversion conversion = conversionFor(TIME, to); + Converter conversion = converterFor(TIME, to); assertNull(conversion.convert(null)); assertEquals(true, conversion.convert(asTimeOnly(123456789101L))); assertEquals(true, conversion.convert(asTimeOnly(-123456789101L))); assertEquals(false, conversion.convert(asTimeOnly(0L))); } { - Conversion conversion = conversionFor(DATETIME, to); + Converter conversion = converterFor(DATETIME, to); assertNull(conversion.convert(null)); assertEquals(true, conversion.convert(asDateTime(123456789101L))); assertEquals(true, conversion.convert(asDateTime(-123456789101L))); assertEquals(false, conversion.convert(asDateTime(0L))); } { - Conversion conversion = conversionFor(KEYWORD, to); + Converter conversion = converterFor(KEYWORD, to); assertNull(conversion.convert(null)); // We only handled upper and lower case true and false assertEquals(true, conversion.convert("true")); @@ -464,17 +460,17 @@ public void testConversionToBoolean() { assertEquals(true, conversion.convert("True")); assertEquals(false, conversion.convert("fAlSe")); // Everything else should fail - Exception e = expectThrows(SqlIllegalArgumentException.class, () -> conversion.convert("10")); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert("10")); assertEquals("cannot cast [10] to [boolean]", e.getMessage()); - e = expectThrows(SqlIllegalArgumentException.class, () -> conversion.convert("-1")); + e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert("-1")); assertEquals("cannot cast [-1] to [boolean]", e.getMessage()); - e = expectThrows(SqlIllegalArgumentException.class, () -> conversion.convert("0")); + e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert("0")); assertEquals("cannot cast [0] to [boolean]", e.getMessage()); - e = expectThrows(SqlIllegalArgumentException.class, () -> conversion.convert("blah")); + e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert("blah")); assertEquals("cannot cast [blah] to [boolean]", e.getMessage()); - e = expectThrows(SqlIllegalArgumentException.class, () -> conversion.convert("Yes")); + e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert("Yes")); assertEquals("cannot cast [Yes] to [boolean]", e.getMessage()); - e = expectThrows(SqlIllegalArgumentException.class, () -> conversion.convert("nO")); + e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert("nO")); assertEquals("cannot cast [nO] to [boolean]", e.getMessage()); } } @@ -482,26 +478,26 @@ public void testConversionToBoolean() { public void testConversionToInt() { DataType to = INTEGER; { - Conversion conversion = conversionFor(DOUBLE, to); + Converter conversion = converterFor(DOUBLE, to); assertNull(conversion.convert(null)); assertEquals(10, conversion.convert(10.0)); assertEquals(10, conversion.convert(10.1)); assertEquals(11, conversion.convert(10.6)); - Exception e = expectThrows(SqlIllegalArgumentException.class, () -> conversion.convert(Long.MAX_VALUE)); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert(Long.MAX_VALUE)); assertEquals("[" + Long.MAX_VALUE + "] out of [integer] range", e.getMessage()); } { - Conversion conversion = conversionFor(DATE, to); + Converter conversion = converterFor(DATE, to); assertNull(conversion.convert(null)); assertEquals(0, conversion.convert(asDateOnly(12345678L))); assertEquals(86400000, conversion.convert(asDateOnly(123456789L))); assertEquals(172800000, conversion.convert(asDateOnly(223456789L))); assertEquals(-172800000, conversion.convert(asDateOnly(-123456789L))); - Exception e = expectThrows(SqlIllegalArgumentException.class, () -> conversion.convert(asDateOnly(Long.MAX_VALUE))); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert(asDateOnly(Long.MAX_VALUE))); assertEquals("[9223372036828800000] out of [integer] range", e.getMessage()); } { - Conversion conversion = conversionFor(TIME, to); + Converter conversion = converterFor(TIME, to); assertNull(conversion.convert(null)); assertEquals(123456, conversion.convert(asTimeOnly(123456L))); assertEquals(77589101, conversion.convert(asTimeOnly(123456789101L))); @@ -510,12 +506,12 @@ public void testConversionToInt() { assertEquals(25975807, conversion.convert(asTimeOnly(Long.MAX_VALUE))); } { - Conversion conversion = conversionFor(DATETIME, to); + Converter conversion = converterFor(DATETIME, to); assertNull(conversion.convert(null)); assertEquals(12345678, conversion.convert(asDateTime(12345678L))); assertEquals(223456789, conversion.convert(asDateTime(223456789L))); assertEquals(-123456789, conversion.convert(asDateTime(-123456789L))); - Exception e = expectThrows(SqlIllegalArgumentException.class, () -> conversion.convert(asDateTime(Long.MAX_VALUE))); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert(asDateTime(Long.MAX_VALUE))); assertEquals("[" + Long.MAX_VALUE + "] out of [integer] range", e.getMessage()); } } @@ -523,37 +519,36 @@ public void testConversionToInt() { public void testConversionToShort() { DataType to = SHORT; { - Conversion conversion = conversionFor(DOUBLE, to); + Converter conversion = converterFor(DOUBLE, to); assertNull(conversion.convert(null)); assertEquals((short) 10, conversion.convert(10.0)); assertEquals((short) 10, conversion.convert(10.1)); assertEquals((short) 11, conversion.convert(10.6)); - Exception e = expectThrows(SqlIllegalArgumentException.class, () -> conversion.convert(Integer.MAX_VALUE)); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert(Integer.MAX_VALUE)); assertEquals("[" + Integer.MAX_VALUE + "] out of [short] range", e.getMessage()); } { - Conversion conversion = conversionFor(DATE, to); + Converter conversion = converterFor(DATE, to); assertNull(conversion.convert(null)); assertEquals((short) 0, conversion.convert(asDateOnly(12345678L))); - Exception e = expectThrows(SqlIllegalArgumentException.class, () -> conversion.convert(asDateOnly(123456789L))); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert(asDateOnly(123456789L))); assertEquals("[86400000] out of [short] range", e.getMessage()); } { - Conversion conversion = conversionFor(TIME, to); + Converter conversion = converterFor(TIME, to); assertNull(conversion.convert(null)); assertEquals((short) 12345, conversion.convert(asTimeOnly(12345L))); - Exception e1 = expectThrows(SqlIllegalArgumentException.class, () -> conversion.convert(asTimeOnly(-123456789L))); + Exception e1 = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert(asTimeOnly(-123456789L))); assertEquals("[49343211] out of [short] range", e1.getMessage()); - Exception e2 = expectThrows(SqlIllegalArgumentException.class, () -> conversion.convert(asTimeOnly(123456789L))); + Exception e2 = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert(asTimeOnly(123456789L))); assertEquals("[37056789] out of [short] range", e2.getMessage()); } { - Conversion conversion = conversionFor(DATETIME, to); + Converter conversion = converterFor(DATETIME, to); assertNull(conversion.convert(null)); assertEquals((short) 12345, conversion.convert(asDateTime(12345L))); assertEquals((short) -12345, conversion.convert(asDateTime(-12345L))); - Exception e = expectThrows(SqlIllegalArgumentException.class, - () -> conversion.convert(asDateTime(Integer.MAX_VALUE))); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert(asDateTime(Integer.MAX_VALUE))); assertEquals("[" + Integer.MAX_VALUE + "] out of [short] range", e.getMessage()); } } @@ -561,55 +556,54 @@ public void testConversionToShort() { public void testConversionToByte() { DataType to = BYTE; { - Conversion conversion = conversionFor(DOUBLE, to); + Converter conversion = converterFor(DOUBLE, to); assertNull(conversion.convert(null)); assertEquals((byte) 10, conversion.convert(10.0)); assertEquals((byte) 10, conversion.convert(10.1)); assertEquals((byte) 11, conversion.convert(10.6)); - Exception e = expectThrows(SqlIllegalArgumentException.class, () -> conversion.convert(Short.MAX_VALUE)); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert(Short.MAX_VALUE)); assertEquals("[" + Short.MAX_VALUE + "] out of [byte] range", e.getMessage()); } { - Conversion conversion = conversionFor(DATE, to); + Converter conversion = converterFor(DATE, to); assertNull(conversion.convert(null)); assertEquals((byte) 0, conversion.convert(asDateOnly(12345678L))); - Exception e = expectThrows(SqlIllegalArgumentException.class, () -> conversion.convert(asDateOnly(123456789L))); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert(asDateOnly(123456789L))); assertEquals("[86400000] out of [byte] range", e.getMessage()); } { - Conversion conversion = conversionFor(TIME, to); + Converter conversion = converterFor(TIME, to); assertNull(conversion.convert(null)); assertEquals((byte) 123, conversion.convert(asTimeOnly(123L))); - Exception e1 = expectThrows(SqlIllegalArgumentException.class, () -> conversion.convert(asTimeOnly(-123L))); + Exception e1 = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert(asTimeOnly(-123L))); assertEquals("[86399877] out of [byte] range", e1.getMessage()); - Exception e2 = expectThrows(SqlIllegalArgumentException.class, () -> conversion.convert(asTimeOnly(123456789L))); + Exception e2 = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert(asTimeOnly(123456789L))); assertEquals("[37056789] out of [byte] range", e2.getMessage()); } { - Conversion conversion = conversionFor(DATETIME, to); + Converter conversion = converterFor(DATETIME, to); assertNull(conversion.convert(null)); assertEquals((byte) 123, conversion.convert(asDateTime(123L))); assertEquals((byte) -123, conversion.convert(asDateTime(-123L))); - Exception e = expectThrows(SqlIllegalArgumentException.class, - () -> conversion.convert(asDateTime(Integer.MAX_VALUE))); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert(asDateTime(Integer.MAX_VALUE))); assertEquals("[" + Integer.MAX_VALUE + "] out of [byte] range", e.getMessage()); } } public void testConversionToNull() { - Conversion conversion = conversionFor(DOUBLE, NULL); + Converter conversion = converterFor(DOUBLE, NULL); assertNull(conversion.convert(null)); assertNull(conversion.convert(10.0)); } public void testConversionFromNull() { - Conversion conversion = conversionFor(NULL, INTEGER); + Converter conversion = converterFor(NULL, INTEGER); assertNull(conversion.convert(null)); assertNull(conversion.convert(10)); } public void testConversionToIdentity() { - Conversion conversion = conversionFor(INTEGER, INTEGER); + Converter conversion = converterFor(INTEGER, INTEGER); assertNull(conversion.convert(null)); assertEquals(10, conversion.convert(10)); } @@ -643,8 +637,8 @@ public void testCommonType() { assertEquals(DATETIME, commonType(randomInterval(), DATETIME)); assertEquals(DATETIME, commonType(DATE, TIME)); assertEquals(DATETIME, commonType(TIME, DATE)); - assertEquals(DATE, commonType(DATE, randomInterval())); - assertEquals(DATE, commonType(randomInterval(), DATE)); + assertEquals(DATE, commonType(DATE, INTERVAL_YEAR)); + assertEquals(DATETIME, commonType(DATE, INTERVAL_HOUR_TO_MINUTE)); assertEquals(TIME, commonType(TIME, randomInterval())); assertEquals(TIME, commonType(randomInterval(), TIME)); @@ -654,36 +648,48 @@ public void testCommonType() { } public void testEsDataTypes() { - for (DataType type : values()) { + for (DataType type : types()) { if (type != DATE) { // Doesn't have a corresponding type in ES - assertEquals(type, fromTypeName(type.typeName)); + assertEquals(type, fromTypeName(type.typeName())); } } } public void testConversionToUnsupported() { - Exception e = expectThrows(SqlIllegalArgumentException.class, - () -> conversionFor(INTEGER, UNSUPPORTED)); - assertEquals("cannot convert from [integer] to [unsupported]", e.getMessage()); + assertNull(converterFor(INTEGER, UNSUPPORTED)); } public void testStringToIp() { - Conversion conversion = conversionFor(KEYWORD, IP); + Converter conversion = converterFor(KEYWORD, IP); assertNull(conversion.convert(null)); assertEquals("192.168.1.1", conversion.convert("192.168.1.1")); - Exception e = expectThrows(SqlIllegalArgumentException.class, () -> conversion.convert("10.1.1.300")); + Exception e = expectThrows(QlIllegalArgumentException.class, () -> conversion.convert("10.1.1.300")); assertEquals("[10.1.1.300] is not a valid IPv4 or IPv6 address", e.getMessage()); } public void testIpToString() { Source s = new Source(Location.EMPTY, "10.0.0.1"); - Conversion ipToString = conversionFor(IP, KEYWORD); + Converter ipToString = converterFor(IP, KEYWORD); assertEquals("10.0.0.1", ipToString.convert(new Literal(s, "10.0.0.1", IP))); - Conversion stringToIp = conversionFor(KEYWORD, IP); - assertEquals("10.0.0.1", ipToString.convert(stringToIp.convert(Literal.of(s, "10.0.0.1")))); + Converter stringToIp = converterFor(KEYWORD, IP); + assertEquals("10.0.0.1", ipToString.convert(stringToIp.convert(new Literal(s, "10.0.0.1", KEYWORD)))); } private DataType randomInterval() { - return randomFrom(Stream.of(DataType.values()).filter(DataType::isInterval).collect(Collectors.toList())); + return randomFrom(SqlDataTypes.types().stream() + .filter(SqlDataTypes::isInterval) + .collect(toList())); + } + + static ZonedDateTime dateTime(long millisSinceEpoch) { + return DateUtils.asDateTime(millisSinceEpoch); + } + + static ZonedDateTime date(long millisSinceEpoch) { + return DateUtils.asDateOnly(millisSinceEpoch); + } + + static OffsetTime time(long millisSinceEpoch) { + return DateUtils.asTimeOnly(millisSinceEpoch); } -} +} \ No newline at end of file diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/type/DataTypesTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/type/SqlDataTypesTests.java similarity index 59% rename from x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/type/DataTypesTests.java rename to x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/type/SqlDataTypesTests.java index 5b0111b5998a7..dce63dbc69559 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/type/DataTypesTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/type/SqlDataTypesTests.java @@ -6,44 +6,48 @@ package org.elasticsearch.xpack.sql.type; import org.elasticsearch.test.ESTestCase; +import org.elasticsearch.xpack.ql.type.DataType; +import org.elasticsearch.xpack.ql.type.DataTypes; import java.util.ArrayList; import java.util.Arrays; -import java.util.EnumSet; import java.util.List; -import java.util.stream.Stream; +import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; -import static org.elasticsearch.xpack.sql.type.DataType.DATETIME; -import static org.elasticsearch.xpack.sql.type.DataType.FLOAT; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_DAY; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_DAY_TO_HOUR; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_DAY_TO_MINUTE; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_DAY_TO_SECOND; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_HOUR; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_HOUR_TO_MINUTE; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_HOUR_TO_SECOND; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_MINUTE; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_MINUTE_TO_SECOND; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_MONTH; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_SECOND; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_YEAR; -import static org.elasticsearch.xpack.sql.type.DataType.INTERVAL_YEAR_TO_MONTH; -import static org.elasticsearch.xpack.sql.type.DataType.KEYWORD; -import static org.elasticsearch.xpack.sql.type.DataType.LONG; -import static org.elasticsearch.xpack.sql.type.DataTypes.compatibleInterval; -import static org.elasticsearch.xpack.sql.type.DataTypes.metaSqlDataType; -import static org.elasticsearch.xpack.sql.type.DataTypes.metaSqlDateTimeSub; -import static org.elasticsearch.xpack.sql.type.DataTypes.metaSqlMaximumScale; -import static org.elasticsearch.xpack.sql.type.DataTypes.metaSqlMinimumScale; -import static org.elasticsearch.xpack.sql.type.DataTypes.metaSqlRadix; - -public class DataTypesTests extends ESTestCase { +import static org.elasticsearch.xpack.ql.type.DataTypes.DATETIME; +import static org.elasticsearch.xpack.ql.type.DataTypes.FLOAT; +import static org.elasticsearch.xpack.ql.type.DataTypes.KEYWORD; +import static org.elasticsearch.xpack.ql.type.DataTypes.LONG; +import static org.elasticsearch.xpack.sql.expression.literal.interval.Intervals.compatibleInterval; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_DAY; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_DAY_TO_HOUR; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_DAY_TO_MINUTE; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_DAY_TO_SECOND; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_HOUR; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_HOUR_TO_MINUTE; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_HOUR_TO_SECOND; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_MINUTE; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_MINUTE_TO_SECOND; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_MONTH; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_SECOND; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_YEAR; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.INTERVAL_YEAR_TO_MONTH; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.defaultPrecision; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.isInterval; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.metaSqlDataType; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.metaSqlDateTimeSub; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.metaSqlMaximumScale; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.metaSqlMinimumScale; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.metaSqlRadix; +import static org.elasticsearch.xpack.sql.type.SqlDataTypes.sqlType; + +public class SqlDataTypesTests extends ESTestCase { public void testMetaDataType() { assertEquals(Integer.valueOf(9), metaSqlDataType(DATETIME)); DataType t = randomDataTypeNoDateTime(); - assertEquals(t.sqlType.getVendorTypeNumber(), metaSqlDataType(t)); + assertEquals(sqlType(t).getVendorTypeNumber(), metaSqlDataType(t)); } public void testMetaDateTypeSub() { @@ -54,14 +58,14 @@ public void testMetaDateTypeSub() { public void testMetaMinimumScale() { assertEquals(Short.valueOf((short) 3), metaSqlMinimumScale(DATETIME)); assertEquals(Short.valueOf((short) 0), metaSqlMinimumScale(LONG)); - assertEquals(Short.valueOf((short) FLOAT.defaultPrecision), metaSqlMaximumScale(FLOAT)); + assertEquals(Short.valueOf((short) defaultPrecision(FLOAT)), metaSqlMaximumScale(FLOAT)); assertNull(metaSqlMinimumScale(KEYWORD)); } public void testMetaMaximumScale() { assertEquals(Short.valueOf((short) 3), metaSqlMaximumScale(DATETIME)); assertEquals(Short.valueOf((short) 0), metaSqlMaximumScale(LONG)); - assertEquals(Short.valueOf((short) FLOAT.defaultPrecision), metaSqlMaximumScale(FLOAT)); + assertEquals(Short.valueOf((short) defaultPrecision(FLOAT)), metaSqlMaximumScale(FLOAT)); assertNull(metaSqlMaximumScale(KEYWORD)); } @@ -75,8 +79,20 @@ public void testMetaRadix() { // type checks public void testIsInterval() throws Exception { - for (DataType dataType : EnumSet.range(INTERVAL_YEAR, INTERVAL_MINUTE_TO_SECOND)) { - assertTrue(dataType.isInterval()); + for (DataType dataType : asList(INTERVAL_YEAR, + INTERVAL_MONTH, + INTERVAL_DAY, + INTERVAL_HOUR, + INTERVAL_MINUTE, + INTERVAL_SECOND, + INTERVAL_YEAR_TO_MONTH, + INTERVAL_DAY_TO_HOUR, + INTERVAL_DAY_TO_MINUTE, + INTERVAL_DAY_TO_SECOND, + INTERVAL_HOUR_TO_MINUTE, + INTERVAL_HOUR_TO_SECOND, + INTERVAL_MINUTE_TO_SECOND)) { + assertTrue(dataType + " is not an interval", isInterval(dataType)); } } @@ -131,16 +147,16 @@ public void testEsToDataType() throws Exception { "interval_hour_to_minute", "interval_hour_to_second", "interval_minute_to_second")); - types.addAll(Stream.of(DataType.values()) - .filter(DataType::isPrimitive) - .map(DataType::name) + types.addAll(SqlDataTypes.types().stream() + .filter(DataTypes::isPrimitive) + .map(DataType::typeName) .collect(toList())); String type = randomFrom(types.toArray(new String[0])); - DataType dataType = DataType.fromSqlOrEsType(type); - assertNotNull(dataType); + DataType dataType = SqlDataTypes.fromSqlOrEsType(type); + assertNotNull("cound not find " + type, dataType); } private DataType randomDataTypeNoDateTime() { - return randomValueOtherThan(DataType.DATETIME, () -> randomFrom(DataType.values())); + return randomValueOtherThan(DATETIME, () -> randomFrom(SqlDataTypes.types())); } -} +} \ No newline at end of file diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/types/SqlTypesTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/types/SqlTypesTests.java new file mode 100644 index 0000000000000..30de718093a1a --- /dev/null +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/types/SqlTypesTests.java @@ -0,0 +1,84 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +package org.elasticsearch.xpack.sql.types; + +import org.elasticsearch.test.ESTestCase; +import org.elasticsearch.xpack.ql.type.EsField; +import org.elasticsearch.xpack.ql.type.KeywordEsField; +import org.elasticsearch.xpack.ql.type.TextEsField; +import org.elasticsearch.xpack.ql.type.TypesTests; +import org.elasticsearch.xpack.sql.type.SqlDataTypeRegistry; +import org.elasticsearch.xpack.sql.type.SqlDataTypes; + +import java.util.Map; + +import static org.elasticsearch.xpack.ql.type.DataTypes.DATETIME; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; + +public class SqlTypesTests extends ESTestCase { + + + public void testGeoField() { + Map mapping = loadMapping("mapping-geo.json"); + assertThat(mapping.size(), is(2)); + EsField gp = mapping.get("location"); + assertThat(gp.getDataType().typeName(), is("geo_point")); + EsField gs = mapping.get("site"); + assertThat(gs.getDataType().typeName(), is("geo_shape")); + } + + + public void testTextField() { + Map mapping = loadMapping("mapping-text.json"); + assertThat(mapping.size(), is(1)); + EsField type = mapping.get("full_name"); + assertThat(type, instanceOf(TextEsField.class)); + assertThat(type.isAggregatable(), is(false)); + TextEsField ttype = (TextEsField) type; + assertThat(SqlDataTypes.defaultPrecision(ttype.getDataType()), is(32766)); + assertThat(ttype.isAggregatable(), is(false)); + } + + public void testKeywordField() { + Map mapping = loadMapping("mapping-keyword.json"); + + assertThat(mapping.size(), is(1)); + EsField field = mapping.get("full_name"); + assertThat(field, instanceOf(KeywordEsField.class)); + assertThat(field.isAggregatable(), is(true)); + assertThat(((KeywordEsField) field).getPrecision(), is(256)); + } + + public void testDateField() { + Map mapping = loadMapping("mapping-date.json"); + + assertThat(mapping.size(), is(1)); + EsField field = mapping.get("date"); + assertThat(field.getDataType(), is(DATETIME)); + assertThat(field.isAggregatable(), is(true)); + assertThat(SqlDataTypes.defaultPrecision(field.getDataType()), is(3)); + } + + public void testDocValueField() { + Map mapping = loadMapping("mapping-docvalues.json"); + + assertThat(mapping.size(), is(1)); + EsField field = mapping.get("session_id"); + assertThat(field, instanceOf(KeywordEsField.class)); + assertThat(((KeywordEsField) field).getPrecision(), is(15)); + assertThat(field.isAggregatable(), is(false)); + } + + public static Map loadMapping(String name) { + return TypesTests.loadMapping(SqlDataTypeRegistry.INSTANCE, name); + } + + public static Map loadMapping(String name, boolean ordered) { + return TypesTests.loadMapping(SqlDataTypeRegistry.INSTANCE, name, ordered); + } +} \ No newline at end of file diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/util/LikeConversionTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/util/LikeConversionTests.java index 29cbb9b985ffd..860bc2d759d93 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/util/LikeConversionTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/util/LikeConversionTests.java @@ -7,9 +7,9 @@ import org.elasticsearch.test.ESTestCase; -import static org.elasticsearch.xpack.sql.util.StringUtils.likeToJavaPattern; -import static org.elasticsearch.xpack.sql.util.StringUtils.likeToLuceneWildcard; -import static org.elasticsearch.xpack.sql.util.StringUtils.likeToUnescaped; +import static org.elasticsearch.xpack.ql.util.StringUtils.likeToJavaPattern; +import static org.elasticsearch.xpack.ql.util.StringUtils.likeToLuceneWildcard; +import static org.elasticsearch.xpack.ql.util.StringUtils.likeToUnescaped; public class LikeConversionTests extends ESTestCase {