forked from alibaba/AliSQL
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrange_analysis.cc
More file actions
1737 lines (1548 loc) · 66.9 KB
/
range_analysis.cc
File metadata and controls
1737 lines (1548 loc) · 66.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
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
339
340
341
342
343
344
345
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
376
377
378
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
431
432
433
434
435
436
437
438
439
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
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
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
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
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
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
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
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
/* Copyright (c) 2000, 2025, Oracle and/or its affiliates.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is designed to work with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have either included with
the program or referenced in the documentation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
#include <assert.h>
#include <string.h>
#include <sys/types.h>
#include "field_types.h"
#include "m_ctype.h"
#include "memory_debugging.h"
#include "mf_wcomp.h"
#include "my_alloc.h"
#include "my_base.h"
#include "my_byteorder.h"
#include "my_compiler.h"
#include "my_dbug.h"
#include "my_inttypes.h"
#include "my_table_map.h"
#include "mysql/udf_registration_types.h"
#include "mysql_com.h"
#include "mysqld_error.h"
#include "sql-common/json_dom.h"
#include "sql/current_thd.h"
#include "sql/derror.h"
#include "sql/field.h"
#include "sql/handler.h"
#include "sql/item.h"
#include "sql/item_cmpfunc.h"
#include "sql/item_func.h"
#include "sql/item_json_func.h"
#include "sql/item_row.h"
#include "sql/key.h"
#include "sql/mem_root_array.h"
#include "sql/opt_trace.h"
#include "sql/opt_trace_context.h"
#include "sql/query_options.h"
#include "sql/range_optimizer/internal.h"
#include "sql/range_optimizer/range_optimizer.h"
#include "sql/range_optimizer/tree.h"
#include "sql/sql_bitmap.h"
#include "sql/sql_class.h"
#include "sql/sql_const.h"
#include "sql/sql_error.h"
#include "sql/sql_lex.h"
#include "sql/sql_list.h"
#include "sql/sql_optimizer.h"
#include "sql/system_variables.h"
#include "sql/table.h"
#include "sql_string.h"
#include "template_utils.h"
/*
A null_sel_tree is used in get_func_mm_tree_from_in_predicate to pass
as an argument to tree_or. It is used only to influence the return
value from tree_or function.
*/
static MEM_ROOT null_root;
static SEL_TREE null_sel_tree(SEL_TREE::IMPOSSIBLE, &null_root, 0);
static uchar is_null_string[2] = {1, 0};
static SEL_TREE *get_mm_parts(THD *thd, RANGE_OPT_PARAM *param,
table_map prev_tables, table_map read_tables,
Item_func *cond_func, Field *field,
Item_func::Functype type, Item *value);
static SEL_ROOT *get_mm_leaf(THD *thd, RANGE_OPT_PARAM *param, Item *cond_func,
Field *field, KEY_PART *key_part,
Item_func::Functype type, Item *value,
bool *inexact);
static SEL_TREE *get_full_func_mm_tree(THD *thd, RANGE_OPT_PARAM *param,
table_map prev_tables,
table_map read_tables,
table_map current_table,
bool remove_jump_scans, Item *predicand,
Item_func *op, Item *value, bool inv);
static SEL_ROOT *sel_add(SEL_ROOT *key1, SEL_ROOT *key2);
/**
If EXPLAIN or if the --safe-updates option is enabled, add a warning that
the index cannot be used for range access due to either type conversion or
different collations on the field used for comparison
@param thd Thread handle
@param param RANGE_OPT_PARAM from test_quick_select
@param key_num Key number
@param field Field in the predicate
*/
static void warn_index_not_applicable(THD *thd, const RANGE_OPT_PARAM *param,
const uint key_num, const Field *field) {
if (param->using_real_indexes &&
(thd->lex->is_explain() ||
thd->variables.option_bits & OPTION_SAFE_UPDATES))
push_warning_printf(thd, Sql_condition::SL_WARNING,
ER_WARN_INDEX_NOT_APPLICABLE,
ER_THD(thd, ER_WARN_INDEX_NOT_APPLICABLE), "range",
field->table->key_info[param->real_keynr[key_num]].name,
field->field_name);
}
/*
Build a SEL_TREE for <> or NOT BETWEEN predicate
SYNOPSIS
get_ne_mm_tree()
param RANGE_OPT_PARAM from test_quick_select
prev_tables See test_quick_select()
read_tables See test_quick_select()
remove_jump_scans See get_mm_tree()
cond_func item for the predicate
field field in the predicate
lt_value constant that field should be smaller
gt_value constant that field should be greaterr
RETURN
# Pointer to tree built tree
0 on error
*/
static SEL_TREE *get_ne_mm_tree(THD *thd, RANGE_OPT_PARAM *param,
table_map prev_tables, table_map read_tables,
bool remove_jump_scans, Item_func *cond_func,
Field *field, Item *lt_value, Item *gt_value) {
SEL_TREE *tree = nullptr;
if (param->has_errors()) return nullptr;
tree = get_mm_parts(thd, param, prev_tables, read_tables, cond_func, field,
Item_func::LT_FUNC, lt_value);
if (tree) {
tree = tree_or(param, remove_jump_scans, tree,
get_mm_parts(thd, param, prev_tables, read_tables, cond_func,
field, Item_func::GT_FUNC, gt_value));
}
return tree;
}
/**
Factory function to build a SEL_TREE from an @<in predicate@>
@param thd Thread handle
@param param Information on 'just about everything'.
@param prev_tables See test_quick_select()
@param read_tables See test_quick_select()
@param remove_jump_scans See get_mm_tree()
@param predicand The @<in predicate's@> predicand, i.e. the left-hand
side of the @<in predicate@> expression.
@param op The 'in' operator itself.
@param is_negated If true, the operator is NOT IN, otherwise IN.
*/
static SEL_TREE *get_func_mm_tree_from_in_predicate(
THD *thd, RANGE_OPT_PARAM *param, table_map prev_tables,
table_map read_tables, bool remove_jump_scans, Item *predicand,
Item_func_in *op, bool is_negated) {
if (param->has_errors()) return nullptr;
// Populate array as we need to examine its values here
if (op->m_const_array != nullptr && !op->m_populated) {
op->populate_bisection(thd);
}
if (is_negated) {
// We don't support row constructors (multiple columns on lhs) here.
if (predicand->type() != Item::FIELD_ITEM) return nullptr;
Field *field = down_cast<Item_field *>(predicand)->field;
if (op->m_const_array != nullptr && !op->m_const_array->is_row_result()) {
/*
We get here for conditions on the form "t.key NOT IN (c1, c2, ...)",
where c{i} are constants. Our goal is to produce a SEL_TREE that
represents intervals:
($MIN<t.key<c1) OR (c1<t.key<c2) OR (c2<t.key<c3) OR ... (*)
where $MIN is either "-inf" or NULL.
The most straightforward way to produce it is to convert NOT
IN into "(t.key != c1) AND (t.key != c2) AND ... " and let the
range analyzer build a SEL_TREE from that. The problem is that
the range analyzer will use O(N^2) memory (which is probably a
bug), and people who do use big NOT IN lists (e.g. see
BUG#15872, BUG#21282), will run out of memory.
Another problem with big lists like (*) is that a big list is
unlikely to produce a good "range" access, while considering
that range access will require expensive CPU calculations (and
for MyISAM even index accesses). In short, big NOT IN lists
are rarely worth analyzing.
Considering the above, we'll handle NOT IN as follows:
- if the number of entries in the NOT IN list is less than
NOT_IN_IGNORE_THRESHOLD, construct the SEL_TREE (*)
manually.
- Otherwise, don't produce a SEL_TREE.
*/
const uint NOT_IN_IGNORE_THRESHOLD = 1000;
// If we have t.key NOT IN (null, null, ...) or the list is too long
if (op->m_const_array->m_used_size == 0 ||
op->m_const_array->m_used_size > NOT_IN_IGNORE_THRESHOLD)
return nullptr;
/*
Create one Item_type constant object. We'll need it as
get_mm_parts only accepts constant values wrapped in Item_Type
objects.
We create the Item on thd->mem_root which points to
per-statement mem_root.
*/
Item_basic_constant *value_item =
op->m_const_array->create_item(thd->mem_root);
if (value_item == nullptr) return nullptr;
/* Get a SEL_TREE for "(-inf|NULL) < X < c_0" interval. */
uint i = 0;
SEL_TREE *tree = nullptr;
do {
op->m_const_array->value_to_item(i, value_item);
tree = get_mm_parts(thd, param, prev_tables, read_tables, op, field,
Item_func::LT_FUNC, value_item);
if (!tree) break;
i++;
} while (i < op->m_const_array->m_used_size &&
tree->type == SEL_TREE::IMPOSSIBLE);
if (!tree || tree->type == SEL_TREE::IMPOSSIBLE)
/* We get here in cases like "t.unsigned NOT IN (-1,-2,-3) */
return nullptr;
SEL_TREE *tree2 = nullptr;
Item_basic_constant *previous_range_value =
op->m_const_array->create_item(thd->mem_root);
for (; i < op->m_const_array->m_used_size; i++) {
// Check if the value stored in the field for the previous range
// is greater, lesser or equal to the actual value specified in the
// query. Used further down to set the flags for the current range
// correctly (as the max value for the previous range will become
// the min value for the current range).
op->m_const_array->value_to_item(i - 1, previous_range_value);
int cmp_value =
stored_field_cmp_to_item(thd, field, previous_range_value);
if (op->m_const_array->compare_elems(i, i - 1)) {
/* Get a SEL_TREE for "-inf < X < c_i" interval */
op->m_const_array->value_to_item(i, value_item);
tree2 = get_mm_parts(thd, param, prev_tables, read_tables, op, field,
Item_func::LT_FUNC, value_item);
if (!tree2) {
tree = nullptr;
break;
}
/* Change all intervals to be "c_{i-1} < X < c_i" */
for (uint idx = 0; idx < param->keys; idx++) {
SEL_ARG *last_val;
if (tree->keys[idx] && tree2->keys[idx] &&
((last_val = tree->keys[idx]->root->last()))) {
SEL_ARG *new_interval = tree2->keys[idx]->root;
new_interval->min_value = last_val->max_value;
// We set the max value of the previous range as the beginning
// for this range interval. However we need values higher than
// this value:
// For ex: If the range is "not in (1,2)" we first construct
// X < 1 before this loop and add 1 < X < 2 in this loop and
// follow it up with 2 < X below.
// While fetching values for the second interval, we set
// "NEAR_MIN" flag so that we fetch values higher than "1".
// However, when the values specified are not compatible
// with the field that is being compared to, they are rounded
// off.
// For the example above, if the range given was "not in (0.9,
// 1.9)", range optimizer rounds of the values to (1,2). In such
// a case, setting the flag to "NEAR_MIN" is not right. Because
// we need values higher than "0.9" not "1". We check this
// before we set the flag below.
if (cmp_value <= 0)
new_interval->min_flag = NEAR_MIN;
else
new_interval->min_flag = 0;
/*
If the interval is over a partial keypart, the
interval must be "c_{i-1} <= X < c_i" instead of
"c_{i-1} < X < c_i". Reason:
Consider a table with a column "my_col VARCHAR(3)",
and an index with definition
"INDEX my_idx my_col(1)". If the table contains rows
with my_col values "f" and "foo", the index will not
distinguish the two rows.
Note that tree_or() below will effectively merge
this range with the range created for c_{i-1} and
we'll eventually end up with only one range:
"NULL < X".
Partitioning indexes are never partial.
*/
if (param->using_real_indexes) {
const KEY key = param->table->key_info[param->real_keynr[idx]];
const KEY_PART_INFO *kpi = key.key_part + new_interval->part;
if (kpi->key_part_flag & HA_PART_KEY_SEG)
new_interval->min_flag = 0;
}
}
}
/*
The following doesn't try to allocate memory so no need to
check for NULL.
*/
tree = tree_or(param, remove_jump_scans, tree, tree2);
}
}
if (tree && tree->type != SEL_TREE::IMPOSSIBLE) {
/*
Get the SEL_TREE for the last "c_last < X < +inf" interval
(value_item contains c_last already)
*/
tree2 = get_mm_parts(thd, param, prev_tables, read_tables, op, field,
Item_func::GT_FUNC, value_item);
tree = tree_or(param, remove_jump_scans, tree, tree2);
}
return tree;
} else {
SEL_TREE *tree = get_ne_mm_tree(thd, param, prev_tables, read_tables,
remove_jump_scans, op, field,
op->arguments()[1], op->arguments()[1]);
if (tree) {
Item **arg, **end;
for (arg = op->arguments() + 2, end = arg + op->argument_count() - 2;
arg < end; arg++) {
tree = tree_and(
param, tree,
get_ne_mm_tree(thd, param, prev_tables, read_tables,
remove_jump_scans, op, field, *arg, *arg));
}
}
return tree;
}
return nullptr;
}
// The expression is IN, not negated.
if (predicand->type() == Item::FIELD_ITEM) {
// The expression is (<column>) IN (...)
Field *field = down_cast<Item_field *>(predicand)->field;
SEL_TREE *tree =
get_mm_parts(thd, param, prev_tables, read_tables, op, field,
Item_func::EQ_FUNC, op->arguments()[1]);
if (tree) {
Item **arg, **end;
for (arg = op->arguments() + 2, end = arg + op->argument_count() - 2;
arg < end; arg++) {
tree = tree_or(param, remove_jump_scans, tree,
get_mm_parts(thd, param, prev_tables, read_tables, op,
field, Item_func::EQ_FUNC, *arg));
}
}
return tree;
}
if (predicand->type() == Item::ROW_ITEM) {
/*
The expression is (<column>,...) IN (...)
We iterate over the rows on the rhs of the in predicate,
building an OR tree of ANDs, a.k.a. a DNF expression out of this. E.g:
(col1, col2) IN ((const1, const2), (const3, const4))
becomes
(col1 = const1 AND col2 = const2) OR (col1 = const3 AND col2 = const4)
*/
SEL_TREE *or_tree = &null_sel_tree;
Item_row *row_predicand = down_cast<Item_row *>(predicand);
// Iterate over the rows on the rhs of the in predicate, building an OR.
for (uint i = 1; i < op->argument_count(); ++i) {
/*
We only support row value expressions. Some optimizations rewrite
the Item tree, and we don't handle that.
*/
Item *in_list_item = op->arguments()[i];
if (in_list_item->type() != Item::ROW_ITEM) return nullptr;
Item_row *row = static_cast<Item_row *>(in_list_item);
// Iterate over the columns, building an AND tree.
SEL_TREE *and_tree = nullptr;
for (uint j = 0; j < row_predicand->cols(); ++j) {
Item *item = row_predicand->element_index(j);
// We only support columns in the row on the lhs of the in predicate.
if (item->type() != Item::FIELD_ITEM) return nullptr;
Field *field = static_cast<Item_field *>(item)->field;
Item *value = row->element_index(j);
SEL_TREE *and_expr = get_mm_parts(thd, param, prev_tables, read_tables,
op, field, Item_func::EQ_FUNC, value);
and_tree = tree_and(param, and_tree, and_expr);
/*
Short-circuit evaluation: If and_expr is NULL then no key part in
this disjunct can be used as a search key. Or in other words the
condition is always true. Hence the whole disjunction is always true.
*/
if (and_tree == nullptr) return nullptr;
}
or_tree = tree_or(param, remove_jump_scans, or_tree, and_tree);
}
return or_tree;
}
return nullptr;
}
/**
Factory function to build a SEL_TREE from a JSON_OVERLAPS or JSON_CONTAINS
functions
\verbatim
This function builds SEL_TREE out of JSON_OEVRLAPS() of form:
JSON_OVERLAPS(typed_array_field, "[<val>,...,<val>]")
JSON_OVERLAPS("[<val>,...,<val>]", typed_array_field)
JSON_CONTAINS(typed_array_field, "[<val>,...,<val>]")
where
typed_array_field is a field which has multi-valued index defined on it
<val> each value in the array is coercible to the array's
type
These conditions are pre-checked in substitute_gc().
\endverbatim
@param thd Thread handle
@param param Information on 'just about everything'.
@param prev_tables See test_quick_select()
@param read_tables See test_quick_select()
@param remove_jump_scans See get_mm_tree()
@param predicand the typed array JSON_CONTAIN's argument
@param op The 'JSON_OVERLAPS' operator itself.
@returns
non-NULL constructed SEL_TREE
NULL in case of any error
*/
static SEL_TREE *get_func_mm_tree_from_json_overlaps_contains(
THD *thd, RANGE_OPT_PARAM *param, table_map prev_tables,
table_map read_tables, bool remove_jump_scans, Item *predicand,
Item_func *op) {
if (param->has_errors()) return nullptr;
// The expression is JSON_OVERLAPS(<array_field>,<JSON array/scalar>), or
// The expression is JSON_OVERLAPS(<JSON array/scalar>, <array_field>), or
// The expression is JSON_CONTAINS(<array_field>, <JSON array/scalar>)
if (predicand->type() == Item::FIELD_ITEM && predicand->returns_array()) {
Json_wrapper wr, elt;
String str;
uint values;
if (op->functype() == Item_func::JSON_OVERLAPS) {
// If the predicand is the 1st arg, then the values arg is 2nd.
values = (predicand == op->arguments()[0]) ? 1 : 0;
} else {
assert(op->functype() == Item_func::JSON_CONTAINS);
values = 1;
}
if (get_json_wrapper(op->arguments(), values, &str, op->func_name(), &wr))
return nullptr; /* purecov: inspected */
// Should be pre-checked already
assert(!(op->arguments()[values])->null_value &&
wr.type() != enum_json_type::J_OBJECT &&
wr.type() != enum_json_type::J_ERROR);
if (wr.length() == 0) return nullptr;
Field_typed_array *field = down_cast<Field_typed_array *>(
down_cast<Item_field *>(predicand)->field);
if (wr.type() == enum_json_type::J_ARRAY)
wr.remove_duplicates(
field->type() == MYSQL_TYPE_VARCHAR ? field->charset() : nullptr);
size_t i = 0;
const size_t len = (wr.type() == enum_json_type::J_ARRAY) ? wr.length() : 1;
// Skip leading JSON null values as they can't be indexed and thus doesn't
// exist in index.
while (i < len && wr[i].type() == enum_json_type::J_NULL) ++i;
// No non-null values were found.
if (i == len) return nullptr;
// Fake const table for get_mm_parts, as we're using constants from JSON
// array
const bool save_const = field->table->const_table;
field->table->const_table = true;
field->set_notnull();
// Get the SEL_ARG tree for the first non-null element..
elt = wr[i++];
field->coerce_json_value(&elt, true, nullptr);
SEL_TREE *tree =
get_mm_parts(thd, param, prev_tables, read_tables, op, field,
Item_func::EQ_FUNC, down_cast<Item_field *>(predicand));
// .. and OR with others
if (tree) {
for (; i < len; i++) {
elt = wr[i];
field->coerce_json_value(&elt, true, nullptr);
tree = tree_or(param, remove_jump_scans, tree,
get_mm_parts(thd, param, prev_tables, read_tables, op,
field, Item_func::EQ_FUNC,
down_cast<Item_field *>(predicand)));
if (!tree) // OOM
break;
}
}
field->table->const_table = save_const;
return tree;
}
return nullptr;
}
/**
Build a SEL_TREE for a simple predicate.
@param param RANGE_OPT_PARAM from test_quick_select
@param remove_jump_scans See get_mm_tree()
@param predicand field in the predicate
@param cond_func item for the predicate
@param value constant in the predicate
@param inv true <> NOT cond_func is considered
(makes sense only when cond_func is BETWEEN or IN)
@return Pointer to the built tree.
@todo Remove the appaling hack that 'value' can be a 1 cast to an Item*.
*/
static SEL_TREE *get_func_mm_tree(THD *thd, RANGE_OPT_PARAM *param,
table_map prev_tables, table_map read_tables,
bool remove_jump_scans, Item *predicand,
Item_func *cond_func, Item *value, bool inv) {
SEL_TREE *tree = nullptr;
DBUG_TRACE;
if (param->has_errors()) return nullptr;
switch (cond_func->functype()) {
case Item_func::XOR_FUNC:
return nullptr; // Always true (don't use range access on XOR).
break; // See WL#5800
case Item_func::NE_FUNC:
if (predicand->type() == Item::FIELD_ITEM) {
Field *field = down_cast<Item_field *>(predicand)->field;
tree =
get_ne_mm_tree(thd, param, prev_tables, read_tables,
remove_jump_scans, cond_func, field, value, value);
}
break;
case Item_func::BETWEEN:
if (predicand->type() == Item::FIELD_ITEM) {
Field *field = down_cast<Item_field *>(predicand)->field;
if (!value) {
if (inv) {
tree = get_ne_mm_tree(thd, param, prev_tables, read_tables,
remove_jump_scans, cond_func, field,
cond_func->arguments()[1],
cond_func->arguments()[2]);
} else {
tree = get_mm_parts(thd, param, prev_tables, read_tables, cond_func,
field, Item_func::GE_FUNC,
cond_func->arguments()[1]);
if (tree) {
tree = tree_and(param, tree,
get_mm_parts(thd, param, prev_tables, read_tables,
cond_func, field, Item_func::LE_FUNC,
cond_func->arguments()[2]));
}
}
} else
tree = get_mm_parts(
thd, param, prev_tables, read_tables, cond_func, field,
(inv ? (value == reinterpret_cast<Item *>(1) ? Item_func::GT_FUNC
: Item_func::LT_FUNC)
: (value == reinterpret_cast<Item *>(1)
? Item_func::LE_FUNC
: Item_func::GE_FUNC)),
cond_func->arguments()[0]);
}
break;
case Item_func::IN_FUNC: {
Item_func_in *in_pred = down_cast<Item_func_in *>(cond_func);
tree = get_func_mm_tree_from_in_predicate(thd, param, prev_tables,
read_tables, remove_jump_scans,
predicand, in_pred, inv);
} break;
case Item_func::JSON_CONTAINS:
case Item_func::JSON_OVERLAPS: {
tree = get_func_mm_tree_from_json_overlaps_contains(
thd, param, prev_tables, read_tables, remove_jump_scans, predicand,
cond_func);
} break;
case Item_func::MEMBER_OF_FUNC:
if (predicand->type() == Item::FIELD_ITEM && predicand->returns_array()) {
Field_typed_array *field = down_cast<Field_typed_array *>(
down_cast<Item_field *>(predicand)->field);
Item *arg = cond_func->arguments()[0];
Json_wrapper wr;
if (arg->val_json(&wr)) {
break;
}
assert(!arg->null_value && wr.type() != enum_json_type::J_ERROR);
if (wr.type() == enum_json_type::J_NULL) {
break;
}
// Fake const table for get_mm_parts(), as we are using constants from
// JSON array
const bool save_const = field->table->const_table;
field->table->const_table = true;
field->set_notnull();
field->coerce_json_value(&wr, true, nullptr);
tree = get_mm_parts(thd, param, prev_tables, read_tables, cond_func,
field, Item_func::EQ_FUNC, predicand);
field->table->const_table = save_const;
}
break;
default:
if (predicand->type() == Item::FIELD_ITEM) {
Field *field = down_cast<Item_field *>(predicand)->field;
/*
Here the function for the following predicates are processed:
<, <=, =, >=, >, LIKE, IS NULL, IS NOT NULL and GIS functions.
If the predicate is of the form (value op field) it is handled
as the equivalent predicate (field rev_op value), e.g.
2 <= a is handled as a >= 2.
*/
Item_func::Functype func_type =
(value != cond_func->arguments()[0])
? cond_func->functype()
: ((Item_bool_func2 *)cond_func)->rev_functype();
tree = get_mm_parts(thd, param, prev_tables, read_tables, cond_func,
field, func_type, value);
}
}
return tree;
}
/*
Build conjunction of all SEL_TREEs for a simple predicate applying equalities
SYNOPSIS
get_full_func_mm_tree()
param RANGE_OPT_PARAM from test_quick_select
prev_tables See test_quick_select()
read_tables See test_quick_select()
remove_jump_scans See get_mm_tree()
predicand column or row constructor in the predicate's left-hand side.
op Item for the predicate operator
value constant in the predicate (or a field already read from
a table in the case of dynamic range access)
For BETWEEN it contains the number of the field argument.
inv If true, the predicate is negated, e.g. NOT IN.
(makes sense only when cond_func is BETWEEN or IN)
DESCRIPTION
For a simple SARGable predicate of the form (f op c), where f is a field and
c is a constant, the function builds a conjunction of all SEL_TREES that can
be obtained by the substitution of f for all different fields equal to f.
NOTES
If the WHERE condition contains a predicate (fi op c),
then not only SELL_TREE for this predicate is built, but
the trees for the results of substitution of fi for
each fj belonging to the same multiple equality as fi
are built as well.
E.g. for WHERE t1.a=t2.a AND t2.a > 10
a SEL_TREE for t2.a > 10 will be built for quick select from t2
and
a SEL_TREE for t1.a > 10 will be built for quick select from t1.
A BETWEEN predicate of the form (fi [NOT] BETWEEN c1 AND c2) is treated
in a similar way: we build a conjunction of trees for the results
of all substitutions of fi for equal fj.
Yet a predicate of the form (c BETWEEN f1i AND f2i) is processed
differently. It is considered as a conjunction of two SARGable
predicates (f1i <= c) and (f2i <=c) and the function get_full_func_mm_tree
is called for each of them separately producing trees for
AND j (f1j <=c ) and AND j (f2j <= c)
After this these two trees are united in one conjunctive tree.
It's easy to see that the same tree is obtained for
AND j,k (f1j <=c AND f2k<=c)
which is equivalent to
AND j,k (c BETWEEN f1j AND f2k).
The validity of the processing of the predicate (c NOT BETWEEN f1i AND f2i)
which equivalent to (f1i > c OR f2i < c) is not so obvious. Here the
function get_full_func_mm_tree is called for (f1i > c) and (f2i < c)
producing trees for AND j (f1j > c) and AND j (f2j < c). Then this two
trees are united in one OR-tree. The expression
(AND j (f1j > c) OR AND j (f2j < c)
is equivalent to the expression
AND j,k (f1j > c OR f2k < c)
which is just a translation of
AND j,k (c NOT BETWEEN f1j AND f2k)
In the cases when one of the items f1, f2 is a constant c1 we do not create
a tree for it at all. It works for BETWEEN predicates but does not
work for NOT BETWEEN predicates as we have to evaluate the expression
with it. If it is true then the other tree can be completely ignored.
We do not do it now and no trees are built in these cases for
NOT BETWEEN predicates.
As to IN predicates only ones of the form (f IN (c1,...,cn)),
where f1 is a field and c1,...,cn are constant, are considered as
SARGable. We never try to narrow the index scan using predicates of
the form (c IN (c1,...,f,...,cn)).
RETURN
Pointer to the tree representing the built conjunction of SEL_TREEs
*/
static SEL_TREE *get_full_func_mm_tree(THD *thd, RANGE_OPT_PARAM *param,
table_map prev_tables,
table_map read_tables,
table_map current_table,
bool remove_jump_scans, Item *predicand,
Item_func *op, Item *value, bool inv) {
SEL_TREE *tree = nullptr;
SEL_TREE *ftree = nullptr;
const table_map param_comp = ~(prev_tables | read_tables | current_table);
DBUG_TRACE;
if (param->has_errors()) return nullptr;
/*
Here we compute a set of tables that we consider as constants
suppliers during execution of the SEL_TREE that we produce below.
*/
table_map ref_tables = 0;
for (uint i = 0; i < op->arg_count; i++) {
Item *arg = op->arguments()[i]->real_item();
if (arg != predicand) ref_tables |= arg->used_tables();
}
if (predicand->type() == Item::FIELD_ITEM) {
Item_field *item_field = static_cast<Item_field *>(predicand);
Field *field = item_field->field;
if (!((ref_tables | item_field->table_ref->map()) & param_comp))
ftree = get_func_mm_tree(thd, param, prev_tables, read_tables,
remove_jump_scans, predicand, op, value, inv);
Item_equal *item_equal = item_field->item_equal;
if (item_equal != nullptr) {
for (Item_field &item : item_equal->get_fields()) {
Field *f = item.field;
if (!field->eq(f) &&
!((ref_tables | item.table_ref->map()) & param_comp)) {
tree = get_func_mm_tree(thd, param, prev_tables, read_tables,
remove_jump_scans, &item, op, value, inv);
ftree = !ftree ? tree : tree_and(param, ftree, tree);
}
}
}
} else if (predicand->type() == Item::ROW_ITEM) {
ftree = get_func_mm_tree(thd, param, prev_tables, read_tables,
remove_jump_scans, predicand, op, value, inv);
return ftree;
}
return ftree;
}
/**
The Range Analysis Module, which finds range access alternatives
applicable to single or multi-index (UNION) access. The function
does not calculate or care about the cost of the different
alternatives.
get_mm_tree() employs a relaxed boolean algebra where the solution
may be bigger than what the rules of boolean algebra accept. In
other words, get_mm_tree() may return range access plans that will
read more rows than the input conditions dictate. In it's simplest
form, consider a condition on two fields indexed by two different
indexes:
"WHERE fld1 > 'x' AND fld2 > 'y'"
In this case, there are two single-index range access alternatives.
No matter which access path is chosen, rows that are not in the
result set may be read.
In the case above, get_mm_tree() will create range access
alternatives for both indexes, so boolean algebra is still correct.
In other cases, however, the conditions are too complex to be used
without relaxing the rules. This typically happens when ORing a
conjunction to a multi-index disjunctions (@see e.g.
imerge_list_or_tree()). When this happens, the range optimizer may
choose to ignore conjunctions (any condition connected with AND). The
effect of this is that the result includes a "bigger" solution than
necessary. This is OK since all conditions will be used as filters
after row retrieval.
@see SEL_TREE::keys and SEL_TREE::merges for details of how single
and multi-index range access alternatives are stored.
remove_jump_scans: Aggressively remove "scans" that do not have
conditions on first keyparts. Such scans are usable when doing partition
pruning but not regular range optimization.
A return value of nullptr from get_mm_tree() means that this condition
could not be represented by a range. Normally, this means that the best
thing to do is to keep that condition entirely out of the range optimization,
since ANDing it with other conditions (in tree_and()) would make the entire
tree inexact and no predicates subsumable (see SEL_TREE::inexact). However,
the old join optimizer does not care, and always just gives in the entire
condition (with different parts ANDed together) in one go, since it never
subsumes anything anyway.
*/
SEL_TREE *get_mm_tree(THD *thd, RANGE_OPT_PARAM *param, table_map prev_tables,
table_map read_tables, table_map current_table,
bool remove_jump_scans, Item *cond) {
SEL_TREE *ftree = nullptr;
bool inv = false;
DBUG_TRACE;
if (param->has_errors()) return nullptr;
if (cond->type() == Item::COND_ITEM) {
Item_func::Functype functype = down_cast<Item_cond *>(cond)->functype();
SEL_TREE *tree = nullptr;
bool first = true;
for (Item &item : *down_cast<Item_cond *>(cond)->argument_list()) {
SEL_TREE *new_tree = get_mm_tree(thd, param, prev_tables, read_tables,
current_table, remove_jump_scans, &item);
if (param->has_errors()) return nullptr;
if (first) {
tree = new_tree;
first = false;
continue;
}
if (functype == Item_func::COND_AND_FUNC) {
tree = tree_and(param, tree, new_tree);
dbug_print_tree("after_and", tree, param);
if (tree && tree->type == SEL_TREE::IMPOSSIBLE) break;
} else { // OR.
tree = tree_or(param, remove_jump_scans, tree, new_tree);
dbug_print_tree("after_or", tree, param);
if (tree == nullptr || tree->type == SEL_TREE::ALWAYS) break;
}
}
dbug_print_tree("tree_returned", tree, param);
return tree;
}
if (cond->const_item() && !cond->is_expensive()) {
const SEL_TREE::Type type =
cond->val_int() ? SEL_TREE::ALWAYS : SEL_TREE::IMPOSSIBLE;
SEL_TREE *tree = new (param->temp_mem_root)
SEL_TREE(type, param->temp_mem_root, param->keys);
if (param->has_errors()) return nullptr;
dbug_print_tree("tree_returned", tree, param);
return tree;
}
// This used to be a guard against predicates like “WHERE x;”. But these are
// now always rewritten to “x <> 0”, so it does not trigger there.
// However, it is still relevant for subselects.
if (cond->type() != Item::FUNC_ITEM) {
return nullptr;
}
Item_func *cond_func = (Item_func *)cond;
if (cond_func->functype() == Item_func::BETWEEN ||
cond_func->functype() == Item_func::IN_FUNC)
inv = ((Item_func_opt_neg *)cond_func)->negated;
else {
Item_func::optimize_type opt_type = cond_func->select_optimize(thd);
if (opt_type == Item_func::OPTIMIZE_NONE) return nullptr;
}
/*
Notice that all fields that are outer references are const during
the execution and should not be considered for range analysis like
fields coming from the local query block are.
*/
switch (cond_func->functype()) {
case Item_func::BETWEEN: {
Item *const arg_left = cond_func->arguments()[0];
if (!arg_left->is_outer_reference() &&
arg_left->real_item()->type() == Item::FIELD_ITEM) {
Item_field *field_item = down_cast<Item_field *>(arg_left->real_item());
ftree = get_full_func_mm_tree(thd, param, prev_tables, read_tables,
current_table, remove_jump_scans,
field_item, cond_func, nullptr, inv);
}
/*
Concerning the code below see the NOTES section in
the comments for the function get_full_func_mm_tree()
*/
SEL_TREE *tree = nullptr;
for (uint i = 1; i < cond_func->arg_count; i++) {
Item *const arg = cond_func->arguments()[i];
if (!arg->is_outer_reference() &&
arg->real_item()->type() == Item::FIELD_ITEM) {
Item_field *field_item = down_cast<Item_field *>(arg->real_item());
SEL_TREE *tmp = get_full_func_mm_tree(
thd, param, prev_tables, read_tables, current_table,
remove_jump_scans, field_item, cond_func,
reinterpret_cast<Item *>(i), inv);
if (inv) {
tree = !tree ? tmp : tree_or(param, remove_jump_scans, tree, tmp);
if (tree == nullptr) break;
} else
tree = tree_and(param, tree, tmp);
} else if (inv) {
tree = nullptr;
break;
}
}
ftree = tree_and(param, ftree, tree);
break;
} // end case Item_func::BETWEEN
case Item_func::JSON_CONTAINS:
case Item_func::JSON_OVERLAPS:
case Item_func::MEMBER_OF_FUNC:
case Item_func::IN_FUNC: {
Item *predicand = cond_func->key_item();
if (!predicand) return nullptr;
predicand = predicand->real_item();
if (predicand->type() != Item::FIELD_ITEM &&
predicand->type() != Item::ROW_ITEM)
return nullptr;
ftree = get_full_func_mm_tree(thd, param, prev_tables, read_tables,
current_table, remove_jump_scans, predicand,
cond_func, nullptr, inv);
break;
} // end case Item_func::IN_FUNC
case Item_func::MULT_EQUAL_FUNC: {
Item_equal *item_equal = down_cast<Item_equal *>(cond);
Item *value = item_equal->const_arg();
if (value == nullptr) return nullptr;
table_map ref_tables = value->used_tables();
for (Item_field &field_item : item_equal->get_fields()) {
Field *field = field_item.field;
table_map param_comp = ~(prev_tables | read_tables | current_table);
if (!((ref_tables | field_item.table_ref->map()) & param_comp)) {
SEL_TREE *tree =
get_mm_parts(thd, param, prev_tables, read_tables, item_equal,
field, Item_func::EQ_FUNC, value);
ftree = !ftree ? tree : tree_and(param, ftree, tree);
}
}
dbug_print_tree("tree_returned", ftree, param);
return ftree;
} // end case Item_func::MULT_EQUAL_FUNC
default: {
Item *const arg_left = cond_func->arguments()[0];
assert(!ftree);
if (!arg_left->is_outer_reference() &&
arg_left->real_item()->type() == Item::FIELD_ITEM) {
Item_field *field_item = down_cast<Item_field *>(arg_left->real_item());
Item *value =
cond_func->arg_count > 1 ? cond_func->arguments()[1] : nullptr;
ftree = get_full_func_mm_tree(thd, param, prev_tables, read_tables,