ExpressionAnalyzer.cpp 131.6 KB
Newer Older
1
#include <Poco/Util/Application.h>
A
Alexey Milovidov 已提交
2
#include <Poco/String.h>
3

4
#include <DataTypes/FieldToDataType.h>
5

6 7 8 9
#include <Parsers/ASTFunction.h>
#include <Parsers/ASTIdentifier.h>
#include <Parsers/ASTLiteral.h>
#include <Parsers/ASTAsterisk.h>
10
#include <Parsers/ASTQualifiedAsterisk.h>
11 12
#include <Parsers/ASTExpressionList.h>
#include <Parsers/ASTSelectQuery.h>
13
#include <Parsers/ASTSelectWithUnionQuery.h>
14 15
#include <Parsers/ASTSubquery.h>
#include <Parsers/ASTOrderByElement.h>
16
#include <Parsers/formatAST.h>
17

18
#include <DataTypes/DataTypeSet.h>
19
#include <DataTypes/DataTypeNullable.h>
20
#include <DataTypes/NestedUtils.h>
21
#include <DataTypes/DataTypesNumber.h>
22

23
#include <Columns/ColumnSet.h>
24
#include <Columns/ColumnConst.h>
25

26
#include <Interpreters/InterpreterSelectWithUnionQuery.h>
27 28 29 30 31
#include <Interpreters/ExpressionAnalyzer.h>
#include <Interpreters/ExpressionActions.h>
#include <Interpreters/InJoinSubqueriesPreprocessor.h>
#include <Interpreters/LogicalExpressionsOptimizer.h>
#include <Interpreters/ExternalDictionaries.h>
A
Alexey Milovidov 已提交
32
#include <Interpreters/convertFieldToType.h>
33 34
#include <Interpreters/Set.h>
#include <Interpreters/Join.h>
35 36
#include <Interpreters/ProjectionManipulation.h>
#include <Interpreters/evaluateConstantExpression.h>
37

38
#include <AggregateFunctions/AggregateFunctionFactory.h>
39
#include <AggregateFunctions/parseAggregateFunctionParameters.h>
40

41 42 43 44
#include <Storages/StorageDistributed.h>
#include <Storages/StorageMemory.h>
#include <Storages/StorageSet.h>
#include <Storages/StorageJoin.h>
45

46 47
#include <DataStreams/LazyBlockInputStream.h>
#include <DataStreams/copyData.h>
48

49
#include <Dictionaries/IDictionary.h>
50

51
#include <Common/typeid_cast.h>
52
#include <Common/StringUtils/StringUtils.h>
53

54
#include <Parsers/formatAST.h>
55

56 57
#include <Functions/FunctionFactory.h>
#include <Functions/IFunction.h>
A
Andrey Mironov 已提交
58

59
#include <ext/range.h>
60
#include <DataTypes/DataTypeFactory.h>
61 62
#include <DataTypes/DataTypeFunction.h>
#include <Functions/FunctionsMiscellaneous.h>
63
#include <DataTypes/DataTypeTuple.h>
64
#include <Parsers/queryToString.h>
65 66
#include <Parsers/ExpressionListParsers.h>
#include <Parsers/parseQuery.h>
67

68 69 70 71

namespace DB
{

72 73
namespace ErrorCodes
{
74
    extern const int BAD_ARGUMENTS;
75 76 77 78
    extern const int MULTIPLE_EXPRESSIONS_FOR_ALIAS;
    extern const int UNKNOWN_IDENTIFIER;
    extern const int CYCLIC_ALIASES;
    extern const int INCORRECT_RESULT_OF_SCALAR_SUBQUERY;
A
Alexey Milovidov 已提交
79
    extern const int TOO_MANY_ROWS;
80 81 82 83 84 85 86 87 88 89 90
    extern const int NOT_FOUND_COLUMN_IN_BLOCK;
    extern const int INCORRECT_ELEMENT_OF_SET;
    extern const int ALIAS_REQUIRED;
    extern const int EMPTY_NESTED_TABLE;
    extern const int NOT_AN_AGGREGATE;
    extern const int UNEXPECTED_EXPRESSION;
    extern const int DUPLICATE_COLUMN;
    extern const int FUNCTION_CANNOT_HAVE_PARAMETERS;
    extern const int ILLEGAL_AGGREGATION;
    extern const int SUPPORT_IS_DISABLED;
    extern const int TOO_DEEP_AST;
91
    extern const int TOO_BIG_AST;
92
    extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH;
T
Tsarkova Anastasia 已提交
93
    extern const int CONDITIONAL_TREE_PARENT_NOT_FOUND;
94
    extern const int TYPE_MISMATCH;
95
    extern const int INVALID_JOIN_ON_EXPRESSION;
96 97
}

98

99 100
/** Calls to these functions in the GROUP BY statement would be
  * replaced by their immediate argument.
101
  */
A
Alexey Milovidov 已提交
102 103
const std::unordered_set<String> injective_function_names
{
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
    "negate",
    "bitNot",
    "reverse",
    "reverseUTF8",
    "toString",
    "toFixedString",
    "IPv4NumToString",
    "IPv4StringToNum",
    "hex",
    "unhex",
    "bitmaskToList",
    "bitmaskToArray",
    "tuple",
    "regionToName",
    "concatAssumeInjective",
119 120
};

121 122
const std::unordered_set<String> possibly_injective_function_names
{
123 124 125 126 127 128 129 130 131 132 133 134 135
    "dictGetString",
    "dictGetUInt8",
    "dictGetUInt16",
    "dictGetUInt32",
    "dictGetUInt64",
    "dictGetInt8",
    "dictGetInt16",
    "dictGetInt32",
    "dictGetInt64",
    "dictGetFloat32",
    "dictGetFloat64",
    "dictGetDate",
    "dictGetDateTime"
136 137
};

A
Merge  
Alexey Arno 已提交
138 139 140 141
namespace
{

bool functionIsInOperator(const String & name)
142
{
143
    return name == "in" || name == "notIn";
144 145
}

A
Merge  
Alexey Arno 已提交
146
bool functionIsInOrGlobalInOperator(const String & name)
147
{
148
    return name == "in" || name == "notIn" || name == "globalIn" || name == "globalNotIn";
149 150
}

151
void removeDuplicateColumns(NamesAndTypesList & columns)
152
{
153
    std::set<String> names;
154 155 156 157 158 159 160
    for (auto it = columns.begin(); it != columns.end();)
    {
        if (names.emplace(it->name).second)
            ++it;
        else
            columns.erase(it++);
    }
161 162
}

A
Merge  
Alexey Arno 已提交
163
}
164

165

166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
String DatabaseAndTableWithAlias::getQualifiedNamePrefix() const
{
    return (!alias.empty() ? alias : (database + '.' + table)) + '.';
}


void DatabaseAndTableWithAlias::makeQualifiedName(const ASTPtr & ast) const
{
    if (auto identifier = typeid_cast<ASTIdentifier *>(ast.get()))
    {
        String prefix = getQualifiedNamePrefix();
        identifier->name.insert(identifier->name.begin(), prefix.begin(), prefix.end());

        Names qualifiers;
        if (!alias.empty())
            qualifiers.push_back(alias);
        else
        {
            qualifiers.push_back(database);
            qualifiers.push_back(table);
        }

        for (const auto & qualifier : qualifiers)
            identifier->children.emplace_back(std::make_shared<ASTIdentifier>(qualifier));
    }
}


194
ExpressionAnalyzer::ExpressionAnalyzer(
195 196
    const ASTPtr & ast_,
    const Context & context_,
197
    const StoragePtr & storage_,
198 199
    const NamesAndTypesList & source_columns_,
    const Names & required_result_columns_,
200
    size_t subquery_depth_,
A
Alexey Milovidov 已提交
201 202
    bool do_global_,
    const SubqueriesForSets & subqueries_for_set_)
203
    : ast(ast_), context(context_), settings(context.getSettings()),
204
    subquery_depth(subquery_depth_),
205
    source_columns(source_columns_),
206
    storage(storage_),
A
Alexey Milovidov 已提交
207
    do_global(do_global_), subqueries_for_sets(subqueries_for_set_)
208
{
209
    select_query = typeid_cast<ASTSelectQuery *>(ast.get());
210

211 212 213 214
    if (!storage && select_query)
    {
        auto select_database = select_query->database();
        auto select_table = select_query->table();
215

216 217 218 219 220 221 222 223 224 225 226
        if (select_table
            && !typeid_cast<const ASTSelectWithUnionQuery *>(select_table.get())
            && !typeid_cast<const ASTFunction *>(select_table.get()))
        {
            String database = select_database
                ? typeid_cast<const ASTIdentifier &>(*select_database).name
                : "";
            const String & table = typeid_cast<const ASTIdentifier &>(*select_table).name;
            storage = context.tryGetTable(database, table);
        }
    }
227

228
    if (storage && source_columns.empty())
A
Alexey Zatelepin 已提交
229
        source_columns = storage->getColumns().getAllPhysical();
230 231 232
    else
        removeDuplicateColumns(source_columns);

233
    addAliasColumns();
234

235 236
    translateQualifiedNames();

F
f1yegor 已提交
237 238
    /// Depending on the user's profile, check for the execution rights
    /// distributed subqueries inside the IN or JOIN sections and process these subqueries.
239
    InJoinSubqueriesPreprocessor(context).process(select_query);
A
Merge  
Alexey Arno 已提交
240

F
f1yegor 已提交
241
    /// Optimizes logical expressions.
242
    LogicalExpressionsOptimizer(select_query, settings).perform();
243

F
f1yegor 已提交
244
    /// Creates a dictionary `aliases`: alias -> ASTPtr
245
    addASTAliases(ast);
246

247 248
    /// Common subexpression elimination. Rewrite rules.
    normalizeTree();
249

250 251 252
    /// Substitute aliases for required_result_columns and create set with their names.
    required_result_columns = createRequiredResultColumnsMap(required_result_columns_);

A
Alexey Milovidov 已提交
253
    /// Remove unneeded columns according to 'required_result_columns'.
254 255 256 257 258
    /// Leave all selected columns in case of DISTINCT; columns that contain arrayJoin function inside.
    /// Must be after 'normalizeTree' (after expanding aliases, for aliases not get lost)
    ///  and before 'executeScalarSubqueries', 'analyzeAggregation', etc. to avoid excessive calculations.
    removeUnneededColumnsFromSelectClause();

F
f1yegor 已提交
259
    /// Executing scalar subqueries - replacing them with constant values.
260
    executeScalarSubqueries();
261

262
    /// Optimize if with constant condition after constants was substituted instead of sclalar subqueries.
263
    optimizeIfWithConstantCondition();
264

265 266
    /// GROUP BY injective function elimination.
    optimizeGroupBy();
267

F
f1yegor 已提交
268
    /// Remove duplicate items from ORDER BY.
269
    optimizeOrderBy();
270

271 272
    // Remove duplicated elements from LIMIT BY clause.
    optimizeLimitBy();
273

274 275
    /// array_join_alias_to_name, array_join_result_to_source.
    getArrayJoinedColumns();
276

277
    /// Delete the unnecessary from `source_columns` list. Create `unknown_required_source_columns`. Form `columns_added_by_join`.
278
    collectUsedColumns();
279

F
f1yegor 已提交
280 281
    /// external_tables, subqueries_for_sets for global subqueries.
    /// Replaces global subqueries with the generated names of temporary tables that will be sent to remote servers.
282
    initGlobalSubqueriesAndExternalTables();
283

284
    /// has_aggregation, aggregation_keys, aggregate_descriptions, aggregated_columns.
F
f1yegor 已提交
285 286 287 288 289 290
    /// This analysis should be performed after processing global subqueries, because otherwise,
    /// if the aggregate function contains a global subquery, then `analyzeAggregation` method will save
    /// in `aggregate_descriptions` the information about the parameters of this aggregate function, among which
    /// global subquery. Then, when you call `initGlobalSubqueriesAndExternalTables` method, this
    /// the global subquery will be replaced with a temporary table, resulting in aggregate_descriptions
    /// will contain out-of-date information, which will lead to an error when the query is executed.
291
    analyzeAggregation();
292 293
}

294 295
static DatabaseAndTableWithAlias getTableNameWithAliasFromTableExpression(const ASTTableExpression & table_expression,
                                                                          const Context & context)
296
{
297
    DatabaseAndTableWithAlias database_and_table_with_alias;
298 299 300

    if (table_expression.database_and_table_name)
    {
301
        const auto & identifier = static_cast<const ASTIdentifier &>(*table_expression.database_and_table_name);
302

303
        database_and_table_with_alias.alias = identifier.tryGetAlias();
304 305 306

        if (table_expression.database_and_table_name->children.empty())
        {
307 308
            database_and_table_with_alias.database = context.getCurrentDatabase();
            database_and_table_with_alias.table = identifier.name;
309 310 311 312 313 314
        }
        else
        {
            if (table_expression.database_and_table_name->children.size() != 2)
                throw Exception("Logical error: number of components in table expression not equal to two", ErrorCodes::LOGICAL_ERROR);

315 316
            database_and_table_with_alias.database = static_cast<const ASTIdentifier &>(*identifier.children[0]).name;
            database_and_table_with_alias.table = static_cast<const ASTIdentifier &>(*identifier.children[1]).name;
317 318 319 320
        }
    }
    else if (table_expression.table_function)
    {
321
        database_and_table_with_alias.alias = table_expression.table_function->tryGetAlias();
322 323 324
    }
    else if (table_expression.subquery)
    {
325
        database_and_table_with_alias.alias = table_expression.subquery->tryGetAlias();
326 327 328 329
    }
    else
        throw Exception("Logical error: no known elements in ASTTableExpression", ErrorCodes::LOGICAL_ERROR);

330 331 332 333 334 335 336 337 338 339 340 341 342 343
    return database_and_table_with_alias;
};


void ExpressionAnalyzer::translateQualifiedNames()
{
    if (!select_query || !select_query->tables || select_query->tables->children.empty())
        return;

    auto & element = static_cast<ASTTablesInSelectQueryElement &>(*select_query->tables->children[0]);

    if (!element.table_expression)        /// This is ARRAY JOIN without a table at the left side.
        return;

344 345 346 347
    auto & table_expression = static_cast<ASTTableExpression &>(*element.table_expression);
    auto * join = select_query->join();

    std::vector<DatabaseAndTableWithAlias> tables = {getTableNameWithAliasFromTableExpression(table_expression, context)};
348

349 350 351 352 353
    if (join)
    {
        const auto & join_table_expression = static_cast<const ASTTableExpression &>(*join->table_expression);
        tables.emplace_back(getTableNameWithAliasFromTableExpression(join_table_expression, context));
    }
354

355
    translateQualifiedNamesImpl(ast, tables);
356 357 358
}


359 360
static size_t getNumComponentsToStripInOrderToTranslateQualifiedName(const ASTIdentifier & identifier,
                                                                     const DatabaseAndTableWithAlias & names)
361
{
362 363 364 365 366 367
    size_t num_qualifiers_to_strip = 0;

    auto get_identifier_name = [](const ASTPtr & ast) { return static_cast<const ASTIdentifier &>(*ast).name; };

    /// It is compound identifier
    if (!identifier.children.empty())
368
    {
369 370 371 372
        size_t num_components = identifier.children.size();

        /// database.table.column
        if (num_components >= 3
373 374 375
            && !names.database.empty()
            && get_identifier_name(identifier.children[0]) == names.database
            && get_identifier_name(identifier.children[1]) == names.table)
376
        {
377 378
            num_qualifiers_to_strip = 2;
        }
379

380 381
        /// table.column or alias.column. If num_components > 2, it is like table.nested.column.
        if (num_components >= 2
382
            && ((!names.table.empty() && get_identifier_name(identifier.children[0]) == names.table)
383 384 385 386 387
                || (!names.alias.empty() && get_identifier_name(identifier.children[0]) == names.alias)))
        {
            num_qualifiers_to_strip = 1;
        }
    }
388

389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
    return num_qualifiers_to_strip;
}


static void stripIdentifier(ASTPtr & ast, size_t num_qualifiers_to_strip)
{
    ASTIdentifier * identifier = typeid_cast<ASTIdentifier *>(ast.get());

    if (!identifier)
        throw Exception("ASTIdentifier expected for stripIdentifier", ErrorCodes::LOGICAL_ERROR);

    if (num_qualifiers_to_strip)
    {
        size_t num_components = identifier->children.size();

        /// plain column
        if (num_components - num_qualifiers_to_strip == 1)
        {
            String node_alias = identifier->tryGetAlias();
            ast = identifier->children.back();
            if (!node_alias.empty())
                ast->setAlias(node_alias);
        }
        else
        /// nested column
        {
            identifier->children.erase(identifier->children.begin(), identifier->children.begin() + num_qualifiers_to_strip);
            String new_name;
            for (const auto & child : identifier->children)
            {
                if (!new_name.empty())
                    new_name += '.';
                new_name += static_cast<const ASTIdentifier &>(*child.get()).name;
422
            }
423 424 425 426 427 428
            identifier->name = new_name;
        }
    }
}


429
void ExpressionAnalyzer::translateQualifiedNamesImpl(ASTPtr & ast, const std::vector<DatabaseAndTableWithAlias> & tables)
430 431 432 433 434
{
    if (auto * identifier = typeid_cast<ASTIdentifier *>(ast.get()))
    {
        if (identifier->kind == ASTIdentifier::Column)
        {
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
            /// Select first table name with max number of qualifiers which can be stripped.
            size_t max_num_qualifiers_to_strip = 0;
            size_t best_table_pos = 0;

            for (size_t table_pos = 0; table_pos < tables.size(); ++table_pos)
            {
                const auto & table = tables[table_pos];
                auto num_qualifiers_to_strip = getNumComponentsToStripInOrderToTranslateQualifiedName(*identifier, table);

                if (num_qualifiers_to_strip > max_num_qualifiers_to_strip)
                {
                    max_num_qualifiers_to_strip = num_qualifiers_to_strip;
                    best_table_pos = table_pos;
                }
            }

            stripIdentifier(ast, max_num_qualifiers_to_strip);
452

453 454 455 456 457 458
            /// In case if column from the joined table are in source columns, change it's name to qualified.
            if (best_table_pos && source_columns.contains(ast->getColumnName()))
            {
                duplicate_columns_from_joined_table.insert(ast->getColumnName());
                tables[best_table_pos].makeQualifiedName(ast);
            }
459 460
        }
    }
A
Alexey Milovidov 已提交
461
    else if (typeid_cast<ASTQualifiedAsterisk *>(ast.get()))
462 463 464 465 466 467 468 469 470 471 472 473
    {
        if (ast->children.size() != 1)
            throw Exception("Logical error: qualified asterisk must have exactly one child", ErrorCodes::LOGICAL_ERROR);

        ASTIdentifier * ident = typeid_cast<ASTIdentifier *>(ast->children[0].get());
        if (!ident)
            throw Exception("Logical error: qualified asterisk must have identifier as its child", ErrorCodes::LOGICAL_ERROR);

        size_t num_components = ident->children.size();
        if (num_components > 2)
            throw Exception("Qualified asterisk cannot have more than two qualifiers", ErrorCodes::UNKNOWN_ELEMENT_IN_AST);

474
        for (const auto & table_names : tables)
475
        {
476 477 478 479 480 481 482 483 484 485 486 487
            /// database.table.*, table.* or alias.*
            if ((num_components == 2
                 && !table_names.database.empty()
                 && static_cast<const ASTIdentifier &>(*ident->children[0]).name == table_names.database
                 && static_cast<const ASTIdentifier &>(*ident->children[1]).name == table_names.table)
                || (num_components == 0
                    && ((!table_names.table.empty() && ident->name == table_names.table)
                        || (!table_names.alias.empty() && ident->name == table_names.alias))))
            {
                /// Replace to plain asterisk.
                ast = std::make_shared<ASTAsterisk>();
            }
488 489
        }
    }
490 491 492 493 494 495
    else if (auto * join = typeid_cast<ASTTableJoin *>(ast.get()))
    {
        /// Don't translate on_expression hear in order to resolve equasions parts later.
        if (join->using_expression_list)
            translateQualifiedNamesImpl(join->using_expression_list, tables);
    }
496 497 498 499
    else
    {
        for (auto & child : ast->children)
        {
500
            /// Do not go to FROM, JOIN, subqueries.
501
            if (!typeid_cast<const ASTTableExpression *>(child.get())
502
                && !typeid_cast<const ASTSelectWithUnionQuery *>(child.get()))
503
            {
504
                translateQualifiedNamesImpl(child, tables);
505 506 507 508 509 510
            }
        }
    }
}


511 512
void ExpressionAnalyzer::optimizeIfWithConstantCondition()
{
513
    optimizeIfWithConstantConditionImpl(ast, aliases);
514 515 516 517
}

bool ExpressionAnalyzer::tryExtractConstValueFromCondition(const ASTPtr & condition, bool & value) const
{
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
    /// numeric constant in condition
    if (const ASTLiteral * literal = typeid_cast<ASTLiteral *>(condition.get()))
    {
        if (literal->value.getType() == Field::Types::Int64 ||
            literal->value.getType() == Field::Types::UInt64)
        {
            value = literal->value.get<Int64>();
            return true;
        }
    }

    /// cast of numeric constant in condition to UInt8
    if (const ASTFunction * function = typeid_cast<ASTFunction * >(condition.get()))
    {
        if (function->name == "CAST")
        {
            if (ASTExpressionList * expr_list = typeid_cast<ASTExpressionList *>(function->arguments.get()))
            {
                const ASTPtr & type_ast = expr_list->children.at(1);
                if (const ASTLiteral * type_literal = typeid_cast<ASTLiteral *>(type_ast.get()))
                {
                    if (type_literal->value.getType() == Field::Types::String &&
                        type_literal->value.get<std::string>() == "UInt8")
                        return tryExtractConstValueFromCondition(expr_list->children.at(0), value);
                }
            }
        }
    }

    return false;
548 549
}

550
void ExpressionAnalyzer::optimizeIfWithConstantConditionImpl(ASTPtr & current_ast, ExpressionAnalyzer::Aliases & aliases) const
551
{
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
    if (!current_ast)
        return;

    for (ASTPtr & child : current_ast->children)
    {
        ASTFunction * function_node = typeid_cast<ASTFunction *>(child.get());
        if (!function_node || function_node->name != "if")
        {
            optimizeIfWithConstantConditionImpl(child, aliases);
            continue;
        }

        optimizeIfWithConstantConditionImpl(function_node->arguments, aliases);
        ASTExpressionList * args = typeid_cast<ASTExpressionList *>(function_node->arguments.get());

        ASTPtr condition_expr = args->children.at(0);
        ASTPtr then_expr = args->children.at(1);
        ASTPtr else_expr = args->children.at(2);


        bool condition;
        if (tryExtractConstValueFromCondition(condition_expr, condition))
        {
            ASTPtr replace_ast = condition ? then_expr : else_expr;
            ASTPtr child_copy = child;
            String replace_alias = replace_ast->tryGetAlias();
            String if_alias = child->tryGetAlias();

            if (replace_alias.empty())
            {
                replace_ast->setAlias(if_alias);
                child = replace_ast;
            }
            else
            {
                /// Only copy of one node is required here.
                /// But IAST has only method for deep copy of subtree.
                /// This can be a reason of performance degradation in case of deep queries.
                ASTPtr replace_ast_deep_copy = replace_ast->clone();
                replace_ast_deep_copy->setAlias(if_alias);
                child = replace_ast_deep_copy;
            }

            if (!if_alias.empty())
            {
                auto alias_it = aliases.find(if_alias);
                if (alias_it != aliases.end() && alias_it->second.get() == child_copy.get())
                    alias_it->second = child;
            }
        }
    }
603
}
604 605 606

void ExpressionAnalyzer::analyzeAggregation()
{
F
f1yegor 已提交
607 608 609
    /** Find aggregation keys (aggregation_keys), information about aggregate functions (aggregate_descriptions),
     *  as well as a set of columns obtained after the aggregation, if any,
     *  or after all the actions that are usually performed before aggregation (aggregated_columns).
610
     *
F
f1yegor 已提交
611
     * Everything below (compiling temporary ExpressionActions) - only for the purpose of query analysis (type output).
612 613 614 615 616
     */

    if (select_query && (select_query->group_expression_list || select_query->having_expression))
        has_aggregation = true;

617
    ExpressionActionsPtr temp_actions = std::make_shared<ExpressionActions>(source_columns, settings);
618 619 620 621 622

    if (select_query && select_query->array_join_expression_list())
    {
        getRootActions(select_query->array_join_expression_list(), true, false, temp_actions);
        addMultipleArrayJoinAction(temp_actions);
623
        array_join_columns = temp_actions->getSampleBlock().getNamesAndTypesList();
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
    }

    if (select_query)
    {
        const ASTTablesInSelectQueryElement * join = select_query->join();
        if (join)
        {
            if (static_cast<const ASTTableJoin &>(*join->table_join).using_expression_list)
                getRootActions(static_cast<const ASTTableJoin &>(*join->table_join).using_expression_list, true, false, temp_actions);

            addJoinAction(temp_actions, true);
        }
    }

    getAggregates(ast, temp_actions);

    if (has_aggregation)
    {
        assertSelect();

        /// Find out aggregation keys.
        if (select_query->group_expression_list)
        {
            NameSet unique_keys;
            ASTs & group_asts = select_query->group_expression_list->children;
            for (ssize_t i = 0; i < ssize_t(group_asts.size()); ++i)
            {
                ssize_t size = group_asts.size();
                getRootActions(group_asts[i], true, false, temp_actions);

                const auto & column_name = group_asts[i]->getColumnName();
                const auto & block = temp_actions->getSampleBlock();

                if (!block.has(column_name))
                    throw Exception("Unknown identifier (in GROUP BY): " + column_name, ErrorCodes::UNKNOWN_IDENTIFIER);

                const auto & col = block.getByName(column_name);

                /// Constant expressions have non-null column pointer at this stage.
                if (const auto is_constexpr = col.column)
                {
                    /// But don't remove last key column if no aggregate functions, otherwise aggregation will not work.
                    if (!aggregate_descriptions.empty() || size > 1)
                    {
                        if (i + 1 < static_cast<ssize_t>(size))
                            group_asts[i] = std::move(group_asts.back());

                        group_asts.pop_back();

                        --i;
                        continue;
                    }
                }

678
                NameAndTypePair key{column_name, col.type};
679 680 681 682 683

                /// Aggregation keys are uniqued.
                if (!unique_keys.count(key.name))
                {
                    unique_keys.insert(key.name);
684
                    aggregation_keys.push_back(key);
685 686

                    /// Key is no longer needed, therefore we can save a little by moving it.
687
                    aggregated_columns.push_back(std::move(key));
688 689 690 691 692 693
                }
            }

            if (group_asts.empty())
            {
                select_query->group_expression_list = nullptr;
694
                has_aggregation = select_query->having_expression || aggregate_descriptions.size();
695 696 697 698 699 700
            }
        }

        for (size_t i = 0; i < aggregate_descriptions.size(); ++i)
        {
            AggregateDescription & desc = aggregate_descriptions[i];
701
            aggregated_columns.emplace_back(desc.column_name, desc.function->getReturnType());
702 703
        }
    }
704 705 706 707
    else
    {
        aggregated_columns = temp_actions->getSampleBlock().getNamesAndTypesList();
    }
708 709 710
}


711 712
void ExpressionAnalyzer::initGlobalSubqueriesAndExternalTables()
{
F
f1yegor 已提交
713
    /// Adds existing external tables (not subqueries) to the external_tables dictionary.
714
    findExternalTables(ast);
715

F
f1yegor 已提交
716
    /// Converts GLOBAL subqueries to external tables; Puts them into the external_tables dictionary: name -> StoragePtr.
717
    initGlobalSubqueries(ast);
718 719 720 721 722
}


void ExpressionAnalyzer::initGlobalSubqueries(ASTPtr & ast)
{
F
f1yegor 已提交
723
    /// Recursive calls. We do not go into subqueries.
724 725 726 727 728

    for (auto & child : ast->children)
        if (!typeid_cast<ASTSelectQuery *>(child.get()))
            initGlobalSubqueries(child);

F
f1yegor 已提交
729
    /// Bottom-up actions.
730 731 732

    if (ASTFunction * node = typeid_cast<ASTFunction *>(ast.get()))
    {
F
f1yegor 已提交
733
        /// For GLOBAL IN.
734 735 736 737 738
        if (do_global && (node->name == "globalIn" || node->name == "globalNotIn"))
            addExternalStorage(node->arguments->children.at(1));
    }
    else if (ASTTablesInSelectQueryElement * node = typeid_cast<ASTTablesInSelectQueryElement *>(ast.get()))
    {
F
f1yegor 已提交
739
        /// For GLOBAL JOIN.
740 741 742 743
        if (do_global && node->table_join
            && static_cast<const ASTTableJoin &>(*node->table_join).locality == ASTTableJoin::Locality::Global)
            addExternalStorage(node->table_expression);
    }
744 745 746 747 748
}


void ExpressionAnalyzer::findExternalTables(ASTPtr & ast)
{
F
f1yegor 已提交
749
    /// Traverse from the bottom. Intentionally go into subqueries.
750 751
    for (auto & child : ast->children)
        findExternalTables(child);
752

F
f1yegor 已提交
753
    /// If table type identifier
754
    StoragePtr external_storage;
755

756 757 758 759
    if (ASTIdentifier * node = typeid_cast<ASTIdentifier *>(ast.get()))
        if (node->kind == ASTIdentifier::Table)
            if ((external_storage = context.tryGetExternalTable(node->name)))
                external_tables[node->name] = external_storage;
760 761 762
}


763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
static std::pair<String, String> getDatabaseAndTableNameFromIdentifier(const ASTIdentifier & identifier)
{
    std::pair<String, String> res;
    res.second = identifier.name;
    if (!identifier.children.empty())
    {
        if (identifier.children.size() != 2)
            throw Exception("Qualified table name could have only two components", ErrorCodes::LOGICAL_ERROR);

        res.first = typeid_cast<const ASTIdentifier &>(*identifier.children[0]).name;
        res.second = typeid_cast<const ASTIdentifier &>(*identifier.children[1]).name;
    }
    return res;
}


779
static std::shared_ptr<InterpreterSelectWithUnionQuery> interpretSubquery(
780
    const ASTPtr & subquery_or_table_name, const Context & context, size_t subquery_depth, const Names & required_source_columns, ASTPtr select_expression_list = nullptr)
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
{
    /// Subquery or table name. The name of the table is similar to the subquery `SELECT * FROM t`.
    const ASTSubquery * subquery = typeid_cast<const ASTSubquery *>(subquery_or_table_name.get());
    const ASTIdentifier * table = typeid_cast<const ASTIdentifier *>(subquery_or_table_name.get());

    if (!subquery && !table)
        throw Exception("IN/JOIN supports only SELECT subqueries.", ErrorCodes::BAD_ARGUMENTS);

    /** The subquery in the IN / JOIN section does not have any restrictions on the maximum size of the result.
      * Because the result of this query is not the result of the entire query.
      * Constraints work instead
      *  max_rows_in_set, max_bytes_in_set, set_overflow_mode,
      *  max_rows_in_join, max_bytes_in_join, join_overflow_mode,
      *  which are checked separately (in the Set, Join objects).
      */
    Context subquery_context = context;
    Settings subquery_settings = context.getSettings();
798 799
    subquery_settings.max_result_rows = 0;
    subquery_settings.max_result_bytes = 0;
800 801 802 803 804 805 806 807
    /// The calculation of `extremes` does not make sense and is not necessary (if you do it, then the `extremes` of the subquery can be taken instead of the whole query).
    subquery_settings.extremes = 0;
    subquery_context.setSettings(subquery_settings);

    ASTPtr query;
    if (table)
    {
        /// create ASTSelectQuery for "SELECT * FROM table" as if written by hand
808 809 810 811 812
        const auto select_with_union_query = std::make_shared<ASTSelectWithUnionQuery>();
        query = select_with_union_query;

        select_with_union_query->list_of_selects = std::make_shared<ASTExpressionList>();

813
        const auto select_query = std::make_shared<ASTSelectQuery>();
814
        select_with_union_query->list_of_selects->children.push_back(select_query);
815 816 817

        auto database_table = getDatabaseAndTableNameFromIdentifier(*table);

818 819 820
        if (!select_expression_list)
        {
            select_expression_list = std::make_shared<ASTExpressionList>();
821

822 823 824 825 826 827 828 829 830 831 832 833
            /// get columns list for target table
            const auto & storage = context.getTable(database_table.first, database_table.second);
            const auto & columns = storage->getColumns().ordinary;
            select_expression_list->children.reserve(columns.size());

            /// manually substitute column names in place of asterisk
            for (const auto & column : columns)
                select_expression_list->children.emplace_back(std::make_shared<ASTIdentifier>(column.name));
        }

        select_query->select_expression_list = std::move(select_expression_list);
        select_query->children.emplace_back(select_query->select_expression_list);
834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
        select_query->replaceDatabaseAndTable(database_table.first, database_table.second);
    }
    else
    {
        query = subquery->children.at(0);

        /** Columns with the same name can be specified in a subquery. For example, SELECT x, x FROM t
          * This is bad, because the result of such a query can not be saved to the table, because the table can not have the same name columns.
          * Saving to the table is required for GLOBAL subqueries.
          *
          * To avoid this situation, we will rename the same columns.
          */

        std::set<std::string> all_column_names;
        std::set<std::string> assigned_column_names;

850
        if (ASTSelectWithUnionQuery * select_with_union = typeid_cast<ASTSelectWithUnionQuery *>(query.get()))
851
        {
852
            if (ASTSelectQuery * select = typeid_cast<ASTSelectQuery *>(select_with_union->list_of_selects->children.at(0).get()))
853
            {
854 855
                for (auto & expr : select->select_expression_list->children)
                    all_column_names.insert(expr->getAliasOrColumnName());
856

857
                for (auto & expr : select->select_expression_list->children)
858
                {
859 860 861 862 863 864 865
                    auto name = expr->getAliasOrColumnName();

                    if (!assigned_column_names.insert(name).second)
                    {
                        size_t i = 1;
                        while (all_column_names.end() != all_column_names.find(name + "_" + toString(i)))
                            ++i;
866

867 868 869
                        name = name + "_" + toString(i);
                        expr = expr->clone();   /// Cancels fuse of the same expressions in the tree.
                        expr->setAlias(name);
870

871 872 873
                        all_column_names.insert(name);
                        assigned_column_names.insert(name);
                    }
874 875 876 877 878
                }
            }
        }
    }

879 880
    return std::make_shared<InterpreterSelectWithUnionQuery>(
        query, subquery_context, required_source_columns, QueryProcessingStage::Complete, subquery_depth + 1);
881
}
882 883


884
void ExpressionAnalyzer::addExternalStorage(ASTPtr & subquery_or_table_name_or_table_expression)
885
{
F
f1yegor 已提交
886
    /// With nondistributed queries, creating temporary tables does not make sense.
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
    if (!(storage && storage->isRemote()))
        return;

    ASTPtr subquery;
    ASTPtr table_name;
    ASTPtr subquery_or_table_name;

    if (typeid_cast<const ASTIdentifier *>(subquery_or_table_name_or_table_expression.get()))
    {
        table_name = subquery_or_table_name_or_table_expression;
        subquery_or_table_name = table_name;
    }
    else if (auto ast_table_expr = typeid_cast<const ASTTableExpression *>(subquery_or_table_name_or_table_expression.get()))
    {
        if (ast_table_expr->database_and_table_name)
        {
            table_name = ast_table_expr->database_and_table_name;
            subquery_or_table_name = table_name;
        }
        else if (ast_table_expr->subquery)
        {
            subquery = ast_table_expr->subquery;
            subquery_or_table_name = subquery;
        }
    }
    else if (typeid_cast<const ASTSubquery *>(subquery_or_table_name_or_table_expression.get()))
    {
        subquery = subquery_or_table_name_or_table_expression;
        subquery_or_table_name = subquery;
    }

    if (!subquery_or_table_name)
        throw Exception("Logical error: unknown AST element passed to ExpressionAnalyzer::addExternalStorage method", ErrorCodes::LOGICAL_ERROR);

    if (table_name)
    {
F
f1yegor 已提交
923
        /// If this is already an external table, you do not need to add anything. Just remember its presence.
924 925 926 927
        if (external_tables.end() != external_tables.find(static_cast<const ASTIdentifier &>(*table_name).name))
            return;
    }

F
f1yegor 已提交
928
    /// Generate the name for the external table.
929 930 931 932 933 934 935 936 937 938
    String external_table_name = "_data" + toString(external_table_id);
    while (external_tables.count(external_table_name))
    {
        ++external_table_id;
        external_table_name = "_data" + toString(external_table_id);
    }

    auto interpreter = interpretSubquery(subquery_or_table_name, context, subquery_depth, {});

    Block sample = interpreter->getSampleBlock();
939
    NamesAndTypesList columns = sample.getNamesAndTypesList();
940

941
    StoragePtr external_storage = StorageMemory::create(external_table_name, ColumnsDescription{columns});
942
    external_storage->startup();
943

944 945 946 947 948
    /** We replace the subquery with the name of the temporary table.
        * It is in this form, the request will go to the remote server.
        * This temporary table will go to the remote server, and on its side,
        *  instead of doing a subquery, you just need to read it.
        */
949

A
Alexey Milovidov 已提交
950
    auto database_and_table_name = std::make_shared<ASTIdentifier>(external_table_name, ASTIdentifier::Table);
951

952
    if (auto ast_table_expr = typeid_cast<ASTTableExpression *>(subquery_or_table_name_or_table_expression.get()))
953
    {
954 955
        ast_table_expr->subquery.reset();
        ast_table_expr->database_and_table_name = database_and_table_name;
956

957 958
        ast_table_expr->children.clear();
        ast_table_expr->children.emplace_back(database_and_table_name);
959 960
    }
    else
961
        subquery_or_table_name_or_table_expression = database_and_table_name;
962 963 964 965 966

    external_tables[external_table_name] = external_storage;
    subqueries_for_sets[external_table_name].source = interpreter->execute().in;
    subqueries_for_sets[external_table_name].table = external_storage;

F
f1yegor 已提交
967 968 969 970
    /** NOTE If it was written IN tmp_table - the existing temporary (but not external) table,
      *  then a new temporary table will be created (for example, _data1),
      *  and the data will then be copied to it.
      * Maybe this can be avoided.
971
      */
972 973 974
}


975
static NamesAndTypesList::iterator findColumn(const String & name, NamesAndTypesList & cols)
976
{
977
    return std::find_if(cols.begin(), cols.end(),
978
        [&](const NamesAndTypesList::value_type & val) { return val.name == name; });
979 980 981
}


F
f1yegor 已提交
982 983
/// ignore_levels - aliases in how many upper levels of the subtree should be ignored.
/// For example, with ignore_levels=1 ast can not be put in the dictionary, but its children can.
984
void ExpressionAnalyzer::addASTAliases(ASTPtr & ast, int ignore_levels)
985
{
F
f1yegor 已提交
986
    /// Bottom-up traversal. We do not go into subqueries.
987 988 989 990
    for (auto & child : ast->children)
    {
        int new_ignore_levels = std::max(0, ignore_levels - 1);

F
f1yegor 已提交
991 992
        /// The top-level aliases in the ARRAY JOIN section have a special meaning, we will not add them
        ///  (skip the expression list itself and its children).
993 994 995
        if (typeid_cast<ASTArrayJoin *>(ast.get()))
            new_ignore_levels = 3;

996
        /// Don't descent into table functions and subqueries.
997
        if (!typeid_cast<ASTTableExpression *>(child.get())
998
            && !typeid_cast<ASTSelectWithUnionQuery *>(child.get()))
999 1000 1001 1002 1003 1004 1005 1006 1007 1008
            addASTAliases(child, new_ignore_levels);
    }

    if (ignore_levels > 0)
        return;

    String alias = ast->tryGetAlias();
    if (!alias.empty())
    {
        if (aliases.count(alias) && ast->getTreeHash() != aliases[alias]->getTreeHash())
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
        {
            std::stringstream message;
            message << "Different expressions with the same alias " << backQuoteIfNeed(alias) << ":\n";
            formatAST(*ast, message, false, true);
            message << "\nand\n";
            formatAST(*aliases[alias], message, false, true);
            message << "\n";

            throw Exception(message.str(), ErrorCodes::MULTIPLE_EXPRESSIONS_FOR_ALIAS);
        }
1019 1020 1021

        aliases[alias] = ast;
    }
A
Alexey Milovidov 已提交
1022
    else if (auto subquery = typeid_cast<ASTSubquery *>(ast.get()))
A
Alexey Milovidov 已提交
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
    {
        /// Set unique aliases for all subqueries. This is needed, because content of subqueries could change after recursive analysis,
        ///  and auto-generated column names could become incorrect.

        size_t subquery_index = 1;
        while (true)
        {
            alias = "_subquery" + toString(subquery_index);
            if (!aliases.count("_subquery" + toString(subquery_index)))
                break;
            ++subquery_index;
        }

A
Alexey Milovidov 已提交
1036 1037
        subquery->setAlias(alias);
        subquery->prefer_alias_to_column_name = true;
A
Alexey Milovidov 已提交
1038 1039
        aliases[alias] = ast;
    }
1040 1041 1042
}


1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
NameToNameSetMap ExpressionAnalyzer::createRequiredResultColumnsMap(const Names & required_result_columns)
{
    NameToNameSetMap map;
    ParserExpression parser;

    for (const auto & column : required_result_columns)
    {
        /// TODO: it's better to change type of required_result_columns to ASTs
        auto expr = parseQuery(parser, column, 0);
        SetOfASTs tmp_set;
        MapOfASTs tmp_map;
        normalizeTreeImpl(expr, tmp_map, tmp_set, "", 0);
        map[expr->getColumnName()].insert(column);
    }

    return map;
}


1062 1063
void ExpressionAnalyzer::normalizeTree()
{
1064 1065 1066
    SetOfASTs tmp_set;
    MapOfASTs tmp_map;
    normalizeTreeImpl(ast, tmp_map, tmp_set, "", 0);
1067 1068 1069

    try
    {
1070
        ast->checkSize(settings.max_expanded_ast_elements);
1071 1072 1073 1074 1075 1076
    }
    catch (Exception & e)
    {
        e.addMessage("(after expansion of aliases)");
        throw;
    }
1077 1078 1079
}


F
f1yegor 已提交
1080 1081 1082
/// finished_asts - already processed vertices (and by what they replaced)
/// current_asts - vertices in the current call stack of this method
/// current_alias - the alias referencing to the ancestor of ast (the deepest ancestor with aliases)
1083
void ExpressionAnalyzer::normalizeTreeImpl(
1084 1085
    ASTPtr & ast, MapOfASTs & finished_asts, SetOfASTs & current_asts, std::string current_alias, size_t level)
{
1086
    if (level > settings.max_ast_depth)
1087
        throw Exception("Normalized AST is too deep. Maximum: "
1088
            + settings.max_ast_depth.toString(), ErrorCodes::TOO_DEEP_AST);
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102

    if (finished_asts.count(ast))
    {
        ast = finished_asts[ast];
        return;
    }

    ASTPtr initial_ast = ast;
    current_asts.insert(initial_ast.get());

    String my_alias = ast->tryGetAlias();
    if (!my_alias.empty())
        current_alias = my_alias;

F
f1yegor 已提交
1103
    /// rewrite rules that act when you go from top to bottom.
1104 1105
    bool replaced = false;

1106 1107 1108 1109
    ASTIdentifier * identifier_node = nullptr;
    ASTFunction * func_node = nullptr;

    if ((func_node = typeid_cast<ASTFunction *>(ast.get())))
1110
    {
F
f1yegor 已提交
1111
        /// `IN t` can be specified, where t is a table, which is equivalent to `IN (SELECT * FROM t)`.
1112 1113
        if (functionIsInOrGlobalInOperator(func_node->name))
            if (ASTIdentifier * right = typeid_cast<ASTIdentifier *>(func_node->arguments->children.at(1).get()))
1114 1115
                if (!aliases.count(right->name))
                    right->kind = ASTIdentifier::Table;
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135

        /// Special cases for count function.
        String func_name_lowercase = Poco::toLower(func_node->name);
        if (startsWith(func_name_lowercase, "count"))
        {
            /// Select implementation of countDistinct based on settings.
            /// Important that it is done as query rewrite. It means rewritten query
            ///  will be sent to remote servers during distributed query execution,
            ///  and on all remote servers, function implementation will be same.
            if (endsWith(func_node->name, "Distinct") && func_name_lowercase == "countdistinct")
                func_node->name = settings.count_distinct_implementation;

            /// As special case, treat count(*) as count(), not as count(list of all columns).
            if (func_name_lowercase == "count" && func_node->arguments->children.size() == 1
                && typeid_cast<const ASTAsterisk *>(func_node->arguments->children[0].get()))
            {
                func_node->arguments->children.clear();
            }
        }
    }
1136
    else if ((identifier_node = typeid_cast<ASTIdentifier *>(ast.get())))
1137
    {
1138
        if (identifier_node->kind == ASTIdentifier::Column)
1139
        {
F
f1yegor 已提交
1140
            /// If it is an alias, but not a parent alias (for constructs like "SELECT column + 1 AS column").
1141 1142
            auto it_alias = aliases.find(identifier_node->name);
            if (it_alias != aliases.end() && current_alias != identifier_node->name)
1143
            {
F
f1yegor 已提交
1144
                /// Let's replace it with the corresponding tree node.
1145
                if (current_asts.count(it_alias->second.get()))
1146
                    throw Exception("Cyclic aliases", ErrorCodes::CYCLIC_ALIASES);
1147 1148

                if (!my_alias.empty() && my_alias != it_alias->second->getAliasOrColumnName())
1149
                {
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
                    /// Avoid infinite recursion here
                    auto replace_to_identifier = typeid_cast<ASTIdentifier *>(it_alias->second.get());
                    bool is_cycle = replace_to_identifier &&
                        replace_to_identifier->kind == ASTIdentifier::Column &&
                        replace_to_identifier->name == identifier_node->name;

                    if (!is_cycle)
                    {
                        /// In a construct like "a AS b", where a is an alias, you must set alias b to the result of substituting alias a.
                        ast = it_alias->second->clone();
                        ast->setAlias(my_alias);
                        replaced = true;
                    }
1163 1164 1165
                }
                else
                {
1166 1167
                    ast = it_alias->second;
                    replaced = true;
1168 1169 1170 1171 1172 1173
                }
            }
        }
    }
    else if (ASTExpressionList * node = typeid_cast<ASTExpressionList *>(ast.get()))
    {
F
f1yegor 已提交
1174
        /// Replace * with a list of columns.
1175 1176 1177
        ASTs & asts = node->children;
        for (int i = static_cast<int>(asts.size()) - 1; i >= 0; --i)
        {
A
Alexey Milovidov 已提交
1178
            if (typeid_cast<ASTAsterisk *>(asts[i].get()))
1179 1180
            {
                ASTs all_columns;
1181 1182 1183 1184

                if (storage)
                {
                    /// If we select from a table, get only not MATERIALIZED, not ALIAS columns.
1185
                    for (const auto & name_type : storage->getColumns().ordinary)
1186 1187 1188 1189 1190 1191 1192
                        all_columns.emplace_back(std::make_shared<ASTIdentifier>(name_type.name));
                }
                else
                {
                    for (const auto & name_type : source_columns)
                        all_columns.emplace_back(std::make_shared<ASTIdentifier>(name_type.name));
                }
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213

                asts.erase(asts.begin() + i);
                asts.insert(asts.begin() + i, all_columns.begin(), all_columns.end());
            }
        }
    }
    else if (ASTTablesInSelectQueryElement * node = typeid_cast<ASTTablesInSelectQueryElement *>(ast.get()))
    {
        if (node->table_expression)
        {
            auto & database_and_table_name = static_cast<ASTTableExpression &>(*node->table_expression).database_and_table_name;
            if (database_and_table_name)
            {
                if (ASTIdentifier * right = typeid_cast<ASTIdentifier *>(database_and_table_name.get()))
                {
                    right->kind = ASTIdentifier::Table;
                }
            }
        }
    }

F
f1yegor 已提交
1214
    /// If we replace the root of the subtree, we will be called again for the new root, in case the alias is replaced by an alias.
1215 1216 1217 1218 1219 1220 1221 1222 1223
    if (replaced)
    {
        normalizeTreeImpl(ast, finished_asts, current_asts, current_alias, level + 1);
        current_asts.erase(initial_ast.get());
        current_asts.erase(ast.get());
        finished_asts[initial_ast] = ast;
        return;
    }

1224
    /// Recurring calls. Don't go into subqueries. Don't go into components of compound identifiers.
F
f1yegor 已提交
1225 1226
    /// We also do not go to the left argument of lambda expressions, so as not to replace the formal parameters
    ///  on aliases in expressions of the form 123 AS x, arrayMap(x -> 1, [2]).
1227 1228 1229

    if (func_node && func_node->name == "lambda")
    {
F
f1yegor 已提交
1230
        /// We skip the first argument. We also assume that the lambda function can not have parameters.
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
        for (size_t i = 1, size = func_node->arguments->children.size(); i < size; ++i)
        {
            auto & child = func_node->arguments->children[i];

            if (typeid_cast<const ASTSelectQuery *>(child.get())
                || typeid_cast<const ASTTableExpression *>(child.get()))
                continue;

            normalizeTreeImpl(child, finished_asts, current_asts, current_alias, level + 1);
        }
    }
1242 1243 1244
    else if (identifier_node)
    {
    }
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
    else
    {
        for (auto & child : ast->children)
        {
            if (typeid_cast<const ASTSelectQuery *>(child.get())
                || typeid_cast<const ASTTableExpression *>(child.get()))
                continue;

            normalizeTreeImpl(child, finished_asts, current_asts, current_alias, level + 1);
        }
    }

F
f1yegor 已提交
1257
    /// If the WHERE clause or HAVING consists of a single alias, the reference must be replaced not only in children, but also in where_expression and having_expression.
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
    if (ASTSelectQuery * select = typeid_cast<ASTSelectQuery *>(ast.get()))
    {
        if (select->prewhere_expression)
            normalizeTreeImpl(select->prewhere_expression, finished_asts, current_asts, current_alias, level + 1);
        if (select->where_expression)
            normalizeTreeImpl(select->where_expression, finished_asts, current_asts, current_alias, level + 1);
        if (select->having_expression)
            normalizeTreeImpl(select->having_expression, finished_asts, current_asts, current_alias, level + 1);
    }

    current_asts.erase(initial_ast.get());
    current_asts.erase(ast.get());
    finished_asts[initial_ast] = ast;
1271 1272
}

1273

1274
void ExpressionAnalyzer::addAliasColumns()
1275
{
1276 1277
    if (!select_query)
        return;
1278

1279 1280
    if (!storage)
        return;
1281

1282 1283
    const auto & aliases = storage->getColumns().aliases;
    source_columns.insert(std::end(source_columns), std::begin(aliases), std::end(aliases));
1284 1285 1286
}


1287 1288
void ExpressionAnalyzer::executeScalarSubqueries()
{
1289 1290 1291 1292 1293 1294
    if (!select_query)
        executeScalarSubqueriesImpl(ast);
    else
    {
        for (auto & child : ast->children)
        {
F
f1yegor 已提交
1295
            /// Do not go to FROM, JOIN, UNION.
1296
            if (!typeid_cast<const ASTTableExpression *>(child.get())
A
Alexey Milovidov 已提交
1297
                && !typeid_cast<const ASTSelectQuery *>(child.get()))
1298 1299 1300 1301 1302
            {
                executeScalarSubqueriesImpl(child);
            }
        }
    }
1303 1304
}

1305

1306
static ASTPtr addTypeConversion(std::unique_ptr<ASTLiteral> && ast, const String & type_name)
1307
{
A
Alexey Milovidov 已提交
1308
    auto func = std::make_shared<ASTFunction>();
1309 1310
    ASTPtr res = func;
    func->alias = ast->alias;
1311
    func->prefer_alias_to_column_name = ast->prefer_alias_to_column_name;
1312 1313
    ast->alias.clear();
    func->name = "CAST";
A
Alexey Milovidov 已提交
1314
    auto exp_list = std::make_shared<ASTExpressionList>();
1315 1316 1317
    func->arguments = exp_list;
    func->children.push_back(func->arguments);
    exp_list->children.emplace_back(ast.release());
A
Alexey Milovidov 已提交
1318
    exp_list->children.emplace_back(std::make_shared<ASTLiteral>(type_name));
1319
    return res;
1320 1321 1322
}


1323 1324
void ExpressionAnalyzer::executeScalarSubqueriesImpl(ASTPtr & ast)
{
F
f1yegor 已提交
1325 1326
    /** Replace subqueries that return exactly one row
      * ("scalar" subqueries) to the corresponding constants.
1327
      *
F
f1yegor 已提交
1328
      * If the subquery returns more than one column, it is replaced by a tuple of constants.
1329
      *
F
f1yegor 已提交
1330
      * Features
1331
      *
F
f1yegor 已提交
1332 1333 1334
      * A replacement occurs during query analysis, and not during the main runtime.
      * This means that the progress indicator will not work during the execution of these requests,
      *  and also such queries can not be aborted.
1335
      *
F
f1yegor 已提交
1336
      * But the query result can be used for the index in the table.
1337
      *
F
f1yegor 已提交
1338 1339
      * Scalar subqueries are executed on the request-initializer server.
      * The request is sent to remote servers with already substituted constants.
1340 1341 1342 1343 1344 1345
      */

    if (ASTSubquery * subquery = typeid_cast<ASTSubquery *>(ast.get()))
    {
        Context subquery_context = context;
        Settings subquery_settings = context.getSettings();
1346
        subquery_settings.max_result_rows = 1;
1347 1348 1349 1350
        subquery_settings.extremes = 0;
        subquery_context.setSettings(subquery_settings);

        ASTPtr query = subquery->children.at(0);
1351
        BlockIO res = InterpreterSelectWithUnionQuery(query, subquery_context, {}, QueryProcessingStage::Complete, subquery_depth + 1).execute();
1352 1353 1354 1355 1356 1357 1358 1359 1360

        Block block;
        try
        {
            block = res.in->read();

            if (!block)
            {
                /// Interpret subquery with empty result as Null literal
A
Alexey Milovidov 已提交
1361
                auto ast_new = std::make_unique<ASTLiteral>(Null());
1362 1363
                ast_new->setAlias(ast->tryGetAlias());
                ast = std::move(ast_new);
1364 1365 1366 1367 1368 1369 1370 1371
                return;
            }

            if (block.rows() != 1 || res.in->read())
                throw Exception("Scalar subquery returned more than one row", ErrorCodes::INCORRECT_RESULT_OF_SCALAR_SUBQUERY);
        }
        catch (const Exception & e)
        {
A
Alexey Milovidov 已提交
1372
            if (e.code() == ErrorCodes::TOO_MANY_ROWS)
1373 1374 1375 1376 1377 1378 1379 1380
                throw Exception("Scalar subquery returned more than one row", ErrorCodes::INCORRECT_RESULT_OF_SCALAR_SUBQUERY);
            else
                throw;
        }

        size_t columns = block.columns();
        if (columns == 1)
        {
A
Alexey Milovidov 已提交
1381
            auto lit = std::make_unique<ASTLiteral>((*block.safeGetByPosition(0).column)[0]);
1382
            lit->alias = subquery->alias;
1383
            lit->prefer_alias_to_column_name = subquery->prefer_alias_to_column_name;
1384 1385 1386 1387
            ast = addTypeConversion(std::move(lit), block.safeGetByPosition(0).type->getName());
        }
        else
        {
A
Alexey Milovidov 已提交
1388
            auto tuple = std::make_shared<ASTFunction>();
1389 1390 1391
            tuple->alias = subquery->alias;
            ast = tuple;
            tuple->name = "tuple";
A
Alexey Milovidov 已提交
1392
            auto exp_list = std::make_shared<ASTExpressionList>();
1393 1394 1395 1396 1397 1398 1399
            tuple->arguments = exp_list;
            tuple->children.push_back(tuple->arguments);

            exp_list->children.resize(columns);
            for (size_t i = 0; i < columns; ++i)
            {
                exp_list->children[i] = addTypeConversion(
A
Alexey Milovidov 已提交
1400
                    std::make_unique<ASTLiteral>((*block.safeGetByPosition(i).column)[0]),
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
                    block.safeGetByPosition(i).type->getName());
            }
        }
    }
    else
    {
        /** Don't descend into subqueries in FROM section.
          */
        if (!typeid_cast<ASTTableExpression *>(ast.get()))
        {
            /** Don't descend into subqueries in arguments of IN operator.
              * But if an argument is not subquery, than deeper may be scalar subqueries and we need to descend in them.
              */
            ASTFunction * func = typeid_cast<ASTFunction *>(ast.get());

1416
            if (func && functionIsInOrGlobalInOperator(func->name))
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
            {
                for (auto & child : ast->children)
                {
                    if (child != func->arguments)
                        executeScalarSubqueriesImpl(child);
                    else
                        for (size_t i = 0, size = func->arguments->children.size(); i < size; ++i)
                            if (i != 1 || !typeid_cast<ASTSubquery *>(func->arguments->children[i].get()))
                                executeScalarSubqueriesImpl(func->arguments->children[i]);
                }
            }
            else
                for (auto & child : ast->children)
                    executeScalarSubqueriesImpl(child);
        }
    }
1433 1434 1435
}


1436
void ExpressionAnalyzer::optimizeGroupBy()
1437
{
1438 1439 1440
    if (!(select_query && select_query->group_expression_list))
        return;

A
Alexey Milovidov 已提交
1441 1442 1443
    const auto is_literal = [] (const ASTPtr & ast)
    {
        return typeid_cast<const ASTLiteral *>(ast.get());
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
    };

    auto & group_exprs = select_query->group_expression_list->children;

    /// removes expression at index idx by making it last one and calling .pop_back()
    const auto remove_expr_at_index = [&group_exprs] (const size_t idx)
    {
        if (idx < group_exprs.size() - 1)
            std::swap(group_exprs[idx], group_exprs.back());

        group_exprs.pop_back();
    };

    /// iterate over each GROUP BY expression, eliminate injective function calls and literals
    for (size_t i = 0; i < group_exprs.size();)
    {
        if (const auto function = typeid_cast<ASTFunction *>(group_exprs[i].get()))
        {
            /// assert function is injective
            if (possibly_injective_function_names.count(function->name))
            {
                /// do not handle semantic errors here
                if (function->arguments->children.size() < 2)
                {
                    ++i;
                    continue;
                }

                const auto & dict_name = typeid_cast<const ASTLiteral &>(*function->arguments->children[0])
                    .value.safeGet<String>();

                const auto & dict_ptr = context.getExternalDictionaries().getDictionary(dict_name);

                const auto & attr_name = typeid_cast<const ASTLiteral &>(*function->arguments->children[1])
                    .value.safeGet<String>();

                if (!dict_ptr->isInjective(attr_name))
                {
                    ++i;
                    continue;
                }
            }
            else if (!injective_function_names.count(function->name))
            {
                ++i;
                continue;
            }

            /// copy shared pointer to args in order to ensure lifetime
            auto args_ast = function->arguments;

            /** remove function call and take a step back to ensure
              * next iteration does not skip not yet processed data
              */
            remove_expr_at_index(i);

            /// copy non-literal arguments
            std::remove_copy_if(
                std::begin(args_ast->children), std::end(args_ast->children),
                std::back_inserter(group_exprs), is_literal
            );
        }
        else if (is_literal(group_exprs[i]))
        {
            remove_expr_at_index(i);
        }
        else
        {
            /// if neither a function nor literal - advance to next expression
            ++i;
        }
    }

    if (group_exprs.empty())
    {
F
f1yegor 已提交
1519 1520 1521
        /** You can not completely remove GROUP BY. Because if there were no aggregate functions, then it turns out that there will be no aggregation.
          * Instead, leave `GROUP BY const`.
          * Next, see deleting the constants in the analyzeAggregation method.
1522 1523
          */

F
f1yegor 已提交
1524
        /// You must insert a constant that is not the name of the column in the table. Such a case is rare, but it happens.
1525 1526 1527
        UInt64 unused_column = 0;
        String unused_column_name = toString(unused_column);

1528
        while (source_columns.end() != std::find_if(source_columns.begin(), source_columns.end(),
1529
            [&unused_column_name](const NameAndTypePair & name_type) { return name_type.name == unused_column_name; }))
1530 1531 1532 1533 1534 1535
        {
            ++unused_column;
            unused_column_name = toString(unused_column);
        }

        select_query->group_expression_list = std::make_shared<ASTExpressionList>();
A
Alexey Milovidov 已提交
1536
        select_query->group_expression_list->children.emplace_back(std::make_shared<ASTLiteral>(UInt64(unused_column)));
1537
    }
1538 1539 1540
}


1541 1542
void ExpressionAnalyzer::optimizeOrderBy()
{
1543 1544
    if (!(select_query && select_query->order_expression_list))
        return;
1545

F
f1yegor 已提交
1546
    /// Make unique sorting conditions.
1547 1548
    using NameAndLocale = std::pair<String, String>;
    std::set<NameAndLocale> elems_set;
1549

1550 1551 1552
    ASTs & elems = select_query->order_expression_list->children;
    ASTs unique_elems;
    unique_elems.reserve(elems.size());
1553

1554 1555 1556 1557
    for (const auto & elem : elems)
    {
        String name = elem->children.front()->getColumnName();
        const ASTOrderByElement & order_by_elem = typeid_cast<const ASTOrderByElement &>(*elem);
1558

1559 1560 1561
        if (elems_set.emplace(name, order_by_elem.collation ? order_by_elem.collation->getColumnName() : "").second)
            unique_elems.emplace_back(elem);
    }
1562

1563 1564
    if (unique_elems.size() < elems.size())
        elems = unique_elems;
1565 1566 1567
}


1568 1569
void ExpressionAnalyzer::optimizeLimitBy()
{
1570 1571
    if (!(select_query && select_query->limit_by_expression_list))
        return;
1572

1573
    std::set<String> elems_set;
1574

1575 1576 1577
    ASTs & elems = select_query->limit_by_expression_list->children;
    ASTs unique_elems;
    unique_elems.reserve(elems.size());
1578

1579 1580 1581 1582 1583
    for (const auto & elem : elems)
    {
        if (elems_set.emplace(elem->getColumnName()).second)
            unique_elems.emplace_back(elem);
    }
1584

1585 1586
    if (unique_elems.size() < elems.size())
        elems = unique_elems;
1587 1588 1589
}


1590
void ExpressionAnalyzer::makeSetsForIndex()
P
Pavel Kartavyy 已提交
1591
{
1592 1593 1594 1595 1596 1597 1598
    if (storage && select_query && storage->supportsIndexForIn())
    {
        if (select_query->where_expression)
            makeSetsForIndexImpl(select_query->where_expression, storage->getSampleBlock());
        if (select_query->prewhere_expression)
            makeSetsForIndexImpl(select_query->prewhere_expression, storage->getSampleBlock());
    }
P
Pavel Kartavyy 已提交
1599 1600
}

1601

1602
void ExpressionAnalyzer::tryMakeSetForIndexFromSubquery(const ASTPtr & subquery_or_table_name)
1603 1604 1605
{
    BlockIO res = interpretSubquery(subquery_or_table_name, context, subquery_depth + 1, {})->execute();

A
Alexey Milovidov 已提交
1606
    SizeLimits set_for_index_size_limits = SizeLimits(settings.max_rows_in_set, settings.max_bytes_in_set, settings.set_overflow_mode);
1607
    SetPtr set = std::make_shared<Set>(set_for_index_size_limits, true);
1608

1609
    set->setHeader(res.in->getHeader());
1610 1611 1612
    while (Block block = res.in->read())
    {
        /// If the limits have been exceeded, give up and let the default subquery processing actions take place.
A
Alexey Milovidov 已提交
1613
        if (!set->insertFromBlock(block))
1614 1615 1616
            return;
    }

1617
    prepared_sets[subquery_or_table_name->range] = std::move(set);
1618 1619 1620
}


1621
void ExpressionAnalyzer::makeSetsForIndexImpl(const ASTPtr & node, const Block & sample_block)
P
Pavel Kartavyy 已提交
1622
{
1623
    for (auto & child : node->children)
1624
    {
1625
        /// Don't descent into subqueries.
1626 1627 1628 1629 1630 1631 1632 1633 1634
        if (typeid_cast<ASTSubquery *>(child.get()))
            continue;

        /// Don't dive into lambda functions
        const ASTFunction * func = typeid_cast<const ASTFunction *>(child.get());
        if (func && func->name == "lambda")
            continue;

        makeSetsForIndexImpl(child, sample_block);
1635
    }
1636

1637
    const ASTFunction * func = typeid_cast<const ASTFunction *>(node.get());
1638
    if (func && functionIsInOperator(func->name))
1639
    {
1640
        const IAST & args = *func->arguments;
1641

1642
        if (storage && storage->mayBenefitFromIndexForIn(args.children.at(0)))
1643
        {
1644 1645
            const ASTPtr & arg = args.children.at(1);

1646
            if (!prepared_sets.count(arg->range)) /// Not already prepared.
1647
            {
1648 1649 1650
                if (typeid_cast<ASTSubquery *>(arg.get()) || typeid_cast<ASTIdentifier *>(arg.get()))
                {
                    if (settings.use_index_for_in_with_subqueries)
1651
                        tryMakeSetForIndexFromSubquery(arg);
1652 1653 1654
                }
                else
                {
1655
                    NamesAndTypesList temp_columns = source_columns;
1656
                    temp_columns.insert(temp_columns.end(), array_join_columns.begin(), array_join_columns.end());
1657
                    temp_columns.insert(temp_columns.end(), columns_added_by_join.begin(), columns_added_by_join.end());
1658
                    ExpressionActionsPtr temp_actions = std::make_shared<ExpressionActions>(temp_columns, settings);
1659
                    getRootActions(func->arguments->children.at(0), true, false, temp_actions);
1660

1661 1662 1663 1664
                    Block sample_block_with_calculated_columns = temp_actions->getSampleBlock();
                    if (sample_block_with_calculated_columns.has(args.children.at(0)->getColumnName()))
                        makeExplicitSet(func, sample_block_with_calculated_columns, true);
                }
1665 1666 1667
            }
        }
    }
P
Pavel Kartavyy 已提交
1668
}
1669

1670

1671
void ExpressionAnalyzer::makeSet(const ASTFunction * node, const Block & sample_block)
1672
{
F
f1yegor 已提交
1673 1674 1675
    /** You need to convert the right argument to a set.
      * This can be a table name, a value, a value enumeration, or a subquery.
      * The enumeration of values is parsed as a function `tuple`.
1676
      */
1677 1678
    const IAST & args = *node->arguments;
    const ASTPtr & arg = args.children.at(1);
1679

F
f1yegor 已提交
1680
    /// Already converted.
1681
    if (prepared_sets.count(arg->range))
1682 1683
        return;

F
f1yegor 已提交
1684
    /// If the subquery or table name for SELECT.
1685 1686
    const ASTIdentifier * identifier = typeid_cast<const ASTIdentifier *>(arg.get());
    if (typeid_cast<const ASTSubquery *>(arg.get()) || identifier)
1687
    {
F
f1yegor 已提交
1688
        /// We get the stream of blocks for the subquery. Create Set and put it in place of the subquery.
1689 1690
        String set_id = arg->getColumnName();

1691 1692
        /// A special case is if the name of the table is specified on the right side of the IN statement,
        ///  and the table has the type Set (a previously prepared set).
1693 1694
        if (identifier)
        {
1695 1696
            auto database_table = getDatabaseAndTableNameFromIdentifier(*identifier);
            StoragePtr table = context.tryGetTable(database_table.first, database_table.second);
1697 1698 1699

            if (table)
            {
A
Alexey Milovidov 已提交
1700
                StorageSet * storage_set = dynamic_cast<StorageSet *>(table.get());
1701 1702 1703

                if (storage_set)
                {
1704
                    prepared_sets[arg->range] = storage_set->getSet();
1705 1706 1707 1708 1709 1710 1711
                    return;
                }
            }
        }

        SubqueryForSet & subquery_for_set = subqueries_for_sets[set_id];

F
f1yegor 已提交
1712
        /// If you already created a Set with the same subquery / table.
1713 1714
        if (subquery_for_set.set)
        {
1715
            prepared_sets[arg->range] = subquery_for_set.set;
1716 1717 1718
            return;
        }

A
Alexey Milovidov 已提交
1719
        SetPtr set = std::make_shared<Set>(SizeLimits(settings.max_rows_in_set, settings.max_bytes_in_set, settings.set_overflow_mode), false);
1720

F
f1yegor 已提交
1721 1722 1723 1724
        /** The following happens for GLOBAL INs:
          * - in the addExternalStorage function, the IN (SELECT ...) subquery is replaced with IN _data1,
          *   in the subquery_for_set object, this subquery is set as source and the temporary table _data1 as the table.
          * - this function shows the expression IN_data1.
1725
          */
1726
        if (!subquery_for_set.source && (!storage || !storage->isRemote()))
1727 1728 1729
        {
            auto interpreter = interpretSubquery(arg, context, subquery_depth, {});
            subquery_for_set.source = std::make_shared<LazyBlockInputStream>(
1730
                interpreter->getSampleBlock(), [interpreter]() mutable { return interpreter->execute().in; });
1731

F
f1yegor 已提交
1732
            /** Why is LazyBlockInputStream used?
1733
              *
A
Alexey Milovidov 已提交
1734
              * The fact is that when processing a query of the form
1735
              *  SELECT ... FROM remote_test WHERE column GLOBAL IN (subquery),
F
f1yegor 已提交
1736
              *  if the distributed remote_test table contains localhost as one of the servers,
A
Alexey Milovidov 已提交
1737
              *  the query will be interpreted locally again (and not sent over TCP, as in the case of a remote server).
1738
              *
F
f1yegor 已提交
1739
              * The query execution pipeline will be:
1740
              * CreatingSets
F
f1yegor 已提交
1741
              *  subquery execution, filling the temporary table with _data1 (1)
1742
              *  CreatingSets
F
f1yegor 已提交
1743 1744
              *   reading from the table _data1, creating the set (2)
              *   read from the table subordinate to remote_test.
1745
              *
A
Alexey Milovidov 已提交
1746
              * (The second part of the pipeline under CreateSets is a reinterpretation of the query inside StorageDistributed,
F
f1yegor 已提交
1747
              *  the query differs in that the database name and tables are replaced with subordinates, and the subquery is replaced with _data1.)
1748
              *
F
f1yegor 已提交
1749 1750 1751
              * But when creating the pipeline, when creating the source (2), it will be found that the _data1 table is empty
              *  (because the query has not started yet), and empty source will be returned as the source.
              * And then, when the query is executed, an empty set will be created in step (2).
1752
              *
F
f1yegor 已提交
1753 1754
              * Therefore, we make the initialization of step (2) lazy
              *  - so that it does not occur until step (1) is completed, on which the table will be populated.
1755
              *
F
f1yegor 已提交
1756
              * Note: this solution is not very good, you need to think better.
1757 1758 1759
              */
        }

1760
        subquery_for_set.set = set;
1761
        prepared_sets[arg->range] = set;
1762 1763 1764
    }
    else
    {
F
f1yegor 已提交
1765
        /// An explicit enumeration of values in parentheses.
1766 1767
        makeExplicitSet(node, sample_block, false);
    }
P
Pavel Kartavyy 已提交
1768 1769
}

F
f1yegor 已提交
1770
/// The case of an explicit enumeration of values.
1771
void ExpressionAnalyzer::makeExplicitSet(const ASTFunction * node, const Block & sample_block, bool create_ordered_set)
P
Pavel Kartavyy 已提交
1772
{
1773
    const IAST & args = *node->arguments;
1774 1775 1776 1777

    if (args.children.size() != 2)
        throw Exception("Wrong number of arguments passed to function in", ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);

1778
    const ASTPtr & left_arg = args.children.at(0);
1779
    const ASTPtr & right_arg = args.children.at(1);
1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794

    auto getTupleTypeFromAst = [this](const ASTPtr & node) -> DataTypePtr
    {
        auto ast_function = typeid_cast<const ASTFunction *>(node.get());
        if (ast_function && ast_function->name == "tuple" && !ast_function->arguments->children.empty())
        {
            /// Won't parse all values of outer tuple.
            auto element = ast_function->arguments->children.at(0);
            std::pair<Field, DataTypePtr> value_raw = evaluateConstantExpression(element, context);
            return std::make_shared<DataTypeTuple>(DataTypes({value_raw.second}));
        }

        return evaluateConstantExpression(node, context).second;
    };

1795
    const DataTypePtr & left_arg_type = sample_block.getByName(left_arg->getColumnName()).type;
1796
    const DataTypePtr & right_arg_type = getTupleTypeFromAst(right_arg);
1797

1798 1799
    std::function<size_t(const DataTypePtr &)> getTupleDepth;
    getTupleDepth = [&getTupleDepth](const DataTypePtr & type) -> size_t
1800
    {
1801 1802
        if (auto tuple_type = typeid_cast<const DataTypeTuple *>(type.get()))
            return 1 + (tuple_type->getElements().empty() ? 0 : getTupleDepth(tuple_type->getElements().at(0)));
1803

1804 1805
        return 0;
    };
1806

1807
    size_t left_tuple_depth = getTupleDepth(left_arg_type);
1808
    size_t right_tuple_depth = getTupleDepth(right_arg_type);
1809

1810 1811 1812
    DataTypes set_element_types = {left_arg_type};
    auto left_tuple_type = typeid_cast<const DataTypeTuple *>(left_arg_type.get());
    if (left_tuple_type && left_tuple_type->getElements().size() != 1)
1813
        set_element_types = left_tuple_type->getElements();
1814 1815

    ASTPtr elements_ast = nullptr;
1816

1817 1818
    /// 1 in 1; (1, 2) in (1, 2); identity(tuple(tuple(tuple(1)))) in tuple(tuple(tuple(1))); etc.
    if (left_tuple_depth == right_tuple_depth)
1819 1820
    {
        ASTPtr exp_list = std::make_shared<ASTExpressionList>();
1821
        exp_list->children.push_back(right_arg);
1822 1823
        elements_ast = exp_list;
    }
1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839
    /// 1 in (1, 2); (1, 2) in ((1, 2), (3, 4)); etc.
    else if (left_tuple_depth + 1 == right_tuple_depth)
    {
        ASTFunction * set_func = typeid_cast<ASTFunction *>(right_arg.get());

        if (!set_func || set_func->name != "tuple")
            throw Exception("Incorrect type of 2nd argument for function " + node->name
                            + ". Must be subquery or set of elements with type " + left_arg_type->getName() + ".",
                            ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT);

        elements_ast = set_func->arguments;
    }
    else
        throw Exception("Invalid types for IN function: "
                        + left_arg_type->getName() + " and " + right_arg_type->getName() + ".",
                        ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT);
1840

A
Alexey Milovidov 已提交
1841 1842
    SetPtr set = std::make_shared<Set>(SizeLimits(settings.max_rows_in_set, settings.max_bytes_in_set, settings.set_overflow_mode), create_ordered_set);
    set->createFromAST(set_element_types, elements_ast, context);
1843
    prepared_sets[right_arg->range] = std::move(set);
1844 1845 1846
}


1847
static String getUniqueName(const Block & block, const String & prefix)
1848
{
1849 1850 1851 1852
    int i = 1;
    while (block.has(prefix + toString(i)))
        ++i;
    return prefix + toString(i);
1853 1854
}

F
f1yegor 已提交
1855 1856 1857 1858 1859
/** For getActionsImpl.
  * A stack of ExpressionActions corresponding to nested lambda expressions.
  * The new action should be added to the highest possible level.
  * For example, in the expression "select arrayMap(x -> x + column1 * column2, array1)"
  *  calculation of the product must be done outside the lambda expression (it does not depend on x), and the calculation of the sum is inside (depends on x).
A
Alexey Milovidov 已提交
1860
  */
T
Tsarkova Anastasia 已提交
1861 1862
ScopeStack::ScopeStack(const ExpressionActionsPtr & actions, const Settings & settings_)
    : settings(settings_)
A
Alexey Milovidov 已提交
1863
{
T
Tsarkova Anastasia 已提交
1864 1865 1866 1867 1868 1869 1870
    stack.emplace_back();
    stack.back().actions = actions;

    const Block & sample_block = actions->getSampleBlock();
    for (size_t i = 0, size = sample_block.columns(); i < size; ++i)
        stack.back().new_columns.insert(sample_block.getByPosition(i).name);
}
1871

T
Tsarkova Anastasia 已提交
1872 1873 1874 1875
void ScopeStack::pushLevel(const NamesAndTypesList & input_columns)
{
    stack.emplace_back();
    Level & prev = stack[stack.size() - 2];
1876

T
Tsarkova Anastasia 已提交
1877 1878
    ColumnsWithTypeAndName all_columns;
    NameSet new_names;
1879

T
Tsarkova Anastasia 已提交
1880
    for (NamesAndTypesList::const_iterator it = input_columns.begin(); it != input_columns.end(); ++it)
1881
    {
T
Tsarkova Anastasia 已提交
1882 1883 1884
        all_columns.emplace_back(nullptr, it->type, it->name);
        new_names.insert(it->name);
        stack.back().new_columns.insert(it->name);
1885 1886
    }

T
Tsarkova Anastasia 已提交
1887 1888
    const Block & prev_sample_block = prev.actions->getSampleBlock();
    for (size_t i = 0, size = prev_sample_block.columns(); i < size; ++i)
1889
    {
T
Tsarkova Anastasia 已提交
1890 1891 1892
        const ColumnWithTypeAndName & col = prev_sample_block.getByPosition(i);
        if (!new_names.count(col.name))
            all_columns.push_back(col);
1893 1894
    }

T
Tsarkova Anastasia 已提交
1895 1896
    stack.back().actions = std::make_shared<ExpressionActions>(all_columns, settings);
}
1897

T
Tsarkova Anastasia 已提交
1898 1899 1900 1901 1902
size_t ScopeStack::getColumnLevel(const std::string & name)
{
    for (int i = static_cast<int>(stack.size()) - 1; i >= 0; --i)
        if (stack[i].new_columns.count(name))
            return i;
1903

T
Tsarkova Anastasia 已提交
1904 1905
    throw Exception("Unknown identifier: " + name, ErrorCodes::UNKNOWN_IDENTIFIER);
}
1906

T
Tsarkova Anastasia 已提交
1907 1908 1909 1910 1911 1912
void ScopeStack::addAction(const ExpressionAction & action)
{
    size_t level = 0;
    Names required = action.getNeededColumns();
    for (size_t i = 0; i < required.size(); ++i)
        level = std::max(level, getColumnLevel(required[i]));
1913

T
Tsarkova Anastasia 已提交
1914 1915
    Names added;
    stack[level].actions->add(action, added);
1916

T
Tsarkova Anastasia 已提交
1917
    stack[level].new_columns.insert(added.begin(), added.end());
1918

T
Tsarkova Anastasia 已提交
1919
    for (size_t i = 0; i < added.size(); ++i)
1920
    {
T
Tsarkova Anastasia 已提交
1921 1922 1923
        const ColumnWithTypeAndName & col = stack[level].actions->getSampleBlock().getByName(added[i]);
        for (size_t j = level + 1; j < stack.size(); ++j)
            stack[j].actions->addInput(col);
1924
    }
T
Tsarkova Anastasia 已提交
1925
}
1926

T
Tsarkova Anastasia 已提交
1927 1928 1929 1930 1931 1932
ExpressionActionsPtr ScopeStack::popLevel()
{
    ExpressionActionsPtr res = stack.back().actions;
    stack.pop_back();
    return res;
}
A
Alexey Milovidov 已提交
1933

T
Tsarkova Anastasia 已提交
1934 1935 1936 1937
const Block & ScopeStack::getSampleBlock() const
{
    return stack.back().actions->getSampleBlock();
}
A
Alexey Milovidov 已提交
1938

1939
void ExpressionAnalyzer::getRootActions(const ASTPtr & ast, bool no_subqueries, bool only_consts, ExpressionActionsPtr & actions)
1940
{
1941
    ScopeStack scopes(actions, settings);
1942

T
Tsarkova Anastasia 已提交
1943 1944 1945 1946 1947
    ProjectionManipulatorPtr projection_manipulator;
    if (!isThereArrayJoin(ast) && settings.enable_conditional_computation && !only_consts)
        projection_manipulator = std::make_shared<ConditionalTree>(scopes, context);
    else
        projection_manipulator = std::make_shared<DefaultProjectionManipulator>(scopes);
1948

T
Tsarkova Anastasia 已提交
1949
    getActionsImpl(ast, no_subqueries, only_consts, scopes, projection_manipulator);
1950

1951
    actions = scopes.popLevel();
1952 1953
}

1954 1955
void ExpressionAnalyzer::getArrayJoinedColumns()
{
1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975
    if (select_query && select_query->array_join_expression_list())
    {
        ASTs & array_join_asts = select_query->array_join_expression_list()->children;
        for (const auto & ast : array_join_asts)
        {
            const String nested_table_name = ast->getColumnName();
            const String nested_table_alias = ast->getAliasOrColumnName();

            if (nested_table_alias == nested_table_name && !typeid_cast<const ASTIdentifier *>(ast.get()))
                throw Exception("No alias for non-trivial value in ARRAY JOIN: " + nested_table_name, ErrorCodes::ALIAS_REQUIRED);

            if (array_join_alias_to_name.count(nested_table_alias) || aliases.count(nested_table_alias))
                throw Exception("Duplicate alias in ARRAY JOIN: " + nested_table_alias, ErrorCodes::MULTIPLE_EXPRESSIONS_FOR_ALIAS);

            array_join_alias_to_name[nested_table_alias] = nested_table_name;
            array_join_name_to_alias[nested_table_name] = nested_table_alias;
        }

        getArrayJoinedColumnsImpl(ast);

F
f1yegor 已提交
1976 1977
        /// If the result of ARRAY JOIN is not used, it is necessary to ARRAY-JOIN any column,
        /// to get the correct number of rows.
1978 1979 1980 1981 1982 1983
        if (array_join_result_to_source.empty())
        {
            ASTPtr expr = select_query->array_join_expression_list()->children.at(0);
            String source_name = expr->getColumnName();
            String result_name = expr->getAliasOrColumnName();

F
f1yegor 已提交
1984
            /// This is an array.
1985
            if (!typeid_cast<ASTIdentifier *>(expr.get()) || findColumn(source_name, source_columns) != source_columns.end())
1986 1987 1988
            {
                array_join_result_to_source[result_name] = source_name;
            }
F
f1yegor 已提交
1989
            else /// This is a nested table.
1990 1991
            {
                bool found = false;
1992
                for (const auto & column_name_type : source_columns)
1993
                {
1994 1995
                    auto splitted = Nested::splitName(column_name_type.name);
                    if (splitted.first == source_name && !splitted.second.empty())
1996
                    {
1997
                        array_join_result_to_source[Nested::concatenateName(result_name, splitted.second)] = column_name_type.name;
1998 1999 2000 2001 2002 2003 2004 2005 2006
                        found = true;
                        break;
                    }
                }
                if (!found)
                    throw Exception("No columns in nested table " + source_name, ErrorCodes::EMPTY_NESTED_TABLE);
            }
        }
    }
2007 2008 2009
}


F
f1yegor 已提交
2010
/// Fills the array_join_result_to_source: on which columns-arrays to replicate, and how to call them after that.
2011
void ExpressionAnalyzer::getArrayJoinedColumnsImpl(const ASTPtr & ast)
2012
{
2013 2014 2015 2016 2017 2018 2019
    if (typeid_cast<ASTTablesInSelectQuery *>(ast.get()))
        return;

    if (ASTIdentifier * node = typeid_cast<ASTIdentifier *>(ast.get()))
    {
        if (node->kind == ASTIdentifier::Column)
        {
2020
            auto splitted = Nested::splitName(node->name);  /// ParsedParams, Key1
2021 2022 2023

            if (array_join_alias_to_name.count(node->name))
            {
F
f1yegor 已提交
2024
                /// ARRAY JOIN was written with an array column. Example: SELECT K1 FROM ... ARRAY JOIN ParsedParams.Key1 AS K1
2025 2026
                array_join_result_to_source[node->name] = array_join_alias_to_name[node->name];    /// K1 -> ParsedParams.Key1
            }
2027
            else if (array_join_alias_to_name.count(splitted.first) && !splitted.second.empty())
2028
            {
F
f1yegor 已提交
2029
                /// ARRAY JOIN was written with a nested table. Example: SELECT PP.KEY1 FROM ... ARRAY JOIN ParsedParams AS PP
2030
                array_join_result_to_source[node->name]    /// PP.Key1 -> ParsedParams.Key1
2031
                    = Nested::concatenateName(array_join_alias_to_name[splitted.first], splitted.second);
2032
            }
2033
            else if (array_join_name_to_alias.count(node->name))
2034
            {
2035
                /** Example: SELECT ParsedParams.Key1 FROM ... ARRAY JOIN ParsedParams.Key1 AS PP.Key1.
F
f1yegor 已提交
2036
                  * That is, the query uses the original array, replicated by itself.
2037 2038
                  */
                array_join_result_to_source[    /// PP.Key1 -> ParsedParams.Key1
2039 2040
                    array_join_name_to_alias[node->name]] = node->name;
            }
2041
            else if (array_join_name_to_alias.count(splitted.first) && !splitted.second.empty())
2042 2043 2044 2045
            {
                /** Example: SELECT ParsedParams.Key1 FROM ... ARRAY JOIN ParsedParams AS PP.
                 */
                array_join_result_to_source[    /// PP.Key1 -> ParsedParams.Key1
2046
                Nested::concatenateName(array_join_name_to_alias[splitted.first], splitted.second)] = node->name;
2047 2048 2049 2050 2051 2052 2053 2054 2055 2056
            }
        }
    }
    else
    {
        for (auto & child : ast->children)
            if (!typeid_cast<const ASTSubquery *>(child.get())
                && !typeid_cast<const ASTSelectQuery *>(child.get()))
                getArrayJoinedColumnsImpl(child);
    }
2057 2058
}

T
Tsarkova Anastasia 已提交
2059 2060
bool ExpressionAnalyzer::isThereArrayJoin(const ASTPtr & ast)
{
T
Tsarkova Anastasia 已提交
2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084
    if (typeid_cast<ASTIdentifier *>(ast.get()))
    {
        return false;
    }
    else if (ASTFunction * node = typeid_cast<ASTFunction *>(ast.get()))
    {
        if (node->name == "arrayJoin")
        {
            return true;
        }
        if (functionIsInOrGlobalInOperator(node->name))
        {
            return isThereArrayJoin(node->arguments->children.at(0));
        }
        if (node->name == "indexHint")
        {
            return false;
        }
        if (AggregateFunctionFactory::instance().isAggregateFunctionName(node->name))
        {
            return false;
        }
        for (auto & child : node->arguments->children)
        {
T
Tsarkova Anastasia 已提交
2085 2086
            if (isThereArrayJoin(child))
            {
T
Tsarkova Anastasia 已提交
2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099
                return true;
            }
        }
        return false;
    }
    else if (typeid_cast<ASTLiteral *>(ast.get()))
    {
        return false;
    }
    else
    {
        for (auto & child : ast->children)
        {
T
Tsarkova Anastasia 已提交
2100 2101
            if (isThereArrayJoin(child))
            {
T
Tsarkova Anastasia 已提交
2102 2103 2104 2105 2106 2107
                return true;
            }
        }
        return false;
    }
}
2108

2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123
void ExpressionAnalyzer::getActionsFromJoinKeys(const ASTTableJoin & table_join, bool no_subqueries, bool only_consts,
                                                ExpressionActionsPtr & actions)
{
    ScopeStack scopes(actions, settings);

    ProjectionManipulatorPtr projection_manipulator;
    if (!isThereArrayJoin(ast) && settings.enable_conditional_computation && !only_consts)
        projection_manipulator = std::make_shared<ConditionalTree>(scopes, context);
    else
        projection_manipulator = std::make_shared<DefaultProjectionManipulator>(scopes);

    if (table_join.using_expression_list)
        getActionsImpl(table_join.using_expression_list, no_subqueries, only_consts, scopes, projection_manipulator);
    else if (table_join.on_expression)
    {
2124 2125
        for (const auto & ast : join_key_asts_left)
            getActionsImpl(ast, no_subqueries, only_consts, scopes, projection_manipulator);
2126 2127 2128 2129 2130
    }

    actions = scopes.popLevel();
}

T
Tsarkova Anastasia 已提交
2131 2132
void ExpressionAnalyzer::getActionsImpl(const ASTPtr & ast, bool no_subqueries, bool only_consts, ScopeStack & actions_stack,
                                        ProjectionManipulatorPtr projection_manipulator)
2133
{
2134 2135 2136 2137 2138 2139 2140 2141 2142
    String ast_column_name;
    auto getColumnName = [&ast, &ast_column_name]()
    {
        if (ast_column_name.empty())
            ast_column_name = ast->getColumnName();

        return ast_column_name;
    };

F
f1yegor 已提交
2143
    /// If the result of the calculation already exists in the block.
2144
    if ((typeid_cast<ASTFunction *>(ast.get()) || typeid_cast<ASTLiteral *>(ast.get()))
2145
        && projection_manipulator->tryToGetFromUpperProjection(getColumnName()))
2146 2147
        return;

2148
    if (typeid_cast<ASTIdentifier *>(ast.get()))
2149
    {
2150
        if (!only_consts && !projection_manipulator->tryToGetFromUpperProjection(getColumnName()))
2151
        {
F
f1yegor 已提交
2152 2153
            /// The requested column is not in the block.
            /// If such a column exists in the table, then the user probably forgot to surround it with an aggregate function or add it to GROUP BY.
2154 2155

            bool found = false;
2156
            for (const auto & column_name_type : source_columns)
2157
                if (column_name_type.name == getColumnName())
2158 2159 2160
                    found = true;

            if (found)
2161
                throw Exception("Column " + getColumnName() + " is not under aggregate function and not in GROUP BY.",
2162 2163 2164 2165 2166
                    ErrorCodes::NOT_AN_AGGREGATE);
        }
    }
    else if (ASTFunction * node = typeid_cast<ASTFunction *>(ast.get()))
    {
2167
        if (node->name == "lambda")
2168 2169
            throw Exception("Unexpected lambda expression", ErrorCodes::UNEXPECTED_EXPRESSION);

F
f1yegor 已提交
2170
        /// Function arrayJoin.
2171
        if (node->name == "arrayJoin")
2172 2173 2174 2175 2176
        {
            if (node->arguments->children.size() != 1)
                throw Exception("arrayJoin requires exactly 1 argument", ErrorCodes::TYPE_MISMATCH);

            ASTPtr arg = node->arguments->children.at(0);
T
Tsarkova Anastasia 已提交
2177
            getActionsImpl(arg, no_subqueries, only_consts, actions_stack, projection_manipulator);
2178 2179
            if (!only_consts)
            {
2180
                String result_name = projection_manipulator->getColumnName(getColumnName());
T
Tsarkova Anastasia 已提交
2181
                actions_stack.addAction(ExpressionAction::copyColumn(projection_manipulator->getColumnName(arg->getColumnName()), result_name));
2182 2183 2184 2185 2186 2187 2188 2189
                NameSet joined_columns;
                joined_columns.insert(result_name);
                actions_stack.addAction(ExpressionAction::arrayJoin(joined_columns, false, context));
            }

            return;
        }

2190
        if (functionIsInOrGlobalInOperator(node->name))
2191
        {
2192
            if (!no_subqueries)
2193
            {
2194
                /// Let's find the type of the first argument (then getActionsImpl will be called again and will not affect anything).
T
Tsarkova Anastasia 已提交
2195 2196
                getActionsImpl(node->arguments->children.at(0), no_subqueries, only_consts, actions_stack,
                               projection_manipulator);
2197

2198 2199
                /// Transform tuple or subquery into a set.
                makeSet(node, actions_stack.getSampleBlock());
2200
            }
2201
            else
2202
            {
2203 2204 2205 2206 2207
                if (!only_consts)
                {
                    /// We are in the part of the tree that we are not going to compute. You just need to define types.
                    /// Do not subquery and create sets. We insert an arbitrary column of the correct type.
                    ColumnWithTypeAndName fake_column;
2208
                    fake_column.name = projection_manipulator->getColumnName(getColumnName());
2209
                    fake_column.type = std::make_shared<DataTypeUInt8>();
2210
                    fake_column.column = fake_column.type->createColumn();
2211
                    actions_stack.addAction(ExpressionAction::addColumn(fake_column, projection_manipulator->getProjectionSourceColumn(), false));
T
Tsarkova Anastasia 已提交
2212 2213
                    getActionsImpl(node->arguments->children.at(0), no_subqueries, only_consts, actions_stack,
                                   projection_manipulator);
2214
                }
2215 2216
                return;
            }
2217
        }
2218

2219
        /// A special function `indexHint`. Everything that is inside it is not calculated
2220
        /// (and is used only for index analysis, see KeyCondition).
2221 2222 2223
        if (node->name == "indexHint")
        {
            actions_stack.addAction(ExpressionAction::addColumn(ColumnWithTypeAndName(
T
Tsarkova Anastasia 已提交
2224
                ColumnConst::create(ColumnUInt8::create(1, 1), 1), std::make_shared<DataTypeUInt8>(),
2225
                    projection_manipulator->getColumnName(getColumnName())), projection_manipulator->getProjectionSourceColumn(), false));
2226 2227 2228 2229 2230
            return;
        }

        if (AggregateFunctionFactory::instance().isAggregateFunctionName(node->name))
            return;
2231

2232
        const FunctionBuilderPtr & function_builder = FunctionFactory::instance().get(node->name, context);
2233
        auto projection_action = getProjectionAction(node->name, actions_stack, projection_manipulator, getColumnName(), context);
2234

2235 2236 2237
        Names argument_names;
        DataTypes argument_types;
        bool arguments_present = true;
2238

2239 2240 2241
        /// If the function has an argument-lambda expression, you need to determine its type before the recursive call.
        bool has_lambda_arguments = false;

2242
        for (size_t arg = 0; arg < node->arguments->children.size(); ++arg)
2243
        {
2244
            auto & child = node->arguments->children[arg];
2245
            auto child_column_name = child->getColumnName();
2246

2247 2248
            ASTFunction * lambda = typeid_cast<ASTFunction *>(child.get());
            if (lambda && lambda->name == "lambda")
2249
            {
2250 2251 2252
                /// If the argument is a lambda expression, just remember its approximate type.
                if (lambda->arguments->children.size() != 2)
                    throw Exception("lambda requires two arguments", ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);
2253

2254
                ASTFunction * lambda_args_tuple = typeid_cast<ASTFunction *>(lambda->arguments->children.at(0).get());
2255

2256 2257
                if (!lambda_args_tuple || lambda_args_tuple->name != "tuple")
                    throw Exception("First argument of lambda must be a tuple", ErrorCodes::TYPE_MISMATCH);
2258

2259 2260 2261 2262 2263
                has_lambda_arguments = true;
                argument_types.emplace_back(std::make_shared<DataTypeFunction>(DataTypes(lambda_args_tuple->arguments->children.size())));
                /// Select the name in the next cycle.
                argument_names.emplace_back();
            }
2264
            else if (prepared_sets.count(child->range) && functionIsInOrGlobalInOperator(node->name) && arg == 1)
2265 2266 2267
            {
                ColumnWithTypeAndName column;
                column.type = std::make_shared<DataTypeSet>();
2268

2269
                const SetPtr & set = prepared_sets[child->range];
2270

2271
                /// If the argument is a set given by an enumeration of values (so, the set was already built), give it a unique name,
2272
                ///  so that sets with the same literal representation do not fuse together (they can have different types).
2273 2274 2275
                if (!set->empty())
                    column.name = getUniqueName(actions_stack.getSampleBlock(), "__set");
                else
2276
                    column.name = child_column_name;
2277

T
Tsarkova Anastasia 已提交
2278 2279
                column.name = projection_manipulator->getColumnName(column.name);

2280 2281 2282
                if (!actions_stack.getSampleBlock().has(column.name))
                {
                    column.column = ColumnSet::create(1, set);
2283

2284
                    actions_stack.addAction(ExpressionAction::addColumn(column, projection_manipulator->getProjectionSourceColumn(), false));
2285
                }
2286

2287 2288 2289 2290 2291 2292
                argument_types.push_back(column.type);
                argument_names.push_back(column.name);
            }
            else
            {
                /// If the argument is not a lambda expression, call it recursively and find out its type.
T
Tsarkova Anastasia 已提交
2293 2294 2295
                projection_action->preArgumentAction();
                getActionsImpl(child, no_subqueries, only_consts, actions_stack,
                               projection_manipulator);
2296 2297
                std::string name = projection_manipulator->getColumnName(child_column_name);
                projection_action->postArgumentAction(child_column_name);
2298 2299 2300 2301
                if (actions_stack.getSampleBlock().has(name))
                {
                    argument_types.push_back(actions_stack.getSampleBlock().getByName(name).type);
                    argument_names.push_back(name);
2302 2303 2304
                }
                else
                {
2305
                    if (only_consts)
2306
                    {
2307
                        arguments_present = false;
2308 2309 2310
                    }
                    else
                    {
T
Tsarkova Anastasia 已提交
2311
                        throw Exception("Unknown identifier: " + name + ", projection layer " + projection_manipulator->getProjectionExpression() , ErrorCodes::UNKNOWN_IDENTIFIER);
2312 2313 2314
                    }
                }
            }
2315
        }
2316

2317 2318
        if (only_consts && !arguments_present)
            return;
2319

2320 2321 2322 2323 2324 2325
        if (has_lambda_arguments && !only_consts)
        {
            function_builder->getLambdaArgumentTypes(argument_types);

            /// Call recursively for lambda expressions.
            for (size_t i = 0; i < node->arguments->children.size(); ++i)
2326
            {
2327
                ASTPtr child = node->arguments->children[i];
2328

2329 2330
                ASTFunction * lambda = typeid_cast<ASTFunction *>(child.get());
                if (lambda && lambda->name == "lambda")
2331
                {
2332 2333 2334 2335
                    const DataTypeFunction * lambda_type = typeid_cast<const DataTypeFunction *>(argument_types[i].get());
                    ASTFunction * lambda_args_tuple = typeid_cast<ASTFunction *>(lambda->arguments->children.at(0).get());
                    ASTs lambda_arg_asts = lambda_args_tuple->arguments->children;
                    NamesAndTypesList lambda_arguments;
2336

2337
                    for (size_t j = 0; j < lambda_arg_asts.size(); ++j)
2338
                    {
2339 2340 2341
                        ASTIdentifier * identifier = typeid_cast<ASTIdentifier *>(lambda_arg_asts[j].get());
                        if (!identifier)
                            throw Exception("lambda argument declarations must be identifiers", ErrorCodes::TYPE_MISMATCH);
2342

2343
                        String arg_name = identifier->name;
2344

2345 2346
                        lambda_arguments.emplace_back(arg_name, lambda_type->getArgumentTypes()[j]);
                    }
2347

T
Tsarkova Anastasia 已提交
2348
                    projection_action->preArgumentAction();
2349
                    actions_stack.pushLevel(lambda_arguments);
T
Tsarkova Anastasia 已提交
2350 2351
                    getActionsImpl(lambda->arguments->children.at(1), no_subqueries, only_consts, actions_stack,
                                   projection_manipulator);
2352
                    ExpressionActionsPtr lambda_actions = actions_stack.popLevel();
2353

T
Tsarkova Anastasia 已提交
2354
                    String result_name = projection_manipulator->getColumnName(lambda->arguments->children.at(1)->getColumnName());
2355 2356
                    lambda_actions->finalize(Names(1, result_name));
                    DataTypePtr result_type = lambda_actions->getSampleBlock().getByName(result_name).type;
2357

2358 2359
                    Names captured;
                    Names required = lambda_actions->getRequiredColumns();
2360 2361 2362
                    for (const auto & required_arg : required)
                        if (findColumn(required_arg, lambda_arguments) == lambda_arguments.end())
                            captured.push_back(required_arg);
2363

2364 2365 2366
                    /// We can not name `getColumnName()`,
                    ///  because it does not uniquely define the expression (the types of arguments can be different).
                    String lambda_name = getUniqueName(actions_stack.getSampleBlock(), "__lambda");
2367

2368 2369
                    auto function_capture = std::make_shared<FunctionCapture>(
                            lambda_actions, captured, lambda_arguments, result_type, result_name);
T
Tsarkova Anastasia 已提交
2370
                    actions_stack.addAction(ExpressionAction::applyFunction(function_capture, captured, lambda_name,
2371
                                            projection_manipulator->getProjectionSourceColumn()));
2372

2373 2374
                    argument_types[i] = std::make_shared<DataTypeFunction>(lambda_type->getArgumentTypes(), result_type);
                    argument_names[i] = lambda_name;
T
Tsarkova Anastasia 已提交
2375
                    projection_action->postArgumentAction(lambda_name);
2376 2377
                }
            }
2378
        }
2379

2380 2381
        if (only_consts)
        {
2382
            for (const auto & argument_name : argument_names)
2383
            {
2384
                if (!actions_stack.getSampleBlock().has(argument_name))
2385
                {
2386 2387
                    arguments_present = false;
                    break;
2388 2389 2390
                }
            }
        }
2391 2392

        if (arguments_present)
T
Tsarkova Anastasia 已提交
2393 2394 2395 2396 2397 2398 2399
        {
            projection_action->preCalculation();
            if (projection_action->isCalculationRequired())
            {
                actions_stack.addAction(
                    ExpressionAction::applyFunction(function_builder,
                                                    argument_names,
2400
                                                    projection_manipulator->getColumnName(getColumnName()),
2401
                                                    projection_manipulator->getProjectionSourceColumn()));
T
Tsarkova Anastasia 已提交
2402 2403
            }
        }
2404 2405 2406 2407 2408 2409
    }
    else if (ASTLiteral * node = typeid_cast<ASTLiteral *>(ast.get()))
    {
        DataTypePtr type = applyVisitor(FieldToDataType(), node->value);

        ColumnWithTypeAndName column;
A
Alexey Milovidov 已提交
2410
        column.column = type->createColumnConst(1, convertFieldToType(node->value, *type));
2411
        column.type = type;
2412
        column.name = getColumnName();
2413

2414
        actions_stack.addAction(ExpressionAction::addColumn(column, "", false));
2415
        projection_manipulator->tryToGetFromUpperProjection(column.name);
2416 2417 2418 2419
    }
    else
    {
        for (auto & child : ast->children)
A
Alexey Milovidov 已提交
2420 2421 2422 2423
        {
            /// Do not go to FROM, JOIN, UNION.
            if (!typeid_cast<const ASTTableExpression *>(child.get())
                && !typeid_cast<const ASTSelectQuery *>(child.get()))
T
Tsarkova Anastasia 已提交
2424
                getActionsImpl(child, no_subqueries, only_consts, actions_stack, projection_manipulator);
A
Alexey Milovidov 已提交
2425
        }
2426
    }
2427 2428 2429
}


2430
void ExpressionAnalyzer::getAggregates(const ASTPtr & ast, ExpressionActionsPtr & actions)
2431
{
F
f1yegor 已提交
2432
    /// There can not be aggregate functions inside the WHERE and PREWHERE.
2433 2434 2435 2436 2437 2438
    if (select_query && (ast.get() == select_query->where_expression.get() || ast.get() == select_query->prewhere_expression.get()))
    {
        assertNoAggregates(ast, "in WHERE or PREWHERE");
        return;
    }

F
f1yegor 已提交
2439
    /// If we are not analyzing a SELECT query, but a separate expression, then there can not be aggregate functions in it.
2440 2441 2442 2443 2444 2445 2446
    if (!select_query)
    {
        assertNoAggregates(ast, "in wrong place");
        return;
    }

    const ASTFunction * node = typeid_cast<const ASTFunction *>(ast.get());
2447
    if (node && AggregateFunctionFactory::instance().isAggregateFunctionName(node->name))
2448 2449 2450 2451 2452
    {
        has_aggregation = true;
        AggregateDescription aggregate;
        aggregate.column_name = node->getColumnName();

F
f1yegor 已提交
2453
        /// Make unique aggregate functions.
2454 2455 2456 2457 2458 2459 2460 2461 2462 2463
        for (size_t i = 0; i < aggregate_descriptions.size(); ++i)
            if (aggregate_descriptions[i].column_name == aggregate.column_name)
                return;

        const ASTs & arguments = node->arguments->children;
        aggregate.argument_names.resize(arguments.size());
        DataTypes types(arguments.size());

        for (size_t i = 0; i < arguments.size(); ++i)
        {
F
f1yegor 已提交
2464
            /// There can not be other aggregate functions within the aggregate functions.
2465 2466 2467 2468 2469 2470 2471 2472
            assertNoAggregates(arguments[i], "inside another aggregate function");

            getRootActions(arguments[i], true, false, actions);
            const std::string & name = arguments[i]->getColumnName();
            types[i] = actions->getSampleBlock().getByName(name).type;
            aggregate.argument_names[i] = name;
        }

2473 2474
        aggregate.parameters = (node->parameters) ? getAggregateFunctionParametersArray(node->parameters) : Array();
        aggregate.function = AggregateFunctionFactory::instance().get(node->name, types, aggregate.parameters);
2475 2476 2477 2478 2479 2480 2481 2482 2483 2484

        aggregate_descriptions.push_back(aggregate);
    }
    else
    {
        for (const auto & child : ast->children)
            if (!typeid_cast<const ASTSubquery *>(child.get())
                && !typeid_cast<const ASTSelectQuery *>(child.get()))
                getAggregates(child, actions);
    }
2485 2486
}

2487 2488 2489

void ExpressionAnalyzer::assertNoAggregates(const ASTPtr & ast, const char * description)
{
2490
    const ASTFunction * node = typeid_cast<const ASTFunction *>(ast.get());
2491

2492
    if (node && AggregateFunctionFactory::instance().isAggregateFunctionName(node->name))
2493 2494
        throw Exception("Aggregate function " + node->getColumnName()
            + " is found " + String(description) + " in query", ErrorCodes::ILLEGAL_AGGREGATION);
2495

2496 2497 2498 2499
    for (const auto & child : ast->children)
        if (!typeid_cast<const ASTSubquery *>(child.get())
            && !typeid_cast<const ASTSelectQuery *>(child.get()))
            assertNoAggregates(child, description);
2500 2501 2502
}


2503
void ExpressionAnalyzer::assertSelect() const
2504
{
2505 2506
    if (!select_query)
        throw Exception("Not a select query", ErrorCodes::LOGICAL_ERROR);
2507
}
2508

2509
void ExpressionAnalyzer::assertAggregation() const
2510
{
2511 2512
    if (!has_aggregation)
        throw Exception("No aggregation", ErrorCodes::LOGICAL_ERROR);
2513
}
2514

2515
void ExpressionAnalyzer::initChain(ExpressionActionsChain & chain, const NamesAndTypesList & columns) const
2516
{
2517 2518 2519 2520 2521
    if (chain.steps.empty())
    {
        chain.settings = settings;
        chain.steps.emplace_back(std::make_shared<ExpressionActions>(columns, settings));
    }
2522
}
2523

2524
/// "Big" ARRAY JOIN.
2525
void ExpressionAnalyzer::addMultipleArrayJoinAction(ExpressionActionsPtr & actions) const
2526
{
2527 2528 2529 2530 2531 2532
    NameSet result_columns;
    for (const auto & result_source : array_join_result_to_source)
    {
        /// Assign new names to columns, if needed.
        if (result_source.first != result_source.second)
            actions->add(ExpressionAction::copyColumn(result_source.second, result_source.first));
2533

F
f1yegor 已提交
2534
        /// Make ARRAY JOIN (replace arrays with their insides) for the columns in these new names.
2535 2536
        result_columns.insert(result_source.first);
    }
2537

2538
    actions->add(ExpressionAction::arrayJoin(result_columns, select_query->array_join_is_left(), context));
2539 2540
}

2541
bool ExpressionAnalyzer::appendArrayJoin(ExpressionActionsChain & chain, bool only_types)
2542
{
2543
    assertSelect();
2544

2545 2546
    if (!select_query->array_join_expression_list())
        return false;
2547

2548
    initChain(chain, source_columns);
2549
    ExpressionActionsChain::Step & step = chain.steps.back();
2550

2551
    getRootActions(select_query->array_join_expression_list(), only_types, false, step.actions);
2552

2553
    addMultipleArrayJoinAction(step.actions);
2554

2555
    return true;
2556 2557
}

2558
void ExpressionAnalyzer::addJoinAction(ExpressionActionsPtr & actions, bool only_types) const
2559
{
2560
    if (only_types)
2561
        actions->add(ExpressionAction::ordinaryJoin(nullptr, join_key_names_left, columns_added_by_join));
2562 2563 2564
    else
        for (auto & subquery_for_set : subqueries_for_sets)
            if (subquery_for_set.second.join)
2565
                actions->add(ExpressionAction::ordinaryJoin(subquery_for_set.second.join, join_key_names_left, columns_added_by_join));
2566 2567 2568 2569
}

bool ExpressionAnalyzer::appendJoin(ExpressionActionsChain & chain, bool only_types)
{
2570 2571 2572 2573 2574
    assertSelect();

    if (!select_query->join())
        return false;

2575
    initChain(chain, source_columns);
2576 2577
    ExpressionActionsChain::Step & step = chain.steps.back();

2578 2579 2580 2581
    const auto & join_element = static_cast<const ASTTablesInSelectQueryElement &>(*select_query->join());
    const auto & join_params = static_cast<const ASTTableJoin &>(*join_element.table_join);
    const auto & table_to_join = static_cast<const ASTTableExpression &>(*join_element.table_expression);
    const auto joined_table_name = getTableNameWithAliasFromTableExpression(table_to_join, context);
2582

2583
    getActionsFromJoinKeys(join_params, only_types, false, step.actions);
2584

F
f1yegor 已提交
2585
    /// Two JOINs are not supported with the same subquery, but different USINGs.
A
Alexey Milovidov 已提交
2586
    auto join_hash = join_element.getTreeHash();
2587

A
Alexey Milovidov 已提交
2588
    SubqueryForSet & subquery_for_set = subqueries_for_sets[toString(join_hash.first) + "_" + toString(join_hash.second)];
2589

F
f1yegor 已提交
2590 2591
    /// Special case - if table name is specified on the right of JOIN, then the table has the type Join (the previously prepared mapping).
    /// TODO This syntax does not support specifying a database name.
2592 2593
    if (table_to_join.database_and_table_name)
    {
2594
        StoragePtr table = context.tryGetTable(joined_table_name.database, joined_table_name.table);
2595 2596 2597

        if (table)
        {
A
Alexey Milovidov 已提交
2598
            StorageJoin * storage_join = dynamic_cast<StorageJoin *>(table.get());
2599 2600 2601 2602

            if (storage_join)
            {
                storage_join->assertCompatible(join_params.kind, join_params.strictness);
F
f1yegor 已提交
2603
                /// TODO Check the set of keys.
2604 2605 2606 2607 2608 2609 2610 2611 2612 2613

                JoinPtr & join = storage_join->getJoin();
                subquery_for_set.join = join;
            }
        }
    }

    if (!subquery_for_set.join)
    {
        JoinPtr join = std::make_shared<Join>(
2614
            join_key_names_left, join_key_names_right,
2615
            settings.join_use_nulls, SizeLimits(settings.max_rows_in_join, settings.max_bytes_in_join, settings.join_overflow_mode),
2616 2617 2618 2619 2620 2621
            join_params.kind, join_params.strictness);

        Names required_joined_columns(join_key_names_right.begin(), join_key_names_right.end());
        for (const auto & name_type : columns_added_by_join)
            required_joined_columns.push_back(name_type.name);

F
f1yegor 已提交
2622 2623 2624 2625
        /** For GLOBAL JOINs (in the case, for example, of the push method for executing GLOBAL subqueries), the following occurs
          * - in the addExternalStorage function, the JOIN (SELECT ...) subquery is replaced with JOIN _data1,
          *   in the subquery_for_set object this subquery is exposed as source and the temporary table _data1 as the `table`.
          * - this function shows the expression JOIN _data1.
2626 2627 2628
          */
        if (!subquery_for_set.source)
        {
2629 2630
            ASTPtr select_expression_list;

2631 2632 2633 2634 2635 2636 2637 2638 2639 2640
            auto add_aliases_to_duplicating_joined_columns = [&](const ASTPtr & expression_list)
            {
                for (const auto & name : duplicate_columns_from_joined_table)
                {
                    auto identifier = std::make_shared<ASTIdentifier>(name);
                    identifier->setAlias(joined_table_name.getQualifiedNamePrefix() + name);
                    expression_list->children.emplace_back(std::move(identifier));
                }
            };

2641 2642
            ASTPtr table;
            if (table_to_join.database_and_table_name)
2643
            {
2644
                table = table_to_join.database_and_table_name;
2645 2646 2647 2648 2649

                /// Create custom expression list with join keys from right table.
                select_expression_list = std::make_shared<ASTExpressionList>();
                for (const auto & join_right_key : join_key_asts_right)
                    select_expression_list->children.emplace_back(join_right_key);
2650 2651 2652 2653 2654 2655 2656

                for (const auto & column : columns_added_by_join)
                    if (join_key_names_right.end() == std::find(join_key_names_right.begin(),
                                                                join_key_names_right.end(), column.name))
                        select_expression_list->children.emplace_back(std::make_shared<ASTIdentifier>(column.name));

                add_aliases_to_duplicating_joined_columns(select_expression_list);
2657
            }
2658
            else
2659 2660 2661
            {
                table = table_to_join.subquery->clone();

2662
                auto * subquery = typeid_cast<ASTSubquery *>(table.get());
2663 2664 2665 2666
                if (!subquery)
                    throw Exception("Expected ASTSubquery as joined subquery.", ErrorCodes::LOGICAL_ERROR);

                const auto & query_ptr = subquery->children.at(0);
2667
                auto * select_with_union = typeid_cast<ASTSelectWithUnionQuery *>(query_ptr.get());
2668 2669 2670 2671
                if (!select_with_union)
                    throw Exception("Expected ASTSelectWithUnionQuery as joined subquery.", ErrorCodes::LOGICAL_ERROR);

                const auto & first_select = select_with_union->list_of_selects->children.at(0);
2672
                auto * select_query = typeid_cast<ASTSelectQuery *>(first_select.get());
2673 2674 2675 2676 2677 2678
                if (!select_query)
                    throw Exception("Expected ASTSelectQuery as joined subquery.", ErrorCodes::LOGICAL_ERROR);

                /// Append right join keys to subquery expression list. Duplicate expressions will be removed further.
                for (auto & expr : join_key_asts_right)
                    select_query->select_expression_list->children.emplace_back(expr);
2679 2680

                add_aliases_to_duplicating_joined_columns(select_query->select_expression_list);
2681
            }
2682

2683
            auto interpreter = interpretSubquery(table, context, subquery_depth, required_joined_columns, select_expression_list);
2684 2685 2686
            subquery_for_set.source = std::make_shared<LazyBlockInputStream>(
                interpreter->getSampleBlock(),
                [interpreter]() mutable { return interpreter->execute().in; });
2687 2688
        }

F
f1yegor 已提交
2689
        /// TODO You do not need to set this up when JOIN is only needed on remote servers.
2690
        subquery_for_set.join = join;
2691
        subquery_for_set.join->setSampleBlock(subquery_for_set.source->getHeader());
2692 2693 2694 2695 2696
    }

    addJoinAction(step.actions, false);

    return true;
2697 2698
}

2699

2700
bool ExpressionAnalyzer::appendWhere(ExpressionActionsChain & chain, bool only_types)
2701
{
2702
    assertSelect();
2703

2704 2705
    if (!select_query->where_expression)
        return false;
2706

2707
    initChain(chain, source_columns);
2708
    ExpressionActionsChain::Step & step = chain.steps.back();
2709

2710 2711
    step.required_output.push_back(select_query->where_expression->getColumnName());
    getRootActions(select_query->where_expression, only_types, false, step.actions);
2712

2713
    return true;
2714 2715
}

2716
bool ExpressionAnalyzer::appendGroupBy(ExpressionActionsChain & chain, bool only_types)
2717
{
2718
    assertAggregation();
2719

2720 2721
    if (!select_query->group_expression_list)
        return false;
2722

2723
    initChain(chain, source_columns);
2724
    ExpressionActionsChain::Step & step = chain.steps.back();
2725

2726 2727 2728 2729 2730 2731
    ASTs asts = select_query->group_expression_list->children;
    for (size_t i = 0; i < asts.size(); ++i)
    {
        step.required_output.push_back(asts[i]->getColumnName());
        getRootActions(asts[i], only_types, false, step.actions);
    }
2732

2733
    return true;
2734 2735
}

2736
void ExpressionAnalyzer::appendAggregateFunctionsArguments(ExpressionActionsChain & chain, bool only_types)
2737
{
2738
    assertAggregation();
2739

2740
    initChain(chain, source_columns);
2741
    ExpressionActionsChain::Step & step = chain.steps.back();
2742

2743 2744 2745 2746 2747 2748 2749
    for (size_t i = 0; i < aggregate_descriptions.size(); ++i)
    {
        for (size_t j = 0; j < aggregate_descriptions[i].argument_names.size(); ++j)
        {
            step.required_output.push_back(aggregate_descriptions[i].argument_names[j]);
        }
    }
2750

2751
    getActionsBeforeAggregation(select_query->select_expression_list, step.actions, only_types);
2752

2753 2754
    if (select_query->having_expression)
        getActionsBeforeAggregation(select_query->having_expression, step.actions, only_types);
2755

2756 2757
    if (select_query->order_expression_list)
        getActionsBeforeAggregation(select_query->order_expression_list, step.actions, only_types);
2758 2759
}

2760
bool ExpressionAnalyzer::appendHaving(ExpressionActionsChain & chain, bool only_types)
2761
{
2762
    assertAggregation();
2763

2764 2765
    if (!select_query->having_expression)
        return false;
2766

2767 2768
    initChain(chain, aggregated_columns);
    ExpressionActionsChain::Step & step = chain.steps.back();
2769

2770 2771
    step.required_output.push_back(select_query->having_expression->getColumnName());
    getRootActions(select_query->having_expression, only_types, false, step.actions);
2772

2773
    return true;
2774 2775
}

2776
void ExpressionAnalyzer::appendSelect(ExpressionActionsChain & chain, bool only_types)
2777
{
2778
    assertSelect();
2779

2780 2781
    initChain(chain, aggregated_columns);
    ExpressionActionsChain::Step & step = chain.steps.back();
2782

2783
    getRootActions(select_query->select_expression_list, only_types, false, step.actions);
2784

2785
    for (const auto & child : select_query->select_expression_list->children)
2786
        step.required_output.push_back(child->getColumnName());
2787
}
2788

2789
bool ExpressionAnalyzer::appendOrderBy(ExpressionActionsChain & chain, bool only_types)
2790
{
2791
    assertSelect();
2792

2793 2794
    if (!select_query->order_expression_list)
        return false;
2795

2796 2797
    initChain(chain, aggregated_columns);
    ExpressionActionsChain::Step & step = chain.steps.back();
2798

2799
    getRootActions(select_query->order_expression_list, only_types, false, step.actions);
2800

2801 2802 2803 2804 2805 2806 2807 2808 2809
    ASTs asts = select_query->order_expression_list->children;
    for (size_t i = 0; i < asts.size(); ++i)
    {
        ASTOrderByElement * ast = typeid_cast<ASTOrderByElement *>(asts[i].get());
        if (!ast || ast->children.size() < 1)
            throw Exception("Bad order expression AST", ErrorCodes::UNKNOWN_TYPE_OF_AST_NODE);
        ASTPtr order_expression = ast->children.at(0);
        step.required_output.push_back(order_expression->getColumnName());
    }
2810

2811
    return true;
2812 2813
}

2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831
bool ExpressionAnalyzer::appendLimitBy(ExpressionActionsChain & chain, bool only_types)
{
    assertSelect();

    if (!select_query->limit_by_expression_list)
        return false;

    initChain(chain, aggregated_columns);
    ExpressionActionsChain::Step & step = chain.steps.back();

    getRootActions(select_query->limit_by_expression_list, only_types, false, step.actions);

    for (const auto & child : select_query->limit_by_expression_list->children)
        step.required_output.push_back(child->getColumnName());

    return true;
}

A
Alexey Milovidov 已提交
2832
void ExpressionAnalyzer::appendProjectResult(ExpressionActionsChain & chain) const
2833
{
2834
    assertSelect();
2835

2836 2837
    initChain(chain, aggregated_columns);
    ExpressionActionsChain::Step & step = chain.steps.back();
2838

2839
    NamesWithAliases result_columns;
2840

2841 2842 2843
    ASTs asts = select_query->select_expression_list->children;
    for (size_t i = 0; i < asts.size(); ++i)
    {
2844 2845
        String result_name = asts[i]->getColumnName();
        if (required_result_columns.empty())
2846
        {
2847
            result_columns.emplace_back(result_name, asts[i]->getAliasOrColumnName());
2848 2849
            step.required_output.push_back(result_columns.back().second);
        }
2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861
        else
        {
            auto iter = required_result_columns.find(result_name);
            if (iter != required_result_columns.end())
            {
                for (const auto & original_name : iter->second)
                {
                    result_columns.emplace_back(result_name, original_name);
                    step.required_output.push_back(result_columns.back().second);
                }
            }
        }
2862
    }
2863

2864
    step.actions->add(ExpressionAction::project(result_columns));
2865 2866 2867
}


2868
void ExpressionAnalyzer::getActionsBeforeAggregation(const ASTPtr & ast, ExpressionActionsPtr & actions, bool no_subqueries)
2869
{
2870
    ASTFunction * node = typeid_cast<ASTFunction *>(ast.get());
2871

2872
    if (node && AggregateFunctionFactory::instance().isAggregateFunctionName(node->name))
2873 2874 2875 2876 2877
        for (auto & argument : node->arguments->children)
            getRootActions(argument, no_subqueries, false, actions);
    else
        for (auto & child : ast->children)
            getActionsBeforeAggregation(child, actions, no_subqueries);
2878 2879 2880
}


M
Merge  
Michael Kolupaev 已提交
2881
ExpressionActionsPtr ExpressionAnalyzer::getActions(bool project_result)
2882
{
2883
    ExpressionActionsPtr actions = std::make_shared<ExpressionActions>(source_columns, settings);
2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912
    NamesWithAliases result_columns;
    Names result_names;

    ASTs asts;

    if (auto node = typeid_cast<const ASTExpressionList *>(ast.get()))
        asts = node->children;
    else
        asts = ASTs(1, ast);

    for (size_t i = 0; i < asts.size(); ++i)
    {
        std::string name = asts[i]->getColumnName();
        std::string alias;
        if (project_result)
            alias = asts[i]->getAliasOrColumnName();
        else
            alias = name;
        result_columns.emplace_back(name, alias);
        result_names.push_back(alias);
        getRootActions(asts[i], false, false, actions);
    }

    if (project_result)
    {
        actions->add(ExpressionAction::project(result_columns));
    }
    else
    {
F
f1yegor 已提交
2913
        /// We will not delete the original columns.
2914
        for (const auto & column_name_type : source_columns)
2915 2916 2917 2918 2919 2920
            result_names.push_back(column_name_type.name);
    }

    actions->finalize(result_names);

    return actions;
2921 2922 2923 2924 2925
}


ExpressionActionsPtr ExpressionAnalyzer::getConstActions()
{
2926
    ExpressionActionsPtr actions = std::make_shared<ExpressionActions>(NamesAndTypesList(), settings);
2927

2928
    getRootActions(ast, true, true, actions);
2929

2930
    return actions;
2931 2932
}

2933
void ExpressionAnalyzer::getAggregateInfo(Names & key_names, AggregateDescriptions & aggregates) const
2934
{
2935 2936
    for (const auto & name_and_type : aggregation_keys)
        key_names.emplace_back(name_and_type.name);
2937

2938
    aggregates = aggregate_descriptions;
2939 2940
}

2941
void ExpressionAnalyzer::collectUsedColumns()
2942
{
F
f1yegor 已提交
2943 2944 2945
    /** Calculate which columns are required to execute the expression.
      * Then, delete all other columns from the list of available columns.
      * After execution, columns will only contain the list of columns needed to read from the table.
2946 2947 2948 2949 2950
      */

    NameSet required;
    NameSet ignored;

2951
    NameSet available_columns;
2952
    for (const auto & column : source_columns)
2953 2954
        available_columns.insert(column.name);

2955 2956 2957 2958 2959
    if (select_query && select_query->array_join_expression_list())
    {
        ASTs & expressions = select_query->array_join_expression_list()->children;
        for (size_t i = 0; i < expressions.size(); ++i)
        {
F
f1yegor 已提交
2960 2961
            /// Ignore the top-level identifiers from the ARRAY JOIN section.
            /// Then add them separately.
2962 2963 2964 2965 2966 2967
            if (typeid_cast<ASTIdentifier *>(expressions[i].get()))
            {
                ignored.insert(expressions[i]->getColumnName());
            }
            else
            {
F
f1yegor 已提交
2968
                /// Nothing needs to be ignored for expressions in ARRAY JOIN.
2969
                NameSet empty;
2970
                getRequiredSourceColumnsImpl(expressions[i], available_columns, required, empty, empty, empty);
2971 2972 2973 2974 2975 2976
            }

            ignored.insert(expressions[i]->getAliasOrColumnName());
        }
    }

F
f1yegor 已提交
2977 2978
    /** You also need to ignore the identifiers of the columns that are obtained by JOIN.
      * (Do not assume that they are required for reading from the "left" table).
2979 2980 2981 2982 2983
      */
    NameSet available_joined_columns;
    collectJoinedColumns(available_joined_columns, columns_added_by_join);

    NameSet required_joined_columns;
2984 2985 2986 2987

    for (const auto & left_key_ast : join_key_asts_left)
        getRequiredSourceColumnsImpl(left_key_ast, available_columns, required, ignored, {}, required_joined_columns);

2988
    getRequiredSourceColumnsImpl(ast, available_columns, required, ignored, available_joined_columns, required_joined_columns);
2989

2990
    for (NamesAndTypesList::iterator it = columns_added_by_join.begin(); it != columns_added_by_join.end();)
2991 2992 2993 2994 2995 2996
    {
        if (required_joined_columns.count(it->name))
            ++it;
        else
            columns_added_by_join.erase(it++);
    }
2997

F
f1yegor 已提交
2998
    /// Insert the columns required for the ARRAY JOIN calculation into the required columns list.
2999 3000 3001 3002
    NameSet array_join_sources;
    for (const auto & result_source : array_join_result_to_source)
        array_join_sources.insert(result_source.second);

3003
    for (const auto & column_name_type : source_columns)
3004 3005 3006
        if (array_join_sources.count(column_name_type.name))
            required.insert(column_name_type.name);

F
f1yegor 已提交
3007
    /// You need to read at least one column to find the number of rows.
Z
zhang2014 已提交
3008
    if (select_query && required.empty())
3009
        required.insert(ExpressionActions::getSmallestColumn(source_columns));
3010

3011
    NameSet unknown_required_source_columns = required;
3012

3013
    for (NamesAndTypesList::iterator it = source_columns.begin(); it != source_columns.end();)
3014
    {
3015
        unknown_required_source_columns.erase(it->name);
3016 3017

        if (!required.count(it->name))
3018
            source_columns.erase(it++);
3019 3020
        else
            ++it;
3021 3022
    }

3023 3024
    /// If there are virtual columns among the unknown columns. Remove them from the list of unknown and add
    /// in columns list, so that when further processing they are also considered.
3025 3026
    if (storage)
    {
3027
        for (auto it = unknown_required_source_columns.begin(); it != unknown_required_source_columns.end();)
3028 3029 3030
        {
            if (storage->hasColumn(*it))
            {
3031 3032
                source_columns.push_back(storage->getColumn(*it));
                unknown_required_source_columns.erase(it++);
3033 3034 3035 3036 3037
            }
            else
                ++it;
        }
    }
3038 3039 3040

    if (!unknown_required_source_columns.empty())
        throw Exception("Unknown identifier: " + *unknown_required_source_columns.begin(), ErrorCodes::UNKNOWN_IDENTIFIER);
3041 3042
}

3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196

void ExpressionAnalyzer::collectJoinedColumnsFromJoinOnExpr()
{
    const auto & tables = static_cast<const ASTTablesInSelectQuery &>(*select_query->tables);
    const auto * left_tables_element = static_cast<const ASTTablesInSelectQueryElement *>(tables.children.at(0).get());
    const auto * right_tables_element = select_query->join();

    if (!left_tables_element || !right_tables_element)
        return;

    const auto & table_join = static_cast<const ASTTableJoin &>(*right_tables_element->table_join);
    if (!table_join.on_expression)
        return;

    const auto & left_table_expression = static_cast<const ASTTableExpression &>(*left_tables_element->table_expression);
    const auto & right_table_expression = static_cast<const ASTTableExpression &>(*right_tables_element->table_expression);

    auto left_source_names = getTableNameWithAliasFromTableExpression(left_table_expression, context);
    auto right_source_names = getTableNameWithAliasFromTableExpression(right_table_expression, context);

    /// Stores examples of columns which are only from one table.
    struct TableBelonging
    {
        const ASTIdentifier * example_only_from_left = nullptr;
        const ASTIdentifier * example_only_from_right = nullptr;
    };

    /// Check all identifiers in ast and decide their possible table belonging.
    /// Throws if there are two identifiers definitely from different tables.
    std::function<TableBelonging(const ASTPtr &)> get_table_belonging;
    get_table_belonging = [&](const ASTPtr & ast) -> TableBelonging
    {
        auto * identifier = typeid_cast<const ASTIdentifier *>(ast.get());
        if (identifier)
        {
            if (identifier->kind == ASTIdentifier::Column)
            {
                auto left_num_components = getNumComponentsToStripInOrderToTranslateQualifiedName(*identifier, left_source_names);
                auto right_num_components = getNumComponentsToStripInOrderToTranslateQualifiedName(*identifier, right_source_names);
                if (left_num_components > right_num_components)
                    return {identifier, nullptr};
                if (left_num_components < right_num_components)
                    return {nullptr, identifier};
            }
            return {};
        }

        TableBelonging table_belonging;
        for (const auto & child : ast->children)
        {
            auto children_belonging = get_table_belonging(child);
            if (!table_belonging.example_only_from_left)
                table_belonging.example_only_from_left = children_belonging.example_only_from_left;
            if (!table_belonging.example_only_from_right)
                table_belonging.example_only_from_right = children_belonging.example_only_from_right;
        }

        if (table_belonging.example_only_from_left && table_belonging.example_only_from_right)
            throw Exception("Invalid columns in JOIN ON section. Columns "
                            + table_belonging.example_only_from_left->getAliasOrColumnName() + " and "
                            + table_belonging.example_only_from_right->getAliasOrColumnName()
                            + " are from different tables.", ErrorCodes::INVALID_JOIN_ON_EXPRESSION);

        return table_belonging;
    };

    std::function<void(ASTPtr &, const DatabaseAndTableWithAlias &)> translate_qualified_names;
    translate_qualified_names = [&](ASTPtr & ast, const DatabaseAndTableWithAlias & source_names)
    {
        auto * identifier = typeid_cast<const ASTIdentifier *>(ast.get());
        if (identifier)
        {
            if (identifier->kind == ASTIdentifier::Column)
            {
                auto num_components = getNumComponentsToStripInOrderToTranslateQualifiedName(*identifier, source_names);
                stripIdentifier(ast, num_components);
            }
            return;
        }

        for (auto & child : ast->children)
            translate_qualified_names(child, source_names);
    };

    const auto supported_syntax = " Supported syntax: JOIN ON Expr([table.]column, ...) = Expr([table.]column, ...) "
                                  "[AND Expr([table.]column, ...) = Expr([table.]column, ...) ...]";
    auto throwSyntaxException = [&](const String & msg)
    {
        throw Exception("Invalid expression for JOIN ON. " + msg + supported_syntax, ErrorCodes::INVALID_JOIN_ON_EXPRESSION);
    };

    /// For equal expression find out corresponding table for each part, translate qualified names and add asts to join keys.
    auto add_columns_from_equals_expr = [&](const ASTPtr & expr)
    {
        auto * func_equals = typeid_cast<const ASTFunction *>(expr.get());
        if (!func_equals || func_equals->name != "equals")
            throwSyntaxException("Expected equals expression, got " + queryToString(expr) + ".");

        ASTPtr left_ast = func_equals->arguments->children.at(0)->clone();
        ASTPtr right_ast = func_equals->arguments->children.at(1)->clone();

        auto left_table_belonging = get_table_belonging(left_ast);
        auto right_table_belonging = get_table_belonging(right_ast);

        bool can_be_left_part_from_left_table = left_table_belonging.example_only_from_right == nullptr;
        bool can_be_left_part_from_right_table = left_table_belonging.example_only_from_left == nullptr;
        bool can_be_right_part_from_left_table = right_table_belonging.example_only_from_right == nullptr;
        bool can_be_right_part_from_right_table = right_table_belonging.example_only_from_left == nullptr;

        auto add_join_keys = [&](ASTPtr & ast_to_left_table, ASTPtr & ast_to_right_table)
        {
            translate_qualified_names(ast_to_left_table, left_source_names);
            translate_qualified_names(ast_to_right_table, right_source_names);

            join_key_asts_left.push_back(ast_to_left_table);
            join_key_names_left.push_back(ast_to_left_table->getColumnName());
            join_key_asts_right.push_back(ast_to_right_table);
            join_key_names_right.push_back(ast_to_right_table->getAliasOrColumnName());
        };

        /// Default variant when all identifiers may be from any table.
        if (can_be_left_part_from_left_table && can_be_right_part_from_right_table)
            add_join_keys(left_ast, right_ast);
        else if (can_be_left_part_from_right_table && can_be_right_part_from_left_table)
            add_join_keys(right_ast, left_ast);
        else
        {
            auto * left_example = left_table_belonging.example_only_from_left ?
                                  left_table_belonging.example_only_from_left :
                                  left_table_belonging.example_only_from_right;

            auto * right_example = right_table_belonging.example_only_from_left ?
                                   right_table_belonging.example_only_from_left :
                                   right_table_belonging.example_only_from_right;

            auto left_name = queryToString(*left_example);
            auto right_name = queryToString(*right_example);
            auto expr_name = queryToString(expr);

            throwSyntaxException("In expression " + expr_name + " columns " + left_name + " and " + right_name
                                 + " are from the same table but from different arguments of equal function.");
        }
    };

    auto * func = typeid_cast<const ASTFunction *>(table_join.on_expression.get());
    if (func && func->name == "and")
    {
        for (const auto & expr : func->arguments->children)
            add_columns_from_equals_expr(expr);
    }
    else
        add_columns_from_equals_expr(table_join.on_expression);
}

3197
void ExpressionAnalyzer::collectJoinedColumns(NameSet & joined_columns, NamesAndTypesList & joined_columns_name_type)
3198
{
3199 3200 3201 3202 3203 3204 3205 3206
    if (!select_query)
        return;

    const ASTTablesInSelectQueryElement * node = select_query->join();

    if (!node)
        return;

3207 3208 3209
    const auto & table_join = static_cast<const ASTTableJoin &>(*node->table_join);
    const auto & table_expression = static_cast<const ASTTableExpression &>(*node->table_expression);
    auto joined_table_name = getTableNameWithAliasFromTableExpression(table_expression, context);
3210 3211 3212 3213

    Block nested_result_sample;
    if (table_expression.database_and_table_name)
    {
3214
        const auto & table = context.getTable(joined_table_name.database, joined_table_name.table);
3215 3216 3217 3218 3219
        nested_result_sample = table->getSampleBlockNonMaterialized();
    }
    else if (table_expression.subquery)
    {
        const auto & subquery = table_expression.subquery->children.at(0);
3220
        nested_result_sample = InterpreterSelectWithUnionQuery::getSampleBlock(subquery, context);
3221 3222
    }

3223
    auto add_name_to_join_keys = [](Names & join_keys, ASTs & join_asts, const String & name, const ASTPtr & ast)
3224 3225
    {
        if (join_keys.end() == std::find(join_keys.begin(), join_keys.end(), name))
3226
        {
3227
            join_keys.push_back(name);
3228 3229
            join_asts.push_back(ast);
        }
3230
        else
3231
            throw Exception("Duplicate column " + name + " in USING list", ErrorCodes::DUPLICATE_COLUMN);
3232 3233
    };

3234 3235 3236 3237 3238
    if (table_join.using_expression_list)
    {
        auto & keys = typeid_cast<ASTExpressionList &>(*table_join.using_expression_list);
        for (const auto & key : keys.children)
        {
3239 3240
            add_name_to_join_keys(join_key_names_left, join_key_asts_left, key->getColumnName(), key);
            add_name_to_join_keys(join_key_names_right, join_key_asts_right, key->getAliasOrColumnName(), key);
3241 3242 3243
        }
    }
    else if (table_join.on_expression)
3244
        collectJoinedColumnsFromJoinOnExpr();
3245

3246

3247 3248 3249
    for (const auto i : ext::range(0, nested_result_sample.columns()))
    {
        const auto & col = nested_result_sample.safeGetByPosition(i);
3250
        if (join_key_names_left.end() == std::find(join_key_names_left.begin(), join_key_names_left.end(), col.name))
3251
        {
3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263
            auto name = col.name;
            /// Change name for duplicate column form joined table.
            if (source_columns.contains(name))
            {
                duplicate_columns_from_joined_table.insert(name);
                name = joined_table_name.getQualifiedNamePrefix() + name;
            }

            if (joined_columns.count(name)) /// Duplicate columns in the subquery for JOIN do not make sense.
                continue;

            joined_columns.insert(name);
3264

3265 3266 3267
            bool make_nullable = settings.join_use_nulls && (table_join.kind == ASTTableJoin::Kind::Left ||
                                                             table_join.kind == ASTTableJoin::Kind::Full);
            joined_columns_name_type.emplace_back(name, make_nullable ? makeNullable(col.type) : col.type);
3268 3269
        }
    }
3270 3271
}

3272

3273
Names ExpressionAnalyzer::getRequiredSourceColumns() const
3274
{
3275
    return source_columns.getNames();
3276 3277
}

3278

3279 3280
void ExpressionAnalyzer::getRequiredSourceColumnsImpl(const ASTPtr & ast,
    const NameSet & available_columns, NameSet & required_source_columns, NameSet & ignored_names,
3281 3282
    const NameSet & available_joined_columns, NameSet & required_joined_columns)
{
F
f1yegor 已提交
3283
    /** Find all the identifiers in the query.
3284
      * We will use depth first search in AST.
F
f1yegor 已提交
3285 3286
      * In this case
      * - for lambda functions we will not take formal parameters;
3287 3288 3289
      * - do not go into subqueries (they have their own identifiers);
      * - there is some exception for the ARRAY JOIN clause (it has a slightly different identifiers);
      * - we put identifiers available from JOIN in required_joined_columns.
3290 3291 3292 3293 3294 3295
      */

    if (ASTIdentifier * node = typeid_cast<ASTIdentifier *>(ast.get()))
    {
        if (node->kind == ASTIdentifier::Column
            && !ignored_names.count(node->name)
3296
            && !ignored_names.count(Nested::extractTableName(node->name)))
3297
        {
3298 3299
            if (!available_joined_columns.count(node->name)
                || available_columns.count(node->name)) /// Read column from left table if has.
3300
                required_source_columns.insert(node->name);
3301 3302 3303 3304 3305 3306 3307 3308 3309
            else
                required_joined_columns.insert(node->name);
        }

        return;
    }

    if (ASTFunction * node = typeid_cast<ASTFunction *>(ast.get()))
    {
3310
        if (node->name == "lambda")
3311 3312 3313 3314 3315 3316 3317 3318 3319
        {
            if (node->arguments->children.size() != 2)
                throw Exception("lambda requires two arguments", ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);

            ASTFunction * lambda_args_tuple = typeid_cast<ASTFunction *>(node->arguments->children.at(0).get());

            if (!lambda_args_tuple || lambda_args_tuple->name != "tuple")
                throw Exception("First argument of lambda must be a tuple", ErrorCodes::TYPE_MISMATCH);

3320
            /// You do not need to add formal parameters of the lambda expression in required_source_columns.
3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335
            Names added_ignored;
            for (auto & child : lambda_args_tuple->arguments->children)
            {
                ASTIdentifier * identifier = typeid_cast<ASTIdentifier *>(child.get());
                if (!identifier)
                    throw Exception("lambda argument declarations must be identifiers", ErrorCodes::TYPE_MISMATCH);

                String & name = identifier->name;
                if (!ignored_names.count(name))
                {
                    ignored_names.insert(name);
                    added_ignored.push_back(name);
                }
            }

3336 3337
            getRequiredSourceColumnsImpl(node->arguments->children.at(1),
                available_columns, required_source_columns, ignored_names,
3338 3339 3340 3341 3342 3343 3344 3345
                available_joined_columns, required_joined_columns);

            for (size_t i = 0; i < added_ignored.size(); ++i)
                ignored_names.erase(added_ignored[i]);

            return;
        }

F
f1yegor 已提交
3346
        /// A special function `indexHint`. Everything that is inside it is not calculated
3347
        /// (and is used only for index analysis, see KeyCondition).
3348 3349 3350 3351
        if (node->name == "indexHint")
            return;
    }

F
f1yegor 已提交
3352
    /// Recursively traverses an expression.
3353 3354
    for (auto & child : ast->children)
    {
F
f1yegor 已提交
3355 3356
        /** We will not go to the ARRAY JOIN section, because we need to look at the names of non-ARRAY-JOIN columns.
          * There, `collectUsedColumns` will send us separately.
3357
          */
A
Alexey Milovidov 已提交
3358 3359
        if (!typeid_cast<const ASTSelectQuery *>(child.get())
            && !typeid_cast<const ASTArrayJoin *>(child.get())
3360 3361
            && !typeid_cast<const ASTTableExpression *>(child.get())
            && !typeid_cast<const ASTTableJoin *>(child.get()))
3362 3363
            getRequiredSourceColumnsImpl(child, available_columns, required_source_columns,
                ignored_names, available_joined_columns, required_joined_columns);
3364
    }
3365 3366
}

3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381

static bool hasArrayJoin(const ASTPtr & ast)
{
    if (const ASTFunction * function = typeid_cast<const ASTFunction *>(&*ast))
        if (function->name == "arrayJoin")
            return true;

    for (const auto & child : ast->children)
        if (!typeid_cast<ASTSelectQuery *>(child.get()) && hasArrayJoin(child))
            return true;

    return false;
}


3382
void ExpressionAnalyzer::removeUnneededColumnsFromSelectClause()
3383 3384 3385 3386
{
    if (!select_query)
        return;

3387 3388 3389 3390 3391 3392 3393
    if (required_result_columns.empty() || select_query->distinct)
        return;

    ASTs & elements = select_query->select_expression_list->children;

    elements.erase(std::remove_if(elements.begin(), elements.end(), [this](const auto & node)
    {
3394
        return !required_result_columns.count(node->getColumnName()) && !hasArrayJoin(node);
3395
    }), elements.end());
3396 3397
}

3398
}