Skip to content

Commit

Permalink
feat: Add convenience API to evalute constant expression (facebookinc…
Browse files Browse the repository at this point in the history
…ubator#12306)

Summary:
Pull Request resolved: facebookincubator#12306

Useful for constant folding.

Reviewed By: Yuhta

Differential Revision: D69463896

fbshipit-source-id: 6ca71daea190c83cdaf816c3945c6624f1639325
  • Loading branch information
mbasmanova authored and facebook-github-bot committed Feb 11, 2025
1 parent 04bfdff commit 5568518
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
16 changes: 16 additions & 0 deletions velox/expression/Expr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2014,4 +2014,20 @@ core::ExecCtx* SimpleExpressionEvaluator::ensureExecCtx() {
return execCtx_.get();
}

VectorPtr evaluateConstantExpression(
const core::TypedExprPtr& expr,
memory::MemoryPool* pool) {
auto data = BaseVector::create<RowVector>(ROW({}), 1, pool);

auto queryCtx = velox::core::QueryCtx::create();
velox::core::ExecCtx execCtx{pool, queryCtx.get()};
velox::exec::ExprSet exprSet({expr}, &execCtx);
velox::exec::EvalCtx evalCtx(&execCtx, &exprSet, data.get());

velox::SelectivityVector singleRow(1);
std::vector<velox::VectorPtr> results(1);
exprSet.eval(singleRow, evalCtx, results);
return results.at(0);
}

} // namespace facebook::velox::exec
6 changes: 6 additions & 0 deletions velox/expression/Expr.h
Original file line number Diff line number Diff line change
Expand Up @@ -830,6 +830,12 @@ std::unique_ptr<ExprSet> makeExprSetFromFlag(
std::vector<core::TypedExprPtr>&& source,
core::ExecCtx* execCtx);

/// Evaluates an expression that doesn't depend on any inputs and returns the
/// result as single-row vector.
VectorPtr evaluateConstantExpression(
const core::TypedExprPtr& expr,
memory::MemoryPool* pool);

/// Returns a string representation of the expression trees annotated with
/// runtime statistics. Expected to be called after calling ExprSet::eval one or
/// more times. If called before ExprSet::eval runtime statistics will be all
Expand Down
13 changes: 13 additions & 0 deletions velox/expression/tests/ExprTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4970,5 +4970,18 @@ TEST_F(ExprTest, disabledeferredLazyLoading) {
expressions, makeRowVector({c0, c1}), {}, execCtx.get());
}

TEST_F(ExprTest, evaluateConstantExpression) {
auto eval = [&](const std::string& sql) {
auto expr = parseExpression(sql, ROW({}));
return exec::evaluateConstantExpression(expr, pool());
};

assertEqualVectors(eval("1 + 2"), makeConstant<int64_t>(3, 1));

assertEqualVectors(
eval("transform(array[1, 2, 3], x -> (x * 2))"),
makeArrayVectorFromJson<int64_t>({"[2, 4, 6]"}));
}

} // namespace
} // namespace facebook::velox::test

0 comments on commit 5568518

Please sign in to comment.