sql_select.h 27.5 KB
Newer Older
unknown's avatar
unknown committed
1
/* Copyright (C) 2000-2006 MySQL AB
unknown's avatar
unknown committed
2

unknown's avatar
unknown committed
3 4
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
unknown's avatar
unknown committed
5
   the Free Software Foundation; version 2 of the License.
unknown's avatar
unknown committed
6

unknown's avatar
unknown committed
7 8 9 10
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
unknown's avatar
unknown committed
11

unknown's avatar
unknown committed
12 13 14 15 16
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */


unknown's avatar
unknown committed
17 18 19 20 21 22
/**
  @file

  @brief
  classes to use when handling where clause
*/
unknown's avatar
unknown committed
23

24
#ifdef USE_PRAGMA_INTERFACE
unknown's avatar
unknown committed
25 26 27 28 29 30 31 32
#pragma interface			/* gcc class implementation */
#endif

#include "procedure.h"
#include <myisam.h>

typedef struct keyuse_t {
  TABLE *table;
unknown's avatar
unknown committed
33
  Item	*val;				/**< or value if no field */
unknown's avatar
unknown committed
34
  table_map used_tables;
35
  uint	key, keypart, optimize;
36 37
  key_part_map keypart_map;
  ha_rows      ref_table_rows;
unknown's avatar
unknown committed
38
  /**
39 40 41 42
    If true, the comparison this value was created from will not be
    satisfied if val has NULL 'value'.
  */
  bool null_rejecting;
43 44 45 46 47 48 49 50 51 52 53
  /*
    !NULL - This KEYUSE was created from an equality that was wrapped into
            an Item_func_trig_cond. This means the equality (and validity of 
            this KEYUSE element) can be turned on and off. The on/off state 
            is indicted by the pointed value:
              *cond_guard == TRUE <=> equality condition is on
              *cond_guard == FALSE <=> equality condition is off

    NULL  - Otherwise (the source equality can't be turned off)
  */
  bool *cond_guard;
unknown's avatar
unknown committed
54 55 56 57 58 59 60
} KEYUSE;

class store_key;

typedef struct st_table_ref
{
  bool		key_err;
61 62
  /** True if something was read into buffer in join_read_key.  */
  bool          has_record;
unknown's avatar
unknown committed
63 64 65 66 67
  uint          key_parts;                ///< num of ...
  uint          key_length;               ///< length of key_buff
  int           key;                      ///< key no
  uchar         *key_buff;                ///< value to look for with key
  uchar         *key_buff2;               ///< key_buff+key_length
unknown's avatar
unknown committed
68
  store_key     **key_copy;               //
unknown's avatar
unknown committed
69
  Item          **items;                  ///< val()'s for each keypart
70 71 72 73 74 75 76 77 78 79 80 81
  /*  
    Array of pointers to trigger variables. Some/all of the pointers may be
    NULL.  The ref access can be used iff
    
      for each used key part i, (!cond_guards[i] || *cond_guards[i]) 

    This array is used by subquery code. The subquery code may inject
    triggered conditions, i.e. conditions that can be 'switched off'. A ref 
    access created from such condition is not valid when at least one of the 
    underlying conditions is switched off (see subquery code for more details)
  */
  bool          **cond_guards;
unknown's avatar
unknown committed
82
  /**
83 84 85 86
    (null_rejecting & (1<<i)) means the condition is '=' and no matching
    rows will be produced if items[i] IS NULL (see add_not_null_conds())
  */
  key_part_map  null_rejecting;
unknown's avatar
unknown committed
87
  table_map	depend_map;		  ///< Table depends on these tables.
88
  /* null byte position in the key_buf. Used for REF_OR_NULL optimization */
89
  uchar          *null_ref_key;
90 91 92 93 94
  /*
    The number of times the record associated with this key was used
    in the join.
  */
  ha_rows       use_count;
unknown's avatar
unknown committed
95 96
} TABLE_REF;

97

98 99 100 101

#define CACHE_BLOB      1        /* blob field  */
#define CACHE_STRIPPED  2        /* field stripped of trailing spaces */

unknown's avatar
unknown committed
102
/**
103 104
  CACHE_FIELD and JOIN_CACHE is used on full join to cache records in outer
  table
unknown's avatar
unknown committed
105 106 107
*/

typedef struct st_cache_field {
108 109
  uchar *str;
  uint length, blob_length;
110 111
  Field *field;
  uint type;    /**< category of the of the copied field (CACHE_BLOB et al.) */
unknown's avatar
unknown committed
112 113 114 115 116 117 118 119 120 121 122 123
} CACHE_FIELD;


typedef struct st_join_cache {
  uchar *buff,*pos,*end;
  uint records,record_nr,ptr_record,fields,length,blobs;
  CACHE_FIELD *field,**blob_ptr;
  SQL_SELECT *select;
} JOIN_CACHE;


/*
124
  The structs which holds the join connections and join states
unknown's avatar
unknown committed
125 126
*/
enum join_type { JT_UNKNOWN,JT_SYSTEM,JT_CONST,JT_EQ_REF,JT_REF,JT_MAYBE_REF,
127
		 JT_ALL, JT_RANGE, JT_NEXT, JT_FT, JT_REF_OR_NULL,
128
		 JT_UNIQUE_SUBQUERY, JT_INDEX_SUBQUERY, JT_INDEX_MERGE};
unknown's avatar
unknown committed
129 130 131

class JOIN;

132 133 134 135 136 137 138
enum enum_nested_loop_state
{
  NESTED_LOOP_KILLED= -2, NESTED_LOOP_ERROR= -1,
  NESTED_LOOP_OK= 0, NESTED_LOOP_NO_MORE_ROWS= 1,
  NESTED_LOOP_QUERY_LIMIT= 3, NESTED_LOOP_CURSOR_LIMIT= 4
};

139 140 141 142 143 144 145

/* Values for JOIN_TAB::packed_info */
#define TAB_INFO_HAVE_VALUE 1
#define TAB_INFO_USING_INDEX 2
#define TAB_INFO_USING_WHERE 4
#define TAB_INFO_FULL_SCAN_ON_NULL 8

146 147
typedef enum_nested_loop_state
(*Next_select_func)(JOIN *, struct st_join_table *, bool);
148
typedef int (*Read_record_func)(struct st_join_table *tab);
149
Next_select_func setup_end_select_func(JOIN *join);
150

151

unknown's avatar
unknown committed
152
typedef struct st_join_table {
153
  st_join_table() {}                          /* Remove gcc warning */
unknown's avatar
unknown committed
154
  TABLE		*table;
unknown's avatar
unknown committed
155
  KEYUSE	*keyuse;			/**< pointer to first used key */
unknown's avatar
unknown committed
156 157
  SQL_SELECT	*select;
  COND		*select_cond;
unknown's avatar
unknown committed
158
  QUICK_SELECT_I *quick;
unknown's avatar
unknown committed
159 160 161 162 163 164 165 166
  Item	       **on_expr_ref;   /**< pointer to the associated on expression   */
  COND_EQUAL    *cond_equal;    /**< multiple equalities for the on expression */
  st_join_table *first_inner;   /**< first inner table for including outerjoin */
  bool           found;         /**< true after all matches or null complement */
  bool           not_null_compl;/**< true before null complement is added      */
  st_join_table *last_inner;    /**< last table table for embedding outer join */
  st_join_table *first_upper;  /**< first inner table for embedding outer join */
  st_join_table *first_unmatched; /**< used for optimization purposes only     */
167 168
  
  /* Special content for EXPLAIN 'Extra' column or NULL if none */
unknown's avatar
unknown committed
169
  const char	*info;
170 171 172 173 174 175
  /* 
    Bitmap of TAB_INFO_* bits that encodes special line for EXPLAIN 'Extra'
    column, or 0 if there is no info.
  */
  uint          packed_info;

176 177
  Read_record_func read_first_record;
  Next_select_func next_select;
unknown's avatar
unknown committed
178
  READ_RECORD	read_record;
179 180 181 182 183 184 185
  /* 
    Currently the following two fields are used only for a [NOT] IN subquery
    if it is executed by an alternative full table scan when the left operand of
    the subquery predicate is evaluated to NULL.
  */  
  Read_record_func save_read_first_record;/* to save read_first_record */ 
  int (*save_read_record) (READ_RECORD *);/* to save read_record.read_record */
unknown's avatar
unknown committed
186
  double	worst_seeks;
unknown's avatar
unknown committed
187 188
  key_map	const_keys;			/**< Keys with constant part */
  key_map	checked_keys;			/**< Keys checked in find_best */
unknown's avatar
unknown committed
189
  key_map	needed_reg;
unknown's avatar
unknown committed
190
  key_map       keys;                           /**< all keys with can be used */
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205

  /* Either #rows in the table or 1 for const table.  */
  ha_rows	records;
  /*
    Number of records that will be scanned (yes scanned, not returned) by the
    best 'independent' access method, i.e. table scan or QUICK_*_SELECT)
  */
  ha_rows       found_records;
  /*
    Cost of accessing the table using "ALL" or range/index_merge access
    method (but not 'index' for some reason), i.e. this matches method which
    E(#records) is in found_records.
  */
  ha_rows       read_time;
  
unknown's avatar
unknown committed
206 207
  table_map	dependent,key_dependent;
  uint		use_quick,index;
unknown's avatar
unknown committed
208
  uint		status;				///< Save status for cache
unknown's avatar
unknown committed
209
  uint		used_fields,used_fieldlength,used_blobs;
unknown's avatar
unknown committed
210 211
  enum join_type type;
  bool		cached_eq_ref_table,eq_ref_table,not_used_in_distinct;
212
  bool		sorted;
unknown's avatar
unknown committed
213 214 215 216 217 218
  /* 
    If it's not 0 the number stored this field indicates that the index
    scan has been chosen to access the table data and we expect to scan 
    this number of rows for the table.
  */ 
  ha_rows       limit; 
unknown's avatar
unknown committed
219
  TABLE_REF	ref;
unknown's avatar
unknown committed
220
  JOIN_CACHE	cache;
221
  JOIN		*join;
unknown's avatar
unknown committed
222
  /** Bitmap of nested joins this table is part of */
223
  nested_join_map embedding_map;
Sergey Petrunya's avatar
Sergey Petrunya committed
224

225
  void cleanup();
226 227 228 229 230 231
  inline bool is_using_loose_index_scan()
  {
    return (select && select->quick &&
            (select->quick->get_type() ==
             QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX));
  }
unknown's avatar
unknown committed
232 233
} JOIN_TAB;

234 235 236 237 238
enum_nested_loop_state sub_select_cache(JOIN *join, JOIN_TAB *join_tab, bool
                                        end_of_records);
enum_nested_loop_state sub_select(JOIN *join,JOIN_TAB *join_tab, bool
                                  end_of_records);

unknown's avatar
unknown committed
239
/**
240 241 242 243
  Information about a position of table within a join order. Used in join
  optimization.
*/
typedef struct st_position
244
{
245 246 247 248 249
  /*
    The "fanout": number of output rows that will be produced (after
    pushed down selection condition is applied) per each row combination of
    previous tables.
  */
unknown's avatar
unknown committed
250
  double records_read;
251

252 253 254 255 256
  /* 
    Cost accessing the table in course of the entire complete join execution,
    i.e. cost of one access method use (e.g. 'range' or 'ref' scan ) times 
    number the access method will be invoked.
  */
257
  double read_time;
unknown's avatar
unknown committed
258
  JOIN_TAB *table;
259 260 261 262 263

  /*
    NULL  -  'index' or 'range' or 'index_merge' or 'ALL' access is used.
    Other - [eq_]ref[_or_null] access is used. Pointer to {t.keypart1 = expr}
  */
unknown's avatar
unknown committed
264
  KEYUSE *key;
265 266 267

  /* If ref-based access is used: bitmap of tables this table depends on  */
  table_map ref_depend_map;
unknown's avatar
unknown committed
268 269
} POSITION;

270

271 272 273 274
typedef struct st_rollup
{
  enum State { STATE_NONE, STATE_INITED, STATE_READY };
  State state;
unknown's avatar
unknown committed
275
  Item_null_result **null_items;
276 277 278 279
  Item ***ref_pointer_arrays;
  List<Item> *fields;
} ROLLUP;

unknown's avatar
unknown committed
280

281 282
class JOIN :public Sql_alloc
{
unknown's avatar
unknown committed
283 284
  JOIN(const JOIN &rhs);                        /**< not implemented */
  JOIN& operator=(const JOIN &rhs);             /**< not implemented */
unknown's avatar
unknown committed
285
public:
286
  JOIN_TAB *join_tab,**best_ref;
unknown's avatar
unknown committed
287 288
  JOIN_TAB **map2table;    ///< mapping between table indexes and JOIN_TABs
  JOIN_TAB *join_tab_save; ///< saved join_tab for subquery reexecution
unknown's avatar
unknown committed
289 290 291
  TABLE    **table,**all_tables,*sort_by_table;
  uint	   tables,const_tables;
  uint	   send_group_parts;
292 293 294 295 296 297 298 299
  /**
    Indicates that grouping will be performed on the result set during
    query execution. This field belongs to query execution.

    @see make_group_fields, alloc_group_fields, JOIN::exec
  */
  bool     sort_and_group; 
  bool     first_record,full_join,group, no_field_update;
300
  bool	   do_send_rows;
unknown's avatar
unknown committed
301
  /**
302 303 304 305
    TRUE when we want to resume nested loop iterations when
    fetching data from a cursor
  */
  bool     resume_nested_loop;
Sergey Petrunya's avatar
Sergey Petrunya committed
306 307 308 309 310 311
  table_map const_table_map;
  /*
    Constant tables for which we have found a row (as opposed to those for
    which we didn't).
  */
  table_map found_const_table_map;
Sergey Petrunia's avatar
Sergey Petrunia committed
312 313
  
  /* Tables removed by table elimination. Set to 0 before the elimination. */
Sergey Petrunia's avatar
Sergey Petrunia committed
314
  table_map eliminated_tables;
315 316 317 318
  /*
     Bitmap of all inner tables from outer joins
  */
  table_map outer_join;
unknown's avatar
unknown committed
319
  ha_rows  send_records,found_records,examined_rows,row_limit, select_limit;
unknown's avatar
unknown committed
320
  /**
unknown's avatar
unknown committed
321
    Used to fetch no more than given amount of rows per one
322 323 324 325 326 327 328 329
    fetch operation of server side cursor.
    The value is checked in end_send and end_send_group in fashion, similar
    to offset_limit_cnt:
      - fetch_limit= HA_POS_ERROR if there is no cursor.
      - when we open a cursor, we set fetch_limit to 0,
      - on each fetch iteration we add num_rows to fetch to fetch_limit
  */
  ha_rows  fetch_limit;
unknown's avatar
unknown committed
330
  POSITION positions[MAX_TABLES+1],best_positions[MAX_TABLES+1];
331
  
unknown's avatar
unknown committed
332
  /* *
333 334 335 336 337
    Bitmap of nested joins embedding the position at the end of the current 
    partial join (valid only during join optimizer run).
  */
  nested_join_map cur_embedding_map;

unknown's avatar
unknown committed
338 339
  double   best_read;
  List<Item> *fields;
unknown's avatar
unknown committed
340
  List<Cached_item> group_fields, group_fields_cache;
unknown's avatar
unknown committed
341
  TABLE    *tmp_table;
unknown's avatar
unknown committed
342
  /// used to store 2 possible tmp table of SELECT
343
  TABLE    *exec_tmp_table1, *exec_tmp_table2;
unknown's avatar
unknown committed
344
  THD	   *thd;
345
  Item_sum  **sum_funcs, ***sum_funcs_end;
unknown's avatar
unknown committed
346
  /** second copy of sumfuncs (for queries with 2 temporary tables */
347
  Item_sum  **sum_funcs2, ***sum_funcs_end2;
unknown's avatar
unknown committed
348 349
  Procedure *procedure;
  Item	    *having;
unknown's avatar
unknown committed
350 351
  Item      *tmp_having; ///< To store having when processed temporary table
  Item      *having_history; ///< Store having for explain
352
  ulonglong  select_options;
unknown's avatar
unknown committed
353 354 355
  select_result *result;
  TMP_TABLE_PARAM tmp_table_param;
  MYSQL_LOCK *lock;
unknown's avatar
unknown committed
356
  /// unit structure (with global parameters) for this select
357
  SELECT_LEX_UNIT *unit;
unknown's avatar
unknown committed
358
  /// select that processed
359
  SELECT_LEX *select_lex;
unknown's avatar
unknown committed
360
  /** 
361 362 363 364 365 366 367
    TRUE <=> optimizer must not mark any table as a constant table.
    This is needed for subqueries in form "a IN (SELECT .. UNION SELECT ..):
    when we optimize the select that reads the results of the union from a
    temporary table, we must not mark the temp. table as constant because
    the number of rows in it may vary from one subquery execution to another.
  */
  bool no_const_tables; 
368
  bool no_rows_in_result_called;
369
  
370 371 372
  /**
    Copy of this JOIN to be used with temporary tables.

373 374 375 376 377 378 379 380 381 382 383 384
    tmp_join is used when the JOIN needs to be "reusable" (e.g. in a
    subquery that gets re-executed several times) and we know will use
    temporary tables for materialization. The materialization to a
    temporary table overwrites the JOIN structure to point to the
    temporary table after the materialization is done. This is where
    tmp_join is used : it's a copy of the JOIN before the
    materialization and is used in restoring before re-execution by
    overwriting the current JOIN structure with the saved copy.
    Because of this we should pay extra care of not freeing up helper
    structures that are referenced by the original contents of the
    JOIN. We can check for this by making sure the "current" join is
    not the temporary copy, e.g.  !tmp_join || tmp_join != join
385
 
386 387
    We should free these sub-structures at JOIN::destroy() if the
    "current" join has a copy is not that copy.
388 389
  */
  JOIN *tmp_join;
unknown's avatar
unknown committed
390
  ROLLUP rollup;				///< Used with rollup
391

unknown's avatar
unknown committed
392 393
  bool select_distinct;				///< Set if SELECT DISTINCT
  /**
394 395 396 397 398 399 400
    If we have the GROUP BY statement in the query,
    but the group_list was emptied by optimizer, this
    flag is TRUE.
    It happens when fields in the GROUP BY are from
    constant table
  */
  bool group_optimized_away;
unknown's avatar
unknown committed
401 402 403 404 405

  /*
    simple_xxxxx is set if ORDER/GROUP BY doesn't include any references
    to other tables than the first non-constant table in the JOIN.
    It's also set if ORDER/GROUP BY is empty.
406 407
    Used for deciding for or against using a temporary table to compute 
    GROUP/ORDER BY.
unknown's avatar
unknown committed
408 409
  */
  bool simple_order, simple_group;
unknown's avatar
unknown committed
410
  /**
unknown's avatar
unknown committed
411 412 413 414
    Is set only in case if we have a GROUP BY clause
    and no ORDER BY after constant elimination of 'order'.
  */
  bool no_order;
unknown's avatar
unknown committed
415
  /** Is set if we have a GROUP BY and we have ORDER BY on a constant. */
unknown's avatar
unknown committed
416 417
  bool          skip_sort_order;

418
  bool need_tmp, hidden_group_fields;
419
  DYNAMIC_ARRAY keyuse;
420
  Item::cond_result cond_value, having_value;
unknown's avatar
unknown committed
421 422
  List<Item> all_fields; ///< to store all fields that used in query
  ///Above list changed to use temporary table
423
  List<Item> tmp_all_fields1, tmp_all_fields2, tmp_all_fields3;
unknown's avatar
unknown committed
424
  ///Part, shared with list above, emulate following list
425
  List<Item> tmp_fields_list1, tmp_fields_list2, tmp_fields_list3;
unknown's avatar
unknown committed
426
  List<Item> &fields_list; ///< hold field list passed to mysql_select
427
  List<Item> procedure_fields_list;
428 429 430 431
  int error;

  ORDER *order, *group_list, *proc_param; //hold parameters of mysql_select
  COND *conds;                            // ---"---
unknown's avatar
unknown committed
432
  Item *conds_history;                    // store WHERE for explain
unknown's avatar
unknown committed
433 434
  TABLE_LIST *tables_list;           ///<hold 'tables' parameter of mysql_select
  List<TABLE_LIST> *join_list;       ///< list of joined tables in reverse order
435
  COND_EQUAL *cond_equal;
unknown's avatar
unknown committed
436 437 438
  SQL_SELECT *select;                ///<created in optimisation phase
  JOIN_TAB *return_tab;              ///<used only for outer joins
  Item **ref_pointer_array; ///<used pointer reference for this select
439
  // Copy of above to be used with different lists
440
  Item **items0, **items1, **items2, **items3, **current_ref_pointer_array;
unknown's avatar
unknown committed
441 442
  uint ref_pointer_array_size; ///< size of above in bytes
  const char *zero_result_cause; ///< not 0 if exec must return zero result
443
  
unknown's avatar
unknown committed
444 445
  bool union_part; ///< this subselect is part of union 
  bool optimized; ///< flag to avoid double optimization in EXPLAIN
446

447 448 449 450 451 452
  /* 
    storage for caching buffers allocated during query execution. 
    These buffers allocations need to be cached as the thread memory pool is
    cleared only at the end of the execution of the whole query and not caching
    allocations that occur in repetition at execution time will result in 
    excessive memory usage.
453 454 455
    Note: make_simple_join always creates an execution plan that accesses
    a single table, thus it is sufficient to have a one-element array for
    table_reexec.
456 457
  */  
  SORT_FIELD *sortorder;                        // make_unireg_sortorder()
458
  TABLE *table_reexec[1];                       // make_simple_join()
459
  JOIN_TAB *join_tab_reexec;                    // make_simple_join()
460 461
  /* end of allocation caching storage */

462
  JOIN(THD *thd_arg, List<Item> &fields_arg, ulonglong select_options_arg,
463
       select_result *result_arg)
464
    :fields_list(fields_arg)
465
  {
466
    init(thd_arg, fields_arg, select_options_arg, result_arg);
467
  }
468

469
  void init(THD *thd_arg, List<Item> &fields_arg, ulonglong select_options_arg,
470 471
       select_result *result_arg)
  {
472
    join_tab= join_tab_save= 0;
473 474 475
    table= 0;
    tables= 0;
    const_tables= 0;
Sergey Petrunia's avatar
Sergey Petrunia committed
476
    eliminated_tables= 0;
477
    join_list= 0;
478
    implicit_grouping= FALSE;
479 480 481
    sort_and_group= 0;
    first_record= 0;
    do_send_rows= 1;
482
    resume_nested_loop= FALSE;
483 484
    send_records= 0;
    found_records= 0;
485
    fetch_limit= HA_POS_ERROR;
486 487 488
    examined_rows= 0;
    exec_tmp_table1= 0;
    exec_tmp_table2= 0;
489
    sortorder= 0;
490
    table_reexec[0]= 0;
491
    join_tab_reexec= 0;
492
    thd= thd_arg;
unknown's avatar
merge  
unknown committed
493
    sum_funcs= sum_funcs2= 0;
494
    procedure= 0;
unknown's avatar
unknown committed
495
    having= tmp_having= having_history= 0;
496 497 498 499 500 501 502 503 504 505 506 507 508 509
    select_options= select_options_arg;
    result= result_arg;
    lock= thd_arg->lock;
    select_lex= 0; //for safety
    tmp_join= 0;
    select_distinct= test(select_options & SELECT_DISTINCT);
    no_order= 0;
    simple_order= 0;
    simple_group= 0;
    skip_sort_order= 0;
    need_tmp= 0;
    hidden_group_fields= 0; /*safety*/
    error= 0;
    select= 0;
510
    return_tab= 0;
511 512 513 514
    ref_pointer_array= items0= items1= items2= items3= 0;
    ref_pointer_array_size= 0;
    zero_result_cause= 0;
    optimized= 0;
515
    cond_equal= 0;
516
    group_optimized_away= 0;
517
    no_rows_in_result_called= 0;
518

unknown's avatar
unknown committed
519
    all_fields= fields_arg;
520 521
    if (&fields_list != &fields_arg)      /* Avoid valgrind-warning */
      fields_list= fields_arg;
522
    bzero((char*) &keyuse,sizeof(keyuse));
523
    tmp_table_param.init();
524
    tmp_table_param.end_write_records= HA_POS_ERROR;
525
    rollup.state= ROLLUP::STATE_NONE;
526 527

    no_const_tables= FALSE;
528
  }
529

530 531 532
  int prepare(Item ***rref_pointer_array, TABLE_LIST *tables, uint wind_num,
	      COND *conds, uint og_num, ORDER *order, ORDER *group,
	      Item *having, ORDER *proc_param, SELECT_LEX *select,
533
	      SELECT_LEX_UNIT *unit);
534
  int optimize();
535
  int reinit();
536
  void exec();
537
  int destroy();
538
  void restore_tmp();
539 540
  bool alloc_func_list();
  bool make_sum_func_list(List<Item> &all_fields, List<Item> &send_fields,
541
			  bool before_group_by, bool recompute= FALSE);
542

543 544 545 546 547
  inline void set_items_ref_array(Item **ptr)
  {
    memcpy((char*) ref_pointer_array, (char*) ptr, ref_pointer_array_size);
    current_ref_pointer_array= ptr;
  }
548 549 550 551
  inline void init_items_ref_array()
  {
    items0= ref_pointer_array + all_fields.elements;
    memcpy(items0, ref_pointer_array, ref_pointer_array_size);
552
    current_ref_pointer_array= items0;
553
  }
554 555

  bool rollup_init();
556
  bool rollup_process_const_fields();
557 558
  bool rollup_make_fields(List<Item> &all_fields, List<Item> &fields,
			  Item_sum ***func);
559
  int rollup_send_data(uint idx);
unknown's avatar
unknown committed
560
  int rollup_write_data(uint idx, TABLE *table);
561
  void remove_subq_pushed_predicates(Item **where);
unknown's avatar
unknown committed
562
  /**
563 564 565 566 567
    Release memory and, if possible, the open tables held by this execution
    plan (and nested plans). It's used to release some tables before
    the end of execution in order to increase concurrency and reduce
    memory consumption.
  */
568
  void join_free();
unknown's avatar
unknown committed
569
  /** Cleanup this JOIN, possibly for reuse */
570
  void cleanup(bool full);
571
  void clear();
572
  bool save_join_tab();
unknown's avatar
unknown committed
573
  bool init_save_join_tab();
574 575 576
  bool send_row_on_empty_set()
  {
    return (do_send_rows && tmp_table_param.sum_func_count != 0 &&
577
	    !group_list && having_value != Item::COND_FALSE);
578
  }
unknown's avatar
unknown committed
579
  bool change_result(select_result *result);
580 581 582 583 584
  bool is_top_level_join() const
  {
    return (unit == &thd->lex->unit && (unit->fake_select_lex == 0 ||
                                        select_lex == unit->fake_select_lex));
  }
Sergey Petrunya's avatar
Sergey Petrunya committed
585 586 587 588
  inline table_map all_tables_map()
  {
    return (table_map(1) << tables) - 1;
  }
589
private:
590 591 592 593 594
  /**
    TRUE if the query contains an aggregate function but has no GROUP
    BY clause. 
  */
  bool implicit_grouping; 
595
  bool make_simple_join(JOIN *join, TABLE *tmp_table);
unknown's avatar
unknown committed
596 597 598 599 600 601 602 603 604 605 606
};


typedef struct st_select_check {
  uint const_ref,reg_ref;
} SELECT_CHECK;

extern const char *join_type_str[];
void TEST_join(JOIN *join);

/* Extern functions in sql_select.cc */
unknown's avatar
unknown committed
607
bool store_val_in_field(Field *field, Item *val, enum_check_fields check_flag);
unknown's avatar
unknown committed
608 609
TABLE *create_tmp_table(THD *thd,TMP_TABLE_PARAM *param,List<Item> &fields,
			ORDER *group, bool distinct, bool save_sum_fields,
610
			ulonglong select_options, ha_rows rows_limit,
611
			char* alias);
unknown's avatar
unknown committed
612
void free_tmp_table(THD *thd, TABLE *entry);
613 614
void count_field_types(SELECT_LEX *select_lex, TMP_TABLE_PARAM *param, 
                       List<Item> &fields, bool reset_with_sum_func);
615 616 617 618
bool setup_copy_fields(THD *thd, TMP_TABLE_PARAM *param,
		       Item **ref_pointer_array,
		       List<Item> &new_list1, List<Item> &new_list2,
		       uint elements, List<Item> &fields);
unknown's avatar
unknown committed
619
void copy_fields(TMP_TABLE_PARAM *param);
unknown's avatar
unknown committed
620
void copy_funcs(Item **func_ptr);
621
bool create_internal_tmp_table_from_heap(THD *thd, TABLE *table, TMP_TABLE_PARAM *param,
unknown's avatar
unknown committed
622
			     int error, bool ignore_last_dupp_error);
unknown's avatar
unknown committed
623
uint find_shortest_key(TABLE *table, const key_map *usable_keys);
624
Field* create_tmp_field_from_field(THD *thd, Field* org_field,
unknown's avatar
unknown committed
625 626 627
                                   const char *name, TABLE *table,
                                   Item_field *item, uint convert_blob_length);
                                                                      
unknown's avatar
unknown committed
628
/* functions from opt_sum.cc */
629
bool simple_pred(Item_func *func_item, Item **args, bool *inv_order);
unknown's avatar
unknown committed
630 631
int opt_sum_query(TABLE_LIST *tables, List<Item> &all_fields,COND *conds);

632
/* from sql_delete.cc, used by opt_range.cc */
633
extern "C" int refpos_order_cmp(void* arg, const void *a,const void *b);
634

unknown's avatar
unknown committed
635
/** class to copying an field/item to a key struct */
unknown's avatar
unknown committed
636 637 638

class store_key :public Sql_alloc
{
639 640
public:
  bool null_key; /* TRUE <=> the value of the key has a null part */
unknown's avatar
unknown committed
641
  enum store_key_result { STORE_KEY_OK, STORE_KEY_FATAL, STORE_KEY_CONV };
642
  store_key(THD *thd, Field *field_arg, uchar *ptr, uchar *null, uint length)
643
    :null_key(0), null_ptr(null), err(0)
unknown's avatar
unknown committed
644
  {
645 646
    if (field_arg->type() == MYSQL_TYPE_BLOB
        || field_arg->type() == MYSQL_TYPE_GEOMETRY)
647
    {
648 649 650 651
      /* 
        Key segments are always packed with a 2 byte length prefix.
        See mi_rkey for details.
      */
652
      to_field= new Field_varstring(ptr, length, 2, null, 1, 
unknown's avatar
unknown committed
653 654 655
                                    Field::NONE, field_arg->field_name,
                                    field_arg->table->s, field_arg->charset());
      to_field->init(field_arg->table);
656
    }
unknown's avatar
unknown committed
657
    else
unknown's avatar
unknown committed
658
      to_field=field_arg->new_key_field(thd->mem_root, field_arg->table,
659
                                        ptr, null, 1);
unknown's avatar
unknown committed
660
  }
unknown's avatar
unknown committed
661
  virtual ~store_key() {}			/** Not actually needed */
unknown's avatar
unknown committed
662
  virtual const char *name() const=0;
663 664 665 666 667 668 669 670 671 672

  /**
    @brief sets ignore truncation warnings mode and calls the real copy method

    @details this function makes sure truncation warnings when preparing the
    key buffers don't end up as errors (because of an enclosing INSERT/UPDATE).
  */
  enum store_key_result copy()
  {
    enum store_key_result result;
673 674 675 676
    THD *thd= to_field->table->in_use;
    enum_check_fields saved_count_cuted_fields= thd->count_cuted_fields;
    ulong sql_mode= thd->variables.sql_mode;
    thd->variables.sql_mode&= ~(MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE);
677

678
    thd->count_cuted_fields= CHECK_FIELD_IGNORE;
679 680 681

    result= copy_inner();

682 683
    thd->count_cuted_fields= saved_count_cuted_fields;
    thd->variables.sql_mode= sql_mode;
684 685 686 687 688 689

    return result;
  }

 protected:
  Field *to_field;				// Store data here
690 691
  uchar *null_ptr;
  uchar err;
692 693

  virtual enum store_key_result copy_inner()=0;
unknown's avatar
unknown committed
694 695 696 697 698 699 700 701
};


class store_key_field: public store_key
{
  Copy_field copy_field;
  const char *field_name;
 public:
702 703
  store_key_field(THD *thd, Field *to_field_arg, uchar *ptr,
                  uchar *null_ptr_arg,
unknown's avatar
unknown committed
704
		  uint length, Field *from_field, const char *name_arg)
unknown's avatar
unknown committed
705
    :store_key(thd, to_field_arg,ptr,
unknown's avatar
unknown committed
706
	       null_ptr_arg ? null_ptr_arg : from_field->maybe_null() ? &err
707
	       : (uchar*) 0, length), field_name(name_arg)
unknown's avatar
unknown committed
708 709 710 711 712 713
  {
    if (to_field)
    {
      copy_field.set(to_field,from_field,0);
    }
  }
714 715 716 717
  const char *name() const { return field_name; }

 protected: 
  enum store_key_result copy_inner()
718
  {
719 720 721
    TABLE *table= copy_field.to_field->table;
    my_bitmap_map *old_map= dbug_tmp_use_all_columns(table,
                                                     table->write_set);
722
    copy_field.do_copy(&copy_field);
723
    dbug_tmp_restore_column_map(table->write_set, old_map);
724
    null_key= to_field->is_null();
unknown's avatar
unknown committed
725
    return err != 0 ? STORE_KEY_FATAL : STORE_KEY_OK;
726
  }
unknown's avatar
unknown committed
727 728 729 730 731 732 733 734
};


class store_key_item :public store_key
{
 protected:
  Item *item;
public:
735 736 737
  store_key_item(THD *thd, Field *to_field_arg, uchar *ptr,
                 uchar *null_ptr_arg, uint length, Item *item_arg)
    :store_key(thd, to_field_arg, ptr,
unknown's avatar
unknown committed
738
	       null_ptr_arg ? null_ptr_arg : item_arg->maybe_null ?
739
	       &err : (uchar*) 0, length), item(item_arg)
unknown's avatar
unknown committed
740
  {}
741 742 743 744
  const char *name() const { return "func"; }

 protected:  
  enum store_key_result copy_inner()
unknown's avatar
unknown committed
745
  {
746 747 748
    TABLE *table= to_field->table;
    my_bitmap_map *old_map= dbug_tmp_use_all_columns(table,
                                                     table->write_set);
unknown's avatar
unknown committed
749
    int res= item->save_in_field(to_field, 1);
750 751 752 753 754
    /*
     Item::save_in_field() may call Item::val_xxx(). And if this is a subquery
     we need to check for errors executing it and react accordingly
    */
    if (!res && table->in_use->is_error())
755
      res= 1; /* STORE_KEY_FATAL */
756
    dbug_tmp_restore_column_map(table->write_set, old_map);
757
    null_key= to_field->is_null() || item->null_value;
758 759
    return ((err != 0 || res < 0 || res > 2) ? STORE_KEY_FATAL : 
            (store_key_result) res);
unknown's avatar
unknown committed
760 761 762 763 764 765 766 767
  }
};


class store_key_const_item :public store_key_item
{
  bool inited;
public:
768 769
  store_key_const_item(THD *thd, Field *to_field_arg, uchar *ptr,
		       uchar *null_ptr_arg, uint length,
unknown's avatar
unknown committed
770
		       Item *item_arg)
unknown's avatar
unknown committed
771
    :store_key_item(thd, to_field_arg,ptr,
unknown's avatar
unknown committed
772
		    null_ptr_arg ? null_ptr_arg : item_arg->maybe_null ?
773
		    &err : (uchar*) 0, length, item_arg), inited(0)
unknown's avatar
unknown committed
774 775
  {
  }
776 777 778 779
  const char *name() const { return "const"; }

protected:  
  enum store_key_result copy_inner()
unknown's avatar
unknown committed
780
  {
unknown's avatar
unknown committed
781
    int res;
unknown's avatar
unknown committed
782 783 784
    if (!inited)
    {
      inited=1;
unknown's avatar
unknown committed
785 786 787
      if ((res= item->save_in_field(to_field, 1)))
      {       
        if (!err)
788
          err= res < 0 ? 1 : res; /* 1=STORE_KEY_FATAL */
unknown's avatar
unknown committed
789
      }
790 791 792 793 794
      /*
        Item::save_in_field() may call Item::val_xxx(). And if this is a subquery
        we need to check for errors executing it and react accordingly
        */
      if (!err && to_field->table->in_use->is_error())
795
        err= 1; /* STORE_KEY_FATAL */
unknown's avatar
unknown committed
796
    }
797
    null_key= to_field->is_null() || item->null_value;
798
    return (err > 2 ? STORE_KEY_FATAL : (store_key_result) err);
unknown's avatar
unknown committed
799 800 801
  }
};

802
bool cp_buffer_from_ref(THD *thd, TABLE *table, TABLE_REF *ref);
unknown's avatar
unknown committed
803
bool error_if_full_join(JOIN *join);
804
int report_error(TABLE *table, int error);
805
int safe_index_read(JOIN_TAB *tab);
806
COND *remove_eq_conds(THD *thd, COND *cond, Item::cond_result *cond_value);
Sergey Petrunia's avatar
Sergey Petrunia committed
807
void set_position(JOIN *join,uint idx,JOIN_TAB *table,KEYUSE *key);
808 809 810 811 812 813

inline bool optimizer_flag(THD *thd, uint flag)
{ 
  return (thd->variables.optimizer_switch & flag);
}

Sergey Petrunya's avatar
Sergey Petrunya committed
814
void eliminate_tables(JOIN *join);
Sergey Petrunia's avatar
Sergey Petrunia committed
815