My Project
sql_select.h
Go to the documentation of this file.
00001 #ifndef SQL_SELECT_INCLUDED
00002 #define SQL_SELECT_INCLUDED
00003 
00004 /* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
00005 
00006    This program is free software; you can redistribute it and/or modify
00007    it under the terms of the GNU General Public License as published by
00008    the Free Software Foundation; version 2 of the License.
00009 
00010    This program is distributed in the hope that it will be useful,
00011    but WITHOUT ANY WARRANTY; without even the implied warranty of
00012    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00013    GNU General Public License for more details.
00014 
00015    You should have received a copy of the GNU General Public License
00016    along with this program; if not, write to the Free Software
00017    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA */
00018 
00019 
00027 #include "procedure.h"
00028 #include <myisam.h>
00029 #include "sql_array.h"                        /* Array */
00030 #include "records.h"                          /* READ_RECORD */
00031 #include "opt_range.h"                /* SQL_SELECT, QUICK_SELECT_I */
00032 #include "filesort.h"
00033 
00034 #include "mem_root_array.h"
00035 #include "sql_executor.h"
00036 #include "opt_explain_format.h" // for Extra_tag
00037 
00038 #include <functional>
00044 #define LOWER_BITS(type,A)      ((type) (((type) 1 << (A)) -1))
00045 
00046 /* Values in optimize */
00047 #define KEY_OPTIMIZE_EXISTS             1
00048 #define KEY_OPTIMIZE_REF_OR_NULL        2
00049 #define FT_KEYPART                      (MAX_REF_PARTS+10)
00050 
00054 class Key_use {
00055 public:
00056   // We need the default constructor for unit testing.
00057   Key_use()
00058     : table(NULL),
00059       val(NULL),
00060       used_tables(0),
00061       key(0),
00062       keypart(0),
00063       optimize(0),
00064       keypart_map(0),
00065       ref_table_rows(0),
00066       null_rejecting(false),
00067       cond_guard(NULL),
00068       sj_pred_no(UINT_MAX)
00069   {}
00070 
00071   Key_use(TABLE *table_arg, Item *val_arg, table_map used_tables_arg,
00072           uint key_arg, uint keypart_arg, uint optimize_arg,
00073           key_part_map keypart_map_arg, ha_rows ref_table_rows_arg,
00074           bool null_rejecting_arg, bool *cond_guard_arg,
00075           uint sj_pred_no_arg) :
00076   table(table_arg), val(val_arg), used_tables(used_tables_arg),
00077   key(key_arg), keypart(keypart_arg), optimize(optimize_arg),
00078   keypart_map(keypart_map_arg), ref_table_rows(ref_table_rows_arg),
00079   null_rejecting(null_rejecting_arg), cond_guard(cond_guard_arg),
00080   sj_pred_no(sj_pred_no_arg)
00081   {}
00082   TABLE *table;            
00083   Item  *val;              
00084   table_map used_tables;   
00085   uint key;                
00086   uint keypart;            
00087   uint optimize;           
00088   key_part_map keypart_map;       
00089   ha_rows      ref_table_rows;    
00090 
00096   bool null_rejecting;
00110   bool *cond_guard;
00118   uint         sj_pred_no;
00119 };
00120 
00121 
00122 // Key_use has a trivial destructor, no need to run it from Mem_root_array.
00123 typedef Mem_root_array<Key_use, true> Key_use_array;
00124 
00125 class store_key;
00126 
00127 typedef struct st_table_ref : public Sql_alloc
00128 {
00129   bool          key_err;
00131   bool          has_record;
00132   uint          key_parts;                
00133   uint          key_length;               
00134   int           key;                      
00135   uchar         *key_buff;                
00136   uchar         *key_buff2;               
00137 
00142   store_key     **key_copy;
00143   Item          **items;                  
00144   /*  
00145     Array of pointers to trigger variables. Some/all of the pointers may be
00146     NULL.  The ref access can be used iff
00147     
00148       for each used key part i, (!cond_guards[i] || *cond_guards[i]) 
00149 
00150     This array is used by subquery code. The subquery code may inject
00151     triggered conditions, i.e. conditions that can be 'switched off'. A ref 
00152     access created from such condition is not valid when at least one of the 
00153     underlying conditions is switched off (see subquery code for more details).
00154     If a table in a subquery has this it means that the table access 
00155     will switch from ref access to table scan when the outer query 
00156     produces a NULL value to be checked for in the subquery. This will
00157     be used by NOT IN subqueries and IN subqueries for which 
00158     is_top_level_item() returns false.
00159   */
00160   bool          **cond_guards;
00165   key_part_map  null_rejecting;
00166   table_map     depend_map;               
00167   /* null byte position in the key_buf. Used for REF_OR_NULL optimization */
00168   uchar          *null_ref_key;
00169   /*
00170     The number of times the record associated with this key was used
00171     in the join.
00172   */
00173   ha_rows       use_count;
00174 
00175   /*
00176     TRUE <=> disable the "cache" as doing lookup with the same key value may
00177     produce different results (because of Index Condition Pushdown)
00178   */
00179   bool          disable_cache;
00180 
00181   st_table_ref()
00182     : key_err(TRUE),
00183       has_record(FALSE),
00184       key_parts(0),
00185       key_length(0),
00186       key(-1),
00187       key_buff(NULL),
00188       key_buff2(NULL),
00189       key_copy(NULL),
00190       items(NULL),
00191       cond_guards(NULL),
00192       null_rejecting(0),
00193       depend_map(0),
00194       null_ref_key(NULL),
00195       use_count(0),
00196       disable_cache(FALSE)
00197   {
00198   }
00199 
00204   bool impossible_null_ref() const
00205   {
00206     if (null_rejecting != 0)
00207     {
00208       for (uint i= 0 ; i < key_parts ; i++)
00209       {
00210         if ((null_rejecting & 1 << i) && items[i]->is_null())
00211           return TRUE;
00212       }
00213     }
00214     return FALSE;
00215   }
00216 
00217 
00226   bool has_guarded_conds() const
00227   {
00228     DBUG_ASSERT(key_parts == 0 || cond_guards != NULL);
00229 
00230     for (uint i = 0; i < key_parts; i++)
00231     {
00232       if (cond_guards[i])
00233         return true;
00234     }
00235     return false;
00236   }
00237 } TABLE_REF;
00238 
00239 
00240 /*
00241   The structs which holds the join connections and join states
00242 */
00243 enum join_type { /*
00244                    Initial state. Access type has not yet been decided
00245                    for the table
00246                  */
00247                  JT_UNKNOWN,
00248                  /* Table has exactly one row */
00249                  JT_SYSTEM,
00250                  /*
00251                    Table has at most one matching row. Values read
00252                    from this row can be treated as constants. Example:
00253                    "WHERE table.pk = 3"
00254                   */
00255                  JT_CONST,
00256                  /*
00257                    '=' operator is used on unique index. At most one
00258                    row is read for each combination of rows from
00259                    preceding tables
00260                  */
00261                  JT_EQ_REF,
00262                  /*
00263                    '=' operator is used on non-unique index
00264                  */
00265                  JT_REF,
00266                  /*
00267                    Full table scan or range scan.
00268                    If select->quick != NULL, it is range access.
00269                    Otherwise it is table scan.
00270                  */
00271                  JT_ALL,
00272                  /*
00273                    Range scan. Note that range scan is not indicated
00274                    by JT_RANGE but by "JT_ALL + select->quick" except
00275                    when printing EXPLAIN output. @see calc_join_type()
00276                  */
00277                  JT_RANGE,
00278                  /*
00279                    Like table scan, but scans index leaves instead of
00280                    the table
00281                  */
00282                  JT_INDEX_SCAN,
00283                  /* Fulltext index is used */
00284                  JT_FT,
00285                  /*
00286                    Like ref, but with extra search for NULL values.
00287                    E.g. used for "WHERE col = ... OR col IS NULL"
00288                   */
00289                  JT_REF_OR_NULL,
00290                  /*
00291                    Like eq_ref for subqueries: Replaces subquery with
00292                    index lookup in unique index
00293                   */
00294                  JT_UNIQUE_SUBQUERY,
00295                  /*
00296                    Like unique_subquery but for non-unique index
00297                  */
00298                  JT_INDEX_SUBQUERY,
00299                  /*
00300                    Do multiple range scans over one table and combine
00301                    the results into one. The merge can be used to
00302                    produce unions and intersections
00303                  */
00304                  JT_INDEX_MERGE};
00305 
00306 class JOIN;
00307 
00308 /* Values for JOIN_TAB::packed_info */
00309 #define TAB_INFO_HAVE_VALUE 1
00310 #define TAB_INFO_USING_INDEX 2
00311 #define TAB_INFO_USING_WHERE 4
00312 #define TAB_INFO_FULL_SCAN_ON_NULL 8
00313 
00314 class JOIN_CACHE;
00315 class SJ_TMP_TABLE;
00316 
00317 #define SJ_OPT_NONE 0
00318 #define SJ_OPT_DUPS_WEEDOUT 1
00319 #define SJ_OPT_LOOSE_SCAN   2
00320 #define SJ_OPT_FIRST_MATCH  3
00321 #define SJ_OPT_MATERIALIZE_LOOKUP  4
00322 #define SJ_OPT_MATERIALIZE_SCAN  5
00323 
00324 inline bool sj_is_materialize_strategy(uint strategy)
00325 {
00326   return strategy >= SJ_OPT_MATERIALIZE_LOOKUP;
00327 }
00328 
00332 enum quick_type { QS_NONE, QS_RANGE, QS_DYNAMIC_RANGE};
00333 
00334 
00362 typedef struct st_position : public Sql_alloc
00363 {
00364   /*
00365     The "fanout" -  number of output rows that will be produced (after
00366     pushed down selection condition is applied) per each row combination of
00367     previous tables.
00368   */
00369   double records_read;
00370 
00371   /* 
00372     Cost accessing the table in course of the entire complete join execution,
00373     i.e. cost of one access method use (e.g. 'range' or 'ref' scan ) times 
00374     number the access method will be invoked.
00375   */
00376   double read_time;
00377   JOIN_TAB *table;
00378 
00379   /*
00380     NULL  -  'index' or 'range' or 'index_merge' or 'ALL' access is used.
00381     Other - [eq_]ref[_or_null] access is used. Pointer to {t.keypart1 = expr}
00382   */
00383   Key_use *key;
00384 
00385   /* If ref-based access is used: bitmap of tables this table depends on  */
00386   table_map ref_depend_map;
00387   bool use_join_buffer; 
00388   
00389   
00390   /* These form a stack of partial join order costs and output sizes */
00391   Cost_estimate prefix_cost;
00392   double    prefix_record_count;
00393 
00394   /*
00395     Current optimization state: Semi-join strategy to be used for this
00396     and preceding join tables.
00397     
00398     Join optimizer sets this for the *last* join_tab in the
00399     duplicate-generating range. That is, in order to interpret this field, 
00400     one needs to traverse join->[best_]positions array from right to left.
00401     When you see a join table with sj_strategy!= SJ_OPT_NONE, some other
00402     field (depending on the strategy) tells how many preceding positions 
00403     this applies to. The values of covered_preceding_positions->sj_strategy
00404     must be ignored.
00405   */
00406   uint sj_strategy;
00407   /*
00408     Valid only after fix_semijoin_strategies_for_picked_join_order() call:
00409     if sj_strategy!=SJ_OPT_NONE, this is the number of subsequent tables that
00410     are covered by the specified semi-join strategy
00411   */
00412   uint n_sj_tables;
00413 
00419   table_map dups_producing_tables;
00420 
00421 /* LooseScan strategy members */
00422 
00423   /* The first (i.e. driving) table we're doing loose scan for */
00424   uint        first_loosescan_table;
00425   /* 
00426      Tables that need to be in the prefix before we can calculate the cost
00427      of using LooseScan strategy.
00428   */
00429   table_map   loosescan_need_tables;
00430 
00431   /*
00432     keyno  -  Planning to do LooseScan on this key. If keyuse is NULL then 
00433               this is a full index scan, otherwise this is a ref+loosescan
00434               scan (and keyno matches the KEUSE's)
00435     MAX_KEY - Not doing a LooseScan
00436   */
00437   uint loosescan_key;  // final (one for strategy instance )
00438   uint loosescan_parts; /* Number of keyparts to be kept distinct */
00439   
00440 /* FirstMatch strategy */
00441   /*
00442     Index of the first inner table that we intend to handle with this
00443     strategy
00444   */
00445   uint first_firstmatch_table;
00446   /*
00447     Tables that were not in the join prefix when we've started considering 
00448     FirstMatch strategy.
00449   */
00450   table_map first_firstmatch_rtbl;
00451   /* 
00452     Tables that need to be in the prefix before we can calculate the cost
00453     of using FirstMatch strategy.
00454    */
00455   table_map firstmatch_need_tables;
00456 
00457 /* Duplicate Weedout strategy */
00458   /* The first table that the strategy will need to handle */
00459   uint  first_dupsweedout_table;
00460   /*
00461     Tables that we will need to have in the prefix to do the weedout step
00462     (all inner and all outer that the involved semi-joins are correlated with)
00463   */
00464   table_map dupsweedout_tables;
00465 
00466 /* SJ-Materialization-Scan strategy */
00467   /* The last inner table (valid once we're after it) */
00468   uint      sjm_scan_last_inner;
00469   /*
00470     Tables that we need to have in the prefix to calculate the correct cost.
00471     Basically, we need all inner tables and outer tables mentioned in the
00472     semi-join's ON expression so we can correctly account for fanout.
00473   */
00474   table_map sjm_scan_need_tables;
00475 
00480   void no_semijoin()
00481   {
00482     sj_strategy= SJ_OPT_NONE;
00483     dups_producing_tables= 0;
00484   }
00485   void set_prefix_costs(double read_time_arg, double row_count_arg)
00486   {
00487     prefix_cost.reset();
00488     prefix_cost.add_io(read_time_arg);
00489     prefix_record_count= row_count_arg;
00490   }
00491 } POSITION;
00492 
00493 
00494 struct st_cache_field;
00495 class QEP_operation;
00496 class Filesort;
00497 
00498 typedef struct st_join_table : public Sql_alloc
00499 {
00500   st_join_table();
00501 
00502   table_map prefix_tables() const { return prefix_tables_map; }
00503 
00504   table_map added_tables() const { return added_tables_map; }
00505 
00513   void set_prefix_tables(table_map prefix_tables, table_map prev_tables)
00514   {
00515     prefix_tables_map= prefix_tables;
00516     added_tables_map= prefix_tables & ~prev_tables;
00517   }
00518 
00524   void add_prefix_tables(table_map tables)
00525   { prefix_tables_map|= tables; added_tables_map|= tables; }
00526 
00528   bool do_firstmatch() const { return firstmatch_return; }
00529 
00531   bool do_loosescan() const { return loosescan_key_len; }
00532 
00534   bool starts_weedout() const { return flush_weedout_table; }
00535 
00537   bool finishes_weedout() const { return check_weed_out_table; }
00538 
00539   TABLE         *table;
00540   POSITION      *position;      
00541   Key_use       *keyuse;        
00542   SQL_SELECT    *select;
00543 private:
00544   Item          *m_condition;   
00545 public:
00546   QUICK_SELECT_I *quick;
00547   Item         **on_expr_ref;   
00548   COND_EQUAL    *cond_equal;    
00549   st_join_table *first_inner;   
00550   bool           found;         
00551   bool           not_null_compl;
00552 
00553   bool           materialized;
00554   st_join_table *last_inner;    
00555   st_join_table *first_upper;  
00556   st_join_table *first_unmatched; 
00557   /* 
00558     The value of m_condition before we've attempted to do Index Condition
00559     Pushdown. We may need to restore everything back if we first choose one
00560     index but then reconsider (see test_if_skip_sort_order() for such
00561     scenarios).
00562     NULL means no index condition pushdown was performed.
00563   */
00564   Item          *pre_idx_push_cond;
00565   
00566   /* Special content for EXPLAIN 'Extra' column or NULL if none */
00567   Extra_tag     info;
00568   /* 
00569     Bitmap of TAB_INFO_* bits that encodes special line for EXPLAIN 'Extra'
00570     column, or 0 if there is no info.
00571   */
00572   uint          packed_info;
00573 
00574   READ_RECORD::Setup_func materialize_table;
00580   READ_RECORD::Setup_func read_first_record;
00581   Next_select_func next_select;
00582   READ_RECORD   read_record;
00583   /* 
00584     The following two fields are used for a [NOT] IN subquery if it is
00585     executed by an alternative full table scan when the left operand of
00586     the subquery predicate is evaluated to NULL.
00587   */  
00588   READ_RECORD::Setup_func save_read_first_record;/* to save read_first_record */
00589   READ_RECORD::Read_func save_read_record;/* to save read_record.read_record */
00595   Semijoin_mat_exec *sj_mat_exec;          
00596   double        worst_seeks;
00598   key_map       const_keys;
00599   key_map       checked_keys;                   
00600   key_map       needed_reg;
00601   key_map       keys;                           
00610   key_map       quick_order_tested;
00611 
00612   /* Either #rows in the table or 1 for const table.  */
00613   ha_rows       records;
00614   /*
00615     Number of records that will be scanned (yes scanned, not returned) by the
00616     best 'independent' access method, i.e. table scan or QUICK_*_SELECT)
00617   */
00618   ha_rows       found_records;
00619   /*
00620     Cost of accessing the table using "ALL" or range/index_merge access
00621     method (but not 'index' for some reason), i.e. this matches method which
00622     E(#records) is in found_records.
00623   */
00624   ha_rows       read_time;
00629   table_map     dependent;
00633   table_map     key_dependent;
00634 private:
00639   table_map     prefix_tables_map;
00644   table_map     added_tables_map;
00645 public:
00647   uint          index;
00648   uint          used_fields,used_fieldlength,used_blobs;
00649   uint          used_null_fields;
00650   uint          used_rowid_fields;
00651   uint          used_uneven_bit_fields;
00652   enum quick_type use_quick;
00653   enum join_type type;
00654   bool          not_used_in_distinct;
00655   /* 
00656     If it's not 0 the number stored this field indicates that the index
00657     scan has been chosen to access the table data and we expect to scan 
00658     this number of rows for the table.
00659   */ 
00660   ha_rows       limit; 
00661   TABLE_REF     ref;
00666   uint          use_join_cache;
00667   QEP_operation *op;
00668   /*
00669     Index condition for BKA access join
00670   */
00671   Item          *cache_idx_cond;
00672   SQL_SELECT    *cache_select;
00673   JOIN          *join;
00674 
00675   /* SemiJoinDuplicateElimination variables: */
00676   /*
00677     Embedding SJ-nest (may be not the direct parent), or NULL if none.
00678     This variable holds the result of table pullout.
00679   */
00680   TABLE_LIST    *emb_sj_nest;
00681 
00688   struct st_join_table *first_sj_inner_tab;
00689   struct st_join_table *last_sj_inner_tab;
00690 
00691   /* Variables for semi-join duplicate elimination */
00692   SJ_TMP_TABLE  *flush_weedout_table;
00693   SJ_TMP_TABLE  *check_weed_out_table;
00694   
00695   /*
00696     If set, means we should stop join enumeration after we've got the first
00697     match and return to the specified join tab. May point to
00698     join->join_tab[-1] which means stop join execution after the first
00699     match.
00700   */
00701   struct st_join_table  *firstmatch_return;
00702  
00703   /*
00704     Length of key tuple (depends on #keyparts used) to store in loosescan_buf.
00705     If zero, means that loosescan is not used.
00706   */
00707   uint loosescan_key_len;
00708 
00709   /* Buffer to save index tuple to be able to skip duplicates */
00710   uchar *loosescan_buf;
00711 
00712   /* 
00713     If doing a LooseScan, this join tab is the first (i.e.  "driving") join
00714     tab, and match_tab points to the last join tab handled by the strategy.
00715     match_tab->found_match should be checked to see if the current value group
00716     had a match.
00717     If doing a FirstMatch, check this join tab to see if there is a match.
00718     Unless the FirstMatch performs a "split jump", this is equal to the
00719     current join_tab.
00720   */
00721   struct st_join_table *match_tab;
00722   /*
00723     Used by FirstMatch and LooseScan. TRUE <=> there is a matching
00724     record combination
00725   */
00726   bool found_match;
00727   
00728   /*
00729     Used by DuplicateElimination. tab->table->ref must have the rowid
00730     whenever we have a current record. copy_current_rowid needed because
00731     we cannot bind to the rowid buffer before the table has been opened.
00732   */
00733   int  keep_current_rowid;
00734   st_cache_field *copy_current_rowid;
00735 
00736   /* NestedOuterJoins: Bitmap of nested joins this table is part of */
00737   nested_join_map embedding_map;
00738 
00739   /* Tmp table info */
00740   TMP_TABLE_PARAM *tmp_table_param;
00741 
00742   /* Sorting related info */
00743   Filesort *filesort;
00744 
00754   List<Item> *fields;
00756   List<Item> *all_fields;
00757   /*
00758     Pointer to the ref array slice which to switch to before sending
00759     records. Valid only for tmp tables.
00760   */
00761   Ref_ptr_array *ref_array;
00762 
00764   ha_rows send_records;
00765 
00767   Item *having;
00768 
00770   bool distinct;
00771 
00773   void cleanup();
00774   inline bool is_using_loose_index_scan()
00775   {
00776     /*
00777       If JOIN_TAB::filesort is set, then the access method defined in
00778       filesort will be used to read from the table and
00779       JOIN_TAB::select reads from filesort using scan or ref access.
00780     */
00781     DBUG_ASSERT(!(select && select->quick && filesort));
00782 
00783     const SQL_SELECT *sel= filesort ? filesort->select : select;
00784     return (sel && sel->quick &&
00785             (sel->quick->get_type() == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX));
00786   }
00787   bool is_using_agg_loose_index_scan ()
00788   {
00789     /*
00790       If JOIN_TAB::filesort is set, then the access method defined in
00791       filesort will be used to read from the table and
00792       JOIN_TAB::select reads from filesort using scan or ref access.
00793     */
00794     DBUG_ASSERT(!(select && select->quick && filesort));
00795 
00796     const SQL_SELECT *sel= filesort ? filesort->select : select;
00797     return (sel && sel->quick &&
00798             (sel->quick->get_type() ==
00799              QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX) &&
00800             static_cast<QUICK_GROUP_MIN_MAX_SELECT*>(sel->quick)->
00801                                                      is_agg_distinct());
00802   }
00803   /* SemiJoinDuplicateElimination: reserve space for rowid */
00804   bool check_rowid_field()
00805   {
00806     if (keep_current_rowid && !used_rowid_fields)
00807     {
00808       used_rowid_fields= 1;
00809       used_fieldlength+= table->file->ref_length;
00810     }
00811     return MY_TEST(used_rowid_fields);
00812   }
00813   bool is_inner_table_of_outer_join()
00814   {
00815     return first_inner != NULL;
00816   }
00817   bool is_single_inner_of_semi_join()
00818   {
00819     return first_sj_inner_tab == this && last_sj_inner_tab == this;
00820   }
00821   bool is_single_inner_of_outer_join()
00822   {
00823     return first_inner == this && first_inner->last_inner == this;
00824   }
00825   bool is_first_inner_for_outer_join()
00826   {
00827     return first_inner && first_inner == this;
00828   }
00829   Item *condition() const
00830   {
00831     return m_condition;
00832   }
00833   void set_condition(Item *to, uint line)
00834   {
00835     DBUG_PRINT("info", 
00836                ("JOIN_TAB::m_condition changes %p -> %p at line %u tab %p",
00837                 m_condition, to, line, this));
00838     m_condition= to;
00839     quick_order_tested.clear_all();
00840   }
00841 
00842   Item *set_jt_and_sel_condition(Item *new_cond, uint line)
00843   {
00844     Item *tmp_cond= m_condition;
00845     set_condition(new_cond, line);
00846     if (select)
00847       select->cond= new_cond;
00848     return tmp_cond;
00849   }
00850 
00852   uint get_sj_strategy() const
00853   {
00854     if (first_sj_inner_tab == NULL)
00855       return SJ_OPT_NONE;
00856     DBUG_ASSERT(first_sj_inner_tab->position->sj_strategy != SJ_OPT_NONE);
00857     return first_sj_inner_tab->position->sj_strategy;
00858   }
00863   uint sjm_query_block_id() const;
00864 
00865   bool and_with_condition(Item *tmp_cond, uint line);
00866   bool and_with_jt_and_sel_condition(Item *tmp_cond, uint line);
00867 
00876   bool has_guarded_conds() const
00877   {
00878     return ref.has_guarded_conds();
00879   }
00880   Item *unified_condition() const;
00881   bool prepare_scan();
00882   bool use_order() const; 
00883   bool sort_table();
00884   bool remove_duplicates();
00885 } JOIN_TAB;
00886 
00887 inline
00888 st_join_table::st_join_table()
00889   : table(NULL),
00890     position(NULL),
00891     keyuse(NULL),
00892     select(NULL),
00893     m_condition(NULL),
00894     quick(NULL),
00895     on_expr_ref(NULL),
00896     cond_equal(NULL),
00897     first_inner(NULL),
00898     found(false),
00899     not_null_compl(false),
00900     materialized(false),
00901     last_inner(NULL),
00902     first_upper(NULL),
00903     first_unmatched(NULL),
00904     pre_idx_push_cond(NULL),
00905     info(ET_none),
00906     packed_info(0),
00907     materialize_table(NULL),
00908     read_first_record(NULL),
00909     next_select(NULL),
00910     read_record(),
00911     save_read_first_record(NULL),
00912     save_read_record(NULL),
00913     sj_mat_exec(NULL),
00914     worst_seeks(0.0),
00915     const_keys(),
00916     checked_keys(),
00917     needed_reg(),
00918     keys(),
00919     quick_order_tested(),
00920 
00921     records(0),
00922     found_records(0),
00923     read_time(0),
00924 
00925     dependent(0),
00926     key_dependent(0),
00927     prefix_tables_map(0),
00928     added_tables_map(0),
00929     index(0),
00930     used_fields(0),
00931     used_fieldlength(0),
00932     used_blobs(0),
00933     used_null_fields(0),
00934     used_rowid_fields(0),
00935     used_uneven_bit_fields(0),
00936     use_quick(QS_NONE),
00937     type(JT_UNKNOWN),
00938     not_used_in_distinct(false),
00939 
00940     limit(0),
00941     ref(),
00942     use_join_cache(0),
00943     op(NULL),
00944 
00945     cache_idx_cond(NULL),
00946     cache_select(NULL),
00947     join(NULL),
00948 
00949     emb_sj_nest(NULL),
00950     first_sj_inner_tab(NULL),
00951     last_sj_inner_tab(NULL),
00952 
00953     flush_weedout_table(NULL),
00954     check_weed_out_table(NULL),
00955     firstmatch_return(NULL),
00956     loosescan_key_len(0),
00957     loosescan_buf(NULL),
00958     match_tab(NULL),
00959     found_match(FALSE),
00960 
00961     keep_current_rowid(0),
00962     copy_current_rowid(NULL),
00963     embedding_map(0),
00964     tmp_table_param(NULL),
00965     filesort(NULL),
00966     fields(NULL),
00967     all_fields(NULL),
00968     ref_array(NULL),
00969     send_records(0),
00970     having(NULL),
00971     distinct(false)
00972 {
00978   memset(&read_record, 0, sizeof(read_record));
00979 }
00980 
01017 class Join_tab_compare_default :
01018   public std::binary_function<const JOIN_TAB*, const JOIN_TAB*, bool>
01019 {
01020 public:
01021   bool operator()(const JOIN_TAB *jt1, const JOIN_TAB *jt2)
01022   {
01023     // Sorting distinct tables, so a table should not be compared with itself
01024     DBUG_ASSERT(jt1 != jt2);
01025 
01026     if (jt1->dependent & jt2->table->map)
01027       return false;
01028     if (jt2->dependent & jt1->table->map)
01029       return true;
01030 
01031     const bool jt1_keydep_jt2= jt1->key_dependent & jt2->table->map;
01032     const bool jt2_keydep_jt1= jt2->key_dependent & jt1->table->map;
01033 
01034     if (jt1_keydep_jt2 && !jt2_keydep_jt1)
01035       return false;
01036     if (jt2_keydep_jt1 && !jt1_keydep_jt2)
01037       return true;
01038 
01039     if (jt1->found_records > jt2->found_records)
01040       return false;
01041     if (jt1->found_records < jt2->found_records)
01042       return true;
01043 
01044     return jt1 < jt2;
01045   }
01046 };
01047 
01055 class Join_tab_compare_straight :
01056   public std::binary_function<const JOIN_TAB*, const JOIN_TAB*, bool>
01057 {
01058 public:
01059   bool operator()(const JOIN_TAB *jt1, const JOIN_TAB *jt2)
01060   {
01061     // Sorting distinct tables, so a table should not be compared with itself
01062     DBUG_ASSERT(jt1 != jt2);
01063 
01064     /*
01065       We don't do subquery flattening if the parent or child select has
01066       STRAIGHT_JOIN modifier. It is complicated to implement and the semantics
01067       is hardly useful.
01068     */
01069     DBUG_ASSERT(!jt1->emb_sj_nest);
01070     DBUG_ASSERT(!jt2->emb_sj_nest);
01071 
01072     if (jt1->dependent & jt2->table->map)
01073       return false;
01074     if (jt2->dependent & jt1->table->map)
01075       return true;
01076 
01077     return jt1 < jt2;
01078   }
01079 };
01080 
01081 /*
01082   Same as Join_tab_compare_default but tables from within the given
01083   semi-join nest go first. Used when optimizing semi-join
01084   materialization nests.
01085 */
01086 class Join_tab_compare_embedded_first :
01087   public std::binary_function<const JOIN_TAB*, const JOIN_TAB*, bool>
01088 {
01089 private:
01090   const TABLE_LIST *emb_nest;
01091 public:
01092   
01093   Join_tab_compare_embedded_first(const TABLE_LIST *nest) : emb_nest(nest){}
01094 
01095   bool operator()(const JOIN_TAB *jt1, const JOIN_TAB *jt2)
01096   {
01097     // Sorting distinct tables, so a table should not be compared with itself
01098     DBUG_ASSERT(jt1 != jt2);
01099 
01100     if (jt1->emb_sj_nest == emb_nest && jt2->emb_sj_nest != emb_nest)
01101       return true;
01102     if (jt1->emb_sj_nest != emb_nest && jt2->emb_sj_nest == emb_nest)
01103       return false;
01104 
01105     Join_tab_compare_default cmp;
01106     return cmp(jt1,jt2);
01107   }
01108 };
01109 
01110 
01111 typedef Bounds_checked_array<Item_null_result*> Item_null_array;
01112 
01113 typedef struct st_select_check {
01114   uint const_ref,reg_ref;
01115 } SELECT_CHECK;
01116 
01117 /* Extern functions in sql_select.cc */
01118 void count_field_types(SELECT_LEX *select_lex, TMP_TABLE_PARAM *param, 
01119                        List<Item> &fields, bool reset_with_sum_func);
01120 uint find_shortest_key(TABLE *table, const key_map *usable_keys);
01121 
01122 /* functions from opt_sum.cc */
01123 bool simple_pred(Item_func *func_item, Item **args, bool *inv_order);
01124 int opt_sum_query(THD* thd,
01125                   TABLE_LIST *tables, List<Item> &all_fields, Item *conds);
01126 
01127 /* from sql_delete.cc, used by opt_range.cc */
01128 extern "C" int refpos_order_cmp(const void* arg, const void *a,const void *b);
01129 
01132 class store_key :public Sql_alloc
01133 {
01134 public:
01135   bool null_key; /* TRUE <=> the value of the key has a null part */
01136   enum store_key_result { STORE_KEY_OK, STORE_KEY_FATAL, STORE_KEY_CONV };
01137   store_key(THD *thd, Field *field_arg, uchar *ptr, uchar *null, uint length)
01138     :null_key(0), null_ptr(null), err(0)
01139   {
01140     if (field_arg->type() == MYSQL_TYPE_BLOB
01141         || field_arg->type() == MYSQL_TYPE_GEOMETRY)
01142     {
01143       /* 
01144         Key segments are always packed with a 2 byte length prefix.
01145         See mi_rkey for details.
01146       */
01147       to_field= new Field_varstring(ptr, length, 2, null, 1, 
01148                                     Field::NONE, field_arg->field_name,
01149                                     field_arg->table->s, field_arg->charset());
01150       to_field->init(field_arg->table);
01151     }
01152     else
01153       to_field=field_arg->new_key_field(thd->mem_root, field_arg->table,
01154                                         ptr, null, 1);
01155   }
01156   virtual ~store_key() {}                       
01157   virtual const char *name() const=0;
01158 
01165   enum store_key_result copy()
01166   {
01167     enum store_key_result result;
01168     THD *thd= to_field->table->in_use;
01169     enum_check_fields saved_count_cuted_fields= thd->count_cuted_fields;
01170     sql_mode_t sql_mode= thd->variables.sql_mode;
01171     thd->variables.sql_mode&= ~(MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE);
01172 
01173     thd->count_cuted_fields= CHECK_FIELD_IGNORE;
01174 
01175     result= copy_inner();
01176 
01177     thd->count_cuted_fields= saved_count_cuted_fields;
01178     thd->variables.sql_mode= sql_mode;
01179 
01180     return result;
01181   }
01182 
01183  protected:
01184   Field *to_field;                              // Store data here
01185   uchar *null_ptr;
01186   uchar err;
01187 
01188   virtual enum store_key_result copy_inner()=0;
01189 };
01190 
01191 
01192 static store_key::store_key_result
01193 type_conversion_status_to_store_key (type_conversion_status ts)
01194 {
01195   switch (ts)
01196   {
01197   case TYPE_OK:
01198     return store_key::STORE_KEY_OK;
01199   case TYPE_NOTE_TIME_TRUNCATED:
01200     return store_key::STORE_KEY_CONV;
01201   case TYPE_WARN_OUT_OF_RANGE:
01202   case TYPE_NOTE_TRUNCATED:
01203   case TYPE_WARN_TRUNCATED:
01204   case TYPE_ERR_NULL_CONSTRAINT_VIOLATION:
01205   case TYPE_ERR_BAD_VALUE:
01206   case TYPE_ERR_OOM:
01207     return store_key::STORE_KEY_FATAL;
01208   default:
01209     DBUG_ASSERT(false); // not possible
01210   }
01211 
01212   return store_key::STORE_KEY_FATAL;
01213 }
01214 
01215 class store_key_field: public store_key
01216 {
01217   Copy_field copy_field;
01218   const char *field_name;
01219  public:
01220   store_key_field(THD *thd, Field *to_field_arg, uchar *ptr,
01221                   uchar *null_ptr_arg,
01222                   uint length, Field *from_field, const char *name_arg)
01223     :store_key(thd, to_field_arg,ptr,
01224                null_ptr_arg ? null_ptr_arg : from_field->maybe_null() ? &err
01225                : (uchar*) 0, length), field_name(name_arg)
01226   {
01227     if (to_field)
01228     {
01229       copy_field.set(to_field,from_field,0);
01230     }
01231   }
01232   const char *name() const { return field_name; }
01233 
01234  protected: 
01235   enum store_key_result copy_inner()
01236   {
01237     TABLE *table= copy_field.to_field->table;
01238     my_bitmap_map *old_map= dbug_tmp_use_all_columns(table,
01239                                                      table->write_set);
01240     copy_field.do_copy(&copy_field);
01241     dbug_tmp_restore_column_map(table->write_set, old_map);
01242     null_key= to_field->is_null();
01243     return err != 0 ? STORE_KEY_FATAL : STORE_KEY_OK;
01244   }
01245 };
01246 
01247 
01248 class store_key_item :public store_key
01249 {
01250  protected:
01251   Item *item;
01252 public:
01253   store_key_item(THD *thd, Field *to_field_arg, uchar *ptr,
01254                  uchar *null_ptr_arg, uint length, Item *item_arg)
01255     :store_key(thd, to_field_arg, ptr,
01256                null_ptr_arg ? null_ptr_arg : item_arg->maybe_null ?
01257                &err : (uchar*) 0, length), item(item_arg)
01258   {}
01259   const char *name() const { return "func"; }
01260 
01261  protected:  
01262   enum store_key_result copy_inner()
01263   {
01264     TABLE *table= to_field->table;
01265     my_bitmap_map *old_map= dbug_tmp_use_all_columns(table,
01266                                                      table->write_set);
01267     type_conversion_status save_res= item->save_in_field(to_field, true);
01268     store_key_result res;
01269     /*
01270      Item::save_in_field() may call Item::val_xxx(). And if this is a subquery
01271      we need to check for errors executing it and react accordingly
01272     */
01273     if (save_res != TYPE_OK && table->in_use->is_error())
01274       res= STORE_KEY_FATAL;
01275     else
01276       res= type_conversion_status_to_store_key(save_res);
01277     dbug_tmp_restore_column_map(table->write_set, old_map);
01278     null_key= to_field->is_null() || item->null_value;
01279     return (err != 0) ? STORE_KEY_FATAL : res;
01280   }
01281 };
01282 
01283 
01284 class store_key_const_item :public store_key_item
01285 {
01286   bool inited;
01287 public:
01288   store_key_const_item(THD *thd, Field *to_field_arg, uchar *ptr,
01289                        uchar *null_ptr_arg, uint length,
01290                        Item *item_arg)
01291     :store_key_item(thd, to_field_arg, ptr,
01292                     null_ptr_arg, length, item_arg), inited(0)
01293   {
01294   }
01295   const char *name() const { return "const"; }
01296 
01297 protected:  
01298   enum store_key_result copy_inner()
01299   {
01300     if (!inited)
01301     {
01302       inited=1;
01303       store_key_result res= store_key_item::copy_inner();
01304       if (res && !err)
01305         err= res;
01306     }
01307     return (err > 2 ? STORE_KEY_FATAL : (store_key_result) err);
01308   }
01309 };
01310 
01311 bool error_if_full_join(JOIN *join);
01312 bool handle_select(THD *thd, select_result *result,
01313                    ulong setup_tables_done_option);
01314 bool mysql_select(THD *thd,
01315                   TABLE_LIST *tables, uint wild_num,  List<Item> &list,
01316                   Item *conds, SQL_I_List<ORDER> *order,
01317                   SQL_I_List<ORDER> *group,
01318                   Item *having, ulonglong select_type, 
01319                   select_result *result, SELECT_LEX_UNIT *unit, 
01320                   SELECT_LEX *select_lex);
01321 void free_underlaid_joins(THD *thd, SELECT_LEX *select);
01322 
01323 
01324 void calc_used_field_length(THD *thd, JOIN_TAB *join_tab);
01325 
01326 inline bool optimizer_flag(THD *thd, uint flag)
01327 { 
01328   return (thd->variables.optimizer_switch & flag);
01329 }
01330 
01331 uint get_index_for_order(ORDER *order, TABLE *table, SQL_SELECT *select,
01332                          ha_rows limit, bool *need_sort, bool *reverse);
01333 ORDER *simple_remove_const(ORDER *order, Item *where);
01334 bool const_expression_in_where(Item *cond, Item *comp_item,
01335                                Field *comp_field= NULL,
01336                                Item **const_item= NULL);
01337 bool test_if_subpart(ORDER *a,ORDER *b);
01338 void calc_group_buffer(JOIN *join,ORDER *group);
01339 bool
01340 test_if_skip_sort_order(JOIN_TAB *tab, ORDER *order, ha_rows select_limit,
01341                         const bool no_changes, const key_map *map,
01342                         const char *clause_type);
01343 bool make_join_readinfo(JOIN *join, ulonglong options, uint no_jbuf_after);
01344 bool create_ref_for_key(JOIN *join, JOIN_TAB *j, Key_use *org_keyuse,
01345                         table_map used_tables);
01346 bool types_allow_materialization(Item *outer, Item *inner);
01347 bool and_conditions(Item **e1, Item *e2);
01348 
01349 static inline Item * and_items(Item* cond, Item *item)
01350 {
01351   return (cond? (new Item_cond_and(cond, item)) : item);
01352 }
01353 
01354 uint actual_key_parts(KEY *key_info);
01355 uint actual_key_flags(KEY *key_info);
01356 
01357 int test_if_order_by_key(ORDER *order, TABLE *table, uint idx,
01358                          uint *used_key_parts= NULL);
01359 
01360 #endif /* SQL_SELECT_INCLUDED */
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines