Fix column alias rewriting

This commit is contained in:
Amos Bird 2021-07-18 23:27:19 +08:00
parent f1702d356e
commit d74aa64f6b
No known key found for this signature in database
GPG Key ID: 80D430DCBECFEDB4
7 changed files with 24 additions and 4 deletions

View File

@ -81,6 +81,7 @@ void ColumnAliasesMatcher::visit(ASTIdentifier & node, ASTPtr & ast, Data & data
else
ast->setAlias(*column_name);
data.changed = true;
// revisit ast to track recursive alias columns
Visitor(data).visit(ast);
}

View File

@ -60,6 +60,9 @@ public:
/// private_aliases are from lambda, so these are local names.
NameSet private_aliases;
/// Check if query is changed by this visitor.
bool changed = false;
Data(const ColumnsDescription & columns_, const NameToNameMap & array_join_result_columns_, ContextPtr context_)
: columns(columns_), context(context_)
{

View File

@ -951,8 +951,13 @@ TreeRewriterResultPtr TreeRewriter::analyzeSelect(
/// rewrite filters for select query, must go after getArrayJoinedColumns
if (settings.optimize_respect_aliases && result.metadata_snapshot)
{
replaceAliasColumnsInQuery(query, result.metadata_snapshot->getColumns(), result.array_join_result_to_source, getContext());
result.collectUsedColumns(query, true);
/// If query is changed, we need to redo some work to correct name resolution.
if (replaceAliasColumnsInQuery(query, result.metadata_snapshot->getColumns(), result.array_join_result_to_source, getContext()))
{
result.aggregates = getAggregates(query, *select_query);
result.window_function_asts = getWindowFunctions(query, *select_query);
result.collectUsedColumns(query, true);
}
}
result.ast_join = select_query->join();

View File

@ -6,12 +6,13 @@
namespace DB
{
void replaceAliasColumnsInQuery(
bool replaceAliasColumnsInQuery(
ASTPtr & ast, const ColumnsDescription & columns, const NameToNameMap & array_join_result_to_source, ContextPtr context)
{
ColumnAliasesVisitor::Data aliases_column_data(columns, array_join_result_to_source, context);
ColumnAliasesVisitor aliases_column_visitor(aliases_column_data);
aliases_column_visitor.visit(ast);
return aliases_column_data.changed;
}
}

View File

@ -10,7 +10,8 @@ namespace DB
class ColumnsDescription;
void replaceAliasColumnsInQuery(
/// Replace storage alias columns in select query if possible. Return true if the query is changed.
bool replaceAliasColumnsInQuery(
ASTPtr & ast, const ColumnsDescription & columns, const NameToNameMap & array_join_result_to_source, ContextPtr context);
}

View File

@ -61,3 +61,4 @@ second-index
1
1
1
1 1

View File

@ -127,3 +127,11 @@ select sum(i) from pd group by dt_m settings allow_experimental_projection_optim
drop table pd;
drop table pl;
drop table if exists t;
create temporary table t (x UInt64, y alias x);
insert into t values (1);
select sum(x), sum(y) from t;
drop table t;