MySQL 5.6.14 Source Code Document
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
sql_select.h
Go to the documentation of this file.
1 #ifndef SQL_SELECT_INCLUDED
2 #define SQL_SELECT_INCLUDED
3 
4 /* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
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 as published by
8  the Free Software Foundation; version 2 of the License.
9 
10  This program is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  GNU General Public License for more details.
14 
15  You should have received a copy of the GNU General Public License
16  along with this program; if not, write to the Free Software
17  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
18 
19 
27 #include "procedure.h"
28 #include <myisam.h>
29 #include "sql_array.h" /* Array */
30 #include "records.h" /* READ_RECORD */
31 #include "opt_range.h" /* SQL_SELECT, QUICK_SELECT_I */
32 #include "filesort.h"
33 
34 #include "mem_root_array.h"
35 #include "sql_executor.h"
36 #include "opt_explain_format.h" // for Extra_tag
37 
38 #include <functional>
44 #define LOWER_BITS(type,A) ((type) (((type) 1 << (A)) -1))
45 
46 /* Values in optimize */
47 #define KEY_OPTIMIZE_EXISTS 1
48 #define KEY_OPTIMIZE_REF_OR_NULL 2
49 #define FT_KEYPART (MAX_REF_PARTS+10)
50 
54 class Key_use {
55 public:
56  // We need the default constructor for unit testing.
57  Key_use()
58  : table(NULL),
59  val(NULL),
60  used_tables(0),
61  key(0),
62  keypart(0),
63  optimize(0),
64  keypart_map(0),
65  ref_table_rows(0),
66  null_rejecting(false),
67  cond_guard(NULL),
68  sj_pred_no(UINT_MAX)
69  {}
70 
71  Key_use(TABLE *table_arg, Item *val_arg, table_map used_tables_arg,
72  uint key_arg, uint keypart_arg, uint optimize_arg,
73  key_part_map keypart_map_arg, ha_rows ref_table_rows_arg,
74  bool null_rejecting_arg, bool *cond_guard_arg,
75  uint sj_pred_no_arg) :
76  table(table_arg), val(val_arg), used_tables(used_tables_arg),
77  key(key_arg), keypart(keypart_arg), optimize(optimize_arg),
78  keypart_map(keypart_map_arg), ref_table_rows(ref_table_rows_arg),
79  null_rejecting(null_rejecting_arg), cond_guard(cond_guard_arg),
80  sj_pred_no(sj_pred_no_arg)
81  {}
83  Item *val;
84  table_map used_tables;
85  uint key;
86  uint keypart;
87  uint optimize;
88  key_part_map keypart_map;
89  ha_rows ref_table_rows;
90 
110  bool *cond_guard;
119 };
120 
121 
122 // Key_use has a trivial destructor, no need to run it from Mem_root_array.
124 
125 class store_key;
126 
127 typedef struct st_table_ref : public Sql_alloc
128 {
129  bool key_err;
132  uint key_parts;
133  uint key_length;
134  int key;
135  uchar *key_buff;
136  uchar *key_buff2;
137 
144  /*
145  Array of pointers to trigger variables. Some/all of the pointers may be
146  NULL. The ref access can be used iff
147 
148  for each used key part i, (!cond_guards[i] || *cond_guards[i])
149 
150  This array is used by subquery code. The subquery code may inject
151  triggered conditions, i.e. conditions that can be 'switched off'. A ref
152  access created from such condition is not valid when at least one of the
153  underlying conditions is switched off (see subquery code for more details).
154  If a table in a subquery has this it means that the table access
155  will switch from ref access to table scan when the outer query
156  produces a NULL value to be checked for in the subquery. This will
157  be used by NOT IN subqueries and IN subqueries for which
158  is_top_level_item() returns false.
159  */
160  bool **cond_guards;
165  key_part_map null_rejecting;
166  table_map depend_map;
167  /* null byte position in the key_buf. Used for REF_OR_NULL optimization */
168  uchar *null_ref_key;
169  /*
170  The number of times the record associated with this key was used
171  in the join.
172  */
173  ha_rows use_count;
174 
175  /*
176  TRUE <=> disable the "cache" as doing lookup with the same key value may
177  produce different results (because of Index Condition Pushdown)
178  */
179  bool disable_cache;
180 
181  st_table_ref()
182  : key_err(TRUE),
183  has_record(FALSE),
184  key_parts(0),
185  key_length(0),
186  key(-1),
187  key_buff(NULL),
188  key_buff2(NULL),
189  key_copy(NULL),
190  items(NULL),
191  cond_guards(NULL),
192  null_rejecting(0),
193  depend_map(0),
194  null_ref_key(NULL),
195  use_count(0),
196  disable_cache(FALSE)
197  {
198  }
199 
204  bool impossible_null_ref() const
205  {
206  if (null_rejecting != 0)
207  {
208  for (uint i= 0 ; i < key_parts ; i++)
209  {
210  if ((null_rejecting & 1 << i) && items[i]->is_null())
211  return TRUE;
212  }
213  }
214  return FALSE;
215  }
216 
217 
226  bool has_guarded_conds() const
227  {
228  DBUG_ASSERT(key_parts == 0 || cond_guards != NULL);
229 
230  for (uint i = 0; i < key_parts; i++)
231  {
232  if (cond_guards[i])
233  return true;
234  }
235  return false;
236  }
237 } TABLE_REF;
238 
239 
240 /*
241  The structs which holds the join connections and join states
242 */
243 enum join_type { /*
244  Initial state. Access type has not yet been decided
245  for the table
246  */
247  JT_UNKNOWN,
248  /* Table has exactly one row */
249  JT_SYSTEM,
250  /*
251  Table has at most one matching row. Values read
252  from this row can be treated as constants. Example:
253  "WHERE table.pk = 3"
254  */
255  JT_CONST,
256  /*
257  '=' operator is used on unique index. At most one
258  row is read for each combination of rows from
259  preceding tables
260  */
261  JT_EQ_REF,
262  /*
263  '=' operator is used on non-unique index
264  */
265  JT_REF,
266  /*
267  Full table scan or range scan.
268  If select->quick != NULL, it is range access.
269  Otherwise it is table scan.
270  */
271  JT_ALL,
272  /*
273  Range scan. Note that range scan is not indicated
274  by JT_RANGE but by "JT_ALL + select->quick" except
275  when printing EXPLAIN output. @see calc_join_type()
276  */
277  JT_RANGE,
278  /*
279  Like table scan, but scans index leaves instead of
280  the table
281  */
282  JT_INDEX_SCAN,
283  /* Fulltext index is used */
284  JT_FT,
285  /*
286  Like ref, but with extra search for NULL values.
287  E.g. used for "WHERE col = ... OR col IS NULL"
288  */
289  JT_REF_OR_NULL,
290  /*
291  Like eq_ref for subqueries: Replaces subquery with
292  index lookup in unique index
293  */
294  JT_UNIQUE_SUBQUERY,
295  /*
296  Like unique_subquery but for non-unique index
297  */
298  JT_INDEX_SUBQUERY,
299  /*
300  Do multiple range scans over one table and combine
301  the results into one. The merge can be used to
302  produce unions and intersections
303  */
304  JT_INDEX_MERGE};
305 
306 class JOIN;
307 
308 /* Values for JOIN_TAB::packed_info */
309 #define TAB_INFO_HAVE_VALUE 1
310 #define TAB_INFO_USING_INDEX 2
311 #define TAB_INFO_USING_WHERE 4
312 #define TAB_INFO_FULL_SCAN_ON_NULL 8
313 
314 class JOIN_CACHE;
315 class SJ_TMP_TABLE;
316 
317 #define SJ_OPT_NONE 0
318 #define SJ_OPT_DUPS_WEEDOUT 1
319 #define SJ_OPT_LOOSE_SCAN 2
320 #define SJ_OPT_FIRST_MATCH 3
321 #define SJ_OPT_MATERIALIZE_LOOKUP 4
322 #define SJ_OPT_MATERIALIZE_SCAN 5
323 
324 inline bool sj_is_materialize_strategy(uint strategy)
325 {
326  return strategy >= SJ_OPT_MATERIALIZE_LOOKUP;
327 }
328 
332 enum quick_type { QS_NONE, QS_RANGE, QS_DYNAMIC_RANGE};
333 
334 
362 typedef struct st_position : public Sql_alloc
363 {
364  /*
365  The "fanout" - number of output rows that will be produced (after
366  pushed down selection condition is applied) per each row combination of
367  previous tables.
368  */
369  double records_read;
370 
371  /*
372  Cost accessing the table in course of the entire complete join execution,
373  i.e. cost of one access method use (e.g. 'range' or 'ref' scan ) times
374  number the access method will be invoked.
375  */
376  double read_time;
377  JOIN_TAB *table;
378 
379  /*
380  NULL - 'index' or 'range' or 'index_merge' or 'ALL' access is used.
381  Other - [eq_]ref[_or_null] access is used. Pointer to {t.keypart1 = expr}
382  */
383  Key_use *key;
384 
385  /* If ref-based access is used: bitmap of tables this table depends on */
386  table_map ref_depend_map;
387  bool use_join_buffer;
388 
389 
390  /* These form a stack of partial join order costs and output sizes */
391  Cost_estimate prefix_cost;
392  double prefix_record_count;
393 
394  /*
395  Current optimization state: Semi-join strategy to be used for this
396  and preceding join tables.
397 
398  Join optimizer sets this for the *last* join_tab in the
399  duplicate-generating range. That is, in order to interpret this field,
400  one needs to traverse join->[best_]positions array from right to left.
401  When you see a join table with sj_strategy!= SJ_OPT_NONE, some other
402  field (depending on the strategy) tells how many preceding positions
403  this applies to. The values of covered_preceding_positions->sj_strategy
404  must be ignored.
405  */
406  uint sj_strategy;
407  /*
408  Valid only after fix_semijoin_strategies_for_picked_join_order() call:
409  if sj_strategy!=SJ_OPT_NONE, this is the number of subsequent tables that
410  are covered by the specified semi-join strategy
411  */
412  uint n_sj_tables;
413 
420 
421 /* LooseScan strategy members */
422 
423  /* The first (i.e. driving) table we're doing loose scan for */
424  uint first_loosescan_table;
425  /*
426  Tables that need to be in the prefix before we can calculate the cost
427  of using LooseScan strategy.
428  */
429  table_map loosescan_need_tables;
430 
431  /*
432  keyno - Planning to do LooseScan on this key. If keyuse is NULL then
433  this is a full index scan, otherwise this is a ref+loosescan
434  scan (and keyno matches the KEUSE's)
435  MAX_KEY - Not doing a LooseScan
436  */
437  uint loosescan_key; // final (one for strategy instance )
438  uint loosescan_parts; /* Number of keyparts to be kept distinct */
439 
440 /* FirstMatch strategy */
441  /*
442  Index of the first inner table that we intend to handle with this
443  strategy
444  */
445  uint first_firstmatch_table;
446  /*
447  Tables that were not in the join prefix when we've started considering
448  FirstMatch strategy.
449  */
450  table_map first_firstmatch_rtbl;
451  /*
452  Tables that need to be in the prefix before we can calculate the cost
453  of using FirstMatch strategy.
454  */
455  table_map firstmatch_need_tables;
456 
457 /* Duplicate Weedout strategy */
458  /* The first table that the strategy will need to handle */
459  uint first_dupsweedout_table;
460  /*
461  Tables that we will need to have in the prefix to do the weedout step
462  (all inner and all outer that the involved semi-joins are correlated with)
463  */
464  table_map dupsweedout_tables;
465 
466 /* SJ-Materialization-Scan strategy */
467  /* The last inner table (valid once we're after it) */
468  uint sjm_scan_last_inner;
469  /*
470  Tables that we need to have in the prefix to calculate the correct cost.
471  Basically, we need all inner tables and outer tables mentioned in the
472  semi-join's ON expression so we can correctly account for fanout.
473  */
474  table_map sjm_scan_need_tables;
475 
480  void no_semijoin()
481  {
482  sj_strategy= SJ_OPT_NONE;
484  }
485  void set_prefix_costs(double read_time_arg, double row_count_arg)
486  {
487  prefix_cost.reset();
488  prefix_cost.add_io(read_time_arg);
489  prefix_record_count= row_count_arg;
490  }
491 } POSITION;
492 
493 
494 struct st_cache_field;
495 class QEP_operation;
496 class Filesort;
497 
498 typedef struct st_join_table : public Sql_alloc
499 {
500  st_join_table();
501 
502  table_map prefix_tables() const { return prefix_tables_map; }
503 
504  table_map added_tables() const { return added_tables_map; }
505 
513  void set_prefix_tables(table_map prefix_tables, table_map prev_tables)
514  {
515  prefix_tables_map= prefix_tables;
516  added_tables_map= prefix_tables & ~prev_tables;
517  }
518 
524  void add_prefix_tables(table_map tables)
525  { prefix_tables_map|= tables; added_tables_map|= tables; }
526 
528  bool do_firstmatch() const { return firstmatch_return; }
529 
531  bool do_loosescan() const { return loosescan_key_len; }
532 
534  bool starts_weedout() const { return flush_weedout_table; }
535 
537  bool finishes_weedout() const { return check_weed_out_table; }
538 
539  TABLE *table;
542  SQL_SELECT *select;
543 private:
544  Item *m_condition;
545 public:
546  QUICK_SELECT_I *quick;
549  st_join_table *first_inner;
550  bool found;
552 
554  st_join_table *last_inner;
555  st_join_table *first_upper;
556  st_join_table *first_unmatched;
557  /*
558  The value of m_condition before we've attempted to do Index Condition
559  Pushdown. We may need to restore everything back if we first choose one
560  index but then reconsider (see test_if_skip_sort_order() for such
561  scenarios).
562  NULL means no index condition pushdown was performed.
563  */
564  Item *pre_idx_push_cond;
565 
566  /* Special content for EXPLAIN 'Extra' column or NULL if none */
567  Extra_tag info;
568  /*
569  Bitmap of TAB_INFO_* bits that encodes special line for EXPLAIN 'Extra'
570  column, or 0 if there is no info.
571  */
572  uint packed_info;
573 
574  READ_RECORD::Setup_func materialize_table;
580  READ_RECORD::Setup_func read_first_record;
581  Next_select_func next_select;
582  READ_RECORD read_record;
583  /*
584  The following two fields are used for a [NOT] IN subquery if it is
585  executed by an alternative full table scan when the left operand of
586  the subquery predicate is evaluated to NULL.
587  */
588  READ_RECORD::Setup_func save_read_first_record;/* to save read_first_record */
589  READ_RECORD::Read_func save_read_record;/* to save read_record.read_record */
596  double worst_seeks;
600  key_map needed_reg;
611 
612  /* Either #rows in the table or 1 for const table. */
613  ha_rows records;
614  /*
615  Number of records that will be scanned (yes scanned, not returned) by the
616  best 'independent' access method, i.e. table scan or QUICK_*_SELECT)
617  */
618  ha_rows found_records;
619  /*
620  Cost of accessing the table using "ALL" or range/index_merge access
621  method (but not 'index' for some reason), i.e. this matches method which
622  E(#records) is in found_records.
623  */
624  ha_rows read_time;
629  table_map dependent;
633  table_map key_dependent;
634 private:
639  table_map prefix_tables_map;
644  table_map added_tables_map;
645 public:
647  uint index;
648  uint used_fields,used_fieldlength,used_blobs;
649  uint used_null_fields;
650  uint used_rowid_fields;
651  uint used_uneven_bit_fields;
652  enum quick_type use_quick;
653  enum join_type type;
654  bool not_used_in_distinct;
655  /*
656  If it's not 0 the number stored this field indicates that the index
657  scan has been chosen to access the table data and we expect to scan
658  this number of rows for the table.
659  */
660  ha_rows limit;
661  TABLE_REF ref;
667  QEP_operation *op;
668  /*
669  Index condition for BKA access join
670  */
671  Item *cache_idx_cond;
672  SQL_SELECT *cache_select;
673  JOIN *join;
674 
675  /* SemiJoinDuplicateElimination variables: */
676  /*
677  Embedding SJ-nest (may be not the direct parent), or NULL if none.
678  This variable holds the result of table pullout.
679  */
680  TABLE_LIST *emb_sj_nest;
681 
688  struct st_join_table *first_sj_inner_tab;
689  struct st_join_table *last_sj_inner_tab;
690 
691  /* Variables for semi-join duplicate elimination */
692  SJ_TMP_TABLE *flush_weedout_table;
693  SJ_TMP_TABLE *check_weed_out_table;
694 
695  /*
696  If set, means we should stop join enumeration after we've got the first
697  match and return to the specified join tab. May point to
698  join->join_tab[-1] which means stop join execution after the first
699  match.
700  */
701  struct st_join_table *firstmatch_return;
702 
703  /*
704  Length of key tuple (depends on #keyparts used) to store in loosescan_buf.
705  If zero, means that loosescan is not used.
706  */
707  uint loosescan_key_len;
708 
709  /* Buffer to save index tuple to be able to skip duplicates */
710  uchar *loosescan_buf;
711 
712  /*
713  If doing a LooseScan, this join tab is the first (i.e. "driving") join
714  tab, and match_tab points to the last join tab handled by the strategy.
715  match_tab->found_match should be checked to see if the current value group
716  had a match.
717  If doing a FirstMatch, check this join tab to see if there is a match.
718  Unless the FirstMatch performs a "split jump", this is equal to the
719  current join_tab.
720  */
721  struct st_join_table *match_tab;
722  /*
723  Used by FirstMatch and LooseScan. TRUE <=> there is a matching
724  record combination
725  */
726  bool found_match;
727 
728  /*
729  Used by DuplicateElimination. tab->table->ref must have the rowid
730  whenever we have a current record. copy_current_rowid needed because
731  we cannot bind to the rowid buffer before the table has been opened.
732  */
733  int keep_current_rowid;
734  st_cache_field *copy_current_rowid;
735 
736  /* NestedOuterJoins: Bitmap of nested joins this table is part of */
737  nested_join_map embedding_map;
738 
739  /* Tmp table info */
740  TMP_TABLE_PARAM *tmp_table_param;
741 
742  /* Sorting related info */
743  Filesort *filesort;
744 
757  /*
758  Pointer to the ref array slice which to switch to before sending
759  records. Valid only for tmp tables.
760  */
761  Ref_ptr_array *ref_array;
762 
764  ha_rows send_records;
765 
768 
770  bool distinct;
771 
773  void cleanup();
774  inline bool is_using_loose_index_scan()
775  {
776  /*
777  If JOIN_TAB::filesort is set, then the access method defined in
778  filesort will be used to read from the table and
779  JOIN_TAB::select reads from filesort using scan or ref access.
780  */
781  DBUG_ASSERT(!(select && select->quick && filesort));
782 
783  const SQL_SELECT *sel= filesort ? filesort->select : select;
784  return (sel && sel->quick &&
785  (sel->quick->get_type() == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX));
786  }
787  bool is_using_agg_loose_index_scan ()
788  {
789  /*
790  If JOIN_TAB::filesort is set, then the access method defined in
791  filesort will be used to read from the table and
792  JOIN_TAB::select reads from filesort using scan or ref access.
793  */
794  DBUG_ASSERT(!(select && select->quick && filesort));
795 
796  const SQL_SELECT *sel= filesort ? filesort->select : select;
797  return (sel && sel->quick &&
798  (sel->quick->get_type() ==
799  QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX) &&
800  static_cast<QUICK_GROUP_MIN_MAX_SELECT*>(sel->quick)->
801  is_agg_distinct());
802  }
803  /* SemiJoinDuplicateElimination: reserve space for rowid */
804  bool check_rowid_field()
805  {
806  if (keep_current_rowid && !used_rowid_fields)
807  {
808  used_rowid_fields= 1;
809  used_fieldlength+= table->file->ref_length;
810  }
811  return test(used_rowid_fields);
812  }
813  bool is_inner_table_of_outer_join()
814  {
815  return first_inner != NULL;
816  }
817  bool is_single_inner_of_semi_join()
818  {
819  return first_sj_inner_tab == this && last_sj_inner_tab == this;
820  }
821  bool is_single_inner_of_outer_join()
822  {
823  return first_inner == this && first_inner->last_inner == this;
824  }
825  bool is_first_inner_for_outer_join()
826  {
827  return first_inner && first_inner == this;
828  }
829  Item *condition() const
830  {
831  return m_condition;
832  }
833  void set_condition(Item *to, uint line)
834  {
835  DBUG_PRINT("info",
836  ("JOIN_TAB::m_condition changes %p -> %p at line %u tab %p",
837  m_condition, to, line, this));
838  m_condition= to;
839  quick_order_tested.clear_all();
840  }
841 
842  Item *set_jt_and_sel_condition(Item *new_cond, uint line)
843  {
844  Item *tmp_cond= m_condition;
845  set_condition(new_cond, line);
846  if (select)
847  select->cond= new_cond;
848  return tmp_cond;
849  }
850 
852  uint get_sj_strategy() const
853  {
854  if (first_sj_inner_tab == NULL)
855  return SJ_OPT_NONE;
856  DBUG_ASSERT(first_sj_inner_tab->position->sj_strategy != SJ_OPT_NONE);
857  return first_sj_inner_tab->position->sj_strategy;
858  }
863  uint sjm_query_block_id() const;
864 
865  bool and_with_condition(Item *tmp_cond, uint line);
866  bool and_with_jt_and_sel_condition(Item *tmp_cond, uint line);
867 
876  bool has_guarded_conds() const
877  {
878  return ref.has_guarded_conds();
879  }
880  Item *unified_condition() const;
881  bool prepare_scan();
882  bool use_order() const;
883  bool sort_table();
884  bool remove_duplicates();
885 } JOIN_TAB;
886 
887 inline
889  : table(NULL),
890  position(NULL),
891  keyuse(NULL),
892  select(NULL),
893  m_condition(NULL),
894  quick(NULL),
895  on_expr_ref(NULL),
896  cond_equal(NULL),
897  first_inner(NULL),
898  found(false),
899  not_null_compl(false),
900  materialized(false),
901  last_inner(NULL),
902  first_upper(NULL),
903  first_unmatched(NULL),
904  pre_idx_push_cond(NULL),
905  info(ET_none),
906  packed_info(0),
907  materialize_table(NULL),
908  read_first_record(NULL),
909  next_select(NULL),
910  read_record(),
911  save_read_first_record(NULL),
912  save_read_record(NULL),
913  sj_mat_exec(NULL),
914  worst_seeks(0.0),
915  const_keys(),
916  checked_keys(),
917  needed_reg(),
918  keys(),
920 
921  records(0),
922  found_records(0),
923  read_time(0),
924 
925  dependent(0),
926  key_dependent(0),
927  prefix_tables_map(0),
928  added_tables_map(0),
929  index(0),
930  used_fields(0),
931  used_fieldlength(0),
932  used_blobs(0),
933  used_null_fields(0),
934  used_rowid_fields(0),
935  used_uneven_bit_fields(0),
936  use_quick(QS_NONE),
937  type(JT_UNKNOWN),
938  not_used_in_distinct(false),
939 
940  limit(0),
941  ref(),
942  use_join_cache(0),
943  op(NULL),
944 
945  cache_idx_cond(NULL),
946  cache_select(NULL),
947  join(NULL),
948 
949  emb_sj_nest(NULL),
950  first_sj_inner_tab(NULL),
951  last_sj_inner_tab(NULL),
952 
953  flush_weedout_table(NULL),
954  check_weed_out_table(NULL),
955  firstmatch_return(NULL),
956  loosescan_key_len(0),
957  loosescan_buf(NULL),
958  match_tab(NULL),
959  found_match(FALSE),
960 
961  keep_current_rowid(0),
962  copy_current_rowid(NULL),
963  embedding_map(0),
964  tmp_table_param(NULL),
965  filesort(NULL),
966  fields(NULL),
967  all_fields(NULL),
968  ref_array(NULL),
969  send_records(0),
970  having(NULL),
971  distinct(false)
972 {
978  memset(&read_record, 0, sizeof(read_record));
979 }
980 
1018  public std::binary_function<const JOIN_TAB*, const JOIN_TAB*, bool>
1019 {
1020 public:
1021  bool operator()(const JOIN_TAB *jt1, const JOIN_TAB *jt2)
1022  {
1023  // Sorting distinct tables, so a table should not be compared with itself
1024  DBUG_ASSERT(jt1 != jt2);
1025 
1026  if (jt1->dependent & jt2->table->map)
1027  return false;
1028  if (jt2->dependent & jt1->table->map)
1029  return true;
1030 
1031  const bool jt1_keydep_jt2= jt1->key_dependent & jt2->table->map;
1032  const bool jt2_keydep_jt1= jt2->key_dependent & jt1->table->map;
1033 
1034  if (jt1_keydep_jt2 && !jt2_keydep_jt1)
1035  return false;
1036  if (jt2_keydep_jt1 && !jt1_keydep_jt2)
1037  return true;
1038 
1039  if (jt1->found_records > jt2->found_records)
1040  return false;
1041  if (jt1->found_records < jt2->found_records)
1042  return true;
1043 
1044  return jt1 < jt2;
1045  }
1046 };
1047 
1056  public std::binary_function<const JOIN_TAB*, const JOIN_TAB*, bool>
1057 {
1058 public:
1059  bool operator()(const JOIN_TAB *jt1, const JOIN_TAB *jt2)
1060  {
1061  // Sorting distinct tables, so a table should not be compared with itself
1062  DBUG_ASSERT(jt1 != jt2);
1063 
1064  /*
1065  We don't do subquery flattening if the parent or child select has
1066  STRAIGHT_JOIN modifier. It is complicated to implement and the semantics
1067  is hardly useful.
1068  */
1069  DBUG_ASSERT(!jt1->emb_sj_nest);
1070  DBUG_ASSERT(!jt2->emb_sj_nest);
1071 
1072  if (jt1->dependent & jt2->table->map)
1073  return false;
1074  if (jt2->dependent & jt1->table->map)
1075  return true;
1076 
1077  return jt1 < jt2;
1078  }
1079 };
1080 
1081 /*
1082  Same as Join_tab_compare_default but tables from within the given
1083  semi-join nest go first. Used when optimizing semi-join
1084  materialization nests.
1085 */
1087  public std::binary_function<const JOIN_TAB*, const JOIN_TAB*, bool>
1088 {
1089 private:
1090  const TABLE_LIST *emb_nest;
1091 public:
1092 
1093  Join_tab_compare_embedded_first(const TABLE_LIST *nest) : emb_nest(nest){}
1094 
1095  bool operator()(const JOIN_TAB *jt1, const JOIN_TAB *jt2)
1096  {
1097  // Sorting distinct tables, so a table should not be compared with itself
1098  DBUG_ASSERT(jt1 != jt2);
1099 
1100  if (jt1->emb_sj_nest == emb_nest && jt2->emb_sj_nest != emb_nest)
1101  return true;
1102  if (jt1->emb_sj_nest != emb_nest && jt2->emb_sj_nest == emb_nest)
1103  return false;
1104 
1106  return cmp(jt1,jt2);
1107  }
1108 };
1109 
1110 
1112 
1113 typedef struct st_select_check {
1114  uint const_ref,reg_ref;
1115 } SELECT_CHECK;
1116 
1117 /* Extern functions in sql_select.cc */
1118 void count_field_types(SELECT_LEX *select_lex, TMP_TABLE_PARAM *param,
1119  List<Item> &fields, bool reset_with_sum_func);
1120 uint find_shortest_key(TABLE *table, const key_map *usable_keys);
1121 
1122 /* functions from opt_sum.cc */
1123 bool simple_pred(Item_func *func_item, Item **args, bool *inv_order);
1124 int opt_sum_query(THD* thd,
1125  TABLE_LIST *tables, List<Item> &all_fields, Item *conds);
1126 
1127 /* from sql_delete.cc, used by opt_range.cc */
1128 extern "C" int refpos_order_cmp(const void* arg, const void *a,const void *b);
1129 
1132 class store_key :public Sql_alloc
1133 {
1134 public:
1135  bool null_key; /* TRUE <=> the value of the key has a null part */
1136  enum store_key_result { STORE_KEY_OK, STORE_KEY_FATAL, STORE_KEY_CONV };
1137  store_key(THD *thd, Field *field_arg, uchar *ptr, uchar *null, uint length)
1138  :null_key(0), null_ptr(null), err(0)
1139  {
1140  if (field_arg->type() == MYSQL_TYPE_BLOB
1141  || field_arg->type() == MYSQL_TYPE_GEOMETRY)
1142  {
1143  /*
1144  Key segments are always packed with a 2 byte length prefix.
1145  See mi_rkey for details.
1146  */
1147  to_field= new Field_varstring(ptr, length, 2, null, 1,
1148  Field::NONE, field_arg->field_name,
1149  field_arg->table->s, field_arg->charset());
1150  to_field->init(field_arg->table);
1151  }
1152  else
1153  to_field=field_arg->new_key_field(thd->mem_root, field_arg->table,
1154  ptr, null, 1);
1155  }
1156  virtual ~store_key() {}
1157  virtual const char *name() const=0;
1158 
1165  enum store_key_result copy()
1166  {
1167  enum store_key_result result;
1168  THD *thd= to_field->table->in_use;
1169  enum_check_fields saved_count_cuted_fields= thd->count_cuted_fields;
1170  sql_mode_t sql_mode= thd->variables.sql_mode;
1171  thd->variables.sql_mode&= ~(MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE);
1172 
1173  thd->count_cuted_fields= CHECK_FIELD_IGNORE;
1174 
1175  result= copy_inner();
1176 
1177  thd->count_cuted_fields= saved_count_cuted_fields;
1178  thd->variables.sql_mode= sql_mode;
1179 
1180  return result;
1181  }
1182 
1183  protected:
1184  Field *to_field; // Store data here
1185  uchar *null_ptr;
1186  uchar err;
1187 
1188  virtual enum store_key_result copy_inner()=0;
1189 };
1190 
1191 
1192 static store_key::store_key_result
1193 type_conversion_status_to_store_key (type_conversion_status ts)
1194 {
1195  switch (ts)
1196  {
1197  case TYPE_OK:
1198  return store_key::STORE_KEY_OK;
1199  case TYPE_NOTE_TIME_TRUNCATED:
1200  return store_key::STORE_KEY_CONV;
1201  case TYPE_WARN_OUT_OF_RANGE:
1202  case TYPE_NOTE_TRUNCATED:
1203  case TYPE_WARN_TRUNCATED:
1204  case TYPE_ERR_NULL_CONSTRAINT_VIOLATION:
1205  case TYPE_ERR_BAD_VALUE:
1206  case TYPE_ERR_OOM:
1207  return store_key::STORE_KEY_FATAL;
1208  default:
1209  DBUG_ASSERT(false); // not possible
1210  }
1211 
1212  return store_key::STORE_KEY_FATAL;
1213 }
1214 
1216 {
1217  Copy_field copy_field;
1218  const char *field_name;
1219  public:
1220  store_key_field(THD *thd, Field *to_field_arg, uchar *ptr,
1221  uchar *null_ptr_arg,
1222  uint length, Field *from_field, const char *name_arg)
1223  :store_key(thd, to_field_arg,ptr,
1224  null_ptr_arg ? null_ptr_arg : from_field->maybe_null() ? &err
1225  : (uchar*) 0, length), field_name(name_arg)
1226  {
1227  if (to_field)
1228  {
1229  copy_field.set(to_field,from_field,0);
1230  }
1231  }
1232  const char *name() const { return field_name; }
1233 
1234  protected:
1235  enum store_key_result copy_inner()
1236  {
1237  TABLE *table= copy_field.to_field->table;
1238  my_bitmap_map *old_map= dbug_tmp_use_all_columns(table,
1239  table->write_set);
1240  copy_field.do_copy(&copy_field);
1241  dbug_tmp_restore_column_map(table->write_set, old_map);
1242  null_key= to_field->is_null();
1243  return err != 0 ? STORE_KEY_FATAL : STORE_KEY_OK;
1244  }
1245 };
1246 
1247 
1249 {
1250  protected:
1251  Item *item;
1252 public:
1253  store_key_item(THD *thd, Field *to_field_arg, uchar *ptr,
1254  uchar *null_ptr_arg, uint length, Item *item_arg)
1255  :store_key(thd, to_field_arg, ptr,
1256  null_ptr_arg ? null_ptr_arg : item_arg->maybe_null ?
1257  &err : (uchar*) 0, length), item(item_arg)
1258  {}
1259  const char *name() const { return "func"; }
1260 
1261  protected:
1262  enum store_key_result copy_inner()
1263  {
1264  TABLE *table= to_field->table;
1265  my_bitmap_map *old_map= dbug_tmp_use_all_columns(table,
1266  table->write_set);
1267  type_conversion_status save_res= item->save_in_field(to_field, true);
1268  store_key_result res;
1269  /*
1270  Item::save_in_field() may call Item::val_xxx(). And if this is a subquery
1271  we need to check for errors executing it and react accordingly
1272  */
1273  if (save_res != TYPE_OK && table->in_use->is_error())
1274  res= STORE_KEY_FATAL;
1275  else
1276  res= type_conversion_status_to_store_key(save_res);
1277  dbug_tmp_restore_column_map(table->write_set, old_map);
1278  null_key= to_field->is_null() || item->null_value;
1279  return (err != 0) ? STORE_KEY_FATAL : res;
1280  }
1281 };
1282 
1283 
1285 {
1286  bool inited;
1287 public:
1288  store_key_const_item(THD *thd, Field *to_field_arg, uchar *ptr,
1289  uchar *null_ptr_arg, uint length,
1290  Item *item_arg)
1291  :store_key_item(thd, to_field_arg, ptr,
1292  null_ptr_arg, length, item_arg), inited(0)
1293  {
1294  }
1295  const char *name() const { return "const"; }
1296 
1297 protected:
1298  enum store_key_result copy_inner()
1299  {
1300  if (!inited)
1301  {
1302  inited=1;
1303  store_key_result res= store_key_item::copy_inner();
1304  if (res && !err)
1305  err= res;
1306  }
1307  return (err > 2 ? STORE_KEY_FATAL : (store_key_result) err);
1308  }
1309 };
1310 
1311 bool error_if_full_join(JOIN *join);
1312 bool handle_select(THD *thd, select_result *result,
1313  ulong setup_tables_done_option);
1314 bool mysql_select(THD *thd,
1315  TABLE_LIST *tables, uint wild_num, List<Item> &list,
1316  Item *conds, SQL_I_List<ORDER> *order,
1318  Item *having, ulonglong select_type,
1319  select_result *result, SELECT_LEX_UNIT *unit,
1320  SELECT_LEX *select_lex);
1321 void free_underlaid_joins(THD *thd, SELECT_LEX *select);
1322 
1323 
1324 void calc_used_field_length(THD *thd, JOIN_TAB *join_tab);
1325 
1326 inline bool optimizer_flag(THD *thd, uint flag)
1327 {
1328  return (thd->variables.optimizer_switch & flag);
1329 }
1330 
1331 uint get_index_for_order(ORDER *order, TABLE *table, SQL_SELECT *select,
1332  ha_rows limit, bool *need_sort, bool *reverse);
1333 ORDER *simple_remove_const(ORDER *order, Item *where);
1334 bool const_expression_in_where(Item *cond, Item *comp_item,
1335  Field *comp_field= NULL,
1336  Item **const_item= NULL);
1337 bool test_if_subpart(ORDER *a,ORDER *b);
1338 void calc_group_buffer(JOIN *join,ORDER *group);
1339 bool
1340 test_if_skip_sort_order(JOIN_TAB *tab, ORDER *order, ha_rows select_limit,
1341  const bool no_changes, const key_map *map,
1342  const char *clause_type);
1343 bool make_join_readinfo(JOIN *join, ulonglong options, uint no_jbuf_after);
1344 bool create_ref_for_key(JOIN *join, JOIN_TAB *j, Key_use *org_keyuse,
1345  table_map used_tables);
1346 bool types_allow_materialization(Item *outer, Item *inner);
1347 bool and_conditions(Item **e1, Item *e2);
1348 
1349 static inline Item * and_items(Item* cond, Item *item)
1350 {
1351  return (cond? (new Item_cond_and(cond, item)) : item);
1352 }
1353 
1354 uint actual_key_parts(KEY *key_info);
1355 uint actual_key_flags(KEY *key_info);
1356 
1357 int test_if_order_by_key(ORDER *order, TABLE *table, uint idx,
1358  uint *used_key_parts= NULL);
1359 
1360 #endif /* SQL_SELECT_INCLUDED */