MySQL 9.5.0
Source Code Documentation
item_subselect.h
Go to the documentation of this file.
1#ifndef ITEM_SUBSELECT_INCLUDED
2#define ITEM_SUBSELECT_INCLUDED
3
4/* Copyright (c) 2002, 2025, Oracle and/or its affiliates.
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License, version 2.0,
8 as published by the Free Software Foundation.
9
10 This program is designed to work with certain software (including
11 but not limited to OpenSSL) that is licensed under separate terms,
12 as designated in a particular file or component or in included license
13 documentation. The authors of MySQL hereby grant you an additional
14 permission to link the program and your derivative works with the
15 separately licensed software that they have either included with
16 the program or referenced in the documentation.
17
18 This program is distributed in the hope that it will be useful,
19 but WITHOUT ANY WARRANTY; without even the implied warranty of
20 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 GNU General Public License, version 2.0, for more details.
22
23 You should have received a copy of the GNU General Public License
24 along with this program; if not, write to the Free Software
25 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
26
27/// Implements classes that represent subqueries and predicates containing
28/// table subqueries.
29
30#include <assert.h>
31#include <sys/types.h>
32
33#include <cstddef>
34#include <memory> // unique_ptr
35#include <vector>
36
37#include "field_types.h" // enum_field_types
38#include "my_alloc.h" // Destroy_only
39
40#include "my_inttypes.h"
41#include "my_table_map.h"
42#include "my_time.h"
44#include "mysql_time.h"
45#include "sql/comp_creator.h"
46#include "sql/enum_query_type.h"
47#include "sql/item.h" // Item_result_field
48#include "sql/iterators/row_iterator.h" // IWYU pragma: keep
49#include "sql/parse_location.h" // POS
51#include "sql/sql_const.h"
53#include "template_utils.h"
54
55class Comp_creator;
56class Field;
59class JOIN;
60class Json_wrapper;
61class PT_subquery;
65class Query_block;
67class String;
68class THD;
70class my_decimal;
72struct AccessPath;
73class Table_ref;
74
75template <class T>
76class List;
77
78/// Base class that is common to all subqueries and subquery predicates
79
82
83 public:
85
86 /**
87 For Item_subselect constructor with POS parameter, the contextualized
88 field must be transitioned explicitly.
89 */
91#ifndef NDEBUG
92 assert(!contextualized);
93 contextualized = true;
94#endif // NDEBUG
95 }
96 /**
97 If !=NO_PLAN_IDX: this Item is in the condition attached to the JOIN_TAB
98 having this index in the parent JOIN.
99 */
101
102 // For EXPLAIN.
105
106 // For EXPLAIN. Only valid if engine_type() == HASH_SJ_ENGINE.
107 const TABLE *get_table() const;
108 const Index_lookup &index_lookup() const;
109 join_type get_join_type() const;
110
111 void create_iterators(THD *thd);
112 virtual AccessPath *root_access_path() const { return nullptr; }
113
115 SCALAR_SUBQUERY, ///< Scalar or row subquery
116 EXISTS_SUBQUERY, ///< [NOT] EXISTS subquery predicate
117 IN_SUBQUERY, ///< [NOT] IN subquery predicate
118 ALL_SUBQUERY, ///< comp-op ALL quantified comparison predicate
119 ANY_SUBQUERY ///< comp-op ANY quantified comparison predicate
120 };
121
122 /// Accumulate used tables
126 }
127
128 /// Return whether this subquery references any tables in the directly
129 /// containing query block, i.e. whether there are outer references to the
130 /// containing block inside the subquery.
132 return (subquery_used_tables() & ~PSEUDO_TABLE_BITS) != 0;
133 }
134
135 virtual Subquery_type subquery_type() const = 0;
136
137 /**
138 @returns whether this subquery is a single column scalar subquery.
139 (Note that scalar and row subqueries are both represented as
140 scalar subqueries, this function can be used to distinguish them)
141 */
142 virtual bool is_single_column_scalar_subquery() const { return false; }
143
144 void cleanup() override;
145 /**
146 Reset state after a single execution of a subquery, useful when a
147 dependent subquery must be evaluated multiple times for varying values
148 of the outer references.
149 This is a lighter cleanup procedure than the one provided by cleanup().
150 */
151 virtual void reset() {
152 m_value_assigned = false;
153 null_value = true;
154 }
155 bool is_value_assigned() const { return m_value_assigned; }
158 enum Type type() const override;
159 bool is_null() override { return update_null_value() || null_value; }
160 bool fix_fields(THD *thd, Item **ref) override;
161 void fix_after_pullout(Query_block *parent_query_block,
162 Query_block *removed_query_block) override;
163 virtual bool exec(THD *thd);
164 table_map used_tables() const override { return m_used_tables_cache; }
165 table_map not_null_tables() const override { return 0; }
166 /// @returns used tables for subquery (excluding any left-hand expression)
168 Item *get_tmp_table_item(THD *thd) override;
169 void update_used_tables() override;
170 void print(const THD *thd, String *str,
171 enum_query_type query_type) const override;
172
175 }
176
177 /*
178 True if this subquery has been already evaluated. Implemented only for
179 single select and union subqueries only.
180 */
181 bool is_evaluated() const;
182 bool is_uncacheable() const;
183
184 /**
185 Used by max/min subquery to initialize value presence registration
186 mechanism. Engine calls this function before re-execution of subquery.
187 */
188 virtual void reset_has_values() {}
189 /**
190 @returns the "place" where this subquery is located in the simply
191 containing query block.
192 */
194
195 bool walk(Item_processor processor, enum_walk walk, uchar *arg) override;
196 bool explain_subquery_checker(uchar **arg) override;
197 bool inform_item_in_cond_of_tab(uchar *arg) override;
198 bool clean_up_after_removal(uchar *arg) override;
199
202 pointer_cast<Check_function_as_value_generator_parameters *>(args);
203 func_arg->err_code = func_arg->get_unnamed_function_error_code();
204 return true;
205 }
206
207 /// argument used by walk method collect_scalar_subqueries ("css")
209 ///< accumulated all subq (or aggregates) found
210 std::vector<Item_subselect *> list;
213 bool contains(Query_expression *candidate) {
214 for (auto sq : list) {
215 if (sq->m_query_expr == candidate) return true;
216 }
217 return false;
218 }
219 };
220
221 bool collect_subqueries(uchar *) override;
222 Item *replace_item_field(uchar *arg) override;
223 Item *replace_item_view_ref(uchar *arg) override;
224
225 protected:
227 explicit Item_subselect(const POS &pos) : super(pos) { set_subquery(); }
228 /**
229 Bind this subquery object with the supplied query expression.
230 As part of transformations, this function may re-bind the subquery to
231 a different query expression.
232
233 @param qe supplied query expression
234 */
235 void bind(Query_expression *qe);
236
237 /// The query expression of the subquery
238 Query_expression *m_query_expr{nullptr}; // Actual value set in construction
239
240 /// The query result object associated with the query expression
242
243 /// Only relevant for Item_in_subselect; optimized structure used for
244 /// execution in place of running the entire subquery.
246
247 /// cache of used tables
249 /// cache of used tables from subquery only (not including LHS of IN subquery)
251
252 /// allowed number of columns (1 for scalar subqueries)
253 uint m_max_columns{0}; // Irrelevant value, actually set during construction
254 /// where subquery is placed
256
257 private:
258 bool subq_opt_away_processor(uchar *arg) override;
259
260 /// Accumulate properties from underlying query expression
262 /// Accumulate properties from underlying query block
264 /// Accumulate properties from a selected expression within a query block.
265 void accumulate_expression(Item *item);
266 /// Accumulate properties from a condition or GROUP/ORDER within a query
267 /// block.
268 void accumulate_condition(Item *item);
269
270 /// True if value has been assigned to subquery
271 bool m_value_assigned{false};
272 /**
273 Whether or not execution of this subquery has been traced by
274 optimizer tracing already. If optimizer trace option
275 REPEATED_SUBSELECT is disabled, this is used to disable tracing
276 after the first one.
277 */
278 bool m_traced_before{false};
279};
280
281/// Class that represents scalar subquery and row subquery
282
284 public:
285 explicit Item_singlerow_subselect(Query_block *query_block);
286 Item_singlerow_subselect(const POS &pos, Query_block *query_block);
288
289 bool fix_fields(THD *thd, Item **ref) override;
290 void cleanup() override;
291 Subquery_type subquery_type() const override { return SCALAR_SUBQUERY; }
292 bool create_row(const mem_root_deque<Item *> &item_list, Item_cache **row,
293 bool possibly_empty);
294
295 bool is_single_column_scalar_subquery() const override;
296
297 void reset() override;
298 void store(uint i, Item *item);
299 double val_real() override;
300 longlong val_int() override;
301 String *val_str(String *) override;
302 my_decimal *val_decimal(my_decimal *) override;
303 bool val_json(Json_wrapper *result) override;
304 bool val_date(Date_val *date, my_time_flags_t flags) override;
305 bool val_time(Time_val *time) override;
307 bool val_bool() override;
308 enum Item_result result_type() const override;
309 bool resolve_type(THD *) override;
310
311 /*
312 Mark the subquery as having no rows.
313 If there are aggregate functions (in the outer query),
314 we need to generate a NULL row. @c return_zero_rows().
315 */
316 void no_rows_in_result() override;
317
318 uint cols() const override;
319
320 /**
321 @note that this returns the i-th element of the SELECT list.
322 To check for nullability, look at this->is_nullable() and not
323 element_index[i]->is_nullable(), since the selected expressions are
324 always NULL if the subquery is empty.
325 */
326 Item *element_index(uint i) override { return m_row[i]; }
327 Item **addr(uint i) override { return pointer_cast<Item **>(m_row) + i; }
328 bool check_cols(uint c) override;
329 bool null_inside() override;
330 void bring_value() override;
331
332 bool collect_scalar_subqueries(uchar *) override;
333 virtual bool is_maxmin() const { return false; }
334
335 /**
336 Argument for walk method replace_scalar_subquery
337 */
339 ///< subquery to be replaced with ␓field from derived table
341 ///< The derived table of the transform
343 ///< the replacement field
345 ///< The transformed query block.
347 ///< The immediately surrounding query block. This will be the transformed
348 ///< block or a subquery of it
350 ///< True if subquery's selected item contains a COUNT aggregate
351 bool m_add_coalesce{false};
352 ///< Presence of HAVING clause in subquery: Only relevant if
353 ///< \c m_add_coalesce is true
355 ///< Index of field holding value of having clause in derived table's list
356 ///< of fields. Only relevant if \c m_add_coalesce is true
358
360 TABLE *derived, Field *field,
361 Query_block *select, bool add_coalesce,
362 bool add_having_compensation, uint having_idx)
363 : m_target(target),
364 m_derived(derived),
365 m_field(field),
366 m_outer_query_block(select),
367 m_inner_query_block(select),
368 m_add_coalesce(add_coalesce),
369 m_add_having_compensation(add_having_compensation),
370 m_having_idx(having_idx) {}
371 };
372
373 Item *replace_scalar_subquery(uchar *arge) override;
374 /**
375 This method is used to implement a special case of semantic tree
376 rewriting, mandated by a SQL:2003 exception in the specification.
377 The only caller of this method is handle_sql2003_note184_exception(),
378 see the code there for more details.
379 Note that this method breaks the object internal integrity, by
380 removing it's association with the corresponding Query_block,
381 making this object orphan from the parse tree.
382 No other method, beside the destructor, should be called on this
383 object, as it is now invalid.
384 @return the Query_block structure that was given in the constructor.
385 */
387 std::optional<ContainedSubquery> get_contained_subquery(
388 const Query_block *outer_query_block) override;
390
391 private:
392 /// Value cache of a scalar subquery
394 /**
395 Value cache for a row or scalar subquery. In case of a scalar subquery,
396 m_row points directly at m_value. In case of a row subquery, m_row
397 is an array of pointers to individual Item_cache objects.
398 */
399 Item_cache **m_row{nullptr};
400 bool m_no_rows{false}; ///< @c no_rows_in_result
401};
402
403/* used in static ALL/ANY optimization */
405 public:
406 /**
407 Create an Item for use in transformation of quantified comparison
408 predicates that can be evaluated using MAX or MIN aggregation.
409
410 @param parent The quantified comparison predicate that is transformed.
411 @param query_block The query block representing the inner part of the subq.
412 @param max_arg Whether the aggregation is for MAX or MIN.
413 */
415 bool max_arg);
416 void print(const THD *thd, String *str,
417 enum_query_type query_type) const override;
418 void cleanup() override;
419 bool has_values() const { return m_has_values; }
420 void register_value() { m_has_values = true; }
421 void reset_has_values() override { m_has_values = false; }
422 bool is_maxmin() const override { return true; }
423
424 private:
425 bool m_max; ///< True if performing MAX, false if MIN
426 bool m_has_values{false}; ///< Set if we have found at least one row
427};
428
429/// Classes that represent predicates over table subqueries:
430/// [NOT] EXISTS, [NOT] IN, ANY/SOME and ALL
431
432/**
433 Strategy which will be used to handle this subquery: flattening to a
434 semi-join, conversion to a derived table, rewrite of IN to EXISTS...
435 Sometimes the strategy is first only a candidate, then the real decision
436 happens in a second phase. Other times the first decision is final.
437 */
438enum class Subquery_strategy : int {
439 /// Nothing decided yet
441 /// Candidate for rewriting IN(subquery) to EXISTS, or subquery
442 /// materialization
444 /// Candidate for semi-join flattening
446 /// Candidate for rewriting to joined derived table
448 /// Semi-join flattening
449 SEMIJOIN,
450 /// Rewrite to joined derived table
452 /// Evaluate as EXISTS subquery (possibly after rewriting from another type)
454 /// Subquery materialization (HASH_SJ_ENGINE)
456 /// Subquery has been deleted, probably because it was always false
457 DELETED,
458};
459
462
463 public:
464 /**
465 Create an Item that represents an EXISTS subquery predicate, or any
466 quantified comparison predicate that uses the same base class.
467
468 @param pos String representing the parsed item
469 @param query_block First query block of query expression representing
470 the contained subquery.
471 */
472 Item_exists_subselect(const POS &pos, Query_block *query_block);
473
474 explicit Item_exists_subselect(const POS &pos) : super(pos) {}
475
476 // The left-hand expression of the subquery predicate. Unused with EXISTS
477 Item *left_expr{nullptr};
478
479 /// Priority of this predicate in the convert-to-semi-join-nest process.
481 /// Execution strategy chosen for this Item
483 /// Used by the transformation to derived table
485
486 /**
487 Used by subquery optimizations to keep track about where this subquery
488 predicate is located, and whether it is a candidate for transformation.
489 (Table_ref*) 1 - the predicate is an AND-part of the WHERE
490 join nest pointer - the predicate is an AND-part of ON expression
491 of a join nest
492 NULL - for all other locations. It also means that the
493 predicate is not a candidate for transformation.
494 See also THD::emb_on_expr_nest.
495
496 As for the second case above (the join nest pointer), note that this value
497 may change if scalar subqueries are transformed to derived tables,
498 cf. transform_scalar_subqueries_to_join_with_derived, due to the need to
499 build new join nests. The change is performed in Query_block::nest_derived.
500 */
502
504
505 /*
506 Transform subquery predicate to a form that can be executed, e.g.
507 as an EXISTS subquery, or a MAX or MIN aggregation on the subquery.
508
509 This is a virtual function that has implementations for EXISTS, IN
510 and quantified comparison subquery predicates.
511
512 @param thd Thread handle
513 @param[out] transformed Points to transformed representation of the object
514 if unchanged: No transformation was performed
515
516 @returns false if success, true if error
517 */
518 virtual bool transformer(THD *thd, Item **transformed);
519
520 Subquery_type subquery_type() const override { return EXISTS_SUBQUERY; }
521 bool is_bool_func() const override { return true; }
522 void reset() override {
524 m_value = false;
525 }
526
527 enum Item_result result_type() const override { return INT_RESULT; }
528 /*
529 The item is
530 ([NOT] IN/EXISTS) [ IS [NOT] TRUE|FALSE ]
531 */
533 bool with_is_op() const {
534 switch (value_transform) {
535 case BOOL_IS_TRUE:
536 case BOOL_IS_FALSE:
537 case BOOL_NOT_TRUE:
538 case BOOL_NOT_FALSE:
539 return true;
540 default:
541 return false;
542 }
543 }
544 /// True if the IS TRUE/FALSE wasn't explicit in the query
545 bool implicit_is_op = false;
546 Item *truth_transformer(THD *, enum Bool_test test) override;
547 /**
548 Convert result according to value_transform, null value and supplied value
549
550 @param v boolean value from the primitive subquery predicate
551
552 @returns translated boolean value
553
554 @note Operation will possibly take into account and possibly change null
555 value of the Item.
556 */
557 virtual bool return_value(bool v);
558 void apply_is_true() override {
559 const bool had_is = with_is_op();
561 if (!had_is && value_transform == BOOL_IS_TRUE)
562 implicit_is_op = true; // needn't be written by EXPLAIN
563 }
565 bool use_anti_join_transform() const;
566 bool fix_fields(THD *thd, Item **ref) override;
567 longlong val_int() override;
568 double val_real() override;
569 String *val_str(String *) override;
570 my_decimal *val_decimal(my_decimal *) override;
571 bool val_bool() override;
572 bool val_date(Date_val *date, my_time_flags_t flags) override {
573 return get_date_from_int(date, flags);
574 }
575 bool val_time(Time_val *time) override { return get_time_from_int(time); }
577 return get_datetime_from_int(dt, flags);
578 }
579 bool resolve_type(THD *thd) override;
580 void print(const THD *thd, String *str,
581 enum_query_type query_type) const override;
582
584
585 protected:
586 bool is_semijoin_candidate(THD *thd) const;
587 bool is_derived_candidate(THD *thd) const;
588
589 /// value of this item (boolean: exists/not-exists)
590 bool m_value{false};
591};
592
593/**
594 Representation of IN subquery predicates of the form
595 "left_expr IN (SELECT ...)".
596
597 @details
598 This class has:
599 - A "subquery execution engine" (as a subclass of Item_subselect) that allows
600 it to evaluate subqueries. (and this class participates in execution by
601 having m_was_null variable where part of execution result is stored.
602 - Transformation methods (todo: more on this).
603
604 This class is not used directly, it is "wrapped" into Item_in_optimizer
605 which provides some small bits of subquery evaluation.
606*/
607
610
611 public:
612 Item_in_subselect(const POS &pos, Item *left_expr, Query_block *query_block);
613 Item_in_subselect(const POS &pos, Item *left_expr,
614 PT_subquery *pt_subquery_arg);
615
618
619 bool do_itemize(Parse_context *pc, Item **res) override;
620
621 void cleanup() override;
622 Subquery_type subquery_type() const override { return IN_SUBQUERY; }
623
624 void reset() override {
625 m_value = false;
626 null_value = false;
627 m_was_null = false;
628 }
629 // Whether to ignore UNKNOWN result (only return TRUE or FALSE)
630 bool ignore_unknown() const {
632 }
633 /*
634 @returns true if implementation has to process NULL values.
635 Always true if ignore_unknown() is false.
636 Also true if quantified comparison predicate is ALL.
637 Virtual since IN and ALL/ANY need different checks.
638 */
639 virtual bool process_nulls() const { return value_transform != BOOL_IS_TRUE; }
640 bool return_value(bool v) override;
641
642 bool transformer(THD *thd, Item **transformed) override;
644 Item **transformed);
646 Item **transformed);
647 bool row_value_transformer(THD *thd, Item **transformed);
649 Comp_creator *func);
651 Item_in_optimizer *optimizer);
652 bool subquery_allows_materialization(THD *thd, Query_block *query_block,
653 const Query_block *outer);
654 bool walk(Item_processor processor, enum_walk walk, uchar *arg) override;
656 Item *compile(Item_analyzer analyzer, uchar **arg_p,
657 Item_transformer transformer, uchar *arg_t) override;
658
659 bool exec(THD *thd) override;
660 longlong val_int() override;
661 double val_real() override;
662 String *val_str(String *) override;
663 my_decimal *val_decimal(my_decimal *) override;
664 bool val_bool() override;
665 bool test_limit();
666 void print(const THD *thd, String *str,
667 enum_query_type query_type) const override;
668 void fix_after_pullout(Query_block *parent_query_block,
669 Query_block *removed_query_block) override;
670 void update_used_tables() override;
671 bool init_left_expr_cache(THD *thd);
672
673 /**
674 Once the decision to use IN->EXISTS has been taken, performs some last
675 steps of this transformation.
676 */
677 bool finalize_exists_transform(THD *thd, Query_block *select);
678 /**
679 Once the decision to use materialization has been taken, performs some
680 last steps of this transformation.
681 */
683 AccessPath *root_access_path() const override;
684 std::optional<ContainedSubquery> get_contained_subquery(
685 const Query_block *outer_query_block) override;
686
688 return m_in2exists_info != nullptr && m_in2exists_info->added_to_where;
689 }
690
691 /// Is reliable only if IN->EXISTS has been done.
693 return m_in2exists_info->dependent_before;
694 }
695
696 bool *get_cond_guard(int i) const {
697 return m_pushed_cond_guards != nullptr ? m_pushed_cond_guards + i : nullptr;
698 }
699 void set_cond_guard_var(int i, bool v) const {
700 if (m_pushed_cond_guards != nullptr) m_pushed_cond_guards[i] = v;
701 }
702
705 friend class Item_in_optimizer;
708
709 /// Used to trigger on/off conditions that were pushed down to subquery
710 bool *m_pushed_cond_guards{nullptr};
711
712 /// Point on NOT/NOP before ALL/SOME subquery
714
715 protected:
716 /**
717 Cache of the left operand of the subquery predicate. Allocated in the
718 runtime memory root, for each execution, thus need not be freed.
719 */
721
722 /// Whether m_left_expr_cache holds a value
724
725 /// The need for expr cache may be optimized away, @sa init_left_expr_cache.
726 bool need_expr_cache{true};
727
728 private:
729 bool mark_as_outer(Item *left_row, size_t col);
730
731 /**
732 In the case of
733
734 x COMP_OP (SELECT1 UNION SELECT2 ...)
735
736 - the subquery transformation is done on SELECT1; this requires wrapping
737 'x' with more Item layers, and injecting that in a condition in SELECT1.
738
739 - the same transformation is done on SELECT2; but the wrapped 'x' doesn't
740 need to be created again, the one created for SELECT1 could be reused
741
742 - to achieve this, the wrapped 'x' is stored in member
743 'm_injected_left_expr' when it is created for SELECT1, and is later
744 reused for SELECT2.
745
746 This will refer to a cached value which is reevaluated once for each
747 candidate row, cf. setup in #single_value_transformer.
748 */
750
751 bool m_was_null{false};
752
753 /**
754 This bundles several pieces of information useful when doing the
755 IN->EXISTS transform. If this transform has not been done, pointer is
756 NULL.
757 */
759 /**
760 True: if IN->EXISTS has been done and has added a condition to the
761 subquery's WHERE clause.
762 */
764 /**
765 True: if subquery was dependent (correlated) before IN->EXISTS
766 was done.
767 */
769 /**
770 True: if subquery was dependent (correlated) after IN->EXISTS
771 was done.
772 */
774 } *m_in2exists_info{nullptr};
775
777
778 bool val_bool_naked();
779};
780
781/**
782 Class that represents a quantified comparison predicate.
783
784 expression comp-op ANY ( subquery )
785 expression comp-op ALL ( subquery )
786
787 Note that the special cases = ANY (aka IN) and <> ALL (aka NOT IN)
788 are handled by the base class Item_in_subselect.
789*/
791 public:
794 bool all);
795
796 Subquery_type subquery_type() const override {
798 }
800
801 Item *truth_transformer(THD *, enum Bool_test test) override;
802 void apply_is_true() override {
803 implicit_is_op = true;
806 } else if (value_transform == BOOL_NEGATED) {
808 }
809 }
810 bool process_nulls() const override {
811 return !ignore_unknown() || m_all_subquery;
812 }
813 bool eqne_op() const;
814 bool return_value(bool v) override;
815
816 bool transformer(THD *thd, Item **transformed) override;
817 void print(const THD *thd, String *str,
818 enum_query_type query_type) const override;
819
820 private:
821 /// The original source for the comparison function
823 /// The comparison function generator, possibly inverted by NOT
825 /// Whether ALL or ANY subquery
827 /// Used to generate the correct comparison function
828 bool m_inverted{false};
829};
830
831/**
832 A subquery execution engine that evaluates the subquery by doing index
833 lookups in a single table's index.
834
835 This engine is used to resolve subqueries in forms
836
837 outer_expr IN (SELECT tbl.key FROM tbl WHERE subq_where)
838
839 or, row-based:
840
841 (oe1, .. oeN) IN (SELECT key_part1, ... key_partK
842 FROM tbl WHERE subqwhere)
843
844 i.e. the subquery is a single table SELECT without GROUP BY, aggregate
845 functions, etc.
846*/
848 protected:
849 Query_result_union *result = nullptr; /* results storage class */
850 /// Table which is read, using one of eq_ref, ref, ref_or_null.
851 TABLE *table{nullptr};
855 Item *m_cond; ///< The WHERE condition of the subquery
856 ulonglong m_hash; ///< Hash value calculated by RefIterator, when needed.
857 /*
858 The "having" clause. This clause (further referred to as "artificial
859 having") was inserted by subquery transformation code. It contains
860 Item(s) that have a side-effect: they record whether the subquery has
861 produced a row with NULL certain components. We need to use it for cases
862 like
863 (oe1, oe2) IN (SELECT t.key, t.no_key FROM t1)
864 where we do index lookup on t.key=oe1 but need also to check if there
865 was a row such that t.no_key IS NULL.
866 */
868
869 Item_in_subselect *item; /* item that uses this engine */
870
871 public:
873
875 const Index_lookup &ref,
876 enum join_type join_type,
878 Item *having)
879 : table(table),
881 ref(ref),
883 m_cond(where),
884 m_having(having),
885 item(subs) {}
887 virtual bool exec(THD *thd);
888 virtual void print(const THD *thd, String *str, enum_query_type query_type);
890 virtual void cleanup() {}
891 virtual void create_iterators(THD *) {}
892};
893
894/*
895 This function is actually defined in sql_parse.cc, but it depends on
896 chooser_compare_func_creator defined in this file.
897 */
898Item *all_any_subquery_creator(THD *thd, const POS &pos, Item *left_expr,
900 Query_block *select);
901
902/**
903 Compute an IN predicate via a hash semi-join. The subquery is materialized
904 during the first evaluation of the IN predicate. The IN predicate is executed
905 via the functionality inherited from subselect_indexsubquery_engine.
906*/
907
909 private:
910 /* true if the subquery was materialized into a temp table. */
912 // true if we know for sure that there are zero rows in the table.
913 // Set only after is_materialized is true.
914 bool has_zero_rows = false;
915 /**
916 Existence of inner NULLs in materialized table:
917 By design, other values than IRRELEVANT_OR_FALSE are possible only if the
918 subquery has only one inner expression.
919 */
921 /// none, or they don't matter
923 /// they matter, and we don't know yet if they exists
925 /// they matter, and we know there exists at least one.
926 NEX_TRUE = 2
927 };
932
933 /// Saved result object, must be restored after use
935
936 public:
938 Query_expression *query_expr)
940 in_predicate, nullptr, nullptr),
941 is_materialized(false),
942 m_query_expr(query_expr) {}
943 ~subselect_hash_sj_engine() override;
944
945 bool setup(THD *thd, const mem_root_deque<Item *> &tmp_columns);
946 void cleanup() override;
947 bool exec(THD *thd) override;
948 void print(const THD *thd, String *str, enum_query_type query_type) override;
949 enum_engine_type engine_type() const override { return HASH_SJ_ENGINE; }
950
951 TABLE *get_table() const { return table; }
952 const Index_lookup &index_lookup() const { return ref; }
953 enum join_type get_join_type() const { return type; }
955 void create_iterators(THD *thd) override;
956};
957
958/**
959 Removes every predicate injected by IN->EXISTS.
960
961 This function is different from others:
962 - it wants to remove all traces of IN->EXISTS (for
963 materialization)
964 - remove_subq_pushed_predicates() and remove_additional_cond() want to
965 remove only the conditions of IN->EXISTS which index lookup already
966 satisfies (they are just an optimization).
967
968 If there are no in2exists conditions, it will return the exact same
969 pointer. If it returns a new Item, the old Item is left alone, so it
970 can be reused in other settings.
971
972 @param conds Condition; may be nullptr.
973 @returns new condition
974 */
976
977/// @returns whether the item is a quantified comparison predicate
979
980#endif /* ITEM_SUBSELECT_INCLUDED */
Kerberos Client Authentication nullptr
Definition: auth_kerberos_client_plugin.cc:247
Abstract factory interface for creating comparison predicates.
Definition: item_cmpfunc.h:546
Definition: my_temporal.h:395
Definition: my_temporal.h:339
Definition: field.h:570
Class that represents a quantified comparison predicate.
Definition: item_subselect.h:790
Comp_creator * m_compare_func
The comparison function generator, possibly inverted by NOT.
Definition: item_subselect.h:824
bool transformer(THD *thd, Item **transformed) override
Definition: item_subselect.cc:3117
bool return_value(bool v) override
ALL and ANY subquery predicates are wrapped in an Item_func_not_all or Item_func_nop_all object that ...
Definition: item_subselect.cc:1444
Item_allany_subselect(const POS &pos, Item *left_expr, chooser_compare_func_creator fc, Query_block *select, bool all)
Definition: item_subselect.cc:1530
Subquery_type subquery_type() const override
Definition: item_subselect.h:796
Comp_creator * compare_func() const
Definition: item_subselect.h:799
bool eqne_op() const
Definition: item_subselect.cc:3149
void print(const THD *thd, String *str, enum_query_type query_type) const override
This method is used for to:
Definition: item_subselect.cc:3157
bool process_nulls() const override
Definition: item_subselect.h:810
void apply_is_true() override
Apply the IS TRUE truth property, meaning that an UNKNOWN result and a FALSE result are treated the s...
Definition: item_subselect.h:802
Item * truth_transformer(THD *, enum Bool_test test) override
Informs an item that it is wrapped in a truth test, in case it wants to transforms itself to implemen...
Definition: item_subselect.cc:3095
chooser_compare_func_creator m_func_creator
The original source for the comparison function.
Definition: item_subselect.h:822
bool m_all_subquery
Whether ALL or ANY subquery.
Definition: item_subselect.h:826
bool m_inverted
Used to generate the correct comparison function.
Definition: item_subselect.h:828
Definition: item.h:6899
Definition: item_subselect.h:460
bool val_time(Time_val *time) override
Evaluate the item and return result as a time value.
Definition: item_subselect.h:575
enum_condition_context outer_condition_context
Used by the transformation to derived table.
Definition: item_subselect.h:484
void apply_is_true() override
Apply the IS TRUE truth property, meaning that an UNKNOWN result and a FALSE result are treated the s...
Definition: item_subselect.h:558
bool resolve_type(THD *thd) override
Resolve type-related information for this item, such as result field type, maximum size,...
Definition: item_subselect.cc:1546
String * val_str(String *) override
Return the result of EXISTS as a string value.
Definition: item_subselect.cc:1877
bool val_date(Date_val *date, my_time_flags_t flags) override
Evaluate the item and return result as a date value.
Definition: item_subselect.h:572
bool m_value
value of this item (boolean: exists/not-exists)
Definition: item_subselect.h:590
double val_real() override
Definition: item_subselect.cc:1863
bool implicit_is_op
True if the IS TRUE/FALSE wasn't explicit in the query.
Definition: item_subselect.h:545
bool is_semijoin_candidate(THD *thd) const
Definition: item_subselect.cc:1585
Item * truth_transformer(THD *, enum Bool_test test) override
Informs an item that it is wrapped in a truth test, in case it wants to transforms itself to implemen...
Definition: item_subselect.cc:1460
longlong val_int() override
Definition: item_subselect.cc:1865
bool is_derived_candidate(THD *thd) const
Definition: item_subselect.cc:1681
Subquery_strategy strategy
Execution strategy chosen for this Item.
Definition: item_subselect.h:482
Item_exists_subselect(const POS &pos, Query_block *query_block)
Create an Item that represents an EXISTS subquery predicate, or any quantified comparison predicate t...
Definition: item_subselect.cc:1355
Item * left_expr
Definition: item_subselect.h:477
virtual bool return_value(bool v)
Convert result according to value_transform, null value and supplied value.
Definition: item_subselect.cc:1394
bool val_bool() override
Definition: item_subselect.cc:1901
int sj_convert_priority
Priority of this predicate in the convert-to-semi-join-nest process.
Definition: item_subselect.h:480
void reset() override
Reset state after a single execution of a subquery, useful when a dependent subquery must be evaluate...
Definition: item_subselect.h:522
void print(const THD *thd, String *str, enum_query_type query_type) const override
This method is used for to:
Definition: item_subselect.cc:1368
virtual bool transformer(THD *thd, Item **transformed)
Definition: item_subselect.cc:1568
bool val_datetime(Datetime_val *dt, my_time_flags_t flags) override
Evaluate the item and return result as a datetime value.
Definition: item_subselect.h:576
bool with_is_op() const
Definition: item_subselect.h:533
bool fix_fields(THD *thd, Item **ref) override
An object of class Item_in_subselect is always substituted with another object of class Item_in_optim...
Definition: item_subselect.cc:2833
enum Bool_test value_transform
Definition: item_subselect.h:532
void notify_removal() override
Called when an item has been removed, can be used to notify external objects about the removal,...
Definition: item_subselect.h:503
Subquery_type subquery_type() const override
Definition: item_subselect.h:520
bool allow_table_subquery_transform() const
Helper for is_semijoin_candidate() and is_derived_candidate().
Definition: item_subselect.cc:1811
Item_subselect super
Definition: item_subselect.h:461
bool is_bool_func() const override
Definition: item_subselect.h:521
Table_ref * embedding_join_nest
Used by subquery optimizations to keep track about where this subquery predicate is located,...
Definition: item_subselect.h:501
Item_exists_subselect(const POS &pos)
Definition: item_subselect.h:474
my_decimal * val_decimal(my_decimal *) override
Return the result of EXISTS as a decimal value.
Definition: item_subselect.cc:1894
bool use_anti_join_transform() const
Definition: item_subselect.cc:1843
enum Item_result result_type() const override
Definition: item_subselect.h:527
Definition: item_cmpfunc.h:970
Definition: item_cmpfunc.h:512
Representation of IN subquery predicates of the form "left_expr IN (SELECT ...)".
Definition: item_subselect.h:608
Item_in_subselect(const POS &pos, Item *left_expr, Query_block *query_block)
Definition: item_subselect.cc:1494
void fix_after_pullout(Query_block *parent_query_block, Query_block *removed_query_block) override
Definition: item_subselect.cc:2904
my_decimal * val_decimal(my_decimal *) override
Return the result of EXISTS as a decimal value.
Definition: item_subselect.cc:1953
Item * compile(Item_analyzer analyzer, uchar **arg_p, Item_transformer transformer, uchar *arg_t) override
Perform a generic "compilation" of the Item tree, ie transform the Item tree by adding zero or more I...
Definition: item_subselect.cc:796
double val_real() override
Definition: item_subselect.cc:1910
struct Item_in_subselect::In2exists_info nullptr
virtual bool process_nulls() const
Definition: item_subselect.h:639
bool m_left_expr_cache_filled
Whether m_left_expr_cache holds a value.
Definition: item_subselect.h:723
bool single_value_transformer(THD *thd, Comp_creator *func, Item **transformed)
Transform a single-column IN/ALL/ANY subquery predicate.
Definition: item_subselect.cc:1989
void set_cond_guard_var(int i, bool v) const
Definition: item_subselect.h:699
bool row_value_transformer(THD *thd, Item **transformed)
Transform a multi-column IN/ALL/ANY subquery predicate.
Definition: item_subselect.cc:2429
std::optional< ContainedSubquery > get_contained_subquery(const Query_block *outer_query_block) override
If this item represents a IN/ALL/ANY/comparison_operator subquery, return that (along with data on ho...
Definition: item_subselect.cc:2962
Item_func_not_all * m_upper_item
Point on NOT/NOP before ALL/SOME subquery.
Definition: item_subselect.h:713
bool need_expr_cache
The need for expr cache may be optimized away,.
Definition: item_subselect.h:726
bool finalize_materialization_transform(THD *thd, JOIN *join)
Once the decision to use materialization has been taken, performs some last steps of this transformat...
Definition: item_subselect.cc:506
bool do_itemize(Parse_context *pc, Item **res) override
The core function that does the actual itemization.
Definition: item_subselect.cc:1517
void print(const THD *thd, String *str, enum_query_type query_type) const override
This method is used for to:
Definition: item_subselect.cc:2791
Item_in_subselect(const POS &pos)
Definition: item_subselect.h:616
void reset() override
Reset state after a single execution of a subquery, useful when a dependent subquery must be evaluate...
Definition: item_subselect.h:624
List< Cached_item > * m_left_expr_cache
Cache of the left operand of the subquery predicate.
Definition: item_subselect.h:720
bool mark_as_outer(Item *left_row, size_t col)
Decide whether to mark the injected left expression "outer" relative to the subquery.
Definition: item_subselect.cc:458
Item * transform(Item_transformer transformer, uchar *arg) override
Perform a generic transformation of the Item tree, by adding zero or more additional Item objects to ...
Definition: item_subselect.cc:789
bool * m_pushed_cond_guards
Used to trigger on/off conditions that were pushed down to subquery.
Definition: item_subselect.h:710
bool dependent_before_in2exists() const
Is reliable only if IN->EXISTS has been done.
Definition: item_subselect.h:692
AccessPath * root_access_path() const override
Definition: item_subselect.cc:597
PT_subquery * pt_subselect
Definition: item_subselect.h:776
longlong val_int() override
Definition: item_subselect.cc:1917
bool return_value(bool v) override
Same as for Item_exists_subselect(), except it has to process NULL values.
Definition: item_subselect.cc:1404
bool * get_cond_guard(int i) const
Definition: item_subselect.h:696
bool row_value_in_to_exists_transformer(THD *thd, Query_block *select, Item_in_optimizer *optimizer)
Transform a (possibly non-correlated) IN subquery into a correlated EXISTS.
Definition: item_subselect.cc:2494
bool finalize_exists_transform(THD *thd, Query_block *select)
Once the decision to use IN->EXISTS has been taken, performs some last steps of this transformation.
Definition: item_subselect.cc:465
bool val_bool() override
Definition: item_subselect.cc:1931
bool m_was_null
Definition: item_subselect.h:751
bool init_left_expr_cache(THD *thd)
Initialize the cache of the left operand of the IN predicate.
Definition: item_subselect.cc:2929
bool quantified_comp_transformer(THD *thd, Comp_creator *func, Item **transformed)
Perform transformation of quantified comparison predicates (ie.
Definition: item_subselect.cc:2705
void cleanup() override
Called for every Item after use (preparation and execution).
Definition: item_subselect.cc:565
String * val_str(String *) override
Return the result of EXISTS as a string value.
Definition: item_subselect.cc:1924
void update_used_tables() override
Updates used tables, not null tables information and accumulates properties up the item tree,...
Definition: item_subselect.cc:2911
bool in2exists_added_to_where() const
Definition: item_subselect.h:687
bool walk(Item_processor processor, enum_walk walk, uchar *arg) override
Traverses a tree of Items in prefix and/or postfix order.
Definition: item_subselect.cc:783
Item_exists_subselect super
Definition: item_subselect.h:609
Subquery_type subquery_type() const override
Definition: item_subselect.h:622
bool single_value_in_to_exists_transformer(THD *thd, Query_block *select, Comp_creator *func)
Transform an IN predicate into EXISTS via predicate injection.
Definition: item_subselect.cc:2214
bool test_limit()
Definition: item_subselect.cc:1488
bool ignore_unknown() const
Definition: item_subselect.h:630
bool val_bool_naked()
Definition: item_subselect.cc:1938
Item_ref * m_injected_left_expr
In the case of.
Definition: item_subselect.h:749
bool exec(THD *thd) override
Definition: item_subselect.cc:812
bool transformer(THD *thd, Item **transformed) override
Definition: item_subselect.cc:2689
Definition: item_cmpfunc.h:2434
Definition: item_subselect.h:404
void print(const THD *thd, String *str, enum_query_type query_type) const override
This method is used for to:
Definition: item_subselect.cc:1144
bool m_has_values
Set if we have found at least one row.
Definition: item_subselect.h:426
bool is_maxmin() const override
Definition: item_subselect.h:422
bool m_max
True if performing MAX, false if MIN.
Definition: item_subselect.h:425
void reset_has_values() override
Used by max/min subquery to initialize value presence registration mechanism.
Definition: item_subselect.h:421
void cleanup() override
Called for every Item after use (preparation and execution).
Definition: item_subselect.cc:1137
bool has_values() const
Definition: item_subselect.h:419
void register_value()
Definition: item_subselect.h:420
Item_maxmin_subselect(Item_subselect *parent, Query_block *query_block, bool max_arg)
Create an Item for use in transformation of quantified comparison predicates that can be evaluated us...
Definition: item_subselect.cc:1121
Definition: item.h:6455
Definition: item.h:6011
Item with result field.
Definition: item.h:5946
Class that represents scalar subquery and row subquery.
Definition: item_subselect.h:283
Item * replace_scalar_subquery(uchar *arge) override
When walking the item tree seeing an Item_singlerow_subselect matching a target, replace it with a su...
Definition: item_subselect.cc:3246
enum Item_result result_type() const override
Definition: item_subselect.cc:1164
void store(uint i, Item *item)
Definition: item_subselect.cc:1155
void cleanup() override
Called for every Item after use (preparation and execution).
Definition: item_subselect.cc:424
bool null_inside() override
Definition: item_subselect.cc:1218
Item ** addr(uint i) override
Definition: item_subselect.h:327
double val_real() override
Definition: item_subselect.cc:1232
bool resolve_type(THD *) override
Resolve type-related information for this item, such as result field type, maximum size,...
Definition: item_subselect.cc:1169
void no_rows_in_result() override
Definition: item_subselect.cc:1201
bool val_json(Json_wrapper *result) override
Get a JSON value from an Item.
Definition: item_subselect.cc:1277
bool val_datetime(Datetime_val *dt, my_time_flags_t flags) override
Evaluate the item and return result as a datetime value.
Definition: item_subselect.cc:1310
Item_cache ** m_row
Value cache for a row or scalar subquery.
Definition: item_subselect.h:399
bool val_time(Time_val *time) override
Evaluate the item and return result as a time value.
Definition: item_subselect.cc:1299
bool m_no_rows
no_rows_in_result
Definition: item_subselect.h:400
void reset() override
Reset state after a single execution of a subquery, useful when a dependent subquery must be evaluate...
Definition: item_subselect.cc:1150
Subquery_type subquery_type() const override
Definition: item_subselect.h:291
std::optional< ContainedSubquery > get_contained_subquery(const Query_block *outer_query_block) override
If this item represents a IN/ALL/ANY/comparison_operator subquery, return that (along with data on ho...
Definition: item_subselect.cc:3304
longlong val_int() override
Definition: item_subselect.cc:1243
uint cols() const override
Definition: item_subselect.cc:3526
virtual bool is_maxmin() const
Definition: item_subselect.h:333
bool is_single_column_scalar_subquery() const override
Definition: item_subselect.cc:1160
bool fix_fields(THD *thd, Item **ref) override
Definition: item_subselect.cc:356
Item * element_index(uint i) override
Definition: item_subselect.h:326
Item_singlerow_subselect()
Definition: item_subselect.h:287
Query_block * invalidate_and_restore_query_block()
This method is used to implement a special case of semantic tree rewriting, mandated by a SQL:2003 ex...
Definition: item_subselect.cc:936
bool collect_scalar_subqueries(uchar *) override
Definition: item_subselect.cc:3171
bool val_date(Date_val *date, my_time_flags_t flags) override
Evaluate the item and return result as a date value.
Definition: item_subselect.cc:1288
String * val_str(String *) override
Definition: item_subselect.cc:1254
bool val_bool() override
Definition: item_subselect.cc:1322
void bring_value() override
Definition: item_subselect.cc:1225
bool create_row(const mem_root_deque< Item * > &item_list, Item_cache **row, bool possibly_empty)
Makes storage for the output values for a scalar or row subquery and calculates their data and column...
Definition: item_subselect.cc:3425
bool check_cols(uint c) override
Definition: item_subselect.cc:1210
my_decimal * val_decimal(my_decimal *) override
Definition: item_subselect.cc:1265
Item_cache * m_value
Value cache of a scalar subquery.
Definition: item_subselect.h:393
Base class that is common to all subqueries and subquery predicates.
Definition: item_subselect.h:80
subselect_indexsubquery_engine * indexsubquery_engine
Only relevant for Item_in_subselect; optimized structure used for execution in place of running the e...
Definition: item_subselect.h:245
Item * replace_item_view_ref(uchar *arg) override
Transform processor.
Definition: item_subselect.cc:3409
void set_value_assigned()
Definition: item_subselect.h:156
bool clean_up_after_removal(uchar *arg) override
Clean up after removing the subquery from the item tree.
Definition: item_subselect.cc:3055
bool is_evaluated() const
Definition: item_subselect.cc:3153
enum_parsing_context m_parsing_place
where subquery is placed
Definition: item_subselect.h:255
bool collect_subqueries(uchar *) override
Definition: item_subselect.cc:3088
table_map used_tables() const override
Definition: item_subselect.h:164
void accumulate_expression(Item *item)
Accumulate properties from a selected expression within a query block.
Definition: item_subselect.cc:290
void accumulate_used_tables(table_map add_tables)
Accumulate used tables.
Definition: item_subselect.h:123
Query_expression * m_query_expr
The query expression of the subquery.
Definition: item_subselect.h:238
virtual Subquery_type subquery_type() const =0
bool check_function_as_value_generator(uchar *args) override
Check if this item is allowed for a virtual column or inside a default expression.
Definition: item_subselect.h:200
table_map subquery_used_tables() const
Definition: item_subselect.h:167
bool is_uncacheable() const
Definition: item_subselect.cc:3531
void accumulate_properties()
Accumulate properties from underlying query expression.
Definition: item_subselect.cc:226
virtual bool exec(THD *thd)
Definition: item_subselect.cc:690
Query_expression * query_expr() const
Definition: item_subselect.h:84
enum_engine_type
Definition: item_subselect.h:103
@ INDEXSUBQUERY_ENGINE
Definition: item_subselect.h:103
@ HASH_SJ_ENGINE
Definition: item_subselect.h:103
@ OTHER_ENGINE
Definition: item_subselect.h:103
void print(const THD *thd, String *str, enum_query_type query_type) const override
This method is used for to:
Definition: item_subselect.cc:888
Subquery_type
Definition: item_subselect.h:114
@ ALL_SUBQUERY
comp-op ALL quantified comparison predicate
Definition: item_subselect.h:118
@ IN_SUBQUERY
[NOT] IN subquery predicate
Definition: item_subselect.h:117
@ SCALAR_SUBQUERY
Scalar or row subquery.
Definition: item_subselect.h:115
@ ANY_SUBQUERY
comp-op ANY quantified comparison predicate
Definition: item_subselect.h:119
@ EXISTS_SUBQUERY
[NOT] EXISTS subquery predicate
Definition: item_subselect.h:116
void set_contextualized()
For Item_subselect constructor with POS parameter, the contextualized field must be transitioned expl...
Definition: item_subselect.h:90
bool explain_subquery_checker(uchar **arg) override
Register subquery to the table where it is used within a condition.
Definition: item_subselect.cc:683
bool m_value_assigned
True if value has been assigned to subquery.
Definition: item_subselect.h:271
Item * get_tmp_table_item(THD *thd) override
If an Item is materialized in a temporary table, a different Item may have to be used in the part of ...
Definition: item_subselect.cc:867
enum_parsing_context place()
Definition: item_subselect.h:193
virtual void reset()
Reset state after a single execution of a subquery, useful when a dependent subquery must be evaluate...
Definition: item_subselect.h:151
Item * replace_item_field(uchar *arg) override
Transform processor.
Definition: item_subselect.cc:3399
join_type get_join_type() const
Definition: item_subselect.cc:336
int in_cond_of_tab
If !=NO_PLAN_IDX: this Item is in the condition attached to the JOIN_TAB having this index in the par...
Definition: item_subselect.h:100
void accumulate_condition(Item *item)
Accumulate properties from a condition or GROUP/ORDER within a query block.
Definition: item_subselect.cc:301
virtual AccessPath * root_access_path() const
Definition: item_subselect.h:112
void create_iterators(THD *thd)
Definition: item_subselect.cc:306
void cleanup() override
Called for every Item after use (preparation and execution).
Definition: item_subselect.cc:341
Query_result_interceptor * m_query_result
The query result object associated with the query expression.
Definition: item_subselect.h:241
table_map m_subquery_used_tables
cache of used tables from subquery only (not including LHS of IN subquery)
Definition: item_subselect.h:250
const TABLE * get_table() const
Definition: item_subselect.cc:326
enum Type type() const override
Definition: item_subselect.cc:865
bool fix_fields(THD *thd, Item **ref) override
Definition: item_subselect.cc:618
void set_indexsubquery_engine(subselect_indexsubquery_engine *eng)
Definition: item_subselect.h:173
void bind(Query_expression *qe)
Bind this subquery object with the supplied query expression.
Definition: item_subselect.cc:170
void reset_value_assigned()
Definition: item_subselect.h:157
bool contains_outer_references() const
Return whether this subquery references any tables in the directly containing query block,...
Definition: item_subselect.h:131
table_map not_null_tables() const override
Return table map of tables that can't be NULL tables (tables that are used in a context where if they...
Definition: item_subselect.h:165
void update_used_tables() override
Updates used tables, not null tables information and accumulates properties up the item tree,...
Definition: item_subselect.cc:879
bool walk(Item_processor processor, enum_walk walk, uchar *arg) override
Traverses a tree of Items in prefix and/or postfix order.
Definition: item_subselect.cc:662
Item_subselect()
Definition: item_subselect.h:226
bool is_null() override
The method allows to determine nullness of a complex expression without fully evaluating it,...
Definition: item_subselect.h:159
const Index_lookup & index_lookup() const
Definition: item_subselect.cc:331
enum_engine_type engine_type() const
Definition: item_subselect.cc:312
bool is_value_assigned() const
Definition: item_subselect.h:155
Item_result_field super
Definition: item_subselect.h:81
bool m_traced_before
Whether or not execution of this subquery has been traced by optimizer tracing already.
Definition: item_subselect.h:278
bool inform_item_in_cond_of_tab(uchar *arg) override
Tells an Item that it is in the condition of a JOIN_TAB of a query block.
Definition: item_subselect.cc:3027
virtual void reset_has_values()
Used by max/min subquery to initialize value presence registration mechanism.
Definition: item_subselect.h:188
bool subq_opt_away_processor(uchar *arg) override
Mark the subquery as optimized away, for EXPLAIN.
Definition: item_subselect.cc:3039
uint m_max_columns
allowed number of columns (1 for scalar subqueries)
Definition: item_subselect.h:253
virtual bool is_single_column_scalar_subquery() const
Definition: item_subselect.h:142
void fix_after_pullout(Query_block *parent_query_block, Query_block *removed_query_block) override
Definition: item_subselect.cc:763
Item_subselect(const POS &pos)
Definition: item_subselect.h:227
table_map m_used_tables_cache
cache of used tables
Definition: item_subselect.h:248
Base class that is used to represent any kind of expression in a relational query.
Definition: item.h:928
bool get_date_from_int(Date_val *date, my_time_flags_t flags)
Convert val_int() to date.
Definition: item.cc:1599
void set_subquery()
Set the "has subquery" property.
Definition: item.h:3500
bool null_value
True if item is null.
Definition: item.h:3773
bool get_datetime_from_int(Datetime_val *dt, my_time_flags_t flags)
Convert val_int() to datetime.
Definition: item.cc:1593
bool get_time_from_int(Time_val *time)
Convert val_int() to time.
Definition: item.cc:1722
Bool_test
< Modifier for result transformation
Definition: item.h:1006
@ BOOL_NOT_FALSE
Definition: item.h:1011
@ BOOL_NOT_TRUE
Definition: item.h:1010
@ BOOL_IS_TRUE
Definition: item.h:1007
@ BOOL_IS_FALSE
Definition: item.h:1008
@ BOOL_IDENTITY
Definition: item.h:1013
@ BOOL_NEGATED
Definition: item.h:1014
bool update_null_value()
Make sure the null_value member has a correct value.
Definition: item.cc:7876
Definition: sql_optimizer.h:133
Abstraction for accessing JSON values irrespective of whether they are (started out as) binary JSON v...
Definition: json_dom.h:1225
Definition: sql_list.h:494
Definition: parse_tree_nodes.h:1808
Base class for parse tree nodes (excluding the Parse_tree_root hierarchy)
Definition: parse_tree_node_base.h:231
bool contextualized
Definition: parse_tree_node_base.h:240
This class represents a query block, aka a query specification, which is a query consisting of a SELE...
Definition: sql_lex.h:1179
This class represents a query expression (one query block or several query blocks combined with UNION...
Definition: sql_lex.h:643
Definition: item_subselect.cc:1333
Definition: query_result.h:191
Query result class for scalar and row subqueries.
Definition: item_subselect.cc:107
Base class for result from a subquery.
Definition: query_result.h:340
Definition: sql_union.h:40
Using this class is fraught with peril, and you need to be very careful when doing so.
Definition: sql_string.h:169
For each client connection we create a separate thread with THD serving as a thread/connection descri...
Definition: sql_lexer_thd.h:36
Definition: table.h:2933
Object containing parameters used when creating and using temporary tables.
Definition: temp_table_param.h:97
Time_val is a temporal type that represents only time.
Definition: my_temporal.h:55
A (partial) implementation of std::deque allocating its blocks on a MEM_ROOT.
Definition: mem_root_deque.h:111
my_decimal class limits 'decimal_t' type to what we need in MySQL.
Definition: my_decimal.h:97
Compute an IN predicate via a hash semi-join.
Definition: item_subselect.h:908
void create_iterators(THD *thd) override
Definition: item_subselect.cc:3769
void print(const THD *thd, String *str, enum_query_type query_type) override
Print the state of this engine into a string for debugging and views.
Definition: item_subselect.cc:4002
nulls_exist
Existence of inner NULLs in materialized table: By design, other values than IRRELEVANT_OR_FALSE are ...
Definition: item_subselect.h:920
@ NEX_TRUE
they matter, and we know there exists at least one.
Definition: item_subselect.h:926
@ NEX_UNKNOWN
they matter, and we don't know yet if they exists
Definition: item_subselect.h:924
@ NEX_IRRELEVANT_OR_FALSE
none, or they don't matter
Definition: item_subselect.h:922
void cleanup() override
Cleanup performed after each execution.
Definition: item_subselect.cc:3847
unique_ptr_destroy_only< RowIterator > m_iterator
Definition: item_subselect.h:930
subselect_hash_sj_engine(Item_in_subselect *in_predicate, Query_expression *query_expr)
Definition: item_subselect.h:937
TABLE * get_table() const
Definition: item_subselect.h:951
~subselect_hash_sj_engine() override
Definition: item_subselect.cc:3836
Query_result_interceptor * saved_result
Saved result object, must be restored after use.
Definition: item_subselect.h:934
enum nulls_exist mat_table_has_nulls
Definition: item_subselect.h:928
bool is_materialized
Definition: item_subselect.h:911
Query_expression *const m_query_expr
Definition: item_subselect.h:929
bool has_zero_rows
Definition: item_subselect.h:914
const Index_lookup & index_lookup() const
Definition: item_subselect.h:952
bool exec(THD *thd) override
Execute a subquery IN predicate via materialization.
Definition: item_subselect.cc:3882
enum_engine_type engine_type() const override
Definition: item_subselect.h:949
AccessPath * root_access_path() const
Definition: item_subselect.h:954
bool setup(THD *thd, const mem_root_deque< Item * > &tmp_columns)
Create all structures needed for subquery execution using hash semijoin.
Definition: item_subselect.cc:3599
enum join_type get_join_type() const
Definition: item_subselect.h:953
AccessPath * m_root_access_path
Definition: item_subselect.h:931
A subquery execution engine that evaluates the subquery by doing index lookups in a single table's in...
Definition: item_subselect.h:847
Item * m_cond
The WHERE condition of the subquery.
Definition: item_subselect.h:855
TABLE * table
Table which is read, using one of eq_ref, ref, ref_or_null.
Definition: item_subselect.h:851
virtual ~subselect_indexsubquery_engine()=default
virtual void cleanup()
Definition: item_subselect.h:890
virtual bool exec(THD *thd)
Definition: item_subselect.cc:3515
virtual void print(const THD *thd, String *str, enum_query_type query_type)
Definition: item_subselect.cc:3535
virtual void create_iterators(THD *)
Definition: item_subselect.h:891
Item * m_having
Definition: item_subselect.h:867
join_type type
Definition: item_subselect.h:854
enum_engine_type
Definition: item_subselect.h:872
@ HASH_SJ_ENGINE
Definition: item_subselect.h:872
@ INDEXSUBQUERY_ENGINE
Definition: item_subselect.h:872
Index_lookup ref
Definition: item_subselect.h:853
subselect_indexsubquery_engine(TABLE *table, Table_ref *table_ref, const Index_lookup &ref, enum join_type join_type, Item_in_subselect *subs, Item *where, Item *having)
Definition: item_subselect.h:874
ulonglong m_hash
Hash value calculated by RefIterator, when needed.
Definition: item_subselect.h:856
virtual enum_engine_type engine_type() const
Definition: item_subselect.h:889
Item_in_subselect * item
Definition: item_subselect.h:869
Table_ref * table_ref
Definition: item_subselect.h:852
Comp_creator *(*)(bool invert) chooser_compare_func_creator
Convenience typedef for a function that returns factories for Item comparators (ie....
Definition: comp_creator.h:39
static int cmp(Bigint *a, Bigint *b)
Definition: dtoa.cc:1064
enum_query_type
Query type constants (usable as bitmap flags).
Definition: enum_query_type.h:31
This file contains the field type.
bool subquery_allows_materialization(THD *thd, Query_block *query_block, const Query_block *outer)
Check if the subquery predicate can be executed via materialization.
Definition: sql_resolver.cc:1059
Item * all_any_subquery_creator(THD *thd, const POS &pos, Item *left_expr, chooser_compare_func_creator cmp, bool all, Query_block *select)
Construct ALL/ANY/SOME subquery Item.
Definition: sql_parse.cc:6795
static int flags[50]
Definition: hp_test1.cc:40
bool(Item::* Item_analyzer)(uchar **argp)
Definition: item.h:710
Item *(Item::* Item_transformer)(uchar *arg)
Type for transformers used by Item::transform and Item::compile.
Definition: item.h:719
Item * remove_in2exists_conds(Item *conds)
Removes every predicate injected by IN->EXISTS.
Definition: item_subselect.cc:490
Subquery_strategy
Classes that represent predicates over table subqueries: [NOT] EXISTS, [NOT] IN, ANY/SOME and ALL.
Definition: item_subselect.h:438
@ CANDIDATE_FOR_SEMIJOIN
Candidate for semi-join flattening.
@ UNSPECIFIED
Nothing decided yet.
@ SUBQ_EXISTS
Evaluate as EXISTS subquery (possibly after rewriting from another type)
@ DERIVED_TABLE
Rewrite to joined derived table.
@ DELETED
Subquery has been deleted, probably because it was always false.
@ CANDIDATE_FOR_IN2EXISTS_OR_MAT
Candidate for rewriting IN(subquery) to EXISTS, or subquery materialization.
@ SEMIJOIN
Semi-join flattening.
@ SUBQ_MATERIALIZATION
Subquery materialization (HASH_SJ_ENGINE)
@ CANDIDATE_FOR_DERIVED_TABLE
Candidate for rewriting to joined derived table.
bool is_quantified_comp_predicate(Item *item)
Definition: item_subselect.cc:2994
This file follows Google coding style, except for the name MEM_ROOT (which is kept for historical rea...
std::unique_ptr< T, Destroy_only< T > > unique_ptr_destroy_only
std::unique_ptr, but only destroying.
Definition: my_alloc.h:480
Some integer typedefs for easier portability.
unsigned long long int ulonglong
Definition: my_inttypes.h:56
unsigned char uchar
Definition: my_inttypes.h:52
long long int longlong
Definition: my_inttypes.h:55
uint64_t table_map
Definition: my_table_map.h:30
Interface for low level time utilities.
unsigned int my_time_flags_t
Flags to str_to_datetime and number_to_datetime.
Definition: my_time.h:85
static char * where
Definition: mysqldump.cc:153
std::string str(const mysqlrouter::ConfigGenerator::Options::Endpoint &ep)
Definition: config_generator.cc:1078
PT & ref(PT *tp)
Definition: tablespace_impl.cc:359
MediaType
Definition: media_type.h:33
std::string join(const detail::range auto &rng, std::string_view delim)
join elements of a range into a string separated by a delimiter.
Definition: string.h:74
int add_tables(PFS_engine_table_share_proxy **, unsigned int) noexcept
Definition: pfs_plugin_table_v1_all_empty.cc:33
enum_parsing_context
Names for different query parse tree parts.
Definition: parse_tree_node_base.h:61
@ CTX_NONE
Empty value.
Definition: parse_tree_node_base.h:62
File containing constants that can be used throughout the server.
constexpr const table_map PSEUDO_TABLE_BITS
Definition: sql_const.h:114
enum_walk
Enumeration for {Item,Query_block[_UNIT],Table_function}walk.
Definition: sql_const.h:289
bool(Item::*)(unsigned char *) Item_processor
Processor type for {Item,Query_block[_UNIT],Table_function}walk.
Definition: sql_const.h:307
enum_condition_context
Enumeration for Query_block::condition_context.
Definition: sql_const.h:313
Common types of the Optimizer, used by optimization and execution.
join_type
Definition: sql_opt_exec_shared.h:186
@ JT_UNKNOWN
Definition: sql_opt_exec_shared.h:188
#define NO_PLAN_IDX
undefined index
Definition: sql_opt_exec_shared.h:55
Access paths are a query planning structure that correspond 1:1 to iterators, in that an access path ...
Definition: access_path.h:238
Struct used to pass around arguments to/from check_function_as_value_generator.
Definition: item.h:486
int err_code
the error code found during check(if any)
Definition: item.h:493
int get_unnamed_function_error_code() const
Return the correct error code, based on whether or not if we are checking for disallowed functions in...
Definition: item.h:505
Structure used for index-based lookups.
Definition: sql_opt_exec_shared.h:67
This bundles several pieces of information useful when doing the IN->EXISTS transform.
Definition: item_subselect.h:758
bool added_to_where
True: if IN->EXISTS has been done and has added a condition to the subquery's WHERE clause.
Definition: item_subselect.h:763
bool dependent_before
True: if subquery was dependent (correlated) before IN->EXISTS was done.
Definition: item_subselect.h:768
bool dependent_after
True: if subquery was dependent (correlated) after IN->EXISTS was done.
Definition: item_subselect.h:773
Argument for walk method replace_scalar_subquery.
Definition: item_subselect.h:338
Query_block * m_outer_query_block
The immediately surrounding query block.
Definition: item_subselect.h:346
Field * m_field
The transformed query block.
Definition: item_subselect.h:344
TABLE * m_derived
the replacement field
Definition: item_subselect.h:342
Scalar_subquery_replacement(Item_singlerow_subselect *target, TABLE *derived, Field *field, Query_block *select, bool add_coalesce, bool add_having_compensation, uint having_idx)
Definition: item_subselect.h:359
Query_block * m_inner_query_block
True if subquery's selected item contains a COUNT aggregate.
Definition: item_subselect.h:349
bool m_add_coalesce
Presence of HAVING clause in subquery: Only relevant if m_add_coalesce is true.
Definition: item_subselect.h:351
Item_singlerow_subselect * m_target
< subquery to be replaced with ␓field from derived table
Definition: item_subselect.h:340
bool m_add_having_compensation
Index of field holding value of having clause in derived table's list of fields.
Definition: item_subselect.h:354
uint m_having_idx
Definition: item_subselect.h:357
argument used by walk method collect_scalar_subqueries ("css")
Definition: item_subselect.h:208
Collect_subq_info(Query_block *owner)
Definition: item_subselect.h:212
Query_block * m_query_block
Definition: item_subselect.h:211
std::vector< Item_subselect * > list
< accumulated all subq (or aggregates) found
Definition: item_subselect.h:210
bool contains(Query_expression *candidate)
Definition: item_subselect.h:213
Bison "location" class.
Definition: parse_location.h:43
Environment data for the contextualization phase.
Definition: parse_tree_node_base.h:422
Definition: table.h:1435
Definition: result.h:30
Item_result
Type of the user defined function return slot and arguments.
Definition: udf_registration_types.h:39
@ INT_RESULT
double
Definition: udf_registration_types.h:43
static int all(site_def const *s, node_no node)
Definition: xcom_transport.cc:890