sql_select.cc 284 KB
Newer Older
1
/* Copyright (C) 2000-2004 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

   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
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   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.

   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 */


/* mysql_select and join optimization */

20
#ifdef USE_PRAGMA_IMPLEMENTATION
bk@work.mysql.com's avatar
bk@work.mysql.com committed
21 22
#pragma implementation				// gcc: Class implementation
#endif
23 24

#include "mysql_priv.h"
bk@work.mysql.com's avatar
bk@work.mysql.com committed
25
#include "sql_select.h"
sasha@mysql.sashanet.com's avatar
sasha@mysql.sashanet.com committed
26

bk@work.mysql.com's avatar
bk@work.mysql.com committed
27 28 29 30 31
#include <m_ctype.h>
#include <hash.h>
#include <ft_global.h>

const char *join_type_str[]={ "UNKNOWN","system","const","eq_ref","ref",
32
			      "MAYBE_REF","ALL","range","index","fulltext",
33
			      "ref_or_null","unique_subquery","index_subquery"
34
};
bk@work.mysql.com's avatar
bk@work.mysql.com committed
35

36
static void optimize_keyuse(JOIN *join, DYNAMIC_ARRAY *keyuse_array);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
37
static bool make_join_statistics(JOIN *join,TABLE_LIST *tables,COND *conds,
38
				 DYNAMIC_ARRAY *keyuse);
39 40
static bool update_ref_and_keys(THD *thd, DYNAMIC_ARRAY *keyuse,
				JOIN_TAB *join_tab,
41 42
                                uint tables, COND *conds,
				table_map table_map, SELECT_LEX *select_lex);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
43 44
static int sort_keyuse(KEYUSE *a,KEYUSE *b);
static void set_position(JOIN *join,uint index,JOIN_TAB *table,KEYUSE *key);
45 46
static bool create_ref_for_key(JOIN *join, JOIN_TAB *j, KEYUSE *org_keyuse,
			       table_map used_tables);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
47 48 49 50 51 52
static void find_best_combination(JOIN *join,table_map rest_tables);
static void find_best(JOIN *join,table_map rest_tables,uint index,
		      double record_count,double read_time);
static uint cache_record_length(JOIN *join,uint index);
static double prev_record_reads(JOIN *join,table_map found_ref);
static bool get_best_combination(JOIN *join);
53 54
static store_key *get_store_key(THD *thd,
				KEYUSE *keyuse, table_map used_tables,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
55 56 57 58 59
				KEY_PART_INFO *key_part, char *key_buff,
				uint maybe_null);
static bool make_simple_join(JOIN *join,TABLE *tmp_table);
static bool make_join_select(JOIN *join,SQL_SELECT *select,COND *item);
static void make_join_readinfo(JOIN *join,uint options);
60
static bool only_eq_ref_tables(JOIN *join, ORDER *order, table_map tables);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
61 62 63
static void update_depend_map(JOIN *join);
static void update_depend_map(JOIN *join, ORDER *order);
static ORDER *remove_const(JOIN *join,ORDER *first_order,COND *cond,
64
			   bool change_list, bool *simple_order);
65
static int return_zero_rows(JOIN *join, select_result *res,TABLE_LIST *tables,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
66 67
			    List<Item> &fields, bool send_row,
			    uint select_options, const char *info,
68 69
			    Item *having, Procedure *proc,
			    SELECT_LEX_UNIT *unit);
70 71 72 73
static COND *optimize_cond(THD *thd, COND *conds,
			   Item::cond_result *cond_value);
static COND *remove_eq_conds(THD *thd, COND *cond, 
			     Item::cond_result *cond_value);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
74 75 76
static bool const_expression_in_where(COND *conds,Item *item, Item **comp_item);
static bool open_tmp_table(TABLE *table);
static bool create_myisam_tmp_table(TABLE *table,TMP_TABLE_PARAM *param,
77
				    ulong options);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
78 79 80 81
static int do_select(JOIN *join,List<Item> *fields,TABLE *tmp_table,
		     Procedure *proc);
static int sub_select_cache(JOIN *join,JOIN_TAB *join_tab,bool end_of_records);
static int sub_select(JOIN *join,JOIN_TAB *join_tab,bool end_of_records);
82
static int flush_cached_records(JOIN *join,JOIN_TAB *join_tab,bool skip_last);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
83 84 85 86 87 88 89 90 91
static int end_send(JOIN *join, JOIN_TAB *join_tab, bool end_of_records);
static int end_send_group(JOIN *join, JOIN_TAB *join_tab,bool end_of_records);
static int end_write(JOIN *join, JOIN_TAB *join_tab, bool end_of_records);
static int end_update(JOIN *join, JOIN_TAB *join_tab, bool end_of_records);
static int end_unique_update(JOIN *join,JOIN_TAB *join_tab,
			     bool end_of_records);
static int end_write_group(JOIN *join, JOIN_TAB *join_tab,
			   bool end_of_records);
static int test_if_group_changed(List<Item_buff> &list);
92
static int join_read_const_table(JOIN_TAB *tab, POSITION *pos);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
93 94 95 96
static int join_read_system(JOIN_TAB *tab);
static int join_read_const(JOIN_TAB *tab);
static int join_read_key(JOIN_TAB *tab);
static int join_read_always_key(JOIN_TAB *tab);
97
static int join_read_last_key(JOIN_TAB *tab);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
98 99 100 101 102
static int join_no_more_records(READ_RECORD *info);
static int join_read_next(READ_RECORD *info);
static int join_init_quick_read_record(JOIN_TAB *tab);
static int test_if_quick_select(JOIN_TAB *tab);
static int join_init_read_record(JOIN_TAB *tab);
103 104 105 106 107 108
static int join_read_first(JOIN_TAB *tab);
static int join_read_next(READ_RECORD *info);
static int join_read_next_same(READ_RECORD *info);
static int join_read_last(JOIN_TAB *tab);
static int join_read_prev_same(READ_RECORD *info);
static int join_read_prev(READ_RECORD *info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
109 110
static int join_ft_read_first(JOIN_TAB *tab);
static int join_ft_read_next(READ_RECORD *info);
111 112
static int join_read_always_key_or_null(JOIN_TAB *tab);
static int join_read_next_same_or_null(READ_RECORD *info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
113 114 115
static COND *make_cond_for_table(COND *cond,table_map table,
				 table_map used_table);
static Item* part_of_refkey(TABLE *form,Field *field);
serg@serg.mylan's avatar
serg@serg.mylan committed
116
static uint find_shortest_key(TABLE *table, const key_map *usable_keys);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
117
static bool test_if_skip_sort_order(JOIN_TAB *tab,ORDER *order,
118
				    ha_rows select_limit, bool no_changes);
119
static int create_sort_index(THD *thd, JOIN *join, ORDER *order,
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
120
			     ha_rows filesort_limit, ha_rows select_limit);
121 122
static int remove_duplicates(JOIN *join,TABLE *entry,List<Item> &fields,
			     Item *having);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
123
static int remove_dup_with_compare(THD *thd, TABLE *entry, Field **field,
124
				   ulong offset,Item *having);
125
static int remove_dup_with_hash_index(THD *thd,TABLE *table,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
126
				      uint field_count, Field **first_field,
127
				      ulong key_length,Item *having);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
128 129 130
static int join_init_cache(THD *thd,JOIN_TAB *tables,uint table_count);
static ulong used_blob_length(CACHE_FIELD **ptr);
static bool store_record_in_cache(JOIN_CACHE *cache);
131 132
static void reset_cache_read(JOIN_CACHE *cache);
static void reset_cache_write(JOIN_CACHE *cache);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
133 134 135 136
static void read_cached_record(JOIN_TAB *tab);
static bool cmp_buffer_with_ref(JOIN_TAB *tab);
static bool setup_new_fields(THD *thd,TABLE_LIST *tables,List<Item> &fields,
			     List<Item> &all_fields,ORDER *new_order);
137 138 139
static ORDER *create_distinct_group(THD *thd, ORDER *order,
				    List<Item> &fields,
				    bool *all_order_by_fields_used);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
140 141 142
static bool test_if_subpart(ORDER *a,ORDER *b);
static TABLE *get_sort_by_table(ORDER *a,ORDER *b,TABLE_LIST *tables);
static void calc_group_buffer(JOIN *join,ORDER *group);
143
static bool make_group_fields(JOIN *main_join, JOIN *curr_join);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
144
static bool alloc_group_fields(JOIN *join,ORDER *group);
145
// Create list for using with tempory table
146
static bool change_to_use_tmp_fields(THD *thd, Item **ref_pointer_array,
147 148 149 150 151 152 153 154
				     List<Item> &new_list1,
				     List<Item> &new_list2,
				     uint elements, List<Item> &items);
// Create list for using with tempory table
static bool change_refs_to_tmp_fields(THD *thd, Item **ref_pointer_array,
				      List<Item> &new_list1,
				      List<Item> &new_list2,
				      uint elements, List<Item> &items);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
155 156
static void init_tmptable_sum_functions(Item_sum **func);
static void update_tmptable_sum_func(Item_sum **func,TABLE *tmp_table);
157
static void copy_sum_funcs(Item_sum **func_ptr, Item_sum **end);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
158
static bool add_ref_to_table_cond(THD *thd, JOIN_TAB *join_tab);
159
static bool init_sum_functions(Item_sum **func, Item_sum **end);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
160
static bool update_sum_func(Item_sum **func);
161
static void select_describe(JOIN *join, bool need_tmp_table,bool need_order,
162
			    bool distinct, const char *message=NullS);
163
static Item *remove_additional_cond(Item* conds);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
164

165

166 167 168 169 170 171 172 173
/*
  This handles SELECT with and without UNION
*/

int handle_select(THD *thd, LEX *lex, select_result *result)
{
  int res;
  register SELECT_LEX *select_lex = &lex->select_lex;
174 175
  DBUG_ENTER("handle_select");

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
176
  if (select_lex->next_select())
177
    res=mysql_union(thd, lex, result, &lex->unit);
178
  else
179 180 181 182 183 184 185 186 187 188 189
    res= mysql_select(thd, &select_lex->ref_pointer_array,
		      (TABLE_LIST*) select_lex->table_list.first,
		      select_lex->with_wild, select_lex->item_list,
		      select_lex->where,
		      select_lex->order_list.elements +
		      select_lex->group_list.elements,
		      (ORDER*) select_lex->order_list.first,
		      (ORDER*) select_lex->group_list.first,
		      select_lex->having,
		      (ORDER*) lex->proc_list.first,
		      select_lex->options | thd->options,
190
		      result, &(lex->unit), &(lex->select_lex));
191

192 193 194
  /* Don't set res if it's -1 as we may want this later */
  DBUG_PRINT("info",("res: %d  report_error: %d", res,
		     thd->net.report_error));
195
  if (thd->net.report_error || res<0)
196
  {
197 198
    result->send_error(0, NullS);
    result->abort();
199
    res= 1;					// Error sent to client
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
200
  }
201
  DBUG_RETURN(res);
202 203
}

204

205
/*
206
  Function to setup clauses without sum functions
207
*/
208 209
inline int setup_without_group(THD *thd, Item **ref_pointer_array,
			       TABLE_LIST *tables,
210 211 212 213 214 215
			       List<Item> &fields,
			       List<Item> &all_fields,
			       COND **conds,
			       ORDER *order,
			       ORDER *group, bool *hidden_group_fields)
{
monty@mysql.com's avatar
monty@mysql.com committed
216 217 218 219 220
  bool save_allow_sum_func;
  int res;
  DBUG_ENTER("setup_without_group");

  save_allow_sum_func= thd->allow_sum_func;
221
  thd->allow_sum_func= 0;
monty@mysql.com's avatar
monty@mysql.com committed
222 223 224 225 226
  res= (setup_conds(thd, tables, conds) ||
        setup_order(thd, ref_pointer_array, tables, fields, all_fields,
                    order) ||
        setup_group(thd, ref_pointer_array, tables, fields, all_fields,
                    group, hidden_group_fields));
227
  thd->allow_sum_func= save_allow_sum_func;
monty@mysql.com's avatar
monty@mysql.com committed
228
  DBUG_RETURN(res);
229 230
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
231
/*****************************************************************************
232 233
  Check fields, find best join, do the select and output fields.
  mysql_select assumes that all tables are already opened
bk@work.mysql.com's avatar
bk@work.mysql.com committed
234 235
*****************************************************************************/

236
/*
monty@mysql.com's avatar
monty@mysql.com committed
237
  Prepare of whole select (including sub queries in future).
238 239 240
  return -1 on error
          0 on success
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
241
int
242 243 244 245
JOIN::prepare(Item ***rref_pointer_array,
	      TABLE_LIST *tables_init,
	      uint wild_num, COND *conds_init, uint og_num,
	      ORDER *order_init, ORDER *group_init,
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
246
	      Item *having_init,
247 248
	      ORDER *proc_param_init, SELECT_LEX *select_lex_arg,
	      SELECT_LEX_UNIT *unit_arg)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
249
{
250
  DBUG_ENTER("JOIN::prepare");
251

252 253 254 255
  // to prevent double initialization on EXPLAIN
  if (optimized)
    DBUG_RETURN(0);

256 257 258 259 260 261
  conds= conds_init;
  order= order_init;
  group_list= group_init;
  having= having_init;
  proc_param= proc_param_init;
  tables_list= tables_init;
262
  select_lex= select_lex_arg;
263
  select_lex->join= this;
264
  union_part= (unit_arg->first_select()->next_select() != 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
265 266 267

  /* Check that all tables, fields, conds and order are ok */

268
  if (setup_tables(tables_list) ||
269
      setup_wild(thd, tables_list, fields_list, &all_fields, wild_num) ||
bell@laptop.sanja.is.com.ua's avatar
bell@laptop.sanja.is.com.ua committed
270
      select_lex->setup_ref_array(thd, og_num) ||
271 272 273 274 275
      setup_fields(thd, (*rref_pointer_array), tables_list, fields_list, 1,
		   &all_fields, 1) ||
      setup_without_group(thd, (*rref_pointer_array), tables_list, fields_list,
			  all_fields, &conds, order, group_list, 
			  &hidden_group_fields))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
276 277
    DBUG_RETURN(-1);				/* purecov: inspected */

278
  ref_pointer_array= *rref_pointer_array;
279
  
bk@work.mysql.com's avatar
bk@work.mysql.com committed
280 281 282 283
  if (having)
  {
    thd->where="having clause";
    thd->allow_sum_func=1;
284
    select_lex->having_fix_field= 1;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
285 286 287
    bool having_fix_rc= (!having->fixed &&
			 (having->fix_fields(thd, tables_list, &having) ||
			  having->check_cols(1)));
288
    select_lex->having_fix_field= 0;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
289
    if (having_fix_rc || thd->net.report_error)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
290 291
      DBUG_RETURN(-1);				/* purecov: inspected */
    if (having->with_sum_func)
292
      having->split_sum_func(thd, ref_pointer_array, all_fields);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
293
  }
294

295 296 297
  // Is it subselect
  {
    Item_subselect *subselect;
298
    if ((subselect= select_lex->master_unit()->item))
299 300
    {
      Item_subselect::trans_res res;
301
      if ((res= subselect->select_transformer(this)) !=
302 303
	  Item_subselect::RES_OK)
	DBUG_RETURN((res == Item_subselect::RES_ERROR));
304 305 306
    }
  }

307
  if (setup_ftfuncs(select_lex)) /* should be after having->fix_fields */
serg@serg.mysql.com's avatar
serg@serg.mysql.com committed
308
    DBUG_RETURN(-1);
309 310
  

bk@work.mysql.com's avatar
bk@work.mysql.com committed
311 312 313 314 315
  /*
    Check if one one uses a not constant column with group functions
    and no GROUP BY.
    TODO:  Add check of calculation of GROUP functions and fields:
	   SELECT COUNT(*)+table.col1 from table1;
316
  */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
317
  {
318
    if (!group_list)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
319 320
    {
      uint flag=0;
321
      List_iterator_fast<Item> it(fields_list);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
322 323 324 325 326
      Item *item;
      while ((item= it++))
      {
	if (item->with_sum_func)
	  flag|=1;
327
	else if (!(flag & 2) && !item->const_during_execution())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
328 329 330 331 332 333 334 335
	  flag|=2;
      }
      if (flag == 3)
      {
	my_error(ER_MIX_OF_GROUP_FUNC_AND_FIELDS,MYF(0));
	DBUG_RETURN(-1);
      }
    }
336 337
    TABLE_LIST *table_ptr;
    for (table_ptr= tables_list ; table_ptr ; table_ptr= table_ptr->next)
338
      tables++;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
339
  }
340 341 342
  {
    /* Caclulate the number of groups */
    send_group_parts= 0;
343
    for (ORDER *group_tmp= group_list ; group_tmp ; group_tmp= group_tmp->next)
344 345 346
      send_group_parts++;
  }
  
347
  procedure= setup_procedure(thd, proc_param, result, fields_list, &error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
348
  if (error)
349
    goto err;					/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
350 351
  if (procedure)
  {
352 353
    if (setup_new_fields(thd, tables_list, fields_list, all_fields,
			 procedure->param_fields))
354
	goto err;				/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
355 356
    if (procedure->group)
    {
357
      if (!test_if_subpart(procedure->group,group_list))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
358 359 360
      {						/* purecov: inspected */
	my_message(0,"Can't handle procedures with differents groups yet",
		   MYF(0));			/* purecov: inspected */
361
	goto err;				/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
362 363 364
      }
    }
#ifdef NOT_NEEDED
365
    else if (!group_list && procedure->flags & PROC_GROUP)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
366 367
    {
      my_message(0,"Select must have a group with this procedure",MYF(0));
368
      goto err;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
369 370 371
    }
#endif
    if (order && (procedure->flags & PROC_NO_SORT))
372
    {						/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
373
      my_message(0,"Can't use order with this procedure",MYF(0)); /* purecov: inspected */
374
      goto err;					/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
375 376 377 378
    }
  }

  /* Init join struct */
379
  count_field_types(&tmp_table_param, all_fields, 0);
380
  ref_pointer_array_size= all_fields.elements*sizeof(Item*);
381 382
  this->group= group_list != 0;
  row_limit= ((select_distinct || order || group_list) ? HA_POS_ERROR :
383
	      unit_arg->select_limit_cnt);
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
384
  /* select_limit is used to decide if we are likely to scan the whole table */
385
  select_limit= unit_arg->select_limit_cnt;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
386 387
  if (having || (select_options & OPTION_FOUND_ROWS))
    select_limit= HA_POS_ERROR;
388 389
  do_send_rows = (unit_arg->select_limit_cnt) ? 1 : 0;
  unit= unit_arg;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
390 391

#ifdef RESTRICTED_GROUP
392
  if (sum_func_count && !group_list && (func_count || field_count))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
393
  {
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
394
    my_message(ER_WRONG_SUM_SELECT,ER(ER_WRONG_SUM_SELECT),MYF(0));
395
    goto err;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
396 397
  }
#endif
398 399 400 401 402 403 404 405 406 407
  /*
    We must not yet prepare the result table if it is the same as one of the 
    source tables (INSERT SELECT). This is checked in mysql_execute_command()
    and OPTION_BUFFER_RESULT is added to the select_options. A temporary 
    table is then used to hold the result. The preparation may disable 
    indexes on the result table, which may be used during the select, if it
    is the same table (Bug #6034). Do the preparation after the select phase.
  */
  if (! procedure && ! test(select_options & OPTION_BUFFER_RESULT) &&
      result && result->prepare(fields_list, unit_arg))
408 409 410 411 412 413 414
    goto err;					/* purecov: inspected */

  if (select_lex->olap == ROLLUP_TYPE && rollup_init())
    goto err;
  if (alloc_func_list())
    goto err;

415
  DBUG_RETURN(0); // All OK
416 417 418 419 420

err:
  delete procedure;				/* purecov: inspected */
  procedure= 0;
  DBUG_RETURN(-1);				/* purecov: inspected */
421
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
422

423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
/*
  test if it is known for optimisation IN subquery

  SYNOPSYS
    JOIN::test_in_subselect
    where - pointer for variable in which conditions should be
            stored if subquery is known

  RETURN
    1 - known
    0 - unknown
*/

bool JOIN::test_in_subselect(Item **where)
{
  if (conds->type() == Item::FUNC_ITEM &&
439
      ((Item_func *)this->conds)->functype() == Item_func::EQ_FUNC &&
440 441 442 443 444 445 446 447 448 449 450
      ((Item_func *)conds)->arguments()[0]->type() == Item::REF_ITEM &&
      ((Item_func *)conds)->arguments()[1]->type() == Item::FIELD_ITEM)
  {
    join_tab->info= "Using index";
    *where= 0;
    return 1;
  }
  if (conds->type() == Item::COND_ITEM &&
      ((class Item_func *)this->conds)->functype() ==
      Item_func::COND_AND_FUNC)
  {
451 452 453 454
    if ((*where= remove_additional_cond(conds)))
      join_tab->info= "Using index; Using where";
    else
      join_tab->info= "Using index";
455 456 457 458 459 460
    return 1;
  }
  return 0;
}


461 462 463
/*
  global select optimisation.
  return 0 - success
464
         1 - error
465 466 467 468 469 470
  error code saved in field 'error'
*/
int
JOIN::optimize()
{
  DBUG_ENTER("JOIN::optimize");
471
  // to prevent double initialization on EXPLAIN
472 473 474
  if (optimized)
    DBUG_RETURN(0);
  optimized= 1;
475

476
  // Ignore errors of execution if option IGNORE present
477
  if (thd->lex->ignore)
478
    thd->lex->current_select->no_error= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
479 480
#ifdef HAVE_REF_TO_FIELDS			// Not done yet
  /* Add HAVING to WHERE if possible */
481
  if (having && !group_list && !sum_func_count)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
482 483 484
  {
    if (!conds)
    {
485 486
      conds= having;
      having= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
487 488 489
    }
    else if ((conds=new Item_cond_and(conds,having)))
    {
490
      conds->fix_fields(thd, tables_list, &conds);
491
      conds->change_ref_to_fields(thd, tables_list);
492
      conds->top_level_item();
493
      having= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
494 495 496 497
    }
  }
#endif

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
498
  conds= optimize_cond(thd, conds, &cond_value);
499
  if (thd->net.report_error)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
500
  {
serg@serg.mylan's avatar
serg@serg.mylan committed
501
    error= 1;
502
    DBUG_PRINT("error",("Error from optimize_cond"));
503
    DBUG_RETURN(1);
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
504
  }
505

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
506 507
  if (cond_value == Item::COND_FALSE ||
      (!unit->select_limit_cnt && !(select_options & OPTION_FOUND_ROWS)))
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
508
  {						/* Impossible cond */
509
    zero_result_cause= "Impossible WHERE";
510
    error= 0;
511
    DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
512 513 514
  }

  /* Optimize count(*), min() and max() */
515
  if (tables_list && tmp_table_param.sum_func_count && ! group_list)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
516 517
  {
    int res;
518
    /*
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
519 520
      opt_sum_query() returns -1 if no rows match to the WHERE conditions,
      or 1 if all items were resolved, or 0, or an error number HA_ERR_...
521
    */
522
    if ((res=opt_sum_query(tables_list, all_fields, conds)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
523
    {
524 525
      if (res > 1)
      {
526
	DBUG_RETURN(1);
527
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
528 529
      if (res < 0)
      {
530
	zero_result_cause= "No matching min/max row";
serg@serg.mylan's avatar
serg@serg.mylan committed
531
	error=0;
532
	DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
533
      }
534
      zero_result_cause= "Select tables optimized away";
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
535
      tables_list= 0;				// All tables resolved
bk@work.mysql.com's avatar
bk@work.mysql.com committed
536 537
    }
  }
538
  if (!tables_list)
539 540
  {
    error= 0;
541
    DBUG_RETURN(0);
542
  }
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
543
  error= -1;					// Error is sent to client
544
  sort_by_table= get_sort_by_table(order, group_list, tables_list);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
545 546

  /* Calculate how to do the join */
547 548
  thd->proc_info= "statistics";
  if (make_join_statistics(this, tables_list, conds, &keyuse) ||
549
      thd->is_fatal_error)
550 551
  {
    DBUG_PRINT("error",("Error: make_join_statistics() failed"));
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
552
    DBUG_RETURN(1);
553
  }
554

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
555 556
  /* Remove distinct if only const tables */
  select_distinct= select_distinct && (const_tables != tables);
557
  thd->proc_info= "preparing";
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
558
  if (result->initialize_tables(this))
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
559
  {
560 561
    DBUG_PRINT("error",("Error: initialize_tables() failed"));
    DBUG_RETURN(1);				// error == -1
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
562
  }
563
  if (const_table_map != found_const_table_map &&
564
      !(select_options & SELECT_DESCRIBE) &&
565 566 567
      (!conds ||
       !(conds->used_tables() & RAND_TABLE_BIT) ||
       select_lex->master_unit() == &thd->lex->unit)) // upper level SELECT
bk@work.mysql.com's avatar
bk@work.mysql.com committed
568
  {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
569
    zero_result_cause= "no matching row in const table";
570 571
    DBUG_PRINT("error",("Error: %s", zero_result_cause));
    error= 0;
572
    DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
573 574
  }
  if (!(thd->options & OPTION_BIG_SELECTS) &&
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
575
      best_read > (double) thd->variables.max_join_size &&
bk@work.mysql.com's avatar
bk@work.mysql.com committed
576 577
      !(select_options & SELECT_DESCRIBE))
  {						/* purecov: inspected */
578
    my_message(ER_TOO_BIG_SELECT, ER(ER_TOO_BIG_SELECT), MYF(0));
579
    error= -1;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
580
    DBUG_RETURN(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
581
  }
582
  if (const_tables && !thd->locked_tables &&
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
583
      !(select_options & SELECT_NO_UNLOCK))
584
    mysql_unlock_some_tables(thd, table, const_tables);
585

586
  if (!conds && outer_join)
587 588 589 590
  {
    /* Handle the case where we have an OUTER JOIN without a WHERE */
    conds=new Item_int((longlong) 1,1);	// Always true
  }
591 592
  select=make_select(*table, const_table_map,
		     const_table_map, conds, &error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
593
  if (error)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
594 595
  {						/* purecov: inspected */
    error= -1;					/* purecov: inspected */
596
    DBUG_PRINT("error",("Error: make_select() failed"));
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
597
    DBUG_RETURN(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
598
  }
599
  if (make_join_select(this, select, conds))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
600
  {
601 602
    zero_result_cause=
      "Impossible WHERE noticed after reading const tables";
603
    DBUG_RETURN(0);				// error == 0
bk@work.mysql.com's avatar
bk@work.mysql.com committed
604 605 606 607 608
  }

  error= -1;					/* if goto err */

  /* Optimize distinct away if possible */
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
609 610
  {
    ORDER *org_order= order;
611
    order=remove_const(this, order,conds,1, &simple_order);
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
612 613 614 615 616 617 618
    /*
      If we are using ORDER BY NULL or ORDER BY const_expression,
      return result in any order (even if we are using a GROUP BY)
    */
    if (!order && org_order)
      skip_sort_order= 1;
  }
619
  if (group_list || tmp_table_param.sum_func_count)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
620 621 622 623
  {
    if (! hidden_group_fields)
      select_distinct=0;
  }
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
624
  else if (select_distinct && tables - const_tables == 1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
625
  {
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
    /*
      We are only using one table. In this case we change DISTINCT to a
      GROUP BY query if:
      - The GROUP BY can be done through indexes (no sort) and the ORDER
        BY only uses selected fields.
	(In this case we can later optimize away GROUP BY and ORDER BY)
      - We are scanning the whole table without LIMIT
        This can happen if:
        - We are using CALC_FOUND_ROWS
        - We are using an ORDER BY that can't be optimized away.

      We don't want to use this optimization when we are using LIMIT
      because in this case we can just create a temporary table that
      holds LIMIT rows and stop when this table is full.
    */
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
641
    JOIN_TAB *tab= &join_tab[const_tables];
642 643 644
    bool all_order_fields_used;
    if (order)
      skip_sort_order= test_if_skip_sort_order(tab, order, select_limit, 1);
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
645 646
    if ((group_list=create_distinct_group(thd, order, fields_list,
				          &all_order_fields_used)))
647 648
    {
      bool skip_group= (skip_sort_order &&
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
649
			test_if_skip_sort_order(tab, group_list, select_limit,
650 651 652 653 654 655 656 657 658
						1) != 0);
      if ((skip_group && all_order_fields_used) ||
	  select_limit == HA_POS_ERROR ||
	  (order && !skip_sort_order))
      {
	/*  Change DISTINCT to GROUP BY */
	select_distinct= 0;
	no_order= !order;
	if (all_order_fields_used)
659 660 661 662 663 664
	{
	  if (order && skip_sort_order)
	  {
	    /*
	      Force MySQL to read the table in sorted order to get result in
	      ORDER BY order.
serg@serg.mylan's avatar
serg@serg.mylan committed
665
	    */
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
666
	    tmp_table_param.quick_group=0;
667
	  }
668
	  order=0;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
669
        }
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
670
	group=1;				// For end_write_group
671 672
      }
      else
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
673
	group_list= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
674
    }
675
    else if (thd->is_fatal_error)			// End of memory
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
676
      DBUG_RETURN(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
677
  }
678
  simple_group= 0;
679 680 681
  group_list= remove_const(this, group_list, conds,
                           rollup.state == ROLLUP::STATE_NONE,
                           &simple_group);
682
  if (!group_list && group)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
683 684 685 686 687
  {
    order=0;					// The output has only one row
    simple_order=1;
  }

688 689
  calc_group_buffer(this, group_list);
  send_group_parts= tmp_table_param.group_parts; /* Save org parts */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
690 691
  if (procedure && procedure->group)
  {
692
    group_list= procedure->group= remove_const(this, procedure->group, conds,
693
					       1, &simple_group);
694
    calc_group_buffer(this, group_list);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
695 696
  }

697 698
  if (test_if_subpart(group_list, order) ||
      (!group_list && tmp_table_param.sum_func_count))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
699 700
    order=0;

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
701
  // Can't use sort on head table if using row cache
702
  if (full_join)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
703
  {
704
    if (group_list)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
705 706 707 708 709
      simple_group=0;
    if (order)
      simple_order=0;
  }

710 711 712 713 714 715 716 717 718
  /*
    Check if we need to create a temporary table.
    This has to be done if all tables are not already read (const tables)
    and one of the following conditions holds:
    - We are using DISTINCT (simple distinct's are already optimized away)
    - We are using an ORDER BY or GROUP BY on fields not in the first table
    - We are using different ORDER BY and GROUP BY orders
    - The user wants us to buffer the result.
  */
719
  need_tmp= (const_tables != tables &&
bk@work.mysql.com's avatar
bk@work.mysql.com committed
720
	     ((select_distinct || !simple_order || !simple_group) ||
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
721
	      (group_list && order) ||
722
	      test(select_options & OPTION_BUFFER_RESULT)));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
723

724
  // No cache for MATCH
725
  make_join_readinfo(this,
726
		     (select_options & (SELECT_DESCRIBE |
727
					SELECT_NO_JOIN_CACHE)) |
serg@serg.mylan's avatar
serg@serg.mylan committed
728
		     (select_lex->ftfunc_list->elements ?
729
		      SELECT_NO_JOIN_CACHE : 0));
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
730

731 732 733 734
  /* Perform FULLTEXT search before all regular searches */
  if (!(select_options & SELECT_DESCRIBE))
    init_ftfuncs(thd, select_lex, test(order));

735 736 737
  /*
    is this simple IN subquery?
  */
738
  if (!group_list && !order &&
739
      unit->item && unit->item->substype() == Item_subselect::IN_SUBS &&
740
      tables == 1 && conds &&
741 742
      !unit->first_select()->next_select())
  {
743
    if (!having)
744
    {
745
      Item *where= 0;
746 747
      if (join_tab[0].type == JT_EQ_REF &&
	  join_tab[0].ref.items[0]->name == in_left_expr_name)
748
      {
749 750
	if (test_in_subselect(&where))
	{
751
	  join_tab[0].type= JT_UNIQUE_SUBQUERY;
752 753
	  error= 0;
	  DBUG_RETURN(unit->item->
754 755 756 757 758
		      change_engine(new
				    subselect_uniquesubquery_engine(thd,
								    join_tab,
								    unit->item,
								    where)));
759
	}
760
      }
761 762
      else if (join_tab[0].type == JT_REF &&
	       join_tab[0].ref.items[0]->name == in_left_expr_name)
763
      {
764 765
	if (test_in_subselect(&where))
	{
766
	  join_tab[0].type= JT_INDEX_SUBQUERY;
767 768
	  error= 0;
	  DBUG_RETURN(unit->item->
769 770 771 772 773 774
		      change_engine(new
				    subselect_indexsubquery_engine(thd,
								   join_tab,
								   unit->item,
								   where,
								   0)));
775
	}
776
      }
777
    } else if (join_tab[0].type == JT_REF_OR_NULL &&
778
	       join_tab[0].ref.items[0]->name == in_left_expr_name &&
779 780 781 782
	       having->type() == Item::FUNC_ITEM &&
	       ((Item_func *) having)->functype() ==
	       Item_func::ISNOTNULLTEST_FUNC)
    {
783
      join_tab[0].type= JT_INDEX_SUBQUERY;
784
      error= 0;
785 786 787 788 789

      if ((conds= remove_additional_cond(conds)))
	join_tab->info= "Using index; Using where";
      else
	join_tab->info= "Using index";
790

791
      DBUG_RETURN(unit->item->
792 793 794 795 796
		  change_engine(new subselect_indexsubquery_engine(thd,
								   join_tab,
								   unit->item,
								   conds,
								   1)));
797
    }
798

799
  }
800 801 802 803 804 805 806
  /*
    Need to tell Innobase that to play it safe, it should fetch all
    columns of the tables: this is because MySQL may build row
    pointers for the rows, and for all columns of the primary key the
    field->query_id has not necessarily been set to thd->query_id by
    MySQL.
  */
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
807 808

#ifdef HAVE_INNOBASE_DB
809
  if (need_tmp || select_distinct || group_list || order)
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
810
  {
811
    for (uint i_h = const_tables; i_h < tables; i_h++)
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
812
    {
813
      TABLE* table_h = join_tab[i_h].table;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
814
      table_h->file->extra(HA_EXTRA_RETRIEVE_PRIMARY_KEY);
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
815 816 817 818
    }
  }
#endif

819
  DBUG_EXECUTE("info",TEST_join(this););
bk@work.mysql.com's avatar
bk@work.mysql.com committed
820 821 822 823 824
  /*
    Because filesort always does a full table scan or a quick range scan
    we must add the removed reference to the select for the table.
    We only need to do this when we have a simple_order or simple_group
    as in other cases the join is done before the sort.
825
  */
826
  if (const_tables != tables &&
827
      (order || group_list) &&
828
      join_tab[const_tables].type != JT_ALL &&
829
      join_tab[const_tables].type != JT_FT &&
830
      join_tab[const_tables].type != JT_REF_OR_NULL &&
831
      (order && simple_order || group_list && simple_group))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
832
  {
833
    if (add_ref_to_table_cond(thd,&join_tab[const_tables]))
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
834
      DBUG_RETURN(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
835 836 837
  }

  if (!(select_options & SELECT_BIG_RESULT) &&
838
      ((group_list && const_tables != tables &&
839
	(!simple_group ||
840
	 !test_if_skip_sort_order(&join_tab[const_tables], group_list,
monty@mysql.com's avatar
monty@mysql.com committed
841 842
				  unit->select_limit_cnt, 0))) ||
       select_distinct) &&
843
      tmp_table_param.quick_group && !procedure)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
844 845 846
  {
    need_tmp=1; simple_order=simple_group=0;	// Force tmp table without sort
  }
847

848
  tmp_having= having;
849
  if (select_options & SELECT_DESCRIBE)
850 851
  {
    error= 0;
852
    DBUG_RETURN(0);
853
  }
854 855 856 857 858 859 860 861 862
  having= 0;

  /* Create a tmp table if distinct or if the sort is too complicated */
  if (need_tmp)
  {
    DBUG_PRINT("info",("Creating tmp table"));
    thd->proc_info="Creating tmp table";

    init_items_ref_array();
863

864 865 866 867 868 869 870 871 872 873 874
    tmp_table_param.hidden_field_count= (all_fields.elements -
					 fields_list.elements);
    if (!(exec_tmp_table1 =
	  create_tmp_table(thd, &tmp_table_param, all_fields,
			   ((!simple_group && !procedure &&
			     !(test_flags & TEST_NO_KEY_GROUP)) ?
			    group_list : (ORDER*) 0),
			   group_list ? 0 : select_distinct,
			   group_list && simple_group,
			   select_options,
			   (order == 0 || skip_sort_order) ? select_limit :
875 876
			   HA_POS_ERROR,
			   (char *) "")))
877
      DBUG_RETURN(1);
878 879 880 881 882 883 884 885 886 887 888

    /*
      We don't have to store rows in temp table that doesn't match HAVING if:
      - we are sorting the table and writing complete group rows to the
        temp table.
      - We are using DISTINCT without resolving the distinct as a GROUP BY
        on all columns.
      
      If having is not handled here, it will be checked before the row
      is sent to the client.
    */    
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
889
    if (tmp_having && 
890 891 892 893 894 895 896 897
	(sort_and_group || (exec_tmp_table1->distinct && !group_list)))
      having= tmp_having;

    /* if group or order on first table, sort first */
    if (group_list && simple_group)
    {
      DBUG_PRINT("info",("Sorting for group"));
      thd->proc_info="Sorting for group";
898
      if (create_sort_index(thd, this, group_list,
899
			    HA_POS_ERROR, HA_POS_ERROR) ||
900 901
	  alloc_group_fields(this, group_list) ||
	  make_sum_func_list(all_fields, fields_list, 1))
902 903 904 905 906
	DBUG_RETURN(1);
      group_list=0;
    }
    else
    {
907
      if (make_sum_func_list(all_fields, fields_list, 0))
908 909 910 911 912
	DBUG_RETURN(1);
      if (!group_list && ! exec_tmp_table1->distinct && order && simple_order)
      {
	DBUG_PRINT("info",("Sorting for order"));
	thd->proc_info="Sorting for order";
913
	if (create_sort_index(thd, this, order,
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
                              HA_POS_ERROR, HA_POS_ERROR))
	  DBUG_RETURN(1);
	order=0;
      }
    }
    
    /*
      Optimize distinct when used on some of the tables
      SELECT DISTINCT t1.a FROM t1,t2 WHERE t1.b=t2.b
      In this case we can stop scanning t2 when we have found one t1.a
    */

    if (exec_tmp_table1->distinct)
    {
      table_map used_tables= thd->used_tables;
929
      JOIN_TAB *last_join_tab= join_tab+tables-1;
930 931
      do
      {
932
	if (used_tables & last_join_tab->table->map)
933
	  break;
934 935
	last_join_tab->not_used_in_distinct=1;
      } while (last_join_tab-- != join_tab);
936 937 938 939
      /* Optimize "select distinct b from t1 order by key_part_1 limit #" */
      if (order && skip_sort_order)
      {
 	/* Should always succeed */
940
	if (test_if_skip_sort_order(&join_tab[const_tables],
941 942 943 944 945
				    order, unit->select_limit_cnt, 0))
	  order=0;
      }
    }
    
946
    if (thd->lex->subqueries)
947 948 949
    {
      if (!(tmp_join= (JOIN*)thd->alloc(sizeof(JOIN))))
	DBUG_RETURN(-1);
950
      error= 0;				// Ensure that tmp_join.error= 0
951 952 953 954
      restore_tmp();
    }
  }

955
  error= 0;
956 957 958
  DBUG_RETURN(0);
}

959

960
/*
961
  Restore values in temporary join
962
*/
963
void JOIN::restore_tmp()
964
{
965
  memcpy(tmp_join, this, (size_t) sizeof(JOIN));
966 967
}

968

969 970 971 972
int
JOIN::reinit()
{
  DBUG_ENTER("JOIN::reinit");
973
  /* TODO move to unit reinit */
974 975 976 977 978 979
  unit->offset_limit_cnt =select_lex->offset_limit;
  unit->select_limit_cnt =select_lex->select_limit+select_lex->offset_limit;
  if (unit->select_limit_cnt < select_lex->select_limit)
    unit->select_limit_cnt= HA_POS_ERROR;		// no limit
  if (unit->select_limit_cnt == HA_POS_ERROR)
    select_lex->options&= ~OPTION_FOUND_ROWS;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
980
  
981
  if (setup_tables(tables_list))
982
    DBUG_RETURN(1);
983
  
984
  /* Reset of sum functions */
985
  first_record= 0;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
986

987 988 989 990 991
  if (exec_tmp_table1)
  {
    exec_tmp_table1->file->extra(HA_EXTRA_RESET_STATE);
    exec_tmp_table1->file->delete_all_rows();
    free_io_cache(exec_tmp_table1);
992
    filesort_free_buffers(exec_tmp_table1);
993 994 995 996 997 998
  }
  if (exec_tmp_table2)
  {
    exec_tmp_table2->file->extra(HA_EXTRA_RESET_STATE);
    exec_tmp_table2->file->delete_all_rows();
    free_io_cache(exec_tmp_table2);
999
    filesort_free_buffers(exec_tmp_table2);
1000 1001
  }
  if (items0)
1002
    set_items_ref_array(items0);
1003

1004 1005 1006
  if (join_tab_save)
    memcpy(join_tab, join_tab_save, sizeof(JOIN_TAB) * tables);

1007 1008 1009
  if (tmp_join)
    restore_tmp();

1010 1011 1012 1013 1014 1015 1016
  if (sum_funcs)
  {
    Item_sum *func, **func_ptr= sum_funcs;
    while ((func= *(func_ptr++)))
      func->clear();
  }

1017 1018 1019
  DBUG_RETURN(0);
}

1020 1021 1022 1023

bool
JOIN::save_join_tab()
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1024
  if (!join_tab_save && select_lex->master_unit()->uncacheable)
1025
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1026 1027
    if (!(join_tab_save= (JOIN_TAB*)thd->memdup((gptr) join_tab,
						sizeof(JOIN_TAB) * tables)))
1028 1029 1030 1031 1032 1033
      return 1;
  }
  return 0;
}


1034
/*
1035
  Exec select
1036 1037 1038 1039 1040 1041
*/
void
JOIN::exec()
{
  int      tmp_error;
  DBUG_ENTER("JOIN::exec");
1042
  
1043
  error= 0;
1044 1045 1046 1047
  if (procedure)
  {
    if (procedure->change_columns(fields_list) ||
	result->prepare(fields_list, unit))
1048 1049
    {
      thd->limit_found_rows= thd->examined_row_count= 0;
1050
      DBUG_VOID_RETURN;
1051
    }
1052
  }
1053 1054 1055 1056 1057 1058 1059
  else if (test(select_options & OPTION_BUFFER_RESULT) &&
           result && result->prepare(fields_list, unit))
  {
    error= 1;
    thd->limit_found_rows= thd->examined_row_count= 0;
    DBUG_VOID_RETURN;
  }
1060

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1061
  if (!tables_list)
1062 1063
  {                                           // Only test of functions
    if (select_options & SELECT_DESCRIBE)
monty@mysql.com's avatar
monty@mysql.com committed
1064
      select_describe(this, FALSE, FALSE, FALSE,
1065
		      (zero_result_cause?zero_result_cause:"No tables used"));
1066 1067 1068 1069 1070
    else
    {
      result->send_fields(fields_list,1);
      if (!having || having->val_int())
      {
1071 1072 1073
	if (do_send_rows && (procedure ? (procedure->send_row(fields_list) ||
                                          procedure->end_of_records())
                                       : result->send_data(fields_list)))
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1074
	  error= 1;
1075
	else
1076
	{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1077
	  error= (int) result->send_eof();
1078 1079
	  send_records=1;
	}
1080 1081
      }
      else
1082
	error=(int) result->send_eof();
1083
    }
1084 1085 1086
    /* Single select (without union and limit) always returns 1 row */
    thd->limit_found_rows= 1;
    thd->examined_row_count= 0;
1087 1088
    DBUG_VOID_RETURN;
  }
1089
  thd->limit_found_rows= thd->examined_row_count= 0;
1090 1091 1092

  if (zero_result_cause)
  {
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
1093
    (void) return_zero_rows(this, result, tables_list, fields_list,
1094
			    send_row_on_empty_set(),
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
1095 1096
			    select_options,
			    zero_result_cause,
1097
			    having, procedure,
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
1098
			    unit);
1099 1100 1101
    DBUG_VOID_RETURN;
  }

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1102 1103
  if (select_options & SELECT_DESCRIBE)
  {
monty@mysql.com's avatar
monty@mysql.com committed
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
    /*
      Check if we managed to optimize ORDER BY away and don't use temporary
      table to resolve ORDER BY: in that case, we only may need to do
      filesort for GROUP BY.
    */
    if (!order && !no_order && (!skip_sort_order || !need_tmp))
    {
      /*
	Reset 'order' to 'group_list' and reinit variables describing
	'order'
      */
      order= group_list;
      simple_order= simple_group;
      skip_sort_order= 0;
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1119
    if (order &&
1120
	(const_tables == tables ||
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1121
 	 ((simple_order || skip_sort_order) &&
1122
	  test_if_skip_sort_order(&join_tab[const_tables], order,
1123
				  select_limit, 0))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1124
      order=0;
1125
    having= tmp_having;
1126
    select_describe(this, need_tmp,
1127
		    order != 0 && !skip_sort_order,
monty@tramp.mysql.fi's avatar
monty@tramp.mysql.fi committed
1128
		    select_distinct);
1129
    DBUG_VOID_RETURN;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1130 1131
  }

1132 1133 1134 1135
  JOIN *curr_join= this;
  List<Item> *curr_all_fields= &all_fields;
  List<Item> *curr_fields_list= &fields_list;
  TABLE *curr_tmp_table= 0;
1136

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1137 1138 1139
  /* Create a tmp table if distinct or if the sort is too complicated */
  if (need_tmp)
  {
1140 1141 1142
    if (tmp_join)
      curr_join= tmp_join;
    curr_tmp_table= exec_tmp_table1;
monty@tramp.mysql.fi's avatar
monty@tramp.mysql.fi committed
1143 1144

    /* Copy data to the temporary table */
1145
    thd->proc_info= "Copying to tmp table";
1146 1147
    
    if ((tmp_error= do_select(curr_join, (List<Item> *) 0, curr_tmp_table, 0)))
1148
    {
1149 1150
      error= tmp_error;
      DBUG_VOID_RETURN;
1151
    }
1152 1153 1154 1155 1156
    curr_tmp_table->file->info(HA_STATUS_VARIABLE);
    
    if (curr_join->having)
      curr_join->having= curr_join->tmp_having= 0; // Allready done
    
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1157
    /* Change sum_fields reference to calculated fields in tmp_table */
1158 1159
    curr_join->all_fields= *curr_all_fields;
    if (!items1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1160
    {
1161 1162 1163
      items1= items0 + all_fields.elements;
      if (sort_and_group || curr_tmp_table->group)
      {
1164
	if (change_to_use_tmp_fields(thd, items1,
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
				     tmp_fields_list1, tmp_all_fields1,
				     fields_list.elements, all_fields))
	  DBUG_VOID_RETURN;
      }
      else
      {
	if (change_refs_to_tmp_fields(thd, items1,
				      tmp_fields_list1, tmp_all_fields1,
				      fields_list.elements, all_fields))
	  DBUG_VOID_RETURN;
      }
      curr_join->tmp_all_fields1= tmp_all_fields1;
      curr_join->tmp_fields_list1= tmp_fields_list1;
      curr_join->items1= items1;
    }
    curr_all_fields= &tmp_all_fields1;
    curr_fields_list= &tmp_fields_list1;
1182
    curr_join->set_items_ref_array(items1);
1183 1184 1185 1186 1187 1188 1189 1190
    
    if (sort_and_group || curr_tmp_table->group)
    {
      curr_join->tmp_table_param.field_count+= 
	curr_join->tmp_table_param.sum_func_count+
	curr_join->tmp_table_param.func_count;
      curr_join->tmp_table_param.sum_func_count= 
	curr_join->tmp_table_param.func_count= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1191 1192 1193
    }
    else
    {
1194 1195 1196
      curr_join->tmp_table_param.field_count+= 
	curr_join->tmp_table_param.func_count;
      curr_join->tmp_table_param.func_count= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1197
    }
1198 1199
    
    // procedure can't be used inside subselect => we do nothing special for it
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1200 1201
    if (procedure)
      procedure->update_refs();
1202 1203
    
    if (curr_tmp_table->group)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1204
    {						// Already grouped
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1205
      if (!curr_join->order && !curr_join->no_order && !skip_sort_order)
1206 1207
	curr_join->order= curr_join->group_list;  /* order by group */
      curr_join->group_list= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1208
    }
1209
    
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1210
    /*
1211 1212 1213 1214 1215
      If we have different sort & group then we must sort the data by group
      and copy it to another tmp table
      This code is also used if we are using distinct something
      we haven't been able to store in the temporary table yet
      like SEC_TO_TIME(SUM(...)).
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1216 1217
    */

1218 1219 1220 1221 1222
    if (curr_join->group_list && (!test_if_subpart(curr_join->group_list,
						   curr_join->order) || 
				  curr_join->select_distinct) ||
	(curr_join->select_distinct &&
	 curr_join->tmp_table_param.using_indirect_summary_function))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1223 1224
    {					/* Must copy to another table */
      DBUG_PRINT("info",("Creating group table"));
1225
      
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1226
      /* Free first data from old join */
1227
      curr_join->join_free(0);
1228
      if (make_simple_join(curr_join, curr_tmp_table))
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1229
	DBUG_VOID_RETURN;
1230
      calc_group_buffer(curr_join, group_list);
1231 1232
      count_field_types(&curr_join->tmp_table_param,
			curr_join->tmp_all_fields1,
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
			curr_join->select_distinct && !curr_join->group_list);
      curr_join->tmp_table_param.hidden_field_count= 
	(curr_join->tmp_all_fields1.elements-
	 curr_join->tmp_fields_list1.elements);
      
      
      if (exec_tmp_table2)
	curr_tmp_table= exec_tmp_table2;
      else
      {
	/* group data to new table */
	if (!(curr_tmp_table=
	      exec_tmp_table2= create_tmp_table(thd,
						&curr_join->tmp_table_param,
						*curr_all_fields,
						(ORDER*) 0,
						curr_join->select_distinct && 
						!curr_join->group_list,
						1, curr_join->select_options,
1252 1253
						HA_POS_ERROR,
						(char *) "")))
1254 1255 1256
	  DBUG_VOID_RETURN;
	curr_join->exec_tmp_table2= exec_tmp_table2;
      }
1257
      if (curr_join->group_list)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1258
      {
1259
	thd->proc_info= "Creating sort index";
1260 1261 1262 1263
	if (curr_join->join_tab == join_tab && save_join_tab())
	{
	  DBUG_VOID_RETURN;
	}
1264
	if (create_sort_index(thd, curr_join, curr_join->group_list,
1265
			      HA_POS_ERROR, HA_POS_ERROR) ||
1266
	    make_group_fields(this, curr_join))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1267
	{
1268
	  DBUG_VOID_RETURN;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1269 1270
	}
      }
1271
      
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1272
      thd->proc_info="Copying to group table";
1273
      tmp_error= -1;
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
      if (curr_join != this)
      {
	if (sum_funcs2)
	{
	  curr_join->sum_funcs= sum_funcs2;
	  curr_join->sum_funcs_end= sum_funcs_end2; 
	}
	else
	{
	  curr_join->alloc_func_list();
	  sum_funcs2= curr_join->sum_funcs;
	  sum_funcs_end2= curr_join->sum_funcs_end;
	}
      }
1288
      if (curr_join->make_sum_func_list(*curr_all_fields, *curr_fields_list,
1289 1290 1291 1292
					1))
        DBUG_VOID_RETURN;
      curr_join->group_list= 0;
      if ((tmp_error= do_select(curr_join, (List<Item> *) 0, curr_tmp_table,
1293
				0)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1294
      {
1295
	error= tmp_error;
1296
	DBUG_VOID_RETURN;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1297
      }
1298 1299 1300 1301 1302 1303 1304 1305
      end_read_record(&curr_join->join_tab->read_record);
      curr_join->const_tables= curr_join->tables; // Mark free for join_free()
      curr_join->join_tab[0].table= 0;           // Table is freed
      
      // No sum funcs anymore
      if (!items2)
      {
	items2= items1 + all_fields.elements;
1306
	if (change_to_use_tmp_fields(thd, items2,
1307 1308 1309 1310 1311 1312 1313 1314
				     tmp_fields_list2, tmp_all_fields2, 
				     fields_list.elements, tmp_all_fields1))
	  DBUG_VOID_RETURN;
	curr_join->tmp_fields_list2= tmp_fields_list2;
	curr_join->tmp_all_fields2= tmp_all_fields2;
      }
      curr_fields_list= &curr_join->tmp_fields_list2;
      curr_all_fields= &curr_join->tmp_all_fields2;
1315
      curr_join->set_items_ref_array(items2);
1316 1317 1318 1319 1320 1321 1322
      curr_join->tmp_table_param.field_count+= 
	curr_join->tmp_table_param.sum_func_count;
      curr_join->tmp_table_param.sum_func_count= 0;
    }
    if (curr_tmp_table->distinct)
      curr_join->select_distinct=0;		/* Each row is unique */
    
1323
    curr_join->join_free(0);			/* Free quick selects */
1324
    if (curr_join->select_distinct && ! curr_join->group_list)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1325 1326
    {
      thd->proc_info="Removing duplicates";
1327 1328 1329
      if (curr_join->tmp_having)
	curr_join->tmp_having->update_used_tables();
      if (remove_duplicates(curr_join, curr_tmp_table,
1330
			    *curr_fields_list, curr_join->tmp_having))
1331
	DBUG_VOID_RETURN;
1332 1333
      curr_join->tmp_having=0;
      curr_join->select_distinct=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1334
    }
1335 1336
    curr_tmp_table->reginfo.lock_type= TL_UNLOCK;
    if (make_simple_join(curr_join, curr_tmp_table))
1337
      DBUG_VOID_RETURN;
1338 1339 1340
    calc_group_buffer(curr_join, curr_join->group_list);
    count_field_types(&curr_join->tmp_table_param, *curr_all_fields, 0);
    
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1341 1342
  }
  if (procedure)
1343 1344 1345
    count_field_types(&curr_join->tmp_table_param, *curr_all_fields, 0);
  
  if (curr_join->group || curr_join->tmp_table_param.sum_func_count ||
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1346 1347
      (procedure && (procedure->flags & PROC_GROUP)))
  {
1348 1349 1350 1351
    if (make_group_fields(this, curr_join))
    {
      DBUG_VOID_RETURN;
    }
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
    if (!items3)
    {
      if (!items0)
	init_items_ref_array();
      items3= ref_pointer_array + (all_fields.elements*4);
      setup_copy_fields(thd, &curr_join->tmp_table_param,
			items3, tmp_fields_list3, tmp_all_fields3,
			curr_fields_list->elements, *curr_all_fields);
      tmp_table_param.save_copy_funcs= curr_join->tmp_table_param.copy_funcs;
      tmp_table_param.save_copy_field= curr_join->tmp_table_param.copy_field;
      tmp_table_param.save_copy_field_end=
	curr_join->tmp_table_param.copy_field_end;
      curr_join->tmp_all_fields3= tmp_all_fields3;
      curr_join->tmp_fields_list3= tmp_fields_list3;
    }
    else
    {
      curr_join->tmp_table_param.copy_funcs= tmp_table_param.save_copy_funcs;
      curr_join->tmp_table_param.copy_field= tmp_table_param.save_copy_field;
      curr_join->tmp_table_param.copy_field_end=
	tmp_table_param.save_copy_field_end;
    }
    curr_fields_list= &tmp_fields_list3;
    curr_all_fields= &tmp_all_fields3;
1376
    curr_join->set_items_ref_array(items3);
1377

1378 1379
    if (curr_join->make_sum_func_list(*curr_all_fields, *curr_fields_list,
				      1) || thd->is_fatal_error)
1380
      DBUG_VOID_RETURN;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1381
  }
1382
  if (curr_join->group_list || curr_join->order)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1383 1384 1385 1386
  {
    DBUG_PRINT("info",("Sorting for send_fields"));
    thd->proc_info="Sorting result";
    /* If we have already done the group, add HAVING to sorted table */
1387 1388
    if (curr_join->tmp_having && ! curr_join->group_list && 
	! curr_join->sort_and_group)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1389
    {
1390 1391
      // Some tables may have been const
      curr_join->tmp_having->update_used_tables();
1392 1393 1394
      JOIN_TAB *curr_table= &curr_join->join_tab[curr_join->const_tables];
      table_map used_tables= (curr_join->const_table_map |
			      curr_table->table->map);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1395

1396 1397
      Item* sort_table_cond= make_cond_for_table(curr_join->tmp_having,
						 used_tables,
1398
						 used_tables);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1399 1400
      if (sort_table_cond)
      {
1401 1402
	if (!curr_table->select)
	  if (!(curr_table->select= new SQL_SELECT))
1403
	    DBUG_VOID_RETURN;
1404 1405
	if (!curr_table->select->cond)
	  curr_table->select->cond= sort_table_cond;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1406
	else					// This should never happen
1407
	{
1408
	  if (!(curr_table->select->cond=
1409
		new Item_cond_and(curr_table->select->cond,
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1410
				  sort_table_cond)))
1411
	    DBUG_VOID_RETURN;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1412 1413 1414 1415 1416
	  /*
	    Item_cond_and do not need fix_fields for execution, its parameters
	    are fixed or do not need fix_fields, too
	  */
	  curr_table->select->cond->quick_fix_field();
1417
	}
1418
	curr_table->select_cond= curr_table->select->cond;
1419 1420
	curr_table->select_cond->top_level_item();
	DBUG_EXECUTE("where",print_where(curr_table->select->cond,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1421
					 "select and having"););
1422 1423 1424
	curr_join->tmp_having= make_cond_for_table(curr_join->tmp_having,
						   ~ (table_map) 0,
						   ~used_tables);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1425 1426 1427
	DBUG_EXECUTE("where",print_where(conds,"having after sort"););
      }
    }
1428
    {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1429
      if (group)
1430
	curr_join->select_limit= HA_POS_ERROR;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1431
      else
1432
      {
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1433 1434 1435 1436
	/*
	  We can abort sorting after thd->select_limit rows if we there is no
	  WHERE clause for any tables after the sorted one.
	*/
1437
	JOIN_TAB *curr_table= &curr_join->join_tab[curr_join->const_tables+1];
1438
	JOIN_TAB *end_table= &curr_join->join_tab[curr_join->tables];
1439
	for (; curr_table < end_table ; curr_table++)
1440
	{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1441 1442 1443 1444 1445 1446
	  /*
	    table->keyuse is set in the case there was an original WHERE clause
	    on the table that was optimized away.
	    table->on_expr tells us that it was a LEFT JOIN and there will be
	    at least one row generated from the table.
	  */
1447 1448
	  if (curr_table->select_cond ||
	      (curr_table->keyuse && !curr_table->on_expr))
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1449 1450
	  {
	    /* We have to sort all rows */
1451
	    curr_join->select_limit= HA_POS_ERROR;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1452 1453
	    break;
	  }
1454 1455
	}
      }
1456 1457 1458 1459
      if (curr_join->join_tab == join_tab && save_join_tab())
      {
	DBUG_VOID_RETURN;
      }
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
1460 1461 1462 1463 1464 1465 1466 1467 1468
      /*
	Here we sort rows for ORDER BY/GROUP BY clause, if the optimiser
	chose FILESORT to be faster than INDEX SCAN or there is no 
	suitable index present.
	Note, that create_sort_index calls test_if_skip_sort_order and may
	finally replace sorting with index scan if there is a LIMIT clause in
	the query. XXX: it's never shown in EXPLAIN!
	OPTION_FOUND_ROWS supersedes LIMIT and is taken into account.
      */
1469
      if (create_sort_index(thd, curr_join,
1470 1471
			    curr_join->group_list ? 
			    curr_join->group_list : curr_join->order,
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
1472 1473 1474
			    curr_join->select_limit,
			    (select_options & OPTION_FOUND_ROWS ?
			     HA_POS_ERROR : unit->select_limit_cnt)))
1475
	DBUG_VOID_RETURN;
1476
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1477
  }
1478
  curr_join->having= curr_join->tmp_having;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1479
  thd->proc_info="Sending data";
1480
  error= thd->net.report_error ? -1 :
1481
    do_select(curr_join, curr_fields_list, NULL, procedure);
Sinisa@sinisa.nasamreza.org's avatar
Sinisa@sinisa.nasamreza.org committed
1482 1483
  thd->limit_found_rows= curr_join->send_records;
  thd->examined_row_count= curr_join->examined_rows;
1484 1485
  DBUG_VOID_RETURN;
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1486

1487

1488 1489 1490 1491 1492
/*
  Clean up join. Return error that hold JOIN.
*/

int
1493
JOIN::cleanup()
1494
{
1495
  DBUG_ENTER("JOIN::cleanup");
1496 1497 1498
  select_lex->join= 0;

  if (tmp_join)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1499 1500 1501 1502 1503 1504
  {
    if (join_tab != tmp_join->join_tab)
    {
      JOIN_TAB *tab, *end;
      for (tab= join_tab, end= tab+tables ; tab != end ; tab++)
      {
1505
	tab->cleanup();
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1506 1507 1508
      }
    }
    tmp_join->tmp_join= 0;
1509
    tmp_table_param.copy_field=0;
1510
    DBUG_RETURN(tmp_join->cleanup());
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1511
  }
1512

1513
  lock=0;                                     // It's faster to unlock later
1514
  join_free(1);
1515 1516 1517 1518
  if (exec_tmp_table1)
    free_tmp_table(thd, exec_tmp_table1);
  if (exec_tmp_table2)
    free_tmp_table(thd, exec_tmp_table2);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1519 1520 1521
  delete select;
  delete_dynamic(&keyuse);
  delete procedure;
1522 1523 1524
  for (SELECT_LEX_UNIT *lex_unit= select_lex->first_inner_unit();
       lex_unit != 0;
       lex_unit= lex_unit->next_unit())
1525
  {
1526
    error|= lex_unit->cleanup();
1527 1528
  }
  DBUG_RETURN(error);
1529 1530
}

1531

1532
int
1533
mysql_select(THD *thd, Item ***rref_pointer_array,
serg@serg.mylan's avatar
serg@serg.mylan committed
1534
	     TABLE_LIST *tables, uint wild_num, List<Item> &fields,
1535 1536 1537
	     COND *conds, uint og_num,  ORDER *order, ORDER *group,
	     Item *having, ORDER *proc_param, ulong select_options,
	     select_result *result, SELECT_LEX_UNIT *unit,
1538
	     SELECT_LEX *select_lex)
1539
{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1540 1541
  int err;
  bool free_join= 1;
1542 1543
  DBUG_ENTER("mysql_select");

1544
  JOIN *join;
1545
  if (select_lex->join != 0)
1546
  {
1547
    join= select_lex->join;
1548 1549 1550
    // is it single SELECT in derived table, called in derived table creation
    if (select_lex->linkage != DERIVED_TABLE_TYPE ||
	(select_options & SELECT_DESCRIBE))
1551
    {
1552
      if (select_lex->linkage != GLOBAL_OPTIONS_TYPE)
1553
      {
1554
	//here is EXPLAIN of subselect or derived table
1555
	if (join->change_result(result))
1556 1557 1558
	{
	  DBUG_RETURN(-1);
	}
1559
      }
1560
      else
1561
      {
1562 1563 1564 1565 1566 1567
	if (join->prepare(rref_pointer_array, tables, wild_num,
			  conds, og_num, order, group, having, proc_param,
			  select_lex, unit))
	{
	  goto err;
	}
1568
      }
1569
    }
1570
    free_join= 0;
1571
    join->select_options= select_options;
1572
  }
1573 1574
  else
  {
1575 1576
    if (!(join= new JOIN(thd, fields, select_options, result)))
	DBUG_RETURN(-1);
1577 1578
    thd->proc_info="init";
    thd->used_tables=0;                         // Updated by setup_fields
1579 1580
    if (join->prepare(rref_pointer_array, tables, wild_num,
		      conds, og_num, order, group, having, proc_param,
1581
		      select_lex, unit))
1582
    {
1583
      goto err;
1584 1585 1586
    }
  }

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1587
  if ((err= join->optimize()))
1588
  {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1589 1590
    goto err;					// 1
  }
1591

1592
  if (thd->lex->describe & DESCRIBE_EXTENDED)
1593 1594 1595 1596 1597
  {
    join->conds_history= join->conds;
    join->having_history= (join->having?join->having:join->tmp_having);
  }

1598
  if (thd->net.report_error)
1599 1600 1601 1602
    goto err;

  join->exec();

1603
  if (thd->lex->describe & DESCRIBE_EXTENDED)
1604 1605 1606 1607 1608
  {
    select_lex->where= join->conds_history;
    select_lex->having= join->having_history;
  }

1609
err:
1610 1611 1612
  if (free_join)
  {
    thd->proc_info="end";
1613
    err= join->cleanup();
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1614 1615
    if (thd->net.report_error)
      err= -1;
1616
    delete join;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1617
    DBUG_RETURN(err);
1618
  }
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1619
  DBUG_RETURN(join->error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1620 1621 1622
}

/*****************************************************************************
1623 1624
  Create JOIN_TABS, make a guess about the table types,
  Approximate how many records will be used in each table
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1625 1626
*****************************************************************************/

1627 1628
static ha_rows get_quick_record_count(THD *thd, SQL_SELECT *select,
				      TABLE *table,
serg@serg.mylan's avatar
serg@serg.mylan committed
1629
				      const key_map *keys,ha_rows limit)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1630 1631 1632 1633 1634 1635 1636
{
  int error;
  DBUG_ENTER("get_quick_record_count");
  if (select)
  {
    select->head=table;
    table->reginfo.impossible_range=0;
1637 1638
    if ((error= select->test_quick_select(thd, *(key_map *)keys,(table_map) 0,
                                          limit, 0)) == 1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650
      DBUG_RETURN(select->quick->records);
    if (error == -1)
    {
      table->reginfo.impossible_range=1;
      DBUG_RETURN(0);
    }
    DBUG_PRINT("warning",("Couldn't use record count on const keypart"));
  }
  DBUG_RETURN(HA_POS_ERROR);			/* This shouldn't happend */
}


1651 1652 1653 1654 1655 1656 1657
/*
  Calculate the best possible join and initialize the join structure

  RETURN VALUES
  0	ok
  1	Fatal error
*/
serg@serg.mysql.com's avatar
serg@serg.mysql.com committed
1658

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1659 1660
static bool
make_join_statistics(JOIN *join,TABLE_LIST *tables,COND *conds,
1661
		     DYNAMIC_ARRAY *keyuse_array)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1662 1663
{
  int error;
1664 1665 1666
  uint i,table_count,const_count,key;
  table_map found_const_table_map, all_table_map, found_ref, refs;
  key_map const_ref, eq_part;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1667 1668 1669 1670 1671 1672 1673 1674
  TABLE **table_vector;
  JOIN_TAB *stat,*stat_end,*s,**stat_ref;
  KEYUSE *keyuse,*start_keyuse;
  table_map outer_join=0;
  JOIN_TAB *stat_vector[MAX_TABLES+1];
  DBUG_ENTER("make_join_statistics");

  table_count=join->tables;
1675 1676
  stat=(JOIN_TAB*) join->thd->calloc(sizeof(JOIN_TAB)*table_count);
  stat_ref=(JOIN_TAB**) join->thd->alloc(sizeof(JOIN_TAB*)*MAX_TABLES);
1677
  table_vector=(TABLE**) join->thd->alloc(sizeof(TABLE*)*(table_count*2));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1678 1679 1680 1681 1682 1683
  if (!stat || !stat_ref || !table_vector)
    DBUG_RETURN(1);				// Eom /* purecov: inspected */

  join->best_ref=stat_vector;

  stat_end=stat+table_count;
1684
  found_const_table_map= all_table_map=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1685 1686 1687 1688 1689 1690
  const_count=0;

  for (s=stat,i=0 ; tables ; s++,tables=tables->next,i++)
  {
    TABLE *table;
    stat_vector[i]=s;
1691 1692 1693 1694
    s->keys.init();
    s->const_keys.init();
    s->checked_keys.init();
    s->needed_reg.init();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1695 1696
    table_vector[i]=s->table=table=tables->table;
    table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);// record count
1697
    table->quick_keys.clear_all();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1698 1699 1700 1701
    table->reginfo.join_tab=s;
    table->reginfo.not_exists_optimize=0;
    bzero((char*) table->const_key_parts, sizeof(key_part_map)*table->keys);
    all_table_map|= table->map;
1702
    s->join=join;
1703
    s->info=0;					// For describe
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1704 1705
    if ((s->on_expr=tables->on_expr))
    {
1706
      /* Left join */
1707 1708
      if (!table->file->records)
      {						// Empty table
1709
	s->key_dependent=s->dependent=0;	// Ignore LEFT JOIN depend.
1710 1711 1712
	set_position(join,const_count++,s,(KEYUSE*) 0);
	continue;
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1713 1714
      s->key_dependent=s->dependent=
	s->on_expr->used_tables() & ~(table->map);
1715 1716 1717 1718
      if (table->outer_join & JOIN_TYPE_LEFT)
	s->dependent|=stat_vector[i-1]->dependent | table_vector[i-1]->map;
      if (tables->outer_join & JOIN_TYPE_RIGHT)
	s->dependent|=tables->next->table->map;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1719 1720 1721 1722 1723 1724 1725 1726
      outer_join|=table->map;
      continue;
    }
    if (tables->straight)			// We don't have to move this
      s->dependent= table_vector[i-1]->map | stat_vector[i-1]->dependent;
    else
      s->dependent=(table_map) 0;
    s->key_dependent=(table_map) 0;
1727
    if ((table->system || table->file->records <= 1) && ! s->dependent &&
1728
	!(table->file->table_flags() & HA_NOT_EXACT_COUNT) &&
1729
        !table->fulltext_searched)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1730 1731 1732 1733 1734
    {
      set_position(join,const_count++,s,(KEYUSE*) 0);
    }
  }
  stat_vector[i]=0;
1735
  join->outer_join=outer_join;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1736 1737

  /*
1738 1739 1740 1741
    If outer join: Re-arrange tables in stat_vector so that outer join
    tables are after all tables it is dependent of.
    For example: SELECT * from A LEFT JOIN B ON B.c=C.c, C WHERE A.C=C.C
    Will shift table B after table C.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
  */
  if (outer_join)
  {
    table_map used_tables=0L;
    for (i=0 ; i < join->tables-1 ; i++)
    {
      if (stat_vector[i]->dependent & ~used_tables)
      {
	JOIN_TAB *save= stat_vector[i];
	uint j;
	for (j=i+1;
	     j < join->tables && stat_vector[j]->dependent & ~used_tables;
	     j++)
	{
	  JOIN_TAB *tmp=stat_vector[j];		// Move element up
	  stat_vector[j]=save;
	  save=tmp;
	}
	if (j == join->tables)
	{
	  join->tables=0;			// Don't use join->table
	  my_error(ER_WRONG_OUTER_JOIN,MYF(0));
	  DBUG_RETURN(1);
	}
	stat_vector[i]=stat_vector[j];
	stat_vector[j]=save;
      }
      used_tables|= stat_vector[i]->table->map;
    }
  }

  if (conds || outer_join)
1774 1775
    if (update_ref_and_keys(join->thd, keyuse_array, stat, join->tables,
                            conds, ~outer_join, join->select_lex))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1776 1777
      DBUG_RETURN(1);

1778
  /* Read tables with 0 or 1 rows (system tables) */
1779
  join->const_table_map= 0;
1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797

  for (POSITION *p_pos=join->positions, *p_end=p_pos+const_count;
       p_pos < p_end ;
       p_pos++)
  {
    int tmp;
    s= p_pos->table;
    s->type=JT_SYSTEM;
    join->const_table_map|=s->table->map;
    if ((tmp=join_read_const_table(s, p_pos)))
    {
      if (tmp > 0)
	DBUG_RETURN(1);			// Fatal error
    }
    else
      found_const_table_map|= s->table->map;
  }

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1798
  /* loop until no more const tables are found */
1799
  int ref_changed;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1800 1801
  do
  {
1802
    ref_changed = 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1803
    found_ref=0;
1804 1805 1806 1807 1808 1809 1810

    /*
      We only have to loop from stat_vector + const_count as
      set_position() will move all const_tables first in stat_vector
    */

    for (JOIN_TAB **pos=stat_vector+const_count ; (s= *pos) ; pos++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1811
    {
1812
      TABLE *table=s->table;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1813 1814
      if (s->dependent)				// If dependent on some table
      {
1815
	// All dep. must be constants
1816
	if (s->dependent & ~(found_const_table_map))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1817
	  continue;
1818
	if (table->file->records <= 1L &&
1819
	    !(table->file->table_flags() & HA_NOT_EXACT_COUNT))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1820
	{					// system table
1821
	  int tmp= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1822
	  s->type=JT_SYSTEM;
1823
	  join->const_table_map|=table->map;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1824
	  set_position(join,const_count++,s,(KEYUSE*) 0);
1825
	  if ((tmp= join_read_const_table(s,join->positions+const_count-1)))
1826 1827 1828 1829 1830 1831
	  {
	    if (tmp > 0)
	      DBUG_RETURN(1);			// Fatal error
	  }
	  else
	    found_const_table_map|= table->map;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842
	  continue;
	}
      }
      /* check if table can be read by key or table only uses const refs */
      if ((keyuse=s->keyuse))
      {
	s->type= JT_REF;
	while (keyuse->table == table)
	{
	  start_keyuse=keyuse;
	  key=keyuse->key;
1843
	  s->keys.set_bit(key);               // QQ: remove this ?
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1844

1845 1846 1847
	  refs=0;
          const_ref.clear_all();
	  eq_part.clear_all();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1848 1849
	  do
	  {
1850
	    if (keyuse->val->type() != Item::NULL_ITEM && !keyuse->optimize)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1851
	    {
1852
	      if (!((~found_const_table_map) & keyuse->used_tables))
1853
		const_ref.set_bit(keyuse->keypart);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1854 1855
	      else
		refs|=keyuse->used_tables;
1856
	      eq_part.set_bit(keyuse->keypart);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1857 1858 1859 1860
	    }
	    keyuse++;
	  } while (keyuse->table == table && keyuse->key == key);

1861
	  if (eq_part.is_prefix(table->key_info[key].key_parts) &&
1862 1863
	      ((table->key_info[key].flags & (HA_NOSAME | HA_END_SPACE_KEY)) ==
	       HA_NOSAME) &&
1864
              !table->fulltext_searched)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1865 1866 1867
	  {
	    if (const_ref == eq_part)
	    {					// Found everything for ref.
1868 1869
	      int tmp;
	      ref_changed = 1;
1870
	      s->type= JT_CONST;
1871
	      join->const_table_map|=table->map;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1872
	      set_position(join,const_count++,s,start_keyuse);
1873
	      if (create_ref_for_key(join, s, start_keyuse,
1874
				     found_const_table_map))
1875 1876 1877 1878 1879 1880 1881 1882 1883
		DBUG_RETURN(1);
	      if ((tmp=join_read_const_table(s,
					     join->positions+const_count-1)))
	      {
		if (tmp > 0)
		  DBUG_RETURN(1);			// Fatal error
	      }
	      else
		found_const_table_map|= table->map;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1884 1885 1886 1887 1888 1889 1890 1891
	      break;
	    }
	    else
	      found_ref|= refs;		// Table is const if all refs are const
	  }
	}
      }
    }
1892
  } while (join->const_table_map & found_ref && ref_changed);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905

  /* Calc how many (possible) matched records in each table */

  for (s=stat ; s < stat_end ; s++)
  {
    if (s->type == JT_SYSTEM || s->type == JT_CONST)
    {
      /* Only one matching row */
      s->found_records=s->records=s->read_time=1; s->worst_seeks=1.0;
      continue;
    }
    /* Approximate found rows and time to read them */
    s->found_records=s->records=s->table->file->records;
1906
    s->read_time=(ha_rows) s->table->file->scan_time();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1907

1908 1909
    /*
      Set a max range of how many seeks we can expect when using keys
1910 1911
      This is can't be to high as otherwise we are likely to use
      table scan.
1912
    */
1913 1914
    s->worst_seeks= min((double) s->found_records / 10,
			(double) s->read_time*3);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1915 1916 1917
    if (s->worst_seeks < 2.0)			// Fix for small tables
      s->worst_seeks=2.0;

1918
    if (! s->const_keys.is_clear_all())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1919 1920
    {
      ha_rows records;
1921 1922 1923 1924 1925
      SQL_SELECT *select;
      select= make_select(s->table, found_const_table_map,
			  found_const_table_map,
			  s->on_expr ? s->on_expr : conds,
			  &error);
1926
      records= get_quick_record_count(join->thd, select, s->table,
serg@serg.mylan's avatar
serg@serg.mylan committed
1927
				      &s->const_keys, join->row_limit);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1928 1929 1930
      s->quick=select->quick;
      s->needed_reg=select->needed_reg;
      select->quick=0;
1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950
      if (records == 0 && s->table->reginfo.impossible_range)
      {
	/*
	  Impossible WHERE or ON expression
	  In case of ON, we mark that the we match one empty NULL row.
	  In case of WHERE, don't set found_const_table_map to get the
	  caller to abort with a zero row result.
	*/
	join->const_table_map|= s->table->map;
	set_position(join,const_count++,s,(KEYUSE*) 0);
	s->type= JT_CONST;
	if (s->on_expr)
	{
	  /* Generate empty row */
	  s->info= "Impossible ON condition";
	  found_const_table_map|= s->table->map;
	  s->type= JT_CONST;
	  mark_as_null_row(s->table);		// All fields are NULL
	}
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1951 1952
      if (records != HA_POS_ERROR)
      {
1953
	s->found_records=records;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1954 1955
	s->read_time= (ha_rows) (s->quick ? s->quick->read_time : 0.0);
      }
1956
      delete select;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1957 1958 1959 1960 1961 1962 1963 1964
    }
  }

  /* Find best combination and return it */
  join->join_tab=stat;
  join->map2table=stat_ref;
  join->table= join->all_tables=table_vector;
  join->const_tables=const_count;
1965
  join->found_const_table_map=found_const_table_map;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1966 1967

  if (join->const_tables != join->tables)
1968 1969
  {
    optimize_keyuse(join, keyuse_array);
1970
    find_best_combination(join,all_table_map & ~join->const_table_map);
1971
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1972 1973 1974 1975 1976 1977
  else
  {
    memcpy((gptr) join->best_positions,(gptr) join->positions,
	   sizeof(POSITION)*join->const_tables);
    join->best_read=1.0;
  }
serg@serg.mysql.com's avatar
serg@serg.mysql.com committed
1978
  DBUG_RETURN(join->thd->killed || get_best_combination(join));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1979 1980 1981 1982
}


/*****************************************************************************
1983 1984 1985 1986 1987
  Check with keys are used and with tables references with tables
  Updates in stat:
	  keys	     Bitmap of all used keys
	  const_keys Bitmap of all keys with may be used with quick_select
	  keyuse     Pointer to possible keys
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1988 1989 1990 1991 1992
*****************************************************************************/

typedef struct key_field_t {		// Used when finding key fields
  Field		*field;
  Item		*val;			// May be empty if diff constant
1993 1994
  uint		level;
  uint		optimize;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1995
  bool		eq_func;
1996 1997 1998 1999 2000
  /*
    If true, the condition this struct represents will not be satisfied
    when val IS NULL.
  */
  bool          null_rejecting; 
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2001 2002
} KEY_FIELD;

2003 2004 2005 2006 2007 2008 2009 2010
/* Values in optimize */
#define KEY_OPTIMIZE_EXISTS		1
#define KEY_OPTIMIZE_REF_OR_NULL	2

/*
  Merge new key definitions to old ones, remove those not used in both

  This is called for OR between different levels
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2011

2012 2013 2014 2015 2016
  To be able to do 'ref_or_null' we merge a comparison of a column
  and 'column IS NULL' to one test.  This is useful for sub select queries
  that are internally transformed to something like:

  SELECT * FROM t1 WHERE t1.key=outer_ref_field or t1.key IS NULL 
2017 2018 2019 2020 2021 2022

  KEY_FIELD::null_rejecting is processed as follows:
  result has null_rejecting=true if it is set for both ORed references.
  for example:
    (t2.key = t1.field OR t2.key  =  t1.field) -> null_rejecting=true
    (t2.key = t1.field OR t2.key <=> t1.field) -> null_rejecting=false
2023
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2024 2025 2026 2027 2028 2029 2030 2031

static KEY_FIELD *
merge_key_fields(KEY_FIELD *start,KEY_FIELD *new_fields,KEY_FIELD *end,
		 uint and_level)
{
  if (start == new_fields)
    return start;				// Impossible or
  if (new_fields == end)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2032
    return start;				// No new fields, skip all
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044

  KEY_FIELD *first_free=new_fields;

  /* Mark all found fields in old array */
  for (; new_fields != end ; new_fields++)
  {
    for (KEY_FIELD *old=start ; old != first_free ; old++)
    {
      if (old->field == new_fields->field)
      {
	if (new_fields->val->used_tables())
	{
2045 2046 2047 2048
	  /*
	    If the value matches, we can use the key reference.
	    If not, we keep it until we have examined all new values
	  */
2049
	  if (old->val->eq(new_fields->val, old->field->binary()))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2050
	  {
2051 2052 2053 2054 2055
	    old->level= and_level;
	    old->optimize= ((old->optimize & new_fields->optimize &
			     KEY_OPTIMIZE_EXISTS) |
			    ((old->optimize | new_fields->optimize) &
			     KEY_OPTIMIZE_REF_OR_NULL));
monty@mysql.com's avatar
monty@mysql.com committed
2056 2057
            old->null_rejecting= (old->null_rejecting &&
                                  new_fields->null_rejecting);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2058 2059
	  }
	}
2060 2061
	else if (old->eq_func && new_fields->eq_func &&
		 old->val->eq(new_fields->val, old->field->binary()))
2062

2063 2064 2065 2066 2067 2068
	{
	  old->level= and_level;
	  old->optimize= ((old->optimize & new_fields->optimize &
			   KEY_OPTIMIZE_EXISTS) |
			  ((old->optimize | new_fields->optimize) &
			   KEY_OPTIMIZE_REF_OR_NULL));
monty@mysql.com's avatar
monty@mysql.com committed
2069 2070
          old->null_rejecting= (old->null_rejecting &&
                                new_fields->null_rejecting);
2071 2072 2073
	}
	else if (old->eq_func && new_fields->eq_func &&
		 (old->val->is_null() || new_fields->val->is_null()))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2074
	{
2075 2076 2077 2078 2079 2080
	  /* field = expression OR field IS NULL */
	  old->level= and_level;
	  old->optimize= KEY_OPTIMIZE_REF_OR_NULL;
	  /* Remember the NOT NULL value */
	  if (old->val->is_null())
	    old->val= new_fields->val;
2081
          /* The referred expression can be NULL: */ 
monty@mysql.com's avatar
monty@mysql.com committed
2082
          old->null_rejecting= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2083
	}
2084
	else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2085
	{
2086 2087 2088 2089 2090
	  /*
	    We are comparing two different const.  In this case we can't
	    use a key-lookup on this so it's better to remove the value
	    and let the range optimzier handle it
	  */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101
	  if (old == --first_free)		// If last item
	    break;
	  *old= *first_free;			// Remove old value
	  old--;				// Retry this value
	}
      }
    }
  }
  /* Remove all not used items */
  for (KEY_FIELD *old=start ; old != first_free ;)
  {
2102
    if (old->level != and_level)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114
    {						// Not used in all levels
      if (old == --first_free)
	break;
      *old= *first_free;			// Remove old value
      continue;
    }
    old++;
  }
  return first_free;
}


2115 2116 2117 2118 2119 2120 2121 2122 2123 2124
/*
  Add a possible key to array of possible keys if it's usable as a key

  SYNPOSIS
    add_key_field()
    key_fields			Pointer to add key, if usable
    and_level			And level, to be stored in KEY_FIELD
    field			Field used in comparision
    eq_func			True if we used =, <=> or IS NULL
    value			Value used for comparison with field
2125
                                Is NULL for BETWEEN and IN
2126 2127 2128 2129 2130 2131 2132 2133 2134 2135
    usable_tables		Tables which can be used for key optimization

  NOTES
    If we are doing a NOT NULL comparison on a NOT NULL field in a outer join
    table, we store this to be able to do not exists optimization later.

  RETURN
    *key_fields is incremented if we stored a key in the array
*/

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2136
static void
2137
add_key_field(KEY_FIELD **key_fields,uint and_level, Item_func *cond,
2138
	      Field *field,bool eq_func,Item **value, uint num_values,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2139 2140
	      table_map usable_tables)
{
2141
  uint exists_optimize= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2142 2143 2144
  if (!(field->flags & PART_KEY_FLAG))
  {
    // Don't remove column IS NULL on a LEFT JOIN table
2145 2146
    if (!eq_func || (*value)->type() != Item::NULL_ITEM ||
        !field->table->maybe_null || field->null_ptr)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2147
      return;					// Not a key. Skip it
2148
    exists_optimize= KEY_OPTIMIZE_EXISTS;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2149 2150 2151 2152
  }
  else
  {
    table_map used_tables=0;
2153 2154 2155
    bool optimizable=0;
    for (uint i=0; i<num_values; i++)
    {
2156 2157
      used_tables|=(value[i])->used_tables();
      if (!((value[i])->used_tables() & (field->table->map | RAND_TABLE_BIT)))
2158 2159 2160
        optimizable=1;
    }
    if (!optimizable)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2161 2162 2163
      return;
    if (!(usable_tables & field->table->map))
    {
2164 2165
      if (!eq_func || (*value)->type() != Item::NULL_ITEM ||
          !field->table->maybe_null || field->null_ptr)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2166
	return;					// Can't use left join optimize
2167
      exists_optimize= KEY_OPTIMIZE_EXISTS;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2168 2169 2170 2171
    }
    else
    {
      JOIN_TAB *stat=field->table->reginfo.join_tab;
serg@serg.mylan's avatar
serg@serg.mylan committed
2172
      key_map possible_keys=field->key_start;
2173 2174
      possible_keys.intersect(field->table->keys_in_use_for_query);
      stat[0].keys.merge(possible_keys);             // Add possible keys
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2175

2176 2177 2178 2179 2180 2181 2182 2183
      /*
	Save the following cases:
	Field op constant
	Field LIKE constant where constant doesn't start with a wildcard
	Field = field2 where field2 is in a different table
	Field op formula
	Field IS NULL
	Field IS NOT NULL
2184 2185
         Field BETWEEN ...
         Field IN ...
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2186 2187 2188
      */
      stat[0].key_dependent|=used_tables;

2189 2190
      bool is_const=1;
      for (uint i=0; i<num_values; i++)
2191
        is_const&= value[i]->const_item();
2192
      if (is_const)
2193
        stat[0].const_keys.merge(possible_keys);
2194 2195
      /*
	We can't always use indexes when comparing a string index to a
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2196 2197
	number. cmp_type() is checked to allow compare of dates to numbers.
        eq_func is NEVER true when num_values > 1
2198
       */
monty@mysql.com's avatar
monty@mysql.com committed
2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212
      if (!eq_func)
        return;
      if (field->result_type() == STRING_RESULT)
      {
        if ((*value)->result_type() != STRING_RESULT)
        {
          if (field->cmp_type() != (*value)->result_type())
            return;
        }
        else
        {
          /*
            We can't use indexes if the effective collation
            of the operation differ from the field collation.
2213

monty@mysql.com's avatar
monty@mysql.com committed
2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224
            We can also not used index on a text column, as the column may
            contain 'x' 'x\t' 'x ' and 'read_next_same' will stop after
            'x' when searching for WHERE col='x '
          */
          if (field->cmp_type() == STRING_RESULT &&
              (((Field_str*)field)->charset() != cond->compare_collation() ||
               ((*value)->type() != Item::NULL_ITEM &&
                (field->flags & BLOB_FLAG) && !field->binary())))
            return;
        }
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2225 2226
    }
  }
2227
  DBUG_ASSERT(num_values == 1);
2228 2229 2230 2231 2232
  /*
    For the moment eq_func is always true. This slot is reserved for future
    extensions where we want to remembers other things than just eq comparisons
  */
  DBUG_ASSERT(eq_func);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2233
  /* Store possible eq field */
2234 2235
  (*key_fields)->field=		field;
  (*key_fields)->eq_func=	eq_func;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2236
  (*key_fields)->val=		*value;
2237 2238
  (*key_fields)->level=		and_level;
  (*key_fields)->optimize=	exists_optimize;
2239 2240 2241 2242
  /*
    If the condition has form "tbl.keypart = othertbl.field" and 
    othertbl.field can be NULL, there will be no matches if othertbl.field 
    has NULL value.
monty@mysql.com's avatar
monty@mysql.com committed
2243 2244
    We use null_rejecting in add_not_null_conds() to add
    'othertbl.field IS NOT NULL' to tab->select_cond.
2245 2246 2247 2248
  */
  (*key_fields)->null_rejecting= (cond->functype() == Item_func::EQ_FUNC) &&
                                 ((*value)->type() == Item::FIELD_ITEM) &&
                                 ((Item_field*)*value)->field->maybe_null();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2249 2250 2251
  (*key_fields)++;
}

2252 2253 2254 2255 2256 2257 2258 2259 2260 2261
/*
  SYNOPSIS
    add_key_fields()
      key_fields      Add KEY_FIELD entries to this array (and move the 
                      pointer)
      and_level       AND-level (a value that is different for every n-way
                      AND operation)
      cond            Condition to analyze
      usable_tables   Value to pass to add_key_field
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2262
static void
2263
add_key_fields(KEY_FIELD **key_fields,uint *and_level,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2264 2265 2266 2267
	       COND *cond, table_map usable_tables)
{
  if (cond->type() == Item_func::COND_ITEM)
  {
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
2268
    List_iterator_fast<Item> li(*((Item_cond*) cond)->argument_list());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2269 2270 2271 2272 2273 2274
    KEY_FIELD *org_key_fields= *key_fields;

    if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
    {
      Item *item;
      while ((item=li++))
2275
	add_key_fields(key_fields,and_level,item,usable_tables);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2276
      for (; org_key_fields != *key_fields ; org_key_fields++)
2277
	org_key_fields->level= *and_level;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2278 2279 2280 2281
    }
    else
    {
      (*and_level)++;
2282
      add_key_fields(key_fields,and_level,li++,usable_tables);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2283 2284 2285 2286 2287
      Item *item;
      while ((item=li++))
      {
	KEY_FIELD *start_key_fields= *key_fields;
	(*and_level)++;
2288
	add_key_fields(key_fields,and_level,item,usable_tables);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303
	*key_fields=merge_key_fields(org_key_fields,start_key_fields,
				     *key_fields,++(*and_level));
      }
    }
    return;
  }
  /* If item is of type 'field op field/constant' add it to key_fields */

  if (cond->type() != Item::FUNC_ITEM)
    return;
  Item_func *cond_func= (Item_func*) cond;
  switch (cond_func->select_optimize()) {
  case Item_func::OPTIMIZE_NONE:
    break;
  case Item_func::OPTIMIZE_KEY:
serg@serg.mylan's avatar
serg@serg.mylan committed
2304
    // BETWEEN, IN, NOT
2305
    if (cond_func->key_item()->real_item()->type() == Item::FIELD_ITEM &&
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2306
	!(cond_func->used_tables() & OUTER_REF_TABLE_BIT))
2307
      add_key_field(key_fields,*and_level,cond_func,
serg@serg.mylan's avatar
serg@serg.mylan committed
2308 2309 2310
		    ((Item_field*)(cond_func->key_item()->real_item()))->field,
                    cond_func->argument_count() == 2 &&
                    cond_func->functype() == Item_func::IN_FUNC,
2311 2312
                    cond_func->arguments()+1, cond_func->argument_count()-1,
                    usable_tables);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2313 2314 2315 2316 2317 2318
    break;
  case Item_func::OPTIMIZE_OP:
  {
    bool equal_func=(cond_func->functype() == Item_func::EQ_FUNC ||
		     cond_func->functype() == Item_func::EQUAL_FUNC);

2319
    if (cond_func->arguments()[0]->real_item()->type() == Item::FIELD_ITEM &&
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2320
	!(cond_func->arguments()[0]->used_tables() & OUTER_REF_TABLE_BIT))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2321
    {
2322
      add_key_field(key_fields,*and_level,cond_func,
2323 2324
		    ((Item_field*) (cond_func->arguments()[0])->real_item())
		    ->field,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2325
		    equal_func,
2326
                    cond_func->arguments()+1, 1, usable_tables);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2327
    }
2328
    if (cond_func->arguments()[1]->real_item()->type() == Item::FIELD_ITEM &&
2329
	cond_func->functype() != Item_func::LIKE_FUNC &&
2330
	!(cond_func->arguments()[1]->used_tables() & OUTER_REF_TABLE_BIT))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2331
    {
2332
      add_key_field(key_fields,*and_level,cond_func,
2333 2334
		    ((Item_field*) (cond_func->arguments()[1])->real_item())
		    ->field,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2335
		    equal_func,
2336
		    cond_func->arguments(),1,usable_tables);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2337 2338 2339 2340 2341
    }
    break;
  }
  case Item_func::OPTIMIZE_NULL:
    /* column_name IS [NOT] NULL */
2342
    if (cond_func->arguments()[0]->real_item()->type() == Item::FIELD_ITEM &&
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2343
	!(cond_func->used_tables() & OUTER_REF_TABLE_BIT))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2344
    {
2345
      Item *tmp=new Item_null;
2346
      if (unlikely(!tmp))                       // Should never be true
2347
	return;
2348
      add_key_field(key_fields,*and_level,cond_func,
2349 2350
		    ((Item_field*) (cond_func->arguments()[0])->real_item())
		    ->field,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2351
		    cond_func->functype() == Item_func::ISNULL_FUNC,
2352
		    &tmp, 1, usable_tables);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2353 2354 2355 2356 2357 2358 2359
    }
    break;
  }
  return;
}

/*
2360 2361
  Add all keys with uses 'field' for some keypart
  If field->and_level != and_level then only mark key_part as const_part
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2362 2363 2364
*/

static uint
2365
max_part_bit(key_part_map bits)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378
{
  uint found;
  for (found=0; bits & 1 ; found++,bits>>=1) ;
  return found;
}

static void
add_key_part(DYNAMIC_ARRAY *keyuse_array,KEY_FIELD *key_field)
{
  Field *field=key_field->field;
  TABLE *form= field->table;
  KEYUSE keyuse;

2379
  if (key_field->eq_func && !(key_field->optimize & KEY_OPTIMIZE_EXISTS))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2380 2381 2382
  {
    for (uint key=0 ; key < form->keys ; key++)
    {
2383
      if (!(form->keys_in_use_for_query.is_set(key)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396
	continue;
      if (form->key_info[key].flags & HA_FULLTEXT)
	continue;    // ToDo: ft-keys in non-ft queries.   SerG

      uint key_parts= (uint) form->key_info[key].key_parts;
      for (uint part=0 ; part <  key_parts ; part++)
      {
	if (field->eq(form->key_info[key].key_part[part].field))
	{
	  keyuse.table= field->table;
	  keyuse.val =  key_field->val;
	  keyuse.key =  key;
	  keyuse.keypart=part;
2397
	  keyuse.keypart_map= (key_part_map) 1 << part;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2398
	  keyuse.used_tables=key_field->val->used_tables();
2399
	  keyuse.optimize= key_field->optimize & KEY_OPTIMIZE_REF_OR_NULL;
2400
          keyuse.null_rejecting= key_field->null_rejecting;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2401 2402 2403 2404 2405 2406 2407
	  VOID(insert_dynamic(keyuse_array,(gptr) &keyuse));
	}
      }
    }
  }
}

monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2408 2409 2410

#define FT_KEYPART   (MAX_REF_PARTS+10)

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2411 2412 2413 2414
static void
add_ft_keys(DYNAMIC_ARRAY *keyuse_array,
            JOIN_TAB *stat,COND *cond,table_map usable_tables)
{
2415
  Item_func_match *cond_func=NULL;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2416

2417 2418 2419
  if (!cond)
    return;

2420 2421
  if (cond->type() == Item::FUNC_ITEM)
  {
2422 2423 2424
    Item_func *func=(Item_func *)cond;
    Item_func::Functype functype=  func->functype();
    if (functype == Item_func::FT_FUNC)
2425
      cond_func=(Item_func_match *)cond;
2426 2427 2428 2429
    else if (func->arg_count == 2)
    {
      Item_func *arg0=(Item_func *)(func->arguments()[0]),
                *arg1=(Item_func *)(func->arguments()[1]);
2430 2431 2432 2433 2434
      if (arg1->const_item()  &&
          ((functype == Item_func::GE_FUNC && arg1->val()> 0) ||
           (functype == Item_func::GT_FUNC && arg1->val()>=0))  &&
           arg0->type() == Item::FUNC_ITEM            &&
           arg0->functype() == Item_func::FT_FUNC)
2435
        cond_func=(Item_func_match *) arg0;
2436 2437 2438
      else if (arg0->const_item() &&
               ((functype == Item_func::LE_FUNC && arg0->val()> 0) ||
                (functype == Item_func::LT_FUNC && arg0->val()>=0)) &&
2439
                arg1->type() == Item::FUNC_ITEM          &&
2440
                arg1->functype() == Item_func::FT_FUNC)
2441 2442
        cond_func=(Item_func_match *) arg1;
    }
2443 2444 2445
  }
  else if (cond->type() == Item::COND_ITEM)
  {
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
2446
    List_iterator_fast<Item> li(*((Item_cond*) cond)->argument_list());
2447 2448 2449 2450 2451

    if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
    {
      Item *item;
      while ((item=li++))
2452
        add_ft_keys(keyuse_array,stat,item,usable_tables);
2453 2454 2455
    }
  }

2456 2457
  if (!cond_func || cond_func->key == NO_SUCH_KEY ||
      !(usable_tables & cond_func->table->map))
2458
    return;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2459 2460 2461

  KEYUSE keyuse;
  keyuse.table= cond_func->table;
2462
  keyuse.val =  cond_func;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2463
  keyuse.key =  cond_func->key;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2464
  keyuse.keypart= FT_KEYPART;
2465
  keyuse.used_tables=cond_func->key_item()->used_tables();
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2466
  keyuse.optimize= 0;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2467
  keyuse.keypart_map= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2468 2469 2470
  VOID(insert_dynamic(keyuse_array,(gptr) &keyuse));
}

2471

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2472 2473 2474
static int
sort_keyuse(KEYUSE *a,KEYUSE *b)
{
2475
  int res;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2476 2477 2478 2479 2480 2481
  if (a->table->tablenr != b->table->tablenr)
    return (int) (a->table->tablenr - b->table->tablenr);
  if (a->key != b->key)
    return (int) (a->key - b->key);
  if (a->keypart != b->keypart)
    return (int) (a->keypart - b->keypart);
2482
  // Place const values before other ones
2483 2484
  if ((res= test((a->used_tables & ~OUTER_REF_TABLE_BIT)) -
       test((b->used_tables & ~OUTER_REF_TABLE_BIT))))
2485 2486 2487 2488
    return res;
  /* Place rows that are not 'OPTIMIZE_REF_OR_NULL' first */
  return (int) ((a->optimize & KEY_OPTIMIZE_REF_OR_NULL) -
		(b->optimize & KEY_OPTIMIZE_REF_OR_NULL));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2489 2490 2491 2492
}


/*
2493
  Update keyuse array with all possible keys we can use to fetch rows
2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509
  
  SYNOPSIS
    update_ref_and_keys()
      thd 
      keyuse     OUT Put here ordered array of KEYUSE structures
      join_tab       Array in tablenr_order
      tables         Number of tables in join
      cond           WHERE condition (note that the function analyzes 
                     join_tab[i]->on_expr too)
      normal_tables  tables not inner w.r.t some outer join (ones for which
                     we can make ref access based the WHERE clause)
      select_lex     current SELECT
      
  RETURN 
   0 - OK
   1 - Out of memory.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2510 2511 2512
*/

static bool
2513
update_ref_and_keys(THD *thd, DYNAMIC_ARRAY *keyuse,JOIN_TAB *join_tab,
2514 2515
		    uint tables, COND *cond, table_map normal_tables,
		    SELECT_LEX *select_lex)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2516 2517
{
  uint	and_level,i,found_eq_constant;
monty@mysql.com's avatar
monty@mysql.com committed
2518
  KEY_FIELD *key_fields, *end, *field;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2519

2520
  if (!(key_fields=(KEY_FIELD*)
monty@mashka.mysql.fi's avatar
merge  
monty@mashka.mysql.fi committed
2521
	thd->alloc(sizeof(key_fields[0])*
2522
		   (thd->lex->current_select->cond_count+1)*2)))
2523
    return TRUE; /* purecov: inspected */
monty@mysql.com's avatar
monty@mysql.com committed
2524 2525 2526 2527
  and_level= 0;
  field= end= key_fields;
  if (my_init_dynamic_array(keyuse,sizeof(KEYUSE),20,64))
    return TRUE;
2528
  if (cond)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2529
  {
2530
    add_key_fields(&end,&and_level,cond,normal_tables);
monty@mysql.com's avatar
monty@mysql.com committed
2531
    for (; field != end ; field++)
hf@deer.(none)'s avatar
hf@deer.(none) committed
2532
    {
monty@mysql.com's avatar
monty@mysql.com committed
2533 2534 2535 2536 2537
      add_key_part(keyuse,field);
      /* Mark that we can optimize LEFT JOIN */
      if (field->val->type() == Item::NULL_ITEM &&
	  !field->field->real_maybe_null())
	field->field->table->reginfo.not_exists_optimize=1;
hf@deer.(none)'s avatar
hf@deer.(none) committed
2538
    }
monty@mysql.com's avatar
monty@mysql.com committed
2539
  }
2540
  for (i=0 ; i < tables ; i++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2541
  {
2542
    if (join_tab[i].on_expr)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2543
    {
2544
      add_key_fields(&end,&and_level,join_tab[i].on_expr,
2545
		     join_tab[i].table->map);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2546 2547
    }
  }
2548
  /* fill keyuse with found key parts */
monty@mysql.com's avatar
monty@mysql.com committed
2549
  for ( ; field != end ; field++)
2550
    add_key_part(keyuse,field);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2551

2552
  if (select_lex->ftfunc_list->elements)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2553 2554 2555 2556 2557
  {
    add_ft_keys(keyuse,join_tab,cond,normal_tables);
  }

  /*
2558
    Special treatment for ft-keys.
2559 2560 2561
    Remove the following things from KEYUSE:
    - ref if there is a keypart which is a ref and a const.
    - keyparts without previous keyparts.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578
  */
  if (keyuse->elements)
  {
    KEYUSE end,*prev,*save_pos,*use;

    qsort(keyuse->buffer,keyuse->elements,sizeof(KEYUSE),
	  (qsort_cmp) sort_keyuse);

    bzero((char*) &end,sizeof(end));		/* Add for easy testing */
    VOID(insert_dynamic(keyuse,(gptr) &end));

    use=save_pos=dynamic_element(keyuse,0,KEYUSE*);
    prev=&end;
    found_eq_constant=0;
    for (i=0 ; i < keyuse->elements-1 ; i++,use++)
    {
      if (!use->used_tables)
2579
	use->table->const_key_parts[use->key]|= use->keypart_map;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2580 2581
      if (use->keypart != FT_KEYPART)
      {
2582 2583 2584 2585 2586 2587 2588 2589
	if (use->key == prev->key && use->table == prev->table)
	{
	  if (prev->keypart+1 < use->keypart ||
	      prev->keypart == use->keypart && found_eq_constant)
	    continue;				/* remove */
	}
	else if (use->keypart != 0)		// First found must be 0
	  continue;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2590 2591 2592 2593 2594 2595 2596 2597
      }

      *save_pos= *use;
      prev=use;
      found_eq_constant= !use->used_tables;
      /* Save ptr to first use */
      if (!use->table->reginfo.join_tab->keyuse)
	use->table->reginfo.join_tab->keyuse=save_pos;
2598
      use->table->reginfo.join_tab->checked_keys.set_bit(use->key);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2599 2600 2601 2602 2603 2604 2605 2606 2607
      save_pos++;
    }
    i=(uint) (save_pos-(KEYUSE*) keyuse->buffer);
    VOID(set_dynamic(keyuse,(gptr) &end,i));
    keyuse->elements=i;
  }
  return FALSE;
}

2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626
/*
  Update some values in keyuse for faster find_best_combination() loop
*/

static void optimize_keyuse(JOIN *join, DYNAMIC_ARRAY *keyuse_array)
{
  KEYUSE *end,*keyuse= dynamic_element(keyuse_array, 0, KEYUSE*);

  for (end= keyuse+ keyuse_array->elements ; keyuse < end ; keyuse++)
  {
    table_map map;
    /*
      If we find a ref, assume this table matches a proportional
      part of this table.
      For example 100 records matching a table with 5000 records
      gives 5000/100 = 50 records per key
      Constant tables are ignored.
      To avoid bad matches, we don't make ref_table_rows less than 100.
    */
serg@serg.mylan's avatar
serg@serg.mylan committed
2627
    keyuse->ref_table_rows= ~(ha_rows) 0;	// If no ref
2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639
    if (keyuse->used_tables &
	(map= (keyuse->used_tables & ~join->const_table_map &
	       ~OUTER_REF_TABLE_BIT)))
    {
      uint tablenr;
      for (tablenr=0 ; ! (map & 1) ; map>>=1, tablenr++) ;
      if (map == 1)			// Only one table
      {
	TABLE *tmp_table=join->all_tables[tablenr];
	keyuse->ref_table_rows= max(tmp_table->file->records, 100);
      }
    }
2640 2641 2642 2643 2644 2645
    /*
      Outer reference (external field) is constant for single executing
      of subquery
    */
    if (keyuse->used_tables == OUTER_REF_TABLE_BIT)
      keyuse->ref_table_rows= 1;
2646 2647 2648
  }
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2649 2650

/*****************************************************************************
2651 2652
  Go through all combinations of not marked tables and find the one
  which uses least records
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666
*****************************************************************************/

/* Save const tables first as used tables */

static void
set_position(JOIN *join,uint idx,JOIN_TAB *table,KEYUSE *key)
{
  join->positions[idx].table= table;
  join->positions[idx].key=key;
  join->positions[idx].records_read=1.0;	/* This is a const table */

  /* Move the const table as down as possible in best_ref */
  JOIN_TAB **pos=join->best_ref+idx+1;
  JOIN_TAB *next=join->best_ref[idx];
2667
  for (;next != table ; pos++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690
  {
    JOIN_TAB *tmp=pos[0];
    pos[0]=next;
    next=tmp;
  }
  join->best_ref[idx]=table;
}


static void
find_best_combination(JOIN *join, table_map rest_tables)
{
  DBUG_ENTER("find_best_combination");
  join->best_read=DBL_MAX;
  find_best(join,rest_tables, join->const_tables,1.0,0.0);
  DBUG_VOID_RETURN;
}


static void
find_best(JOIN *join,table_map rest_tables,uint idx,double record_count,
	  double read_time)
{
2691
  ha_rows rec;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2692
  double tmp;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2693
  THD *thd= join->thd;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2694 2695 2696 2697 2698 2699 2700 2701

  if (!rest_tables)
  {
    DBUG_PRINT("best",("read_time: %g  record_count: %g",read_time,
		       record_count));

    read_time+=record_count/(double) TIME_FOR_COMPARE;
    if (join->sort_by_table &&
2702 2703
	join->sort_by_table !=
	join->positions[join->const_tables].table->table)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725
      read_time+=record_count;			// We have to make a temp table
    if (read_time < join->best_read)
    {
      memcpy((gptr) join->best_positions,(gptr) join->positions,
	     sizeof(POSITION)*idx);
      join->best_read=read_time;
    }
    return;
  }
  if (read_time+record_count/(double) TIME_FOR_COMPARE >= join->best_read)
    return;					/* Found better before */

  JOIN_TAB *s;
  double best_record_count=DBL_MAX,best_read_time=DBL_MAX;
  for (JOIN_TAB **pos=join->best_ref+idx ; (s=*pos) ; pos++)
  {
    table_map real_table_bit=s->table->map;
    if ((rest_tables & real_table_bit) && !(rest_tables & s->dependent))
    {
      double best,best_time,records;
      best=best_time=records=DBL_MAX;
      KEYUSE *best_key=0;
2726
      uint best_max_key_part=0;
2727
      my_bool found_constraint= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2728 2729 2730 2731 2732 2733

      if (s->keyuse)
      {						/* Use key if possible */
	TABLE *table=s->table;
	KEYUSE *keyuse,*start_key=0;
	double best_records=DBL_MAX;
2734
	uint max_key_part=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2735 2736

	/* Test how we can use keys */
2737
	rec= s->records/MATCHING_ROWS_IN_OTHER_TABLE;  // Assumed records/key
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2738 2739
	for (keyuse=s->keyuse ; keyuse->table == table ;)
	{
2740
	  key_part_map found_part=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2741 2742 2743 2744
	  table_map found_ref=0;
	  uint key=keyuse->key;
	  KEY *keyinfo=table->key_info+key;
          bool ft_key=(keyuse->keypart == FT_KEYPART);
2745
	  uint found_ref_or_null= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2746

2747
	  /* Calculate how many key segments of the current key we can use */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2748 2749 2750 2751
	  start_key=keyuse;
	  do
	  {
            uint keypart=keyuse->keypart;
monty@mysql.com's avatar
monty@mysql.com committed
2752 2753
            table_map best_part_found_ref= 0;
            double best_prev_record_reads= DBL_MAX;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2754 2755
	    do
	    {
2756 2757 2758 2759
	      if (!(rest_tables & keyuse->used_tables) &&
		  !(found_ref_or_null & keyuse->optimize))
	      {
		found_part|=keyuse->keypart_map;
monty@mysql.com's avatar
monty@mysql.com committed
2760 2761 2762 2763 2764 2765 2766 2767
                double tmp= prev_record_reads(join,
					      (found_ref |
					       keyuse->used_tables));
                if (tmp < best_prev_record_reads)
                {
                  best_part_found_ref= keyuse->used_tables;
                  best_prev_record_reads= tmp;
                }
2768 2769
		if (rec > keyuse->ref_table_rows)
		  rec= keyuse->ref_table_rows;
monty@mysql.com's avatar
monty@mysql.com committed
2770 2771
		/*
		  If there is one 'key_column IS NULL' expression, we can
2772
		  use this ref_or_null optimisation of this field
monty@mysql.com's avatar
monty@mysql.com committed
2773 2774 2775
		*/
		found_ref_or_null|= (keyuse->optimize &
				     KEY_OPTIMIZE_REF_OR_NULL);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2776 2777 2778 2779
              }
	      keyuse++;
	    } while (keyuse->table == table && keyuse->key == key &&
		     keyuse->keypart == keypart);
monty@mysql.com's avatar
monty@mysql.com committed
2780
	    found_ref|= best_part_found_ref;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2781 2782 2783
	  } while (keyuse->table == table && keyuse->key == key);

	  /*
2784
	    Assume that that each key matches a proportional part of table.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2785 2786 2787
	  */
          if (!found_part && !ft_key)
	    continue;				// Nothing usable found
2788 2789
	  if (rec < MATCHING_ROWS_IN_OTHER_TABLE)
	    rec= MATCHING_ROWS_IN_OTHER_TABLE;	// Fix for small tables
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2790 2791

          /*
2792
	    ft-keys require special treatment
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2793 2794 2795 2796
          */
          if (ft_key)
          {
            /*
2797 2798
	      Really, there should be records=0.0 (yes!)
	      but 1.0 would be probably safer
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2799 2800 2801 2802 2803 2804
            */
            tmp=prev_record_reads(join,found_ref);
            records=1.0;
          }
          else
          {
2805
	  found_constraint= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2806
	  /*
2807
	    Check if we found full key
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2808
	  */
2809 2810
	  if (found_part == PREV_BITS(uint,keyinfo->key_parts) &&
	      !found_ref_or_null)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2811
	  {				/* use eq key */
2812
	    max_key_part= (uint) ~0;
2813 2814
	    if ((keyinfo->flags & (HA_NOSAME | HA_NULL_PART_KEY |
				   HA_END_SPACE_KEY)) == HA_NOSAME)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2815 2816 2817 2818 2819 2820
	    {
	      tmp=prev_record_reads(join,found_ref);
	      records=1.0;
	    }
	    else
	    {
2821 2822
	      if (!found_ref)
	      {					// We found a const key
2823
		if (table->quick_keys.is_set(key))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2824 2825
		  records= (double) table->quick_rows[key];
		else
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2826 2827 2828 2829
		{
		  /* quick_range couldn't use key! */
		  records= (double) s->records/rec;
		}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843
	      }
	      else
	      {
		if (!(records=keyinfo->rec_per_key[keyinfo->key_parts-1]))
		{				// Prefere longer keys
		  records=
		    ((double) s->records / (double) rec *
		     (1.0 +
		      ((double) (table->max_key_length-keyinfo->key_length) /
		       (double) table->max_key_length)));
		  if (records < 2.0)
		    records=2.0;		// Can't be as good as a unique
		}
	      }
2844 2845 2846
	      /* Limit the number of matched rows */
	      tmp= records;
	      set_if_smaller(tmp, (double) thd->variables.max_seeks_for_key);
2847
	      if (table->used_keys.is_set(key))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2848 2849 2850
	      {
		/* we can use only index tree */
		uint keys_per_block= table->file->block_size/2/
2851
		  (keyinfo->key_length+table->file->ref_length)+1;
2852
		tmp=record_count*(tmp+keys_per_block-1)/keys_per_block;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2853 2854
	      }
	      else
2855
		tmp=record_count*min(tmp,s->worst_seeks);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2856 2857 2858 2859 2860
	    }
	  }
	  else
	  {
	    /*
2861 2862 2863
	      Use as much key-parts as possible and a uniq key is better
	      than a not unique key
	      Set tmp to (previous record count) * (records / combination)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2864
	    */
2865
	    if ((found_part & 1) &&
2866
		(!(table->file->index_flags(key,0,0) & HA_ONLY_WHOLE_INDEX) ||
2867
		 found_part == PREV_BITS(uint,keyinfo->key_parts)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2868
	    {
2869
	      max_key_part=max_part_bit(found_part);
2870 2871 2872 2873
	      /*
		Check if quick_range could determinate how many rows we
		will match
	      */
2874
	      if (table->quick_keys.is_set(key) &&
2875
		  table->quick_key_parts[key] == max_key_part)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2876 2877 2878 2879 2880 2881 2882 2883 2884
		tmp=records= (double) table->quick_rows[key];
	      else
	      {
		/* Check if we have statistic about the distribution */
		if ((records=keyinfo->rec_per_key[max_key_part-1]))
		  tmp=records;
		else
		{
		  /*
2885
		    Assume that the first key part matches 1% of the file
2886
		    and that the hole key matches 10 (duplicates) or 1
2887 2888 2889 2890 2891
		    (unique) records.
		    Assume also that more key matches proportionally more
		    records
		    This gives the formula:
		    records= (x * (b-a) + a*c-b)/(c-1)
2892

2893 2894 2895 2896
		    b = records matched by whole key
		    a = records matched by first key part (10% of all records?)
		    c = number of key parts in key
		    x = used key parts (1 <= x <= c)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2897 2898
		  */
		  double rec_per_key;
2899 2900 2901
                  rec_per_key= keyinfo->rec_per_key[keyinfo->key_parts-1] ?
		    (double) keyinfo->rec_per_key[keyinfo->key_parts-1] :
		    (double) s->records/rec+1;   
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915
		  if (!s->records)
		    tmp=0;
		  else if (rec_per_key/(double) s->records >= 0.01)
		    tmp=rec_per_key;
		  else
		  {
		    double a=s->records*0.01;
		    tmp=(max_key_part * (rec_per_key - a) +
			 a*keyinfo->key_parts - rec_per_key)/
		      (keyinfo->key_parts-1);
		    set_if_bigger(tmp,1.0);
		  }
		  records=(ulong) tmp;
		}
2916 2917 2918 2919
		/*
		  If quick_select was used on a part of this key, we know
		  the maximum number of rows that the key can match.
		*/
monty@mysql.com's avatar
monty@mysql.com committed
2920
		if (table->quick_keys.is_set(key) &&
2921 2922 2923
		    table->quick_key_parts[key] <= max_key_part &&
		    records > (double) table->quick_rows[key])
		  tmp= records= (double) table->quick_rows[key];
monty@mysql.com's avatar
monty@mysql.com committed
2924
		else if (found_ref_or_null)
2925 2926 2927 2928 2929
		{
		  /* We need to do two key searches to find key */
		  tmp*= 2.0;
		  records*= 2.0;
		}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2930
	      }
2931 2932
	      /* Limit the number of matched rows */
	      set_if_smaller(tmp, (double) thd->variables.max_seeks_for_key);
2933
	      if (table->used_keys.is_set(key))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2934 2935 2936
	      {
		/* we can use only index tree */
		uint keys_per_block= table->file->block_size/2/
2937
		  (keyinfo->key_length+table->file->ref_length)+1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2938 2939 2940 2941 2942 2943 2944 2945
		tmp=record_count*(tmp+keys_per_block-1)/keys_per_block;
	      }
	      else
		tmp=record_count*min(tmp,s->worst_seeks);
	    }
	    else
	      tmp=best_time;			// Do nothing
	  }
2946
          } /* not ft_key */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2947 2948 2949 2950 2951 2952
	  if (tmp < best_time - records/(double) TIME_FOR_COMPARE)
	  {
	    best_time=tmp + records/(double) TIME_FOR_COMPARE;
	    best=tmp;
	    best_records=records;
	    best_key=start_key;
2953
	    best_max_key_part=max_key_part;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2954 2955 2956 2957
	  }
	}
	records=best_records;
      }
2958 2959 2960 2961

      /*
	Don't test table scan if it can't be better.
	Prefer key lookup if we would use the same key for scanning.
2962 2963 2964 2965 2966

	Don't do a table scan on InnoDB tables, if we can read the used
	parts of the row from any of the used index.
	This is because table scans uses index and we would not win
	anything by using a table scan.
2967 2968 2969
      */
      if ((records >= s->found_records || best > s->read_time) &&
	  !(s->quick && best_key && s->quick->index == best_key->key &&
2970
	    best_max_key_part >= s->table->quick_key_parts[best_key->key]) &&
2971
	  !((s->table->file->table_flags() & HA_TABLE_SCAN_ON_INDEX) &&
2972
	    ! s->table->used_keys.is_clear_all() && best_key) &&
2973
	  !(s->table->force_index && best_key))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2974
      {						// Check full join
2975 2976 2977 2978 2979 2980 2981 2982 2983 2984
        ha_rows rnd_records= s->found_records;
        /*
          If there is a restriction on the table, assume that 25% of the
          rows can be skipped on next part.
          This is to force tables that this table depends on before this
          table
        */
        if (found_constraint)
          rnd_records-= rnd_records/4;

2985 2986 2987 2988 2989 2990
        /*
          Range optimizer never proposes a RANGE if it isn't better
          than FULL: so if RANGE is present, it's always preferred to FULL.
          Here we estimate its cost.
        */
        if (s->quick)
2991
        {
2992 2993 2994 2995 2996
          /*
            For each record we:
             - read record range through 'quick'
             - skip rows which does not satisfy WHERE constraints
           */
2997
          tmp= record_count *
2998 2999
               (s->quick->read_time +
               (s->found_records - rnd_records)/(double) TIME_FOR_COMPARE);
3000 3001 3002
        }
        else
        {
3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030
          /* Estimate cost of reading table. */
          tmp= s->table->file->scan_time();
          if (s->on_expr)                         // Can't use join cache
          {
            /*
              For each record we have to:
              - read the whole table record 
              - skip rows which does not satisfy join condition
            */
            tmp= record_count *
                 (tmp +     
                 (s->records - rnd_records)/(double) TIME_FOR_COMPARE);
          }
          else
          {
            /* We read the table as many times as join buffer becomes full. */
            tmp*= (1.0 + floor((double) cache_record_length(join,idx) *
                               record_count /
                               (double) thd->variables.join_buff_size));
            /* 
              We don't make full cartesian product between rows in the scanned
              table and existing records because we skip all rows from the
              scanned table, which does not satisfy join condition when 
              we read the table (see flush_cached_records for details). Here we
              take into account cost to read and skip these records.
            */
            tmp+= (s->records - rnd_records)/(double) TIME_FOR_COMPARE;
          }
3031
        }
3032

3033
        /*
3034
          We estimate the cost of evaluating WHERE clause for found records
3035
          as record_count * rnd_records / TIME_FOR_COMPARE. This cost plus
3036
          tmp give us total cost of using TABLE SCAN
3037
        */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3038
	if (best == DBL_MAX ||
3039
	    (tmp  + record_count/(double) TIME_FOR_COMPARE*rnd_records <
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3040 3041
	     best + record_count/(double) TIME_FOR_COMPARE*records))
	{
3042 3043 3044 3045
	  /*
	    If the table has a range (s->quick is set) make_join_select()
	    will ensure that this will be used
	  */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3046
	  best=tmp;
3047
	  records= rows2double(rnd_records);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3048 3049 3050
	  best_key=0;
	}
      }
3051
      join->positions[idx].records_read= records;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3052 3053 3054
      join->positions[idx].key=best_key;
      join->positions[idx].table= s;
      if (!best_key && idx == join->const_tables &&
3055
	  s->table == join->sort_by_table &&
3056
	  join->unit->select_limit_cnt >= records)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075
	join->sort_by_table= (TABLE*) 1;	// Must use temporary table

     /*
	Go to the next level only if there hasn't been a better key on
	this level! This will cut down the search for a lot simple cases!
       */
      double current_record_count=record_count*records;
      double current_read_time=read_time+best;
      if (best_record_count > current_record_count ||
	  best_read_time > current_read_time ||
	  idx == join->const_tables && s->table == join->sort_by_table)
      {
	if (best_record_count >= current_record_count &&
	    best_read_time >= current_read_time &&
	    (!(s->key_dependent & rest_tables) || records < 2.0))
	{
	  best_record_count=current_record_count;
	  best_read_time=current_read_time;
	}
3076
	swap_variables(JOIN_TAB*, join->best_ref[idx], *pos);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3077 3078
	find_best(join,rest_tables & ~real_table_bit,idx+1,
		  current_record_count,current_read_time);
serg@serg.mysql.com's avatar
serg@serg.mysql.com committed
3079 3080
        if (thd->killed)
          return;
3081
	swap_variables(JOIN_TAB*, join->best_ref[idx], *pos);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3082 3083 3084 3085 3086 3087 3088 3089 3090
      }
      if (join->select_options & SELECT_STRAIGHT_JOIN)
	break;				// Don't test all combinations
    }
  }
}


/*
3091
  Find how much space the prevous read not const tables takes in cache
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3092 3093
*/

3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128
static void calc_used_field_length(THD *thd, JOIN_TAB *join_tab)
{
  uint null_fields,blobs,fields,rec_length;
  null_fields=blobs=fields=rec_length=0;

  Field **f_ptr,*field;
  for (f_ptr=join_tab->table->field ; (field= *f_ptr) ; f_ptr++)
  {
    if (field->query_id == thd->query_id)
    {
      uint flags=field->flags;
      fields++;
      rec_length+=field->pack_length();
      if (flags & BLOB_FLAG)
	blobs++;
      if (!(flags & NOT_NULL_FLAG))
	null_fields++;
    }
  }
  if (null_fields)
    rec_length+=(join_tab->table->null_fields+7)/8;
  if (join_tab->table->maybe_null)
    rec_length+=sizeof(my_bool);
  if (blobs)
  {
    uint blob_length=(uint) (join_tab->table->file->mean_rec_length-
			     (join_tab->table->reclength- rec_length));
    rec_length+=(uint) max(4,blob_length);
  }
  join_tab->used_fields=fields;
  join_tab->used_fieldlength=rec_length;
  join_tab->used_blobs=blobs;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
3129 3130 3131
static uint
cache_record_length(JOIN *join,uint idx)
{
3132
  uint length=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3133
  JOIN_TAB **pos,**end;
3134
  THD *thd=join->thd;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3135 3136 3137 3138 3139 3140

  for (pos=join->best_ref+join->const_tables,end=join->best_ref+idx ;
       pos != end ;
       pos++)
  {
    JOIN_TAB *join_tab= *pos;
3141 3142
    if (!join_tab->used_fieldlength)		/* Not calced yet */
      calc_used_field_length(thd, join_tab);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3143 3144 3145 3146 3147 3148 3149 3150 3151 3152
    length+=join_tab->used_fieldlength;
  }
  return length;
}


static double
prev_record_reads(JOIN *join,table_map found_ref)
{
  double found=1.0;
3153
  found_ref&= ~OUTER_REF_TABLE_BIT;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166
  for (POSITION *pos=join->positions ; found_ref ; pos++)
  {
    if (pos->table->table->map & found_ref)
    {
      found_ref&= ~pos->table->table->map;
      found*=pos->records_read;
    }
  }
  return found;
}


/*****************************************************************************
3167
  Set up join struct according to best position.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3168 3169 3170 3171 3172
*****************************************************************************/

static bool
get_best_combination(JOIN *join)
{
3173
  uint i,tablenr;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3174 3175 3176 3177
  table_map used_tables;
  JOIN_TAB *join_tab,*j;
  KEYUSE *keyuse;
  uint table_count;
3178
  THD *thd=join->thd;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3179 3180 3181

  table_count=join->tables;
  if (!(join->join_tab=join_tab=
3182
	(JOIN_TAB*) thd->alloc(sizeof(JOIN_TAB)*table_count)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3183 3184 3185 3186
    return TRUE;

  join->full_join=0;

3187
  used_tables= OUTER_REF_TABLE_BIT;		// Outer row is already read
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3188 3189 3190 3191 3192 3193 3194 3195 3196
  for (j=join_tab, tablenr=0 ; tablenr < table_count ; tablenr++,j++)
  {
    TABLE *form;
    *j= *join->best_positions[tablenr].table;
    form=join->table[tablenr]=j->table;
    used_tables|= form->map;
    form->reginfo.join_tab=j;
    if (!j->on_expr)
      form->reginfo.not_exists_optimize=0;	// Only with LEFT JOIN
3197 3198 3199 3200 3201
    if (j->type == JT_CONST)
      continue;					// Handled in make_join_stat..

    j->ref.key = -1;
    j->ref.key_parts=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3202 3203 3204

    if (j->type == JT_SYSTEM)
      continue;
3205
    if (j->keys.is_clear_all() || !(keyuse= join->best_positions[tablenr].key))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3206 3207 3208 3209 3210
    {
      j->type=JT_ALL;
      if (tablenr != join->const_tables)
	join->full_join=1;
    }
3211 3212 3213
    else if (create_ref_for_key(join, j, keyuse, used_tables))
      return TRUE;				// Something went wrong
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3214

3215 3216 3217 3218 3219
  for (i=0 ; i < table_count ; i++)
    join->map2table[join->join_tab[i].table->tablenr]=join->join_tab+i;
  update_depend_map(join);
  return 0;
}
3220

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3221

3222 3223 3224 3225 3226 3227 3228 3229 3230
static bool create_ref_for_key(JOIN *join, JOIN_TAB *j, KEYUSE *org_keyuse,
			       table_map used_tables)
{
  KEYUSE *keyuse=org_keyuse;
  bool ftkey=(keyuse->keypart == FT_KEYPART);
  THD  *thd= join->thd;
  uint keyparts,length,key;
  TABLE *table;
  KEY *keyinfo;
3231

3232
  /*  Use best key from find_best */
3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247
  table=j->table;
  key=keyuse->key;
  keyinfo=table->key_info+key;

  if (ftkey)
  {
    Item_func_match *ifm=(Item_func_match *)keyuse->val;

    length=0;
    keyparts=1;
    ifm->join_key=1;
  }
  else
  {
    keyparts=length=0;
3248 3249 3250 3251 3252 3253
    uint found_part_ref_or_null= 0;
    /*
      Calculate length for the used key
      Stop if there is a missing key part or when we find second key_part
      with KEY_OPTIMIZE_REF_OR_NULL
    */
3254 3255
    do
    {
3256
      if (!(~used_tables & keyuse->used_tables))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3257
      {
3258 3259
	if (keyparts == keyuse->keypart &&
	    !(found_part_ref_or_null & keyuse->optimize))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3260
	{
3261
	  keyparts++;
3262 3263
	  length+= keyinfo->key_part[keyuse->keypart].store_length;
	  found_part_ref_or_null|= keyuse->optimize;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3264 3265
	}
      }
3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283
      keyuse++;
    } while (keyuse->table == table && keyuse->key == key);
  } /* not ftkey */

  /* set up fieldref */
  keyinfo=table->key_info+key;
  j->ref.key_parts=keyparts;
  j->ref.key_length=length;
  j->ref.key=(int) key;
  if (!(j->ref.key_buff= (byte*) thd->calloc(ALIGN_SIZE(length)*2)) ||
      !(j->ref.key_copy= (store_key**) thd->alloc((sizeof(store_key*) *
						   (keyparts+1)))) ||
      !(j->ref.items=    (Item**) thd->alloc(sizeof(Item*)*keyparts)))
  {
    return TRUE;
  }
  j->ref.key_buff2=j->ref.key_buff+ALIGN_SIZE(length);
  j->ref.key_err=1;
3284
  j->ref.null_rejecting= 0;
3285 3286
  keyuse=org_keyuse;

3287 3288
  store_key **ref_key= j->ref.key_copy;
  byte *key_buff=j->ref.key_buff, *null_ref_key= 0;
3289
  bool keyuse_uses_no_tables= TRUE;
3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308
  if (ftkey)
  {
    j->ref.items[0]=((Item_func*)(keyuse->val))->key_item();
    if (keyuse->used_tables)
      return TRUE; // not supported yet. SerG

    j->type=JT_FT;
  }
  else
  {
    uint i;
    for (i=0 ; i < keyparts ; keyuse++,i++)
    {
      while (keyuse->keypart != i ||
	     ((~used_tables) & keyuse->used_tables))
	keyuse++;				/* Skip other parts */

      uint maybe_null= test(keyinfo->key_part[i].null_bit);
      j->ref.items[i]=keyuse->val;		// Save for cond removal
3309 3310
      if (keyuse->null_rejecting) 
        j->ref.null_rejecting |= 1 << i;
3311
      keyuse_uses_no_tables= keyuse_uses_no_tables && !keyuse->used_tables;
3312 3313 3314
      if (!keyuse->used_tables &&
	  !(join->select_options & SELECT_DESCRIBE))
      {					// Compare against constant
serg@serg.mysql.com's avatar
serg@serg.mysql.com committed
3315 3316 3317 3318
	store_key_item tmp(thd, keyinfo->key_part[i].field,
                           (char*)key_buff + maybe_null,
                           maybe_null ?  (char*) key_buff : 0,
                           keyinfo->key_part[i].length, keyuse->val);
3319
	if (thd->is_fatal_error)
3320
	  return TRUE;
serg@serg.mysql.com's avatar
serg@serg.mysql.com committed
3321
	tmp.copy();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3322 3323
      }
      else
3324 3325 3326 3327
	*ref_key++= get_store_key(thd,
				  keyuse,join->const_table_map,
				  &keyinfo->key_part[i],
				  (char*) key_buff,maybe_null);
3328
      /*
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3329
	Remeber if we are going to use REF_OR_NULL
3330 3331 3332
	But only if field _really_ can be null i.e. we force JT_REF
	instead of JT_REF_OR_NULL in case if field can't be null
      */
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3333
      if ((keyuse->optimize & KEY_OPTIMIZE_REF_OR_NULL) && maybe_null)
3334
	null_ref_key= key_buff;
3335
      key_buff+=keyinfo->key_part[i].store_length;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3336
    }
3337 3338
  } /* not ftkey */
  *ref_key=0;				// end_marker
3339 3340 3341 3342
  if (j->type == JT_FT)
    return 0;
  if (j->type == JT_CONST)
    j->table->const_table= 1;
3343
  else if (((keyinfo->flags & (HA_NOSAME | HA_NULL_PART_KEY |
monty@mysql.com's avatar
monty@mysql.com committed
3344
			       HA_END_SPACE_KEY)) != HA_NOSAME) ||
monty@mysql.com's avatar
monty@mysql.com committed
3345
	   keyparts != keyinfo->key_parts || null_ref_key)
3346 3347 3348
  {
    /* Must read with repeat */
    j->type= null_ref_key ? JT_REF_OR_NULL : JT_REF;
3349
    j->ref.null_ref_key= null_ref_key;
3350
  }
sergefp@mysql.com's avatar
sergefp@mysql.com committed
3351
  else if (keyuse_uses_no_tables)
3352
  {
3353 3354 3355 3356 3357 3358 3359 3360
    /*
      This happen if we are using a constant expression in the ON part
      of an LEFT JOIN.
      SELECT * FROM a LEFT JOIN b ON b.key=30
      Here we should not mark the table as a 'const' as a field may
      have a 'normal' value or a NULL value.
    */
    j->type=JT_CONST;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3361
  }
3362 3363
  else
    j->type=JT_EQ_REF;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3364 3365 3366 3367
  return 0;
}


3368

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3369
static store_key *
3370 3371
get_store_key(THD *thd, KEYUSE *keyuse, table_map used_tables,
	      KEY_PART_INFO *key_part, char *key_buff, uint maybe_null)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3372 3373 3374
{
  if (!((~used_tables) & keyuse->used_tables))		// if const item
  {
3375 3376
    return new store_key_const_item(thd,
				    key_part->field,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3377 3378 3379 3380 3381 3382
				    key_buff + maybe_null,
				    maybe_null ? key_buff : 0,
				    key_part->length,
				    keyuse->val);
  }
  else if (keyuse->val->type() == Item::FIELD_ITEM)
3383 3384
    return new store_key_field(thd,
			       key_part->field,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3385 3386 3387 3388 3389
			       key_buff + maybe_null,
			       maybe_null ? key_buff : 0,
			       key_part->length,
			       ((Item_field*) keyuse->val)->field,
			       keyuse->val->full_name());
3390 3391
  return new store_key_item(thd,
			    key_part->field,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3392 3393 3394 3395 3396 3397 3398
			    key_buff + maybe_null,
			    maybe_null ? key_buff : 0,
			    key_part->length,
			    keyuse->val);
}

/*
3399 3400
  This function is only called for const items on fields which are keys
  returns 1 if there was some conversion made when the field was stored.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3401 3402 3403 3404 3405
*/

bool
store_val_in_field(Field *field,Item *item)
{
3406
  bool error;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3407
  THD *thd=current_thd;
3408
  ha_rows cuted_fields=thd->cuted_fields;
3409 3410 3411 3412 3413
  /*
    we should restore old value of count_cuted_fields because
    store_val_in_field can be called from mysql_insert 
    with select_insert, which make count_cuted_fields= 1
   */
monty@mysql.com's avatar
monty@mysql.com committed
3414
  enum_check_fields old_count_cuted_fields= thd->count_cuted_fields;
3415
  thd->count_cuted_fields= CHECK_FIELD_WARN;
3416
  error= item->save_in_field(field, 1);
3417
  thd->count_cuted_fields= old_count_cuted_fields;
3418
  return error || cuted_fields != thd->cuted_fields;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3419 3420 3421 3422 3423 3424 3425 3426 3427
}


static bool
make_simple_join(JOIN *join,TABLE *tmp_table)
{
  TABLE **tableptr;
  JOIN_TAB *join_tab;

3428 3429
  if (!(tableptr=(TABLE**) join->thd->alloc(sizeof(TABLE*))) ||
      !(join_tab=(JOIN_TAB*) join->thd->alloc(sizeof(JOIN_TAB))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3430 3431 3432 3433 3434 3435
    return TRUE;
  join->join_tab=join_tab;
  join->table=tableptr; tableptr[0]=tmp_table;
  join->tables=1;
  join->const_tables=0;
  join->const_table_map=0;
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
3436 3437 3438
  join->tmp_table_param.field_count= join->tmp_table_param.sum_func_count=
    join->tmp_table_param.func_count=0;
  join->tmp_table_param.copy_field=join->tmp_table_param.copy_field_end=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3439
  join->first_record=join->sort_and_group=0;
monty@tramp.mysql.fi's avatar
monty@tramp.mysql.fi committed
3440
  join->send_records=(ha_rows) 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3441
  join->group=0;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3442
  join->row_limit=join->unit->select_limit_cnt;
3443
  join->do_send_rows = (join->row_limit) ? 1 : 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3444

serg@serg.mylan's avatar
serg@serg.mylan committed
3445
  join_tab->cache.buff=0;			/* No caching */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3446 3447 3448 3449 3450
  join_tab->table=tmp_table;
  join_tab->select=0;
  join_tab->select_cond=0;
  join_tab->quick=0;
  join_tab->type= JT_ALL;			/* Map through all records */
3451 3452
  join_tab->keys.init();
  join_tab->keys.set_all();                     /* test everything in quick */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3453 3454 3455
  join_tab->info=0;
  join_tab->on_expr=0;
  join_tab->ref.key = -1;
monty@tramp.mysql.fi's avatar
monty@tramp.mysql.fi committed
3456 3457
  join_tab->not_used_in_distinct=0;
  join_tab->read_first_record= join_init_read_record;
3458
  join_tab->join=join;
monty@tramp.mysql.fi's avatar
monty@tramp.mysql.fi committed
3459
  bzero((char*) &join_tab->read_record,sizeof(join_tab->read_record));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3460 3461 3462 3463 3464 3465
  tmp_table->status=0;
  tmp_table->null_row=0;
  return FALSE;
}


3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535
inline void add_cond_and_fix(Item **e1, Item *e2)
{
  if (*e1)
  {
    Item *res;
    if ((res= new Item_cond_and(*e1, e2)))
    {
      *e1= res;
      res->quick_fix_field();
    }
  }
  else
    *e1= e2;
}


/*
  Add to join_tab->select_cond[i] "table.field IS NOT NULL" conditions we've
  inferred from ref/eq_ref access performed.

  SYNOPSIS
    add_not_null_conds()
      join  Join to process

  NOTES
    This function is a part of "Early NULL-values filtering for ref access"
    optimization.

    Example of this optimization:
      For query SELECT * FROM t1,t2 WHERE t2.key=t1.field
      and plan " any-access(t1), ref(t2.key=t1.field) "
      add "t1.field IS NOT NULL" to t1's table condition.
    Description of the optimization:
    
      We look through equalities choosen to perform ref/eq_ref access,
      pick equalities that have form "tbl.part_of_key = othertbl.field"
      (where othertbl is a non-const table and othertbl.field may be NULL)
      and add them to conditions on correspoding tables (othertbl in this
      example).
      
      This optimization doesn't affect the choices that ref, range, or join
      optimizer make. This was intentional because this was added after 4.1
      was GA.
      
    Implementation overview
      1. update_ref_and_keys() accumulates info about null-rejecting
         predicates in in KEY_FIELD::null_rejecting
      1.1 add_key_part saves these to KEYUSE.
      2. create_ref_for_key copies them to TABLE_REF.
      3. add_not_null_conds adds "x IS NOT NULL" to join_tab->select_cond of
         appropiate JOIN_TAB members.
*/

static void add_not_null_conds(JOIN *join)
{
  DBUG_ENTER("add_not_null_conds");
  for (uint i=join->const_tables ; i < join->tables ; i++)
  {
    JOIN_TAB *tab=join->join_tab+i;
    if ((tab->type == JT_REF || tab->type == JT_REF_OR_NULL) &&
         !tab->table->maybe_null)
    {
      for (uint keypart= 0; keypart < tab->ref.key_parts; keypart++)
      {
        if (tab->ref.null_rejecting & (1 << keypart))
        {
          Item *item= tab->ref.items[keypart];
          DBUG_ASSERT(item->type() == Item::FIELD_ITEM);
          Item_field *not_null_item= (Item_field*)item;
          JOIN_TAB *referred_tab= not_null_item->field->table->reginfo.join_tab;
3536 3537
          Item_func_isnotnull *notnull;
          if (!(notnull= new Item_func_isnotnull(not_null_item)))
3538 3539
            DBUG_VOID_RETURN;

3540 3541
          notnull->quick_fix_field();
          DBUG_EXECUTE("where",print_where(notnull,
3542
                                           referred_tab->table->table_name););
3543
          add_cond_and_fix(&referred_tab->select_cond, notnull);
3544 3545 3546 3547 3548 3549 3550
        }
      }
    }
  }
  DBUG_VOID_RETURN;
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3551 3552 3553 3554 3555 3556
static bool
make_join_select(JOIN *join,SQL_SELECT *select,COND *cond)
{
  DBUG_ENTER("make_join_select");
  if (select)
  {
3557
    add_not_null_conds(join);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3558 3559 3560
    table_map used_tables;
    if (join->tables > 1)
      cond->update_used_tables();		// Tablenr may have changed
3561 3562 3563
    if (join->const_tables == join->tables &&
	join->thd->lex->current_select->master_unit() ==
	&join->thd->lex->unit)		// not upper level SELECT
3564
      join->const_table_map|=RAND_TABLE_BIT;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3565 3566 3567 3568 3569
    {						// Check const tables
      COND *const_cond=
	make_cond_for_table(cond,join->const_table_map,(table_map) 0);
      DBUG_EXECUTE("where",print_where(const_cond,"constants"););
      if (const_cond && !const_cond->val_int())
3570 3571
      {
	DBUG_PRINT("info",("Found impossible WHERE condition"));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3572
	DBUG_RETURN(1);				// Impossible const condition
3573
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3574
    }
3575 3576
    used_tables=((select->const_tables=join->const_table_map) |
		 OUTER_REF_TABLE_BIT | RAND_TABLE_BIT);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3577 3578 3579 3580
    for (uint i=join->const_tables ; i < join->tables ; i++)
    {
      JOIN_TAB *tab=join->join_tab+i;
      table_map current_map= tab->table->map;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3581 3582 3583 3584
      /*
	Following force including random expression in last table condition.
	It solve problem with select like SELECT * FROM t1 WHERE rand() > 0.5
      */
3585
      if (i == join->tables-1)
3586
	current_map|= OUTER_REF_TABLE_BIT | RAND_TABLE_BIT;
3587
      bool use_quick_range=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3588
      used_tables|=current_map;
3589 3590

      if (tab->type == JT_REF && tab->quick &&
3591
	  (uint) tab->ref.key == tab->quick->index &&
3592 3593 3594 3595 3596 3597
	  tab->ref.key_length < tab->quick->max_used_key_length)
      {
	/* Range uses longer key;  Use this instead of ref on key */
	tab->type=JT_ALL;
	use_quick_range=1;
	tab->use_quick=1;
3598
        tab->ref.key= -1;
3599
	tab->ref.key_parts=0;		// Don't use ref key.
3600
	join->best_positions[i].records_read= rows2double(tab->quick->records);
3601 3602
      }

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3603
      COND *tmp=make_cond_for_table(cond,used_tables,current_map);
3604 3605 3606 3607 3608 3609 3610 3611
      if (!tmp && tab->quick)
      {						// Outer join
	/*
	  Hack to handle the case where we only refer to a table
	  in the ON part of an OUTER JOIN.
	*/
	tmp=new Item_int((longlong) 1,1);	// Always true
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3612 3613 3614
      if (tmp)
      {
	SQL_SELECT *sel=tab->select=(SQL_SELECT*)
3615
	  join->thd->memdup((gptr) select, sizeof(SQL_SELECT));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3616 3617
	if (!sel)
	  DBUG_RETURN(1);			// End of memory
3618 3619
        add_cond_and_fix(&tab->select_cond, tmp);
        sel->cond= tab->select_cond;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3620
	sel->head=tab->table;
3621
	DBUG_EXECUTE("where",print_where(tmp,tab->table->table_name););
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3622 3623
	if (tab->quick)
	{
3624 3625
	  /* Use quick key read if it's a constant and it's not used
	     with key reading */
3626
	  if (tab->needed_reg.is_clear_all() && tab->type != JT_EQ_REF
3627
	      && tab->type != JT_FT && (tab->type != JT_REF ||
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3628 3629 3630
	       (uint) tab->ref.key == tab->quick->index))
	  {
	    sel->quick=tab->quick;		// Use value from get_quick_...
3631 3632
	    sel->quick_keys.clear_all();
	    sel->needed_reg.clear_all();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3633 3634 3635 3636 3637 3638 3639 3640 3641 3642
	  }
	  else
	  {
	    delete tab->quick;
	  }
	  tab->quick=0;
	}
	uint ref_key=(uint) sel->head->reginfo.join_tab->ref.key+1;
	if (i == join->const_tables && ref_key)
	{
3643 3644
	  if (!tab->const_keys.is_clear_all() &&
              tab->table->reginfo.impossible_range)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3645 3646
	    DBUG_RETURN(1);
	}
3647
	else if (tab->type == JT_ALL && ! use_quick_range)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3648
	{
3649
	  if (!tab->const_keys.is_clear_all() &&
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3650 3651 3652 3653
	      tab->table->reginfo.impossible_range)
	    DBUG_RETURN(1);				// Impossible range
	  /*
	    We plan to scan all rows.
3654 3655 3656
	    Check again if we should use an index.
	    We could have used an column from a previous table in
	    the index if we are using limit and this is the first table
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3657 3658
	  */

3659 3660 3661
	  if ((!tab->keys.is_subset(tab->const_keys) && i > 0) ||
	      (!tab->const_keys.is_clear_all() && i == join->const_tables &&
	       join->unit->select_limit_cnt <
3662
	       join->best_positions[i].records_read &&
3663
	       !(join->select_options & OPTION_FOUND_ROWS)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3664
	  {
3665 3666
	    /* Join with outer join condition */
	    COND *orig_cond=sel->cond;
3667
	    sel->cond= and_conds(sel->cond, tab->on_expr);
3668 3669 3670 3671 3672 3673 3674 3675

	    /*
              We can't call sel->cond->fix_fields,
              as it will break tab->on_expr if it's AND condition
              (fix_fields currently removes extra AND/OR levels).
              Yet attributes of the just built condition are not needed.
              Thus we call sel->cond->quick_fix_field for safety.
	    */
3676
	    if (sel->cond && !sel->cond->fixed)
3677 3678
	      sel->cond->quick_fix_field();

3679
	    if (sel->test_quick_select(join->thd, tab->keys,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3680
				       used_tables & ~ current_map,
3681 3682 3683
				       (join->select_options &
					OPTION_FOUND_ROWS ?
					HA_POS_ERROR :
3684
					join->unit->select_limit_cnt), 0) < 0)
3685 3686 3687 3688 3689
            {
	      /*
		Before reporting "Impossible WHERE" for the whole query
		we have to check isn't it only "impossible ON" instead
	      */
3690 3691
              sel->cond=orig_cond;
              if (!tab->on_expr ||
3692
                  sel->test_quick_select(join->thd, tab->keys,
3693 3694 3695 3696
                                         used_tables & ~ current_map,
                                         (join->select_options &
                                          OPTION_FOUND_ROWS ?
                                          HA_POS_ERROR :
3697
                                          join->unit->select_limit_cnt),0) < 0)
3698
		DBUG_RETURN(1);			// Impossible WHERE
3699 3700 3701 3702
            }
            else
	      sel->cond=orig_cond;

3703 3704 3705
	    /* Fix for EXPLAIN */
	    if (sel->quick)
	      join->best_positions[i].records_read= sel->quick->records;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3706 3707 3708 3709
	  }
	  else
	  {
	    sel->needed_reg=tab->needed_reg;
3710
	    sel->quick_keys.clear_all();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3711
	  }
3712 3713
	  if (!sel->quick_keys.is_subset(tab->checked_keys) ||
              !sel->needed_reg.is_subset(tab->checked_keys))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3714
	  {
3715 3716 3717 3718
	    tab->keys=sel->quick_keys;
            tab->keys.merge(sel->needed_reg);
	    tab->use_quick= (!sel->needed_reg.is_clear_all() &&
			     (select->quick_keys.is_clear_all() ||
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3719 3720 3721
			      (select->quick &&
			       (select->quick->records >= 100L)))) ?
	      2 : 1;
hf@deer.(none)'s avatar
hf@deer.(none) committed
3722
	    sel->read_tables= used_tables & ~current_map;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3723 3724 3725 3726 3727 3728 3729 3730 3731
	  }
	  if (i != join->const_tables && tab->use_quick != 2)
	  {					/* Read with cache */
	    if ((tmp=make_cond_for_table(cond,
					 join->const_table_map |
					 current_map,
					 current_map)))
	    {
	      DBUG_EXECUTE("where",print_where(tmp,"cache"););
3732 3733
	      tab->cache.select=(SQL_SELECT*)
		join->thd->memdup((gptr) sel, sizeof(SQL_SELECT));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746
	      tab->cache.select->cond=tmp;
	      tab->cache.select->read_tables=join->const_table_map;
	    }
	  }
	}
      }
    }
  }
  DBUG_RETURN(0);
}


static void
3747
make_join_readinfo(JOIN *join, uint options)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3748 3749
{
  uint i;
3750
  bool statistics= test(!(join->select_options & SELECT_DESCRIBE));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769
  DBUG_ENTER("make_join_readinfo");

  for (i=join->const_tables ; i < join->tables ; i++)
  {
    JOIN_TAB *tab=join->join_tab+i;
    TABLE *table=tab->table;
    tab->read_record.table= table;
    tab->read_record.file=table->file;
    tab->next_select=sub_select;		/* normal select */
    switch (tab->type) {
    case JT_SYSTEM:				// Only happens with left join
      table->status=STATUS_NO_RECORD;
      tab->read_first_record= join_read_system;
      tab->read_record.read_record= join_no_more_records;
      break;
    case JT_CONST:				// Only happens with left join
      table->status=STATUS_NO_RECORD;
      tab->read_first_record= join_read_const;
      tab->read_record.read_record= join_no_more_records;
3770
      if (table->used_keys.is_set(tab->ref.key) &&
3771 3772 3773 3774 3775
          !table->no_keyread)
      {
        table->key_read=1;
        table->file->extra(HA_EXTRA_KEYREAD);
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3776 3777 3778
      break;
    case JT_EQ_REF:
      table->status=STATUS_NO_RECORD;
3779 3780 3781 3782 3783
      if (tab->select)
      {
	delete tab->select->quick;
	tab->select->quick=0;
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3784 3785 3786 3787
      delete tab->quick;
      tab->quick=0;
      tab->read_first_record= join_read_key;
      tab->read_record.read_record= join_no_more_records;
3788
      if (table->used_keys.is_set(tab->ref.key) &&
3789
	  !table->no_keyread)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3790 3791 3792 3793 3794
      {
	table->key_read=1;
	table->file->extra(HA_EXTRA_KEYREAD);
      }
      break;
3795
    case JT_REF_OR_NULL:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3796 3797
    case JT_REF:
      table->status=STATUS_NO_RECORD;
3798 3799 3800 3801 3802
      if (tab->select)
      {
	delete tab->select->quick;
	tab->select->quick=0;
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3803 3804
      delete tab->quick;
      tab->quick=0;
3805
      if (table->used_keys.is_set(tab->ref.key) &&
3806
	  !table->no_keyread)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3807 3808 3809 3810
      {
	table->key_read=1;
	table->file->extra(HA_EXTRA_KEYREAD);
      }
3811 3812 3813 3814 3815 3816 3817 3818 3819 3820
      if (tab->type == JT_REF)
      {
	tab->read_first_record= join_read_always_key;
	tab->read_record.read_record= join_read_next_same;
      }
      else
      {
	tab->read_first_record= join_read_always_key_or_null;
	tab->read_record.read_record= join_read_next_same_or_null;
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3821 3822 3823 3824 3825 3826 3827 3828
      break;
    case JT_FT:
      table->status=STATUS_NO_RECORD;
      tab->read_first_record= join_ft_read_first;
      tab->read_record.read_record= join_ft_read_next;
      break;
    case JT_ALL:
      /*
3829
	If previous table use cache
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3830 3831
      */
      table->status=STATUS_NO_RECORD;
3832
      if (i != join->const_tables && !(options & SELECT_NO_JOIN_CACHE) &&
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843
	  tab->use_quick != 2 && !tab->on_expr)
      {
	if ((options & SELECT_DESCRIBE) ||
	    !join_init_cache(join->thd,join->join_tab+join->const_tables,
			     i-join->const_tables))
	{
	  tab[-1].next_select=sub_select_cache; /* Patch previous */
	}
      }
      /* These init changes read_record */
      if (tab->use_quick == 2)
3844
      {
3845
	join->thd->server_status|=SERVER_QUERY_NO_GOOD_INDEX_USED;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3846
	tab->read_first_record= join_init_quick_read_record;
3847 3848
	if (statistics)
	  statistic_increment(select_range_check_count, &LOCK_status);
3849
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3850 3851 3852
      else
      {
	tab->read_first_record= join_init_read_record;
3853 3854 3855 3856
	if (i == join->const_tables)
	{
	  if (tab->select && tab->select->quick)
	  {
3857 3858
	    if (statistics)
	      statistic_increment(select_range_count, &LOCK_status);
3859 3860 3861
	  }
	  else
	  {
3862
	    join->thd->server_status|=SERVER_QUERY_NO_INDEX_USED;
3863 3864
	    if (statistics)
	      statistic_increment(select_scan_count, &LOCK_status);
3865 3866 3867 3868 3869 3870
	  }
	}
	else
	{
	  if (tab->select && tab->select->quick)
	  {
3871 3872
	    if (statistics)
	      statistic_increment(select_full_range_join_count, &LOCK_status);
3873 3874 3875
	  }
	  else
	  {
3876
	    join->thd->server_status|=SERVER_QUERY_NO_INDEX_USED;
3877 3878
	    if (statistics)
	      statistic_increment(select_full_join_count, &LOCK_status);
3879 3880
	  }
	}
3881
	if (!table->no_keyread)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3882
	{
3883
	  if (tab->select && tab->select->quick &&
3884
	      table->used_keys.is_set(tab->select->quick->index))
3885 3886 3887 3888
	  {
	    table->key_read=1;
	    table->file->extra(HA_EXTRA_KEYREAD);
	  }
3889 3890
	  else if (!table->used_keys.is_clear_all() &&
		   !(tab->select && tab->select->quick))
3891
	  {					// Only read index tree
serg@serg.mylan's avatar
serg@serg.mylan committed
3892
	    tab->index=find_shortest_key(table, & table->used_keys);
3893
	    tab->read_first_record= join_read_first;
3894 3895
	    tab->type=JT_NEXT;		// Read with index_first / index_next
	  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911
	}
      }
      break;
    default:
      DBUG_PRINT("error",("Table type %d found",tab->type)); /* purecov: deadcode */
      break;					/* purecov: deadcode */
    case JT_UNKNOWN:
    case JT_MAYBE_REF:
      abort();					/* purecov: deadcode */
    }
  }
  join->join_tab[join->tables-1].next_select=0; /* Set by do_select */
  DBUG_VOID_RETURN;
}


3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933
/*
  Give error if we some tables are done with a full join

  SYNOPSIS
    error_if_full_join()
    join		Join condition

  USAGE
   This is used by multi_table_update and multi_table_delete when running
   in safe mode

 RETURN VALUES
   0	ok
   1	Error (full join used)
*/

bool error_if_full_join(JOIN *join)
{
  for (JOIN_TAB *tab=join->join_tab, *end=join->join_tab+join->tables;
       tab < end;
       tab++)
  {
3934
    if (tab->type == JT_ALL && (!tab->select || !tab->select->quick))
3935 3936 3937 3938 3939 3940 3941 3942 3943
    {
      my_error(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE,MYF(0));
      return(1);
    }
  }
  return(0);
}


3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965
/*
  cleanup JOIN_TAB

  SYNOPSIS
    JOIN_TAB::cleanup()
*/

void JOIN_TAB::cleanup()
{
  delete select;
  select= 0;
  delete quick;
  quick= 0;
  x_free(cache.buff);
  cache.buff= 0;
  if (table)
  {
    if (table->key_read)
    {
      table->key_read= 0;
      table->file->extra(HA_EXTRA_NO_KEYREAD);
    }
3966
    table->file->ha_index_or_rnd_end();
3967 3968 3969 3970 3971 3972 3973 3974 3975 3976
    /*
      We need to reset this for next select
      (Tested in part_of_refkey)
    */
    table->reginfo.join_tab= 0;
  }
  end_read_record(&read_record);
}


3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989
/*
  Free resources of given join

  SYNOPSIS
    JOIN::join_free()
    fill - true if we should free all resources, call with full==1 should be
           last, before it this function can be called with full==0

  NOTE: with subquery this function definitely will be called several times,
    but even for simple query it can be called several times.
*/
void
JOIN::join_free(bool full)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3990 3991
{
  JOIN_TAB *tab,*end;
3992
  DBUG_ENTER("JOIN::join_free");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3993

3994
  full= full || (!select_lex->uncacheable &&
3995
                 !thd->lex->subqueries &&
3996
                 !thd->lex->describe); // do not cleanup too early on EXPLAIN
3997

3998
  if (table)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3999
  {
4000 4001 4002 4003
    /*
      Only a sorted table may be cached.  This sorted table is always the
      first non const table in join->table
    */
4004
    if (tables > const_tables) // Test for not-const tables
4005
    {
4006 4007
      free_io_cache(table[const_tables]);
      filesort_free_buffers(table[const_tables]);
4008
    }
4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020

    for (SELECT_LEX_UNIT *unit= select_lex->first_inner_unit(); unit;
         unit= unit->next_unit())
    {
      JOIN *join;
      for (SELECT_LEX *sl= unit->first_select_in_union(); sl;
           sl= sl->next_select())
        if ((join= sl->join))
          join->join_free(full);
    }

    if (full)
4021 4022 4023 4024
    {
      for (tab= join_tab, end= tab+tables; tab != end; tab++)
	tab->cleanup();
      table= 0;
4025
      tables= 0;
4026 4027
    }
    else
4028
    {
4029
      for (tab= join_tab, end= tab+tables; tab != end; tab++)
4030
      {
4031 4032
	if (tab->table)
	    tab->table->file->ha_index_or_rnd_end();
4033
      }
4034
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4035
  }
4036

4037 4038 4039 4040
  /*
    We are not using tables anymore
    Unlock all tables. We may be in an INSERT .... SELECT statement.
  */
serg@serg.mylan's avatar
serg@serg.mylan committed
4041
  if (full && lock && thd->lock && !(select_options & SELECT_NO_UNLOCK) &&
4042
      !select_lex->subquery_in_having)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4043
  {
4044 4045 4046 4047 4048 4049 4050
    // TODO: unlock tables even if the join isn't top level select in the tree
    if (select_lex == (thd->lex->unit.fake_select_lex ?
                       thd->lex->unit.fake_select_lex : &thd->lex->select_lex))
    {
      mysql_unlock_read_tables(thd, lock);        // Don't free join->lock
      lock=0;
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4051
  }
4052

4053 4054
  if (full)
  {
4055
    group_fields.delete_elements();
4056 4057 4058 4059 4060
    /*
      We can't call delete_elements() on copy_funcs as this will cause
      problems in free_elements() as some of the elements are then deleted.
    */
    tmp_table_param.copy_funcs.empty();
4061
    tmp_table_param.cleanup();
4062
  }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
4063
  DBUG_VOID_RETURN;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4064 4065 4066 4067
}


/*****************************************************************************
4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080
  Remove the following expressions from ORDER BY and GROUP BY:
  Constant expressions
  Expression that only uses tables that are of type EQ_REF and the reference
  is in the ORDER list or if all refereed tables are of the above type.

  In the following, the X field can be removed:
  SELECT * FROM t1,t2 WHERE t1.a=t2.a ORDER BY t1.a,t2.X
  SELECT * FROM t1,t2,t3 WHERE t1.a=t2.a AND t2.b=t3.b ORDER BY t1.a,t3.X

  These can't be optimized:
  SELECT * FROM t1,t2 WHERE t1.a=t2.a ORDER BY t2.X,t1.a
  SELECT * FROM t1,t2 WHERE t1.a=t2.a AND t1.b=t2.b ORDER BY t1.a,t2.c
  SELECT * FROM t1,t2 WHERE t1.a=t2.a ORDER BY t2.b,t1.a
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104
*****************************************************************************/

static bool
eq_ref_table(JOIN *join, ORDER *start_order, JOIN_TAB *tab)
{
  if (tab->cached_eq_ref_table)			// If cached
    return tab->eq_ref_table;
  tab->cached_eq_ref_table=1;
  if (tab->type == JT_CONST)			// We can skip const tables
    return (tab->eq_ref_table=1);		/* purecov: inspected */
  if (tab->type != JT_EQ_REF)
    return (tab->eq_ref_table=0);		// We must use this
  Item **ref_item=tab->ref.items;
  Item **end=ref_item+tab->ref.key_parts;
  uint found=0;
  table_map map=tab->table->map;

  for (; ref_item != end ; ref_item++)
  {
    if (! (*ref_item)->const_item())
    {						// Not a const ref
      ORDER *order;
      for (order=start_order ; order ; order=order->next)
      {
4105
	if ((*ref_item)->eq(order->item[0],0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4106 4107 4108 4109 4110
	  break;
      }
      if (order)
      {
	found++;
monty@bitch.mysql.fi's avatar
monty@bitch.mysql.fi committed
4111
	DBUG_ASSERT(!(order->used & map));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4112 4113 4114 4115 4116 4117 4118 4119
	order->used|=map;
	continue;				// Used in ORDER BY
      }
      if (!only_eq_ref_tables(join,start_order, (*ref_item)->used_tables()))
	return (tab->eq_ref_table=0);
    }
  }
  /* Check that there was no reference to table before sort order */
4120
  for (; found && start_order ; start_order=start_order->next)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137
  {
    if (start_order->used & map)
    {
      found--;
      continue;
    }
    if (start_order->depend_map & map)
      return (tab->eq_ref_table=0);
  }
  return tab->eq_ref_table=1;
}


static bool
only_eq_ref_tables(JOIN *join,ORDER *order,table_map tables)
{
  if (specialflag &  SPECIAL_SAFE_MODE)
4138
    return 0;			// skip this optimize /* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153
  for (JOIN_TAB **tab=join->map2table ; tables ; tab++, tables>>=1)
  {
    if (tables & 1 && !eq_ref_table(join, order, *tab))
      return 0;
  }
  return 1;
}


/* Update the dependency map for the tables */

static void update_depend_map(JOIN *join)
{
  JOIN_TAB *join_tab=join->join_tab, *end=join_tab+join->tables;

4154
  for (; join_tab != end ; join_tab++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4155 4156 4157 4158 4159 4160 4161
  {
    TABLE_REF *ref= &join_tab->ref;
    table_map depend_map=0;
    Item **item=ref->items;
    uint i;
    for (i=0 ; i < ref->key_parts ; i++,item++)
      depend_map|=(*item)->used_tables();
4162
    ref->depend_map=depend_map & ~OUTER_REF_TABLE_BIT;
4163
    depend_map&= ~OUTER_REF_TABLE_BIT;
4164
    for (JOIN_TAB **tab=join->map2table;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4165
	 depend_map ;
4166
	 tab++,depend_map>>=1 )
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4167 4168
    {
      if (depend_map & 1)
4169
	ref->depend_map|=(*tab)->ref.depend_map;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4170 4171 4172 4173 4174 4175 4176 4177 4178
    }
  }
}


/* Update the dependency map for the sort order */

static void update_depend_map(JOIN *join, ORDER *order)
{
4179
  for (; order ; order=order->next)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4180 4181 4182 4183
  {
    table_map depend_map;
    order->item[0]->update_used_tables();
    order->depend_map=depend_map=order->item[0]->used_tables();
4184 4185
    // Not item_sum(), RAND() and no reference to table outside of sub select
    if (!(order->depend_map & (OUTER_REF_TABLE_BIT | RAND_TABLE_BIT)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4186
    {
4187
      for (JOIN_TAB **tab=join->map2table;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4188
	   depend_map ;
4189
	   tab++, depend_map>>=1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4190 4191
      {
	if (depend_map & 1)
4192
	  order->depend_map|=(*tab)->ref.depend_map;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4193 4194 4195 4196 4197 4198 4199
      }
    }
  }
}


/*
4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217
  Remove all constants and check if ORDER only contains simple expressions

  SYNOPSIS
   remove_const()
   join			Join handler
   first_order		List of SORT or GROUP order
   cond			WHERE statement
   change_list		Set to 1 if we should remove things from list
			If this is not set, then only simple_order is
                        calculated   
   simple_order		Set to 1 if we are only using simple expressions

  RETURN
    Returns new sort order

    simple_order is set to 1 if sort_order only uses fields from head table
    and the head table is not a LEFT JOIN table

bk@work.mysql.com's avatar
bk@work.mysql.com committed
4218 4219 4220
*/

static ORDER *
4221 4222
remove_const(JOIN *join,ORDER *first_order, COND *cond,
             bool change_list, bool *simple_order)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4223 4224
{
  if (join->tables == join->const_tables)
4225 4226
    return change_list ? 0 : first_order;		// No need to sort

bk@work.mysql.com's avatar
bk@work.mysql.com committed
4227 4228 4229 4230
  ORDER *order,**prev_ptr;
  table_map first_table= join->join_tab[join->const_tables].table->map;
  table_map not_const_tables= ~join->const_table_map;
  table_map ref;
4231 4232
  DBUG_ENTER("remove_const");

bk@work.mysql.com's avatar
bk@work.mysql.com committed
4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246
  prev_ptr= &first_order;
  *simple_order= join->join_tab[join->const_tables].on_expr ? 0 : 1;

  /* NOTE: A variable of not_const_tables ^ first_table; breaks gcc 2.7 */

  update_depend_map(join, first_order);
  for (order=first_order; order ; order=order->next)
  {
    table_map order_tables=order->item[0]->used_tables();
    if (order->item[0]->with_sum_func)
      *simple_order=0;				// Must do a temp table to sort
    else if (!(order_tables & not_const_tables))
    {
      DBUG_PRINT("info",("removing: %s", order->item[0]->full_name()));
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
4247
      continue;					// skip const item
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4248 4249 4250
    }
    else
    {
4251
      if (order_tables & (RAND_TABLE_BIT | OUTER_REF_TABLE_BIT))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262
	*simple_order=0;
      else
      {
	Item *comp_item=0;
	if (cond && const_expression_in_where(cond,order->item[0], &comp_item))
	{
	  DBUG_PRINT("info",("removing: %s", order->item[0]->full_name()));
	  continue;
	}
	if ((ref=order_tables & (not_const_tables ^ first_table)))
	{
4263 4264
	  if (!(order_tables & first_table) &&
              only_eq_ref_tables(join,first_order, ref))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4265 4266 4267 4268 4269 4270 4271 4272
	  {
	    DBUG_PRINT("info",("removing: %s", order->item[0]->full_name()));
	    continue;
	  }
	  *simple_order=0;			// Must do a temp table to sort
	}
      }
    }
4273 4274
    if (change_list)
      *prev_ptr= order;				// use this entry
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4275 4276
    prev_ptr= &order->next;
  }
4277 4278 4279
  if (change_list)
    *prev_ptr=0;
  if (prev_ptr == &first_order)			// Nothing to sort/group
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4280 4281 4282 4283 4284
    *simple_order=1;
  DBUG_PRINT("exit",("simple_order: %d",(int) *simple_order));
  DBUG_RETURN(first_order);
}

4285

bk@work.mysql.com's avatar
bk@work.mysql.com committed
4286
static int
4287 4288
return_zero_rows(JOIN *join, select_result *result,TABLE_LIST *tables,
		 List<Item> &fields, bool send_row, uint select_options,
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
4289 4290
		 const char *info, Item *having, Procedure *procedure,
		 SELECT_LEX_UNIT *unit)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4291 4292 4293 4294
{
  DBUG_ENTER("return_zero_rows");

  if (select_options & SELECT_DESCRIBE)
4295
  {
monty@mysql.com's avatar
monty@mysql.com committed
4296
    select_describe(join, FALSE, FALSE, FALSE, info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4297 4298
    DBUG_RETURN(0);
  }
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4299

4300 4301
  join->join_free(0);

bk@work.mysql.com's avatar
bk@work.mysql.com committed
4302 4303 4304 4305
  if (send_row)
  {
    for (TABLE_LIST *table=tables; table ; table=table->next)
      mark_as_null_row(table->table);		// All fields are NULL
4306
    if (having && having->val_int() == 0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4307 4308
      send_row=0;
  }
4309
  if (!(result->send_fields(fields,1)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4310 4311
  {
    if (send_row)
4312 4313 4314 4315 4316
    {
      List_iterator_fast<Item> it(fields);
      Item *item;
      while ((item= it++))
	item->no_rows_in_result();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4317
      result->send_data(fields);
4318
    }
4319
    result->send_eof();				// Should be safe
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4320
  }
4321 4322
  /* Update results for FOUND_ROWS */
  join->thd->limit_found_rows= join->thd->examined_row_count= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333
  DBUG_RETURN(0);
}


static void clear_tables(JOIN *join)
{
  for (uint i=0 ; i < join->tables ; i++)
    mark_as_null_row(join->table[i]);		// All fields are NULL
}

/*****************************************************************************
4334 4335 4336 4337 4338 4339
  Make som simple condition optimization:
  If there is a test 'field = const' change all refs to 'field' to 'const'
  Remove all dummy tests 'item = item', 'const op const'.
  Remove all 'item is NULL', when item can never be null!
  item->marker should be 0 for all items on entry
  Return in cond_value FALSE if condition is impossible (1 = 2)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4340 4341 4342 4343
*****************************************************************************/

class COND_CMP :public ilink {
public:
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
4344
  static void *operator new(size_t size) {return (void*) sql_alloc((uint) size); }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360
  static void operator delete(void *ptr __attribute__((unused)),
			      size_t size __attribute__((unused))) {} /*lint -e715 */

  Item *and_level;
  Item_func *cmp_func;
  COND_CMP(Item *a,Item_func *b) :and_level(a),cmp_func(b) {}
};

#ifdef __GNUC__
template class I_List<COND_CMP>;
template class I_List_iterator<COND_CMP>;
template class List<Item_func_match>;
template class List_iterator<Item_func_match>;
#endif

/*
4361 4362
  change field = field to field = const for each found field = const in the
  and_level
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4363 4364 4365
*/

static void
4366 4367 4368
change_cond_ref_to_const(THD *thd, I_List<COND_CMP> *save_list,
                         Item *and_father, Item *cond,
                         Item *field, Item *value)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4369 4370 4371 4372 4373 4374 4375 4376
{
  if (cond->type() == Item::COND_ITEM)
  {
    bool and_level= ((Item_cond*) cond)->functype() ==
      Item_func::COND_AND_FUNC;
    List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
    Item *item;
    while ((item=li++))
4377
      change_cond_ref_to_const(thd, save_list,and_level ? cond : item, item,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4378 4379 4380 4381 4382 4383 4384
			       field, value);
    return;
  }
  if (cond->eq_cmp_result() == Item::COND_OK)
    return;					// Not a boolean function

  Item_bool_func2 *func=  (Item_bool_func2*) cond;
4385 4386 4387
  Item **args= func->arguments();
  Item *left_item=  args[0];
  Item *right_item= args[1];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4388 4389
  Item_func::Functype functype=  func->functype();

4390 4391 4392 4393
  if (right_item->eq(field,0) && left_item != value &&
      (left_item->result_type() != STRING_RESULT ||
       value->result_type() != STRING_RESULT ||
       left_item->collation.collation == value->collation.collation))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4394 4395 4396 4397
  {
    Item *tmp=value->new_item();
    if (tmp)
    {
4398
      thd->change_item_tree(args + 1, tmp);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4399 4400 4401 4402 4403 4404 4405 4406 4407
      func->update_used_tables();
      if ((functype == Item_func::EQ_FUNC || functype == Item_func::EQUAL_FUNC)
	  && and_father != cond && !left_item->const_item())
      {
	cond->marker=1;
	COND_CMP *tmp2;
	if ((tmp2=new COND_CMP(and_father,func)))
	  save_list->push_back(tmp2);
      }
4408
      func->set_cmp_func();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4409 4410
    }
  }
4411 4412 4413 4414
  else if (left_item->eq(field,0) && right_item != value &&
           (right_item->result_type() != STRING_RESULT ||
            value->result_type() != STRING_RESULT ||
            right_item->collation.collation == value->collation.collation))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4415 4416 4417 4418
  {
    Item *tmp=value->new_item();
    if (tmp)
    {
4419 4420
      thd->change_item_tree(args, tmp);
      value= tmp;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4421 4422 4423 4424
      func->update_used_tables();
      if ((functype == Item_func::EQ_FUNC || functype == Item_func::EQUAL_FUNC)
	  && and_father != cond && !right_item->const_item())
      {
4425
        args[0]= args[1];                       // For easy check
4426
        thd->change_item_tree(args + 1, value);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4427 4428 4429 4430 4431
	cond->marker=1;
	COND_CMP *tmp2;
	if ((tmp2=new COND_CMP(and_father,func)))
	  save_list->push_back(tmp2);
      }
4432
      func->set_cmp_func();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4433 4434 4435 4436
    }
  }
}

4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469
/*
  Remove additional condition inserted by IN/ALL/ANY transformation

  SYNOPSIS
    remove_additional_cond()
    conds - condition for processing

  RETURN VALUES
    new conditions
*/

static Item *remove_additional_cond(Item* conds)
{
  if (conds->name == in_additional_cond)
    return 0;
  if (conds->type() == Item::COND_ITEM)
  {
    Item_cond *cnd= (Item_cond*) conds;
    List_iterator<Item> li(*(cnd->argument_list()));
    Item *item;
    while ((item= li++))
    {
      if (item->name == in_additional_cond)
      {
	li.remove();
	if (cnd->argument_list()->elements == 1)
	  return cnd->argument_list()->head();
	return conds;
      }
    }
  }
  return conds;
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4470 4471

static void
4472 4473
propagate_cond_constants(THD *thd, I_List<COND_CMP> *save_list,
                         COND *and_father, COND *cond)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4474 4475 4476 4477 4478
{
  if (cond->type() == Item::COND_ITEM)
  {
    bool and_level= ((Item_cond*) cond)->functype() ==
      Item_func::COND_AND_FUNC;
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
4479
    List_iterator_fast<Item> li(*((Item_cond*) cond)->argument_list());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4480 4481 4482 4483
    Item *item;
    I_List<COND_CMP> save;
    while ((item=li++))
    {
4484
      propagate_cond_constants(thd, &save,and_level ? cond : item, item);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4485 4486 4487 4488 4489 4490
    }
    if (and_level)
    {						// Handle other found items
      I_List_iterator<COND_CMP> cond_itr(save);
      COND_CMP *cond_cmp;
      while ((cond_cmp=cond_itr++))
4491 4492 4493 4494 4495 4496
      {
        Item **args= cond_cmp->cmp_func->arguments();
        if (!args[0]->const_item())
          change_cond_ref_to_const(thd, &save,cond_cmp->and_level,
                                   cond_cmp->and_level, args[0], args[1]);
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4497 4498
    }
  }
4499
  else if (and_father != cond && !cond->marker)		// In a AND group
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4500 4501 4502 4503 4504 4505
  {
    if (cond->type() == Item::FUNC_ITEM &&
	(((Item_func*) cond)->functype() == Item_func::EQ_FUNC ||
	 ((Item_func*) cond)->functype() == Item_func::EQUAL_FUNC))
    {
      Item_func_eq *func=(Item_func_eq*) cond;
4506 4507 4508
      Item **args= func->arguments();
      bool left_const= args[0]->const_item();
      bool right_const= args[1]->const_item();
4509
      if (!(left_const && right_const) &&
4510
          args[0]->result_type() == args[1]->result_type())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4511 4512 4513
      {
	if (right_const)
	{
4514
          resolve_const_item(thd, &args[1], args[0]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4515
	  func->update_used_tables();
4516 4517
          change_cond_ref_to_const(thd, save_list, and_father, and_father,
                                   args[0], args[1]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4518 4519 4520
	}
	else if (left_const)
	{
4521
          resolve_const_item(thd, &args[0], args[1]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4522
	  func->update_used_tables();
4523 4524
          change_cond_ref_to_const(thd, save_list, and_father, and_father,
                                   args[1], args[0]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4525 4526 4527 4528 4529 4530 4531 4532
	}
      }
    }
  }
}


static COND *
4533
optimize_cond(THD *thd, COND *conds, Item::cond_result *cond_value)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4534
{
4535
  SELECT_LEX *select= thd->lex->current_select;
4536
  DBUG_ENTER("optimize_cond");
4537 4538 4539 4540
  if (conds)
  {
    DBUG_EXECUTE("where", print_where(conds, "original"););
    /* change field = field to field = const for each found field = const */
4541
    propagate_cond_constants(thd, (I_List<COND_CMP> *) 0, conds, conds);
4542 4543 4544 4545 4546 4547 4548 4549 4550
    /*
      Remove all instances of item == item
      Remove all and-levels where CONST item != CONST item
    */
    DBUG_EXECUTE("where", print_where(conds, "after const change"););
    conds= remove_eq_conds(thd, conds, cond_value);
    DBUG_EXECUTE("info", print_where(conds, "after remove"););
  }
  else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4551 4552
  {
    *cond_value= Item::COND_TRUE;
4553
    select->prep_where= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4554
  }
4555
  DBUG_RETURN(conds);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4556 4557 4558 4559
}


/*
4560 4561 4562 4563 4564
  Remove const and eq items. Return new item, or NULL if no condition
  cond_value is set to according:
  COND_OK    query is possible (field = constant)
  COND_TRUE  always true	( 1 = 1 )
  COND_FALSE always false	( 1 = 2 )
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4565 4566 4567
*/

static COND *
4568
remove_eq_conds(THD *thd, COND *cond, Item::cond_result *cond_value)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4569 4570 4571 4572 4573 4574 4575
{
  if (cond->type() == Item::COND_ITEM)
  {
    bool and_level= ((Item_cond*) cond)->functype()
      == Item_func::COND_AND_FUNC;
    List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
    Item::cond_result tmp_cond_value;
4576
    bool should_fix_fields=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4577 4578 4579 4580 4581

    *cond_value=Item::COND_UNDEF;
    Item *item;
    while ((item=li++))
    {
4582
      Item *new_item=remove_eq_conds(thd, item, &tmp_cond_value);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4583 4584 4585 4586 4587
      if (!new_item)
	li.remove();
      else if (item != new_item)
      {
	VOID(li.replace(new_item));
4588
	should_fix_fields=1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614
      }
      if (*cond_value == Item::COND_UNDEF)
	*cond_value=tmp_cond_value;
      switch (tmp_cond_value) {
      case Item::COND_OK:			// Not TRUE or FALSE
	if (and_level || *cond_value == Item::COND_FALSE)
	  *cond_value=tmp_cond_value;
	break;
      case Item::COND_FALSE:
	if (and_level)
	{
	  *cond_value=tmp_cond_value;
	  return (COND*) 0;			// Always false
	}
	break;
      case Item::COND_TRUE:
	if (!and_level)
	{
	  *cond_value= tmp_cond_value;
	  return (COND*) 0;			// Always true
	}
	break;
      case Item::COND_UNDEF:			// Impossible
	break; /* purecov: deadcode */
      }
    }
4615
    if (should_fix_fields)
4616
      cond->update_used_tables();
4617

bk@work.mysql.com's avatar
bk@work.mysql.com committed
4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631
    if (!((Item_cond*) cond)->argument_list()->elements ||
	*cond_value != Item::COND_OK)
      return (COND*) 0;
    if (((Item_cond*) cond)->argument_list()->elements == 1)
    {						// Remove list
      item= ((Item_cond*) cond)->argument_list()->head();
      ((Item_cond*) cond)->argument_list()->empty();
      return item;
    }
  }
  else if (cond->type() == Item::FUNC_ITEM &&
	   ((Item_func*) cond)->functype() == Item_func::ISNULL_FUNC)
  {
    /*
4632 4633 4634 4635 4636 4637 4638
      Handles this special case for some ODBC applications:
      The are requesting the row that was just updated with a auto_increment
      value with this construct:

      SELECT * from table_name where auto_increment_column IS NULL
      This will be changed to:
      SELECT * from table_name where auto_increment_column = LAST_INSERT_ID
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4639 4640 4641 4642 4643 4644 4645 4646
    */

    Item_func_isnull *func=(Item_func_isnull*) cond;
    Item **args= func->arguments();
    if (args[0]->type() == Item::FIELD_ITEM)
    {
      Field *field=((Item_field*) args[0])->field;
      if (field->flags & AUTO_INCREMENT_FLAG && !field->table->maybe_null &&
4647 4648
	  (thd->options & OPTION_AUTO_IS_NULL) &&
	  thd->insert_id())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4649
      {
4650
#ifdef HAVE_QUERY_CACHE
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
4651
	query_cache_abort(&thd->net);
4652
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4653 4654 4655
	COND *new_cond;
	if ((new_cond= new Item_func_eq(args[0],
					new Item_int("last_insert_id()",
4656
						     thd->insert_id(),
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4657 4658 4659
						     21))))
	{
	  cond=new_cond;
4660
	  cond->fix_fields(thd, 0, &cond);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4661
	}
4662
	thd->insert_id(0);		// Clear for next request
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4663 4664 4665 4666
      }
      /* fix to replace 'NULL' dates with '0' (shreeve@uci.edu) */
      else if (((field->type() == FIELD_TYPE_DATE) ||
		(field->type() == FIELD_TYPE_DATETIME)) &&
4667 4668
		(field->flags & NOT_NULL_FLAG) &&
	       !field->table->maybe_null)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4669 4670 4671 4672 4673
      {
	COND *new_cond;
	if ((new_cond= new Item_func_eq(args[0],new Item_int("0", 0, 2))))
	{
	  cond=new_cond;
4674
	  cond->fix_fields(thd, 0, &cond);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687
	}
      }
    }
  }
  else if (cond->const_item())
  {
    *cond_value= eval_const_cond(cond) ? Item::COND_TRUE : Item::COND_FALSE;
    return (COND*) 0;
  }
  else if ((*cond_value= cond->eq_cmp_result()) != Item::COND_OK)
  {						// boolan compare function
    Item *left_item=	((Item_func*) cond)->arguments()[0];
    Item *right_item= ((Item_func*) cond)->arguments()[1];
4688
    if (left_item->eq(right_item,1))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4689 4690 4691 4692 4693 4694 4695
    {
      if (!left_item->maybe_null ||
	  ((Item_func*) cond)->functype() == Item_func::EQUAL_FUNC)
	return (COND*) 0;			// Compare of identical items
    }
  }
  *cond_value=Item::COND_OK;
4696
  return cond;					// Point at next and level
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4697 4698 4699
}

/*
4700
  Return 1 if the item is a const value in all the WHERE clause
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4701 4702 4703 4704 4705 4706 4707 4708 4709
*/

static bool
const_expression_in_where(COND *cond, Item *comp_item, Item **const_item)
{
  if (cond->type() == Item::COND_ITEM)
  {
    bool and_level= (((Item_cond*) cond)->functype()
		     == Item_func::COND_AND_FUNC);
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
4710
    List_iterator_fast<Item> li(*((Item_cond*) cond)->argument_list());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732
    Item *item;
    while ((item=li++))
    {
      bool res=const_expression_in_where(item, comp_item, const_item);
      if (res)					// Is a const value
      {
	if (and_level)
	  return 1;
      }
      else if (!and_level)
	return 0;
    }
    return and_level ? 0 : 1;
  }
  else if (cond->eq_cmp_result() != Item::COND_OK)
  {						// boolan compare function
    Item_func* func= (Item_func*) cond;
    if (func->functype() != Item_func::EQUAL_FUNC &&
	func->functype() != Item_func::EQ_FUNC)
      return 0;
    Item *left_item=	((Item_func*) cond)->arguments()[0];
    Item *right_item= ((Item_func*) cond)->arguments()[1];
4733
    if (left_item->eq(comp_item,1))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4734 4735 4736 4737
    {
      if (right_item->const_item())
      {
	if (*const_item)
4738
	  return right_item->eq(*const_item, 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4739 4740 4741 4742
	*const_item=right_item;
	return 1;
      }
    }
4743
    else if (right_item->eq(comp_item,1))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4744 4745 4746 4747
    {
      if (left_item->const_item())
      {
	if (*const_item)
4748
	  return left_item->eq(*const_item, 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4749 4750 4751 4752 4753 4754 4755 4756 4757 4758
	*const_item=left_item;
	return 1;
      }
    }
  }
  return 0;
}


/****************************************************************************
4759
  Create internal temporary table
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4760 4761
****************************************************************************/

4762 4763 4764 4765 4766 4767 4768
/*
  Create field for temporary table from given field
  
  SYNOPSIS
    create_tmp_field_from_field()
    thd			Thread handler
    org_field           field from which new field will be created
4769
    name                New field name
4770 4771
    item		Item to create a field for
    table		Temporary table
4772 4773 4774
    item	        !=NULL if item->result_field should point to new field.
			This is relevant for how fill_record() is going to work:
			If item != NULL then fill_record() will update
4775
			the record in the original table.
4776
			If item == NULL then fill_record() will update
4777
			the temporary table
4778 4779
    convert_blob_length If >0 create a varstring(convert_blob_length) field 
                        instead of blob.
4780 4781 4782 4783 4784

  RETURN
    0			on error
    new_created field
*/
4785 4786

static Field* create_tmp_field_from_field(THD *thd, Field* org_field,
4787 4788
                                          const char *name, TABLE *table,
                                          Item_field *item,
4789
                                          uint convert_blob_length)
4790 4791 4792
{
  Field *new_field;

4793 4794 4795 4796 4797
  if (convert_blob_length && org_field->flags & BLOB_FLAG)
    new_field= new Field_varstring(convert_blob_length, org_field->maybe_null(),
                                   org_field->field_name, table,
                                   org_field->charset());
  else
4798
    new_field= org_field->new_field(thd->mem_root, table);
4799
  if (new_field)
4800
  {
4801 4802
    if (item)
      item->result_field= new_field;
4803
    else
4804
      new_field->field_name= name;
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
4805
    if (org_field->maybe_null() || (item && item->maybe_null))
4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829
      new_field->flags&= ~NOT_NULL_FLAG;	// Because of outer join
    if (org_field->type() == FIELD_TYPE_VAR_STRING)
      table->db_create_options|= HA_OPTION_PACK_RECORD;
  }
  return new_field;
}

/*
  Create field for temporary table using type of given item
  
  SYNOPSIS
    create_tmp_field_from_item()
    thd			Thread handler
    item		Item to create a field for
    table		Temporary table
    copy_func		If set and item is a function, store copy of item
			in this array
    modify_item		1 if item->result_field should point to new item.
			This is relevent for how fill_record() is going to
			work:
			If modify_item is 1 then fill_record() will update
			the record in the original table.
			If modify_item is 0 then fill_record() will update
			the temporary table
4830 4831
    convert_blob_length If >0 create a varstring(convert_blob_length) field 
                        instead of blob.
4832 4833 4834 4835 4836

  RETURN
    0			on error
    new_created field
*/
4837 4838 4839
static Field* create_tmp_field_from_item(THD *thd, Item *item, TABLE *table,
                                         Item ***copy_func, bool modify_item,
                                         uint convert_blob_length)
4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855
{
  bool maybe_null=item->maybe_null;
  Field *new_field;
  LINT_INIT(new_field);

  switch (item->result_type()) {
  case REAL_RESULT:
    new_field=new Field_double(item->max_length, maybe_null,
			       item->name, table, item->decimals);
    break;
  case INT_RESULT:
    new_field=new Field_longlong(item->max_length, maybe_null,
				   item->name, table, item->unsigned_flag);
    break;
  case STRING_RESULT:
    if (item->max_length > 255)
4856 4857 4858 4859 4860 4861 4862 4863 4864
    {
      if (convert_blob_length)
        new_field= new Field_varstring(convert_blob_length, maybe_null,
                                       item->name, table,
                                       item->collation.collation);
      else
        new_field= new Field_blob(item->max_length, maybe_null, item->name,
                                  table, item->collation.collation);
    }
4865
    else
4866 4867
      new_field= new Field_string(item->max_length, maybe_null, item->name, 
                                  table, item->collation.collation);
4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882
    break;
  case ROW_RESULT: 
  default: 
    // This case should never be choosen
    DBUG_ASSERT(0);
    new_field= 0; // to satisfy compiler (uninitialized variable)
    break;
  }
  if (copy_func && item->is_result_field())
    *((*copy_func)++) = item;			// Save for copy_funcs
  if (modify_item)
    item->set_result_field(new_field);
  return new_field;
}

4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893
/*
  Create field for temporary table

  SYNOPSIS
    create_tmp_field()
    thd			Thread handler
    table		Temporary table
    item		Item to create a field for
    type		Type of item (normally item->type)
    copy_func		If set and item is a function, store copy of item
			in this array
4894
    from_field          if field will be created using other field as example,
serg@serg.mylan's avatar
serg@serg.mylan committed
4895
                        pointer example field will be written here
4896 4897 4898 4899 4900 4901 4902 4903
    group		1 if we are going to do a relative group by on result
    modify_item		1 if item->result_field should point to new item.
			This is relevent for how fill_record() is going to
			work:
			If modify_item is 1 then fill_record() will update
			the record in the original table.
			If modify_item is 0 then fill_record() will update
			the temporary table
4904 4905
    convert_blob_length If >0 create a varstring(convert_blob_length) field 
                        instead of blob.
serg@serg.mylan's avatar
serg@serg.mylan committed
4906

4907 4908 4909 4910 4911
  RETURN
    0			on error
    new_created field
*/

4912
Field *create_tmp_field(THD *thd, TABLE *table,Item *item, Item::Type type,
4913 4914
                        Item ***copy_func, Field **from_field,
                        bool group, bool modify_item, uint convert_blob_length)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4915 4916 4917 4918 4919 4920 4921 4922 4923 4924
{
  switch (type) {
  case Item::SUM_FUNC_ITEM:
  {
    Item_sum *item_sum=(Item_sum*) item;
    bool maybe_null=item_sum->maybe_null;
    switch (item_sum->sum_func()) {
    case Item_sum::AVG_FUNC:			/* Place for sum & count */
      if (group)
	return new Field_string(sizeof(double)+sizeof(longlong),
igor@hundin.mysql.fi's avatar
igor@hundin.mysql.fi committed
4925
				0, item->name,table,&my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4926 4927 4928
      else
	return new Field_double(item_sum->max_length,maybe_null,
				item->name, table, item_sum->decimals);
4929
    case Item_sum::VARIANCE_FUNC:		/* Place for sum & count */
serg@serg.mylan's avatar
serg@serg.mylan committed
4930
    case Item_sum::STD_FUNC:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4931 4932
      if (group)
	return	new Field_string(sizeof(double)*2+sizeof(longlong),
igor@hundin.mysql.fi's avatar
igor@hundin.mysql.fi committed
4933
				 0, item->name,table,&my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4934 4935
      else
	return new Field_double(item_sum->max_length, maybe_null,
serg@serg.mylan's avatar
serg@serg.mylan committed
4936
				item->name,table,item_sum->decimals);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4937 4938
    case Item_sum::UNIQUE_USERS_FUNC:
      return new Field_long(9,maybe_null,item->name,table,1);
4939 4940 4941 4942 4943
    case Item_sum::MIN_FUNC:
    case Item_sum::MAX_FUNC:
      if (item_sum->args[0]->type() == Item::FIELD_ITEM)
      {
        *from_field= ((Item_field*) item_sum->args[0])->field;
4944 4945
        return create_tmp_field_from_field(thd, *from_field, item->name, table,
                                           NULL, convert_blob_length);
4946 4947
      }
      /* fall through */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4948 4949 4950 4951 4952 4953 4954
    default:
      switch (item_sum->result_type()) {
      case REAL_RESULT:
	return new Field_double(item_sum->max_length,maybe_null,
				item->name,table,item_sum->decimals);
      case INT_RESULT:
	return new Field_longlong(item_sum->max_length,maybe_null,
4955
				  item->name,table,item->unsigned_flag);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4956 4957
      case STRING_RESULT:
	if (item_sum->max_length > 255)
4958 4959 4960 4961 4962 4963 4964 4965 4966
        {
          if (convert_blob_length)
            return new Field_varstring(convert_blob_length, maybe_null,
                                       item->name, table,
                                       item->collation.collation);
          else
            return new Field_blob(item_sum->max_length, maybe_null, item->name,
                                  table, item->collation.collation);
        }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4967
	return	new Field_string(item_sum->max_length,maybe_null,
4968
				 item->name,table,item->collation.collation);
4969
      case ROW_RESULT:
4970
      default:
4971 4972
	// This case should never be choosen
	DBUG_ASSERT(0);
4973
	thd->fatal_error();
4974
	return 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4975 4976
      }
    }
4977
    /* We never come here */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4978 4979
  }
  case Item::FIELD_ITEM:
4980
  case Item::DEFAULT_VALUE_ITEM:
4981 4982
  {
    Item_field *field= (Item_field*) item;
4983 4984 4985 4986
    return create_tmp_field_from_field(thd, (*from_field= field->field),
                                       item->name, table,
                                       modify_item ? (Item_field*) item : NULL,
                                       convert_blob_length);
4987
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4988 4989 4990 4991
  case Item::FUNC_ITEM:
  case Item::COND_ITEM:
  case Item::FIELD_AVG_ITEM:
  case Item::FIELD_STD_ITEM:
4992
  case Item::SUBSELECT_ITEM:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4993
    /* The following can only happen with 'CREATE TABLE ... SELECT' */
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
4994
  case Item::PROC_ITEM:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4995 4996 4997 4998
  case Item::INT_ITEM:
  case Item::REAL_ITEM:
  case Item::STRING_ITEM:
  case Item::REF_ITEM:
4999
  case Item::NULL_ITEM:
5000
  case Item::VARBIN_ITEM:
5001 5002
    return create_tmp_field_from_item(thd, item, table, copy_func, modify_item,
                                      convert_blob_length);
5003
  case Item::TYPE_HOLDER:
5004
    return ((Item_type_holder *)item)->make_field_by_type(table);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5005 5006 5007 5008 5009 5010
  default:					// Dosen't have to be stored
    return 0;
  }
}


5011 5012 5013 5014 5015 5016 5017
/*
  Create a temp table according to a field list.
  Set distinct if duplicates could be removed
  Given fields field pointers are changed to point at tmp_table
  for send_fields
*/

bk@work.mysql.com's avatar
bk@work.mysql.com committed
5018 5019 5020
TABLE *
create_tmp_table(THD *thd,TMP_TABLE_PARAM *param,List<Item> &fields,
		 ORDER *group, bool distinct, bool save_sum_fields,
5021 5022
		 ulong select_options, ha_rows rows_limit,
		 char *table_alias)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5023 5024 5025
{
  TABLE *table;
  uint	i,field_count,reclength,null_count,null_pack_length,
5026
        hidden_null_count, hidden_null_pack_length, hidden_field_count,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5027 5028
	blob_count,group_null_items;
  bool	using_unique_constraint=0;
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
5029
  bool  not_all_columns= !(select_options & TMP_TABLE_ALL_COLUMNS);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5030 5031 5032
  char	*tmpname,path[FN_REFLEN];
  byte	*pos,*group_buff;
  uchar *null_flags;
5033
  Field **reg_field, **from_field, **blob_field;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5034 5035 5036
  Copy_field *copy=0;
  KEY *keyinfo;
  KEY_PART_INFO *key_part_info;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
5037
  Item **copy_func;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5038
  MI_COLUMNDEF *recinfo;
5039
  uint temp_pool_slot=MY_BIT_NONE;
5040

bk@work.mysql.com's avatar
bk@work.mysql.com committed
5041
  DBUG_ENTER("create_tmp_table");
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
5042
  DBUG_PRINT("enter",("distinct: %d  save_sum_fields: %d  rows_limit: %lu  group: %d",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5043
		      (int) distinct, (int) save_sum_fields,
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
5044
		      (ulong) rows_limit,test(group)));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5045

5046
  statistic_increment(created_tmp_tables, &LOCK_status);
5047

5048
  if (use_temp_pool)
5049
    temp_pool_slot = bitmap_set_next(&temp_pool);
5050 5051

  if (temp_pool_slot != MY_BIT_NONE) // we got a slot
5052
    sprintf(path, "%s_%lx_%i", tmp_file_prefix,
5053 5054
	    current_pid, temp_pool_slot);
  else // if we run out of slots or we are not using tempool
5055
    sprintf(path,"%s%lx_%lx_%x", tmp_file_prefix,current_pid,
5056
            thd->thread_id, thd->tmp_table++);
serg@serg.mylan's avatar
serg@serg.mylan committed
5057

5058 5059
  fn_format(path, path, mysql_tmpdir, "", MY_REPLACE_EXT|MY_UNPACK_FILENAME);

5060 5061
  if (lower_case_table_names)
    my_casedn_str(files_charset_info, path);
5062

bk@work.mysql.com's avatar
bk@work.mysql.com committed
5063 5064 5065 5066 5067
  if (group)
  {
    if (!param->quick_group)
      group=0;					// Can't use group key
    else for (ORDER *tmp=group ; tmp ; tmp=tmp->next)
5068
    {
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5069
      (*tmp->item)->marker=4;			// Store null in key
5070 5071 5072
      if ((*tmp->item)->max_length >= MAX_CHAR_WIDTH)
	using_unique_constraint=1;
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5073 5074
    if (param->group_length >= MAX_BLOB_WIDTH)
      using_unique_constraint=1;
5075 5076
    if (group)
      distinct=0;				// Can't use distinct
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5077 5078 5079
  }

  field_count=param->field_count+param->func_count+param->sum_func_count;
5080
  hidden_field_count=param->hidden_field_count;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5081 5082
  if (!my_multi_malloc(MYF(MY_WME),
		       &table,sizeof(*table),
5083 5084 5085
		       &reg_field,  sizeof(Field*)*(field_count+1),
		       &blob_field, sizeof(Field*)*(field_count+1),
		       &from_field, sizeof(Field*)*field_count,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096
		       &copy_func,sizeof(*copy_func)*(param->func_count+1),
		       &param->keyinfo,sizeof(*param->keyinfo),
		       &key_part_info,
		       sizeof(*key_part_info)*(param->group_parts+1),
		       &param->start_recinfo,
		       sizeof(*param->recinfo)*(field_count*2+4),
		       &tmpname,(uint) strlen(path)+1,
		       &group_buff,group && ! using_unique_constraint ?
		       param->group_length : 0,
		       NullS))
  {
5097
    bitmap_clear_bit(&temp_pool, temp_pool_slot);
5098
    DBUG_RETURN(NULL);				/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5099 5100 5101
  }
  if (!(param->copy_field=copy=new Copy_field[field_count]))
  {
5102
    bitmap_clear_bit(&temp_pool, temp_pool_slot);
5103 5104
    my_free((gptr) table,MYF(0));		/* purecov: inspected */
    DBUG_RETURN(NULL);				/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5105
  }
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
5106
  param->items_to_copy= copy_func;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5107 5108 5109 5110 5111 5112 5113
  strmov(tmpname,path);
  /* make table according to fields */

  bzero((char*) table,sizeof(*table));
  bzero((char*) reg_field,sizeof(Field*)*(field_count+1));
  bzero((char*) from_field,sizeof(Field*)*field_count);
  table->field=reg_field;
5114
  table->blob_field= (Field_blob**) blob_field;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5115
  table->real_name=table->path=tmpname;
5116
  table->table_name= table_alias;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5117 5118 5119 5120
  table->reginfo.lock_type=TL_WRITE;	/* Will be updated */
  table->db_stat=HA_OPEN_KEYFILE+HA_OPEN_RNDFILE;
  table->blob_ptr_size=mi_portable_sizeof_char_ptr;
  table->map=1;
5121
  table->tmp_table= TMP_TABLE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5122
  table->db_low_byte_first=1;			// True for HEAP and MyISAM
5123
  table->temp_pool_slot = temp_pool_slot;
5124
  table->copy_blobs= 1;
5125
  table->in_use= thd;
5126 5127 5128 5129 5130 5131
  table->keys_for_keyread.init();
  table->keys_in_use.init();
  table->read_only_keys.init();
  table->quick_keys.init();
  table->used_keys.init();
  table->keys_in_use_for_query.init();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5132

5133
  /* Calculate which type of fields we will store in the temporary table */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5134

5135 5136
  reclength=blob_count=null_count=hidden_null_count=group_null_items=0;
  param->using_indirect_summary_function=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5137

monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
5138
  List_iterator_fast<Item> li(fields);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5139 5140
  Item *item;
  Field **tmp_from_field=from_field;
5141
  while ((item=li++))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5142 5143
  {
    Item::Type type=item->type();
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
5144
    if (not_all_columns)
5145
    {
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
5146 5147 5148 5149 5150 5151 5152 5153 5154 5155
      if (item->with_sum_func && type != Item::SUM_FUNC_ITEM)
      {
	/*
	  Mark that the we have ignored an item that refers to a summary
	  function. We need to know this if someone is going to use
	  DISTINCT on the result.
	*/
	param->using_indirect_summary_function=1;
	continue;
      }
5156
      if (item->const_item() && (int) hidden_field_count <= 0)
5157
        continue; // We don't have to store this
5158
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5159 5160 5161 5162 5163
    if (type == Item::SUM_FUNC_ITEM && !group && !save_sum_fields)
    {						/* Can't calc group yet */
      ((Item_sum*) item)->result_field=0;
      for (i=0 ; i < ((Item_sum*) item)->arg_count ; i++)
      {
5164 5165
	Item **argp= ((Item_sum*) item)->args + i;
	Item *arg= *argp;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5166 5167 5168
	if (!arg->const_item())
	{
	  Field *new_field=
5169 5170 5171
            create_tmp_field(thd, table, arg, arg->type(), &copy_func,
                             tmp_from_field, group != 0,not_all_columns,
                             param->convert_blob_length);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5172 5173 5174 5175 5176 5177
	  if (!new_field)
	    goto err;					// Should be OOM
	  tmp_from_field++;
	  *(reg_field++)= new_field;
	  reclength+=new_field->pack_length();
	  if (new_field->flags & BLOB_FLAG)
5178 5179
	  {
	    *blob_field++= new_field;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5180
	    blob_count++;
5181
	  }
5182
          thd->change_item_tree(argp, new Item_field(new_field));
serg@serg.mylan's avatar
serg@serg.mylan committed
5183 5184 5185 5186 5187 5188 5189
	  if (!(new_field->flags & NOT_NULL_FLAG))
          {
	    null_count++;
            /*
              new_field->maybe_null() is still false, it will be
              changed below. But we have to setup Item_field correctly
            */
5190
            (*argp)->maybe_null=1;
serg@serg.mylan's avatar
serg@serg.mylan committed
5191
          }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5192 5193 5194 5195 5196
	}
      }
    }
    else
    {
5197 5198 5199 5200 5201 5202 5203 5204 5205 5206
      /*
	The last parameter to create_tmp_field() is a bit tricky:

	We need to set it to 0 in union, to get fill_record() to modify the
	temporary table.
	We need to set it to 1 on multi-table-update and in select to
	write rows to the temporary table.
	We here distinguish between UNION and multi-table-updates by the fact
	that in the later case group is set to the row pointer.
      */
5207 5208 5209 5210
      Field *new_field= create_tmp_field(thd, table, item, type, &copy_func,
                                         tmp_from_field, group != 0,
                                         not_all_columns || group !=0,
                                         param->convert_blob_length);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5211 5212
      if (!new_field)
      {
5213
	if (thd->is_fatal_error)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5214 5215 5216 5217 5218 5219 5220 5221 5222 5223
	  goto err;				// Got OOM
	continue;				// Some kindf of const item
      }
      if (type == Item::SUM_FUNC_ITEM)
	((Item_sum *) item)->result_field= new_field;
      tmp_from_field++;
      reclength+=new_field->pack_length();
      if (!(new_field->flags & NOT_NULL_FLAG))
	null_count++;
      if (new_field->flags & BLOB_FLAG)
5224 5225
      {
	*blob_field++= new_field;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5226
	blob_count++;
5227
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5228 5229 5230 5231 5232 5233 5234
      if (item->marker == 4 && item->maybe_null)
      {
	group_null_items++;
	new_field->flags|= GROUP_FLAG;
      }
      *(reg_field++) =new_field;
    }
5235 5236
    if (!--hidden_field_count)
      hidden_null_count=null_count;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5237
  }
5238
  DBUG_ASSERT(field_count >= (uint) (reg_field - table->field));
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
5239
  field_count= (uint) (reg_field - table->field);
5240
  *blob_field= 0;				// End marker
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5241 5242

  /* If result table is small; use a heap */
5243
  if (blob_count || using_unique_constraint ||
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262
      (select_options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) ==
      OPTION_BIG_TABLES)
  {
    table->file=get_new_handler(table,table->db_type=DB_TYPE_MYISAM);
    if (group &&
	(param->group_parts > table->file->max_key_parts() ||
	 param->group_length > table->file->max_key_length()))
      using_unique_constraint=1;
  }
  else
  {
    table->file=get_new_handler(table,table->db_type=DB_TYPE_HEAP);
  }

  if (!using_unique_constraint)
    reclength+= group_null_items;	// null flag is stored separately

  table->blob_fields=blob_count;
  if (blob_count == 0)
5263 5264
  {
    /* We need to ensure that first byte is not 0 for the delete link */
5265
    if (param->hidden_field_count)
5266 5267 5268 5269 5270 5271 5272
      hidden_null_count++;
    else
      null_count++;
  }
  hidden_null_pack_length=(hidden_null_count+7)/8;
  null_pack_length=hidden_null_count+(null_count+7)/8;
  reclength+=null_pack_length;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5273 5274 5275 5276 5277 5278 5279 5280
  if (!reclength)
    reclength=1;				// Dummy select

  table->fields=field_count;
  table->reclength=reclength;
  {
    uint alloc_length=ALIGN_SIZE(reclength+MI_UNIQUE_HASH_LENGTH+1);
    table->rec_buff_length=alloc_length;
5281
    if (!(table->record[0]= (byte *) my_malloc(alloc_length*3, MYF(MY_WME))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5282
      goto err;
5283
    table->record[1]= table->record[0]+alloc_length;
5284
    table->default_values= table->record[1]+alloc_length;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297
  }
  copy_func[0]=0;				// End marker

  recinfo=param->start_recinfo;
  null_flags=(uchar*) table->record[0];
  pos=table->record[0]+ null_pack_length;
  if (null_pack_length)
  {
    bzero((byte*) recinfo,sizeof(*recinfo));
    recinfo->type=FIELD_NORMAL;
    recinfo->length=null_pack_length;
    recinfo++;
    bfill(null_flags,null_pack_length,255);	// Set null fields
5298 5299 5300 5301

    table->null_flags= (uchar*) table->record[0];
    table->null_fields= null_count+ hidden_null_count;
    table->null_bytes= null_pack_length;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5302 5303
  }
  null_count= (blob_count == 0) ? 1 : 0;
5304
  hidden_field_count=param->hidden_field_count;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5305 5306 5307 5308 5309 5310 5311 5312 5313 5314
  for (i=0,reg_field=table->field; i < field_count; i++,reg_field++,recinfo++)
  {
    Field *field= *reg_field;
    uint length;
    bzero((byte*) recinfo,sizeof(*recinfo));

    if (!(field->flags & NOT_NULL_FLAG))
    {
      if (field->flags & GROUP_FLAG && !using_unique_constraint)
      {
5315 5316 5317 5318
	/*
	  We have to reserve one byte here for NULL bits,
	  as this is updated by 'end_update()'
	*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352
	*pos++=0;				// Null is stored here
	recinfo->length=1;
	recinfo->type=FIELD_NORMAL;
	recinfo++;
	bzero((byte*) recinfo,sizeof(*recinfo));
      }
      else
      {
	recinfo->null_bit= 1 << (null_count & 7);
	recinfo->null_pos= null_count/8;
      }
      field->move_field((char*) pos,null_flags+null_count/8,
			1 << (null_count & 7));
      null_count++;
    }
    else
      field->move_field((char*) pos,(uchar*) 0,0);
    field->reset();
    if (from_field[i])
    {						/* Not a table Item */
      copy->set(field,from_field[i],save_sum_fields);
      copy++;
    }
    length=field->pack_length();
    pos+= length;

    /* Make entry for create table */
    recinfo->length=length;
    if (field->flags & BLOB_FLAG)
      recinfo->type= (int) FIELD_BLOB;
    else if (!field->zero_pack() &&
	     (field->type() == FIELD_TYPE_STRING ||
	      field->type() == FIELD_TYPE_VAR_STRING) &&
	     length >= 10 && blob_count)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
5353
      recinfo->type=FIELD_SKIP_ENDSPACE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5354 5355
    else
      recinfo->type=FIELD_NORMAL;
5356 5357
    if (!--hidden_field_count)
      null_count=(null_count+7) & ~7;		// move to next byte
5358 5359 5360

    // fix table name in field entry
    field->table_name= table->table_name;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5361 5362
  }

monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
5363
  param->copy_field_end=copy;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5364
  param->recinfo=recinfo;
5365
  store_record(table,default_values);		// Make empty default record
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5366

5367
  if (thd->variables.tmp_table_size == ~(ulong) 0)		// No limit
5368 5369 5370
    table->max_rows= ~(ha_rows) 0;
  else
    table->max_rows=(((table->db_type == DB_TYPE_HEAP) ?
5371 5372 5373
		      min(thd->variables.tmp_table_size,
			  thd->variables.max_heap_table_size) :
		      thd->variables.tmp_table_size)/ table->reclength);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389
  set_if_bigger(table->max_rows,1);		// For dummy start options
  keyinfo=param->keyinfo;

  if (group)
  {
    DBUG_PRINT("info",("Creating group key in temporary table"));
    table->group=group;				/* Table is grouped by key */
    param->group_buff=group_buff;
    table->keys=1;
    table->uniques= test(using_unique_constraint);
    table->key_info=keyinfo;
    keyinfo->key_part=key_part_info;
    keyinfo->flags=HA_NOSAME;
    keyinfo->usable_key_parts=keyinfo->key_parts= param->group_parts;
    keyinfo->key_length=0;
    keyinfo->rec_per_key=0;
5390
    keyinfo->algorithm= HA_KEY_ALG_UNDEF;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5391 5392
    for (; group ; group=group->next,key_part_info++)
    {
5393
      Field *field=(*group->item)->get_tmp_table_field();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5394
      bool maybe_null=(*group->item)->maybe_null;
5395
      key_part_info->null_bit=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406
      key_part_info->field=  field;
      key_part_info->offset= field->offset();
      key_part_info->length= (uint16) field->pack_length();
      key_part_info->type=   (uint8) field->key_type();
      key_part_info->key_type =
	((ha_base_keytype) key_part_info->type == HA_KEYTYPE_TEXT ||
	 (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT) ?
	0 : FIELDFLAG_BINARY;
      if (!using_unique_constraint)
      {
	group->buff=(char*) group_buff;
5407
	if (!(group->field=field->new_field(thd->mem_root,table)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5408 5409 5410 5411
	  goto err; /* purecov: inspected */
	if (maybe_null)
	{
	  /*
5412 5413 5414 5415
	    To be able to group on NULL, we reserve place in group_buff
	    for the NULL flag just before the column.
	    The field data is after this flag.
	    The NULL flag is updated by 'end_update()' and 'end_write()'
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5416
	  */
5417 5418 5419 5420 5421
	  keyinfo->flags|= HA_NULL_ARE_EQUAL;	// def. that NULL == NULL
	  key_part_info->null_bit=field->null_bit;
	  key_part_info->null_offset= (uint) (field->null_ptr -
					      (uchar*) table->record[0]);
	  group->field->move_field((char*) ++group->buff);
5422
	  group_buff++;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5423 5424 5425 5426 5427 5428 5429 5430 5431
	}
	else
	  group->field->move_field((char*) group_buff);
	group_buff+= key_part_info->length;
      }
      keyinfo->key_length+=  key_part_info->length;
    }
  }

5432
  if (distinct)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5433
  {
5434 5435 5436 5437 5438 5439
    /*
      Create an unique key or an unique constraint over all columns
      that should be in the result.  In the temporary table, there are
      'param->hidden_field_count' extra columns, whose null bits are stored
      in the first 'hidden_null_pack_length' bytes of the row.
    */
5440 5441
    DBUG_PRINT("info",("hidden_field_count: %d", param->hidden_field_count));

5442
    null_pack_length-=hidden_null_pack_length;
5443
    keyinfo->key_parts= ((field_count-param->hidden_field_count)+
5444
			 test(null_pack_length));
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
5445 5446
    set_if_smaller(table->max_rows, rows_limit);
    param->end_write_records= rows_limit;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458
    table->distinct=1;
    table->keys=1;
    if (blob_count)
    {
      using_unique_constraint=1;
      table->uniques=1;
    }
    if (!(key_part_info= (KEY_PART_INFO*)
	  sql_calloc((keyinfo->key_parts)*sizeof(KEY_PART_INFO))))
      goto err;
    table->key_info=keyinfo;
    keyinfo->key_part=key_part_info;
5459
    keyinfo->flags=HA_NOSAME | HA_NULL_ARE_EQUAL;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5460 5461
    keyinfo->key_length=(uint16) reclength;
    keyinfo->name=(char*) "tmp";
5462
    keyinfo->algorithm= HA_KEY_ALG_UNDEF;
5463
    keyinfo->rec_per_key=0;
5464
    if (null_pack_length)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5465
    {
5466
      key_part_info->null_bit=0;
5467 5468
      key_part_info->offset=hidden_null_pack_length;
      key_part_info->length=null_pack_length;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5469 5470 5471 5472 5473
      key_part_info->field=new Field_string((char*) table->record[0],
					    (uint32) key_part_info->length,
					    (uchar*) 0,
					    (uint) 0,
					    Field::NONE,
5474
					    NullS, table, &my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5475 5476 5477 5478
      key_part_info->key_type=FIELDFLAG_BINARY;
      key_part_info->type=    HA_KEYTYPE_BINARY;
      key_part_info++;
    }
5479
    /* Create a distinct key over the columns we are going to return */
5480 5481
    for (i=param->hidden_field_count, reg_field=table->field + i ;
	 i < field_count;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5482 5483
	 i++, reg_field++, key_part_info++)
    {
5484
      key_part_info->null_bit=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5485 5486 5487 5488 5489 5490 5491 5492 5493 5494
      key_part_info->field=    *reg_field;
      key_part_info->offset=   (*reg_field)->offset();
      key_part_info->length=   (uint16) (*reg_field)->pack_length();
      key_part_info->type=     (uint8) (*reg_field)->key_type();
      key_part_info->key_type =
	((ha_base_keytype) key_part_info->type == HA_KEYTYPE_TEXT ||
	 (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT) ?
	0 : FIELDFLAG_BINARY;
    }
  }
5495
  if (thd->is_fatal_error)				// If end of memory
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506
    goto err;					 /* purecov: inspected */
  table->db_record_offset=1;
  if (table->db_type == DB_TYPE_MYISAM)
  {
    if (create_myisam_tmp_table(table,param,select_options))
      goto err;
  }
  if (!open_tmp_table(table))
    DBUG_RETURN(table);

 err:
5507 5508 5509 5510 5511
  /*
    Hack to ensure that free_blobs() doesn't fail if blob_field is not yet
    complete
  */
  *table->blob_field= 0;
5512
  free_tmp_table(thd,table);                    /* purecov: inspected */
5513
  bitmap_clear_bit(&temp_pool, temp_pool_slot);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532
  DBUG_RETURN(NULL);				/* purecov: inspected */
}


static bool open_tmp_table(TABLE *table)
{
  int error;
  if ((error=table->file->ha_open(table->real_name,O_RDWR,HA_OPEN_TMP_TABLE)))
  {
    table->file->print_error(error,MYF(0)); /* purecov: inspected */
    table->db_stat=0;
    return(1);
  }
  (void) table->file->extra(HA_EXTRA_QUICK);		/* Faster */
  return(0);
}


static bool create_myisam_tmp_table(TABLE *table,TMP_TABLE_PARAM *param,
5533
				    ulong options)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5534 5535 5536 5537 5538 5539 5540 5541 5542 5543
{
  int error;
  MI_KEYDEF keydef;
  MI_UNIQUEDEF uniquedef;
  KEY *keyinfo=param->keyinfo;

  DBUG_ENTER("create_myisam_tmp_table");
  if (table->keys)
  {						// Get keys for ni_create
    bool using_unique_constraint=0;
5544
    HA_KEYSEG *seg= (HA_KEYSEG*) sql_calloc(sizeof(*seg) *
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579
					    keyinfo->key_parts);
    if (!seg)
      goto err;

    if (keyinfo->key_length >= table->file->max_key_length() ||
	keyinfo->key_parts > table->file->max_key_parts() ||
	table->uniques)
    {
      /* Can't create a key; Make a unique constraint instead of a key */
      table->keys=0;
      table->uniques=1;
      using_unique_constraint=1;
      bzero((char*) &uniquedef,sizeof(uniquedef));
      uniquedef.keysegs=keyinfo->key_parts;
      uniquedef.seg=seg;
      uniquedef.null_are_equal=1;

      /* Create extra column for hash value */
      bzero((byte*) param->recinfo,sizeof(*param->recinfo));
      param->recinfo->type= FIELD_CHECK;
      param->recinfo->length=MI_UNIQUE_HASH_LENGTH;
      param->recinfo++;
      table->reclength+=MI_UNIQUE_HASH_LENGTH;
    }
    else
    {
      /* Create an unique key */
      bzero((char*) &keydef,sizeof(keydef));
      keydef.flag=HA_NOSAME | HA_BINARY_PACK_KEY | HA_PACK_KEY;
      keydef.keysegs=  keyinfo->key_parts;
      keydef.seg= seg;
    }
    for (uint i=0; i < keyinfo->key_parts ; i++,seg++)
    {
      Field *field=keyinfo->key_part[i].field;
5580
      seg->flag=     0;
5581
      seg->language= field->charset()->number;
5582 5583
      seg->length=   keyinfo->key_part[i].length;
      seg->start=    keyinfo->key_part[i].offset;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603
      if (field->flags & BLOB_FLAG)
      {
	seg->type=
	((keyinfo->key_part[i].key_type & FIELDFLAG_BINARY) ?
	 HA_KEYTYPE_VARBINARY : HA_KEYTYPE_VARTEXT);
	seg->bit_start=seg->length - table->blob_ptr_size;
	seg->flag= HA_BLOB_PART;
	seg->length=0;			// Whole blob in unique constraint
      }
      else
      {
	seg->type=
	  ((keyinfo->key_part[i].key_type & FIELDFLAG_BINARY) ?
	   HA_KEYTYPE_BINARY : HA_KEYTYPE_TEXT);
	if (!(field->flags & ZEROFILL_FLAG) &&
	    (field->type() == FIELD_TYPE_STRING ||
	     field->type() == FIELD_TYPE_VAR_STRING) &&
	    keyinfo->key_part[i].length > 4)
	  seg->flag|=HA_SPACE_PACK;
      }
5604
      if (!(field->flags & NOT_NULL_FLAG))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5605 5606 5607
      {
	seg->null_bit= field->null_bit;
	seg->null_pos= (uint) (field->null_ptr - (uchar*) table->record[0]);
5608 5609 5610 5611 5612 5613 5614
	/*
	  We are using a GROUP BY on something that contains NULL
	  In this case we have to tell MyISAM that two NULL should
	  on INSERT be compared as equal
	*/
	if (!using_unique_constraint)
	  keydef.flag|= HA_NULL_ARE_EQUAL;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5615 5616 5617 5618 5619
      }
    }
  }
  MI_CREATE_INFO create_info;
  bzero((char*) &create_info,sizeof(create_info));
5620

5621 5622
  if ((options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) ==
      OPTION_BIG_TABLES)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635
    create_info.data_file_length= ~(ulonglong) 0;

  if ((error=mi_create(table->real_name,table->keys,&keydef,
		       (uint) (param->recinfo-param->start_recinfo),
		       param->start_recinfo,
		       table->uniques, &uniquedef,
		       &create_info,
		       HA_CREATE_TMP_TABLE)))
  {
    table->file->print_error(error,MYF(0));	/* purecov: inspected */
    table->db_stat=0;
    goto err;
  }
5636
  statistic_increment(created_tmp_disk_tables, &LOCK_status);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652
  table->db_record_offset=1;
  DBUG_RETURN(0);
 err:
  DBUG_RETURN(1);
}


void
free_tmp_table(THD *thd, TABLE *entry)
{
  const char *save_proc_info;
  DBUG_ENTER("free_tmp_table");
  DBUG_PRINT("enter",("table: %s",entry->table_name));

  save_proc_info=thd->proc_info;
  thd->proc_info="removing tmp table";
5653
  free_blobs(entry);
5654
  if (entry->file)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5655
  {
5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666
    if (entry->db_stat)
    {
      (void) entry->file->close();
    }
    /*
      We can't call ha_delete_table here as the table may created in mixed case
      here and we have to ensure that delete_table gets the table name in
      the original case.
    */
    if (!(test_flags & TEST_KEEP_TMP_TABLES) || entry->db_type == DB_TYPE_HEAP)
      entry->file->delete_table(entry->real_name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5667 5668
    delete entry->file;
  }
5669

bk@work.mysql.com's avatar
bk@work.mysql.com committed
5670 5671
  /* free blobs */
  for (Field **ptr=entry->field ; *ptr ; ptr++)
5672
    (*ptr)->free();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5673 5674
  my_free((gptr) entry->record[0],MYF(0));
  free_io_cache(entry);
5675

5676
  bitmap_clear_bit(&temp_pool, entry->temp_pool_slot);
5677

bk@work.mysql.com's avatar
bk@work.mysql.com committed
5678 5679 5680 5681 5682 5683 5684 5685 5686 5687
  my_free((gptr) entry,MYF(0));
  thd->proc_info=save_proc_info;

  DBUG_VOID_RETURN;
}

/*
* If a HEAP table gets full, create a MyISAM table and copy all rows to this
*/

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
5688 5689
bool create_myisam_from_heap(THD *thd, TABLE *table, TMP_TABLE_PARAM *param,
			     int error, bool ignore_last_dupp_key_error)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709
{
  TABLE new_table;
  const char *save_proc_info;
  int write_err;
  DBUG_ENTER("create_myisam_from_heap");

  if (table->db_type != DB_TYPE_HEAP || error != HA_ERR_RECORD_FILE_FULL)
  {
    table->file->print_error(error,MYF(0));
    DBUG_RETURN(1);
  }
  new_table= *table;
  new_table.db_type=DB_TYPE_MYISAM;
  if (!(new_table.file=get_new_handler(&new_table,DB_TYPE_MYISAM)))
    DBUG_RETURN(1);				// End of memory

  save_proc_info=thd->proc_info;
  thd->proc_info="converting HEAP to MyISAM";

  if (create_myisam_tmp_table(&new_table,param,
5710
			      thd->lex->select_lex.options | thd->options))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5711 5712 5713
    goto err2;
  if (open_tmp_table(&new_table))
    goto err1;
5714 5715
  if (table->file->indexes_are_disabled())
    new_table.file->disable_indexes(HA_KEY_SWITCH_ALL);
5716
  table->file->ha_index_or_rnd_end();
5717
  table->file->ha_rnd_init(1);
5718 5719
  if (table->no_rows)
  {
5720 5721
    new_table.file->extra(HA_EXTRA_NO_ROWS);
    new_table.no_rows=1;
5722 5723
  }

5724 5725 5726 5727 5728 5729 5730 5731
#ifdef TO_BE_DONE_LATER_IN_4_1
  /*
    To use start_bulk_insert() (which is new in 4.1) we need to find
    all places where a corresponding end_bulk_insert() should be put.
  */
  table->file->info(HA_STATUS_VARIABLE); /* update table->file->records */
  new_table.file->start_bulk_insert(table->file->records);
#else
monty@mysql.com's avatar
monty@mysql.com committed
5732
  /* HA_EXTRA_WRITE_CACHE can stay until close, no need to disable it */
5733 5734 5735
  new_table.file->extra(HA_EXTRA_WRITE_CACHE);
#endif

bk@work.mysql.com's avatar
bk@work.mysql.com committed
5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750
  /* copy all old rows */
  while (!table->file->rnd_next(new_table.record[1]))
  {
    if ((write_err=new_table.file->write_row(new_table.record[1])))
      goto err;
  }
  /* copy row that filled HEAP table */
  if ((write_err=new_table.file->write_row(table->record[0])))
  {
    if (write_err != HA_ERR_FOUND_DUPP_KEY &&
	write_err != HA_ERR_FOUND_DUPP_UNIQUE || !ignore_last_dupp_key_error)
    goto err;
  }

  /* remove heap table and change to use myisam table */
5751
  (void) table->file->ha_rnd_end();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5752 5753 5754 5755 5756 5757
  (void) table->file->close();
  (void) table->file->delete_table(table->real_name);
  delete table->file;
  table->file=0;
  *table =new_table;
  table->file->change_table_ptr(table);
5758 5759
  thd->proc_info= (!strcmp(save_proc_info,"Copying to tmp table") ?
		   "Copying to tmp table on disk" : save_proc_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5760 5761 5762 5763 5764
  DBUG_RETURN(0);

 err:
  DBUG_PRINT("error",("Got error: %d",write_err));
  table->file->print_error(error,MYF(0));	// Give table is full error
5765
  (void) table->file->ha_rnd_end();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5766 5767 5768 5769 5770 5771 5772 5773 5774 5775
  (void) new_table.file->close();
 err1:
  new_table.file->delete_table(new_table.real_name);
  delete new_table.file;
 err2:
  thd->proc_info=save_proc_info;
  DBUG_RETURN(1);
}


5776 5777 5778 5779 5780 5781
/****************************************************************************
  Make a join of all tables and write it on socket or to table
  Return:  0 if ok
           1 if error is sent
          -1 if error should be sent
****************************************************************************/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5782 5783 5784 5785

static int
do_select(JOIN *join,List<Item> *fields,TABLE *table,Procedure *procedure)
{
5786
  int error= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5787 5788 5789 5790 5791 5792
  JOIN_TAB *join_tab;
  int (*end_select)(JOIN *, struct st_join_table *,bool);
  DBUG_ENTER("do_select");

  join->procedure=procedure;
  /*
5793
    Tell the client how many fields there are in a row
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5794 5795 5796 5797 5798 5799 5800 5801
  */
  if (!table)
    join->result->send_fields(*fields,1);
  else
  {
    VOID(table->file->extra(HA_EXTRA_WRITE_CACHE));
    empty_record(table);
  }
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5802
  join->tmp_table= table;			/* Save for easy recursion */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5803 5804 5805 5806 5807 5808 5809 5810 5811
  join->fields= fields;

  /* Set up select_end */
  if (table)
  {
    if (table->group && join->tmp_table_param.sum_func_count)
    {
      if (table->keys)
      {
5812
	DBUG_PRINT("info",("Using end_update"));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5813
	end_select=end_update;
5814 5815
        if (!table->file->inited)
          table->file->ha_index_init(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5816 5817
      }
      else
5818 5819
      {
	DBUG_PRINT("info",("Using end_unique_update"));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5820
	end_select=end_unique_update;
5821
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847
    }
    else if (join->sort_and_group)
    {
      DBUG_PRINT("info",("Using end_write_group"));
      end_select=end_write_group;
    }
    else
    {
      DBUG_PRINT("info",("Using end_write"));
      end_select=end_write;
    }
  }
  else
  {
    if (join->sort_and_group || (join->procedure &&
				 join->procedure->flags & PROC_GROUP))
      end_select=end_send_group;
    else
      end_select=end_send;
  }
  join->join_tab[join->tables-1].next_select=end_select;

  join_tab=join->join_tab+join->const_tables;
  join->send_records=0;
  if (join->tables == join->const_tables)
  {
5848 5849 5850 5851
    /*
      HAVING will be chcked after processing aggregate functions,
      But WHERE should checkd here (we alredy have read tables)
    */
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
5852
    if (!join->conds || join->conds->val_int())
5853
    {
5854 5855
      if (!(error=(*end_select)(join,join_tab,0)) || error == -3)
	error=(*end_select)(join,join_tab,1);
5856
    }
5857
    else if (join->send_row_on_empty_set())
5858
      error= join->result->send_data(*join->fields);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5859 5860 5861
  }
  else
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5862
    error= sub_select(join,join_tab,0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5863
    if (error >= 0)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5864
      error= sub_select(join,join_tab,1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5865
    if (error == -3)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5866
      error= 0;					/* select_limit used */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5867
  }
5868

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5869
  if (error >= 0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5870
  {
5871 5872
    error=0;
    if (!table)					// If sending data to client
5873
    {
5874
      /*
5875 5876
	The following will unlock all cursors if the command wasn't an
	update command
5877
      */
5878
      join->join_free(0);				// Unlock all cursors
5879
      if (join->result->send_eof())
5880
	error= 1;				// Don't send error
5881
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5882 5883 5884 5885
    DBUG_PRINT("info",("%ld records output",join->send_records));
  }
  if (table)
  {
5886
    int tmp;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5887 5888
    if ((tmp=table->file->extra(HA_EXTRA_NO_CACHE)))
    {
5889 5890
      DBUG_PRINT("error",("extra(HA_EXTRA_NO_CACHE) failed"));
      my_errno= tmp;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5891 5892
      error= -1;
    }
5893
    if ((tmp=table->file->ha_index_or_rnd_end()))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5894
    {
5895
      DBUG_PRINT("error",("ha_index_or_rnd_end() failed"));
5896
      my_errno= tmp;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5897 5898
      error= -1;
    }
5899
    if (error == -1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5900 5901
      table->file->print_error(my_errno,MYF(0));
  }
5902 5903 5904 5905 5906 5907
#ifndef DBUG_OFF
  if (error)
  {
    DBUG_PRINT("error",("Error: do_select() failed"));
  }
#endif
5908
  DBUG_RETURN(join->thd->net.report_error ? -1 : error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922
}


static int
sub_select_cache(JOIN *join,JOIN_TAB *join_tab,bool end_of_records)
{
  int error;

  if (end_of_records)
  {
    if ((error=flush_cached_records(join,join_tab,FALSE)) < 0)
      return error; /* purecov: inspected */
    return sub_select(join,join_tab,end_of_records);
  }
5923 5924 5925 5926 5927
  if (join->thd->killed)		// If aborted by user
  {
    my_error(ER_SERVER_SHUTDOWN,MYF(0)); /* purecov: inspected */
    return -2;				 /* purecov: inspected */
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951
  if (join_tab->use_quick != 2 || test_if_quick_select(join_tab) <= 0)
  {
    if (!store_record_in_cache(&join_tab->cache))
      return 0;					// There is more room in cache
    return flush_cached_records(join,join_tab,FALSE);
  }
  if ((error=flush_cached_records(join,join_tab,TRUE)) < 0)
    return error; /* purecov: inspected */
  return sub_select(join,join_tab,end_of_records); /* Use ordinary select */
}


static int
sub_select(JOIN *join,JOIN_TAB *join_tab,bool end_of_records)
{

  join_tab->table->null_row=0;
  if (end_of_records)
    return (*join_tab->next_select)(join,join_tab+1,end_of_records);

  /* Cache variables for faster loop */
  int error;
  bool found=0;
  COND *on_expr=join_tab->on_expr, *select_cond=join_tab->select_cond;
5952
  my_bool *report_error= &(join->thd->net.report_error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5953 5954 5955

  if (!(error=(*join_tab->read_first_record)(join_tab)))
  {
monty@tramp.mysql.fi's avatar
monty@tramp.mysql.fi committed
5956 5957 5958
    bool not_exists_optimize= join_tab->table->reginfo.not_exists_optimize;
    bool not_used_in_distinct=join_tab->not_used_in_distinct;
    ha_rows found_records=join->found_records;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5959 5960
    READ_RECORD *info= &join_tab->read_record;

5961
    join->thd->row_count= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5962 5963 5964 5965 5966 5967 5968
    do
    {
      if (join->thd->killed)			// Aborted by user
      {
	my_error(ER_SERVER_SHUTDOWN,MYF(0));	/* purecov: inspected */
	return -2;				/* purecov: inspected */
      }
5969
      join->examined_rows++;
5970
      join->thd->row_count++;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5971 5972 5973 5974 5975 5976 5977
      if (!on_expr || on_expr->val_int())
      {
	found=1;
	if (not_exists_optimize)
	  break;			// Searching after not null columns
	if (!select_cond || select_cond->val_int())
	{
5978
	  if ((error=(*join_tab->next_select)(join,join_tab+1,0)) < 0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5979
	    return error;
5980 5981 5982 5983 5984
	  /*
	    Test if this was a SELECT DISTINCT query on a table that
	    was not in the field list;  In this case we can abort if
	    we found a row, as no new rows can be added to the result.
	  */
monty@tramp.mysql.fi's avatar
monty@tramp.mysql.fi committed
5985 5986
	  if (not_used_in_distinct && found_records != join->found_records)
	    return 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5987
	}
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
5988
	else
5989 5990 5991 5992 5993 5994 5995
        {
          /* 
            This row failed selection, release lock on it.
            XXX: There is no table handler in MySQL which makes use of this
            call. It's kept from Gemini times. A lot of new code was added
            recently (i. e. subselects) without having it in mind.
          */
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
5996
	  info->file->unlock_row();
5997
        }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
5998
      }
5999
    } while (!(error=info->read_record(info)) && !(*report_error));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6000
  }
6001
  if (error > 0 || (*report_error))				// Fatal error
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6002 6003 6004 6005
    return -1;

  if (!found && on_expr)
  {						// OUTER JOIN
6006
    restore_record(join_tab->table,default_values);		// Make empty record
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6007 6008 6009
    mark_as_null_row(join_tab->table);		// For group by without error
    if (!select_cond || select_cond->val_int())
    {
6010
      if ((error=(*join_tab->next_select)(join,join_tab+1,0)) < 0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6011 6012 6013 6014 6015 6016 6017 6018
	return error;				/* purecov: inspected */
    }
  }
  return 0;
}


static int
6019
flush_cached_records(JOIN *join,JOIN_TAB *join_tab,bool skip_last)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6020 6021 6022 6023 6024 6025
{
  int error;
  READ_RECORD *info;

  if (!join_tab->cache.records)
    return 0;				/* Nothing to do */
6026
  if (skip_last)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038
    (void) store_record_in_cache(&join_tab->cache); // Must save this for later
  if (join_tab->use_quick == 2)
  {
    if (join_tab->select->quick)
    {					/* Used quick select last. reset it */
      delete join_tab->select->quick;
      join_tab->select->quick=0;
    }
  }
 /* read through all records */
  if ((error=join_init_read_record(join_tab)))
  {
6039
    reset_cache_write(&join_tab->cache);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058
    return -error;			/* No records or error */
  }

  for (JOIN_TAB *tmp=join->join_tab; tmp != join_tab ; tmp++)
  {
    tmp->status=tmp->table->status;
    tmp->table->status=0;
  }

  info= &join_tab->read_record;
  do
  {
    if (join->thd->killed)
    {
      my_error(ER_SERVER_SHUTDOWN,MYF(0)); /* purecov: inspected */
      return -2;				// Aborted by user /* purecov: inspected */
    }
    SQL_SELECT *select=join_tab->select;
    if (!error && (!join_tab->cache.select ||
6059
		   !join_tab->cache.select->skip_record()))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6060 6061
    {
      uint i;
6062
      reset_cache_read(&join_tab->cache);
6063
      for (i=(join_tab->cache.records- (skip_last ? 1 : 0)) ; i-- > 0 ;)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6064 6065
      {
	read_cached_record(join_tab);
6066
	if (!select || !select->skip_record())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6067
	  if ((error=(join_tab->next_select)(join,join_tab+1,0)) < 0)
6068 6069
          {
            reset_cache_write(&join_tab->cache);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6070
	    return error; /* purecov: inspected */
6071
          }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6072 6073 6074 6075
      }
    }
  } while (!(error=info->read_record(info)));

6076
  if (skip_last)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6077
    read_cached_record(join_tab);		// Restore current record
6078
  reset_cache_write(&join_tab->cache);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6079 6080 6081 6082 6083 6084 6085 6086 6087
  if (error > 0)				// Fatal error
    return -1;					/* purecov: inspected */
  for (JOIN_TAB *tmp2=join->join_tab; tmp2 != join_tab ; tmp2++)
    tmp2->table->status=tmp2->status;
  return 0;
}


/*****************************************************************************
6088 6089
  The different ways to read a record
  Returns -1 if row was not found, 0 if row was found and 1 on errors
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6090
*****************************************************************************/
6091 6092 6093

/* Help function when we get some an error from the table handler */

6094
int report_error(TABLE *table, int error)
6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112
{
  if (error == HA_ERR_END_OF_FILE || error == HA_ERR_KEY_NOT_FOUND)
  {
    table->status= STATUS_GARBAGE;
    return -1;					// key not found; ok
  }
  /*
    Locking reads can legally return also these errors, do not
    print them to the .err log
  */
  if (error != HA_ERR_LOCK_DEADLOCK && error != HA_ERR_LOCK_WAIT_TIMEOUT)
    sql_print_error("Got error %d when reading table '%s'",
		    error, table->path);
  table->file->print_error(error,MYF(0));
  return 1;
}


6113
int safe_index_read(JOIN_TAB *tab)
6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124
{
  int error;
  TABLE *table= tab->table;
  if ((error=table->file->index_read(table->record[0],
				     tab->ref.key_buff,
				     tab->ref.key_length, HA_READ_KEY_EXACT)))
    return report_error(table, error);
  return 0;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
6125
static int
6126
join_read_const_table(JOIN_TAB *tab, POSITION *pos)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6127 6128
{
  int error;
6129 6130 6131 6132 6133 6134 6135
  DBUG_ENTER("join_read_const_table");
  TABLE *table=tab->table;
  table->const_table=1;
  table->null_row=0;
  table->status=STATUS_NO_RECORD;
  
  if (tab->type == JT_SYSTEM)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6136
  {
6137 6138 6139 6140 6141 6142 6143
    if ((error=join_read_system(tab)))
    {						// Info for DESCRIBE
      tab->info="const row not found";
      /* Mark for EXPLAIN that the row was not found */
      pos->records_read=0.0;
      if (!table->outer_join || error > 0)
	DBUG_RETURN(error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6144
    }
6145 6146 6147
  }
  else
  {
6148
    if (!table->key_read && table->used_keys.is_set(tab->ref.key) &&
6149 6150
	!table->no_keyread &&
        (int) table->reginfo.lock_type <= (int) TL_READ_HIGH_PRIORITY)
6151 6152 6153
    {
      table->key_read=1;
      table->file->extra(HA_EXTRA_KEYREAD);
6154
      tab->index= tab->ref.key;
6155
    }
6156
    if ((error=join_read_const(tab)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6157
    {
6158 6159 6160 6161 6162
      tab->info="unique row not found";
      /* Mark for EXPLAIN that the row was not found */
      pos->records_read=0.0;
      if (!table->outer_join || error > 0)
	DBUG_RETURN(error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6163
    }
6164 6165 6166 6167 6168
    if (table->key_read)
    {
      table->key_read=0;
      table->file->extra(HA_EXTRA_NO_KEYREAD);
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6169
  }
6170 6171 6172
  if (tab->on_expr && !table->null_row)
  {
    if ((table->null_row= test(tab->on_expr->val_int() == 0)))
6173 6174
      mark_as_null_row(table);  
  }
6175 6176
  if (!table->null_row)
    table->maybe_null=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187
  DBUG_RETURN(0);
}


static int
join_read_system(JOIN_TAB *tab)
{
  TABLE *table= tab->table;
  int error;
  if (table->status & STATUS_GARBAGE)		// If first read
  {
6188 6189
    if ((error=table->file->read_first_row(table->record[0],
					   table->primary_key)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6190 6191
    {
      if (error != HA_ERR_END_OF_FILE)
6192
	return report_error(table, error);
6193
      mark_as_null_row(tab->table);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6194 6195 6196
      empty_record(table);			// Make empty record
      return -1;
    }
6197
    store_record(table,record[1]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6198 6199
  }
  else if (!table->status)			// Only happens with left join
6200
    restore_record(table,record[1]);			// restore old record
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212
  table->null_row=0;
  return table->status ? -1 : 0;
}


static int
join_read_const(JOIN_TAB *tab)
{
  int error;
  TABLE *table= tab->table;
  if (table->status & STATUS_GARBAGE)		// If first read
  {
sergefp@mysql.com's avatar
sergefp@mysql.com committed
6213
    if (cp_buffer_from_ref(tab->join->thd, &tab->ref))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6214 6215 6216 6217 6218 6219 6220 6221 6222
      error=HA_ERR_KEY_NOT_FOUND;
    else
    {
      error=table->file->index_read_idx(table->record[0],tab->ref.key,
					(byte*) tab->ref.key_buff,
					tab->ref.key_length,HA_READ_KEY_EXACT);
    }
    if (error)
    {
6223
      mark_as_null_row(tab->table);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6224 6225
      empty_record(table);
      if (error != HA_ERR_KEY_NOT_FOUND)
6226
	return report_error(table, error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6227 6228
      return -1;
    }
6229
    store_record(table,record[1]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6230
  }
6231 6232 6233
  else if (!(table->status & ~STATUS_NULL_ROW))	// Only happens with left join
  {
    table->status=0;
6234
    restore_record(table,record[1]);			// restore old record
6235
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246
  table->null_row=0;
  return table->status ? -1 : 0;
}


static int
join_read_key(JOIN_TAB *tab)
{
  int error;
  TABLE *table= tab->table;

6247 6248
  if (!table->file->inited)
    table->file->ha_index_init(tab->ref.key);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6249
  if (cmp_buffer_with_ref(tab) ||
6250
      (table->status & (STATUS_GARBAGE | STATUS_NO_PARENT | STATUS_NULL_ROW)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6251 6252 6253 6254 6255 6256 6257 6258 6259 6260
  {
    if (tab->ref.key_err)
    {
      table->status=STATUS_NOT_FOUND;
      return -1;
    }
    error=table->file->index_read(table->record[0],
				  tab->ref.key_buff,
				  tab->ref.key_length,HA_READ_KEY_EXACT);
    if (error && error != HA_ERR_KEY_NOT_FOUND)
6261
      return report_error(table, error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6262
  }
6263
  table->null_row=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6264 6265 6266 6267 6268 6269 6270 6271 6272 6273
  return table->status ? -1 : 0;
}


static int
join_read_always_key(JOIN_TAB *tab)
{
  int error;
  TABLE *table= tab->table;

6274 6275
  if (!table->file->inited)
    table->file->ha_index_init(tab->ref.key);
sergefp@mysql.com's avatar
sergefp@mysql.com committed
6276
  if (cp_buffer_from_ref(tab->join->thd, &tab->ref))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6277 6278 6279 6280 6281 6282
    return -1;
  if ((error=table->file->index_read(table->record[0],
				     tab->ref.key_buff,
				     tab->ref.key_length,HA_READ_KEY_EXACT)))
  {
    if (error != HA_ERR_KEY_NOT_FOUND)
6283
      return report_error(table, error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6284 6285 6286 6287 6288
    return -1; /* purecov: inspected */
  }
  return 0;
}

6289

6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300
/*
  This function is used when optimizing away ORDER BY in 
  SELECT * FROM t1 WHERE a=1 ORDER BY a DESC,b DESC
*/
  
static int
join_read_last_key(JOIN_TAB *tab)
{
  int error;
  TABLE *table= tab->table;

6301 6302
  if (!table->file->inited)
    table->file->ha_index_init(tab->ref.key);
sergefp@mysql.com's avatar
sergefp@mysql.com committed
6303
  if (cp_buffer_from_ref(tab->join->thd, &tab->ref))
6304 6305 6306 6307 6308 6309
    return -1;
  if ((error=table->file->index_read_last(table->record[0],
					  tab->ref.key_buff,
					  tab->ref.key_length)))
  {
    if (error != HA_ERR_KEY_NOT_FOUND)
6310
      return report_error(table, error);
6311 6312 6313 6314 6315
    return -1; /* purecov: inspected */
  }
  return 0;
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
6316 6317 6318 6319 6320 6321 6322 6323 6324 6325

	/* ARGSUSED */
static int
join_no_more_records(READ_RECORD *info __attribute__((unused)))
{
  return -1;
}


static int
6326
join_read_next_same(READ_RECORD *info)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6327 6328 6329 6330 6331 6332 6333 6334 6335 6336
{
  int error;
  TABLE *table= info->table;
  JOIN_TAB *tab=table->reginfo.join_tab;

  if ((error=table->file->index_next_same(table->record[0],
					  tab->ref.key_buff,
					  tab->ref.key_length)))
  {
    if (error != HA_ERR_END_OF_FILE)
6337
      return report_error(table, error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6338 6339 6340 6341 6342 6343
    table->status= STATUS_GARBAGE;
    return -1;
  }
  return 0;
}

6344

6345 6346 6347 6348 6349 6350 6351 6352
static int
join_read_prev_same(READ_RECORD *info)
{
  int error;
  TABLE *table= info->table;
  JOIN_TAB *tab=table->reginfo.join_tab;

  if ((error=table->file->index_prev(table->record[0])))
6353
    return report_error(table, error);
6354 6355
  if (key_cmp_if_same(table, tab->ref.key_buff, tab->ref.key,
                      tab->ref.key_length))
6356 6357
  {
    table->status=STATUS_NOT_FOUND;
6358
    error= -1;
6359 6360 6361 6362
  }
  return error;
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377

static int
join_init_quick_read_record(JOIN_TAB *tab)
{
  if (test_if_quick_select(tab) == -1)
    return -1;					/* No possible records */
  return join_init_read_record(tab);
}


static int
test_if_quick_select(JOIN_TAB *tab)
{
  delete tab->select->quick;
  tab->select->quick=0;
6378
  return tab->select->test_quick_select(tab->join->thd, tab->keys,
6379
					(table_map) 0, HA_POS_ERROR, 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6380 6381 6382 6383 6384 6385 6386 6387
}


static int
join_init_read_record(JOIN_TAB *tab)
{
  if (tab->select && tab->select->quick)
    tab->select->quick->reset();
6388 6389
  init_read_record(&tab->read_record, tab->join->thd, tab->table,
		   tab->select,1,1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6390 6391 6392
  return (*tab->read_record.read_record)(&tab->read_record);
}

6393

bk@work.mysql.com's avatar
bk@work.mysql.com committed
6394
static int
6395
join_read_first(JOIN_TAB *tab)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6396 6397 6398
{
  int error;
  TABLE *table=tab->table;
6399
  if (!table->key_read && table->used_keys.is_set(tab->index) &&
6400
      !table->no_keyread)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6401 6402 6403 6404 6405
  {
    table->key_read=1;
    table->file->extra(HA_EXTRA_KEYREAD);
  }
  tab->table->status=0;
6406
  tab->read_record.read_record=join_read_next;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6407 6408 6409 6410
  tab->read_record.table=table;
  tab->read_record.file=table->file;
  tab->read_record.index=tab->index;
  tab->read_record.record=table->record[0];
6411 6412
  if (!table->file->inited)
    table->file->ha_index_init(tab->index);
6413
  if ((error=tab->table->file->index_first(tab->table->record[0])))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6414 6415
  {
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
6416
      report_error(table, error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6417 6418 6419 6420 6421
    return -1;
  }
  return 0;
}

6422

bk@work.mysql.com's avatar
bk@work.mysql.com committed
6423
static int
6424
join_read_next(READ_RECORD *info)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6425
{
6426 6427 6428
  int error;
  if ((error=info->file->index_next(info->record)))
    return report_error(info->table, error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6429 6430 6431
  return 0;
}

6432

bk@work.mysql.com's avatar
bk@work.mysql.com committed
6433
static int
6434
join_read_last(JOIN_TAB *tab)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6435 6436 6437
{
  TABLE *table=tab->table;
  int error;
6438
  if (!table->key_read && table->used_keys.is_set(tab->index) &&
6439
      !table->no_keyread)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6440 6441 6442 6443 6444
  {
    table->key_read=1;
    table->file->extra(HA_EXTRA_KEYREAD);
  }
  tab->table->status=0;
6445
  tab->read_record.read_record=join_read_prev;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6446 6447 6448 6449
  tab->read_record.table=table;
  tab->read_record.file=table->file;
  tab->read_record.index=tab->index;
  tab->read_record.record=table->record[0];
6450 6451
  if (!table->file->inited)
    table->file->ha_index_init(tab->index);
6452 6453
  if ((error= tab->table->file->index_last(tab->table->record[0])))
    return report_error(table, error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6454 6455 6456
  return 0;
}

6457

bk@work.mysql.com's avatar
bk@work.mysql.com committed
6458
static int
6459
join_read_prev(READ_RECORD *info)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6460
{
6461 6462 6463
  int error;
  if ((error= info->file->index_prev(info->record)))
    return report_error(info->table, error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6464 6465 6466
  return 0;
}

6467

bk@work.mysql.com's avatar
bk@work.mysql.com committed
6468 6469 6470 6471 6472 6473
static int
join_ft_read_first(JOIN_TAB *tab)
{
  int error;
  TABLE *table= tab->table;

6474 6475
  if (!table->file->inited)
    table->file->ha_index_init(tab->ref.key);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
6476
#if NOT_USED_YET
sergefp@mysql.com's avatar
sergefp@mysql.com committed
6477
  if (cp_buffer_from_ref(tab->join->thd, &tab->ref)) // as ft-key doesn't use store_key's
6478
    return -1;                             // see also FT_SELECT::init()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6479
#endif
6480
  table->file->ft_init();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6481

6482 6483
  if ((error= table->file->ft_read(table->record[0])))
    return report_error(table, error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6484 6485 6486 6487 6488 6489
  return 0;
}

static int
join_ft_read_next(READ_RECORD *info)
{
6490 6491 6492
  int error;
  if ((error= info->file->ft_read(info->table->record[0])))
    return report_error(info->table, error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6493 6494 6495 6496
  return 0;
}


6497 6498 6499 6500 6501 6502 6503 6504 6505 6506
/*
  Reading of key with key reference and one part that may be NULL
*/

static int
join_read_always_key_or_null(JOIN_TAB *tab)
{
  int res;

  /* First read according to key which is NOT NULL */
6507
  *tab->ref.null_ref_key= 0;			// Clear null byte
6508 6509 6510 6511
  if ((res= join_read_always_key(tab)) >= 0)
    return res;

  /* Then read key with null value */
6512
  *tab->ref.null_ref_key= 1;			// Set null byte
6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525
  return safe_index_read(tab);
}


static int
join_read_next_same_or_null(READ_RECORD *info)
{
  int error;
  if ((error= join_read_next_same(info)) >= 0)
    return error;
  JOIN_TAB *tab= info->table->reginfo.join_tab;

  /* Test if we have already done a read after null key */
6526
  if (*tab->ref.null_ref_key)
6527
    return -1;					// All keys read
6528 6529
  *tab->ref.null_ref_key= 1;			// Set null byte
  return safe_index_read(tab);			// then read null keys
6530 6531 6532
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
6533
/*****************************************************************************
6534 6535 6536
  The different end of select functions
  These functions returns < 0 when end is reached, 0 on ok and > 0 if a
  fatal error (like table corruption) was detected
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6537 6538
*****************************************************************************/

6539
/* ARGSUSED */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6540 6541 6542 6543 6544 6545 6546 6547
static int
end_send(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
	 bool end_of_records)
{
  DBUG_ENTER("end_send");
  if (!end_of_records)
  {
    int error;
6548
    if (join->having && join->having->val_int() == 0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6549
      DBUG_RETURN(0);				// Didn't match having
6550
    error=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6551 6552
    if (join->procedure)
      error=join->procedure->send_row(*join->fields);
6553
    else if (join->do_send_rows)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6554 6555 6556
      error=join->result->send_data(*join->fields);
    if (error)
      DBUG_RETURN(-1); /* purecov: inspected */
6557
    if (++join->send_records >= join->unit->select_limit_cnt &&
6558
	join->do_send_rows)
6559 6560 6561
    {
      if (join->select_options & OPTION_FOUND_ROWS)
      {
6562
	JOIN_TAB *jt=join->join_tab;
6563
	if ((join->tables == 1) && !join->tmp_table && !join->sort_and_group
6564
	    && !join->send_group_parts && !join->having && !jt->select_cond &&
6565
	    !(jt->select && jt->select->quick) &&
ram@gw.mysql.r18.ru's avatar
ram@gw.mysql.r18.ru committed
6566 6567
	    !(jt->table->file->table_flags() & HA_NOT_EXACT_COUNT) &&
            (jt->ref.key < 0))
6568
	{
6569
	  /* Join over all rows in table;  Return number of found rows */
6570 6571
	  TABLE *table=jt->table;

6572
	  join->select_options ^= OPTION_FOUND_ROWS;
igor@hundin.mysql.fi's avatar
igor@hundin.mysql.fi committed
6573 6574
	  if (table->sort.record_pointers ||
	      (table->sort.io_cache && my_b_inited(table->sort.io_cache)))
6575 6576
	  {
	    /* Using filesort */
igor@hundin.mysql.fi's avatar
igor@hundin.mysql.fi committed
6577
	    join->send_records= table->sort.found_records;
6578 6579 6580 6581 6582 6583
	  }
	  else
	  {
	    table->file->info(HA_STATUS_VARIABLE);
	    join->send_records = table->file->records;
	  }
6584 6585 6586
	}
	else 
	{
6587
	  join->do_send_rows= 0;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
6588 6589
	  if (join->unit->fake_select_lex)
	    join->unit->fake_select_lex->select_limit= HA_POS_ERROR;
6590 6591
	  DBUG_RETURN(0);
	}
6592
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6593
      DBUG_RETURN(-3);				// Abort nicely
6594
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621
  }
  else
  {
    if (join->procedure && join->procedure->end_of_records())
      DBUG_RETURN(-1);
  }
  DBUG_RETURN(0);
}


	/* ARGSUSED */
static int
end_send_group(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
	       bool end_of_records)
{
  int idx= -1;
  DBUG_ENTER("end_send_group");

  if (!join->first_record || end_of_records ||
      (idx=test_if_group_changed(join->group_fields)) >= 0)
  {
    if (join->first_record || (end_of_records && !join->group))
    {
      if (join->procedure)
	join->procedure->end_group();
      if (idx < (int) join->send_group_parts)
      {
6622
	int error=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6623 6624
	if (join->procedure)
	{
6625
	  if (join->having && join->having->val_int() == 0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6626
	    error= -1;				// Didn't satisfy having
6627 6628 6629 6630 6631 6632
 	  else
	  {
	    if (join->do_send_rows)
	      error=join->procedure->send_row(*join->fields) ? 1 : 0;
	    join->send_records++;
	  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6633 6634 6635 6636 6637 6638
	  if (end_of_records && join->procedure->end_of_records())
	    error= 1;				// Fatal error
	}
	else
	{
	  if (!join->first_record)
6639 6640
	  {
	    /* No matching rows for group function */
6641
	    join->clear();
6642
	  }
6643
	  if (join->having && join->having->val_int() == 0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6644
	    error= -1;				// Didn't satisfy having
6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655
	  else
	  {
	    if (join->do_send_rows)
	      error=join->result->send_data(*join->fields) ? 1 : 0;
	    join->send_records++;
	  }
	  if (join->rollup.state != ROLLUP::STATE_NONE && error <= 0)
	  {
	    if (join->rollup_send_data((uint) (idx+1)))
	      error= 1;
	  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6656 6657 6658
	}
	if (error > 0)
	  DBUG_RETURN(-1);			/* purecov: inspected */
6659 6660
	if (end_of_records)
	  DBUG_RETURN(0);
6661
	if (join->send_records >= join->unit->select_limit_cnt &&
6662 6663 6664 6665 6666
	    join->do_send_rows)
	{
	  if (!(join->select_options & OPTION_FOUND_ROWS))
	    DBUG_RETURN(-3);				// Abort nicely
	  join->do_send_rows=0;
6667
	  join->unit->select_limit_cnt = HA_POS_ERROR;
6668
        }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680
      }
    }
    else
    {
      if (end_of_records)
	DBUG_RETURN(0);
      join->first_record=1;
      VOID(test_if_group_changed(join->group_fields));
    }
    if (idx < (int) join->send_group_parts)
    {
      copy_fields(&join->tmp_table_param);
6681 6682
      if (init_sum_functions(join->sum_funcs, join->sum_funcs_end[idx+1]))
	DBUG_RETURN(-1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712
      if (join->procedure)
	join->procedure->add();
      DBUG_RETURN(0);
    }
  }
  if (update_sum_func(join->sum_funcs))
    DBUG_RETURN(-1);
  if (join->procedure)
    join->procedure->add();
  DBUG_RETURN(0);
}


	/* ARGSUSED */
static int
end_write(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
	  bool end_of_records)
{
  TABLE *table=join->tmp_table;
  int error;
  DBUG_ENTER("end_write");

  if (join->thd->killed)			// Aborted by user
  {
    my_error(ER_SERVER_SHUTDOWN,MYF(0));	/* purecov: inspected */
    DBUG_RETURN(-2);				/* purecov: inspected */
  }
  if (!end_of_records)
  {
    copy_fields(&join->tmp_table_param);
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
6713
    copy_funcs(join->tmp_table_param.items_to_copy);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6714

6715
#ifdef TO_BE_DELETED
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6716 6717 6718 6719 6720 6721 6722 6723 6724
    if (!table->uniques)			// If not unique handling
    {
      /* Copy null values from group to row */
      ORDER   *group;
      for (group=table->group ; group ; group=group->next)
      {
	Item *item= *group->item;
	if (item->maybe_null)
	{
6725
	  Field *field=item->get_tmp_table_field();
6726
	  field->ptr[-1]= (byte) (field->is_null() ? 1 : 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6727 6728 6729
	}
      }
    }
6730
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6731 6732
    if (!join->having || join->having->val_int())
    {
monty@tramp.mysql.fi's avatar
monty@tramp.mysql.fi committed
6733
      join->found_records++;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6734 6735
      if ((error=table->file->write_row(table->record[0])))
      {
monty@tramp.mysql.fi's avatar
monty@tramp.mysql.fi committed
6736 6737 6738
	if (error == HA_ERR_FOUND_DUPP_KEY ||
	    error == HA_ERR_FOUND_DUPP_UNIQUE)
	  goto end;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
6739 6740
	if (create_myisam_from_heap(join->thd, table, &join->tmp_table_param,
				    error,1))
6741
	  DBUG_RETURN(-1);			// Not a table_is_full error
monty@tramp.mysql.fi's avatar
monty@tramp.mysql.fi committed
6742
	table->uniques=0;			// To ensure rows are the same
6743
      }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
6744
      if (++join->send_records >= join->tmp_table_param.end_write_records &&
6745 6746 6747 6748 6749
	  join->do_send_rows)
      {
	if (!(join->select_options & OPTION_FOUND_ROWS))
	  DBUG_RETURN(-3);
	join->do_send_rows=0;
6750
	join->unit->select_limit_cnt = HA_POS_ERROR;
6751
	DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6752 6753 6754
      }
    }
  }
monty@tramp.mysql.fi's avatar
monty@tramp.mysql.fi committed
6755
end:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778
  DBUG_RETURN(0);
}

/* Group by searching after group record and updating it if possible */
/* ARGSUSED */

static int
end_update(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
	   bool end_of_records)
{
  TABLE *table=join->tmp_table;
  ORDER   *group;
  int	  error;
  DBUG_ENTER("end_update");

  if (end_of_records)
    DBUG_RETURN(0);
  if (join->thd->killed)			// Aborted by user
  {
    my_error(ER_SERVER_SHUTDOWN,MYF(0));	/* purecov: inspected */
    DBUG_RETURN(-2);				/* purecov: inspected */
  }

monty@tramp.mysql.fi's avatar
monty@tramp.mysql.fi committed
6779
  join->found_records++;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6780 6781 6782 6783 6784 6785
  copy_fields(&join->tmp_table_param);		// Groups are copied twice.
  /* Make a key of group index */
  for (group=table->group ; group ; group=group->next)
  {
    Item *item= *group->item;
    item->save_org_in_field(group->field);
hf@bisonxp.(none)'s avatar
hf@bisonxp.(none) committed
6786 6787 6788
#ifdef EMBEDDED_LIBRARY
    join->thd->net.last_errno= 0;
#endif
6789
    /* Store in the used key if the field was 0 */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6790
    if (item->maybe_null)
6791
      group->buff[-1]=item->null_value ? 1 : 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6792 6793 6794 6795 6796
  }
  if (!table->file->index_read(table->record[1],
			       join->tmp_table_param.group_buff,0,
			       HA_READ_KEY_EXACT))
  {						/* Update old record */
6797
    restore_record(table,record[1]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815
    update_tmptable_sum_func(join->sum_funcs,table);
    if ((error=table->file->update_row(table->record[1],
				       table->record[0])))
    {
      table->file->print_error(error,MYF(0));	/* purecov: inspected */
      DBUG_RETURN(-1);				/* purecov: inspected */
    }
    DBUG_RETURN(0);
  }

  /* The null bits are already set */
  KEY_PART_INFO *key_part;
  for (group=table->group,key_part=table->key_info[0].key_part;
       group ;
       group=group->next,key_part++)
    memcpy(table->record[0]+key_part->offset, group->buff, key_part->length);

  init_tmptable_sum_functions(join->sum_funcs);
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
6816
  copy_funcs(join->tmp_table_param.items_to_copy);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6817 6818
  if ((error=table->file->write_row(table->record[0])))
  {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
6819 6820
    if (create_myisam_from_heap(join->thd, table, &join->tmp_table_param,
				error, 0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6821 6822
      DBUG_RETURN(-1);				// Not a table_is_full error
    /* Change method to update rows */
6823
    table->file->ha_index_init(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849
    join->join_tab[join->tables-1].next_select=end_unique_update;
  }
  join->send_records++;
  DBUG_RETURN(0);
}

/* Like end_update, but this is done with unique constraints instead of keys */

static int
end_unique_update(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
		  bool end_of_records)
{
  TABLE *table=join->tmp_table;
  int	  error;
  DBUG_ENTER("end_unique_update");

  if (end_of_records)
    DBUG_RETURN(0);
  if (join->thd->killed)			// Aborted by user
  {
    my_error(ER_SERVER_SHUTDOWN,MYF(0));	/* purecov: inspected */
    DBUG_RETURN(-2);				/* purecov: inspected */
  }

  init_tmptable_sum_functions(join->sum_funcs);
  copy_fields(&join->tmp_table_param);		// Groups are copied twice.
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
6850
  copy_funcs(join->tmp_table_param.items_to_copy);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865

  if (!(error=table->file->write_row(table->record[0])))
    join->send_records++;			// New group
  else
  {
    if ((int) table->file->get_dup_key(error) < 0)
    {
      table->file->print_error(error,MYF(0));	/* purecov: inspected */
      DBUG_RETURN(-1);				/* purecov: inspected */
    }
    if (table->file->rnd_pos(table->record[1],table->file->dupp_ref))
    {
      table->file->print_error(error,MYF(0));	/* purecov: inspected */
      DBUG_RETURN(-1);				/* purecov: inspected */
    }
6866
    restore_record(table,record[1]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900
    update_tmptable_sum_func(join->sum_funcs,table);
    if ((error=table->file->update_row(table->record[1],
				       table->record[0])))
    {
      table->file->print_error(error,MYF(0));	/* purecov: inspected */
      DBUG_RETURN(-1);				/* purecov: inspected */
    }
  }
  DBUG_RETURN(0);
}


	/* ARGSUSED */
static int
end_write_group(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
		bool end_of_records)
{
  TABLE *table=join->tmp_table;
  int	  error;
  int	  idx= -1;
  DBUG_ENTER("end_write_group");

  if (join->thd->killed)
  {						// Aborted by user
    my_error(ER_SERVER_SHUTDOWN,MYF(0));	/* purecov: inspected */
    DBUG_RETURN(-2);				/* purecov: inspected */
  }
  if (!join->first_record || end_of_records ||
      (idx=test_if_group_changed(join->group_fields)) >= 0)
  {
    if (join->first_record || (end_of_records && !join->group))
    {
      if (join->procedure)
	join->procedure->end_group();
6901 6902
      int send_group_parts= join->send_group_parts;
      if (idx < send_group_parts)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6903 6904
      {
	if (!join->first_record)
6905 6906
	{
	  /* No matching rows for group function */
6907
	  join->clear();
6908
	}
6909 6910 6911 6912 6913
        copy_sum_funcs(join->sum_funcs,
                       join->sum_funcs_end[send_group_parts]);
	if (join->having && join->having->val_int() == 0)
          error= -1;
        else if ((error=table->file->write_row(table->record[0])))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6914
	{
6915 6916 6917 6918
	  if (create_myisam_from_heap(join->thd, table,
				      &join->tmp_table_param,
				      error, 0))
	    DBUG_RETURN(-1);		       
6919 6920 6921 6922 6923
            /* 
              If table->file->write_row() was failed because of 'out of memory'
              and tmp table succesfully created, reset error.
             */
            error=0;
6924 6925 6926 6927 6928
        }
        if (join->rollup.state != ROLLUP::STATE_NONE && error <= 0)
	{
	  if (join->rollup_write_data((uint) (idx+1), table))
	    error= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6929
	}
6930 6931
	if (error > 0)
	  DBUG_RETURN(-1);	  
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6932 6933 6934 6935 6936 6937
	if (end_of_records)
	  DBUG_RETURN(0);
      }
    }
    else
    {
6938 6939
      if (end_of_records)
	DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6940 6941 6942 6943 6944 6945
      join->first_record=1;
      VOID(test_if_group_changed(join->group_fields));
    }
    if (idx < (int) join->send_group_parts)
    {
      copy_fields(&join->tmp_table_param);
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
6946
      copy_funcs(join->tmp_table_param.items_to_copy);
6947 6948
      if (init_sum_functions(join->sum_funcs, join->sum_funcs_end[idx+1]))
	DBUG_RETURN(-1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962
      if (join->procedure)
	join->procedure->add();
      DBUG_RETURN(0);
    }
  }
  if (update_sum_func(join->sum_funcs))
    DBUG_RETURN(-1);
  if (join->procedure)
    join->procedure->add();
  DBUG_RETURN(0);
}


/*****************************************************************************
6963 6964 6965 6966 6967
  Remove calculation with tables that aren't yet read. Remove also tests
  against fields that are read through key where the table is not a
  outer join table.
  We can't remove tests that are made against columns which are stored
  in sorted order.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6968 6969 6970 6971 6972 6973 6974
*****************************************************************************/

/* Return 1 if right_item is used removable reference key on left_item */

static bool test_if_ref(Item_field *left_item,Item *right_item)
{
  Field *field=left_item->field;
6975 6976
  // No need to change const test. We also have to keep tests on LEFT JOIN
  if (!field->table->const_table && !field->table->maybe_null)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6977 6978
  {
    Item *ref_item=part_of_refkey(field->table,field);
6979
    if (ref_item && ref_item->eq(right_item,1))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6980 6981
    {
      if (right_item->type() == Item::FIELD_ITEM)
6982 6983
	return (field->eq_def(((Item_field *) right_item)->field));
      if (right_item->const_item() && !(right_item->is_null()))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6984
      {
6985 6986 6987
	/*
	  We can remove binary fields and numerical fields except float,
	  as float comparison isn't 100 % secure
monty@mysql.com's avatar
monty@mysql.com committed
6988
	  We have to keep binary strings to be able to check for end spaces
6989
	*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6990
	if (field->binary() &&
monty@mysql.com's avatar
monty@mysql.com committed
6991 6992
	    field->real_type() != FIELD_TYPE_STRING &&
	    field->real_type() != FIELD_TYPE_VAR_STRING &&
bk@work.mysql.com's avatar
bk@work.mysql.com committed
6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004
	    (field->type() != FIELD_TYPE_FLOAT || field->decimals() == 0))
	{
	  return !store_val_in_field(field,right_item);
	}
      }
    }
  }
  return 0;					// keep test
}


static COND *
7005
make_cond_for_table(COND *cond, table_map tables, table_map used_table)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7006 7007 7008 7009 7010 7011 7012
{
  if (used_table && !(cond->used_tables() & used_table))
    return (COND*) 0;				// Already checked
  if (cond->type() == Item::COND_ITEM)
  {
    if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
    {
7013
      /* Create new top level AND item */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030
      Item_cond_and *new_cond=new Item_cond_and;
      if (!new_cond)
	return (COND*) 0;			// OOM /* purecov: inspected */
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
      Item *item;
      while ((item=li++))
      {
	Item *fix=make_cond_for_table(item,tables,used_table);
	if (fix)
	  new_cond->argument_list()->push_back(fix);
      }
      switch (new_cond->argument_list()->elements) {
      case 0:
	return (COND*) 0;			// Always true
      case 1:
	return new_cond->argument_list()->head();
      default:
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7031 7032 7033 7034 7035 7036 7037 7038
	/*
	  Item_cond_and do not need fix_fields for execution, its parameters
	  are fixed or do not need fix_fields, too
	*/
	new_cond->quick_fix_field();
	new_cond->used_tables_cache=
	  ((Item_cond_and*) cond)->used_tables_cache &
	  tables;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055
	return new_cond;
      }
    }
    else
    {						// Or list
      Item_cond_or *new_cond=new Item_cond_or;
      if (!new_cond)
	return (COND*) 0;			// OOM /* purecov: inspected */
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
      Item *item;
      while ((item=li++))
      {
	Item *fix=make_cond_for_table(item,tables,0L);
	if (!fix)
	  return (COND*) 0;			// Always true
	new_cond->argument_list()->push_back(fix);
      }
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7056 7057 7058 7059 7060 7061
      /*
	Item_cond_and do not need fix_fields for execution, its parameters
	are fixed or do not need fix_fields, too
      */
      new_cond->quick_fix_field();
      new_cond->used_tables_cache= ((Item_cond_or*) cond)->used_tables_cache;
7062
      new_cond->top_level_item();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7063 7064 7065 7066 7067
      return new_cond;
    }
  }

  /*
7068 7069 7070
    Because the following test takes a while and it can be done
    table_count times, we mark each item that we have examined with the result
    of the test
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101
  */

  if (cond->marker == 3 || (cond->used_tables() & ~tables))
    return (COND*) 0;				// Can't check this yet
  if (cond->marker == 2 || cond->eq_cmp_result() == Item::COND_OK)
    return cond;				// Not boolean op

  if (((Item_func*) cond)->functype() == Item_func::EQ_FUNC)
  {
    Item *left_item=	((Item_func*) cond)->arguments()[0];
    Item *right_item= ((Item_func*) cond)->arguments()[1];
    if (left_item->type() == Item::FIELD_ITEM &&
	test_if_ref((Item_field*) left_item,right_item))
    {
      cond->marker=3;			// Checked when read
      return (COND*) 0;
    }
    if (right_item->type() == Item::FIELD_ITEM &&
	test_if_ref((Item_field*) right_item,left_item))
    {
      cond->marker=3;			// Checked when read
      return (COND*) 0;
    }
  }
  cond->marker=2;
  return cond;
}

static Item *
part_of_refkey(TABLE *table,Field *field)
{
7102 7103 7104
  if (!table->reginfo.join_tab)
    return (Item*) 0;             // field from outer non-select (UPDATE,...)

bk@work.mysql.com's avatar
bk@work.mysql.com committed
7105 7106 7107 7108 7109 7110 7111 7112
  uint ref_parts=table->reginfo.join_tab->ref.key_parts;
  if (ref_parts)
  {
    KEY_PART_INFO *key_part=
      table->key_info[table->reginfo.join_tab->ref.key].key_part;

    for (uint part=0 ; part < ref_parts ; part++,key_part++)
      if (field->eq(key_part->field) &&
7113
	  !(key_part->key_part_flag & HA_PART_KEY_SEG))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7114 7115 7116 7117 7118 7119 7120
	return table->reginfo.join_tab->ref.items[part];
  }
  return (Item*) 0;
}


/*****************************************************************************
7121
  Test if one can use the key to resolve ORDER BY
7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138

  SYNOPSIS
    test_if_order_by_key()
    order		Sort order
    table		Table to sort
    idx			Index to check
    used_key_parts	Return value for used key parts.


  NOTES
    used_key_parts is set to correct key parts used if return value != 0
    (On other cases, used_key_part may be changed)

  RETURN
    1   key is ok.
    0   Key can't be used
    -1  Reverse key can be used
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7139 7140
*****************************************************************************/

7141 7142
static int test_if_order_by_key(ORDER *order, TABLE *table, uint idx,
				uint *used_key_parts)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7143 7144 7145 7146 7147 7148
{
  KEY_PART_INFO *key_part,*key_part_end;
  key_part=table->key_info[idx].key_part;
  key_part_end=key_part+table->key_info[idx].key_parts;
  key_part_map const_key_parts=table->const_key_parts[idx];
  int reverse=0;
7149
  DBUG_ENTER("test_if_order_by_key");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7150 7151 7152 7153 7154 7155 7156 7157 7158 7159

  for (; order ; order=order->next, const_key_parts>>=1)
  {
    Field *field=((Item_field*) (*order->item))->field;
    int flag;

    /*
      Skip key parts that are constants in the WHERE clause.
      These are already skipped in the ORDER BY by const_expression_in_where()
    */
7160 7161 7162
    for (; const_key_parts & 1 ; const_key_parts>>= 1)
      key_part++; 

bk@work.mysql.com's avatar
bk@work.mysql.com committed
7163
    if (key_part == key_part_end || key_part->field != field)
7164
      DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7165 7166

    /* set flag to 1 if we can use read-next on key, else to -1 */
7167 7168
    flag= ((order->asc == !(key_part->key_part_flag & HA_REVERSE_SORT)) ?
           1 : -1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7169
    if (reverse && flag != reverse)
7170
      DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7171 7172 7173
    reverse=flag;				// Remember if reverse
    key_part++;
  }
7174 7175 7176 7177
  *used_key_parts= (uint) (key_part - table->key_info[idx].key_part);
  if (reverse == -1 && !(table->file->index_flags(idx, *used_key_parts-1, 1) &
                         HA_READ_PREV))
    reverse= 0;                                 // Index can't be used
7178
  DBUG_RETURN(reverse);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7179 7180
}

7181

serg@serg.mylan's avatar
serg@serg.mylan committed
7182
static uint find_shortest_key(TABLE *table, const key_map *usable_keys)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7183 7184 7185
{
  uint min_length= (uint) ~0;
  uint best= MAX_KEY;
serg@serg.mylan's avatar
serg@serg.mylan committed
7186
  if (!usable_keys->is_clear_all())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7187
  {
serg@serg.mylan's avatar
serg@serg.mylan committed
7188
    for (uint nr=0; nr < table->keys ; nr++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7189
    {
serg@serg.mylan's avatar
serg@serg.mylan committed
7190
      if (usable_keys->is_set(nr))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7191
      {
7192 7193 7194 7195 7196
        if (table->key_info[nr].key_length < min_length)
        {
          min_length=table->key_info[nr].key_length;
          best=nr;
        }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7197 7198 7199 7200 7201 7202
      }
    }
  }
  return best;
}

7203
/*
7204 7205
  Test if a second key is the subkey of the first one.

7206 7207
  SYNOPSIS
    is_subkey()
7208 7209 7210 7211
    key_part		First key parts
    ref_key_part	Second key parts
    ref_key_part_end	Last+1 part of the second key

7212 7213
  NOTE
    Second key MUST be shorter than the first one.
7214

7215
  RETURN
7216 7217
    1	is a subkey
    0	no sub key
7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230
*/

inline bool 
is_subkey(KEY_PART_INFO *key_part, KEY_PART_INFO *ref_key_part,
	  KEY_PART_INFO *ref_key_part_end)
{
  for (; ref_key_part < ref_key_part_end; key_part++, ref_key_part++)
    if (!key_part->field->eq(ref_key_part->field))
      return 0;
  return 1;
}

/*
7231 7232
  Test if we can use one of the 'usable_keys' instead of 'ref' key for sorting

7233 7234
  SYNOPSIS
    test_if_subkey()
7235 7236 7237
    ref			Number of key, used for WHERE clause
    usable_keys		Keys for testing

7238
  RETURN
7239 7240
    MAX_KEY			If we can't use other key
    the number of found key	Otherwise
7241 7242 7243
*/

static uint
7244
test_if_subkey(ORDER *order, TABLE *table, uint ref, uint ref_key_parts,
7245
	       const key_map *usable_keys)
7246 7247 7248 7249 7250 7251 7252
{
  uint nr;
  uint min_length= (uint) ~0;
  uint best= MAX_KEY;
  uint not_used;
  KEY_PART_INFO *ref_key_part= table->key_info[ref].key_part;
  KEY_PART_INFO *ref_key_part_end= ref_key_part + ref_key_parts;
7253

serg@serg.mylan's avatar
serg@serg.mylan committed
7254
  for (nr= 0 ; nr < table->keys ; nr++)
7255
  {
7256
    if (usable_keys->is_set(nr) &&
7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268
	table->key_info[nr].key_length < min_length &&
	table->key_info[nr].key_parts >= ref_key_parts &&
	is_subkey(table->key_info[nr].key_part, ref_key_part,
		  ref_key_part_end) &&
	test_if_order_by_key(order, table, nr, &not_used))
    {
      min_length= table->key_info[nr].key_length;
      best= nr;
    }
  }
  return best;
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7269

7270 7271 7272 7273 7274 7275 7276 7277 7278 7279
/*
  Test if we can skip the ORDER BY by using an index.

  If we can use an index, the JOIN_TAB / tab->select struct
  is changed to use the index.

  Return:
     0 We have to use filesort to do the sorting
     1 We can use an index.
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7280 7281

static bool
7282 7283
test_if_skip_sort_order(JOIN_TAB *tab,ORDER *order,ha_rows select_limit,
			bool no_changes)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7284 7285
{
  int ref_key;
7286
  uint ref_key_parts;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7287 7288 7289 7290
  TABLE *table=tab->table;
  SQL_SELECT *select=tab->select;
  key_map usable_keys;
  DBUG_ENTER("test_if_skip_sort_order");
7291
  LINT_INIT(ref_key_parts);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7292 7293

  /* Check which keys can be used to resolve ORDER BY */
7294
  usable_keys.set_all();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7295 7296 7297 7298
  for (ORDER *tmp_order=order; tmp_order ; tmp_order=tmp_order->next)
  {
    if ((*tmp_order->item)->type() != Item::FIELD_ITEM)
    {
7299
      usable_keys.clear_all();
7300
      DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7301
    }
7302 7303
    usable_keys.intersect(((Item_field*) (*tmp_order->item))->
			  field->part_of_sortkey);
serg@serg.mylan's avatar
serg@serg.mylan committed
7304
    if (usable_keys.is_clear_all())
7305
      DBUG_RETURN(0);					// No usable keys
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7306 7307 7308
  }

  ref_key= -1;
7309
  /* Test if constant range in WHERE */
7310
  if (tab->ref.key >= 0 && tab->ref.key_parts)
7311 7312 7313
  {
    ref_key=	   tab->ref.key;
    ref_key_parts= tab->ref.key_parts;
7314
    if (tab->type == JT_REF_OR_NULL || tab->type == JT_FT)
7315
      DBUG_RETURN(0);
7316
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7317
  else if (select && select->quick)		// Range found by opt_range
7318 7319 7320 7321
  {
    ref_key=	   select->quick->index;
    ref_key_parts= select->quick->used_key_parts;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7322 7323 7324

  if (ref_key >= 0)
  {
7325 7326 7327
    /*
      We come here when there is a REF key.
    */
7328
    int order_direction;
7329
    uint used_key_parts;
7330
    if (!usable_keys.is_set(ref_key))
7331 7332 7333 7334
    {
      /*
	We come here when ref_key is not among usable_keys
      */
7335 7336 7337 7338 7339
      uint new_ref_key;
      /*
	If using index only read, only consider other possible index only
	keys
      */
7340
      if (table->used_keys.is_set(ref_key))
7341
	usable_keys.intersect(table->used_keys);
7342
      if ((new_ref_key= test_if_subkey(order, table, ref_key, ref_key_parts,
7343
				       &usable_keys)) < MAX_KEY)
7344
      {
7345
	/* Found key that can be used to retrieve data in sorted order */
7346 7347
	if (tab->ref.key >= 0)
	{
7348 7349 7350
          /*
            We'll use ref access method on key new_ref_key. In general case 
            the index search tuple for new_ref_key will be different (e.g.
sergefp@mysql.com's avatar
sergefp@mysql.com committed
7351 7352 7353
            when one index is defined as (part1, part2, ...) and another as
            (part1, part2(N), ...) and the WHERE clause contains 
            "part1 = const1 AND part2=const2". 
7354 7355 7356 7357 7358 7359 7360 7361
            So we build tab->ref from scratch here.
          */
          KEYUSE *keyuse= tab->keyuse;
          while (keyuse->key != new_ref_key && keyuse->table == tab->table)
            keyuse++;
          if (create_ref_for_key(tab->join, tab, keyuse, 
                                 tab->join->const_table_map))
            DBUG_RETURN(0);
7362 7363 7364
	}
	else
	{
timour@mysql.com's avatar
timour@mysql.com committed
7365 7366 7367 7368 7369 7370 7371 7372 7373
          /*
            The range optimizer constructed QUICK_RANGE for ref_key, and
            we want to use instead new_ref_key as the index. We can't
            just change the index of the quick select, because this may
            result in an incosistent QUICK_SELECT object. Below we
            create a new QUICK_SELECT from scratch so that all its
            parameres are set correctly by the range optimizer.
           */
          key_map new_ref_key_map;
7374 7375
          new_ref_key_map.clear_all();  // Force the creation of quick select
          new_ref_key_map.set_bit(new_ref_key); // only for new_ref_key.
timour@mysql.com's avatar
timour@mysql.com committed
7376 7377

          if (select->test_quick_select(tab->join->thd, new_ref_key_map, 0,
7378 7379 7380 7381 7382
                                        (tab->join->select_options &
                                         OPTION_FOUND_ROWS) ?
                                        HA_POS_ERROR :
                                        tab->join->unit->select_limit_cnt,0) <=
              0)
timour@mysql.com's avatar
timour@mysql.com committed
7383
            DBUG_RETURN(0);
7384
	}
timour@mysql.com's avatar
timour@mysql.com committed
7385
        ref_key= new_ref_key;
7386
      }
7387
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7388
    /* Check if we get the rows in requested sorted order by using the key */
7389
    if (usable_keys.is_set(ref_key) &&
7390 7391
	(order_direction = test_if_order_by_key(order,table,ref_key,
						&used_key_parts)))
7392
    {
7393
      if (order_direction == -1)		// If ORDER BY ... DESC
7394
      {
7395 7396
	if (select && select->quick)
	{
7397 7398 7399 7400 7401
	  /*
	    Don't reverse the sort order, if it's already done.
	    (In some cases test_if_order_by_key() can be called multiple times
	  */
	  if (!select->quick->reverse_sorted())
7402
	  {
7403 7404 7405 7406 7407 7408 7409 7410 7411
	    // ORDER BY range_key DESC
	    QUICK_SELECT_DESC *tmp=new QUICK_SELECT_DESC(select->quick,
							 used_key_parts);
	    if (!tmp || tmp->error)
	    {
	      delete tmp;
	      DBUG_RETURN(0);		// Reverse sort not supported
	    }
	    select->quick=tmp;
7412 7413 7414 7415 7416 7417 7418
	  }
	  DBUG_RETURN(1);
	}
	if (tab->ref.key_parts < used_key_parts)
	{
	  /*
	    SELECT * FROM t1 WHERE a=1 ORDER BY a DESC,b DESC
7419 7420 7421

	    Use a traversal function that starts by reading the last row
	    with key part (A) and then traverse the index backwards.
7422
	  */
7423 7424 7425
	  tab->read_first_record=       join_read_last_key;
	  tab->read_record.read_record= join_read_prev_same;
	  /* fall through */
7426
	}
7427
      }
7428 7429
      else if (select && select->quick)
	  select->quick->sorted= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7430
      DBUG_RETURN(1);			/* No need to sort */
7431
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7432 7433 7434 7435 7436 7437
  }
  else
  {
    /* check if we can use a key to resolve the group */
    /* Tables using JT_NEXT are handled here */
    uint nr;
monty@mysql.com's avatar
monty@mysql.com committed
7438
    key_map keys;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7439 7440 7441 7442 7443 7444 7445

    /*
      If not used with LIMIT, only use keys if the whole query can be
      resolved with a key;  This is because filesort() is usually faster than
      retrieving all rows through an index.
    */
    if (select_limit >= table->file->records)
monty@mysql.com's avatar
monty@mysql.com committed
7446 7447 7448
    {
      keys= *table->file->keys_to_use_for_scanning();
      keys.merge(table->used_keys);
7449

monty@mysql.com's avatar
monty@mysql.com committed
7450
      /*
monty@mysql.com's avatar
monty@mysql.com committed
7451
	We are adding here also the index specified in FORCE INDEX clause, 
monty@mysql.com's avatar
monty@mysql.com committed
7452
	if any.
monty@mysql.com's avatar
monty@mysql.com committed
7453
        This is to allow users to use index in ORDER BY.
monty@mysql.com's avatar
monty@mysql.com committed
7454 7455 7456 7457
      */
      if (table->force_index) 
	keys.merge(table->keys_in_use_for_query);
      keys.intersect(usable_keys);
7458 7459
    }
    else
7460
      keys= usable_keys;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7461

serg@serg.mylan's avatar
serg@serg.mylan committed
7462
    for (nr=0; nr < table->keys ; nr++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7463
    {
7464
      uint not_used;
7465
      if (keys.is_set(nr))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7466 7467
      {
	int flag;
monty@mysql.com's avatar
monty@mysql.com committed
7468
	if ((flag= test_if_order_by_key(order, table, nr, &not_used)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7469
	{
7470 7471 7472
	  if (!no_changes)
	  {
	    tab->index=nr;
7473 7474
	    tab->read_first_record=  (flag > 0 ? join_read_first:
				      join_read_last);
7475
	    tab->type=JT_NEXT;	// Read with index_first(), index_next()
7476
	    if (table->used_keys.is_set(nr))
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
7477 7478 7479 7480
	    {
	      table->key_read=1;
	      table->file->extra(HA_EXTRA_KEYREAD);
	    }
7481
	  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7482 7483 7484 7485 7486 7487 7488 7489
	  DBUG_RETURN(1);
	}
      }
    }
  }
  DBUG_RETURN(0);				// Can't use index.
}

7490

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
7491
/*
7492
  If not selecting by given key, create an index how records should be read
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
7493 7494 7495 7496 7497 7498 7499 7500

  SYNOPSIS
   create_sort_index()
     thd		Thread handler
     tab		Table to sort (in join structure)
     order		How table should be sorted
     filesort_limit	Max number of rows that needs to be sorted
     select_limit	Max number of rows in final output
7501
		        Used to decide if we should use index or not
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516


  IMPLEMENTATION
   - If there is an index that can be used, 'tab' is modified to use
     this index.
   - If no index, create with filesort() an index file that can be used to
     retrieve rows in order (should be done with 'read_record').
     The sorted data is stored in tab->table and will be freed when calling
     free_io_cache(tab->table).

  RETURN VALUES
    0		ok
    -1		Some fatal error
    1		No records
*/
7517

bk@work.mysql.com's avatar
bk@work.mysql.com committed
7518
static int
7519
create_sort_index(THD *thd, JOIN *join, ORDER *order,
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
7520
		  ha_rows filesort_limit, ha_rows select_limit)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7521 7522 7523
{
  SORT_FIELD *sortorder;
  uint length;
7524
  ha_rows examined_rows;
7525 7526 7527
  TABLE *table;
  SQL_SELECT *select;
  JOIN_TAB *tab;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7528 7529
  DBUG_ENTER("create_sort_index");

7530 7531 7532 7533 7534 7535
  if (join->tables == join->const_tables)
    DBUG_RETURN(0);				// One row, no need to sort
  tab=    join->join_tab + join->const_tables;
  table=  tab->table;
  select= tab->select;

7536
  if (test_if_skip_sort_order(tab,order,select_limit,0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7537 7538 7539 7540
    DBUG_RETURN(0);
  if (!(sortorder=make_unireg_sortorder(order,&length)))
    goto err;				/* purecov: inspected */
  /* It's not fatal if the following alloc fails */
igor@hundin.mysql.fi's avatar
igor@hundin.mysql.fi committed
7541 7542
  table->sort.io_cache=(IO_CACHE*) my_malloc(sizeof(IO_CACHE),
                                             MYF(MY_WME | MY_ZEROFILL));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563
  table->status=0;				// May be wrong if quick_select

  // If table has a range, move it to select
  if (select && !select->quick && tab->ref.key >= 0)
  {
    if (tab->quick)
    {
      select->quick=tab->quick;
      tab->quick=0;
      /* We can only use 'Only index' if quick key is same as ref_key */
      if (table->key_read && (uint) tab->ref.key != select->quick->index)
      {
	table->key_read=0;
	table->file->extra(HA_EXTRA_NO_KEYREAD);
      }
    }
    else
    {
      /*
	We have a ref on a const;  Change this to a range that filesort
	can use.
7564 7565
	For impossible ranges (like when doing a lookup on NULL on a NOT NULL
	field, quick will contain an empty record set.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7566
      */
7567 7568 7569
      if (!(select->quick= (tab->type == JT_FT ?
			    new FT_SELECT(thd, table, tab->ref.key) :
			    get_quick_select_for_ref(thd, table, &tab->ref))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7570 7571 7572
	goto err;
    }
  }
7573 7574
  if (table->tmp_table)
    table->file->info(HA_STATUS_VARIABLE);	// Get record count
igor@hundin.mysql.fi's avatar
igor@hundin.mysql.fi committed
7575 7576
  table->sort.found_records=filesort(thd, table,sortorder, length,
                                     select, filesort_limit, &examined_rows);
monty@mysql.com's avatar
merge  
monty@mysql.com committed
7577
  tab->records= table->sort.found_records;	// For SQL_CALC_ROWS
7578 7579 7580 7581 7582
  if (select)
  {
    select->cleanup();				// filesort did select
    tab->select= 0;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7583 7584 7585
  tab->select_cond=0;
  tab->type=JT_ALL;				// Read with normal read_record
  tab->read_first_record= join_init_read_record;
7586
  tab->join->examined_rows+=examined_rows;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7587 7588 7589 7590 7591
  if (table->key_read)				// Restore if we used indexes
  {
    table->key_read=0;
    table->file->extra(HA_EXTRA_NO_KEYREAD);
  }
igor@hundin.mysql.fi's avatar
igor@hundin.mysql.fi committed
7592
  DBUG_RETURN(table->sort.found_records == HA_POS_ERROR);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7593 7594 7595 7596
err:
  DBUG_RETURN(-1);
}

7597
/*
7598
  Add the HAVING criteria to table->select
7599 7600
*/

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
7601
#ifdef NOT_YET
7602 7603 7604 7605 7606 7607
static bool fix_having(JOIN *join, Item **having)
{
  (*having)->update_used_tables();	// Some tables may have been const
  JOIN_TAB *table=&join->join_tab[join->const_tables];
  table_map used_tables= join->const_table_map | table->table->map;

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
7608
  DBUG_EXECUTE("where",print_where(*having,"having"););
7609 7610 7611 7612 7613 7614 7615 7616 7617
  Item* sort_table_cond=make_cond_for_table(*having,used_tables,used_tables);
  if (sort_table_cond)
  {
    if (!table->select)
      if (!(table->select=new SQL_SELECT))
	return 1;
    if (!table->select->cond)
      table->select->cond=sort_table_cond;
    else					// This should never happen
7618 7619
      if (!(table->select->cond= new Item_cond_and(table->select->cond,
						   sort_table_cond)) ||
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
7620
	  table->select->cond->fix_fields(join->thd, join->tables_list,
7621
					  &table->select->cond))
7622 7623
	return 1;
    table->select_cond=table->select->cond;
7624
    table->select_cond->top_level_item();
7625 7626 7627 7628 7629 7630 7631
    DBUG_EXECUTE("where",print_where(table->select_cond,
				     "select and having"););
    *having=make_cond_for_table(*having,~ (table_map) 0,~used_tables);
    DBUG_EXECUTE("where",print_where(*having,"having after make_cond"););
  }
  return 0;
}
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
7632
#endif
7633 7634


bk@work.mysql.com's avatar
bk@work.mysql.com committed
7635
/*****************************************************************************
7636 7637 7638 7639 7640
  Remove duplicates from tmp table
  This should be recoded to add a unique index to the table and remove
  duplicates
  Table is a locked single thread table
  fields is the number of fields to check (from the end)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674
*****************************************************************************/

static bool compare_record(TABLE *table, Field **ptr)
{
  for (; *ptr ; ptr++)
  {
    if ((*ptr)->cmp_offset(table->rec_buff_length))
      return 1;
  }
  return 0;
}

static bool copy_blobs(Field **ptr)
{
  for (; *ptr ; ptr++)
  {
    if ((*ptr)->flags & BLOB_FLAG)
      if (((Field_blob *) (*ptr))->copy())
	return 1;				// Error
  }
  return 0;
}

static void free_blobs(Field **ptr)
{
  for (; *ptr ; ptr++)
  {
    if ((*ptr)->flags & BLOB_FLAG)
      ((Field_blob *) (*ptr))->free();
  }
}


static int
7675
remove_duplicates(JOIN *join, TABLE *entry,List<Item> &fields, Item *having)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7676 7677 7678 7679
{
  int error;
  ulong reclength,offset;
  uint field_count;
7680
  THD *thd= join->thd;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7681 7682 7683 7684 7685 7686 7687 7688 7689
  DBUG_ENTER("remove_duplicates");

  entry->reginfo.lock_type=TL_WRITE;

  /* Calculate how many saved fields there is in list */
  field_count=0;
  List_iterator<Item> it(fields);
  Item *item;
  while ((item=it++))
7690
  {
7691
    if (item->get_tmp_table_field() && ! item->const_item())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7692
      field_count++;
7693
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7694

7695 7696
  if (!field_count && !(join->select_options & OPTION_FOUND_ROWS)) 
  {                    // only const items with no OPTION_FOUND_ROWS
7697
    join->unit->select_limit_cnt= 1;		// Only send first row
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7698 7699 7700
    DBUG_RETURN(0);
  }
  Field **first_field=entry->field+entry->fields - field_count;
7701 7702
  offset= field_count ? 
          entry->field[entry->fields - field_count]->offset() : 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7703 7704 7705 7706 7707 7708
  reclength=entry->reclength-offset;

  free_io_cache(entry);				// Safety
  entry->file->info(HA_STATUS_VARIABLE);
  if (entry->db_type == DB_TYPE_HEAP ||
      (!entry->blob_fields &&
7709
       ((ALIGN_SIZE(reclength) + HASH_OVERHEAD) * entry->file->records <
7710
	thd->variables.sortbuff_size)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7711 7712
    error=remove_dup_with_hash_index(join->thd, entry,
				     field_count, first_field,
7713
				     reclength, having);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7714
  else
7715 7716
    error=remove_dup_with_compare(join->thd, entry, first_field, offset,
				  having);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7717 7718 7719 7720 7721 7722 7723

  free_blobs(first_field);
  DBUG_RETURN(error);
}


static int remove_dup_with_compare(THD *thd, TABLE *table, Field **first_field,
7724
				   ulong offset, Item *having)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7725 7726 7727
{
  handler *file=table->file;
  char *org_record,*new_record;
monty@donna.mysql.fi's avatar
monty@donna.mysql.fi committed
7728
  byte *record;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7729 7730 7731 7732
  int error;
  ulong reclength=table->reclength-offset;
  DBUG_ENTER("remove_dup_with_compare");

7733
  org_record=(char*) (record=table->record[0])+offset;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7734 7735
  new_record=(char*) table->record[1]+offset;

7736
  file->ha_rnd_init(1);
7737
  error=file->rnd_next(record);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753
  for (;;)
  {
    if (thd->killed)
    {
      my_error(ER_SERVER_SHUTDOWN,MYF(0));
      error=0;
      goto err;
    }
    if (error)
    {
      if (error == HA_ERR_RECORD_DELETED)
	continue;
      if (error == HA_ERR_END_OF_FILE)
	break;
      goto err;
    }
7754 7755 7756 7757
    if (having && !having->val_int())
    {
      if ((error=file->delete_row(record)))
	goto err;
7758
      error=file->rnd_next(record);
7759 7760
      continue;
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7761 7762
    if (copy_blobs(first_field))
    {
serg@serg.mysql.com's avatar
serg@serg.mysql.com committed
7763
      my_error(ER_OUTOFMEMORY,MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7764 7765 7766 7767 7768 7769 7770 7771 7772
      error=0;
      goto err;
    }
    memcpy(new_record,org_record,reclength);

    /* Read through rest of file and mark duplicated rows deleted */
    bool found=0;
    for (;;)
    {
7773
      if ((error=file->rnd_next(record)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7774 7775 7776 7777 7778 7779 7780 7781 7782
      {
	if (error == HA_ERR_RECORD_DELETED)
	  continue;
	if (error == HA_ERR_END_OF_FILE)
	  break;
	goto err;
      }
      if (compare_record(table, first_field) == 0)
      {
7783
	if ((error=file->delete_row(record)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7784 7785 7786 7787 7788
	  goto err;
      }
      else if (!found)
      {
	found=1;
7789
	file->position(record);	// Remember position
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7790 7791 7792 7793 7794
      }
    }
    if (!found)
      break;					// End of file
    /* Restart search on next row */
7795
    error=file->restart_rnd_next(record,file->ref);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815
  }

  file->extra(HA_EXTRA_NO_CACHE);
  DBUG_RETURN(0);
err:
  file->extra(HA_EXTRA_NO_CACHE);
  if (error)
    file->print_error(error,MYF(0));
  DBUG_RETURN(1);
}


/*
  Generate a hash index for each row to quickly find duplicate rows
  Note that this will not work on tables with blobs!
*/

static int remove_dup_with_hash_index(THD *thd, TABLE *table,
				      uint field_count,
				      Field **first_field,
7816 7817
				      ulong key_length,
				      Item *having)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7818 7819 7820
{
  byte *key_buffer, *key_pos, *record=table->record[0];
  int error;
7821 7822
  handler *file= table->file;
  ulong extra_length= ALIGN_SIZE(key_length)-key_length;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834
  uint *field_lengths,*field_length;
  HASH hash;
  DBUG_ENTER("remove_dup_with_hash_index");

  if (!my_multi_malloc(MYF(MY_WME),
		       &key_buffer,
		       (uint) ((key_length + extra_length) *
			       (long) file->records),
		       &field_lengths,
		       (uint) (field_count*sizeof(*field_lengths)),
		       NullS))
    DBUG_RETURN(1);
7835

7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851
  {
    Field **ptr;
    ulong total_length= 0;
    for (ptr= first_field, field_length=field_lengths ; *ptr ; ptr++)
    {
      uint length= (*ptr)->pack_length();
      (*field_length++)= length;
      total_length+= length;
    }
    DBUG_PRINT("info",("field_count: %u  key_length: %lu  total_length: %lu",
                       field_count, key_length, total_length));
    DBUG_ASSERT(total_length <= key_length);
    key_length= total_length;
    extra_length= ALIGN_SIZE(key_length)-key_length;
  }

bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
7852
  if (hash_init(&hash, &my_charset_bin, (uint) file->records, 0, 
7853
		key_length, (hash_get_key) 0, 0, 0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7854 7855 7856 7857 7858
  {
    my_free((char*) key_buffer,MYF(0));
    DBUG_RETURN(1);
  }

7859
  file->ha_rnd_init(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7860 7861 7862
  key_pos=key_buffer;
  for (;;)
  {
7863
    byte *org_key_pos;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877
    if (thd->killed)
    {
      my_error(ER_SERVER_SHUTDOWN,MYF(0));
      error=0;
      goto err;
    }
    if ((error=file->rnd_next(record)))
    {
      if (error == HA_ERR_RECORD_DELETED)
	continue;
      if (error == HA_ERR_END_OF_FILE)
	break;
      goto err;
    }
7878 7879 7880 7881 7882
    if (having && !having->val_int())
    {
      if ((error=file->delete_row(record)))
	goto err;
      continue;
7883
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7884 7885

    /* copy fields to key buffer */
7886
    org_key_pos= key_pos;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7887 7888 7889 7890 7891 7892 7893
    field_length=field_lengths;
    for (Field **ptr= first_field ; *ptr ; ptr++)
    {
      (*ptr)->sort_string((char*) key_pos,*field_length);
      key_pos+= *field_length++;
    }
    /* Check if it exists before */
7894
    if (hash_search(&hash, org_key_pos, key_length))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7895 7896 7897 7898 7899
    {
      /* Duplicated found ; Remove the row */
      if ((error=file->delete_row(record)))
	goto err;
    }
7900
    else
7901
      (void) my_hash_insert(&hash, org_key_pos);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7902 7903 7904 7905 7906
    key_pos+=extra_length;
  }
  my_free((char*) key_buffer,MYF(0));
  hash_free(&hash);
  file->extra(HA_EXTRA_NO_CACHE);
7907
  (void) file->ha_rnd_end();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7908 7909 7910 7911 7912 7913
  DBUG_RETURN(0);

err:
  my_free((char*) key_buffer,MYF(0));
  hash_free(&hash);
  file->extra(HA_EXTRA_NO_CACHE);
7914
  (void) file->ha_rnd_end();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7915 7916 7917 7918 7919 7920
  if (error)
    file->print_error(error,MYF(0));
  DBUG_RETURN(1);
}


7921
SORT_FIELD *make_unireg_sortorder(ORDER *order, uint *length)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940
{
  uint count;
  SORT_FIELD *sort,*pos;
  DBUG_ENTER("make_unireg_sortorder");

  count=0;
  for (ORDER *tmp = order; tmp; tmp=tmp->next)
    count++;
  pos=sort=(SORT_FIELD*) sql_alloc(sizeof(SORT_FIELD)*(count+1));
  if (!pos)
    return 0;

  for (;order;order=order->next,pos++)
  {
    pos->field=0; pos->item=0;
    if (order->item[0]->type() == Item::FIELD_ITEM)
      pos->field= ((Item_field*) (*order->item))->field;
    else if (order->item[0]->type() == Item::SUM_FUNC_ITEM &&
	     !order->item[0]->const_item())
7941
      pos->field= ((Item_sum*) order->item[0])->get_tmp_table_field();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955
    else if (order->item[0]->type() == Item::COPY_STR_ITEM)
    {						// Blob patch
      pos->item= ((Item_copy_string*) (*order->item))->item;
    }
    else
      pos->item= *order->item;
    pos->reverse=! order->asc;
  }
  *length=count;
  DBUG_RETURN(sort);
}


/*****************************************************************************
7956 7957 7958 7959
  Fill join cache with packed records
  Records are stored in tab->cache.buffer and last record in
  last record is stored with pointers to blobs to support very big
  records
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7960 7961 7962 7963 7964 7965 7966 7967 7968
******************************************************************************/

static int
join_init_cache(THD *thd,JOIN_TAB *tables,uint table_count)
{
  reg1 uint i;
  uint length,blobs,size;
  CACHE_FIELD *copy,**blob_ptr;
  JOIN_CACHE  *cache;
7969
  JOIN_TAB *join_tab;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7970 7971 7972 7973 7974
  DBUG_ENTER("join_init_cache");

  cache= &tables[table_count].cache;
  cache->fields=blobs=0;

7975 7976
  join_tab=tables;
  for (i=0 ; i < table_count ; i++,join_tab++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7977
  {
7978 7979 7980 7981
    if (!join_tab->used_fieldlength)		/* Not calced yet */
      calc_used_field_length(thd, join_tab);
    cache->fields+=join_tab->used_fields;
    blobs+=join_tab->used_blobs;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020
  }
  if (!(cache->field=(CACHE_FIELD*)
	sql_alloc(sizeof(CACHE_FIELD)*(cache->fields+table_count*2)+(blobs+1)*
		  sizeof(CACHE_FIELD*))))
  {
    my_free((gptr) cache->buff,MYF(0));		/* purecov: inspected */
    cache->buff=0;				/* purecov: inspected */
    DBUG_RETURN(1);				/* purecov: inspected */
  }
  copy=cache->field;
  blob_ptr=cache->blob_ptr=(CACHE_FIELD**)
    (cache->field+cache->fields+table_count*2);

  length=0;
  for (i=0 ; i < table_count ; i++)
  {
    uint null_fields=0,used_fields;

    Field **f_ptr,*field;
    for (f_ptr=tables[i].table->field,used_fields=tables[i].used_fields ;
	 used_fields ;
	 f_ptr++)
    {
      field= *f_ptr;
      if (field->query_id == thd->query_id)
      {
	used_fields--;
	length+=field->fill_cache_field(copy);
	if (copy->blob_field)
	  (*blob_ptr++)=copy;
	if (field->maybe_null())
	  null_fields++;
	copy++;
      }
    }
    /* Copy null bits from table */
    if (null_fields && tables[i].table->null_fields)
    {						/* must copy null bits */
      copy->str=(char*) tables[i].table->null_flags;
8021
      copy->length=tables[i].table->null_bytes;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043
      copy->strip=0;
      copy->blob_field=0;
      length+=copy->length;
      copy++;
      cache->fields++;
    }
    /* If outer join table, copy null_row flag */
    if (tables[i].table->maybe_null)
    {
      copy->str= (char*) &tables[i].table->null_row;
      copy->length=sizeof(tables[i].table->null_row);
      copy->strip=0;
      copy->blob_field=0;
      length+=copy->length;
      copy++;
      cache->fields++;
    }
  }

  cache->length=length+blobs*sizeof(char*);
  cache->blobs=blobs;
  *blob_ptr=0;					/* End sequentel */
8044
  size=max(thd->variables.join_buff_size, cache->length);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8045 8046 8047
  if (!(cache->buff=(uchar*) my_malloc(size,MYF(0))))
    DBUG_RETURN(1);				/* Don't use cache */ /* purecov: inspected */
  cache->end=cache->buff+size;
8048
  reset_cache_write(cache);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084
  DBUG_RETURN(0);
}


static ulong
used_blob_length(CACHE_FIELD **ptr)
{
  uint length,blob_length;
  for (length=0 ; *ptr ; ptr++)
  {
    (*ptr)->blob_length=blob_length=(*ptr)->blob_field->get_length();
    length+=blob_length;
    (*ptr)->blob_field->get_ptr(&(*ptr)->str);
  }
  return length;
}


static bool
store_record_in_cache(JOIN_CACHE *cache)
{
  ulong length;
  uchar *pos;
  CACHE_FIELD *copy,*end_field;
  bool last_record;

  pos=cache->pos;
  end_field=cache->field+cache->fields;

  length=cache->length;
  if (cache->blobs)
    length+=used_blob_length(cache->blob_ptr);
  if ((last_record=(length+cache->length > (uint) (cache->end - pos))))
    cache->ptr_record=cache->records;

  /*
8085
    There is room in cache. Put record there
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8086 8087 8088 8089 8090 8091 8092 8093
  */
  cache->records++;
  for (copy=cache->field ; copy < end_field; copy++)
  {
    if (copy->blob_field)
    {
      if (last_record)
      {
8094 8095
	copy->blob_field->get_image((char*) pos,copy->length+sizeof(char*), 
				    copy->blob_field->charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8096 8097 8098 8099
	pos+=copy->length+sizeof(char*);
      }
      else
      {
8100 8101
	copy->blob_field->get_image((char*) pos,copy->length, // blob length
				    copy->blob_field->charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114
	memcpy(pos+copy->length,copy->str,copy->blob_length);  // Blob data
	pos+=copy->length+copy->blob_length;
      }
    }
    else
    {
      if (copy->strip)
      {
	char *str,*end;
	for (str=copy->str,end= str+copy->length;
	     end > str && end[-1] == ' ' ;
	     end--) ;
	length=(uint) (end-str);
8115 8116 8117
	memcpy(pos+sizeof(uint), str, length);
	*((uint *) pos)= length;
	pos+= length+sizeof(uint);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131
      }
      else
      {
	memcpy(pos,copy->str,copy->length);
	pos+=copy->length;
      }
    }
  }
  cache->pos=pos;
  return last_record || (uint) (cache->end -pos) < cache->length;
}


static void
8132
reset_cache_read(JOIN_CACHE *cache)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8133 8134 8135
{
  cache->record_nr=0;
  cache->pos=cache->buff;
8136 8137 8138 8139 8140 8141 8142 8143
}


static void reset_cache_write(JOIN_CACHE *cache)
{
  reset_cache_read(cache);
  cache->records= 0;
  cache->ptr_record= (uint) ~0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165
}


static void
read_cached_record(JOIN_TAB *tab)
{
  uchar *pos;
  uint length;
  bool last_record;
  CACHE_FIELD *copy,*end_field;

  last_record=tab->cache.record_nr++ == tab->cache.ptr_record;
  pos=tab->cache.pos;

  for (copy=tab->cache.field,end_field=copy+tab->cache.fields ;
       copy < end_field;
       copy++)
  {
    if (copy->blob_field)
    {
      if (last_record)
      {
8166 8167
	copy->blob_field->set_image((char*) pos,copy->length+sizeof(char*),
				    copy->blob_field->charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179
	pos+=copy->length+sizeof(char*);
      }
      else
      {
	copy->blob_field->set_ptr((char*) pos,(char*) pos+copy->length);
	pos+=copy->length+copy->blob_field->get_length();
      }
    }
    else
    {
      if (copy->strip)
      {
8180 8181 8182
	memcpy(copy->str, pos+sizeof(uint), length= *((uint *) pos));
	memset(copy->str+length, ' ', copy->length-length);
	pos+= sizeof(uint)+length;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203
      }
      else
      {
	memcpy(copy->str,pos,copy->length);
	pos+=copy->length;
      }
    }
  }
  tab->cache.pos=pos;
  return;
}


static bool
cmp_buffer_with_ref(JOIN_TAB *tab)
{
  bool diff;
  if (!(diff=tab->ref.key_err))
  {
    memcpy(tab->ref.key_buff2, tab->ref.key_buff, tab->ref.key_length);
  }
sergefp@mysql.com's avatar
sergefp@mysql.com committed
8204 8205
  if ((tab->ref.key_err= cp_buffer_from_ref(tab->join->thd, &tab->ref)) || 
      diff)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8206 8207 8208 8209 8210 8211 8212
    return 1;
  return memcmp(tab->ref.key_buff2, tab->ref.key_buff, tab->ref.key_length)
    != 0;
}


bool
sergefp@mysql.com's avatar
sergefp@mysql.com committed
8213
cp_buffer_from_ref(THD *thd, TABLE_REF *ref)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8214
{
sergefp@mysql.com's avatar
sergefp@mysql.com committed
8215 8216
  enum enum_check_fields save_count_cuted_fields= thd->count_cuted_fields;
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8217 8218
  for (store_key **copy=ref->key_copy ; *copy ; copy++)
    if ((*copy)->copy())
sergefp@mysql.com's avatar
sergefp@mysql.com committed
8219 8220
    {
      thd->count_cuted_fields= save_count_cuted_fields;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8221
      return 1;					// Something went wrong
sergefp@mysql.com's avatar
sergefp@mysql.com committed
8222 8223
    }
  thd->count_cuted_fields= save_count_cuted_fields;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8224 8225 8226 8227 8228
  return 0;
}


/*****************************************************************************
8229
  Group and order functions
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8230 8231 8232
*****************************************************************************/

/*
8233 8234 8235
  Find order/group item in requested columns and change the item to point at
  it. If item doesn't exists, add it first in the field list
  Return 0 if ok.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8236 8237 8238
*/

static int
8239 8240
find_order_in_list(THD *thd, Item **ref_pointer_array,
		   TABLE_LIST *tables,ORDER *order, List<Item> &fields,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8241 8242
		   List<Item> &all_fields)
{
8243 8244
  Item *it= *order->item;
  if (it->type() == Item::INT_ITEM)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8245
  {						/* Order by position */
8246
    uint count= (uint) it->val_int();
8247
    if (!count || count > fields.elements)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8248 8249
    {
      my_printf_error(ER_BAD_FIELD_ERROR,ER(ER_BAD_FIELD_ERROR),
8250
		      MYF(0), it->full_name(), thd->where);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8251 8252
      return 1;
    }
8253 8254
    order->item= ref_pointer_array + count-1;
    order->in_field_list= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8255 8256
    return 0;
  }
8257
  uint counter;
8258 8259 8260
  bool unaliased;
  Item **item= find_item_in_list(it, fields, &counter,
                                 REPORT_EXCEPT_NOT_FOUND, &unaliased);
8261 8262 8263
  if (!item)
    return 1;

8264
  if (item != (Item **)not_found_item)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8265
  {
8266 8267 8268 8269 8270 8271 8272 8273
    /*
      If we have found field not by its alias in select list but by its
      original field name, we should additionaly check if we have conflict
      for this name (in case if we would perform lookup in all tables).
    */
    if (unaliased && !it->fixed && it->fix_fields(thd, tables, order->item))
      return 1;

8274
    order->item= ref_pointer_array + counter;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8275 8276 8277
    order->in_field_list=1;
    return 0;
  }
8278

bk@work.mysql.com's avatar
bk@work.mysql.com committed
8279
  order->in_field_list=0;
8280
  /*
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
8281 8282 8283 8284
    We check it->fixed because Item_func_group_concat can put
    arguments for which fix_fields already was called.

    'it' reassigned in if condition because fix_field can change it.
8285 8286 8287 8288 8289
  */
  if (!it->fixed &&
      (it->fix_fields(thd, tables, order->item) ||
       (it= *order->item)->check_cols(1) ||
       thd->is_fatal_error))
8290
    return 1;					// Wrong field 
8291 8292 8293 8294
  uint el= all_fields.elements;
  all_fields.push_front(it);		        // Add new field to field list
  ref_pointer_array[el]= it;
  order->item= ref_pointer_array + el;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8295 8296 8297 8298
  return 0;
}

/*
8299 8300
  Change order to point at item in select list. If item isn't a number
  and doesn't exits in the select list, add it the the field list.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8301 8302
*/

8303 8304
int setup_order(THD *thd, Item **ref_pointer_array, TABLE_LIST *tables,
		List<Item> &fields, List<Item> &all_fields, ORDER *order)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8305 8306 8307 8308
{
  thd->where="order clause";
  for (; order; order=order->next)
  {
8309 8310
    if (find_order_in_list(thd, ref_pointer_array, tables, order, fields,
			   all_fields))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8311 8312 8313 8314 8315 8316
      return 1;
  }
  return 0;
}


monty@mysql.com's avatar
monty@mysql.com committed
8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339
/*
  Intitialize the GROUP BY list.

  SYNOPSIS
   setup_group()
   thd			Thread handler
   ref_pointer_array	We store references to all fields that was not in
			'fields' here.   
   fields		All fields in the select part. Any item in 'order'
			that is part of these list is replaced by a pointer
			to this fields.
   all_fields		Total list of all unique fields used by the select.
			All items in 'order' that was not part of fields will
			be added first to this list.
  order			The fields we should do GROUP BY on.
  hidden_group_fields	Pointer to flag that is set to 1 if we added any fields
			to all_fields.

  RETURN
   0  ok
   1  error (probably out of memory)
*/

8340
int
8341 8342 8343
setup_group(THD *thd, Item **ref_pointer_array, TABLE_LIST *tables,
	    List<Item> &fields, List<Item> &all_fields, ORDER *order,
	    bool *hidden_group_fields)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8344 8345 8346 8347 8348
{
  *hidden_group_fields=0;
  if (!order)
    return 0;				/* Everything is ok */

8349
  if (thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8350 8351 8352 8353 8354 8355 8356 8357 8358
  {
    Item *item;
    List_iterator<Item> li(fields);
    while ((item=li++))
      item->marker=0;			/* Marker that field is not used */
  }
  uint org_fields=all_fields.elements;

  thd->where="group statement";
8359
  for (; order; order=order->next)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8360
  {
8361 8362
    if (find_order_in_list(thd, ref_pointer_array, tables, order, fields,
			   all_fields))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8363 8364 8365 8366 8367 8368 8369 8370 8371
      return 1;
    (*order->item)->marker=1;		/* Mark found */
    if ((*order->item)->with_sum_func)
    {
      my_printf_error(ER_WRONG_GROUP_FIELD, ER(ER_WRONG_GROUP_FIELD),MYF(0),
		      (*order->item)->full_name());
      return 1;
    }
  }
8372
  if (thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8373 8374 8375 8376 8377 8378 8379
  {
    /* Don't allow one to use fields that is not used in GROUP BY */
    Item *item;
    List_iterator<Item> li(fields);

    while ((item=li++))
    {
8380 8381
      if (item->type() != Item::SUM_FUNC_ITEM && !item->marker &&
	  !item->const_item())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395
      {
	my_printf_error(ER_WRONG_FIELD_WITH_GROUP,
			ER(ER_WRONG_FIELD_WITH_GROUP),
			MYF(0),item->full_name());
	return 1;
      }
    }
  }
  if (org_fields != all_fields.elements)
    *hidden_group_fields=1;			// group fields is not used
  return 0;
}

/*
8396
  Add fields with aren't used at start of field list. Return FALSE if ok
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8397 8398 8399 8400 8401 8402 8403 8404 8405 8406
*/

static bool
setup_new_fields(THD *thd,TABLE_LIST *tables,List<Item> &fields,
		 List<Item> &all_fields, ORDER *new_field)
{
  Item	  **item;
  DBUG_ENTER("setup_new_fields");

  thd->set_query_id=1;				// Not really needed, but...
8407
  uint counter;
8408
  bool not_used;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
8409
  for (; new_field ; new_field= new_field->next)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8410
  {
8411
    if ((item= find_item_in_list(*new_field->item, fields, &counter,
8412
				 IGNORE_ERRORS, &not_used)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8413 8414 8415 8416
      new_field->item=item;			/* Change to shared Item */
    else
    {
      thd->where="procedure list";
8417
      if ((*new_field->item)->fix_fields(thd, tables, new_field->item))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8418 8419 8420 8421 8422 8423 8424 8425 8426
	DBUG_RETURN(1); /* purecov: inspected */
      all_fields.push_front(*new_field->item);
      new_field->item=all_fields.head_ref();
    }
  }
  DBUG_RETURN(0);
}

/*
8427 8428 8429
  Create a group by that consist of all non const fields. Try to use
  the fields in the order given by 'order' to allow one to optimize
  away 'order by'.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8430 8431 8432
*/

static ORDER *
8433 8434
create_distinct_group(THD *thd, ORDER *order_list, List<Item> &fields, 
		      bool *all_order_by_fields_used)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8435 8436 8437 8438 8439
{
  List_iterator<Item> li(fields);
  Item *item;
  ORDER *order,*group,**prev;

8440
  *all_order_by_fields_used= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8441 8442 8443 8444 8445 8446 8447 8448
  while ((item=li++))
    item->marker=0;			/* Marker that field is not used */

  prev= &group;  group=0;
  for (order=order_list ; order; order=order->next)
  {
    if (order->in_field_list)
    {
8449
      ORDER *ord=(ORDER*) thd->memdup((char*) order,sizeof(ORDER));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8450 8451 8452 8453 8454 8455
      if (!ord)
	return 0;
      *prev=ord;
      prev= &ord->next;
      (*ord->item)->marker=1;
    }
8456 8457
    else
      *all_order_by_fields_used= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8458 8459 8460 8461 8462 8463 8464 8465 8466
  }

  li.rewind();
  while ((item=li++))
  {
    if (item->const_item() || item->with_sum_func)
      continue;
    if (!item->marker)
    {
8467
      ORDER *ord=(ORDER*) thd->calloc(sizeof(ORDER));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481
      if (!ord)
	return 0;
      ord->item=li.ref();
      ord->asc=1;
      *prev=ord;
      prev= &ord->next;
    }
  }
  *prev=0;
  return group;
}


/*****************************************************************************
8482
  Update join with count of the different type of fields
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8483 8484 8485
*****************************************************************************/

void
8486 8487
count_field_types(TMP_TABLE_PARAM *param, List<Item> &fields,
		  bool reset_with_sum_func)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8488 8489 8490 8491
{
  List_iterator<Item> li(fields);
  Item *field;

8492
  param->field_count=param->sum_func_count=param->func_count=
8493
    param->hidden_field_count=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518
  param->quick_group=1;
  while ((field=li++))
  {
    Item::Type type=field->type();
    if (type == Item::FIELD_ITEM)
      param->field_count++;
    else if (type == Item::SUM_FUNC_ITEM)
    {
      if (! field->const_item())
      {
	Item_sum *sum_item=(Item_sum*) field;
	if (!sum_item->quick_group)
	  param->quick_group=0;			// UDF SUM function
	param->sum_func_count++;

	for (uint i=0 ; i < sum_item->arg_count ; i++)
	{
	  if (sum_item->args[0]->type() == Item::FIELD_ITEM)
	    param->field_count++;
	  else
	    param->func_count++;
	}
      }
    }
    else
8519
    {
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8520
      param->func_count++;
8521 8522 8523
      if (reset_with_sum_func)
	field->with_sum_func=0;
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538
  }
}


/*
  Return 1 if second is a subpart of first argument
  If first parts has different direction, change it to second part
  (group is sorted like order)
*/

static bool
test_if_subpart(ORDER *a,ORDER *b)
{
  for (; a && b; a=a->next,b=b->next)
  {
8539
    if ((*a->item)->eq(*b->item,1))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565
      a->asc=b->asc;
    else
      return 0;
  }
  return test(!b);
}

/*
  Return table number if there is only one table in sort order
  and group and order is compatible
  else return 0;
*/

static TABLE *
get_sort_by_table(ORDER *a,ORDER *b,TABLE_LIST *tables)
{
  table_map map= (table_map) 0;
  DBUG_ENTER("get_sort_by_table");

  if (!a)
    a=b;					// Only one need to be given
  else if (!b)
    b=a;

  for (; a && b; a=a->next,b=b->next)
  {
8566
    if (!(*a->item)->eq(*b->item,1))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8567 8568 8569
      DBUG_RETURN(0);
    map|=a->item[0]->used_tables();
  }
8570
  if (!map || (map & (RAND_TABLE_BIT | OUTER_REF_TABLE_BIT)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8571 8572
    DBUG_RETURN(0);

8573
  for (; !(map & tables->table->map) ; tables=tables->next) ;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585
  if (map != tables->table->map)
    DBUG_RETURN(0);				// More than one table
  DBUG_PRINT("exit",("sort by table: %d",tables->table->tablenr));
  DBUG_RETURN(tables->table);
}


	/* calc how big buffer we need for comparing group entries */

static void
calc_group_buffer(JOIN *join,ORDER *group)
{
8586 8587
  uint key_length=0, parts=0, null_parts=0;

bk@work.mysql.com's avatar
bk@work.mysql.com committed
8588 8589 8590 8591
  if (group)
    join->group= 1;
  for (; group ; group=group->next)
  {
8592
    Field *field=(*group->item)->get_tmp_table_field();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607
    if (field)
    {
      if (field->type() == FIELD_TYPE_BLOB)
	key_length+=MAX_BLOB_WIDTH;		// Can't be used as a key
      else
	key_length+=field->pack_length();
    }
    else if ((*group->item)->result_type() == REAL_RESULT)
      key_length+=sizeof(double);
    else if ((*group->item)->result_type() == INT_RESULT)
      key_length+=sizeof(longlong);
    else
      key_length+=(*group->item)->max_length;
    parts++;
    if ((*group->item)->maybe_null)
8608
      null_parts++;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8609
  }
8610
  join->tmp_table_param.group_length=key_length+null_parts;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8611
  join->tmp_table_param.group_parts=parts;
8612
  join->tmp_table_param.group_null_parts=null_parts;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8613 8614
}

8615

8616
/*
8617
  allocate group fields or take prepared (cached)
8618

8619
  SYNOPSIS
8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631
    make_group_fields()
    main_join - join of current select
    curr_join - current join (join of current select or temporary copy of it)

  RETURN
    0 - ok
    1 - failed
*/

static bool
make_group_fields(JOIN *main_join, JOIN *curr_join)
{
8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643
  if (main_join->group_fields_cache.elements)
  {
    curr_join->group_fields= main_join->group_fields_cache;
    curr_join->sort_and_group= 1;
  }
  else
  {
    if (alloc_group_fields(curr_join, curr_join->group_list))
      return (1);
    main_join->group_fields_cache= curr_join->group_fields;
  }
  return (0);
8644
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8645

8646

bk@work.mysql.com's avatar
bk@work.mysql.com committed
8647
/*
8648 8649
  Get a list of buffers for saveing last group
  Groups are saved in reverse order for easyer check loop
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8650 8651 8652 8653 8654 8655 8656 8657 8658
*/

static bool
alloc_group_fields(JOIN *join,ORDER *group)
{
  if (group)
  {
    for (; group ; group=group->next)
    {
8659
      Item_buff *tmp=new_Item_buff(join->thd, *group->item);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671
      if (!tmp || join->group_fields.push_front(tmp))
	return TRUE;
    }
  }
  join->sort_and_group=1;			/* Mark for do_select */
  return FALSE;
}


static int
test_if_group_changed(List<Item_buff> &list)
{
8672
  DBUG_ENTER("test_if_group_changed");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8673 8674 8675 8676 8677 8678 8679 8680 8681
  List_iterator<Item_buff> li(list);
  int idx= -1,i;
  Item_buff *buff;

  for (i=(int) list.elements-1 ; (buff=li++) ; i--)
  {
    if (buff->cmp())
      idx=i;
  }
8682 8683
  DBUG_PRINT("info", ("idx: %d", idx));
  DBUG_RETURN(idx);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8684 8685 8686 8687
}


/*
8688
  Setup copy_fields to save fields at start of new group
8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707

  setup_copy_fields()
    thd - THD pointer
    param - temporary table parameters
    ref_pointer_array - array of pointers to top elements of filed list
    res_selected_fields - new list of items of select item list
    res_all_fields - new list of all items
    elements - number of elements in select item list
    all_fields - all fields list

  DESCRIPTION
    Setup copy_fields to save fields at start of new group
    Only FIELD_ITEM:s and FUNC_ITEM:s needs to be saved between groups.
    Change old item_field to use a new field with points at saved fieldvalue
    This function is only called before use of send_fields
  
  RETURN
    0 - ok
    !=0 - error
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8708 8709 8710
*/

bool
8711 8712
setup_copy_fields(THD *thd, TMP_TABLE_PARAM *param,
		  Item **ref_pointer_array,
8713 8714
		  List<Item> &res_selected_fields, List<Item> &res_all_fields,
		  uint elements, List<Item> &all_fields)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8715 8716
{
  Item *pos;
8717
  List_iterator_fast<Item> li(all_fields);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8718
  Copy_field *copy;
8719 8720 8721
  res_selected_fields.empty();
  res_all_fields.empty();
  List_iterator_fast<Item> itr(res_all_fields);
8722
  List<Item> extra_funcs;
8723
  uint i, border= all_fields.elements - elements;
monty@mysql.com's avatar
monty@mysql.com committed
8724
  DBUG_ENTER("setup_copy_fields");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8725 8726

  if (!(copy=param->copy_field= new Copy_field[param->field_count]))
8727
    goto err2;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8728 8729

  param->copy_funcs.empty();
8730
  for (i= 0; (pos= li++); i++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8731 8732 8733
  {
    if (pos->type() == Item::FIELD_ITEM)
    {
8734
      Item_field *item;
8735
      if (!(item= new Item_field(thd, ((Item_field*) pos))))
8736 8737
	goto err;
      pos= item;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8738 8739
      if (item->field->flags & BLOB_FLAG)
      {
8740
	if (!(pos= new Item_copy_string(pos)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8741
	  goto err;
8742 8743 8744 8745 8746 8747 8748 8749 8750 8751
       /*
         Item_copy_string::copy for function can call 
         Item_copy_string::val_int for blob via Item_ref.
         But if Item_copy_string::copy for blob isn't called before,
         it's value will be wrong
         so let's insert Item_copy_string for blobs in the beginning of 
         copy_funcs
         (to see full test case look at having.test, BUG #4358) 
       */
	if (param->copy_funcs.push_front(pos))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8752 8753
	  goto err;
      }
8754 8755 8756 8757 8758 8759 8760
      else
      {
	/* 
	   set up save buffer and change result_field to point at 
	   saved value
	*/
	Field *field= item->field;
8761
	item->result_field=field->new_field(thd->mem_root,field->table);
8762 8763 8764 8765 8766 8767 8768
	char *tmp=(char*) sql_alloc(field->pack_length()+1);
	if (!tmp)
	  goto err;
	copy->set(tmp, item->result_field);
	item->result_field->move_field(copy->to_ptr,copy->to_null_ptr,1);
	copy++;
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8769 8770
    }
    else if ((pos->type() == Item::FUNC_ITEM ||
8771 8772
	      pos->type() == Item::SUBSELECT_ITEM ||
	      pos->type() == Item::CACHE_ITEM ||
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783
	      pos->type() == Item::COND_ITEM) &&
	     !pos->with_sum_func)
    {						// Save for send fields
      /* TODO:
	 In most cases this result will be sent to the user.
	 This should be changed to use copy_int or copy_real depending
	 on how the value is to be used: In some cases this may be an
	 argument in a group function, like: IF(ISNULL(col),0,COUNT(*))
      */
      if (!(pos=new Item_copy_string(pos)))
	goto err;
8784 8785 8786 8787 8788 8789
      if (i < border)                           // HAVING, ORDER and GROUP BY
      {
        if (extra_funcs.push_back(pos))
          goto err;
      }
      else if (param->copy_funcs.push_back(pos))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8790 8791
	goto err;
    }
8792 8793
    res_all_fields.push_back(pos);
    ref_pointer_array[((i < border)? all_fields.elements-i-1 : i-border)]=
8794
      pos;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8795
  }
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
8796
  param->copy_field_end= copy;
8797 8798 8799

  for (i= 0; i < border; i++)
    itr++;
8800
  itr.sublist(res_selected_fields, elements);
8801 8802 8803 8804 8805 8806
  /*
    Put elements from HAVING, ORDER BY and GROUP BY last to ensure that any
    reference used in these will resolve to a item that is already calculated
  */
  param->copy_funcs.concat(&extra_funcs);

bk@work.mysql.com's avatar
bk@work.mysql.com committed
8807 8808 8809
  DBUG_RETURN(0);

 err:
8810
  delete [] param->copy_field;			// This is never 0
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8811
  param->copy_field=0;
8812
err2:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8813 8814 8815 8816 8817
  DBUG_RETURN(TRUE);
}


/*
8818 8819 8820 8821
  Make a copy of all simple SELECT'ed items

  This is done at the start of a new group so that we can retrieve
  these later when the group changes.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8822 8823 8824 8825 8826 8827
*/

void
copy_fields(TMP_TABLE_PARAM *param)
{
  Copy_field *ptr=param->copy_field;
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
8828
  Copy_field *end=param->copy_field_end;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8829

8830
  for (; ptr != end; ptr++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8831 8832
    (*ptr->do_copy)(ptr);

sergefp@mysql.com's avatar
sergefp@mysql.com committed
8833
  List_iterator_fast<Item> it(param->copy_funcs);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8834 8835 8836 8837 8838 8839
  Item_copy_string *item;
  while ((item = (Item_copy_string*) it++))
    item->copy();
}


8840 8841
/*
  Make an array of pointers to sum_functions to speed up sum_func calculation
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8842

8843 8844 8845 8846 8847 8848 8849 8850 8851
  SYNOPSIS
    alloc_func_list()

  RETURN
    0	ok
    1	Error
*/

bool JOIN::alloc_func_list()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8852
{
8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879
  uint func_count, group_parts;
  DBUG_ENTER("alloc_func_list");

  func_count= tmp_table_param.sum_func_count;
  /*
    If we are using rollup, we need a copy of the summary functions for
    each level
  */
  if (rollup.state != ROLLUP::STATE_NONE)
    func_count*= (send_group_parts+1);

  group_parts= send_group_parts;
  /*
    If distinct, reserve memory for possible
    disctinct->group_by optimization
  */
  if (select_distinct)
    group_parts+= fields_list.elements;

  /* This must use calloc() as rollup_make_fields depends on this */
  sum_funcs= (Item_sum**) thd->calloc(sizeof(Item_sum**) * (func_count+1) +
				      sizeof(Item_sum***) * (group_parts+1));
  sum_funcs_end= (Item_sum***) (sum_funcs+func_count+1);
  DBUG_RETURN(sum_funcs == 0);
}


8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896
/*
  Initialize 'sum_funcs' array with all Item_sum objects

  SYNOPSIS
    make_sum_func_list()
    field_list		All items
    send_fields		Items in select list
    before_group_by	Set to 1 if this is called before GROUP BY handling

  NOTES
    Calls ::setup() for all item_sum objects in field_list

  RETURN
    0  ok
    1  error
*/

8897
bool JOIN::make_sum_func_list(List<Item> &field_list, List<Item> &send_fields,
8898
			      bool before_group_by)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8899
{
8900
  List_iterator_fast<Item> it(field_list);
8901 8902
  Item_sum **func;
  Item *item;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8903 8904
  DBUG_ENTER("make_sum_func_list");

8905 8906
  func= sum_funcs;
  while ((item=it++))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8907
  {
8908
    if (item->type() == Item::SUM_FUNC_ITEM && !item->const_item())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8909
    {
8910
      *func++= (Item_sum*) item;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8911
      /* let COUNT(DISTINCT) create the temporary table */
8912
      if (((Item_sum*) item)->setup(thd))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8913 8914 8915
	DBUG_RETURN(TRUE);
    }
  }
8916 8917 8918
  if (before_group_by && rollup.state == ROLLUP::STATE_INITED)
  {
    rollup.state= ROLLUP::STATE_READY;
8919
    if (rollup_make_fields(field_list, send_fields, &func))
8920 8921 8922 8923 8924 8925 8926
      DBUG_RETURN(TRUE);			// Should never happen
  }
  else if (rollup.state == ROLLUP::STATE_NONE)
  {
    for (uint i=0 ; i <= send_group_parts ;i++)
      sum_funcs_end[i]= func;
  }
8927 8928
  else if (rollup.state == ROLLUP::STATE_READY)
    DBUG_RETURN(FALSE);                         // Don't put end marker
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8929 8930 8931 8932 8933 8934
  *func=0;					// End marker
  DBUG_RETURN(FALSE);
}


/*
8935
  Change all funcs and sum_funcs to fields in tmp table, and create
8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948
  new list of all items.

  change_to_use_tmp_fields()
    thd - THD pointer
    ref_pointer_array - array of pointers to top elements of filed list
    res_selected_fields - new list of items of select item list
    res_all_fields - new list of all items
    elements - number of elements in select item list
    all_fields - all fields list

   RETURN
    0 - ok
    !=0 - error
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8949 8950 8951
*/

static bool
8952
change_to_use_tmp_fields(THD *thd, Item **ref_pointer_array,
8953 8954 8955
			 List<Item> &res_selected_fields,
			 List<Item> &res_all_fields,
			 uint elements, List<Item> &all_fields)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8956
{
8957
  List_iterator_fast<Item> it(all_fields);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8958
  Item *item_field,*item;
8959 8960
  res_selected_fields.empty();
  res_all_fields.empty();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8961

8962
  uint i, border= all_fields.elements - elements;
8963
  for (i= 0; (item= it++); i++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8964 8965
  {
    Field *field;
8966
    
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8967
    if (item->with_sum_func && item->type() != Item::SUM_FUNC_ITEM)
8968 8969
      item_field= item;
    else
8970
    {
8971
      if (item->type() == Item::FIELD_ITEM)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8972
      {
8973
	item_field= item->get_tmp_table_item(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8974
      }
8975
      else if ((field= item->get_tmp_table_field()))
8976 8977 8978 8979
      {
	if (item->type() == Item::SUM_FUNC_ITEM && field->table->group)
	  item_field= ((Item_sum*) item)->result_item(field);
	else
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
8980
	  item_field= (Item*) new Item_field(field);
8981 8982 8983 8984 8985 8986 8987
	if (!item_field)
	  return TRUE;				// Fatal error
	item_field->name= item->name;		/*lint -e613 */
#ifndef DBUG_OFF
	if (_db_on_ && !item_field->name)
	{
	  char buff[256];
8988
	  String str(buff,sizeof(buff),&my_charset_bin);
8989 8990 8991 8992
	  str.length(0);
	  item->print(&str);
	  item_field->name= sql_strmake(str.ptr(),str.length());
	}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
8993
#endif
8994 8995 8996
      }
      else
	item_field= item;
8997 8998 8999
    }
    res_all_fields.push_back(item_field);
    ref_pointer_array[((i < border)? all_fields.elements-i-1 : i-border)]=
9000
      item_field;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9001
  }
9002

9003
  List_iterator_fast<Item> itr(res_all_fields);
9004 9005
  for (i= 0; i < border; i++)
    itr++;
9006
  itr.sublist(res_selected_fields, elements);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9007 9008 9009 9010 9011
  return FALSE;
}


/*
9012 9013
  Change all sum_func refs to fields to point at fields in tmp table
  Change all funcs to be fields in tmp table
9014 9015 9016 9017 9018 9019 9020 9021 9022 9023

  change_refs_to_tmp_fields()
    thd - THD pointer
    ref_pointer_array - array of pointers to top elements of filed list
    res_selected_fields - new list of items of select item list
    res_all_fields - new list of all items
    elements - number of elements in select item list
    all_fields - all fields list

   RETURN
9024 9025
    0	ok
    1	error
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9026 9027 9028
*/

static bool
9029
change_refs_to_tmp_fields(THD *thd, Item **ref_pointer_array,
9030 9031 9032
			  List<Item> &res_selected_fields,
			  List<Item> &res_all_fields, uint elements,
			  List<Item> &all_fields)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9033
{
9034
  List_iterator_fast<Item> it(all_fields);
9035
  Item *item, *new_item;
9036 9037
  res_selected_fields.empty();
  res_all_fields.empty();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9038

9039
  uint i, border= all_fields.elements - elements;
9040
  for (i= 0; (item= it++); i++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9041
  {
9042 9043
    res_all_fields.push_back(new_item= item->get_tmp_table_item(thd));
    ref_pointer_array[((i < border)? all_fields.elements-i-1 : i-border)]=
9044
      new_item;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9045
  }
9046

9047
  List_iterator_fast<Item> itr(res_all_fields);
9048 9049
  for (i= 0; i < border; i++)
    itr++;
9050
  itr.sublist(res_selected_fields, elements);
9051

9052
  return thd->is_fatal_error;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9053 9054 9055 9056 9057
}



/******************************************************************************
9058
  Code for calculating functions
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077
******************************************************************************/

static void
init_tmptable_sum_functions(Item_sum **func_ptr)
{
  Item_sum *func;
  while ((func= *(func_ptr++)))
    func->reset_field();
}


	/* Update record 0 in tmp_table from record 1 */

static void
update_tmptable_sum_func(Item_sum **func_ptr,
			 TABLE *tmp_table __attribute__((unused)))
{
  Item_sum *func;
  while ((func= *(func_ptr++)))
9078
    func->update_field();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9079 9080 9081 9082 9083 9084
}


	/* Copy result of sum functions to record in tmp_table */

static void
9085
copy_sum_funcs(Item_sum **func_ptr, Item_sum **end_ptr)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9086
{
9087 9088
  for (; func_ptr != end_ptr ; func_ptr++)
    (void) (*func_ptr)->save_in_result_field(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9089 9090 9091 9092
  return;
}


9093 9094
static bool
init_sum_functions(Item_sum **func_ptr, Item_sum **end_ptr)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9095
{
9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107
  for (; func_ptr != end_ptr ;func_ptr++)
  {
    if ((*func_ptr)->reset())
      return 1;
  }
  /* If rollup, calculate the upper sum levels */
  for ( ; *func_ptr ; func_ptr++)
  {
    if ((*func_ptr)->add())
      return 1;
  }
  return 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123
}


static bool
update_sum_func(Item_sum **func_ptr)
{
  Item_sum *func;
  for (; (func= (Item_sum*) *func_ptr) ; func_ptr++)
    if (func->add())
      return 1;
  return 0;
}

	/* Copy result of functions to record in tmp_table */

void
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
9124
copy_funcs(Item **func_ptr)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9125
{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
9126
  Item *func;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9127
  for (; (func = *func_ptr) ; func_ptr++)
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
9128
    func->save_in_result_field(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9129 9130 9131
}


9132
/*
9133 9134
  Create a condition for a const reference and add this to the
  currenct select for the table
9135
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150

static bool add_ref_to_table_cond(THD *thd, JOIN_TAB *join_tab)
{
  DBUG_ENTER("add_ref_to_table_cond");
  if (!join_tab->ref.key_parts)
    DBUG_RETURN(FALSE);

  Item_cond_and *cond=new Item_cond_and();
  TABLE *table=join_tab->table;
  int error;
  if (!cond)
    DBUG_RETURN(TRUE);

  for (uint i=0 ; i < join_tab->ref.key_parts ; i++)
  {
9151 9152
    Field *field=table->field[table->key_info[join_tab->ref.key].key_part[i].
			      fieldnr-1];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9153
    Item *value=join_tab->ref.items[i];
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
9154
    cond->add(new Item_func_equal(new Item_field(field), value));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9155
  }
9156
  if (thd->is_fatal_error)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9157
    DBUG_RETURN(TRUE);
9158

9159 9160
  if (!cond->fixed)
    cond->fix_fields(thd,(TABLE_LIST *) 0, (Item**)&cond);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171
  if (join_tab->select)
  {
    error=(int) cond->add(join_tab->select->cond);
    join_tab->select_cond=join_tab->select->cond=cond;
  }
  else if ((join_tab->select=make_select(join_tab->table, 0, 0, cond,&error)))
    join_tab->select_cond=cond;

  DBUG_RETURN(error ? TRUE : FALSE);
}

9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188

/*
  Free joins of subselect of this select.

  free_underlaid_joins()
    thd - THD pointer
    select - pointer to st_select_lex which subselects joins we will free
*/

void free_underlaid_joins(THD *thd, SELECT_LEX *select)
{
  for (SELECT_LEX_UNIT *unit= select->first_inner_unit();
       unit;
       unit= unit->next_unit())
    unit->cleanup();
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
9189
/****************************************************************************
9190 9191 9192
  ROLLUP handling
****************************************************************************/

9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225
/*
  Replace occurences of group by fields in an expression by ref items

  SYNOPSIS
    change_group_ref()
    thd                  reference to the context
    expr                 expression to make replacement
    group_list           list of references to group by items
    changed        out:  returns 1 if item contains a replaced field item 
     
  DESCRIPTION
    The function replaces occurrences of group by fields in expr
    by ref objects for these fields unless they are under aggregate
    functions.

  IMPLEMENTATION
    The function recursively traverses the tree of the expr expression,
    looks for occurrences of the group by fields that are not under
    aggregate functions and replaces them for the corresponding ref items.

  NOTES
    This substitution is needed GROUP BY queries with ROLLUP if
    SELECT list contains expressions over group by attributes.

  EXAMPLES
    SELECT a+1 FROM t1 GROUP BY a WITH ROLLUP
    SELECT SUM(a)+a FROM t1 GROUP BY a WITH ROLLUP 
    
  RETURN
    0	if ok
    1   on error
*/

igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
9226
static bool change_group_ref(THD *thd, Item_func *expr, ORDER *group_list,
9227 9228
                             bool *changed)
{
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
9229
  if (expr->arg_count)
9230 9231
  {
    Item **arg,**arg_end;
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
9232 9233
    for (arg= expr->arguments(),
         arg_end= expr->arguments()+expr->arg_count;
9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253
         arg != arg_end; arg++)
    {
      Item *item= *arg;
      if (item->type() == Item::FIELD_ITEM || item->type() == Item::REF_ITEM)
      {
        ORDER *group_tmp;
        for (group_tmp= group_list; group_tmp; group_tmp= group_tmp->next)
        {
          if (item->eq(*group_tmp->item,0))
          {
            Item *new_item;    
            if(!(new_item= new Item_ref(group_tmp->item, 0, item->name)))
              return 1;                                 // fatal_error is set
            thd->change_item_tree(arg, new_item);
            *changed= TRUE;
          }
        }
      }
      else if (item->type() == Item::FUNC_ITEM)
      {
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
9254
        if (change_group_ref(thd, (Item_func *) item, group_list, changed))
9255 9256 9257 9258 9259 9260 9261 9262
          return 1;
      }
    }
  }
  return 0;
}


9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278
/* Allocate memory needed for other rollup functions */

bool JOIN::rollup_init()
{
  uint i,j;
  Item **ref_array;

  tmp_table_param.quick_group= 0;	// Can't create groups in tmp table
  rollup.state= ROLLUP::STATE_INITED;

  /*
    Create pointers to the different sum function groups
    These are updated by rollup_make_fields()
  */
  tmp_table_param.group_parts= send_group_parts;

9279 9280 9281 9282 9283
  if (!(rollup.null_items= (Item_null_result**) thd->alloc((sizeof(Item*) +
                                                sizeof(Item**) +
                                                sizeof(List<Item>) +
				                ref_pointer_array_size)
				                * send_group_parts )))
9284
    return 1;
9285 9286
  
  rollup.fields= (List<Item>*) (rollup.null_items + send_group_parts);
9287 9288 9289 9290 9291 9292 9293 9294 9295
  rollup.ref_pointer_arrays= (Item***) (rollup.fields + send_group_parts);
  ref_array= (Item**) (rollup.ref_pointer_arrays+send_group_parts);

  /*
    Prepare space for field list for the different levels
    These will be filled up in rollup_make_fields()
  */
  for (i= 0 ; i < send_group_parts ; i++)
  {
9296
    rollup.null_items[i]= new (thd->mem_root) Item_null_result();
9297 9298
    List<Item> *rollup_fields= &rollup.fields[i];
    rollup_fields->empty();
9299 9300
    rollup.ref_pointer_arrays[i]= ref_array;
    ref_array+= all_fields.elements;
9301 9302 9303
  }
  for (i= 0 ; i < send_group_parts; i++)
  {
9304
    for (j=0 ; j < fields_list.elements ; j++)
9305
      rollup.fields[i].push_back(rollup.null_items[i]);
9306
  }
9307
  List_iterator_fast<Item> it(all_fields);
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
9308 9309 9310 9311 9312 9313
  Item *item;
  while ((item= it++))
  {
    ORDER *group_tmp;
    for (group_tmp= group_list; group_tmp; group_tmp= group_tmp->next)
    {
9314
      if (item->eq(*group_tmp->item,0))
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
9315 9316
        item->maybe_null= 1;
    }
9317 9318 9319
    if (item->type() == Item::FUNC_ITEM)
    {
      bool changed= 0;
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
9320
      if (change_group_ref(thd, (Item_func *) item, group_list, &changed))
9321 9322 9323 9324 9325 9326 9327 9328 9329
        return 1;
      /*
        We have to prevent creation of a field in a temporary table for
        an expression that contains GROUP BY attributes.
        Marking the expression item as 'with_sum_func' will ensure this.
      */ 
      if (changed)
        item->with_sum_func= 1;
    }
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
9330
  }
9331 9332 9333 9334 9335 9336 9337 9338 9339
  return 0;
}
  

/*
  Fill up rollup structures with pointers to fields to use

  SYNOPSIS
    rollup_make_fields()
9340 9341
    fields_arg			List of all fields (hidden and real ones)
    sel_fields			Pointer to selected fields
9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352
    func			Store here a pointer to all fields

  IMPLEMENTATION:
    Creates copies of item_sum items for each sum level

  RETURN
    0	if ok
	In this case func is pointing to next not used element.
    1   on error
*/

9353
bool JOIN::rollup_make_fields(List<Item> &fields_arg, List<Item> &sel_fields,
9354 9355
			      Item_sum ***func)
{
9356 9357
  List_iterator_fast<Item> it(fields_arg);
  Item *first_field= sel_fields.head();
9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380
  uint level;

  /*
    Create field lists for the different levels

    The idea here is to have a separate field list for each rollup level to
    avoid all runtime checks of which columns should be NULL.

    The list is stored in reverse order to get sum function in such an order
    in func that it makes it easy to reset them with init_sum_functions()

    Assuming:  SELECT a, b, c SUM(b) FROM t1 GROUP BY a,b WITH ROLLUP

    rollup.fields[0] will contain list where a,b,c is NULL
    rollup.fields[1] will contain list where b,c is NULL
    ...
    rollup.ref_pointer_array[#] points to fields for rollup.fields[#]
    ...
    sum_funcs_end[0] points to all sum functions
    sum_funcs_end[1] points to all sum functions, except grand totals
    ...
  */

9381
  for (level=0 ; level < send_group_parts ; level++)
9382 9383 9384 9385 9386 9387 9388 9389 9390 9391
  {
    uint i;
    uint pos= send_group_parts - level -1;
    bool real_fields= 0;
    Item *item;
    List_iterator<Item> new_it(rollup.fields[pos]);
    Item **ref_array_start= rollup.ref_pointer_arrays[pos];
    ORDER *start_group;

    /* Point to first hidden field */
9392
    Item **ref_array= ref_array_start + fields_arg.elements-1;
9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428

    /* Remember where the sum functions ends for the previous level */
    sum_funcs_end[pos+1]= *func;

    /* Find the start of the group for this level */
    for (i= 0, start_group= group_list ;
	 i++ < pos ;
	 start_group= start_group->next)
      ;

    it.rewind();
    while ((item= it++))
    {
      if (item == first_field)
      {
	real_fields= 1;				// End of hidden fields
	ref_array= ref_array_start;
      }

      if (item->type() == Item::SUM_FUNC_ITEM && !item->const_item())
      {
	/*
	  This is a top level summary function that must be replaced with
	  a sum function that is reset for this level.

	  NOTE: This code creates an object which is not that nice in a
	  sub select.  Fortunately it's not common to have rollup in
	  sub selects.
	*/
	item= item->copy_or_same(thd);
	((Item_sum*) item)->make_unique();
	if (((Item_sum*) item)->setup(thd))
	  return 1;
	*(*func)= (Item_sum*) item;
	(*func)++;
      }
9429
      else 
9430 9431
      {
	/* Check if this is something that is part of this group by */
9432
	ORDER *group_tmp;
9433
	for (group_tmp= start_group, i= pos ;
9434
             group_tmp ; group_tmp= group_tmp->next, i++)
9435
	{
9436
          if (item->eq(*group_tmp->item,0))
9437 9438 9439 9440 9441
	  {
	    /*
	      This is an element that is used by the GROUP BY and should be
	      set to NULL in this level
	    */
9442
            Item_null_result *null_item;
9443
	    item->maybe_null= 1;		// Value will be null sometimes
9444 9445
            null_item= rollup.null_items[i];
            null_item->result_field= item->get_tmp_table_field();
9446
            item= null_item;
9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494
	    break;
	  }
	}
      }
      *ref_array= item;
      if (real_fields)
      {
	(void) new_it++;			// Point to next item
	new_it.replace(item);			// Replace previous
	ref_array++;
      }
      else
	ref_array--;
    }
  }
  sum_funcs_end[0]= *func;			// Point to last function
  return 0;
}

/*
  Send all rollup levels higher than the current one to the client

  SYNOPSIS:
    rollup_send_data()
    idx			Level we are on:
			0 = Total sum level
			1 = First group changed  (a)
			2 = Second group changed (a,b)

  SAMPLE
    SELECT a, b, c SUM(b) FROM t1 GROUP BY a,b WITH ROLLUP

  RETURN
    0	ok
    1   If send_data_failed()
*/

int JOIN::rollup_send_data(uint idx)
{
  uint i;
  for (i= send_group_parts ; i-- > idx ; )
  {
    /* Get reference pointers to sum functions in place */
    memcpy((char*) ref_pointer_array,
	   (char*) rollup.ref_pointer_arrays[i],
	   ref_pointer_array_size);
    if ((!having || having->val_int()))
    {
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
9495
      if (send_records < unit->select_limit_cnt && do_send_rows &&
9496 9497 9498 9499 9500 9501 9502 9503 9504 9505
	  result->send_data(rollup.fields[i]))
	return 1;
      send_records++;
    }
  }
  /* Restore ref_pointer_array */
  set_items_ref_array(current_ref_pointer_array);
  return 0;
}

9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557
/*
  Write all rollup levels higher than the current one to a temp table

  SYNOPSIS:
    rollup_write_data()
    idx                 Level we are on:
                        0 = Total sum level
                        1 = First group changed  (a)
                        2 = Second group changed (a,b)
    table               reference to temp table

  SAMPLE
    SELECT a, b, SUM(c) FROM t1 GROUP BY a,b WITH ROLLUP

  RETURN
    0	ok
    1   if write_data_failed()
*/

int JOIN::rollup_write_data(uint idx, TABLE *table)
{
  uint i;
  for (i= send_group_parts ; i-- > idx ; )
  {
    /* Get reference pointers to sum functions in place */
    memcpy((char*) ref_pointer_array,
	   (char*) rollup.ref_pointer_arrays[i],
	   ref_pointer_array_size);
    if ((!having || having->val_int()))
    {
      int error;
      Item *item;
      List_iterator_fast<Item> it(rollup.fields[i]);
      while ((item= it++))
      {
        if (item->type() == Item::NULL_ITEM && item->is_result_field())
          item->save_in_result_field(1);
      }
      copy_sum_funcs(sum_funcs_end[i+1], sum_funcs_end[i]);
      if ((error= table->file->write_row(table->record[0])))
      {
	if (create_myisam_from_heap(thd, table, &tmp_table_param,
				      error, 0))
	  return 1;		     
      }
    }
  }
  /* Restore ref_pointer_array */
  set_items_ref_array(current_ref_pointer_array);
  return 0;
}

9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577
/*
  clear results if there are not rows found for group
  (end_send_group/end_write_group)

  SYNOPSYS
     JOIN::clear()
*/

void JOIN::clear()
{
  clear_tables(this);
  copy_fields(&tmp_table_param);

  if (sum_funcs)
  {
    Item_sum *func, **func_ptr= sum_funcs;
    while ((func= *(func_ptr++)))
      func->clear();
  }
}
9578

bk@work.mysql.com's avatar
bk@work.mysql.com committed
9579
/****************************************************************************
9580 9581
  EXPLAIN handling

9582
  Send a description about what how the select will be done to stdout
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9583 9584
****************************************************************************/

monty@tramp.mysql.fi's avatar
monty@tramp.mysql.fi committed
9585
static void select_describe(JOIN *join, bool need_tmp_table, bool need_order,
9586
			    bool distinct,const char *message)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9587 9588
{
  List<Item> field_list;
9589
  List<Item> item_list;
monty@tramp.mysql.fi's avatar
monty@tramp.mysql.fi committed
9590
  THD *thd=join->thd;
9591
  select_result *result=join->result;
9592
  Item *item_null= new Item_null();
9593
  CHARSET_INFO *cs= system_charset_info;
monty@tramp.mysql.fi's avatar
monty@tramp.mysql.fi committed
9594
  DBUG_ENTER("select_describe");
9595
  DBUG_PRINT("info", ("Select 0x%lx, type %s, message %s",
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
9596
		      (ulong)join->select_lex, join->select_lex->type,
9597
		      message ? message : "NULL"));
9598
  /* Don't log this into the slow query log */
9599
  thd->server_status&= ~(SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
9600
  join->unit->offset_limit_cnt= 0;
9601

9602
  if (message)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9603
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
9604
    item_list.push_back(new Item_int((int32)
9605
				     join->select_lex->select_number));
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
9606
    item_list.push_back(new Item_string(join->select_lex->type,
9607
					strlen(join->select_lex->type), cs));
9608
    for (uint i=0 ; i < 7; i++)
9609
      item_list.push_back(item_null);
9610
    item_list.push_back(new Item_string(message,strlen(message),cs));
9611
    if (result->send_data(item_list))
9612
      join->error= 1;
9613
  }
9614 9615 9616
  else if (join->select_lex == join->unit->fake_select_lex)
  {
    /* 
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
9617 9618 9619 9620 9621
      here we assume that the query will return at least two rows, so we
      show "filesort" in EXPLAIN. Of course, sometimes we'll be wrong
      and no filesort will be actually done, but executing all selects in
      the UNION to provide precise EXPLAIN information will hardly be
      appreciated :)
9622
    */
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
9623
    char table_name_buffer[NAME_LEN];
9624 9625
    item_list.empty();
    /* id */
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
9626
    item_list.push_back(new Item_null);
9627 9628 9629 9630 9631
    /* select_type */
    item_list.push_back(new Item_string(join->select_lex->type,
					strlen(join->select_lex->type),
					cs));
    /* table */
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654
    {
      SELECT_LEX *sl= join->unit->first_select();
      uint len= 6, lastop= 0;
      memcpy(table_name_buffer, "<union", 6);
      for (; sl && len + lastop + 5 < NAME_LEN; sl= sl->next_select())
      {
        len+= lastop;
        lastop= my_snprintf(table_name_buffer + len, NAME_LEN - len,
                            "%u,", sl->select_number);
      }
      if (sl || len + lastop >= NAME_LEN)
      {
        memcpy(table_name_buffer + len, "...>", 5);
        len+= 4;
      }
      else
      {
        len+= lastop;
        table_name_buffer[len - 1]= '>';  // change ',' to '>'
      }
      item_list.push_back(new Item_string(table_name_buffer, len, cs));
    }
    /* type */
9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677
    item_list.push_back(new Item_string(join_type_str[JT_ALL],
					  strlen(join_type_str[JT_ALL]),
					  cs));
    /* possible_keys */
    item_list.push_back(item_null);
    /* key*/
    item_list.push_back(item_null);
    /* key_len */
    item_list.push_back(item_null);
    /* ref */
    item_list.push_back(item_null);
    /* rows */
    item_list.push_back(item_null);
    /* extra */
    if (join->unit->global_parameters->order_list.first)
      item_list.push_back(new Item_string("Using filesort",
					  14, cs));
    else
      item_list.push_back(new Item_string("", 0, cs));

    if (result->send_data(item_list))
      join->error= 1;
  }
9678 9679 9680 9681
  else
  {
    table_map used_tables=0;
    for (uint i=0 ; i < join->tables ; i++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9682
    {
9683 9684
      JOIN_TAB *tab=join->join_tab+i;
      TABLE *table=tab->table;
9685
      char buff[512],*buff_ptr=buff;
9686
      char buff1[512], buff2[512];
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
9687
      char table_name_buffer[NAME_LEN];
9688 9689
      String tmp1(buff1,sizeof(buff1),cs);
      String tmp2(buff2,sizeof(buff2),cs);
9690 9691 9692
      tmp1.length(0);
      tmp2.length(0);

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
9693
      item_list.empty();
9694
      /* id */
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
9695
      item_list.push_back(new Item_uint((uint32)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
9696
				       join->select_lex->select_number));
9697
      /* select_type */
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
9698 9699
      item_list.push_back(new Item_string(join->select_lex->type,
					  strlen(join->select_lex->type),
9700
					  cs));
9701 9702
      if (tab->type == JT_ALL && tab->select && tab->select->quick)
	tab->type= JT_RANGE;
9703
      /* table */
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
9704
      if (table->derived_select_number)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
9705
      {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
9706
	/* Derived table name generation */
9707
	int len= my_snprintf(table_name_buffer, sizeof(table_name_buffer)-1,
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
9708
			     "<derived%u>",
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
9709
			     table->derived_select_number);
9710
	item_list.push_back(new Item_string(table_name_buffer, len, cs));
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
9711 9712 9713 9714
      }
      else
	item_list.push_back(new Item_string(table->table_name,
					    strlen(table->table_name),
9715
					    cs));
9716
      /* type */
9717 9718
      item_list.push_back(new Item_string(join_type_str[tab->type],
					  strlen(join_type_str[tab->type]),
9719
					  cs));
9720
      uint j;
9721
      /* possible_keys */
9722
      if (!tab->keys.is_clear_all())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9723
      {
serg@serg.mylan's avatar
serg@serg.mylan committed
9724
        for (j=0 ; j < table->keys ; j++)
9725 9726 9727 9728 9729
        {
          if (tab->keys.is_set(j))
          {
            if (tmp1.length())
              tmp1.append(',');
9730 9731 9732
            tmp1.append(table->key_info[j].name, 
			strlen(table->key_info[j].name),
			system_charset_info);
9733 9734
          }
        }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9735
      }
9736
      if (tmp1.length())
9737
	item_list.push_back(new Item_string(tmp1.ptr(),tmp1.length(),cs));
9738
      else
9739
	item_list.push_back(item_null);
9740
      /* key key_len ref */
9741
      if (tab->ref.key_parts)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9742
      {
9743 9744
	KEY *key_info=table->key_info+ tab->ref.key;
	item_list.push_back(new Item_string(key_info->name,
9745 9746
					    strlen(key_info->name),
					    system_charset_info));
9747
	item_list.push_back(new Item_int((int32) tab->ref.key_length));
9748 9749
	for (store_key **ref=tab->ref.key_copy ; *ref ; ref++)
	{
9750 9751
	  if (tmp2.length())
	    tmp2.append(',');
9752 9753
	  tmp2.append((*ref)->name(), strlen((*ref)->name()),
		      system_charset_info);
9754
	}
9755
	item_list.push_back(new Item_string(tmp2.ptr(),tmp2.length(),cs));
9756 9757 9758
      }
      else if (tab->type == JT_NEXT)
      {
9759 9760
	KEY *key_info=table->key_info+ tab->index;
	item_list.push_back(new Item_string(key_info->name,
9761
					    strlen(key_info->name),cs));
9762 9763
	item_list.push_back(new Item_int((int32) key_info->key_length));
	item_list.push_back(item_null);
9764 9765 9766
      }
      else if (tab->select && tab->select->quick)
      {
9767 9768
	KEY *key_info=table->key_info+ tab->select->quick->index;
	item_list.push_back(new Item_string(key_info->name,
9769
					    strlen(key_info->name),cs));
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
9770 9771
	item_list.push_back(new Item_int((int32) tab->select->quick->
					 max_used_key_length));
9772
	item_list.push_back(item_null);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9773 9774 9775
      }
      else
      {
9776 9777 9778
	item_list.push_back(item_null);
	item_list.push_back(item_null);
	item_list.push_back(item_null);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9779
      }
9780
      /* rows */
9781 9782 9783
      item_list.push_back(new Item_int((longlong) (ulonglong)
				       join->best_positions[i]. records_read,
				       21));
9784
      /* extra */
9785
      my_bool key_read=table->key_read;
9786 9787
      if ((tab->type == JT_NEXT || tab->type == JT_CONST) &&
          table->used_keys.is_set(tab->index))
9788
	key_read=1;
9789

9790
      if (tab->info)
9791
	item_list.push_back(new Item_string(tab->info,strlen(tab->info),cs));
9792
      else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9793
      {
9794
	if (tab->select)
9795
	{
9796 9797
	  if (tab->use_quick == 2)
	  {
9798
            char buf[MAX_KEY/8+1];
serg@serg.mylan's avatar
serg@serg.mylan committed
9799
	    sprintf(buff_ptr,"; Range checked for each record (index map: 0x%s)",
9800
                tab->keys.print(buf));
9801 9802 9803 9804
	    buff_ptr=strend(buff_ptr);
	  }
	  else
	    buff_ptr=strmov(buff_ptr,"; Using where");
9805
	}
9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819
	if (key_read)
	  buff_ptr= strmov(buff_ptr,"; Using index");
	if (table->reginfo.not_exists_optimize)
	  buff_ptr= strmov(buff_ptr,"; Not exists");
	if (need_tmp_table)
	{
	  need_tmp_table=0;
	  buff_ptr= strmov(buff_ptr,"; Using temporary");
	}
	if (need_order)
	{
	  need_order=0;
	  buff_ptr= strmov(buff_ptr,"; Using filesort");
	}
9820
	if (distinct & test_all_bits(used_tables,thd->used_tables))
9821 9822
	  buff_ptr= strmov(buff_ptr,"; Distinct");
	if (buff_ptr == buff)
9823 9824
	  buff_ptr+= 2;				// Skip inital "; "
	item_list.push_back(new Item_string(buff+2,(uint) (buff_ptr - buff)-2,
9825
					    cs));
9826 9827 9828
      }
      // For next iteration
      used_tables|=table->map;
9829
      if (result->send_data(item_list))
9830
	join->error= 1;
9831
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9832
  }
9833 9834 9835 9836 9837 9838 9839
  for (SELECT_LEX_UNIT *unit= join->select_lex->first_inner_unit();
       unit;
       unit= unit->next_unit())
  {
    if (mysql_explain_union(thd, unit, result))
      DBUG_VOID_RETURN;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
9840 9841 9842
  DBUG_VOID_RETURN;
}

9843

9844 9845
int mysql_explain_union(THD *thd, SELECT_LEX_UNIT *unit, select_result *result)
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
9846
  DBUG_ENTER("mysql_explain_union");
9847 9848
  int res= 0;
  SELECT_LEX *first= unit->first_select();
9849

9850 9851 9852 9853
  for (SELECT_LEX *sl= first;
       sl;
       sl= sl->next_select())
  {
9854 9855
    // drop UNCACHEABLE_EXPLAIN, because it is for internal usage only
    uint8 uncacheable= (sl->uncacheable & ~UNCACHEABLE_EXPLAIN);
9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873
    sl->type= (((&thd->lex->select_lex)==sl)?
	       ((thd->lex->all_selects_list != sl) ? 
		primary_key_name : "SIMPLE"):
	       ((sl == first)?
		((sl->linkage == DERIVED_TABLE_TYPE) ?
		 "DERIVED":
		 ((uncacheable & UNCACHEABLE_DEPENDENT) ?
		  "DEPENDENT SUBQUERY":
		  (uncacheable?"UNCACHEABLE SUBQUERY":
		   "SUBQUERY"))):
		((uncacheable & UNCACHEABLE_DEPENDENT) ?
		 "DEPENDENT UNION":
		 uncacheable?"UNCACHEABLE UNION":
		 "UNION")));
    sl->options|= SELECT_DESCRIBE;
  }
  if (first->next_select())
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
9874
    unit->fake_select_lex->select_number= UINT_MAX; // jost for initialization
9875 9876
    unit->fake_select_lex->type= "UNION RESULT";
    unit->fake_select_lex->options|= SELECT_DESCRIBE;
9877 9878
    if (!(res= unit->prepare(thd, result, SELECT_NO_UNLOCK | SELECT_DESCRIBE,
                             "")))
9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896
      res= unit->exec();
    res|= unit->cleanup();
  }
  else
  {
    thd->lex->current_select= first;
    res= mysql_select(thd, &first->ref_pointer_array,
			(TABLE_LIST*) first->table_list.first,
			first->with_wild, first->item_list,
			first->where,
			first->order_list.elements +
			first->group_list.elements,
			(ORDER*) first->order_list.first,
			(ORDER*) first->group_list.first,
			first->having,
			(ORDER*) thd->lex->proc_list.first,
			first->options | thd->options | SELECT_DESCRIBE,
			result, unit, first);
9897
  }
9898 9899
  if (res > 0 || thd->net.report_error)
    res= -1; // mysql_explain_select do not report error
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
9900
  DBUG_RETURN(res);
9901 9902
}

9903

9904 9905 9906 9907 9908
void st_select_lex::print(THD *thd, String *str)
{
  if (!thd)
    thd= current_thd;

9909
  str->append("select ", 7);
9910 9911 9912
  
  //options
  if (options & SELECT_STRAIGHT_JOIN)
9913
    str->append("straight_join ", 14);
9914
  if ((thd->lex->lock_option == TL_READ_HIGH_PRIORITY) &&
9915
      (this == &thd->lex->select_lex))
9916
    str->append("high_priority ", 14);
9917
  if (options & SELECT_DISTINCT)
9918
    str->append("distinct ", 9);
9919
  if (options & SELECT_SMALL_RESULT)
9920
    str->append("sql_small_result ", 17);
9921
  if (options & SELECT_BIG_RESULT)
9922
    str->append("sql_big_result ", 15);
9923
  if (options & OPTION_BUFFER_RESULT)
9924
    str->append("sql_buffer_result ", 18);
9925
  if (options & OPTION_FOUND_ROWS)
9926
    str->append("sql_calc_found_rows ", 20);
9927
  if (!thd->lex->safe_to_cache_query)
9928
    str->append("sql_no_cache ", 13);
9929
  if (options & OPTION_TO_QUERY_CACHE)
9930
    str->append("sql_cache ", 10);
9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950

  //Item List
  bool first= 1;
  List_iterator_fast<Item> it(item_list);
  Item *item;
  while ((item= it++))
  {
    if (first)
      first= 0;
    else
      str->append(',');
    item->print_item_w_name(str);
  }

  /*
    from clause
    TODO: support USING/FORCE/IGNORE index
  */
  if (table_list.elements)
  {
9951
    str->append(" from ", 6);
9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968
    Item *next_on= 0;
    for (TABLE_LIST *table= (TABLE_LIST *) table_list.first;
	 table;
	 table= table->next)
    {
      if (table->derived)
      {
	str->append('(');
	table->derived->print(str);
	str->append(") ");
	str->append(table->alias);
      }
      else
      {
	str->append(table->db);
	str->append('.');
	str->append(table->real_name);
9969
	if (my_strcasecmp(table_alias_charset, table->real_name, table->alias))
9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981
	{
	  str->append(' ');
	  str->append(table->alias);
	}
      }

      if (table->on_expr && ((table->outer_join & JOIN_TYPE_LEFT) ||
			     !(table->outer_join & JOIN_TYPE_RIGHT)))
	next_on= table->on_expr;

      if (next_on)
      {
9982
	str->append(" on(", 4);
9983 9984 9985 9986 9987
	next_on->print(str);
	str->append(')');
	next_on= 0;
      }

9988 9989
      TABLE_LIST *next_table;
      if ((next_table= table->next))
9990 9991 9992
      {
	if (table->outer_join & JOIN_TYPE_RIGHT)
	{
9993
	  str->append(" right join ", 12);
9994 9995 9996 9997
	  if (!(table->outer_join & JOIN_TYPE_LEFT) &&
	      table->on_expr)
	    next_on= table->on_expr;	    
	}
9998
	else if (next_table->straight)
9999
	  str->append(" straight_join ", 15);
10000
	else if (next_table->outer_join & JOIN_TYPE_LEFT)
10001
	  str->append(" left join ", 11);
10002
	else
10003
	  str->append(" join ", 6);
10004 10005 10006 10007
      }
    }
  }

10008 10009
  // Where
  Item *cur_where= where;
10010
  if (join)
10011 10012
    cur_where= join->conds;
  if (cur_where)
10013
  {
10014
    str->append(" where ", 7);
10015
    cur_where->print(str);
10016 10017
  }

10018
  // group by & olap
10019 10020
  if (group_list.elements)
  {
10021
    str->append(" group by ", 10);
10022 10023 10024 10025
    print_order(str, (ORDER *) group_list.first);
    switch (olap)
    {
      case CUBE_TYPE:
10026
	str->append(" with cube", 10);
10027 10028
	break;
      case ROLLUP_TYPE:
10029
	str->append(" with rollup", 12);
10030 10031 10032 10033 10034 10035
	break;
      default:
	;  //satisfy compiler
    }
  }

10036 10037
  // having
  Item *cur_having= having;
10038
  if (join)
10039
    cur_having= join->having;
10040

10041
  if (cur_having)
10042
  {
10043
    str->append(" having ", 8);
10044
    cur_having->print(str);
10045 10046 10047 10048
  }

  if (order_list.elements)
  {
10049
    str->append(" order by ", 10);
10050 10051 10052 10053 10054 10055 10056 10057
    print_order(str, (ORDER *) order_list.first);
  }

  // limit
  print_limit(thd, str);

  // PROCEDURE unsupported here
}
10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081


/*
  change select_result object of JOIN

  SYNOPSIS
    JOIN::change_result()
    res		new select_result object

  RETURN
    0 - OK
    -1 - error
*/

int JOIN::change_result(select_result *res)
{
  DBUG_ENTER("JOIN::change_result");
  result= res;
  if (!procedure && result->prepare(fields_list, select_lex->master_unit()))
  {
    DBUG_RETURN(-1);
  }
  DBUG_RETURN(0);
}