KeyCondition.cpp 45.1 KB
Newer Older
1
#include <Storages/MergeTree/KeyCondition.h>
2 3
#include <Storages/MergeTree/BoolMask.h>
#include <DataTypes/DataTypesNumber.h>
4
#include <Interpreters/SyntaxAnalyzer.h>
5 6
#include <Interpreters/ExpressionAnalyzer.h>
#include <Interpreters/ExpressionActions.h>
7
#include <Interpreters/misc.h>
8 9
#include <Functions/FunctionFactory.h>
#include <Functions/IFunction.h>
10
#include <Common/FieldVisitors.h>
11
#include <Common/typeid_cast.h>
12 13
#include <Interpreters/convertFieldToType.h>
#include <Interpreters/Set.h>
A
Alexey Milovidov 已提交
14
#include <Parsers/queryToString.h>
15
#include <Parsers/ASTLiteral.h>
16 17
#include <Parsers/ASTSubquery.h>
#include <Parsers/ASTIdentifier.h>
18

19 20
#include <cassert>

M
Merge  
Michael Kolupaev 已提交
21 22 23 24

namespace DB
{

25 26 27 28 29 30 31
namespace ErrorCodes
{
    extern const int LOGICAL_ERROR;
    extern const int BAD_TYPE_OF_FIELD;
}


32 33
String Range::toString() const
{
34
    std::stringstream str;
35

36 37 38 39
    if (!left_bounded)
        str << "(-inf, ";
    else
        str << (left_included ? '[' : '(') << applyVisitor(FieldVisitorToString(), left) << ", ";
40

41 42 43 44
    if (!right_bounded)
        str << "+inf)";
    else
        str << applyVisitor(FieldVisitorToString(), right) << (right_included ? ']' : ')');
45

46
    return str.str();
47 48
}

49

F
f1yegor 已提交
50
/// Example: for `Hello\_World% ...` string it returns `Hello_World`, and for `%test%` returns an empty string.
51 52
static String extractFixedPrefixFromLikePattern(const String & like_pattern)
{
53 54 55 56 57 58 59 60 61
    String fixed_prefix;

    const char * pos = like_pattern.data();
    const char * end = pos + like_pattern.size();
    while (pos < end)
    {
        switch (*pos)
        {
            case '%':
A
Alexey Milovidov 已提交
62
                [[fallthrough]];
63 64 65 66 67 68 69
            case '_':
                return fixed_prefix;

            case '\\':
                ++pos;
                if (pos == end)
                    break;
A
Alexey Milovidov 已提交
70
                [[fallthrough]];
71 72 73 74 75 76 77 78 79
            default:
                fixed_prefix += *pos;
                break;
        }

        ++pos;
    }

    return fixed_prefix;
80 81 82
}


F
f1yegor 已提交
83 84
/** For a given string, get a minimum string that is strictly greater than all strings with this prefix,
  *  or return an empty string if there are no such strings.
85 86 87
  */
static String firstStringThatIsGreaterThanAllStringsWithPrefix(const String & prefix)
{
88 89 90 91 92 93 94
    /** Increment the last byte of the prefix by one. But if it is 255, then remove it and increase the previous one.
      * Example (for convenience, suppose that the maximum value of byte is `z`)
      * abcx -> abcy
      * abcz -> abd
      * zzz -> empty string
      * z -> empty string
      */
95

96
    String res = prefix;
97

98 99
    while (!res.empty() && static_cast<UInt8>(res.back()) == 255)
        res.pop_back();
100

101 102
    if (res.empty())
        return res;
103

104 105
    res.back() = static_cast<char>(1 + static_cast<UInt8>(res.back()));
    return res;
106 107 108
}


F
f1yegor 已提交
109
/// A dictionary containing actions to the corresponding functions to turn them into `RPNElement`
110
const KeyCondition::AtomMap KeyCondition::atom_map
111
{
112 113
    {
        "notEquals",
114
        [] (RPNElement & out, const Field & value)
115 116 117 118 119 120 121 122
        {
            out.function = RPNElement::FUNCTION_NOT_IN_RANGE;
            out.range = Range(value);
            return true;
        }
    },
    {
        "equals",
123
        [] (RPNElement & out, const Field & value)
124 125 126 127 128 129 130 131
        {
            out.function = RPNElement::FUNCTION_IN_RANGE;
            out.range = Range(value);
            return true;
        }
    },
    {
        "less",
132
        [] (RPNElement & out, const Field & value)
133 134 135 136 137 138 139 140
        {
            out.function = RPNElement::FUNCTION_IN_RANGE;
            out.range = Range::createRightBounded(value, false);
            return true;
        }
    },
    {
        "greater",
141
        [] (RPNElement & out, const Field & value)
142 143 144 145 146 147 148 149
        {
            out.function = RPNElement::FUNCTION_IN_RANGE;
            out.range = Range::createLeftBounded(value, false);
            return true;
        }
    },
    {
        "lessOrEquals",
150
        [] (RPNElement & out, const Field & value)
151 152 153 154 155 156 157 158
        {
            out.function = RPNElement::FUNCTION_IN_RANGE;
            out.range = Range::createRightBounded(value, true);
            return true;
        }
    },
    {
        "greaterOrEquals",
159
        [] (RPNElement & out, const Field & value)
160 161 162 163 164 165 166 167
        {
            out.function = RPNElement::FUNCTION_IN_RANGE;
            out.range = Range::createLeftBounded(value, true);
            return true;
        }
    },
    {
        "in",
168
        [] (RPNElement & out, const Field &)
169 170 171 172 173 174 175
        {
            out.function = RPNElement::FUNCTION_IN_SET;
            return true;
        }
    },
    {
        "notIn",
176
        [] (RPNElement & out, const Field &)
177 178 179 180 181
        {
            out.function = RPNElement::FUNCTION_NOT_IN_SET;
            return true;
        }
    },
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
    {
        "empty",
        [] (RPNElement & out, const Field &)
        {
            out.function = RPNElement::FUNCTION_IN_RANGE;
            out.range = Range("");
            return true;
        }
    },
    {
        "notEmpty",
        [] (RPNElement & out, const Field &)
        {
            out.function = RPNElement::FUNCTION_NOT_IN_RANGE;
            out.range = Range("");
            return true;
        }
    },
200 201
    {
        "like",
D
dimarub2000 已提交
202
        [] (RPNElement & out, const Field & value)
203 204 205 206 207 208 209 210 211 212 213 214
        {
            if (value.getType() != Field::Types::String)
                return false;

            String prefix = extractFixedPrefixFromLikePattern(value.get<const String &>());
            if (prefix.empty())
                return false;

            String right_bound = firstStringThatIsGreaterThanAllStringsWithPrefix(prefix);

            out.function = RPNElement::FUNCTION_IN_RANGE;
            out.range = !right_bound.empty()
D
dimarub2000 已提交
215 216
                ? Range(prefix, true, right_bound, false)
                : Range::createLeftBounded(prefix, true);
D
dimarub2000 已提交
217 218 219 220

            return true;
        }
    },
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
    {
        "notLike",
        [] (RPNElement & out, const Field & value)
        {
            if (value.getType() != Field::Types::String)
                return false;

            String prefix = extractFixedPrefixFromLikePattern(value.get<const String &>());
            if (prefix.empty())
                return false;

            String right_bound = firstStringThatIsGreaterThanAllStringsWithPrefix(prefix);

            out.function = RPNElement::FUNCTION_NOT_IN_RANGE;
            out.range = !right_bound.empty()
                        ? Range(prefix, true, right_bound, false)
                        : Range::createLeftBounded(prefix, true);

            return true;
        }
    },
D
dimarub2000 已提交
242 243 244 245 246 247 248
    {
        "startsWith",
        [] (RPNElement & out, const Field & value)
        {
            if (value.getType() != Field::Types::String)
                return false;

A
alexey-milovidov 已提交
249
            String prefix = value.get<const String &>();
D
dimarub2000 已提交
250 251 252 253 254 255 256
            if (prefix.empty())
                return false;

            String right_bound = firstStringThatIsGreaterThanAllStringsWithPrefix(prefix);

            out.function = RPNElement::FUNCTION_IN_RANGE;
            out.range = !right_bound.empty()
D
dimarub2000 已提交
257 258
                ? Range(prefix, true, right_bound, false)
                : Range::createLeftBounded(prefix, true);
259 260 261 262

            return true;
        }
    }
263 264
};

265

266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
static const std::map<std::string, std::string> inverse_relations = {
        {"equals", "notEquals"},
        {"notEquals", "equals"},
        {"less", "greaterOrEquals"},
        {"greaterOrEquals", "less"},
        {"greater", "lessOrEquals"},
        {"lessOrEquals", "greater"},
        {"in", "notIn"},
        {"notIn", "in"},
        {"like", "notLike"},
        {"notLike", "like"},
        {"empty", "notEmpty"},
        {"notEmpty", "empty"},
};


bool isLogicalOperator(const String & func_name)
{
284
    return (func_name == "and" || func_name == "or" || func_name == "not");
285 286 287
}

/// The node can be one of:
288
///   - Logical operator (AND, OR, NOT)
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
///   - An "atom" (relational operator, constant, expression)
///   - A logical constant expression
///   - Any other function
ASTPtr cloneASTWithInversionPushDown(const ASTPtr node, const bool need_inversion = false)
{
    const ASTFunction * func = node->as<ASTFunction>();

    if (func && isLogicalOperator(func->name))
    {
        if (func->name == "not")
        {
            return cloneASTWithInversionPushDown(func->arguments->children.front(), !need_inversion);
        }

        const auto result_node = makeASTFunction(func->name);

305
        if (need_inversion)
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
        {
            result_node->name = (result_node->name == "and") ? "or" : "and";
        }

        if (func->arguments)
        {
            for (const auto & child : func->arguments->children)
            {
                result_node->arguments->children.push_back(cloneASTWithInversionPushDown(child, need_inversion));
            }
        }

        return result_node;
    }

    const auto cloned_node = node->clone();

    if (func && inverse_relations.find(func->name) != inverse_relations.cend())
    {
        if (need_inversion)
        {
            cloned_node->as<ASTFunction>()->name = inverse_relations.at(func->name);
        }

        return cloned_node;
    }

    return need_inversion ? makeASTFunction("not", cloned_node) : cloned_node;
}


337 338
inline bool Range::equals(const Field & lhs, const Field & rhs) { return applyVisitor(FieldVisitorAccurateEquals(), lhs, rhs); }
inline bool Range::less(const Field & lhs, const Field & rhs) { return applyVisitor(FieldVisitorAccurateLess(), lhs, rhs); }
339 340


341 342 343 344 345 346 347 348 349 350 351 352 353
FieldWithInfinity::FieldWithInfinity(const Field & field_)
    : field(field_),
    type(Type::NORMAL)
{
}

FieldWithInfinity::FieldWithInfinity(Field && field_)
    : field(std::move(field_)),
    type(Type::NORMAL)
{
}

FieldWithInfinity::FieldWithInfinity(const Type type_)
A
Alexey Milovidov 已提交
354
    : type(type_)
355 356 357 358 359 360 361
{
}

FieldWithInfinity FieldWithInfinity::getMinusInfinity()
{
    return FieldWithInfinity(Type::MINUS_INFINITY);
}
A
Alexey Milovidov 已提交
362

363
FieldWithInfinity FieldWithInfinity::getPlusInfinity()
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
{
    return FieldWithInfinity(Type::PLUS_INFINITY);
}

bool FieldWithInfinity::operator<(const FieldWithInfinity & other) const
{
    return type < other.type || (type == other.type && type == Type::NORMAL && field < other.field);
}

bool FieldWithInfinity::operator==(const FieldWithInfinity & other) const
{
    return type == other.type && (type != Type::NORMAL || field == other.field);
}


379 380 381
/** Calculate expressions, that depend only on constants.
  * For index to work when something like "WHERE Date = toDate(now())" is written.
  */
382
Block KeyCondition::getBlockWithConstants(
383
    const ASTPtr & query, const SyntaxAnalyzerResultPtr & syntax_analyzer_result, const Context & context)
384
{
385 386
    Block result
    {
A
Alexey Milovidov 已提交
387
        { DataTypeUInt8().createColumnConstWithDefaultValue(1), std::make_shared<DataTypeUInt8>(), "_dummy" }
388
    };
389

390
    const auto expr_for_constant_folding = ExpressionAnalyzer(query, syntax_analyzer_result, context).getConstActions();
391

392
    expr_for_constant_folding->execute(result);
393

394
    return result;
395 396 397
}


398
KeyCondition::KeyCondition(
399 400
    const SelectQueryInfo & query_info,
    const Context & context,
A
Alexey Milovidov 已提交
401
    const Names & key_column_names,
402
    const ExpressionActionsPtr & key_expr_)
A
Alexey Milovidov 已提交
403
    : key_expr(key_expr_), prepared_sets(query_info.sets)
M
Merge  
Michael Kolupaev 已提交
404
{
A
Alexey Milovidov 已提交
405
    for (size_t i = 0, size = key_column_names.size(); i < size; ++i)
406
    {
A
Alexey Milovidov 已提交
407
        std::string name = key_column_names[i];
408 409
        if (!key_columns.count(name))
            key_columns[name] = i;
410 411
    }

N
Nikita Vasilev 已提交
412 413 414 415 416
    /** Evaluation of expressions that depend only on constants.
      * For the index to be used, if it is written, for example `WHERE Date = toDate(now())`.
      */
    Block block_with_constants = getBlockWithConstants(query_info.query, query_info.syntax_analyzer_result, context);

417 418
    const ASTSelectQuery & select = query_info.query->as<ASTSelectQuery &>();
    if (select.where() || select.prewhere())
N
Nikita Vasilev 已提交
419
    {
420 421 422 423 424 425 426 427 428 429 430 431 432 433
        ASTPtr filter_query;
        if (select.where() && select.prewhere())
            filter_query = makeASTFunction("and", select.where(), select.prewhere());
        else
            filter_query = select.where() ? select.where() : select.prewhere();

        /** When non-strictly monotonic functions are employed in functional index (e.g. ORDER BY toStartOfHour(dateTime)),
          * the use of NOT operator in predicate will result in the indexing algorithm leave out some data.
          * This is caused by rewriting in KeyCondition::tryParseAtomFromAST of relational operators to less strict
          * when parsing the AST into internal RPN representation.
          * To overcome the problem, before parsing the AST we transform it to its semantically equivalent form where all NOT's
          * are pushed down and applied (when possible) to leaf nodes.
          */
        traverseAST(cloneASTWithInversionPushDown(filter_query), context, block_with_constants);
N
Nikita Vasilev 已提交
434 435 436 437 438
    }
    else
    {
        rpn.emplace_back(RPNElement::FUNCTION_UNKNOWN);
    }
M
Merge  
Michael Kolupaev 已提交
439 440
}

441
bool KeyCondition::addCondition(const String & column, const Range & range)
442
{
443
    if (!key_columns.count(column))
444
        return false;
445
    rpn.emplace_back(RPNElement::FUNCTION_IN_RANGE, key_columns[column], range);
446 447
    rpn.emplace_back(RPNElement::FUNCTION_AND);
    return true;
448 449
}

450
/** Computes value of constant expression and its data type.
451
  * Returns false, if expression isn't constant.
452
  */
N
Nikita Vasilev 已提交
453
bool KeyCondition::getConstant(const ASTPtr & expr, Block & block_with_constants, Field & out_value, DataTypePtr & out_type)
M
Merge  
Michael Kolupaev 已提交
454
{
455 456
    String column_name = expr->getColumnName();

I
Ivan Lezhankin 已提交
457
    if (const auto * lit = expr->as<ASTLiteral>())
458 459 460 461 462 463 464 465 466 467 468 469
    {
        /// By default block_with_constants has only one column named "_dummy".
        /// If block contains only constants it's may not be preprocessed by
        //  ExpressionAnalyzer, so try to look up in the default column.
        if (!block_with_constants.has(column_name))
            column_name = "_dummy";

        /// Simple literal
        out_value = lit->value;
        out_type = block_with_constants.getByName(column_name).type;
        return true;
    }
470
    else if (block_with_constants.has(column_name) && isColumnConst(*block_with_constants.getByName(column_name).column))
471 472 473 474 475 476 477 478 479
    {
        /// An expression which is dependent on constants only
        const auto & expr_info = block_with_constants.getByName(column_name);
        out_value = (*expr_info.column)[0];
        out_type = expr_info.type;
        return true;
    }
    else
        return false;
M
Merge  
Michael Kolupaev 已提交
480 481
}

482 483

static void applyFunction(
484
    const FunctionBasePtr & func,
485 486 487
    const DataTypePtr & arg_type, const Field & arg_value,
    DataTypePtr & res_type, Field & res_value)
{
N
Nikolai Kochetov 已提交
488
    res_type = func->getReturnType();
489 490 491

    Block block
    {
492
        { arg_type->createColumnConst(1, arg_value), arg_type, "x" },
493 494 495
        { nullptr, res_type, "y" }
    };

T
Tsarkova Anastasia 已提交
496
    func->execute(block, {0}, 1, 1);
497 498 499 500 501

    block.safeGetByPosition(1).column->get(0, res_value);
}


N
Nikita Vasilev 已提交
502 503 504 505
void KeyCondition::traverseAST(const ASTPtr & node, const Context & context, Block & block_with_constants)
{
    RPNElement element;

506
    if (const auto * func = node->as<ASTFunction>())
N
Nikita Vasilev 已提交
507
    {
508
        if (tryParseLogicalOperatorFromAST(func, element))
N
Nikita Vasilev 已提交
509
        {
510
            auto & args = func->arguments->children;
N
Nikita Vasilev 已提交
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
            for (size_t i = 0, size = args.size(); i < size; ++i)
            {
                traverseAST(args[i], context, block_with_constants);

                /** The first part of the condition is for the correct support of `and` and `or` functions of arbitrary arity
                  * - in this case `n - 1` elements are added (where `n` is the number of arguments).
                  */
                if (i != 0 || element.function == RPNElement::FUNCTION_NOT)
                    rpn.emplace_back(std::move(element));
            }

            return;
        }
    }

526
    if (!tryParseAtomFromAST(node, context, block_with_constants, element))
N
Nikita Vasilev 已提交
527 528 529 530 531 532 533 534
    {
        element.function = RPNElement::FUNCTION_UNKNOWN;
    }

    rpn.emplace_back(std::move(element));
}


535
bool KeyCondition::canConstantBeWrappedByMonotonicFunctions(
536
    const ASTPtr & node,
537 538
    size_t & out_key_column_num,
    DataTypePtr & out_key_column_type,
539 540 541 542
    Field & out_value,
    DataTypePtr & out_type)
{
    String expr_name = node->getColumnName();
543
    const auto & sample_block = key_expr->getSampleBlock();
544 545 546 547
    if (!sample_block.has(expr_name))
        return false;

    bool found_transformation = false;
548
    for (const ExpressionAction & a : key_expr->getActions())
549
    {
550 551
        /** The key functional expression constraint may be inferred from a plain column in the expression.
          * For example, if the key contains `toStartOfHour(Timestamp)` and query contains `WHERE Timestamp >= now()`,
552 553 554 555 556 557 558 559 560 561 562
          * it can be assumed that if `toStartOfHour()` is monotonic on [now(), inf), the `toStartOfHour(Timestamp) >= toStartOfHour(now())`
          * condition also holds, so the index may be used to select only parts satisfying this condition.
          *
          * To check the assumption, we'd need to assert that the inverse function to this transformation is also monotonic, however the
          * inversion isn't exported (or even viable for not strictly monotonic functions such as `toStartOfHour()`).
          * Instead, we can qualify only functions that do not transform the range (for example rounding),
          * which while not strictly monotonic, are monotonic everywhere on the input range.
          */
        const auto & action = a.argument_names;
        if (a.type == ExpressionAction::Type::APPLY_FUNCTION && action.size() == 1 && a.argument_names[0] == expr_name)
        {
563
            if (!a.function_base->hasInformationAboutMonotonicity())
564 565 566
                return false;

            // Range is irrelevant in this case
567
            IFunction::Monotonicity monotonicity = a.function_base->getMonotonicityForRange(*out_type, Field(), Field());
568 569 570 571 572
            if (!monotonicity.is_always_monotonic)
                return false;

            // Apply the next transformation step
            DataTypePtr new_type;
573
            applyFunction(a.function_base, out_type, out_value, new_type, out_value);
574 575 576 577 578 579
            if (!new_type)
                return false;

            out_type.swap(new_type);
            expr_name = a.result_name;

580
            // Transformation results in a key expression, accept
581 582
            auto it = key_columns.find(expr_name);
            if (key_columns.end() != it)
583
            {
584 585
                out_key_column_num = it->second;
                out_key_column_type = sample_block.getByName(it->first).type;
586 587 588 589 590 591 592 593 594
                found_transformation = true;
                break;
            }
        }
    }

    return found_transformation;
}

A
Alexey Milovidov 已提交
595
bool KeyCondition::tryPrepareSetIndex(
596
    const ASTs & args,
597 598
    const Context & context,
    RPNElement & out,
599
    size_t & out_key_column_num)
600
{
601
    const ASTPtr & left_arg = args[0];
A
Alexey Milovidov 已提交
602

603 604
    out_key_column_num = 0;
    std::vector<MergeTreeSetIndex::KeyTuplePositionMapping> indexes_mapping;
605
    DataTypes data_types;
606

607
    auto get_key_tuple_position_mapping = [&](const ASTPtr & node, size_t tuple_index)
608
    {
609 610 611 612 613
        MergeTreeSetIndex::KeyTuplePositionMapping index_mapping;
        index_mapping.tuple_index = tuple_index;
        DataTypePtr data_type;
        if (isKeyPossiblyWrappedByMonotonicFunctions(
                node, context, index_mapping.key_index, data_type, index_mapping.functions))
614
        {
615 616 617 618
            indexes_mapping.push_back(index_mapping);
            data_types.push_back(data_type);
            if (out_key_column_num < index_mapping.key_index)
                out_key_column_num = index_mapping.key_index;
619
        }
620
    };
621

622
    size_t left_args_count = 1;
I
Ivan Lezhankin 已提交
623
    const auto * left_arg_tuple = left_arg->as<ASTFunction>();
624
    if (left_arg_tuple && left_arg_tuple->name == "tuple")
625
    {
626
        const auto & tuple_elements = left_arg_tuple->arguments->children;
627 628
        left_args_count = tuple_elements.size();
        for (size_t i = 0; i < left_args_count; ++i)
629
            get_key_tuple_position_mapping(tuple_elements[i], i);
630
    }
631 632
    else
        get_key_tuple_position_mapping(left_arg, 0);
633 634 635 636

    if (indexes_mapping.empty())
        return false;

637 638 639
    const ASTPtr & right_arg = args[1];

    PreparedSetKey set_key;
I
Ivan Lezhankin 已提交
640
    if (right_arg->as<ASTSubquery>() || right_arg->as<ASTIdentifier>())
641 642 643 644 645 646 647 648 649 650 651 652 653 654
        set_key = PreparedSetKey::forSubquery(*right_arg);
    else
        set_key = PreparedSetKey::forLiteral(*right_arg, data_types);

    auto set_it = prepared_sets.find(set_key);
    if (set_it == prepared_sets.end())
        return false;

    const SetPtr & prepared_set = set_it->second;

    /// The index can be prepared if the elements of the set were saved in advance.
    if (!prepared_set->hasExplicitSetElements())
        return false;

655 656 657 658
    prepared_set->checkColumnsNumber(left_args_count);
    for (size_t i = 0; i < indexes_mapping.size(); ++i)
        prepared_set->checkTypesEqual(indexes_mapping[i].tuple_index, removeLowCardinality(data_types[i]));

A
Alexey Milovidov 已提交
659
    out.set_index = std::make_shared<MergeTreeSetIndex>(prepared_set->getSetElements(), std::move(indexes_mapping));
660 661 662

    return true;
}
663

664

665
bool KeyCondition::isKeyPossiblyWrappedByMonotonicFunctions(
666 667
    const ASTPtr & node,
    const Context & context,
668 669
    size_t & out_key_column_num,
    DataTypePtr & out_key_res_column_type,
670
    MonotonicFunctionsChain & out_functions_chain)
M
Merge  
Michael Kolupaev 已提交
671
{
672
    std::vector<const ASTFunction *> chain_not_tested_for_monotonicity;
673
    DataTypePtr key_column_type;
674

675
    if (!isKeyPossiblyWrappedByMonotonicFunctionsImpl(node, out_key_column_num, key_column_type, chain_not_tested_for_monotonicity))
676
        return false;
677

678 679
    for (auto it = chain_not_tested_for_monotonicity.rbegin(); it != chain_not_tested_for_monotonicity.rend(); ++it)
    {
N
Nikolai Kochetov 已提交
680
        auto func_builder = FunctionFactory::instance().tryGet((*it)->name, context);
681
        ColumnsWithTypeAndName arguments{{ nullptr, key_column_type, "" }};
N
Nikolai Kochetov 已提交
682 683
        auto func = func_builder->build(arguments);

684 685
        if (!func || !func->hasInformationAboutMonotonicity())
            return false;
686

687
        key_column_type = func->getReturnType();
688 689
        out_functions_chain.push_back(func);
    }
690

691
    out_key_res_column_type = key_column_type;
692

693
    return true;
694 695
}

696
bool KeyCondition::isKeyPossiblyWrappedByMonotonicFunctionsImpl(
697
    const ASTPtr & node,
698 699
    size_t & out_key_column_num,
    DataTypePtr & out_key_column_type,
700
    std::vector<const ASTFunction *> & out_functions_chain)
701
{
702
    /** By itself, the key column can be a functional expression. for example, `intHash32(UserID)`.
703 704
      * Therefore, use the full name of the expression for search.
      */
705
    const auto & sample_block = key_expr->getSampleBlock();
706 707
    String name = node->getColumnName();

708 709
    auto it = key_columns.find(name);
    if (key_columns.end() != it)
710
    {
711 712
        out_key_column_num = it->second;
        out_key_column_type = sample_block.getByName(it->first).type;
713 714 715
        return true;
    }

I
Ivan Lezhankin 已提交
716
    if (const auto * func = node->as<ASTFunction>())
717 718 719 720 721 722 723
    {
        const auto & args = func->arguments->children;
        if (args.size() != 1)
            return false;

        out_functions_chain.push_back(func);

A
Alexey Milovidov 已提交
724
        return isKeyPossiblyWrappedByMonotonicFunctionsImpl(args[0], out_key_column_num, out_key_column_type, out_functions_chain);
725 726 727
    }

    return false;
728 729 730
}


731
static void castValueToType(const DataTypePtr & desired_type, Field & src_value, const DataTypePtr & src_type, const ASTPtr & node)
732
{
733 734 735 736 737 738 739 740 741 742
    if (desired_type->equals(*src_type))
        return;

    try
    {
        /// NOTE: We don't need accurate info about src_type at this moment
        src_value = convertFieldToType(src_value, *desired_type);
    }
    catch (...)
    {
743
        throw Exception("Key expression contains comparison between inconvertible types: " +
744
            desired_type->getName() + " and " + src_type->getName() +
A
Alexey Milovidov 已提交
745
            " inside " + queryToString(node),
746 747
            ErrorCodes::BAD_TYPE_OF_FIELD);
    }
748 749 750
}


751
bool KeyCondition::tryParseAtomFromAST(const ASTPtr & node, const Context & context, Block & block_with_constants, RPNElement & out)
752
{
753
    /** Functions < > = != <= >= in `notIn`, where one argument is a constant, and the other is one of columns of key,
A
Alexey Milovidov 已提交
754
      *  or itself, wrapped in a chain of possibly-monotonic functions,
755 756 757 758
      *  or constant expression - number.
      */
    Field const_value;
    DataTypePtr const_type;
I
Ivan Lezhankin 已提交
759
    if (const auto * func = node->as<ASTFunction>())
760
    {
761
        const ASTs & args = func->arguments->children;
762

763
        DataTypePtr key_expr_type;    /// Type of expression containing key column
764
        size_t key_column_num = -1;   /// Number of a key column (inside key_column_names array)
765
        MonotonicFunctionsChain chain;
766
        std::string func_name = func->name;
767

768 769 770
        if (atom_map.find(func_name) == std::end(atom_map))
            return false;

771
        if (args.size() == 1)
772
        {
773 774 775 776 777
            if (!(isKeyPossiblyWrappedByMonotonicFunctions(args[0], context, key_column_num, key_expr_type, chain)))
                return false;

            if (key_column_num == static_cast<size_t>(-1))
                throw Exception("`key_column_num` wasn't initialized. It is a bug.", ErrorCodes::LOGICAL_ERROR);
778
        }
779
        else if (args.size() == 2)
780
        {
781 782 783
            size_t key_arg_pos;           /// Position of argument with key column (non-const argument)
            bool is_set_const = false;
            bool is_constant_transformed = false;
784

785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
            if (functionIsInOrGlobalInOperator(func_name)
                && tryPrepareSetIndex(args, context, out, key_column_num))
            {
                key_arg_pos = 0;
                is_set_const = true;
            }
            else if (getConstant(args[1], block_with_constants, const_value, const_type)
                     && isKeyPossiblyWrappedByMonotonicFunctions(args[0], context, key_column_num, key_expr_type, chain))
            {
                key_arg_pos = 0;
            }
            else if (getConstant(args[1], block_with_constants, const_value, const_type)
                     && canConstantBeWrappedByMonotonicFunctions(args[0], key_column_num, key_expr_type, const_value, const_type))
            {
                key_arg_pos = 0;
                is_constant_transformed = true;
            }
            else if (getConstant(args[0], block_with_constants, const_value, const_type)
                     && isKeyPossiblyWrappedByMonotonicFunctions(args[1], context, key_column_num, key_expr_type, chain))
            {
                key_arg_pos = 1;
            }
            else if (getConstant(args[0], block_with_constants, const_value, const_type)
                     && canConstantBeWrappedByMonotonicFunctions(args[1], key_column_num, key_expr_type, const_value, const_type))
            {
                key_arg_pos = 1;
                is_constant_transformed = true;
            }
            else
                return false;
815

816 817
            if (key_column_num == static_cast<size_t>(-1))
                throw Exception("`key_column_num` wasn't initialized. It is a bug.", ErrorCodes::LOGICAL_ERROR);
818

819 820 821 822 823 824 825 826
            /// Transformed constant must weaken the condition, for example "x > 5" must weaken to "round(x) >= 5"
            if (is_constant_transformed)
            {
                if (func_name == "less")
                    func_name = "lessOrEquals";
                else if (func_name == "greater")
                    func_name = "greaterOrEquals";
            }
827

828 829
            /// Replace <const> <sign> <data> on to <data> <-sign> <const>
            if (key_arg_pos == 1)
830
            {
831 832 833 834 835 836 837 838
                if (func_name == "less")
                    func_name = "greater";
                else if (func_name == "greater")
                    func_name = "less";
                else if (func_name == "greaterOrEquals")
                    func_name = "lessOrEquals";
                else if (func_name == "lessOrEquals")
                    func_name = "greaterOrEquals";
839 840 841
                else if (func_name == "in" || func_name == "notIn" ||
                         func_name == "like" || func_name == "notLike" ||
                         func_name == "startsWith")
842 843 844 845
                {
                    /// "const IN data_column" doesn't make sense (unlike "data_column IN const")
                    return false;
                }
846 847
            }

848 849 850 851 852 853 854 855 856
            bool cast_not_needed =
                    is_set_const /// Set args are already casted inside Set::createFromAST
                    || (isNativeNumber(key_expr_type) && isNativeNumber(const_type)); /// Numbers are accurately compared without cast.

            if (!cast_not_needed)
                castValueToType(key_expr_type, const_value, const_type, node);
        }
        else
            return false;
857 858 859

        const auto atom_it = atom_map.find(func_name);

860 861
        out.key_column = key_column_num;
        out.monotonic_functions_chain = std::move(chain);
862

863
        return atom_it->second(out, const_value);
864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
    }
    else if (getConstant(node, block_with_constants, const_value, const_type))    /// For cases where it says, for example, `WHERE 0 AND something`
    {
        if (const_value.getType() == Field::Types::UInt64
            || const_value.getType() == Field::Types::Int64
            || const_value.getType() == Field::Types::Float64)
        {
            /// Zero in all types is represented in memory the same way as in UInt64.
            out.function = const_value.get<UInt64>()
                ? RPNElement::ALWAYS_TRUE
                : RPNElement::ALWAYS_FALSE;

            return true;
        }
    }
    return false;
M
Merge  
Michael Kolupaev 已提交
880 881
}

882
bool KeyCondition::tryParseLogicalOperatorFromAST(const ASTFunction * func, RPNElement & out)
N
Nikita Vasilev 已提交
883 884
{
    /// Functions AND, OR, NOT.
885
    const ASTs & args = func->arguments->children;
N
Nikita Vasilev 已提交
886 887 888 889 890 891 892 893 894 895

    if (func->name == "not")
    {
        if (args.size() != 1)
            return false;

        out.function = RPNElement::FUNCTION_NOT;
    }
    else
    {
896
        if (func->name == "and")
N
Nikita Vasilev 已提交
897 898 899 900 901 902 903 904 905 906
            out.function = RPNElement::FUNCTION_AND;
        else if (func->name == "or")
            out.function = RPNElement::FUNCTION_OR;
        else
            return false;
    }

    return true;
}

907
String KeyCondition::toString() const
M
Merge  
Michael Kolupaev 已提交
908
{
909 910 911 912 913 914 915 916
    String res;
    for (size_t i = 0; i < rpn.size(); ++i)
    {
        if (i)
            res += ", ";
        res += rpn[i].toString();
    }
    return res;
M
Merge  
Michael Kolupaev 已提交
917 918
}

919

920
/** Index is the value of key every `index_granularity` rows.
F
f1yegor 已提交
921
  * This value is called a "mark". That is, the index consists of marks.
922
  *
923 924
  * The key is the tuple.
  * The data is sorted by key in the sense of lexicographic order over tuples.
925
  *
F
f1yegor 已提交
926 927
  * A pair of marks specifies a segment with respect to the order over the tuples.
  * Denote it like this: [ x1 y1 z1 .. x2 y2 z2 ],
928 929
  *  where x1 y1 z1 - tuple - value of key in left border of segment;
  *        x2 y2 z2 - tuple - value of key in right boundary of segment.
F
f1yegor 已提交
930
  * In this section there are data between these marks.
931
  *
F
f1yegor 已提交
932
  * Or, the last mark specifies the range open on the right: [ a b c .. + inf )
933
  *
F
f1yegor 已提交
934 935
  * The set of all possible tuples can be considered as an n-dimensional space, where n is the size of the tuple.
  * A range of tuples specifies some subset of this space.
936
  *
F
f1yegor 已提交
937 938 939
  * Parallelograms (you can also find the term "rail")
  *  will be the subrange of an n-dimensional space that is a direct product of one-dimensional ranges.
  * In this case, the one-dimensional range can be: a period, a segment, an interval, a half-interval, unlimited on the left, unlimited on the right ...
940
  *
F
f1yegor 已提交
941 942
  * The range of tuples can always be represented as a combination of parallelograms.
  * For example, the range [ x1 y1 .. x2 y2 ] given x1 != x2 is equal to the union of the following three parallelograms:
943 944 945 946
  * [x1]       x [y1 .. +inf)
  * (x1 .. x2) x (-inf .. +inf)
  * [x2]       x (-inf .. y2]
  *
F
f1yegor 已提交
947
  * Or, for example, the range [ x1 y1 .. +inf ] is equal to the union of the following two parallelograms:
948 949
  * [x1]         x [y1 .. +inf)
  * (x1 .. +inf) x (-inf .. +inf)
F
f1yegor 已提交
950
  * It's easy to see that this is a special case of the variant above.
951
  *
F
f1yegor 已提交
952 953 954
  * This is important because it is easy for us to check the feasibility of the condition over the parallelogram,
  *  and therefore, feasibility of condition on the range of tuples will be checked by feasibility of condition
  *  over at least one parallelogram from which this range consists.
955 956 957
  */

template <typename F>
958
static BoolMask forAnyParallelogram(
959 960 961 962 963 964 965
    size_t key_size,
    const Field * key_left,
    const Field * key_right,
    bool left_bounded,
    bool right_bounded,
    std::vector<Range> & parallelogram,
    size_t prefix_size,
966
    BoolMask initial_mask,
967
    F && callback)
M
Merge  
Michael Kolupaev 已提交
968
{
969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
    if (!left_bounded && !right_bounded)
        return callback(parallelogram);

    if (left_bounded && right_bounded)
    {
        /// Let's go through the matching elements of the key.
        while (prefix_size < key_size)
        {
            if (key_left[prefix_size] == key_right[prefix_size])
            {
                /// Point ranges.
                parallelogram[prefix_size] = Range(key_left[prefix_size]);
                ++prefix_size;
            }
            else
                break;
        }
    }

    if (prefix_size == key_size)
        return callback(parallelogram);

    if (prefix_size + 1 == key_size)
    {
        if (left_bounded && right_bounded)
            parallelogram[prefix_size] = Range(key_left[prefix_size], true, key_right[prefix_size], true);
        else if (left_bounded)
            parallelogram[prefix_size] = Range::createLeftBounded(key_left[prefix_size], true);
        else if (right_bounded)
            parallelogram[prefix_size] = Range::createRightBounded(key_right[prefix_size], true);

        return callback(parallelogram);
    }

    /// (x1 .. x2) x (-inf .. +inf)

    if (left_bounded && right_bounded)
        parallelogram[prefix_size] = Range(key_left[prefix_size], false, key_right[prefix_size], false);
    else if (left_bounded)
        parallelogram[prefix_size] = Range::createLeftBounded(key_left[prefix_size], false);
    else if (right_bounded)
        parallelogram[prefix_size] = Range::createRightBounded(key_right[prefix_size], false);

    for (size_t i = prefix_size + 1; i < key_size; ++i)
        parallelogram[i] = Range();

1015 1016 1017 1018 1019 1020 1021 1022

    BoolMask result = initial_mask;
    result = result | callback(parallelogram);

    /// There are several early-exit conditions (like the one below) hereinafter.
    /// They are important; in particular, if initial_mask == BoolMask::consider_only_can_be_true
    /// (which happens when this routine is called from KeyCondition::mayBeTrueXXX),
    /// they provide significant speedup, which may be observed on merge_tree_huge_pk performance test.
M
Maxim Akhmedov 已提交
1023
    if (result.isComplete())
1024
        return result;
1025 1026 1027 1028 1029 1030

    /// [x1]       x [y1 .. +inf)

    if (left_bounded)
    {
        parallelogram[prefix_size] = Range(key_left[prefix_size]);
1031
        result = result | forAnyParallelogram(key_size, key_left, key_right, true, false, parallelogram, prefix_size + 1, initial_mask, callback);
M
Maxim Akhmedov 已提交
1032
        if (result.isComplete())
1033
            return result;
1034 1035 1036 1037 1038 1039 1040
    }

    /// [x2]       x (-inf .. y2]

    if (right_bounded)
    {
        parallelogram[prefix_size] = Range(key_right[prefix_size]);
1041
        result = result | forAnyParallelogram(key_size, key_left, key_right, false, true, parallelogram, prefix_size + 1, initial_mask, callback);
M
Maxim Akhmedov 已提交
1042
        if (result.isComplete())
1043
            return result;
1044 1045
    }

1046
    return result;
1047 1048 1049
}


1050
BoolMask KeyCondition::checkInRange(
1051
    size_t used_key_size,
1052 1053
    const Field * left_key,
    const Field * right_key,
1054
    const DataTypes & data_types,
1055 1056
    bool right_bounded,
    BoolMask initial_mask) const
1057
{
1058 1059
    std::vector<Range> key_ranges(used_key_size, Range());

1060
/*  std::cerr << "Checking for: [";
1061
    for (size_t i = 0; i != used_key_size; ++i)
1062
        std::cerr << (i != 0 ? ", " : "") << applyVisitor(FieldVisitorToString(), left_key[i]);
1063 1064 1065 1066 1067
    std::cerr << " ... ";

    if (right_bounded)
    {
        for (size_t i = 0; i != used_key_size; ++i)
1068
            std::cerr << (i != 0 ? ", " : "") << applyVisitor(FieldVisitorToString(), right_key[i]);
1069 1070 1071 1072 1073
        std::cerr << "]\n";
    }
    else
        std::cerr << "+inf)\n";*/

1074
    return forAnyParallelogram(used_key_size, left_key, right_key, true, right_bounded, key_ranges, 0, initial_mask,
1075
        [&] (const std::vector<Range> & key_ranges_parallelogram)
1076
    {
1077
        auto res = checkInParallelogram(key_ranges_parallelogram, data_types);
1078

1079
/*      std::cerr << "Parallelogram: ";
1080 1081 1082 1083 1084 1085
        for (size_t i = 0, size = key_ranges.size(); i != size; ++i)
            std::cerr << (i != 0 ? " x " : "") << key_ranges[i].toString();
        std::cerr << ": " << res << "\n";*/

        return res;
    });
1086 1087
}

1088

1089
std::optional<Range> KeyCondition::applyMonotonicFunctionsChainToRange(
1090
    Range key_range,
1091
    MonotonicFunctionsChain & functions,
1092
    DataTypePtr current_type)
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
{
    for (auto & func : functions)
    {
        /// We check the monotonicity of each function on a specific range.
        IFunction::Monotonicity monotonicity = func->getMonotonicityForRange(
            *current_type.get(), key_range.left, key_range.right);

        if (!monotonicity.is_monotonic)
        {
            return {};
        }

        /// Apply the function.
        DataTypePtr new_type;
        if (!key_range.left.isNull())
            applyFunction(func, current_type, key_range.left, new_type, key_range.left);
        if (!key_range.right.isNull())
            applyFunction(func, current_type, key_range.right, new_type, key_range.right);

        if (!new_type)
        {
            return {};
        }

        current_type.swap(new_type);

        if (!monotonicity.is_positive)
            key_range.swapLeftAndRight();
    }
    return key_range;
}
1124

1125 1126 1127
BoolMask KeyCondition::checkInParallelogram(
    const std::vector<Range> & parallelogram,
    const DataTypes & data_types) const
1128
{
1129
    std::vector<BoolMask> rpn_stack;
A
Alexey Milovidov 已提交
1130
    for (const auto & element : rpn)
1131 1132 1133 1134 1135 1136
    {
        if (element.function == RPNElement::FUNCTION_UNKNOWN)
        {
            rpn_stack.emplace_back(true, true);
        }
        else if (element.function == RPNElement::FUNCTION_IN_RANGE
1137
            || element.function == RPNElement::FUNCTION_NOT_IN_RANGE)
1138
        {
1139
            const Range * key_range = &parallelogram[element.key_column];
1140

1141
            /// The case when the column is wrapped in a chain of possibly monotonic functions.
1142
            Range transformed_range;
1143 1144
            if (!element.monotonic_functions_chain.empty())
            {
1145 1146 1147 1148 1149
                std::optional<Range> new_range = applyMonotonicFunctionsChainToRange(
                    *key_range,
                    element.monotonic_functions_chain,
                    data_types[element.key_column]
                );
1150

1151
                if (!new_range)
1152 1153 1154 1155
                {
                    rpn_stack.emplace_back(true, true);
                    continue;
                }
1156 1157
                transformed_range = *new_range;
                key_range = &transformed_range;
1158 1159
            }

1160 1161
            bool intersects = element.range.intersectsRange(*key_range);
            bool contains = element.range.containsRange(*key_range);
1162

1163 1164 1165 1166 1167 1168 1169 1170
            rpn_stack.emplace_back(intersects, !contains);
            if (element.function == RPNElement::FUNCTION_NOT_IN_RANGE)
                rpn_stack.back() = !rpn_stack.back();
        }
        else if (
            element.function == RPNElement::FUNCTION_IN_SET
            || element.function == RPNElement::FUNCTION_NOT_IN_SET)
        {
1171
            if (!element.set_index)
A
Alexey Milovidov 已提交
1172
                throw Exception("Set for IN is not created yet", ErrorCodes::LOGICAL_ERROR);
1173

1174
            rpn_stack.emplace_back(element.set_index->checkInRange(parallelogram, data_types));
1175 1176
            if (element.function == RPNElement::FUNCTION_NOT_IN_SET)
                rpn_stack.back() = !rpn_stack.back();
1177 1178 1179
        }
        else if (element.function == RPNElement::FUNCTION_NOT)
        {
1180 1181
            assert(!rpn_stack.empty());

1182 1183 1184 1185
            rpn_stack.back() = !rpn_stack.back();
        }
        else if (element.function == RPNElement::FUNCTION_AND)
        {
1186 1187
            assert(!rpn_stack.empty());

1188 1189 1190 1191 1192 1193 1194
            auto arg1 = rpn_stack.back();
            rpn_stack.pop_back();
            auto arg2 = rpn_stack.back();
            rpn_stack.back() = arg1 & arg2;
        }
        else if (element.function == RPNElement::FUNCTION_OR)
        {
1195 1196
            assert(!rpn_stack.empty());

1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
            auto arg1 = rpn_stack.back();
            rpn_stack.pop_back();
            auto arg2 = rpn_stack.back();
            rpn_stack.back() = arg1 | arg2;
        }
        else if (element.function == RPNElement::ALWAYS_FALSE)
        {
            rpn_stack.emplace_back(false, true);
        }
        else if (element.function == RPNElement::ALWAYS_TRUE)
        {
            rpn_stack.emplace_back(true, false);
        }
        else
1211
            throw Exception("Unexpected function type in KeyCondition::RPNElement", ErrorCodes::LOGICAL_ERROR);
1212 1213 1214
    }

    if (rpn_stack.size() != 1)
1215
        throw Exception("Unexpected stack size in KeyCondition::checkInRange", ErrorCodes::LOGICAL_ERROR);
1216

1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
    return rpn_stack[0];
}


BoolMask KeyCondition::checkInRange(
    size_t used_key_size,
    const Field * left_key,
    const Field * right_key,
    const DataTypes & data_types,
    BoolMask initial_mask) const
{
    return checkInRange(used_key_size, left_key, right_key, data_types, true, initial_mask);
M
Merge  
Michael Kolupaev 已提交
1229 1230
}

1231

1232
bool KeyCondition::mayBeTrueInRange(
1233 1234 1235 1236
    size_t used_key_size,
    const Field * left_key,
    const Field * right_key,
    const DataTypes & data_types) const
M
Merge  
Michael Kolupaev 已提交
1237
{
1238
    return checkInRange(used_key_size, left_key, right_key, data_types, true, BoolMask::consider_only_can_be_true).can_be_true;
M
Merge  
Michael Kolupaev 已提交
1239 1240
}

1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251

BoolMask KeyCondition::checkAfter(
    size_t used_key_size,
    const Field * left_key,
    const DataTypes & data_types,
    BoolMask initial_mask) const
{
    return checkInRange(used_key_size, left_key, nullptr, data_types, false, initial_mask);
}


1252
bool KeyCondition::mayBeTrueAfter(
1253 1254 1255
    size_t used_key_size,
    const Field * left_key,
    const DataTypes & data_types) const
M
Merge  
Michael Kolupaev 已提交
1256
{
1257
    return checkInRange(used_key_size, left_key, nullptr, data_types, false, BoolMask::consider_only_can_be_true).can_be_true;
M
Merge  
Michael Kolupaev 已提交
1258 1259
}

1260

1261
String KeyCondition::RPNElement::toString() const
1262
{
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
    auto print_wrapped_column = [this](std::ostringstream & ss)
    {
        for (auto it = monotonic_functions_chain.rbegin(); it != monotonic_functions_chain.rend(); ++it)
            ss << (*it)->getName() << "(";

        ss << "column " << key_column;

        for (auto it = monotonic_functions_chain.rbegin(); it != monotonic_functions_chain.rend(); ++it)
            ss << ")";
    };

    std::ostringstream ss;
    switch (function)
    {
        case FUNCTION_AND:
            return "and";
        case FUNCTION_OR:
            return "or";
        case FUNCTION_NOT:
            return "not";
        case FUNCTION_UNKNOWN:
            return "unknown";
        case FUNCTION_NOT_IN_SET:
        case FUNCTION_IN_SET:
        {
            ss << "(";
            print_wrapped_column(ss);
A
Alexey Milovidov 已提交
1290
            ss << (function == FUNCTION_IN_SET ? " in " : " notIn ");
A
Alexey Milovidov 已提交
1291 1292 1293 1294
            if (!set_index)
                ss << "unknown size set";
            else
                ss << set_index->size() << "-element set";
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
            ss << ")";
            return ss.str();
        }
        case FUNCTION_IN_RANGE:
        case FUNCTION_NOT_IN_RANGE:
        {
            ss << "(";
            print_wrapped_column(ss);
            ss << (function == FUNCTION_NOT_IN_RANGE ? " not" : "") << " in " << range.toString();
            ss << ")";
            return ss.str();
        }
        case ALWAYS_FALSE:
            return "false";
        case ALWAYS_TRUE:
            return "true";
    }
1312 1313

    __builtin_unreachable();
1314
}
1315 1316


1317
bool KeyCondition::alwaysUnknownOrTrue() const
1318
{
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
    std::vector<UInt8> rpn_stack;

    for (const auto & element : rpn)
    {
        if (element.function == RPNElement::FUNCTION_UNKNOWN
            || element.function == RPNElement::ALWAYS_TRUE)
        {
            rpn_stack.push_back(true);
        }
        else if (element.function == RPNElement::FUNCTION_NOT_IN_RANGE
            || element.function == RPNElement::FUNCTION_IN_RANGE
            || element.function == RPNElement::FUNCTION_IN_SET
            || element.function == RPNElement::FUNCTION_NOT_IN_SET
            || element.function == RPNElement::ALWAYS_FALSE)
        {
            rpn_stack.push_back(false);
        }
        else if (element.function == RPNElement::FUNCTION_NOT)
        {
        }
        else if (element.function == RPNElement::FUNCTION_AND)
        {
1341 1342
            assert(!rpn_stack.empty());

1343 1344 1345 1346 1347 1348 1349
            auto arg1 = rpn_stack.back();
            rpn_stack.pop_back();
            auto arg2 = rpn_stack.back();
            rpn_stack.back() = arg1 & arg2;
        }
        else if (element.function == RPNElement::FUNCTION_OR)
        {
1350 1351
            assert(!rpn_stack.empty());

1352 1353 1354 1355 1356 1357
            auto arg1 = rpn_stack.back();
            rpn_stack.pop_back();
            auto arg2 = rpn_stack.back();
            rpn_stack.back() = arg1 | arg2;
        }
        else
1358
            throw Exception("Unexpected function type in KeyCondition::RPNElement", ErrorCodes::LOGICAL_ERROR);
1359 1360
    }

1361
    if (rpn_stack.size() != 1)
A
alexey-milovidov 已提交
1362
        throw Exception("Unexpected stack size in KeyCondition::alwaysUnknownOrTrue", ErrorCodes::LOGICAL_ERROR);
1363

1364
    return rpn_stack[0];
1365 1366 1367
}


1368
size_t KeyCondition::getMaxKeyColumn() const
1369
{
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
    size_t res = 0;
    for (const auto & element : rpn)
    {
        if (element.function == RPNElement::FUNCTION_NOT_IN_RANGE
            || element.function == RPNElement::FUNCTION_IN_RANGE
            || element.function == RPNElement::FUNCTION_IN_SET
            || element.function == RPNElement::FUNCTION_NOT_IN_SET)
        {
            if (element.key_column > res)
                res = element.key_column;
        }
    }
    return res;
1383 1384
}

M
Merge  
Michael Kolupaev 已提交
1385
}