ClickHouse/src/Interpreters/RewriteCountVariantsVisitor.cpp

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

68 lines
1.7 KiB
C++
Raw Normal View History

2021-02-07 07:22:51 +00:00
#include <Interpreters/RewriteCountVariantsVisitor.h>
#include <Parsers/ASTFunction.h>
#include <Parsers/ASTLiteral.h>
#include <Parsers/ASTSubquery.h>
#include <Parsers/ASTTablesInSelectQuery.h>
#include <Poco/String.h>
#include <Common/typeid_cast.h>
2022-10-01 15:47:58 +00:00
#include <Common/checkStackSize.h>
#include <Interpreters/Context.h>
2022-10-01 15:47:58 +00:00
2021-02-07 07:22:51 +00:00
namespace DB
{
2022-10-01 15:47:58 +00:00
2021-02-07 07:22:51 +00:00
void RewriteCountVariantsVisitor::visit(ASTPtr & node)
{
2022-10-01 15:47:58 +00:00
checkStackSize();
2021-02-07 07:22:51 +00:00
if (node->as<ASTSubquery>() || node->as<ASTTableExpression>() || node->as<ASTArrayJoin>())
return;
for (auto & child : node->children)
visit(child);
if (auto * func = node->as<ASTFunction>())
visit(*func);
}
void RewriteCountVariantsVisitor::visit(ASTFunction & func)
{
2021-02-11 15:21:21 +00:00
if (!func.arguments || func.arguments->children.empty() || func.arguments->children.size() > 1 || !func.arguments->children[0])
2021-02-07 07:22:51 +00:00
return;
auto name = Poco::toLower(func.name);
if (name != "sum" && name != "count")
return;
auto & func_arguments = func.arguments->children;
const auto * first_arg_literal = func_arguments[0]->as<ASTLiteral>();
if (!first_arg_literal)
return;
bool transform = false;
if (name == "count")
{
if (first_arg_literal->value.getType() != Field::Types::Null)
transform = true;
}
else if (name == "sum")
{
if (first_arg_literal->value.getType() == Field::Types::UInt64)
{
auto constant = first_arg_literal->value.get<UInt64>();
if (constant == 1 && !context->getSettingsRef().aggregate_functions_null_for_empty)
2021-02-07 07:22:51 +00:00
transform = true;
}
}
if (!transform)
return;
func.name = "count";
func.arguments->children.clear();
}
}