1#pragma once
2
3#include <ostream>
4#include <optional>
5
6#include <Common/typeid_cast.h>
7#include <Core/Names.h>
8#include <Parsers/ASTIdentifier.h>
9#include <Parsers/ASTTablesInSelectQuery.h>
10
11namespace DB
12{
13
14/// Information about table and column names extracted from ASTSelectQuery block. Do not include info from subselects.
15struct ColumnNamesContext
16{
17 struct JoinedTable
18 {
19 const ASTTableExpression * expr = nullptr;
20 const ASTTableJoin * join = nullptr;
21
22 std::optional<String> alias() const
23 {
24 String alias;
25 if (expr)
26 {
27 if (expr->database_and_table_name)
28 alias = expr->database_and_table_name->tryGetAlias();
29 else if (expr->table_function)
30 alias = expr->table_function->tryGetAlias();
31 else if (expr->subquery)
32 alias = expr->subquery->tryGetAlias();
33 }
34 if (!alias.empty())
35 return alias;
36 return {};
37 }
38
39 std::optional<String> name() const
40 {
41 if (expr)
42 return tryGetIdentifierName(expr->database_and_table_name);
43 return {};
44 }
45
46 std::optional<ASTTableJoin::Kind> joinKind() const
47 {
48 if (join)
49 return join->kind;
50 return {};
51 }
52 };
53
54 struct NameInfo
55 {
56 std::set<String> aliases;
57 size_t appears = 0;
58
59 void addInclusion(const String & alias)
60 {
61 if (!alias.empty())
62 aliases.insert(alias);
63 ++appears;
64 }
65 };
66
67 std::unordered_map<String, NameInfo> required_names;
68 NameSet table_aliases;
69 NameSet private_aliases;
70 NameSet complex_aliases;
71 NameSet masked_columns;
72 NameSet array_join_columns;
73 std::vector<JoinedTable> tables; /// ordered list of visited tables in FROM section with joins
74 bool has_table_join = false;
75 bool has_array_join = false;
76
77 bool addTableAliasIfAny(const IAST & ast);
78 bool addColumnAliasIfAny(const IAST & ast);
79 void addColumnIdentifier(const ASTIdentifier & node);
80 bool addArrayJoinAliasIfAny(const IAST & ast);
81 void addArrayJoinIdentifier(const ASTIdentifier & node);
82
83 NameSet requiredColumns() const;
84 size_t nameInclusion(const String & name) const;
85};
86
87std::ostream & operator << (std::ostream & os, const ColumnNamesContext & cols);
88
89}
90