ClickHouse/dbms/src/Parsers/ParserCase.cpp

107 lines
2.6 KiB
C++
Raw Normal View History

#include <Parsers/ParserCase.h>
#include <Parsers/ExpressionElementParsers.h>
#include <Parsers/ExpressionListParsers.h>
#include <Parsers/ASTFunction.h>
#include <Parsers/ASTLiteral.h>
#include <Core/Field.h>
2016-05-03 23:19:14 +00:00
namespace DB
{
bool ParserCase::parseImpl(Pos & pos, ASTPtr & node, Expected & expected)
2016-05-03 23:19:14 +00:00
{
ParserKeyword s_case{"CASE"};
ParserKeyword s_when{"WHEN"};
ParserKeyword s_then{"THEN"};
ParserKeyword s_else{"ELSE"};
ParserKeyword s_end{ "END"};
ParserExpressionWithOptionalAlias p_expr{false};
2016-05-03 23:19:14 +00:00
if (!s_case.ignore(pos, expected))
return false;
2016-05-03 23:19:14 +00:00
auto old_pos = pos;
bool has_case_expr = !s_when.ignore(pos, expected);
pos = old_pos;
2016-05-03 23:19:14 +00:00
ASTs args;
2016-05-03 23:19:14 +00:00
auto parse_branches = [&]()
{
bool has_branch = false;
while (s_when.ignore(pos, expected))
{
has_branch = true;
2016-05-03 23:19:14 +00:00
ASTPtr expr_when;
if (!p_expr.parse(pos, expr_when, expected))
return false;
args.push_back(expr_when);
2016-05-03 23:19:14 +00:00
if (!s_then.ignore(pos, expected))
return false;
2016-05-03 23:19:14 +00:00
ASTPtr expr_then;
if (!p_expr.parse(pos, expr_then, expected))
return false;
args.push_back(expr_then);
}
2016-05-03 23:19:14 +00:00
if (!has_branch)
return false;
2016-05-03 23:19:14 +00:00
if (!s_else.ignore(pos, expected))
return false;
2016-05-03 23:19:14 +00:00
ASTPtr expr_else;
if (!p_expr.parse(pos, expr_else, expected))
return false;
args.push_back(expr_else);
2016-05-03 23:19:14 +00:00
if (!s_end.ignore(pos, expected))
return false;
2016-05-03 23:19:14 +00:00
return true;
};
2016-05-03 23:19:14 +00:00
if (has_case_expr)
{
ASTPtr case_expr;
if (!p_expr.parse(pos, case_expr, expected))
return false;
args.push_back(case_expr);
2016-05-03 23:19:14 +00:00
if (!parse_branches())
return false;
2016-05-03 23:19:14 +00:00
2018-02-26 03:37:08 +00:00
auto function_args = std::make_shared<ASTExpressionList>();
function_args->children = std::move(args);
2016-05-03 23:19:14 +00:00
2018-02-26 03:37:08 +00:00
auto function = std::make_shared<ASTFunction>();
2017-08-07 01:36:20 +00:00
function->name = "caseWithExpression";
function->arguments = function_args;
function->children.push_back(function->arguments);
2016-05-03 23:19:14 +00:00
node = function;
}
else
{
if (!parse_branches())
return false;
2016-05-03 23:19:14 +00:00
2018-02-26 03:37:08 +00:00
auto function_args = std::make_shared<ASTExpressionList>();
function_args->children = std::move(args);
2016-05-03 23:19:14 +00:00
2018-02-26 03:37:08 +00:00
auto function = std::make_shared<ASTFunction>();
function->name = "multiIf";
function->arguments = function_args;
function->children.push_back(function->arguments);
2016-05-03 23:19:14 +00:00
node = function;
}
2016-05-03 23:19:14 +00:00
return true;
2016-05-03 23:19:14 +00:00
}
}