Skip to content

Query context for built-in functions - #937

Closed
MaxKsyunz wants to merge 18 commits into
opensearch-project:2.xfrom
Bit-Quill:dev-constant-now
Closed

MaxKsyunz wants to merge 18 commits into
opensearch-project:2.xfrom
Bit-Quill:dev-constant-now

Conversation

@MaxKsyunz

@MaxKsyunz MaxKsyunz commented Oct 20, 2022 •

Copy link
Copy Markdown
Collaborator

Description

These changes allow creating SQL functions that expose engine metadata.

As an example, now-family of functions is updated to report consistent time across multiple invocations.

Note: sysdate was unmodified. As per MySQL, it returns the time at invocation.

Implementation Details

  • Add QueryContext interface -- a way for SQL functions to access SQL plugin metadata.
  • FunctionBuilder.apply signature expects QueryContext as well as list of arguments.
  • An instance of QueryContext is setup in Expression.Config.functionRepository and passed to BuiltInFunctionRepository.
  • Add FunctionDSL.queryContextFunction method. It is similar to FunctionDSL.impl but passes QueryContext to the implementing lambda function.

Issues Resolved

[List any issues this PR will resolve]

Check List

  • New functionality includes testing.
    • All tests pass, including unit test, integration test and doctest
  • New functionality has been documented.
    • New functionality has javadoc added
    • New functionality has user manual doc added
  • Commits are signed per the DCO using --signoff

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.
For more information on following Developer Certificate of Origin and signing off your commits, please check here.

@MaxKsyunz MaxKsyunz changed the title QueryContext for BuiltInFunctions Query context for built-in functions Oct 20, 2022
Add QueryContext interface to capture query metadata and provide to
 function implementations.

Update FunctionBuilder to take QueryContext in addition to function
arguments when evaluating a SQL function.

Implement constant date time functions using QueryContext.

Signed-off-by: MaxKsyunz <[email protected]>
@MaxKsyunz

Copy link
Copy Markdown
Collaborator Author

SQL Java CI is failing on test coverage for FunctionDSL class. Is it covered implicitly by other test? I'm not finding tests that explicitly test FunctionDSL.

What does the error message refer to?

Execution failed for task ':core:jacocoTestCoverageVerification'.
> Rule violated for class org.opensearch.sql.expression.function.FunctionDSL.1: lines covered ratio is 0.5, but expected minimum is 1.0
  Rule violated for class org.opensearch.sql.expression.function.FunctionDSL.2: lines covered ratio is 0.7, but expected minimum is 1.0

- Address checkstyle errors
- Add comments to QueryContext.
- Address PR feedback.

Signed-off-by: MaxKsyunz <[email protected]>
@codecov-commenter

codecov-commenter commented Oct 20, 2022 •

Copy link
Copy Markdown

Codecov Report

Merging #937 (5bed983) into 2.x (be4512e) will decrease coverage by 35.49%.
The diff coverage is n/a.

@@              Coverage Diff              @@
##                2.x     #937       +/-   ##
=============================================
- Coverage     98.26%   62.76%   -35.50%     
=============================================
  Files           324       10      -314     
  Lines          8399      658     -7741     
  Branches        553      119      -434     
=============================================
- Hits           8253      413     -7840     
- Misses          142      192       +50     
- Partials          4       53       +49     
Flag Coverage Δ
query-workbench 62.76% <ø> (?)
sql-engine ?

Flags with carried forward coverage won't be shown. Click here to find out more.

Impacted Files Coverage Δ
...a/org/opensearch/sql/analysis/AnalysisContext.java
...rg/opensearch/sql/analysis/ExpressionAnalyzer.java
...c/main/java/org/opensearch/sql/expression/DSL.java
...sql/expression/aggregation/AggregatorFunction.java
...search/sql/expression/config/ExpressionConfig.java
...arch/sql/expression/datetime/DateTimeFunction.java
...expression/function/BuiltinFunctionRepository.java
...pensearch/sql/expression/function/FunctionDSL.java
...expression/function/RelevanceFunctionResolver.java
...nsearch/sql/expression/system/SystemFunctions.java
... and 324 more

Help us with your feedback. Take ten seconds to tell us how you rate us. Have a feature suggestion? Share it here.

@MaxKsyunz

Copy link
Copy Markdown
Collaborator Author

@MaxKsyunz is there a test to confirm that multiple calls to now function within the same context return the same value?

@Yury-Fridlyand

Copy link
Copy Markdown
Collaborator

How to access the brand new QueryContext in unit tests? Integration tests?

@MaxKsyunz

Copy link
Copy Markdown
Collaborator Author

Another way to add this would be to make QueryContext a property of plan execution.

I like that better conceptually since "query execution start time" is related to plan execution, not function definition. It does seem more complex to implement -- the value would have to be passed from ExecutionEngine, to ProjectOperator, to valueOf via Environment. What do you think, @penghuo ?

@MaxKsyunz

Copy link
Copy Markdown
Collaborator Author

Another way to add this would be to make QueryContext a property of plan execution.

I like that better conceptually since "query execution start time" is related to plan execution, not function definition. It does seem more complex to implement -- the value would have to be passed from ExecutionEngine, to ProjectOperator, to valueOf via Environment. What do you think, @penghuo ?

See #960 for QueryContext as part of plan execution.

Comment on lines +79 to +100
FunctionBuilder functionBuilder =
(queryContext, arguments) -> new FunctionExpression(functionName, arguments) {
@Override
public ExprValue valueOf(Environment<Expression, ExprValue> valueEnv) {
ExprValue value = arguments.get(0).valueOf(valueEnv);
return function.apply(queryContext, value);
}

@Override
public ExprType type() {
return returnType;
}

@Override
public String toString() {
return String.format("%s(%s)", functionName,
arguments.stream()
.map(Object::toString)
.collect(Collectors.joining(", ")));
}
};
return Pair.of(functionSignature, functionBuilder);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

avoid duplicate codes?

* Class to capture values that may be necessary to implement some functions.
* An example would be query execution start time to implement now().
*/
public interface QueryContext {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel FunctionParameter is more concrete name.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel "function" is overloaded and we don't want to limit this to just functions. There's no reason why the context couldn't be passed to non-function expressions, if for example, we want to save the storage mechanism in here (catalog vs SQL vs something else) and have that available to... say... identifiers or datatypes.

Comment on lines +41 to +48
QueryContext queryContext = new QueryContext() {
private final Clock currentTime = Clock.fixed(Instant.now(),
ZoneId.systemDefault());
@Override
public Clock getQueryStartTime() {
return currentTime;
}
};

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The implication is BuiltinFunctionRepository and QueryContext is created per request. With current Spring configuration, it is true. I think we should add test to guarantee this.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point -- I will add this test.

@penghuo

penghuo commented Oct 25, 2022

Copy link
Copy Markdown
Collaborator

Another way to add this would be to make QueryContext a property of plan execution.
I like that better conceptually since "query execution start time" is related to plan execution, not function definition. It does seem more complex to implement -- the value would have to be passed from ExecutionEngine, to ProjectOperator, to valueOf via Environment. What do you think, @penghuo ?

See #960 for QueryContext as part of plan execution.

Thanks for push this PR. This is long pending issue.
I did not get the idea why add SessionContext to valueOf interface. i perfer the #937 implementation, In my opinion, expression is compiled with context, and run with env.

forestmvey
forestmvey previously approved these changes Oct 26, 2022
@MaxKsyunz

MaxKsyunz commented Oct 26, 2022 •

Copy link
Copy Markdown
Collaborator Author

Thanks for push this PR. This is long pending issue. I did not get the idea why add SessionContext to valueOf interface. i perfer the #937 implementation, In my opinion, expression is compiled with context, and run with env.

Thank you @penghuo! I will clean up this PR and re-submit it.

As for #960, this is what I'm trying to get to:

  1. PhysicalPlan.next returns a result set as well as metadata.
  2. Expression.valueOf can access this metadata to update the result set.
  3. Each PhyislcalPlan.next implementation can easily preserve metadata it received from its children as well as add its own.

It solves this problem but can also be used for other purposes. I'll write up a separate proposal with some examples and cleaner code.

MaxKsyunz added 4 commits October 28, 2022 03:00
1. Rename QueryContext to FunctionProperties, renmae related parameter
names.
2. Remove QueryContext interface.
3. Add FunctionProperties as a bean to ExpressionConfig.
4. Add unit tests for ExpressionConfig.

Refactored unit tests in opensearch module to keep ExpressionCOnfig
misuse in one place -- OpenSearchTestBase.

Signed-off-by: MaxKsyunz <[email protected]>
# Conflicts:
#	core/src/main/java/org/opensearch/sql/expression/datetime/DateTimeFunction.java
#	core/src/test/java/org/opensearch/sql/expression/datetime/DateTimeTestBase.java
Comment on lines +15 to +18
{
ExpressionConfig config = new ExpressionConfig();
dsl = config.dsl(config.functionRepository(config.functionExecutionContext()));
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is something missing?


private final DSL dsl = new ExpressionConfig().dsl(new ExpressionConfig().functionRepository());
@Autowired
private DSL dsl;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you name it in uppercase to avoid changing all depending tests?

Suggested change
private DSL dsl;
private DSL DSL;

Make FunctionProperties serializable -- required toString override.

Signed-off-by: MaxKsyunz <[email protected]>
MaxKsyunz added 10 commits November 1, 2022 13:07
Add unit tests for FunctionProperties, including ensuring it is
serializable.

Fix serializability of return value of FunctionDSL.implWithProperties

Signed-off-by: MaxKsyunz <[email protected]>
Constant value caching is no longer necessary in ExpressionAnalyzer
-- the same behavior is now implemented with FunctionProperties.

Signed-off-by: MaxKsyunz <[email protected]>
On Windows, getQueryStartClock_differs_from_instantNow fails
because Instant.now() in the test returns the same value as
Instant.now() called for FunctionProperties construction.

Signed-off-by: MaxKsyunz <[email protected]>
It's failing on Windows -- turns out the assumption about Spring
it was testing does not hold true across platforms.

Signed-off-by: MaxKsyunz <[email protected]>
Signed-off-by: MaxKsyunz <[email protected]>
Add FunctionDSL.nullMissingHandlingWithProperties to all for consistent
null and missing value handling across all functions.

Signed-off-by: MaxKsyunz <[email protected]>
@MaxKsyunz MaxKsyunz closed this Nov 9, 2022
@MaxKsyunz
MaxKsyunz deleted the dev-constant-now branch February 8, 2023 17:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants