ExpressionAnalyzer.cpp 108.5 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 10 11 12 13 14
#include <Parsers/ASTFunction.h>
#include <Parsers/ASTIdentifier.h>
#include <Parsers/ASTLiteral.h>
#include <Parsers/ASTAsterisk.h>
#include <Parsers/ASTExpressionList.h>
#include <Parsers/ASTSelectQuery.h>
#include <Parsers/ASTSubquery.h>
#include <Parsers/ASTSet.h>
#include <Parsers/ASTOrderByElement.h>
15

16 17 18 19 20 21
#include <DataTypes/DataTypeSet.h>
#include <DataTypes/DataTypeArray.h>
#include <DataTypes/DataTypeTuple.h>
#include <DataTypes/DataTypeExpression.h>
#include <DataTypes/DataTypeNested.h>
#include <DataTypes/DataTypesNumber.h>
22

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

26 27 28 29 30 31 32 33
#include <Interpreters/InterpreterSelectQuery.h>
#include <Interpreters/ExpressionAnalyzer.h>
#include <Interpreters/ExpressionActions.h>
#include <Interpreters/InJoinSubqueriesPreprocessor.h>
#include <Interpreters/LogicalExpressionsOptimizer.h>
#include <Interpreters/ExternalDictionaries.h>
#include <Interpreters/Set.h>
#include <Interpreters/Join.h>
34

35
#include <AggregateFunctions/AggregateFunctionFactory.h>
36

37 38 39 40
#include <Storages/StorageDistributed.h>
#include <Storages/StorageMemory.h>
#include <Storages/StorageSet.h>
#include <Storages/StorageJoin.h>
41

42 43
#include <DataStreams/LazyBlockInputStream.h>
#include <DataStreams/copyData.h>
44

45
#include <Dictionaries/IDictionary.h>
46

47 48
#include <Common/typeid_cast.h>
#include <Common/StringUtils.h>
49

50
#include <Parsers/formatAST.h>
51

52 53
#include <Functions/FunctionFactory.h>
#include <Functions/IFunction.h>
A
Andrey Mironov 已提交
54

55
#include <ext/range.h>
56
#include <DataTypes/DataTypeFactory.h>
57

58 59 60 61

namespace DB
{

62 63
namespace ErrorCodes
{
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
    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;
    extern const int TOO_MUCH_ROWS;
    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 PARAMETERS_TO_AGGREGATE_FUNCTIONS_MUST_BE_LITERALS;
    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;
81 82
}

83

84 85
/** Calls to these functions in the GROUP BY statement would be
  * replaced by their immediate argument.
86
  */
A
Alexey Milovidov 已提交
87 88
const std::unordered_set<String> injective_function_names
{
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
    "negate",
    "bitNot",
    "reverse",
    "reverseUTF8",
    "toString",
    "toFixedString",
    "IPv4NumToString",
    "IPv4StringToNum",
    "hex",
    "unhex",
    "bitmaskToList",
    "bitmaskToArray",
    "tuple",
    "regionToName",
    "concatAssumeInjective",
104 105
};

106 107
const std::unordered_set<String> possibly_injective_function_names
{
108 109 110 111 112 113 114 115 116 117 118 119 120
    "dictGetString",
    "dictGetUInt8",
    "dictGetUInt16",
    "dictGetUInt32",
    "dictGetUInt64",
    "dictGetInt8",
    "dictGetInt16",
    "dictGetInt32",
    "dictGetInt64",
    "dictGetFloat32",
    "dictGetFloat64",
    "dictGetDate",
    "dictGetDateTime"
121 122
};

A
Merge  
Alexey Arno 已提交
123 124 125 126
namespace
{

bool functionIsInOperator(const String & name)
127
{
128
    return name == "in" || name == "notIn";
129 130
}

A
Merge  
Alexey Arno 已提交
131
bool functionIsInOrGlobalInOperator(const String & name)
132
{
133
    return name == "in" || name == "notIn" || name == "globalIn" || name == "globalNotIn";
134 135
}

136 137
void removeDuplicateColumns(NamesAndTypesList & columns)
{
138 139 140 141 142 143 144 145
    std::set<String> names;
    for (auto it = columns.begin(); it != columns.end();)
    {
        if (names.emplace(it->name).second)
            ++it;
        else
            columns.erase(it++);
    }
146 147
}

A
Merge  
Alexey Arno 已提交
148
}
149

150 151

ExpressionAnalyzer::ExpressionAnalyzer(
152 153 154 155 156 157 158 159 160 161 162 163
    const ASTPtr & ast_,
    const Context & context_,
    StoragePtr storage_,
    const NamesAndTypesList & columns_,
    size_t subquery_depth_,
    bool do_global_)
    : ast(ast_), context(context_), settings(context.getSettings()),
    subquery_depth(subquery_depth_), columns(columns_),
    storage(storage_ ? storage_ : getTable()),
    do_global(do_global_)
{
    init();
164 165 166
}


167 168
void ExpressionAnalyzer::init()
{
169
    removeDuplicateColumns(columns);
170

171
    select_query = typeid_cast<ASTSelectQuery *>(ast.get());
172

173 174
    translateQualifiedNames();

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

F
f1yegor 已提交
179
    /// Optimizes logical expressions.
180
    LogicalExpressionsOptimizer(select_query, settings).perform();
181

F
f1yegor 已提交
182
    /// Creates a dictionary `aliases`: alias -> ASTPtr
183
    addASTAliases(ast);
184

185 186
    /// Common subexpression elimination. Rewrite rules.
    normalizeTree();
187

F
f1yegor 已提交
188
    /// ALIAS columns should not be substituted for ASTAsterisk, we will add them now, after normalizeTree.
189
    addAliasColumns();
190

F
f1yegor 已提交
191
    /// Executing scalar subqueries - replacing them with constant values.
192
    executeScalarSubqueries();
193

194 195
    /// Optimize if with constant condition after constats are substituted instead of sclalar subqueries
    optimizeIfWithConstantCondition();
196

197 198
    /// GROUP BY injective function elimination.
    optimizeGroupBy();
199

F
f1yegor 已提交
200
    /// Remove duplicate items from ORDER BY.
201
    optimizeOrderBy();
202

203 204
    // Remove duplicated elements from LIMIT BY clause.
    optimizeLimitBy();
205

206 207
    /// array_join_alias_to_name, array_join_result_to_source.
    getArrayJoinedColumns();
208

F
f1yegor 已提交
209
    /// Delete the unnecessary from `columns` list. Create `unknown_required_columns`. Form `columns_added_by_join`.
210
    collectUsedColumns();
211

F
f1yegor 已提交
212 213
    /// 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.
214
    initGlobalSubqueriesAndExternalTables();
215

216
    /// has_aggregation, aggregation_keys, aggregate_descriptions, aggregated_columns.
F
f1yegor 已提交
217 218 219 220 221 222
    /// 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.
223
    analyzeAggregation();
224 225
}

226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338

void ExpressionAnalyzer::translateQualifiedNames()
{
    String database_name;
    String table_name;
    String alias;

    if (!select_query || !select_query->tables || select_query->tables->children.empty())
        return;

    ASTTablesInSelectQueryElement & 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;

    ASTTableExpression & table_expression = static_cast<ASTTableExpression &>(*element.table_expression);

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

        alias = identifier.tryGetAlias();

        if (table_expression.database_and_table_name->children.empty())
        {
            database_name = context.getCurrentDatabase();
            table_name = identifier.name;
        }
        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);

            database_name = static_cast<const ASTIdentifier &>(*identifier.children[0]).name;
            table_name = static_cast<const ASTIdentifier &>(*identifier.children[1]).name;
        }
    }
    else if (table_expression.table_function)
    {
        alias = table_expression.table_function->tryGetAlias();
    }
    else if (table_expression.subquery)
    {
        alias = table_expression.subquery->tryGetAlias();
    }
    else
        throw Exception("Logical error: no known elements in ASTTableExpression", ErrorCodes::LOGICAL_ERROR);

    translateQualifiedNamesImpl(ast, database_name, table_name, alias);
}


void ExpressionAnalyzer::translateQualifiedNamesImpl(ASTPtr & ast, const String & database_name, const String & table_name, const String & alias)
{
    if (ASTIdentifier * ident = typeid_cast<ASTIdentifier *>(ast.get()))
    {
        if (ident->kind == ASTIdentifier::Column)
        {
            /// It is compound identifier
            if (!ast->children.empty())
            {
                size_t num_components = ast->children.size();
                size_t num_qualifiers_to_strip = 0;

                /// database.table.column
                if (!database_name.empty()
                        && num_components >= 3
                        && static_cast<const ASTIdentifier &>(*ast->children[0]).name == database_name
                        && static_cast<const ASTIdentifier &>(*ast->children[1]).name == table_name)
                {
                    num_qualifiers_to_strip = 2;
                }
                /// table.column or alias.column
                else if (num_components >= 2
                    && ((!table_name.empty() && static_cast<const ASTIdentifier &>(*ast->children[0]).name == table_name)
                        || (!alias.empty() && static_cast<const ASTIdentifier &>(*ast->children[0]).name == alias)))
                {
                    num_qualifiers_to_strip = 1;
                }

                if (num_qualifiers_to_strip)
                {
                    /// plain column
                    if (num_components - num_qualifiers_to_strip == 1)
                    {
                        String node_alias = ast->tryGetAlias();
                        ast = ast->children.back();
                        if (!node_alias.empty())
                            ast->setAlias(node_alias);
                    }
                    else
                    {
                        ast->children.erase(ast->children.begin(), ast->children.begin() + num_qualifiers_to_strip);
                    }
                }
            }
        }
    }
    else
    {
        for (auto & child : ast->children)
        {
            /// Do not go to FROM, JOIN, UNION.
            if (!typeid_cast<const ASTTableExpression *>(child.get())
                && child.get() != select_query->next_union_all.get())
            {
                translateQualifiedNamesImpl(child, database_name, table_name, alias);
            }
        }
    }
}


339 340
void ExpressionAnalyzer::optimizeIfWithConstantCondition()
{
341
    optimizeIfWithConstantConditionImpl(ast, aliases);
342 343 344 345
}

bool ExpressionAnalyzer::tryExtractConstValueFromCondition(const ASTPtr & condition, bool & value) const
{
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
    /// 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;
376 377
}

378
void ExpressionAnalyzer::optimizeIfWithConstantConditionImpl(ASTPtr & current_ast, ExpressionAnalyzer::Aliases & aliases) const
379
{
380 381 382 383 384 385 386 387 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 422 423 424 425 426 427 428 429 430
    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;
            }
        }
    }
431
}
432 433 434

void ExpressionAnalyzer::analyzeAggregation()
{
F
f1yegor 已提交
435 436 437
    /** 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).
438
     *
F
f1yegor 已提交
439
     * Everything below (compiling temporary ExpressionActions) - only for the purpose of query analysis (type output).
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
     */

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

    ExpressionActionsPtr temp_actions = std::make_shared<ExpressionActions>(columns, settings);

    if (select_query && select_query->array_join_expression_list())
    {
        getRootActions(select_query->array_join_expression_list(), true, false, temp_actions);
        addMultipleArrayJoinAction(temp_actions);
    }

    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;
                    }
                }

                NameAndTypePair key{column_name, col.type};

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

                    /// Key is no longer needed, therefore we can save a little by moving it.
                    aggregated_columns.push_back(std::move(key));
                }
            }

            if (group_asts.empty())
            {
                select_query->group_expression_list = nullptr;
                has_aggregation = select_query->having_expression || aggregate_descriptions.size();
            }
        }

        for (size_t i = 0; i < aggregate_descriptions.size(); ++i)
        {
            AggregateDescription & desc = aggregate_descriptions[i];
            aggregated_columns.emplace_back(desc.column_name, desc.function->getReturnType());
        }
    }
    else
    {
        aggregated_columns = temp_actions->getSampleBlock().getColumnsList();
    }
535 536 537
}


538 539
void ExpressionAnalyzer::initGlobalSubqueriesAndExternalTables()
{
F
f1yegor 已提交
540
    /// Adds existing external tables (not subqueries) to the external_tables dictionary.
541
    findExternalTables(ast);
542

F
f1yegor 已提交
543
    /// Converts GLOBAL subqueries to external tables; Puts them into the external_tables dictionary: name -> StoragePtr.
544
    initGlobalSubqueries(ast);
545 546 547 548 549
}


void ExpressionAnalyzer::initGlobalSubqueries(ASTPtr & ast)
{
F
f1yegor 已提交
550
    /// Recursive calls. We do not go into subqueries.
551 552 553 554 555

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

F
f1yegor 已提交
556
    /// Bottom-up actions.
557 558 559

    if (ASTFunction * node = typeid_cast<ASTFunction *>(ast.get()))
    {
F
f1yegor 已提交
560
        /// For GLOBAL IN.
561 562 563 564 565
        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 已提交
566
        /// For GLOBAL JOIN.
567 568 569 570
        if (do_global && node->table_join
            && static_cast<const ASTTableJoin &>(*node->table_join).locality == ASTTableJoin::Locality::Global)
            addExternalStorage(node->table_expression);
    }
571 572 573 574 575
}


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

F
f1yegor 已提交
580
    /// If table type identifier
581
    StoragePtr external_storage;
582

583 584 585 586
    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;
587 588 589
}


590
static std::shared_ptr<InterpreterSelectQuery> interpretSubquery(
591
    ASTPtr & subquery_or_table_name, const Context & context, size_t subquery_depth, const Names & required_columns);
592 593


594
void ExpressionAnalyzer::addExternalStorage(ASTPtr & subquery_or_table_name_or_table_expression)
595
{
F
f1yegor 已提交
596
    /// With nondistributed queries, creating temporary tables does not make sense.
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
    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 已提交
633
        /// If this is already an external table, you do not need to add anything. Just remember its presence.
634 635 636 637
        if (external_tables.end() != external_tables.find(static_cast<const ASTIdentifier &>(*table_name).name))
            return;
    }

F
f1yegor 已提交
638
    /// Generate the name for the external table.
639 640 641 642 643 644 645 646 647 648 649 650 651
    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();
    NamesAndTypesListPtr columns = std::make_shared<NamesAndTypesList>(sample.getColumnsList());

    StoragePtr external_storage = StorageMemory::create(external_table_name, columns);
652
    external_storage->startup();
653

F
f1yegor 已提交
654
    /** There are two ways to perform distributed GLOBAL subqueries.
655
      *
F
f1yegor 已提交
656 657 658 659
      * "push" method:
      * Subquery data is sent to all remote servers, where they are then used.
      * For this method, the data is sent in the form of "external tables" and will be available on each remote server by the name of the type _data1.
      * Replace in the query a subquery for this name.
660
      *
F
f1yegor 已提交
661 662 663 664
      * "pull" method:
      * Remote servers download the subquery data from the request initiating server.
      * For this method, replace the subquery with another subquery of the form (SELECT * FROM remote ('host: port', _query_QUERY_ID, _data1))
      * This subquery, in fact, says - "you need to download data from there."
665
      *
F
f1yegor 已提交
666
      * The "pull" method takes precedence, because in it a remote server can decide that it does not need data and does not download it in such cases.
667 668 669 670
      */

    if (settings.global_subqueries_method == GlobalSubqueriesMethod::PUSH)
    {
F
f1yegor 已提交
671 672 673 674
        /** 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.
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
          */

        auto database_and_table_name = std::make_shared<ASTIdentifier>(StringRange(), external_table_name, ASTIdentifier::Table);

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

            ast_table_expr->children.clear();
            ast_table_expr->children.emplace_back(database_and_table_name);
        }
        else
            subquery_or_table_name_or_table_expression = database_and_table_name;
    }
    else if (settings.global_subqueries_method == GlobalSubqueriesMethod::PULL)
    {
        throw Exception("Support for 'pull' method of execution of global subqueries is disabled.", ErrorCodes::SUPPORT_IS_DISABLED);

        /// TODO
/*        String host_port = getFQDNOrHostName() + ":" + toString(context.getTCPPort());
        String database = "_query_" + context.getCurrentQueryId();

        auto subquery = std::make_shared<ASTSubquery>();
        subquery_or_table_name = subquery;

        auto select = std::make_shared<ASTSelectQuery>();
        subquery->children.push_back(select);

        auto exp_list = std::make_shared<ASTExpressionList>();
        select->select_expression_list = exp_list;
        select->children.push_back(select->select_expression_list);

        Names column_names = external_storage->getColumnNamesList();
        for (const auto & name : column_names)
            exp_list->children.push_back(std::make_shared<ASTIdentifier>(StringRange(), name));

        auto table_func = std::make_shared<ASTFunction>();
        select->table = table_func;
        select->children.push_back(select->table);

        table_func->name = "remote";
        auto args = std::make_shared<ASTExpressionList>();
        table_func->arguments = args;
        table_func->children.push_back(table_func->arguments);

        auto address_lit = std::make_shared<ASTLiteral>(StringRange(), host_port);
        args->children.push_back(address_lit);

        auto database_lit = std::make_shared<ASTLiteral>(StringRange(), database);
        args->children.push_back(database_lit);

        auto table_lit = std::make_shared<ASTLiteral>(StringRange(), external_table_name);
        args->children.push_back(table_lit);*/
    }
    else
        throw Exception("Unknown global subqueries execution method", ErrorCodes::UNKNOWN_GLOBAL_SUBQUERIES_METHOD);

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

F
f1yegor 已提交
738 739 740 741
    /** 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.
742
      */
743 744 745
}


A
Alexey Milovidov 已提交
746
NamesAndTypesList::iterator ExpressionAnalyzer::findColumn(const String & name, NamesAndTypesList & cols)
747
{
748 749
    return std::find_if(cols.begin(), cols.end(),
        [&](const NamesAndTypesList::value_type & val) { return val.name == name; });
750 751 752
}


F
f1yegor 已提交
753 754
/// 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.
755
void ExpressionAnalyzer::addASTAliases(ASTPtr & ast, int ignore_levels)
756
{
F
f1yegor 已提交
757
    /// Bottom-up traversal. We do not go into subqueries.
758 759 760 761
    for (auto & child : ast->children)
    {
        int new_ignore_levels = std::max(0, ignore_levels - 1);

F
f1yegor 已提交
762 763
        /// 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).
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
        if (typeid_cast<ASTArrayJoin *>(ast.get()))
            new_ignore_levels = 3;

        /// Don't descent into UNION ALL, table functions and subqueries.
        if (!typeid_cast<ASTTableExpression *>(child.get())
            && !typeid_cast<ASTSelectQuery *>(child.get()))
            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())
            throw Exception("Different expressions with the same alias " + alias, ErrorCodes::MULTIPLE_EXPRESSIONS_FOR_ALIAS);

        aliases[alias] = ast;
    }
784 785 786 787 788
}


StoragePtr ExpressionAnalyzer::getTable()
{
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
    if (const ASTSelectQuery * select = typeid_cast<const ASTSelectQuery *>(ast.get()))
    {
        auto select_database = select->database();
        auto select_table = select->table();

        if (select_table
            && !typeid_cast<const ASTSelectQuery *>(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;
            return context.tryGetTable(database, table);
        }
    }

    return StoragePtr();
807 808 809 810 811
}


void ExpressionAnalyzer::normalizeTree()
{
812 813 814
    SetOfASTs tmp_set;
    MapOfASTs tmp_map;
    normalizeTreeImpl(ast, tmp_map, tmp_set, "", 0);
815 816 817
}


F
f1yegor 已提交
818 819 820
/// 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)
821
void ExpressionAnalyzer::normalizeTreeImpl(
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
    ASTPtr & ast, MapOfASTs & finished_asts, SetOfASTs & current_asts, std::string current_alias, size_t level)
{
    if (level > settings.limits.max_ast_depth)
        throw Exception("Normalized AST is too deep. Maximum: " + settings.limits.max_ast_depth.toString(), ErrorCodes::TOO_DEEP_AST);

    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 已提交
840
    /// rewrite rules that act when you go from top to bottom.
841 842 843 844 845
    bool replaced = false;

    ASTFunction * func_node = typeid_cast<ASTFunction *>(ast.get());
    if (func_node)
    {
F
f1yegor 已提交
846 847
        /** Is there a column in the table whose name fully matches the function entry?
          * For example, in the table there is a column "domain(URL)", and we requested domain(URL).
848 849 850 851 852 853 854 855 856 857
          */
        String function_string = func_node->getColumnName();
        NamesAndTypesList::const_iterator it = findColumn(function_string);
        if (columns.end() != it)
        {
            ast = std::make_shared<ASTIdentifier>(func_node->range, function_string);
            current_asts.insert(ast.get());
            replaced = true;
        }

F
f1yegor 已提交
858
        /// `IN t` can be specified, where t is a table, which is equivalent to `IN (SELECT * FROM t)`.
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
        if (functionIsInOrGlobalInOperator(func_node->name))
            if (ASTIdentifier * right = typeid_cast<ASTIdentifier *>(func_node->arguments->children.at(1).get()))
                right->kind = ASTIdentifier::Table;

        /// 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();
            }
        }
    }
    else if (ASTIdentifier * node = typeid_cast<ASTIdentifier *>(ast.get()))
    {
        if (node->kind == ASTIdentifier::Column)
        {
F
f1yegor 已提交
886
            /// If it is an alias, but not a parent alias (for constructs like "SELECT column + 1 AS column").
887 888 889
            Aliases::const_iterator jt = aliases.find(node->name);
            if (jt != aliases.end() && current_alias != node->name)
            {
F
f1yegor 已提交
890
                /// Let's replace it with the corresponding tree node.
891 892 893 894
                if (current_asts.count(jt->second.get()))
                    throw Exception("Cyclic aliases", ErrorCodes::CYCLIC_ALIASES);
                if (!my_alias.empty() && my_alias != jt->second->getAliasOrColumnName())
                {
F
f1yegor 已提交
895
                    /// In a construct like "a AS b", where a is an alias, you must set alias b to the result of substituting alias a.
896 897 898 899 900 901 902 903 904 905 906 907 908 909
                    ast = jt->second->clone();
                    ast->setAlias(my_alias);
                }
                else
                {
                    ast = jt->second;
                }

                replaced = true;
            }
        }
    }
    else if (ASTExpressionList * node = typeid_cast<ASTExpressionList *>(ast.get()))
    {
F
f1yegor 已提交
910
        /// Replace * with a list of columns.
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
        ASTs & asts = node->children;
        for (int i = static_cast<int>(asts.size()) - 1; i >= 0; --i)
        {
            if (ASTAsterisk * asterisk = typeid_cast<ASTAsterisk *>(asts[i].get()))
            {
                ASTs all_columns;
                for (const auto & column_name_type : columns)
                    all_columns.emplace_back(std::make_shared<ASTIdentifier>(asterisk->range, column_name_type.name));

                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 已提交
940
    /// 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.
941 942 943 944 945 946 947 948 949
    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;
    }

F
f1yegor 已提交
950 951 952
    /// Recurring calls. Don't go into subqueries.
    /// 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]).
953 954 955

    if (func_node && func_node->name == "lambda")
    {
F
f1yegor 已提交
956
        /// We skip the first argument. We also assume that the lambda function can not have parameters.
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
        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);
        }
    }
    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 已提交
980
    /// 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.
981 982 983 984 985 986 987 988 989 990
    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);
    }

F
f1yegor 已提交
991
    /// Actions to be performed from the bottom up.
992 993 994 995 996 997 998 999 1000 1001

    if (ASTFunction * node = typeid_cast<ASTFunction *>(ast.get()))
    {
        if (node->kind == ASTFunction::TABLE_FUNCTION)
        {
        }
        else if (node->name == "lambda")
        {
            node->kind = ASTFunction::LAMBDA_EXPRESSION;
        }
1002
        else if (AggregateFunctionFactory::instance().isAggregateFunctionName(node->name))
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
        {
            node->kind = ASTFunction::AGGREGATE_FUNCTION;
        }
        else if (node->name == "arrayJoin")
        {
            node->kind = ASTFunction::ARRAY_JOIN;
        }
        else
        {
            node->kind = ASTFunction::FUNCTION;
        }

        if (node->parameters && node->kind != ASTFunction::AGGREGATE_FUNCTION)
            throw Exception("The only parametric functions (functions with two separate parenthesis pairs) are aggregate functions"
                ", and '" + node->name + "' is not an aggregate function.", ErrorCodes::FUNCTION_CANNOT_HAVE_PARAMETERS);
    }

    current_asts.erase(initial_ast.get());
    current_asts.erase(ast.get());
    finished_asts[initial_ast] = ast;
1023 1024
}

1025

1026 1027
void ExpressionAnalyzer::addAliasColumns()
{
1028 1029
    if (!select_query)
        return;
1030

1031 1032
    if (!storage)
        return;
1033

1034
    columns.insert(std::end(columns), std::begin(storage->alias_columns), std::end(storage->alias_columns));
1035 1036 1037
}


1038 1039
void ExpressionAnalyzer::executeScalarSubqueries()
{
1040 1041 1042 1043 1044 1045
    if (!select_query)
        executeScalarSubqueriesImpl(ast);
    else
    {
        for (auto & child : ast->children)
        {
F
f1yegor 已提交
1046
            /// Do not go to FROM, JOIN, UNION.
1047 1048 1049 1050 1051 1052 1053
            if (!typeid_cast<const ASTTableExpression *>(child.get())
                && child.get() != select_query->next_union_all.get())
            {
                executeScalarSubqueriesImpl(child);
            }
        }
    }
1054 1055
}

1056

1057
static ASTPtr addTypeConversion(std::unique_ptr<ASTLiteral> && ast, const String & type_name)
1058
{
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
    auto func = std::make_shared<ASTFunction>(ast->range);
    ASTPtr res = func;
    func->alias = ast->alias;
    ast->alias.clear();
    func->kind = ASTFunction::FUNCTION;
    func->name = "CAST";
    auto exp_list = std::make_shared<ASTExpressionList>(ast->range);
    func->arguments = exp_list;
    func->children.push_back(func->arguments);
    exp_list->children.emplace_back(ast.release());
    exp_list->children.emplace_back(std::make_shared<ASTLiteral>(StringRange(), type_name));
    return res;
1071 1072 1073
}


1074 1075
void ExpressionAnalyzer::executeScalarSubqueriesImpl(ASTPtr & ast)
{
F
f1yegor 已提交
1076 1077
    /** Replace subqueries that return exactly one row
      * ("scalar" subqueries) to the corresponding constants.
1078
      *
F
f1yegor 已提交
1079
      * If the subquery returns more than one column, it is replaced by a tuple of constants.
1080
      *
F
f1yegor 已提交
1081
      * Features
1082
      *
F
f1yegor 已提交
1083 1084 1085
      * 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.
1086
      *
F
f1yegor 已提交
1087
      * But the query result can be used for the index in the table.
1088
      *
F
f1yegor 已提交
1089 1090
      * Scalar subqueries are executed on the request-initializer server.
      * The request is sent to remote servers with already substituted constants.
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
      */

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

        ASTPtr query = subquery->children.at(0);
        BlockIO res = InterpreterSelectQuery(query, subquery_context, QueryProcessingStage::Complete, subquery_depth + 1).execute();

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

            if (!block)
            {
                /// Interpret subquery with empty result as Null literal
                ast = std::make_unique<ASTLiteral>(ast->range, Null());
                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)
        {
            if (e.code() == ErrorCodes::TOO_MUCH_ROWS)
                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)
        {
            auto lit = std::make_unique<ASTLiteral>(ast->range, (*block.safeGetByPosition(0).column)[0]);
            lit->alias = subquery->alias;
            ast = addTypeConversion(std::move(lit), block.safeGetByPosition(0).type->getName());
        }
        else
        {
            auto tuple = std::make_shared<ASTFunction>(ast->range);
            tuple->alias = subquery->alias;
            ast = tuple;
            tuple->kind = ASTFunction::FUNCTION;
            tuple->name = "tuple";
            auto exp_list = std::make_shared<ASTExpressionList>(ast->range);
            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(
                    std::make_unique<ASTLiteral>(ast->range, (*block.safeGetByPosition(i).column)[0]),
                    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());

            if (func && func->kind == ASTFunction::FUNCTION
                && functionIsInOrGlobalInOperator(func->name))
            {
                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);
        }
    }
1183 1184 1185
}


1186
void ExpressionAnalyzer::optimizeGroupBy()
1187
{
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
    if (!(select_query && select_query->group_expression_list))
        return;

    const auto is_literal = [] (const ASTPtr& ast) {
        return typeid_cast<const ASTLiteral*>(ast.get());
    };

    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 已提交
1268 1269 1270
        /** 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.
1271 1272
          */

F
f1yegor 已提交
1273
        /// You must insert a constant that is not the name of the column in the table. Such a case is rare, but it happens.
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
        UInt64 unused_column = 0;
        String unused_column_name = toString(unused_column);

        while (columns.end() != std::find_if(columns.begin(), columns.end(),
            [&unused_column_name](const NameAndTypePair & name_type) { return name_type.name == unused_column_name; }))
        {
            ++unused_column;
            unused_column_name = toString(unused_column);
        }

        select_query->group_expression_list = std::make_shared<ASTExpressionList>();
        select_query->group_expression_list->children.emplace_back(std::make_shared<ASTLiteral>(StringRange(), UInt64(unused_column)));
    }
1287 1288 1289
}


1290 1291
void ExpressionAnalyzer::optimizeOrderBy()
{
1292 1293
    if (!(select_query && select_query->order_expression_list))
        return;
1294

F
f1yegor 已提交
1295
    /// Make unique sorting conditions.
1296 1297
    using NameAndLocale = std::pair<String, String>;
    std::set<NameAndLocale> elems_set;
1298

1299 1300 1301
    ASTs & elems = select_query->order_expression_list->children;
    ASTs unique_elems;
    unique_elems.reserve(elems.size());
1302

1303 1304 1305 1306
    for (const auto & elem : elems)
    {
        String name = elem->children.front()->getColumnName();
        const ASTOrderByElement & order_by_elem = typeid_cast<const ASTOrderByElement &>(*elem);
1307

1308 1309 1310
        if (elems_set.emplace(name, order_by_elem.collation ? order_by_elem.collation->getColumnName() : "").second)
            unique_elems.emplace_back(elem);
    }
1311

1312 1313
    if (unique_elems.size() < elems.size())
        elems = unique_elems;
1314 1315 1316
}


1317 1318
void ExpressionAnalyzer::optimizeLimitBy()
{
1319 1320
    if (!(select_query && select_query->limit_by_expression_list))
        return;
1321

1322
    std::set<String> elems_set;
1323

1324 1325 1326
    ASTs & elems = select_query->limit_by_expression_list->children;
    ASTs unique_elems;
    unique_elems.reserve(elems.size());
1327

1328 1329 1330 1331 1332
    for (const auto & elem : elems)
    {
        if (elems_set.emplace(elem->getColumnName()).second)
            unique_elems.emplace_back(elem);
    }
1333

1334 1335
    if (unique_elems.size() < elems.size())
        elems = unique_elems;
1336 1337 1338
}


1339
void ExpressionAnalyzer::makeSetsForIndex()
P
Pavel Kartavyy 已提交
1340
{
1341 1342
    if (storage && ast && storage->supportsIndexForIn())
        makeSetsForIndexImpl(ast, storage->getSampleBlock());
P
Pavel Kartavyy 已提交
1343 1344
}

A
Alexey Milovidov 已提交
1345
void ExpressionAnalyzer::makeSetsForIndexImpl(ASTPtr & node, const Block & sample_block)
P
Pavel Kartavyy 已提交
1346
{
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
    for (auto & child : node->children)
        makeSetsForIndexImpl(child, sample_block);

    ASTFunction * func = typeid_cast<ASTFunction *>(node.get());
    if (func && func->kind == ASTFunction::FUNCTION && functionIsInOperator(func->name))
    {
        IAST & args = *func->arguments;
        ASTPtr & arg = args.children.at(1);

        if (!typeid_cast<ASTSet *>(arg.get()) && !typeid_cast<ASTSubquery *>(arg.get()) && !typeid_cast<ASTIdentifier *>(arg.get()))
        {
            try
            {
                makeExplicitSet(func, sample_block, true);
            }
            catch (const DB::Exception & e)
            {
F
f1yegor 已提交
1364
                /// in `sample_block` there are no columns that add `getActions`
1365 1366 1367 1368 1369
                if (e.code() != ErrorCodes::NOT_FOUND_COLUMN_IN_BLOCK)
                    throw;
            }
        }
    }
P
Pavel Kartavyy 已提交
1370
}
1371

1372

1373
static std::shared_ptr<InterpreterSelectQuery> interpretSubquery(
1374 1375
    ASTPtr & subquery_or_table_name, const Context & context, size_t subquery_depth, const Names & required_columns)
{
F
f1yegor 已提交
1376
    /// Subquery or table name. The name of the table is similar to the subquery `SELECT * FROM t`.
1377 1378 1379 1380 1381 1382
    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);

F
f1yegor 已提交
1383 1384 1385
    /** 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
1386 1387
      *  max_rows_in_set, max_bytes_in_set, set_overflow_mode,
      *  max_rows_in_join, max_bytes_in_join, join_overflow_mode,
F
f1yegor 已提交
1388
      *  which are checked separately (in the Set, Join objects).
1389 1390 1391 1392 1393
      */
    Context subquery_context = context;
    Settings subquery_settings = context.getSettings();
    subquery_settings.limits.max_result_rows = 0;
    subquery_settings.limits.max_result_bytes = 0;
F
f1yegor 已提交
1394
    /// 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).
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
    subquery_settings.extremes = 0;
    subquery_context.setSettings(subquery_settings);

    ASTPtr query;
    if (table)
    {
        /// create ASTSelectQuery for "SELECT * FROM table" as if written by hand
        const auto select_query = std::make_shared<ASTSelectQuery>();
        query = select_query;

        const auto select_expression_list = std::make_shared<ASTExpressionList>();
        select_query->select_expression_list = select_expression_list;
        select_query->children.emplace_back(select_query->select_expression_list);

        /// get columns list for target table
        const auto & storage = context.getTable("", table->name);
        const auto & columns = storage->getColumnsListNonMaterialized();
        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>(
                StringRange{}, column.name));

        select_query->replaceDatabaseAndTable("", table->name);
    }
    else
    {
        query = subquery->children.at(0);

F
f1yegor 已提交
1425 1426 1427
        /** 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.
1428
          *
F
f1yegor 已提交
1429
          * To avoid this situation, we will rename the same columns.
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450
          */

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

        if (ASTSelectQuery * select = typeid_cast<ASTSelectQuery *>(query.get()))
        {
            for (auto & expr : select->select_expression_list->children)
                all_column_names.insert(expr->getAliasOrColumnName());

            for (auto & expr : select->select_expression_list->children)
            {
                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;

                    name = name + "_" + toString(i);
F
f1yegor 已提交
1451
                    expr = expr->clone();   /// Cancels fuse of the same expressions in the tree.
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
                    expr->setAlias(name);

                    all_column_names.insert(name);
                    assigned_column_names.insert(name);
                }
            }
        }
    }

    if (required_columns.empty())
        return std::make_shared<InterpreterSelectQuery>(
            query, subquery_context, QueryProcessingStage::Complete, subquery_depth + 1);
    else
        return std::make_shared<InterpreterSelectQuery>(
            query, subquery_context, required_columns, QueryProcessingStage::Complete, subquery_depth + 1);
1467 1468
}

1469

1470
void ExpressionAnalyzer::makeSet(ASTFunction * node, const Block & sample_block)
1471
{
F
f1yegor 已提交
1472 1473 1474
    /** 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`.
1475 1476 1477 1478
      */
    IAST & args = *node->arguments;
    ASTPtr & arg = args.children.at(1);

F
f1yegor 已提交
1479
    /// Already converted.
1480 1481 1482
    if (typeid_cast<ASTSet *>(arg.get()))
        return;

F
f1yegor 已提交
1483
    /// If the subquery or table name for SELECT.
1484 1485 1486
    ASTIdentifier * identifier = typeid_cast<ASTIdentifier *>(arg.get());
    if (typeid_cast<ASTSubquery *>(arg.get()) || identifier)
    {
F
f1yegor 已提交
1487
        /// We get the stream of blocks for the subquery. Create Set and put it in place of the subquery.
1488 1489 1490 1491
        String set_id = arg->getColumnName();
        auto ast_set = std::make_shared<ASTSet>(set_id);
        ASTPtr ast_set_ptr = ast_set;

F
f1yegor 已提交
1492 1493
        /// 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).
        /// TODO This syntax does not support the specification of the database name.
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
        if (identifier)
        {
            StoragePtr table = context.tryGetTable("", identifier->name);

            if (table)
            {
                StorageSet * storage_set = typeid_cast<StorageSet *>(table.get());

                if (storage_set)
                {
                    SetPtr & set = storage_set->getSet();
                    ast_set->set = set;
                    arg = ast_set_ptr;
                    return;
                }
            }
        }

        SubqueryForSet & subquery_for_set = subqueries_for_sets[set_id];

F
f1yegor 已提交
1514
        /// If you already created a Set with the same subquery / table.
1515 1516 1517 1518 1519 1520 1521 1522 1523
        if (subquery_for_set.set)
        {
            ast_set->set = subquery_for_set.set;
            arg = ast_set_ptr;
            return;
        }

        ast_set->set = std::make_shared<Set>(settings.limits);

F
f1yegor 已提交
1524 1525 1526 1527
        /** 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.
1528 1529 1530 1531 1532 1533 1534 1535
          */
        if (!subquery_for_set.source)
        {
            auto interpreter = interpretSubquery(arg, context, subquery_depth, {});
            subquery_for_set.source = std::make_shared<LazyBlockInputStream>(
                [interpreter]() mutable { return interpreter->execute().in; });
            subquery_for_set.source_sample = interpreter->getSampleBlock();

F
f1yegor 已提交
1536
            /** Why is LazyBlockInputStream used?
1537
              *
F
f1yegor 已提交
1538
              * The fact is that when processing a request of the form
1539
              *  SELECT ... FROM remote_test WHERE column GLOBAL IN (subquery),
F
f1yegor 已提交
1540 1541
              *  if the distributed remote_test table contains localhost as one of the servers,
              *  the request will be interpreted locally again (and not sent over TCP, as in the case of a remote server).
1542
              *
F
f1yegor 已提交
1543
              * The query execution pipeline will be:
1544
              * CreatingSets
F
f1yegor 已提交
1545
              *  subquery execution, filling the temporary table with _data1 (1)
1546
              *  CreatingSets
F
f1yegor 已提交
1547 1548
              *   reading from the table _data1, creating the set (2)
              *   read from the table subordinate to remote_test.
1549
              *
F
f1yegor 已提交
1550 1551
              * (The second part of the pipeline under CreateSets is a reinterpretation of the request inside StorageDistributed,
              *  the query differs in that the database name and tables are replaced with subordinates, and the subquery is replaced with _data1.)
1552
              *
F
f1yegor 已提交
1553 1554 1555
              * 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).
1556
              *
F
f1yegor 已提交
1557 1558
              * 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.
1559
              *
F
f1yegor 已提交
1560
              * Note: this solution is not very good, you need to think better.
1561 1562 1563 1564 1565 1566 1567 1568
              */
        }

        subquery_for_set.set = ast_set->set;
        arg = ast_set_ptr;
    }
    else
    {
F
f1yegor 已提交
1569
        /// An explicit enumeration of values in parentheses.
1570 1571
        makeExplicitSet(node, sample_block, false);
    }
P
Pavel Kartavyy 已提交
1572 1573
}

F
f1yegor 已提交
1574
/// The case of an explicit enumeration of values.
P
Pavel Kartavyy 已提交
1575
void ExpressionAnalyzer::makeExplicitSet(ASTFunction * node, const Block & sample_block, bool create_ordered_set)
P
Pavel Kartavyy 已提交
1576
{
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
    IAST & args = *node->arguments;

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

    ASTPtr & arg = args.children.at(1);

    DataTypes set_element_types;
    ASTPtr & left_arg = args.children.at(0);

    ASTFunction * left_arg_tuple = typeid_cast<ASTFunction *>(left_arg.get());

    /** NOTE If tuple in left hand side specified non-explicitly
      * Example: identity((a, b)) IN ((1, 2), (3, 4))
      *  instead of        (a, b)) IN ((1, 2), (3, 4))
      * then set creation of set doesn't work correctly.
      */
    if (left_arg_tuple && left_arg_tuple->name == "tuple")
    {
        for (const auto & arg : left_arg_tuple->arguments->children)
        {
            const auto & data_type = sample_block.getByName(arg->getColumnName()).type;

            /// @note prevent crash in query: SELECT (1, [1]) in (1, 1)
            if (const auto array = typeid_cast<const DataTypeArray * >(data_type.get()))
                throw Exception("Incorrect element of tuple: " + array->getName(), ErrorCodes::INCORRECT_ELEMENT_OF_SET);

            set_element_types.push_back(data_type);
        }
    }
    else
    {
        DataTypePtr left_type = sample_block.getByName(left_arg->getColumnName()).type;
        if (DataTypeArray * array_type = typeid_cast<DataTypeArray *>(left_type.get()))
            set_element_types.push_back(array_type->getNestedType());
        else
            set_element_types.push_back(left_type);
    }

F
f1yegor 已提交
1616
    /// The case `x in (1, 2)` distinguishes from the case `x in 1` (also `x in (1)`).
1617 1618 1619 1620 1621 1622 1623 1624 1625
    bool single_value = false;
    ASTPtr elements_ast = arg;

    if (ASTFunction * set_func = typeid_cast<ASTFunction *>(arg.get()))
    {
        if (set_func->name == "tuple")
        {
            if (set_func->arguments->children.empty())
            {
F
f1yegor 已提交
1626
                /// Empty set.
1627 1628 1629 1630
                elements_ast = set_func->arguments;
            }
            else
            {
F
f1yegor 已提交
1631
                /// Distinguish the case `(x, y) in ((1, 2), (3, 4))` from the case `(x, y) in (1, 2)`.
1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
                ASTFunction * any_element = typeid_cast<ASTFunction *>(set_func->arguments->children.at(0).get());
                if (set_element_types.size() >= 2 && (!any_element || any_element->name != "tuple"))
                    single_value = true;
                else
                    elements_ast = set_func->arguments;
            }
        }
        else
        {
            if (set_element_types.size() >= 2)
                throw Exception("Incorrect type of 2nd argument for function " + node->name
                    + ". Must be subquery or set of " + toString(set_element_types.size()) + "-element tuples.",
                    ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT);

            single_value = true;
        }
    }
    else if (typeid_cast<ASTLiteral *>(arg.get()))
    {
        single_value = true;
    }
    else
    {
        throw Exception("Incorrect type of 2nd argument for function " + node->name + ". Must be subquery or set of values.",
                        ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT);
    }

    if (single_value)
    {
        ASTPtr exp_list = std::make_shared<ASTExpressionList>();
        exp_list->children.push_back(elements_ast);
        elements_ast = exp_list;
    }

    auto ast_set = std::make_shared<ASTSet>(arg->getColumnName());
    ast_set->set = std::make_shared<Set>(settings.limits);
    ast_set->is_explicit = true;
    ast_set->set->createFromAST(set_element_types, elements_ast, context, create_ordered_set);
    arg = ast_set;
1671 1672 1673
}


1674
static String getUniqueName(const Block & block, const String & prefix)
1675
{
1676 1677 1678 1679
    int i = 1;
    while (block.has(prefix + toString(i)))
        ++i;
    return prefix + toString(i);
1680 1681 1682
}


F
f1yegor 已提交
1683 1684 1685 1686 1687
/** 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 已提交
1688 1689 1690
  */
struct ExpressionAnalyzer::ScopeStack
{
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780
    struct Level
    {
        ExpressionActionsPtr actions;
        NameSet new_columns;
    };

    using Levels = std::vector<Level>;

    Levels stack;
    Settings settings;

    ScopeStack(const ExpressionActionsPtr & actions, const Settings & settings_)
        : settings(settings_)
    {
        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);
    }

    void pushLevel(const NamesAndTypesList & input_columns)
    {
        stack.emplace_back();
        Level & prev = stack[stack.size() - 2];

        ColumnsWithTypeAndName all_columns;
        NameSet new_names;

        for (NamesAndTypesList::const_iterator it = input_columns.begin(); it != input_columns.end(); ++it)
        {
            all_columns.emplace_back(nullptr, it->type, it->name);
            new_names.insert(it->name);
            stack.back().new_columns.insert(it->name);
        }

        const Block & prev_sample_block = prev.actions->getSampleBlock();
        for (size_t i = 0, size = prev_sample_block.columns(); i < size; ++i)
        {
            const ColumnWithTypeAndName & col = prev_sample_block.getByPosition(i);
            if (!new_names.count(col.name))
                all_columns.push_back(col);
        }

        stack.back().actions = std::make_shared<ExpressionActions>(all_columns, settings);
    }

    size_t 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;

        throw Exception("Unknown identifier: " + name, ErrorCodes::UNKNOWN_IDENTIFIER);
    }

    void addAction(const ExpressionAction & action, const Names & additional_required_columns = Names())
    {
        size_t level = 0;
        for (size_t i = 0; i < additional_required_columns.size(); ++i)
            level = std::max(level, getColumnLevel(additional_required_columns[i]));
        Names required = action.getNeededColumns();
        for (size_t i = 0; i < required.size(); ++i)
            level = std::max(level, getColumnLevel(required[i]));

        Names added;
        stack[level].actions->add(action, added);

        stack[level].new_columns.insert(added.begin(), added.end());

        for (size_t i = 0; i < added.size(); ++i)
        {
            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);
        }
    }

    ExpressionActionsPtr popLevel()
    {
        ExpressionActionsPtr res = stack.back().actions;
        stack.pop_back();
        return res;
    }

    const Block & getSampleBlock() const
    {
        return stack.back().actions->getSampleBlock();
    }
A
Alexey Milovidov 已提交
1781 1782 1783
};


1784
void ExpressionAnalyzer::getRootActions(ASTPtr ast, bool no_subqueries, bool only_consts, ExpressionActionsPtr & actions)
1785
{
1786 1787 1788
    ScopeStack scopes(actions, settings);
    getActionsImpl(ast, no_subqueries, only_consts, scopes);
    actions = scopes.popLevel();
1789 1790 1791
}


1792 1793
void ExpressionAnalyzer::getArrayJoinedColumns()
{
1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813
    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 已提交
1814 1815
        /// If the result of ARRAY JOIN is not used, it is necessary to ARRAY-JOIN any column,
        /// to get the correct number of rows.
1816 1817 1818 1819 1820 1821
        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 已提交
1822
            /// This is an array.
1823 1824 1825 1826
            if (!typeid_cast<ASTIdentifier *>(expr.get()) || findColumn(source_name, columns) != columns.end())
            {
                array_join_result_to_source[result_name] = source_name;
            }
F
f1yegor 已提交
1827
            else /// This is a nested table.
1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845
            {
                bool found = false;
                for (const auto & column_name_type : columns)
                {
                    String table_name = DataTypeNested::extractNestedTableName(column_name_type.name);
                    String column_name = DataTypeNested::extractNestedColumnName(column_name_type.name);
                    if (table_name == source_name)
                    {
                        array_join_result_to_source[DataTypeNested::concatenateNestedName(result_name, column_name)] = column_name_type.name;
                        found = true;
                        break;
                    }
                }
                if (!found)
                    throw Exception("No columns in nested table " + source_name, ErrorCodes::EMPTY_NESTED_TABLE);
            }
        }
    }
1846 1847 1848
}


F
f1yegor 已提交
1849
/// Fills the array_join_result_to_source: on which columns-arrays to replicate, and how to call them after that.
1850
void ExpressionAnalyzer::getArrayJoinedColumnsImpl(ASTPtr ast)
1851
{
1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862
    if (typeid_cast<ASTTablesInSelectQuery *>(ast.get()))
        return;

    if (ASTIdentifier * node = typeid_cast<ASTIdentifier *>(ast.get()))
    {
        if (node->kind == ASTIdentifier::Column)
        {
            String table_name = DataTypeNested::extractNestedTableName(node->name);

            if (array_join_alias_to_name.count(node->name))
            {
F
f1yegor 已提交
1863
                /// ARRAY JOIN was written with an array column. Example: SELECT K1 FROM ... ARRAY JOIN ParsedParams.Key1 AS K1
1864 1865 1866 1867
                array_join_result_to_source[node->name] = array_join_alias_to_name[node->name];    /// K1 -> ParsedParams.Key1
            }
            else if (array_join_alias_to_name.count(table_name))
            {
F
f1yegor 已提交
1868
                /// ARRAY JOIN was written with a nested table. Example: SELECT PP.KEY1 FROM ... ARRAY JOIN ParsedParams AS PP
1869 1870 1871 1872 1873 1874
                String nested_column = DataTypeNested::extractNestedColumnName(node->name);    /// Key1
                array_join_result_to_source[node->name]    /// PP.Key1 -> ParsedParams.Key1
                    = DataTypeNested::concatenateNestedName(array_join_alias_to_name[table_name], nested_column);
            }
            else if (array_join_name_to_alias.count(table_name))
            {
F
f1yegor 已提交
1875 1876
                /** Example: SELECT ParsedParams.Key1 FROM ... ARRAY JOIN ParsedParams AS PP.
                  * That is, the query uses the original array, replicated by itself.
1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891
                  */

                String nested_column = DataTypeNested::extractNestedColumnName(node->name);    /// Key1
                array_join_result_to_source[    /// PP.Key1 -> ParsedParams.Key1
                    DataTypeNested::concatenateNestedName(array_join_name_to_alias[table_name], nested_column)] = node->name;
            }
        }
    }
    else
    {
        for (auto & child : ast->children)
            if (!typeid_cast<const ASTSubquery *>(child.get())
                && !typeid_cast<const ASTSelectQuery *>(child.get()))
                getArrayJoinedColumnsImpl(child);
    }
1892 1893 1894 1895
}


void ExpressionAnalyzer::getActionsImpl(ASTPtr ast, bool no_subqueries, bool only_consts, ScopeStack & actions_stack)
1896
{
F
f1yegor 已提交
1897
    /// If the result of the calculation already exists in the block.
1898 1899 1900 1901 1902 1903 1904 1905 1906
    if ((typeid_cast<ASTFunction *>(ast.get()) || typeid_cast<ASTLiteral *>(ast.get()))
        && actions_stack.getSampleBlock().has(ast->getColumnName()))
        return;

    if (ASTIdentifier * node = typeid_cast<ASTIdentifier *>(ast.get()))
    {
        std::string name = node->getColumnName();
        if (!only_consts && !actions_stack.getSampleBlock().has(name))
        {
F
f1yegor 已提交
1907 1908
            /// 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.
1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924

            bool found = false;
            for (const auto & column_name_type : columns)
                if (column_name_type.name == name)
                    found = true;

            if (found)
                throw Exception("Column " + name + " is not under aggregate function and not in GROUP BY.",
                    ErrorCodes::NOT_AN_AGGREGATE);
        }
    }
    else if (ASTFunction * node = typeid_cast<ASTFunction *>(ast.get()))
    {
        if (node->kind == ASTFunction::LAMBDA_EXPRESSION)
            throw Exception("Unexpected lambda expression", ErrorCodes::UNEXPECTED_EXPRESSION);

F
f1yegor 已提交
1925
        /// Function arrayJoin.
1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950
        if (node->kind == ASTFunction::ARRAY_JOIN)
        {
            if (node->arguments->children.size() != 1)
                throw Exception("arrayJoin requires exactly 1 argument", ErrorCodes::TYPE_MISMATCH);

            ASTPtr arg = node->arguments->children.at(0);
            getActionsImpl(arg, no_subqueries, only_consts, actions_stack);
            if (!only_consts)
            {
                String result_name = node->getColumnName();
                actions_stack.addAction(ExpressionAction::copyColumn(arg->getColumnName(), result_name));
                NameSet joined_columns;
                joined_columns.insert(result_name);
                actions_stack.addAction(ExpressionAction::arrayJoin(joined_columns, false, context));
            }

            return;
        }

        if (node->kind == ASTFunction::FUNCTION)
        {
            if (functionIsInOrGlobalInOperator(node->name))
            {
                if (!no_subqueries)
                {
F
f1yegor 已提交
1951
                    /// Let's find the type of the first argument (then getActionsImpl will be called again and will not affect anything).
1952 1953
                    getActionsImpl(node->arguments->children.at(0), no_subqueries, only_consts, actions_stack);

F
f1yegor 已提交
1954
                    /// Transform tuple or subquery into a set.
1955 1956 1957 1958 1959 1960
                    makeSet(node, actions_stack.getSampleBlock());
                }
                else
                {
                    if (!only_consts)
                    {
F
f1yegor 已提交
1961 1962
                        /// 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.
1963 1964 1965 1966 1967 1968 1969 1970 1971 1972
                        ColumnWithTypeAndName fake_column;
                        fake_column.name = node->getColumnName();
                        fake_column.type = std::make_shared<DataTypeUInt8>();
                        actions_stack.addAction(ExpressionAction::addColumn(fake_column));
                        getActionsImpl(node->arguments->children.at(0), no_subqueries, only_consts, actions_stack);
                    }
                    return;
                }
            }

F
f1yegor 已提交
1973 1974
            /// A special function `indexHint`. Everything that is inside it is not calculated
            /// (and is used only for index analysis, see PKCondition).
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987
            if (node->name == "indexHint")
            {
                actions_stack.addAction(ExpressionAction::addColumn(ColumnWithTypeAndName(
                    std::make_shared<ColumnConstUInt8>(1, 1), std::make_shared<DataTypeUInt8>(), node->getColumnName())));
                return;
            }

            const FunctionPtr & function = FunctionFactory::instance().get(node->name, context);

            Names argument_names;
            DataTypes argument_types;
            bool arguments_present = true;

F
f1yegor 已提交
1988
            /// If the function has an argument-lambda expression, you need to determine its type before the recursive call.
1989 1990 1991 1992 1993 1994 1995 1996
            bool has_lambda_arguments = false;

            for (auto & child : node->arguments->children)
            {
                ASTFunction * lambda = typeid_cast<ASTFunction *>(child.get());
                ASTSet * set = typeid_cast<ASTSet *>(child.get());
                if (lambda && lambda->name == "lambda")
                {
F
f1yegor 已提交
1997
                    /// If the argument is a lambda expression, just remember its approximate type.
1998 1999 2000 2001 2002 2003 2004 2005 2006 2007
                    if (lambda->arguments->children.size() != 2)
                        throw Exception("lambda requires two arguments", ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);

                    ASTFunction * lambda_args_tuple = typeid_cast<ASTFunction *>(lambda->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);

                    has_lambda_arguments = true;
                    argument_types.emplace_back(std::make_shared<DataTypeExpression>(DataTypes(lambda_args_tuple->arguments->children.size())));
F
f1yegor 已提交
2008
                    /// Select the name in the next cycle.
2009 2010 2011 2012 2013 2014 2015
                    argument_names.emplace_back();
                }
                else if (set)
                {
                    ColumnWithTypeAndName column;
                    column.type = std::make_shared<DataTypeSet>();

F
f1yegor 已提交
2016 2017
                    /// If the argument is a set given by an enumeration of values, give it a unique name,
                    ///  so that sets with the same record do not fuse together (they can have different types).
2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034
                    if (set->is_explicit)
                        column.name = getUniqueName(actions_stack.getSampleBlock(), "__set");
                    else
                        column.name = set->getColumnName();

                    if (!actions_stack.getSampleBlock().has(column.name))
                    {
                        column.column = std::make_shared<ColumnSet>(1, set->set);

                        actions_stack.addAction(ExpressionAction::addColumn(column));
                    }

                    argument_types.push_back(column.type);
                    argument_names.push_back(column.name);
                }
                else
                {
F
f1yegor 已提交
2035
                    /// If the argument is not a lambda expression, call it recursively and find out its type.
2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065
                    getActionsImpl(child, no_subqueries, only_consts, actions_stack);
                    std::string name = child->getColumnName();
                    if (actions_stack.getSampleBlock().has(name))
                    {
                        argument_types.push_back(actions_stack.getSampleBlock().getByName(name).type);
                        argument_names.push_back(name);
                    }
                    else
                    {
                        if (only_consts)
                        {
                            arguments_present = false;
                        }
                        else
                        {
                            throw Exception("Unknown identifier: " + name, ErrorCodes::UNKNOWN_IDENTIFIER);
                        }
                    }
                }
            }

            if (only_consts && !arguments_present)
                return;

            Names additional_requirements;

            if (has_lambda_arguments && !only_consts)
            {
                function->getLambdaArgumentTypes(argument_types);

F
f1yegor 已提交
2066
                /// Call recursively for lambda expressions.
2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103
                for (size_t i = 0; i < node->arguments->children.size(); ++i)
                {
                    ASTPtr child = node->arguments->children[i];

                    ASTFunction * lambda = typeid_cast<ASTFunction *>(child.get());
                    if (lambda && lambda->name == "lambda")
                    {
                        DataTypeExpression * lambda_type = typeid_cast<DataTypeExpression *>(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;

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

                            String arg_name = identifier->name;

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

                        actions_stack.pushLevel(lambda_arguments);
                        getActionsImpl(lambda->arguments->children.at(1), no_subqueries, only_consts, actions_stack);
                        ExpressionActionsPtr lambda_actions = actions_stack.popLevel();

                        String result_name = lambda->arguments->children.at(1)->getColumnName();
                        lambda_actions->finalize(Names(1, result_name));
                        DataTypePtr result_type = lambda_actions->getSampleBlock().getByName(result_name).type;
                        argument_types[i] = std::make_shared<DataTypeExpression>(lambda_type->getArgumentTypes(), result_type);

                        Names captured = lambda_actions->getRequiredColumns();
                        for (size_t j = 0; j < captured.size(); ++j)
                            if (findColumn(captured[j], lambda_arguments) == lambda_arguments.end())
                                additional_requirements.push_back(captured[j]);

F
f1yegor 已提交
2104 2105
                        /// We can not name `getColumnName()`,
                        ///  because it does not uniquely define the expression (the types of arguments can be different).
2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149
                        argument_names[i] = getUniqueName(actions_stack.getSampleBlock(), "__lambda");

                        ColumnWithTypeAndName lambda_column;
                        lambda_column.column = std::make_shared<ColumnExpression>(1, lambda_actions, lambda_arguments, result_type, result_name);
                        lambda_column.type = argument_types[i];
                        lambda_column.name = argument_names[i];
                        actions_stack.addAction(ExpressionAction::addColumn(lambda_column));
                    }
                }
            }

            if (only_consts)
            {
                for (size_t i = 0; i < argument_names.size(); ++i)
                {
                    if (!actions_stack.getSampleBlock().has(argument_names[i]))
                    {
                        arguments_present = false;
                        break;
                    }
                }
            }

            if (arguments_present)
                actions_stack.addAction(ExpressionAction::applyFunction(function, argument_names, node->getColumnName()),
                                        additional_requirements);
        }
    }
    else if (ASTLiteral * node = typeid_cast<ASTLiteral *>(ast.get()))
    {
        DataTypePtr type = applyVisitor(FieldToDataType(), node->value);

        ColumnWithTypeAndName column;
        column.column = type->createConstColumn(1, node->value);
        column.type = type;
        column.name = node->getColumnName();

        actions_stack.addAction(ExpressionAction::addColumn(column));
    }
    else
    {
        for (auto & child : ast->children)
            getActionsImpl(child, no_subqueries, only_consts, actions_stack);
    }
2150 2151 2152
}


2153
void ExpressionAnalyzer::getAggregates(const ASTPtr & ast, ExpressionActionsPtr & actions)
2154
{
F
f1yegor 已提交
2155
    /// There can not be aggregate functions inside the WHERE and PREWHERE.
2156 2157 2158 2159 2160 2161
    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 已提交
2162
    /// If we are not analyzing a SELECT query, but a separate expression, then there can not be aggregate functions in it.
2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175
    if (!select_query)
    {
        assertNoAggregates(ast, "in wrong place");
        return;
    }

    const ASTFunction * node = typeid_cast<const ASTFunction *>(ast.get());
    if (node && node->kind == ASTFunction::AGGREGATE_FUNCTION)
    {
        has_aggregation = true;
        AggregateDescription aggregate;
        aggregate.column_name = node->getColumnName();

F
f1yegor 已提交
2176
        /// Make unique aggregate functions.
2177 2178 2179 2180 2181 2182 2183 2184 2185 2186
        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 已提交
2187
            /// There can not be other aggregate functions within the aggregate functions.
2188 2189 2190 2191 2192 2193 2194 2195
            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;
        }

2196
        aggregate.function = AggregateFunctionFactory::instance().get(node->name, types);
2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227

        if (node->parameters)
        {
            const ASTs & parameters = typeid_cast<const ASTExpressionList &>(*node->parameters).children;
            Array params_row(parameters.size());

            for (size_t i = 0; i < parameters.size(); ++i)
            {
                const ASTLiteral * lit = typeid_cast<const ASTLiteral *>(parameters[i].get());
                if (!lit)
                    throw Exception("Parameters to aggregate functions must be literals",
                        ErrorCodes::PARAMETERS_TO_AGGREGATE_FUNCTIONS_MUST_BE_LITERALS);

                params_row[i] = lit->value;
            }

            aggregate.parameters = params_row;
            aggregate.function->setParameters(params_row);
        }

        aggregate.function->setArguments(types);

        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);
    }
2228 2229
}

2230 2231 2232

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

2235 2236 2237
    if (node && node->kind == ASTFunction::AGGREGATE_FUNCTION)
        throw Exception("Aggregate function " + node->getColumnName()
            + " is found " + String(description) + " in query", ErrorCodes::ILLEGAL_AGGREGATION);
2238

2239 2240 2241 2242
    for (const auto & child : ast->children)
        if (!typeid_cast<const ASTSubquery *>(child.get())
            && !typeid_cast<const ASTSelectQuery *>(child.get()))
            assertNoAggregates(child, description);
2243 2244 2245
}


2246
void ExpressionAnalyzer::assertSelect() const
2247
{
2248 2249
    if (!select_query)
        throw Exception("Not a select query", ErrorCodes::LOGICAL_ERROR);
2250
}
2251

2252
void ExpressionAnalyzer::assertAggregation() const
2253
{
2254 2255
    if (!has_aggregation)
        throw Exception("No aggregation", ErrorCodes::LOGICAL_ERROR);
2256
}
2257

2258
void ExpressionAnalyzer::initChain(ExpressionActionsChain & chain, const NamesAndTypesList & columns) const
2259
{
2260 2261 2262 2263 2264
    if (chain.steps.empty())
    {
        chain.settings = settings;
        chain.steps.emplace_back(std::make_shared<ExpressionActions>(columns, settings));
    }
2265
}
2266

2267
/// "Big" ARRAY JOIN.
2268
void ExpressionAnalyzer::addMultipleArrayJoinAction(ExpressionActionsPtr & actions) const
2269
{
2270 2271 2272 2273 2274 2275
    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));
2276

F
f1yegor 已提交
2277
        /// Make ARRAY JOIN (replace arrays with their insides) for the columns in these new names.
2278 2279
        result_columns.insert(result_source.first);
    }
2280

2281
    actions->add(ExpressionAction::arrayJoin(result_columns, select_query->array_join_is_left(), context));
2282 2283
}

2284
bool ExpressionAnalyzer::appendArrayJoin(ExpressionActionsChain & chain, bool only_types)
2285
{
2286
    assertSelect();
2287

2288 2289
    if (!select_query->array_join_expression_list())
        return false;
2290

2291 2292
    initChain(chain, columns);
    ExpressionActionsChain::Step & step = chain.steps.back();
2293

2294
    getRootActions(select_query->array_join_expression_list(), only_types, false, step.actions);
2295

2296
    addMultipleArrayJoinAction(step.actions);
2297

2298
    return true;
2299 2300
}

2301
void ExpressionAnalyzer::addJoinAction(ExpressionActionsPtr & actions, bool only_types) const
2302
{
2303 2304 2305 2306 2307 2308
    if (only_types)
        actions->add(ExpressionAction::ordinaryJoin(nullptr, columns_added_by_join));
    else
        for (auto & subquery_for_set : subqueries_for_sets)
            if (subquery_for_set.second.join)
                actions->add(ExpressionAction::ordinaryJoin(subquery_for_set.second.join, columns_added_by_join));
2309 2310 2311 2312
}

bool ExpressionAnalyzer::appendJoin(ExpressionActionsChain & chain, bool only_types)
{
2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327
    assertSelect();

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

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

    const ASTTablesInSelectQueryElement & join_element = static_cast<const ASTTablesInSelectQueryElement &>(*select_query->join());
    const ASTTableJoin & join_params = static_cast<const ASTTableJoin &>(*join_element.table_join);
    const ASTTableExpression & table_to_join = static_cast<const ASTTableExpression &>(*join_element.table_expression);

    if (join_params.using_expression_list)
        getRootActions(join_params.using_expression_list, only_types, false, step.actions);

F
f1yegor 已提交
2328
    /// Two JOINs are not supported with the same subquery, but different USINGs.
2329 2330 2331 2332
    String join_id = join_element.getTreeID();

    SubqueryForSet & subquery_for_set = subqueries_for_sets[join_id];

F
f1yegor 已提交
2333 2334
    /// 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.
2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345
    if (table_to_join.database_and_table_name)
    {
        StoragePtr table = context.tryGetTable("", static_cast<const ASTIdentifier &>(*table_to_join.database_and_table_name).name);

        if (table)
        {
            StorageJoin * storage_join = typeid_cast<StorageJoin *>(table.get());

            if (storage_join)
            {
                storage_join->assertCompatible(join_params.kind, join_params.strictness);
F
f1yegor 已提交
2346
                /// TODO Check the set of keys.
2347 2348 2349 2350 2351 2352 2353 2354 2355 2356

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

    if (!subquery_for_set.join)
    {
        JoinPtr join = std::make_shared<Join>(
2357 2358
            join_key_names_left, join_key_names_right,
            settings.join_use_nulls, settings.limits,
2359 2360 2361 2362 2363 2364
            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 已提交
2365 2366 2367 2368
        /** 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.
2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382
          */
        if (!subquery_for_set.source)
        {
            ASTPtr table;
            if (table_to_join.database_and_table_name)
                table = table_to_join.database_and_table_name;
            else
                table = table_to_join.subquery;

            auto interpreter = interpretSubquery(table, context, subquery_depth, required_joined_columns);
            subquery_for_set.source = std::make_shared<LazyBlockInputStream>([interpreter]() mutable { return interpreter->execute().in; });
            subquery_for_set.source_sample = interpreter->getSampleBlock();
        }

F
f1yegor 已提交
2383
        /// TODO You do not need to set this up when JOIN is only needed on remote servers.
2384 2385 2386 2387 2388 2389 2390
        subquery_for_set.join = join;
        subquery_for_set.join->setSampleBlock(subquery_for_set.source_sample);
    }

    addJoinAction(step.actions, false);

    return true;
2391 2392
}

2393

2394
bool ExpressionAnalyzer::appendWhere(ExpressionActionsChain & chain, bool only_types)
2395
{
2396
    assertSelect();
2397

2398 2399
    if (!select_query->where_expression)
        return false;
2400

2401 2402
    initChain(chain, columns);
    ExpressionActionsChain::Step & step = chain.steps.back();
2403

2404 2405
    step.required_output.push_back(select_query->where_expression->getColumnName());
    getRootActions(select_query->where_expression, only_types, false, step.actions);
2406

2407
    return true;
2408 2409
}

2410
bool ExpressionAnalyzer::appendGroupBy(ExpressionActionsChain & chain, bool only_types)
2411
{
2412
    assertAggregation();
2413

2414 2415
    if (!select_query->group_expression_list)
        return false;
2416

2417 2418
    initChain(chain, columns);
    ExpressionActionsChain::Step & step = chain.steps.back();
2419

2420 2421 2422 2423 2424 2425
    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);
    }
2426

2427
    return true;
2428 2429
}

2430
void ExpressionAnalyzer::appendAggregateFunctionsArguments(ExpressionActionsChain & chain, bool only_types)
2431
{
2432
    assertAggregation();
2433

2434 2435
    initChain(chain, columns);
    ExpressionActionsChain::Step & step = chain.steps.back();
2436

2437 2438 2439 2440 2441 2442 2443
    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]);
        }
    }
2444

2445
    getActionsBeforeAggregation(select_query->select_expression_list, step.actions, only_types);
2446

2447 2448
    if (select_query->having_expression)
        getActionsBeforeAggregation(select_query->having_expression, step.actions, only_types);
2449

2450 2451
    if (select_query->order_expression_list)
        getActionsBeforeAggregation(select_query->order_expression_list, step.actions, only_types);
2452 2453
}

2454
bool ExpressionAnalyzer::appendHaving(ExpressionActionsChain & chain, bool only_types)
2455
{
2456
    assertAggregation();
2457

2458 2459
    if (!select_query->having_expression)
        return false;
2460

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

2464 2465
    step.required_output.push_back(select_query->having_expression->getColumnName());
    getRootActions(select_query->having_expression, only_types, false, step.actions);
2466

2467
    return true;
2468 2469
}

2470
void ExpressionAnalyzer::appendSelect(ExpressionActionsChain & chain, bool only_types)
2471
{
2472
    assertSelect();
2473

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

2477
    getRootActions(select_query->select_expression_list, only_types, false, step.actions);
2478

2479 2480 2481 2482 2483
    ASTs asts = select_query->select_expression_list->children;
    for (size_t i = 0; i < asts.size(); ++i)
    {
        step.required_output.push_back(asts[i]->getColumnName());
    }
2484
}
2485

2486
bool ExpressionAnalyzer::appendOrderBy(ExpressionActionsChain & chain, bool only_types)
2487
{
2488
    assertSelect();
2489

2490 2491
    if (!select_query->order_expression_list)
        return false;
2492

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

2496
    getRootActions(select_query->order_expression_list, only_types, false, step.actions);
2497

2498 2499 2500 2501 2502 2503 2504 2505 2506
    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());
    }
2507

2508
    return true;
2509 2510
}

2511
void ExpressionAnalyzer::appendProjectResult(DB::ExpressionActionsChain & chain, bool only_types) const
2512
{
2513
    assertSelect();
2514

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

2518
    NamesWithAliases result_columns;
2519

2520 2521 2522 2523 2524 2525
    ASTs asts = select_query->select_expression_list->children;
    for (size_t i = 0; i < asts.size(); ++i)
    {
        result_columns.emplace_back(asts[i]->getColumnName(), asts[i]->getAliasOrColumnName());
        step.required_output.push_back(result_columns.back().second);
    }
2526

2527
    step.actions->add(ExpressionAction::project(result_columns));
2528 2529 2530
}


2531 2532
Block ExpressionAnalyzer::getSelectSampleBlock()
{
2533
    assertSelect();
2534

2535 2536
    ExpressionActionsPtr temp_actions = std::make_shared<ExpressionActions>(aggregated_columns, settings);
    NamesWithAliases result_columns;
2537

2538 2539 2540 2541 2542 2543
    ASTs asts = select_query->select_expression_list->children;
    for (size_t i = 0; i < asts.size(); ++i)
    {
        result_columns.emplace_back(asts[i]->getColumnName(), asts[i]->getAliasOrColumnName());
        getRootActions(asts[i], true, false, temp_actions);
    }
2544

2545
    temp_actions->add(ExpressionAction::project(result_columns));
2546

2547
    return temp_actions->getSampleBlock();
2548 2549
}

2550
void ExpressionAnalyzer::getActionsBeforeAggregation(ASTPtr ast, ExpressionActionsPtr & actions, bool no_subqueries)
2551
{
2552
    ASTFunction * node = typeid_cast<ASTFunction *>(ast.get());
2553

2554 2555 2556 2557 2558 2559
    if (node && node->kind == ASTFunction::AGGREGATE_FUNCTION)
        for (auto & argument : node->arguments->children)
            getRootActions(argument, no_subqueries, false, actions);
    else
        for (auto & child : ast->children)
            getActionsBeforeAggregation(child, actions, no_subqueries);
2560 2561 2562
}


M
Merge  
Michael Kolupaev 已提交
2563
ExpressionActionsPtr ExpressionAnalyzer::getActions(bool project_result)
2564
{
2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594
    ExpressionActionsPtr actions = std::make_shared<ExpressionActions>(columns, settings);
    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 已提交
2595
        /// We will not delete the original columns.
2596 2597 2598 2599 2600 2601 2602
        for (const auto & column_name_type : columns)
            result_names.push_back(column_name_type.name);
    }

    actions->finalize(result_names);

    return actions;
2603 2604 2605 2606 2607
}


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

2610
    getRootActions(ast, true, true, actions);
2611

2612
    return actions;
2613 2614
}

2615
void ExpressionAnalyzer::getAggregateInfo(Names & key_names, AggregateDescriptions & aggregates) const
2616
{
2617 2618
    for (const auto & name_and_type : aggregation_keys)
        key_names.emplace_back(name_and_type.name);
2619

2620
    aggregates = aggregate_descriptions;
2621 2622
}

2623
void ExpressionAnalyzer::collectUsedColumns()
2624
{
F
f1yegor 已提交
2625 2626 2627
    /** 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.
2628 2629 2630 2631 2632 2633 2634 2635 2636 2637
      */

    NameSet required;
    NameSet ignored;

    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 已提交
2638 2639
            /// Ignore the top-level identifiers from the ARRAY JOIN section.
            /// Then add them separately.
2640 2641 2642 2643 2644 2645
            if (typeid_cast<ASTIdentifier *>(expressions[i].get()))
            {
                ignored.insert(expressions[i]->getColumnName());
            }
            else
            {
F
f1yegor 已提交
2646
                /// Nothing needs to be ignored for expressions in ARRAY JOIN.
2647 2648 2649 2650 2651 2652 2653 2654
                NameSet empty;
                getRequiredColumnsImpl(expressions[i], required, empty, empty, empty);
            }

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

F
f1yegor 已提交
2655 2656
    /** 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).
2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675
      */
    NameSet available_joined_columns;
    collectJoinedColumns(available_joined_columns, columns_added_by_join);

    NameSet required_joined_columns;
    getRequiredColumnsImpl(ast, required, ignored, available_joined_columns, required_joined_columns);

    for (NamesAndTypesList::iterator it = columns_added_by_join.begin(); it != columns_added_by_join.end();)
    {
        if (required_joined_columns.count(it->name))
            ++it;
        else
            columns_added_by_join.erase(it++);
    }

/*    for (const auto & name_type : columns_added_by_join)
        std::cerr << "JOINed column (required, not key): " << name_type.name << std::endl;
    std::cerr << std::endl;*/

F
f1yegor 已提交
2676
    /// Insert the columns required for the ARRAY JOIN calculation into the required columns list.
2677 2678 2679 2680 2681 2682 2683 2684
    NameSet array_join_sources;
    for (const auto & result_source : array_join_result_to_source)
        array_join_sources.insert(result_source.second);

    for (const auto & column_name_type : columns)
        if (array_join_sources.count(column_name_type.name))
            required.insert(column_name_type.name);

F
f1yegor 已提交
2685
    /// You need to read at least one column to find the number of rows.
2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700
    if (required.empty())
        required.insert(ExpressionActions::getSmallestColumn(columns));

    unknown_required_columns = required;

    for (NamesAndTypesList::iterator it = columns.begin(); it != columns.end();)
    {
        unknown_required_columns.erase(it->name);

        if (!required.count(it->name))
            columns.erase(it++);
        else
            ++it;
    }

F
f1yegor 已提交
2701 2702
    /// Perhaps, 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 the request they are perceived as real.
2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715
    if (storage)
    {
        for (auto it = unknown_required_columns.begin(); it != unknown_required_columns.end();)
        {
            if (storage->hasColumn(*it))
            {
                columns.push_back(storage->getColumn(*it));
                unknown_required_columns.erase(it++);
            }
            else
                ++it;
        }
    }
2716 2717
}

2718
void ExpressionAnalyzer::collectJoinedColumns(NameSet & joined_columns, NamesAndTypesList & joined_columns_name_type)
2719
{
2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763
    if (!select_query)
        return;

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

    if (!node)
        return;

    const ASTTableJoin & table_join = static_cast<const ASTTableJoin &>(*node->table_join);
    const ASTTableExpression & table_expression = static_cast<const ASTTableExpression &>(*node->table_expression);

    Block nested_result_sample;
    if (table_expression.database_and_table_name)
    {
        const auto & table = context.getTable("", static_cast<const ASTIdentifier &>(*table_expression.database_and_table_name).name);
        nested_result_sample = table->getSampleBlockNonMaterialized();
    }
    else if (table_expression.subquery)
    {
        const auto & subquery = table_expression.subquery->children.at(0);
        nested_result_sample = InterpreterSelectQuery::getSampleBlock(subquery, context);
    }

    if (table_join.using_expression_list)
    {
        auto & keys = typeid_cast<ASTExpressionList &>(*table_join.using_expression_list);
        for (const auto & key : keys.children)
        {
            if (join_key_names_left.end() == std::find(join_key_names_left.begin(), join_key_names_left.end(), key->getColumnName()))
                join_key_names_left.push_back(key->getColumnName());
            else
                throw Exception("Duplicate column " + key->getColumnName() + " in USING list", ErrorCodes::DUPLICATE_COLUMN);

            if (join_key_names_right.end() == std::find(join_key_names_right.begin(), join_key_names_right.end(), key->getAliasOrColumnName()))
                join_key_names_right.push_back(key->getAliasOrColumnName());
            else
                throw Exception("Duplicate column " + key->getAliasOrColumnName() + " in USING list", ErrorCodes::DUPLICATE_COLUMN);
        }
    }

    for (const auto i : ext::range(0, nested_result_sample.columns()))
    {
        const auto & col = nested_result_sample.safeGetByPosition(i);
        if (join_key_names_right.end() == std::find(join_key_names_right.begin(), join_key_names_right.end(), col.name)
F
f1yegor 已提交
2764
            && !joined_columns.count(col.name)) /// Duplicate columns in the subquery for JOIN do not make sense.
2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778
        {
            joined_columns.insert(col.name);
            joined_columns_name_type.emplace_back(col.name, col.type);
        }
    }

/*    for (const auto & name : join_key_names_left)
        std::cerr << "JOIN key (left): " << name << std::endl;
    for (const auto & name : join_key_names_right)
        std::cerr << "JOIN key (right): " << name << std::endl;
    std::cerr << std::endl;
    for (const auto & name : joined_columns)
        std::cerr << "JOINed column: " << name << std::endl;
    std::cerr << std::endl;*/
2779 2780
}

2781

2782 2783
Names ExpressionAnalyzer::getRequiredColumns()
{
2784 2785
    if (!unknown_required_columns.empty())
        throw Exception("Unknown identifier: " + *unknown_required_columns.begin(), ErrorCodes::UNKNOWN_IDENTIFIER);
2786

2787 2788 2789
    Names res;
    for (const auto & column_name_type : columns)
        res.push_back(column_name_type.name);
A
Alexey Milovidov 已提交
2790

2791
    return res;
2792 2793
}

2794

2795
void ExpressionAnalyzer::getRequiredColumnsImpl(ASTPtr ast,
2796 2797 2798
    NameSet & required_columns, NameSet & ignored_names,
    const NameSet & available_joined_columns, NameSet & required_joined_columns)
{
F
f1yegor 已提交
2799 2800 2801 2802 2803 2804 2805
    /** Find all the identifiers in the query.
      * We will look for them recursively, bypassing by depth AST.
      * In this case
      * - for lambda functions we will not take formal parameters;
      * - do not go into subqueries (there are their identifiers);
      * - is some exception for the ARRAY JOIN section (it has a slightly different identifier);
      * - identifiers available from JOIN, we put in required_joined_columns.
2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834
      */

    if (ASTIdentifier * node = typeid_cast<ASTIdentifier *>(ast.get()))
    {
        if (node->kind == ASTIdentifier::Column
            && !ignored_names.count(node->name)
            && !ignored_names.count(DataTypeNested::extractNestedTableName(node->name)))
        {
            if (!available_joined_columns.count(node->name))
                required_columns.insert(node->name);
            else
                required_joined_columns.insert(node->name);
        }

        return;
    }

    if (ASTFunction * node = typeid_cast<ASTFunction *>(ast.get()))
    {
        if (node->kind == ASTFunction::LAMBDA_EXPRESSION)
        {
            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);

F
f1yegor 已提交
2835
            /// You do not need to add formal parameters of the lambda expression in required_columns.
2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860
            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);
                }
            }

            getRequiredColumnsImpl(node->arguments->children.at(1),
                required_columns, ignored_names,
                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 已提交
2861 2862
        /// A special function `indexHint`. Everything that is inside it is not calculated
        /// (and is used only for index analysis, see PKCondition).
2863 2864 2865 2866
        if (node->name == "indexHint")
            return;
    }

F
f1yegor 已提交
2867
    /// Recursively traverses an expression.
2868 2869
    for (auto & child : ast->children)
    {
F
f1yegor 已提交
2870 2871
        /** 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.
2872 2873 2874 2875 2876
          */
        if (!typeid_cast<ASTSelectQuery *>(child.get())
            && !typeid_cast<ASTArrayJoin *>(child.get()))
            getRequiredColumnsImpl(child, required_columns, ignored_names, available_joined_columns, required_joined_columns);
    }
2877 2878
}

2879
}