1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
|
#pragma once
#include <Functions/FunctionFactory.h>
#include <IO/WriteHelpers.h>
#include <Interpreters/InDepthNodeVisitor.h>
#include <Parsers/ASTFunction.h>
#include <Parsers/ASTSetQuery.h>
#include <Parsers/ASTTablesInSelectQuery.h>
#include <Parsers/ASTIdentifier.h>
#include <Parsers/IAST.h>
#include <Common/typeid_cast.h>
namespace DB
{
/// recursive traversal and check for optimizeGroupByFunctionKeys
struct KeepFunctionMatcher
{
struct Data
{
std::unordered_set<String> & key_names_to_keep;
bool & keep_key;
};
using Visitor = InDepthNodeVisitor<KeepFunctionMatcher, true>;
static bool needChildVisit(const ASTPtr & node, const ASTPtr &)
{
return !(node->as<ASTFunction>());
}
static void visit(ASTFunction * function_node, Data & data)
{
if ((function_node->arguments->children).empty())
{
data.keep_key = true;
return;
}
if (!data.key_names_to_keep.count(function_node->getColumnName()))
{
Visitor(data).visit(function_node->arguments);
}
}
static void visit(ASTIdentifier * ident, Data & data)
{
if (!data.key_names_to_keep.count(ident->shortName()))
{
/// if variable of a function is not in GROUP BY keys, this function should not be deleted
data.keep_key = true;
return;
}
}
static void visit(const ASTPtr & ast, Data & data)
{
if (data.keep_key)
return;
if (auto * function_node = ast->as<ASTFunction>())
{
visit(function_node, data);
}
else if (auto * ident = ast->as<ASTIdentifier>())
{
visit(ident, data);
}
else if (!ast->as<ASTExpressionList>())
{
data.keep_key = true;
}
}
};
using KeepFunctionVisitor = InDepthNodeVisitor<KeepFunctionMatcher, true>;
class GroupByFunctionKeysMatcher
{
public:
struct Data
{
std::unordered_set<String> & key_names_to_keep;
};
static bool needChildVisit(const ASTPtr & node, const ASTPtr &)
{
return !(node->as<ASTFunction>());
}
static void visit(ASTFunction * function_node, Data & data)
{
bool keep_key = false;
KeepFunctionVisitor::Data keep_data{data.key_names_to_keep, keep_key};
KeepFunctionVisitor(keep_data).visit(function_node->arguments);
if (!keep_key)
(data.key_names_to_keep).erase(function_node->getColumnName());
}
static void visit(const ASTPtr & ast, Data & data)
{
if (auto * function_node = ast->as<ASTFunction>())
{
if (function_node->arguments && !function_node->arguments->children.empty())
visit(function_node, data);
}
}
};
using GroupByFunctionKeysVisitor = InDepthNodeVisitor<GroupByFunctionKeysMatcher, true>;
}
|