~drizzle-trunk/drizzle/development

1 by brian
clean slate
1
/* Copyright (C) 2000-2006 MySQL AB
2
3
   This program is free software; you can redistribute it and/or modify
4
   it under the terms of the GNU General Public License as published by
5
   the Free Software Foundation; version 2 of the License.
6
7
   This program is distributed in the hope that it will be useful,
8
   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
   GNU General Public License for more details.
11
12
   You should have received a copy of the GNU General Public License
13
   along with this program; if not, write to the Free Software
14
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
15
16
/**
17
  @file
18
19
  @brief
20
  mysql_select and join optimization
21
22
  @defgroup Query_Optimizer  Query Optimizer
23
  @{
24
*/
934.2.1 by Jay Pipes
Split index hints out into their own file, removal from sql_lex.h and sql_select.cc
25
#include "drizzled/server_includes.h"
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
26
#include "drizzled/sql_select.h" /* include join.h */
934.2.1 by Jay Pipes
Split index hints out into their own file, removal from sql_lex.h and sql_select.cc
27
#include "drizzled/table_map_iterator.h"
1 by brian
clean slate
28
934.2.1 by Jay Pipes
Split index hints out into their own file, removal from sql_lex.h and sql_select.cc
29
#include "drizzled/error.h"
30
#include "drizzled/gettext.h"
31
#include "drizzled/util/test.h"
32
#include "drizzled/name_resolution_context_state.h"
33
#include "drizzled/nested_join.h"
34
#include "drizzled/probes.h"
35
#include "drizzled/show.h"
1063.4.6 by Padraig O'Sullivan
Added a new header file which contains the InfoSchemaTable class and the
36
#include "drizzled/info_schema.h"
934.2.1 by Jay Pipes
Split index hints out into their own file, removal from sql_lex.h and sql_select.cc
37
#include "drizzled/item/cache.h"
38
#include "drizzled/item/cmpfunc.h"
39
#include "drizzled/item/copy_string.h"
40
#include "drizzled/item/uint.h"
41
#include "drizzled/cached_item.h"
42
#include "drizzled/sql_base.h"
43
#include "drizzled/field/blob.h"
44
#include "drizzled/check_stack_overrun.h"
45
#include "drizzled/lock.h"
46
#include "drizzled/item/outer_ref.h"
47
#include "drizzled/index_hint.h"
675 by Brian Aker
Cleanup around item includes.
48
1008.3.22 by Stewart Smith
s/mysql_union/drizzle_union/
49
#include <drizzled/sql_union.h>
50
873.2.33 by Monty Taylor
Added string headers which are needed.
51
#include <string>
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
52
#include <iostream>
1067.4.4 by Nathan Williams
The rest of the files in the drizzled directory were purged of the cmin macro and replace with std::min (except for the definition in globals.h and 1 usage in stacktrace.cc).
53
#include <algorithm>
1 by brian
clean slate
54
873.2.33 by Monty Taylor
Added string headers which are needed.
55
using namespace std;
56
1108.6.20 by Padraig O'Sullivan
Renamed access_type to access_method due to conflicts on Solaris.
57
static const string access_method_str[]=
1108.6.1 by Padraig O'Sullivan
Changed the name of the enum join_type to access_type. It makes much more
58
{
59
  "UNKNOWN",
60
  "system",
61
  "const",
62
  "eq_ref",
63
  "ref",
64
  "MAYBE_REF",
65
  "ALL",
66
  "range",
67
  "index",
68
  "ref_or_null",
1108.6.2 by Padraig O'Sullivan
Whoops, forgot a comma in an array declaration!
69
  "unique_subquery",
1108.6.1 by Padraig O'Sullivan
Changed the name of the enum join_type to access_type. It makes much more
70
  "index_subquery",
71
  "index_merge"
1 by brian
clean slate
72
};
73
1089.1.8 by Brian Aker
Shuffled around a few structures.
74
static int sort_keyuse(KeyUse *a,KeyUse *b);
520.1.22 by Brian Aker
Second pass of thd cleanup
75
static COND *build_equal_items(Session *session, COND *cond,
1 by brian
clean slate
76
                               COND_EQUAL *inherited,
327.2.4 by Brian Aker
Refactoring table.h
77
                               List<TableList> *join_list,
1 by brian
clean slate
78
                               COND_EQUAL **cond_equal_ref);
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
79
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
80
static Item* part_of_refkey(Table *form,Field *field);
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
81
static bool cmp_buffer_with_ref(JoinTable *tab);
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
82
static void change_cond_ref_to_const(Session *session,
1046.2.1 by Nathan Williams
Changed all instances of I_List<COND_CMP> to vector<COND_CMP>
83
                                     vector<COND_CMP>& save_list,
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
84
                                     Item *and_father,
85
                                     Item *cond,
86
                                     Item *field,
87
                                     Item *value);
88
static bool copy_blobs(Field **ptr);
1085.1.2 by Monty Taylor
Fixed -Wmissing-declarations
89
652 by Brian Aker
eval_const_cond moved to being static.
90
static bool eval_const_cond(COND *cond)
91
{
92
    return ((Item_func*) cond)->val_int() ? true : false;
93
}
94
1 by brian
clean slate
95
/*
96
  This is used to mark equalities that were made from i-th IN-equality.
97
  We limit semi-join InsideOut optimization to handling max 64 inequalities,
98
  The following variable occupies 64 addresses.
99
*/
100
const char *subq_sj_cond_name=
101
  "0123456789ABCDEF0123456789abcdef0123456789ABCDEF0123456789abcdef-sj-cond";
102
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
103
static bool copy_blobs(Field **ptr)
1 by brian
clean slate
104
{
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
105
  for (; *ptr ; ptr++)
106
  {
107
    if ((*ptr)->flags & BLOB_FLAG)
108
      if (((Field_blob *) (*ptr))->copy())
109
	return 1;				// Error
110
  }
111
  return 0;
1 by brian
clean slate
112
}
113
114
/**
115
  This handles SELECT with and without UNION.
116
*/
520.1.22 by Brian Aker
Second pass of thd cleanup
117
bool handle_select(Session *session, LEX *lex, select_result *result,
892.2.2 by Monty Taylor
More solaris warnings.
118
                   uint64_t setup_tables_done_option)
1 by brian
clean slate
119
{
120
  bool res;
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
121
  register Select_Lex *select_lex= &lex->select_lex;
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
122
  DRIZZLE_SELECT_START();
1 by brian
clean slate
123
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
124
  if (select_lex->master_unit()->is_union() ||
1 by brian
clean slate
125
      select_lex->master_unit()->fake_select_lex)
1008.3.22 by Stewart Smith
s/mysql_union/drizzle_union/
126
    res= drizzle_union(session, lex, result, &lex->unit,
127
		       setup_tables_done_option);
1 by brian
clean slate
128
  else
129
  {
848 by Brian Aker
typdef class removal (just... use the name of the class).
130
    Select_Lex_Unit *unit= &lex->unit;
1 by brian
clean slate
131
    unit->set_limit(unit->global_parameters);
520.1.22 by Brian Aker
Second pass of thd cleanup
132
    session->session_marker= 0;
1 by brian
clean slate
133
    /*
134
      'options' of mysql_select will be set in JOIN, as far as JOIN for
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
135
      every PS/SP execution new, we will not need reset this flag if
1 by brian
clean slate
136
      setup_tables_done_option changed for next rexecution
137
    */
520.1.22 by Brian Aker
Second pass of thd cleanup
138
    res= mysql_select(session, &select_lex->ref_pointer_array,
327.2.4 by Brian Aker
Refactoring table.h
139
		      (TableList*) select_lex->table_list.first,
1 by brian
clean slate
140
		      select_lex->with_wild, select_lex->item_list,
141
		      select_lex->where,
142
		      select_lex->order_list.elements +
143
		      select_lex->group_list.elements,
327.2.3 by Brian Aker
Refactoring of class Table
144
		      (order_st*) select_lex->order_list.first,
145
		      (order_st*) select_lex->group_list.first,
1 by brian
clean slate
146
		      select_lex->having,
520.1.22 by Brian Aker
Second pass of thd cleanup
147
		      select_lex->options | session->options |
1 by brian
clean slate
148
                      setup_tables_done_option,
149
		      result, unit, select_lex);
150
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
151
  res|= session->is_error();
1 by brian
clean slate
152
  if (unlikely(res))
153
    result->abort();
154
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
155
  DRIZZLE_SELECT_END();
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
156
  return(res);
1 by brian
clean slate
157
}
158
159
/*
160
  Fix fields referenced from inner selects.
161
162
  SYNOPSIS
163
    fix_inner_refs()
520.1.22 by Brian Aker
Second pass of thd cleanup
164
    session               Thread handle
1 by brian
clean slate
165
    all_fields        List of all fields used in select
166
    select            Current select
167
    ref_pointer_array Array of references to Items used in current select
168
169
  DESCRIPTION
170
    The function serves 3 purposes - adds fields referenced from inner
171
    selects to the current select list, resolves which class to use
172
    to access referenced item (Item_ref of Item_direct_ref) and fixes
173
    references (Item_ref objects) to these fields.
174
175
    If a field isn't already in the select list and the ref_pointer_array
176
    is provided then it is added to the all_fields list and the pointer to
177
    it is saved in the ref_pointer_array.
178
179
    The class to access the outer field is determined by the following rules:
180
    1. If the outer field isn't used under an aggregate function
181
      then the Item_ref class should be used.
182
    2. If the outer field is used under an aggregate function and this
183
      function is aggregated in the select where the outer field was
184
      resolved or in some more inner select then the Item_direct_ref
185
      class should be used.
186
    The resolution is done here and not at the fix_fields() stage as
187
    it can be done only after sum functions are fixed and pulled up to
188
    selects where they are have to be aggregated.
189
    When the class is chosen it substitutes the original field in the
190
    Item_outer_ref object.
191
192
    After this we proceed with fixing references (Item_outer_ref objects) to
193
    this field from inner subqueries.
194
195
  RETURN
55 by brian
Update for using real bool types.
196
    true  an error occured
197
    false ok
1 by brian
clean slate
198
*/
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
199
bool fix_inner_refs(Session *session, 
200
                    List<Item> &all_fields, 
201
                    Select_Lex *select, 
202
                    Item **ref_pointer_array)
1 by brian
clean slate
203
{
204
  Item_outer_ref *ref;
55 by brian
Update for using real bool types.
205
  bool res= false;
206
  bool direct_ref= false;
1 by brian
clean slate
207
208
  List_iterator<Item_outer_ref> ref_it(select->inner_refs_list);
209
  while ((ref= ref_it++))
210
  {
211
    Item *item= ref->outer_ref;
212
    Item **item_ref= ref->ref;
213
    Item_ref *new_ref;
214
    /*
215
      TODO: this field item already might be present in the select list.
216
      In this case instead of adding new field item we could use an
217
      existing one. The change will lead to less operations for copying fields,
218
      smaller temporary tables and less data passed through filesort.
219
    */
220
    if (ref_pointer_array && !ref->found_in_select_list)
221
    {
222
      int el= all_fields.elements;
223
      ref_pointer_array[el]= item;
224
      /* Add the field item to the select list of the current select. */
225
      all_fields.push_front(item);
226
      /*
227
        If it's needed reset each Item_ref item that refers this field with
228
        a new reference taken from ref_pointer_array.
229
      */
230
      item_ref= ref_pointer_array + el;
231
    }
232
233
    if (ref->in_sum_func)
234
    {
235
      Item_sum *sum_func;
236
      if (ref->in_sum_func->nest_level > select->nest_level)
55 by brian
Update for using real bool types.
237
        direct_ref= true;
1 by brian
clean slate
238
      else
239
      {
240
        for (sum_func= ref->in_sum_func; sum_func &&
241
             sum_func->aggr_level >= select->nest_level;
242
             sum_func= sum_func->in_sum_func)
243
        {
244
          if (sum_func->aggr_level == select->nest_level)
245
          {
55 by brian
Update for using real bool types.
246
            direct_ref= true;
1 by brian
clean slate
247
            break;
248
          }
249
        }
250
      }
251
    }
252
    new_ref= direct_ref ?
253
              new Item_direct_ref(ref->context, item_ref, ref->table_name,
254
                          ref->field_name, ref->alias_name_used) :
255
              new Item_ref(ref->context, item_ref, ref->table_name,
256
                          ref->field_name, ref->alias_name_used);
257
    if (!new_ref)
55 by brian
Update for using real bool types.
258
      return true;
1 by brian
clean slate
259
    ref->outer_ref= new_ref;
260
    ref->ref= &ref->outer_ref;
261
520.1.22 by Brian Aker
Second pass of thd cleanup
262
    if (!ref->fixed && ref->fix_fields(session, 0))
55 by brian
Update for using real bool types.
263
      return true;
520.1.22 by Brian Aker
Second pass of thd cleanup
264
    session->used_tables|= item->used_tables();
1 by brian
clean slate
265
  }
266
  return res;
267
}
268
269
/*****************************************************************************
270
  Check fields, find best join, do the select and output fields.
271
  mysql_select assumes that all tables are already opened
272
*****************************************************************************/
273
274
/*
275
  Index lookup-based subquery: save some flags for EXPLAIN output
276
277
  SYNOPSIS
278
    save_index_subquery_explain_info()
279
      join_tab  Subquery's join tab (there is only one as index lookup is
280
                only used for subqueries that are single-table SELECTs)
281
      where     Subquery's WHERE clause
282
283
  DESCRIPTION
284
    For index lookup-based subquery (i.e. one executed with
285
    subselect_uniquesubquery_engine or subselect_indexsubquery_engine),
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
286
    check its EXPLAIN output row should contain
287
      "Using index" (TAB_INFO_FULL_SCAN_ON_NULL)
1 by brian
clean slate
288
      "Using Where" (TAB_INFO_USING_WHERE)
289
      "Full scan on NULL key" (TAB_INFO_FULL_SCAN_ON_NULL)
290
    and set appropriate flags in join_tab->packed_info.
291
*/
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
292
void save_index_subquery_explain_info(JoinTable *join_tab, Item* where)
1 by brian
clean slate
293
{
294
  join_tab->packed_info= TAB_INFO_HAVE_VALUE;
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
295
  if (join_tab->table->covering_keys.test(join_tab->ref.key))
1 by brian
clean slate
296
    join_tab->packed_info |= TAB_INFO_USING_INDEX;
297
  if (where)
298
    join_tab->packed_info |= TAB_INFO_USING_WHERE;
482 by Brian Aker
Remove uint.
299
  for (uint32_t i = 0; i < join_tab->ref.key_parts; i++)
1 by brian
clean slate
300
  {
301
    if (join_tab->ref.cond_guards[i])
302
    {
303
      join_tab->packed_info |= TAB_INFO_FULL_SCAN_ON_NULL;
304
      break;
305
    }
306
  }
307
}
308
309
/**
310
  An entry point to single-unit select (a select without UNION).
311
520.1.22 by Brian Aker
Second pass of thd cleanup
312
  @param session                  thread handler
1 by brian
clean slate
313
  @param rref_pointer_array   a reference to ref_pointer_array of
314
                              the top-level select_lex for this query
315
  @param tables               list of all tables used in this query.
316
                              The tables have been pre-opened.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
317
  @param wild_num             number of wildcards used in the top level
1 by brian
clean slate
318
                              select of this query.
319
                              For example statement
320
                              SELECT *, t1.*, catalog.t2.* FROM t0, t1, t2;
321
                              has 3 wildcards.
322
  @param fields               list of items in SELECT list of the top-level
323
                              select
324
                              e.g. SELECT a, b, c FROM t1 will have Item_field
325
                              for a, b and c in this list.
326
  @param conds                top level item of an expression representing
327
                              WHERE clause of the top level select
327.2.3 by Brian Aker
Refactoring of class Table
328
  @param og_num               total number of order_st BY and GROUP BY clauses
1 by brian
clean slate
329
                              arguments
327.2.3 by Brian Aker
Refactoring of class Table
330
  @param order                linked list of order_st BY agruments
1 by brian
clean slate
331
  @param group                linked list of GROUP BY arguments
332
  @param having               top level item of HAVING expression
333
  @param select_options       select options (BIG_RESULT, etc)
334
  @param result               an instance of result set handling class.
335
                              This object is responsible for send result
336
                              set rows to the client or inserting them
337
                              into a table.
846 by Brian Aker
Removing on typedeffed class.
338
  @param select_lex           the only Select_Lex of this query
1 by brian
clean slate
339
  @param unit                 top-level UNIT of this query
340
                              UNIT is an artificial object created by the
341
                              parser for every SELECT clause.
342
                              e.g.
343
                              SELECT * FROM t1 WHERE a1 IN (SELECT * FROM t2)
344
                              has 2 unions.
345
346
  @retval
55 by brian
Update for using real bool types.
347
    false  success
1 by brian
clean slate
348
  @retval
55 by brian
Update for using real bool types.
349
    true   an error
1 by brian
clean slate
350
*/
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
351
bool mysql_select(Session *session,
352
                  Item ***rref_pointer_array,
353
	                TableList *tables, 
354
                  uint32_t wild_num, 
355
                  List<Item> &fields,
356
	                COND *conds, 
357
                  uint32_t og_num,  
358
                  order_st *order, 
359
                  order_st *group,
360
	                Item *having, 
361
                  uint64_t select_options,
362
	                select_result *result, 
363
                  Select_Lex_Unit *unit,
364
	                Select_Lex *select_lex)
1 by brian
clean slate
365
{
366
  bool err;
367
  bool free_join= 1;
368
55 by brian
Update for using real bool types.
369
  select_lex->context.resolve_in_select_list= true;
1 by brian
clean slate
370
  JOIN *join;
371
  if (select_lex->join != 0)
372
  {
373
    join= select_lex->join;
374
    /*
375
      is it single SELECT in derived table, called in derived table
376
      creation
377
    */
378
    if (select_lex->linkage != DERIVED_TABLE_TYPE ||
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
379
        (select_options & SELECT_DESCRIBE))
1 by brian
clean slate
380
    {
381
      if (select_lex->linkage != GLOBAL_OPTIONS_TYPE)
382
      {
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
383
        //here is EXPLAIN of subselect or derived table
384
        if (join->change_result(result))
385
        {
386
          return(true);
387
        }
1 by brian
clean slate
388
      }
389
      else
390
      {
391
        if ((err= join->prepare(rref_pointer_array, tables, wild_num,
923.1.10 by Brian Aker
Remove dead code around old procedures.
392
                               conds, og_num, order, group, having, select_lex, unit)))
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
393
        {
394
          goto err;
395
        }
1 by brian
clean slate
396
      }
397
    }
398
    free_join= 0;
399
    join->select_options= select_options;
400
  }
401
  else
402
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
403
    if (!(join= new JOIN(session, fields, select_options, result)))
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
404
      return(true);
520.1.22 by Brian Aker
Second pass of thd cleanup
405
    session->set_proc_info("init");
406
    session->used_tables=0;                         // Updated by setup_fields
1 by brian
clean slate
407
    if ((err= join->prepare(rref_pointer_array, tables, wild_num,
923.1.10 by Brian Aker
Remove dead code around old procedures.
408
                           conds, og_num, order, group, having,
1 by brian
clean slate
409
                           select_lex, unit)) == true)
410
    {
411
      goto err;
412
    }
413
  }
414
415
  if ((err= join->optimize()))
416
  {
417
    goto err;					// 1
418
  }
419
520.1.22 by Brian Aker
Second pass of thd cleanup
420
  if (session->lex->describe & DESCRIBE_EXTENDED)
1 by brian
clean slate
421
  {
422
    join->conds_history= join->conds;
423
    join->having_history= (join->having?join->having:join->tmp_having);
424
  }
425
520.1.22 by Brian Aker
Second pass of thd cleanup
426
  if (session->is_error())
1 by brian
clean slate
427
    goto err;
428
429
  join->exec();
430
520.1.22 by Brian Aker
Second pass of thd cleanup
431
  if (session->lex->describe & DESCRIBE_EXTENDED)
1 by brian
clean slate
432
  {
433
    select_lex->where= join->conds_history;
434
    select_lex->having= join->having_history;
435
  }
436
437
err:
438
  if (free_join)
439
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
440
    session->set_proc_info("end");
1 by brian
clean slate
441
    err|= select_lex->cleanup();
520.1.22 by Brian Aker
Second pass of thd cleanup
442
    return(err || session->is_error());
1 by brian
clean slate
443
  }
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
444
  return(join->error);
1 by brian
clean slate
445
}
446
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
447
inline Item *and_items(Item* cond, Item *item)
1 by brian
clean slate
448
{
449
  return (cond? (new Item_cond_and(cond, item)) : item);
450
}
451
1085.1.2 by Monty Taylor
Fixed -Wmissing-declarations
452
static void fix_list_after_tbl_changes(Select_Lex *new_parent, List<TableList> *tlist)
1 by brian
clean slate
453
{
327.2.4 by Brian Aker
Refactoring table.h
454
  List_iterator<TableList> it(*tlist);
455
  TableList *table;
1 by brian
clean slate
456
  while ((table= it++))
457
  {
458
    if (table->on_expr)
459
      table->on_expr->fix_after_pullout(new_parent, &table->on_expr);
460
    if (table->nested_join)
461
      fix_list_after_tbl_changes(new_parent, &table->nested_join->join_list);
462
  }
463
}
464
465
/*****************************************************************************
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
466
  Create JoinTableS, make a guess about the table types,
1 by brian
clean slate
467
  Approximate how many records will be used in each table
468
*****************************************************************************/
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
469
ha_rows get_quick_record_count(Session *session, SQL_SELECT *select, Table *table, const key_map *keys,ha_rows limit)
1 by brian
clean slate
470
{
471
  int error;
520.1.22 by Brian Aker
Second pass of thd cleanup
472
  if (check_stack_overrun(session, STACK_MIN_SIZE, NULL))
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
473
    return(0);                           // Fatal error flag is set
1 by brian
clean slate
474
  if (select)
475
  {
476
    select->head=table;
477
    table->reginfo.impossible_range=0;
520.1.22 by Brian Aker
Second pass of thd cleanup
478
    if ((error= select->test_quick_select(session, *(key_map *)keys,(table_map) 0,
55 by brian
Update for using real bool types.
479
                                          limit, 0, false)) == 1)
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
480
      return(select->quick->records);
1 by brian
clean slate
481
    if (error == -1)
482
    {
483
      table->reginfo.impossible_range=1;
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
484
      return(0);
1 by brian
clean slate
485
    }
486
  }
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
487
  return(HA_POS_ERROR);			/* This shouldn't happend */
1 by brian
clean slate
488
}
489
490
/*****************************************************************************
491
  Check with keys are used and with tables references with tables
492
  Updates in stat:
493
	  keys	     Bitmap of all used keys
494
	  const_keys Bitmap of all keys with may be used with quick_select
495
	  keyuse     Pointer to possible keys
496
*****************************************************************************/
497
498
/**
499
  Merge new key definitions to old ones, remove those not used in both.
500
501
  This is called for OR between different levels.
502
503
  To be able to do 'ref_or_null' we merge a comparison of a column
504
  and 'column IS NULL' to one test.  This is useful for sub select queries
505
  that are internally transformed to something like:.
506
507
  @code
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
508
  SELECT * FROM t1 WHERE t1.key=outer_ref_field or t1.key IS NULL
1 by brian
clean slate
509
  @endcode
510
511
  KEY_FIELD::null_rejecting is processed as follows: @n
512
  result has null_rejecting=true if it is set for both ORed references.
513
  for example:
514
  -   (t2.key = t1.field OR t2.key  =  t1.field) -> null_rejecting=true
515
  -   (t2.key = t1.field OR t2.key <=> t1.field) -> null_rejecting=false
516
517
  @todo
518
    The result of this is that we're missing some 'ref' accesses.
519
    OptimizerTeam: Fix this
520
*/
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
521
static KEY_FIELD *merge_key_fields(KEY_FIELD *start,KEY_FIELD *new_fields,KEY_FIELD *end, uint32_t and_level)
1 by brian
clean slate
522
{
523
  if (start == new_fields)
524
    return start;				// Impossible or
525
  if (new_fields == end)
526
    return start;				// No new fields, skip all
527
528
  KEY_FIELD *first_free=new_fields;
529
530
  /* Mark all found fields in old array */
531
  for (; new_fields != end ; new_fields++)
532
  {
533
    for (KEY_FIELD *old=start ; old != first_free ; old++)
534
    {
535
      if (old->field == new_fields->field)
536
      {
537
        /*
538
          NOTE: below const_item() call really works as "!used_tables()", i.e.
55 by brian
Update for using real bool types.
539
          it can return false where it is feasible to make it return true.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
540
1 by brian
clean slate
541
          The cause is as follows: Some of the tables are already known to be
542
          const tables (the detection code is in make_join_statistics(),
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
543
          above the update_ref_and_keys() call), but we didn't propagate
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
544
          information about this: Table::const_table is not set to true, and
1 by brian
clean slate
545
          Item::update_used_tables() hasn't been called for each item.
546
          The result of this is that we're missing some 'ref' accesses.
547
          TODO: OptimizerTeam: Fix this
548
        */
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
549
        if (!new_fields->val->const_item())
550
        {
551
          /*
552
            If the value matches, we can use the key reference.
553
            If not, we keep it until we have examined all new values
554
          */
555
          if (old->val->eq(new_fields->val, old->field->binary()))
556
          {
557
            old->level= and_level;
558
            old->optimize= ((old->optimize & new_fields->optimize &
559
                KEY_OPTIMIZE_EXISTS) |
560
                ((old->optimize | new_fields->optimize) &
561
                KEY_OPTIMIZE_REF_OR_NULL));
562
                  old->null_rejecting= (old->null_rejecting &&
563
                                        new_fields->null_rejecting);
564
          }
565
        }
566
        else if (old->eq_func && new_fields->eq_func &&
567
                      old->val->eq_by_collation(new_fields->val,
568
                                                old->field->binary(),
569
                                                old->field->charset()))
1 by brian
clean slate
570
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
571
        {
572
          old->level= and_level;
573
          old->optimize= ((old->optimize & new_fields->optimize &
574
              KEY_OPTIMIZE_EXISTS) |
575
              ((old->optimize | new_fields->optimize) &
576
              KEY_OPTIMIZE_REF_OR_NULL));
577
                old->null_rejecting= (old->null_rejecting &&
578
                                      new_fields->null_rejecting);
579
        }
580
        else if (old->eq_func && new_fields->eq_func &&
581
          ((old->val->const_item() && old->val->is_null()) ||
582
                        new_fields->val->is_null()))
583
        {
584
          /* field = expression OR field IS NULL */
585
          old->level= and_level;
586
          old->optimize= KEY_OPTIMIZE_REF_OR_NULL;
587
          /*
588
                  Remember the NOT NULL value unless the value does not depend
589
                  on other tables.
590
                */
591
          if (!old->val->used_tables() && old->val->is_null())
592
            old->val= new_fields->val;
593
                /* The referred expression can be NULL: */
594
                old->null_rejecting= 0;
595
        }
596
        else
597
        {
598
          /*
599
            We are comparing two different const.  In this case we can't
600
            use a key-lookup on this so it's better to remove the value
601
            and let the range optimzier handle it
1 by brian
clean slate
602
          */
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
603
          if (old == --first_free)		// If last item
604
            break;
605
          *old= *first_free;			// Remove old value
606
          old--;				// Retry this value
607
        }
1 by brian
clean slate
608
      }
609
    }
610
  }
611
  /* Remove all not used items */
612
  for (KEY_FIELD *old=start ; old != first_free ;)
613
  {
614
    if (old->level != and_level)
615
    {						// Not used in all levels
616
      if (old == --first_free)
617
	break;
618
      *old= *first_free;			// Remove old value
619
      continue;
620
    }
621
    old++;
622
  }
623
  return first_free;
624
}
625
626
/**
627
  Add a possible key to array of possible keys if it's usable as a key
628
629
    @param key_fields      Pointer to add key, if usable
630
    @param and_level       And level, to be stored in KEY_FIELD
631
    @param cond            Condition predicate
632
    @param field           Field used in comparision
633
    @param eq_func         True if we used =, <=> or IS NULL
634
    @param value           Value used for comparison with field
635
    @param usable_tables   Tables which can be used for key optimization
636
    @param sargables       IN/OUT Array of found sargable candidates
637
638
  @note
639
    If we are doing a NOT NULL comparison on a NOT NULL field in a outer join
640
    table, we store this to be able to do not exists optimization later.
641
642
  @returns
643
    *key_fields is incremented if we stored a key in the array
644
*/
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
645
static void add_key_field(KEY_FIELD **key_fields,
646
                          uint32_t and_level,
647
                          Item_func *cond,
648
                          Field *field,
649
                          bool eq_func,
650
                          Item **value,
651
                          uint32_t num_values,
652
                          table_map usable_tables,
653
                          SARGABLE_PARAM **sargables)
1 by brian
clean slate
654
{
482 by Brian Aker
Remove uint.
655
  uint32_t exists_optimize= 0;
1 by brian
clean slate
656
  if (!(field->flags & PART_KEY_FLAG))
657
  {
658
    // Don't remove column IS NULL on a LEFT JOIN table
659
    if (!eq_func || (*value)->type() != Item::NULL_ITEM ||
660
        !field->table->maybe_null || field->null_ptr)
661
      return;					// Not a key. Skip it
662
    exists_optimize= KEY_OPTIMIZE_EXISTS;
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
663
    assert(num_values == 1);
1 by brian
clean slate
664
  }
665
  else
666
  {
667
    table_map used_tables=0;
668
    bool optimizable=0;
482 by Brian Aker
Remove uint.
669
    for (uint32_t i=0; i<num_values; i++)
1 by brian
clean slate
670
    {
671
      used_tables|=(value[i])->used_tables();
672
      if (!((value[i])->used_tables() & (field->table->map | RAND_TABLE_BIT)))
673
        optimizable=1;
674
    }
675
    if (!optimizable)
676
      return;
677
    if (!(usable_tables & field->table->map))
678
    {
679
      if (!eq_func || (*value)->type() != Item::NULL_ITEM ||
680
          !field->table->maybe_null || field->null_ptr)
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
681
        return;					// Can't use left join optimize
1 by brian
clean slate
682
      exists_optimize= KEY_OPTIMIZE_EXISTS;
683
    }
684
    else
685
    {
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
686
      JoinTable *stat=field->table->reginfo.join_tab;
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
687
      key_map possible_keys= field->key_start;
688
      possible_keys&= field->table->keys_in_use_for_query;
689
      stat[0].keys|= possible_keys;             // Add possible keys
1 by brian
clean slate
690
691
      /*
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
692
        Save the following cases:
693
        Field op constant
694
        Field LIKE constant where constant doesn't start with a wildcard
695
        Field = field2 where field2 is in a different table
696
        Field op formula
697
        Field IS NULL
698
        Field IS NOT NULL
699
        Field BETWEEN ...
700
        Field IN ...
1 by brian
clean slate
701
      */
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
702
      stat[0].key_dependent|= used_tables;
1 by brian
clean slate
703
704
      bool is_const=1;
482 by Brian Aker
Remove uint.
705
      for (uint32_t i=0; i<num_values; i++)
1 by brian
clean slate
706
      {
707
        if (!(is_const&= value[i]->const_item()))
708
          break;
709
      }
710
      if (is_const)
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
711
        stat[0].const_keys|= possible_keys;
1 by brian
clean slate
712
      else if (!eq_func)
713
      {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
714
        /*
715
          Save info to be able check whether this predicate can be
1 by brian
clean slate
716
          considered as sargable for range analisis after reading const tables.
717
          We do not save info about equalities as update_const_equal_items
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
718
          will take care of updating info on keys from sargable equalities.
1 by brian
clean slate
719
        */
720
        (*sargables)--;
721
        (*sargables)->field= field;
722
        (*sargables)->arg_value= value;
723
        (*sargables)->num_values= num_values;
724
      }
725
      /*
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
726
        We can't always use indexes when comparing a string index to a
727
        number. cmp_type() is checked to allow compare of dates to numbers.
1 by brian
clean slate
728
        eq_func is NEVER true when num_values > 1
729
       */
730
      if (!eq_func)
731
      {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
732
        /*
1 by brian
clean slate
733
          Additional optimization: if we're processing
734
          "t.key BETWEEN c1 AND c1" then proceed as if we were processing
735
          "t.key = c1".
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
736
          TODO: This is a very limited fix. A more generic fix is possible.
1 by brian
clean slate
737
          There are 2 options:
738
          A) Make equality propagation code be able to handle BETWEEN
739
             (including cases like t1.key BETWEEN t2.key AND t3.key)
740
          B) Make range optimizer to infer additional "t.key = c" equalities
741
             and use them in equality propagation process (see details in
742
             OptimizerKBAndTodo)
743
        */
744
        if ((cond->functype() != Item_func::BETWEEN) ||
745
            ((Item_func_between*) cond)->negated ||
746
            !value[0]->eq(value[1], field->binary()))
747
          return;
55 by brian
Update for using real bool types.
748
        eq_func= true;
1 by brian
clean slate
749
      }
750
751
      if (field->result_type() == STRING_RESULT)
752
      {
753
        if ((*value)->result_type() != STRING_RESULT)
754
        {
755
          if (field->cmp_type() != (*value)->result_type())
756
            return;
757
        }
758
        else
759
        {
760
          /*
761
            We can't use indexes if the effective collation
762
            of the operation differ from the field collation.
763
          */
764
          if (field->cmp_type() == STRING_RESULT &&
765
              ((Field_str*)field)->charset() != cond->compare_collation())
766
            return;
767
        }
768
      }
769
    }
770
  }
771
  /*
772
    For the moment eq_func is always true. This slot is reserved for future
773
    extensions where we want to remembers other things than just eq comparisons
774
  */
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
775
  assert(eq_func);
1 by brian
clean slate
776
  /* Store possible eq field */
777
  (*key_fields)->field=		field;
778
  (*key_fields)->eq_func=	eq_func;
779
  (*key_fields)->val=		*value;
780
  (*key_fields)->level=		and_level;
781
  (*key_fields)->optimize=	exists_optimize;
782
  /*
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
783
    If the condition has form "tbl.keypart = othertbl.field" and
784
    othertbl.field can be NULL, there will be no matches if othertbl.field
1 by brian
clean slate
785
    has NULL value.
786
    We use null_rejecting in add_not_null_conds() to add
787
    'othertbl.field IS NOT NULL' to tab->select_cond.
788
  */
789
  (*key_fields)->null_rejecting= ((cond->functype() == Item_func::EQ_FUNC ||
790
                                   cond->functype() == Item_func::MULT_EQUAL_FUNC) &&
791
                                  ((*value)->type() == Item::FIELD_ITEM) &&
792
                                  ((Item_field*)*value)->field->maybe_null());
793
  (*key_fields)->cond_guard= NULL;
794
  (*key_fields)++;
795
}
796
797
/**
798
  Add possible keys to array of possible keys originated from a simple
799
  predicate.
800
801
    @param  key_fields     Pointer to add key, if usable
802
    @param  and_level      And level, to be stored in KEY_FIELD
803
    @param  cond           Condition predicate
804
    @param  field          Field used in comparision
805
    @param  eq_func        True if we used =, <=> or IS NULL
806
    @param  value          Value used for comparison with field
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
807
                           Is NULL for BETWEEN and IN
1 by brian
clean slate
808
    @param  usable_tables  Tables which can be used for key optimization
809
    @param  sargables      IN/OUT Array of found sargable candidates
810
811
  @note
812
    If field items f1 and f2 belong to the same multiple equality and
813
    a key is added for f1, the the same key is added for f2.
814
815
  @returns
816
    *key_fields is incremented if we stored a key in the array
817
*/
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
818
static void add_key_equal_fields(KEY_FIELD **key_fields,
819
                                 uint32_t and_level,
820
                                 Item_func *cond,
821
                                 Item_field *field_item,
822
                                 bool eq_func,
823
                                 Item **val,
824
                                 uint32_t num_values,
825
                                 table_map usable_tables,
826
                                 SARGABLE_PARAM **sargables)
1 by brian
clean slate
827
{
828
  Field *field= field_item->field;
829
  add_key_field(key_fields, and_level, cond, field,
830
                eq_func, val, num_values, usable_tables, sargables);
831
  Item_equal *item_equal= field_item->item_equal;
832
  if (item_equal)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
833
  {
1 by brian
clean slate
834
    /*
835
      Add to the set of possible key values every substitution of
836
      the field for an equal field included into item_equal
837
    */
838
    Item_equal_iterator it(*item_equal);
839
    Item_field *item;
840
    while ((item= it++))
841
    {
842
      if (!field->eq(item->field))
843
      {
844
        add_key_field(key_fields, and_level, cond, item->field,
845
                      eq_func, val, num_values, usable_tables,
846
                      sargables);
847
      }
848
    }
849
  }
850
}
851
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
852
static void add_key_fields(JOIN *join, 
853
                           KEY_FIELD **key_fields,
854
                           uint32_t *and_level,
855
                           COND *cond,
856
                           table_map usable_tables,
857
                           SARGABLE_PARAM **sargables)
1 by brian
clean slate
858
{
859
  if (cond->type() == Item_func::COND_ITEM)
860
  {
861
    List_iterator_fast<Item> li(*((Item_cond*) cond)->argument_list());
862
    KEY_FIELD *org_key_fields= *key_fields;
863
864
    if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
865
    {
866
      Item *item;
867
      while ((item=li++))
868
        add_key_fields(join, key_fields, and_level, item, usable_tables,
869
                       sargables);
870
      for (; org_key_fields != *key_fields ; org_key_fields++)
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
871
        org_key_fields->level= *and_level;
1 by brian
clean slate
872
    }
873
    else
874
    {
875
      (*and_level)++;
876
      add_key_fields(join, key_fields, and_level, li++, usable_tables,
877
                     sargables);
878
      Item *item;
879
      while ((item=li++))
880
      {
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
881
        KEY_FIELD *start_key_fields= *key_fields;
882
        (*and_level)++;
883
              add_key_fields(join, key_fields, and_level, item, usable_tables,
884
                            sargables);
885
        *key_fields=merge_key_fields(org_key_fields,start_key_fields,
886
                  *key_fields,++(*and_level));
1 by brian
clean slate
887
      }
888
    }
889
    return;
890
  }
891
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
892
  /*
1 by brian
clean slate
893
    Subquery optimization: Conditions that are pushed down into subqueries
894
    are wrapped into Item_func_trig_cond. We process the wrapped condition
1089.1.8 by Brian Aker
Shuffled around a few structures.
895
    but need to set cond_guard for KeyUse elements generated from it.
1 by brian
clean slate
896
  */
897
  {
898
    if (cond->type() == Item::FUNC_ITEM &&
899
        ((Item_func*)cond)->functype() == Item_func::TRIG_COND_FUNC)
900
    {
901
      Item *cond_arg= ((Item_func*)cond)->arguments()[0];
902
      if (!join->group_list && !join->order &&
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
903
          join->unit->item &&
1 by brian
clean slate
904
          join->unit->item->substype() == Item_subselect::IN_SUBS &&
905
          !join->unit->is_union())
906
      {
907
        KEY_FIELD *save= *key_fields;
908
        add_key_fields(join, key_fields, and_level, cond_arg, usable_tables,
909
                       sargables);
910
        // Indicate that this ref access candidate is for subquery lookup:
911
        for (; save != *key_fields; save++)
912
          save->cond_guard= ((Item_func_trig_cond*)cond)->get_trig_var();
913
      }
914
      return;
915
    }
916
  }
917
918
  /* If item is of type 'field op field/constant' add it to key_fields */
919
  if (cond->type() != Item::FUNC_ITEM)
920
    return;
921
  Item_func *cond_func= (Item_func*) cond;
922
  switch (cond_func->select_optimize()) {
923
  case Item_func::OPTIMIZE_NONE:
924
    break;
925
  case Item_func::OPTIMIZE_KEY:
926
  {
927
    Item **values;
928
    // BETWEEN, IN, NE
929
    if (cond_func->key_item()->real_item()->type() == Item::FIELD_ITEM &&
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
930
        !(cond_func->used_tables() & OUTER_REF_TABLE_BIT))
1 by brian
clean slate
931
    {
932
      values= cond_func->arguments()+1;
933
      if (cond_func->functype() == Item_func::NE_FUNC &&
934
        cond_func->arguments()[1]->real_item()->type() == Item::FIELD_ITEM &&
935
	     !(cond_func->arguments()[0]->used_tables() & OUTER_REF_TABLE_BIT))
936
        values--;
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
937
      assert(cond_func->functype() != Item_func::IN_FUNC ||
1 by brian
clean slate
938
                  cond_func->argument_count() != 2);
939
      add_key_equal_fields(key_fields, *and_level, cond_func,
940
                           (Item_field*) (cond_func->key_item()->real_item()),
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
941
                           0, values,
1 by brian
clean slate
942
                           cond_func->argument_count()-1,
943
                           usable_tables, sargables);
944
    }
945
    if (cond_func->functype() == Item_func::BETWEEN)
946
    {
947
      values= cond_func->arguments();
482 by Brian Aker
Remove uint.
948
      for (uint32_t i= 1 ; i < cond_func->argument_count() ; i++)
1 by brian
clean slate
949
      {
950
        Item_field *field_item;
951
        if (cond_func->arguments()[i]->real_item()->type() == Item::FIELD_ITEM
952
            &&
953
            !(cond_func->arguments()[i]->used_tables() & OUTER_REF_TABLE_BIT))
954
        {
955
          field_item= (Item_field *) (cond_func->arguments()[i]->real_item());
956
          add_key_equal_fields(key_fields, *and_level, cond_func,
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
957
                               field_item, 0, values, 1, usable_tables,
1 by brian
clean slate
958
                               sargables);
959
        }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
960
      }
1 by brian
clean slate
961
    }
962
    break;
963
  }
964
  case Item_func::OPTIMIZE_OP:
965
  {
966
    bool equal_func=(cond_func->functype() == Item_func::EQ_FUNC ||
967
		     cond_func->functype() == Item_func::EQUAL_FUNC);
968
969
    if (cond_func->arguments()[0]->real_item()->type() == Item::FIELD_ITEM &&
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
970
        !(cond_func->arguments()[0]->used_tables() & OUTER_REF_TABLE_BIT))
1 by brian
clean slate
971
    {
972
      add_key_equal_fields(key_fields, *and_level, cond_func,
973
	                (Item_field*) (cond_func->arguments()[0])->real_item(),
974
		           equal_func,
975
                           cond_func->arguments()+1, 1, usable_tables,
976
                           sargables);
977
    }
978
    if (cond_func->arguments()[1]->real_item()->type() == Item::FIELD_ITEM &&
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
979
        cond_func->functype() != Item_func::LIKE_FUNC &&
980
        !(cond_func->arguments()[1]->used_tables() & OUTER_REF_TABLE_BIT))
1 by brian
clean slate
981
    {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
982
      add_key_equal_fields(key_fields, *and_level, cond_func,
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
983
                       (Item_field*) (cond_func->arguments()[1])->real_item(), equal_func,
1 by brian
clean slate
984
                           cond_func->arguments(),1,usable_tables,
985
                           sargables);
986
    }
987
    break;
988
  }
989
  case Item_func::OPTIMIZE_NULL:
990
    /* column_name IS [NOT] NULL */
991
    if (cond_func->arguments()[0]->real_item()->type() == Item::FIELD_ITEM &&
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
992
        !(cond_func->used_tables() & OUTER_REF_TABLE_BIT))
1 by brian
clean slate
993
    {
994
      Item *tmp=new Item_null;
995
      if (unlikely(!tmp))                       // Should never be true
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
996
        return;
1 by brian
clean slate
997
      add_key_equal_fields(key_fields, *and_level, cond_func,
998
		    (Item_field*) (cond_func->arguments()[0])->real_item(),
999
		    cond_func->functype() == Item_func::ISNULL_FUNC,
1000
			   &tmp, 1, usable_tables, sargables);
1001
    }
1002
    break;
1003
  case Item_func::OPTIMIZE_EQUAL:
1004
    Item_equal *item_equal= (Item_equal *) cond;
1005
    Item *const_item= item_equal->get_const();
1006
    Item_equal_iterator it(*item_equal);
1007
    Item_field *item;
1008
    if (const_item)
1009
    {
1010
      /*
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1011
        For each field field1 from item_equal consider the equality
1 by brian
clean slate
1012
        field1=const_item as a condition allowing an index access of the table
1013
        with field1 by the keys value of field1.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1014
      */
1 by brian
clean slate
1015
      while ((item= it++))
1016
      {
1017
        add_key_field(key_fields, *and_level, cond_func, item->field,
55 by brian
Update for using real bool types.
1018
                      true, &const_item, 1, usable_tables, sargables);
1 by brian
clean slate
1019
      }
1020
    }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1021
    else
1 by brian
clean slate
1022
    {
1023
      /*
1024
        Consider all pairs of different fields included into item_equal.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1025
        For each of them (field1, field1) consider the equality
1 by brian
clean slate
1026
        field1=field2 as a condition allowing an index access of the table
1027
        with field1 by the keys value of field2.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1028
      */
1 by brian
clean slate
1029
      Item_equal_iterator fi(*item_equal);
1030
      while ((item= fi++))
1031
      {
1032
        Field *field= item->field;
1033
        while ((item= it++))
1034
        {
1035
          if (!field->eq(item->field))
1036
          {
1037
            add_key_field(key_fields, *and_level, cond_func, field,
55 by brian
Update for using real bool types.
1038
                          true, (Item **) &item, 1, usable_tables,
1 by brian
clean slate
1039
                          sargables);
1040
          }
1041
        }
1042
        it.rewind();
1043
      }
1044
    }
1045
    break;
1046
  }
1047
}
1048
1049
/**
1050
  Add all keys with uses 'field' for some keypart.
1051
1052
  If field->and_level != and_level then only mark key_part as const_part.
1053
*/
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
1054
uint32_t max_part_bit(key_part_map bits)
1 by brian
clean slate
1055
{
482 by Brian Aker
Remove uint.
1056
  uint32_t found;
1 by brian
clean slate
1057
  for (found=0; bits & 1 ; found++,bits>>=1) ;
1058
  return found;
1059
}
1060
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
1061
static void add_key_part(DYNAMIC_ARRAY *keyuse_array,KEY_FIELD *key_field)
1 by brian
clean slate
1062
{
1063
  Field *field=key_field->field;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1064
  Table *form= field->table;
1089.1.8 by Brian Aker
Shuffled around a few structures.
1065
  KeyUse keyuse;
1 by brian
clean slate
1066
1067
  if (key_field->eq_func && !(key_field->optimize & KEY_OPTIMIZE_EXISTS))
1068
  {
482 by Brian Aker
Remove uint.
1069
    for (uint32_t key= 0 ; key < form->sizeKeys() ; key++)
1 by brian
clean slate
1070
    {
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
1071
      if (!(form->keys_in_use_for_query.test(key)))
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
1072
        continue;
1 by brian
clean slate
1073
895 by Brian Aker
Completion (?) of uint conversion.
1074
      uint32_t key_parts= (uint32_t) form->key_info[key].key_parts;
482 by Brian Aker
Remove uint.
1075
      for (uint32_t part=0 ; part <  key_parts ; part++)
1 by brian
clean slate
1076
      {
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
1077
        if (field->eq(form->key_info[key].key_part[part].field))
1078
        {
1079
          keyuse.table= field->table;
1080
          keyuse.val =  key_field->val;
1081
          keyuse.key =  key;
1082
          keyuse.keypart=part;
1083
          keyuse.keypart_map= (key_part_map) 1 << part;
1084
          keyuse.used_tables=key_field->val->used_tables();
1085
          keyuse.optimize= key_field->optimize & KEY_OPTIMIZE_REF_OR_NULL;
1103.1.4 by Brian Aker
A couple of stray SJ parts.
1086
          keyuse.null_rejecting= key_field->null_rejecting;
1087
          keyuse.cond_guard= key_field->cond_guard;
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
1088
          insert_dynamic(keyuse_array,(unsigned char*) &keyuse);
1089
        }
1 by brian
clean slate
1090
      }
1091
    }
1092
  }
1093
}
1094
1089.1.8 by Brian Aker
Shuffled around a few structures.
1095
static int sort_keyuse(KeyUse *a,KeyUse *b)
1 by brian
clean slate
1096
{
1097
  int res;
1098
  if (a->table->tablenr != b->table->tablenr)
1099
    return (int) (a->table->tablenr - b->table->tablenr);
1100
  if (a->key != b->key)
1101
    return (int) (a->key - b->key);
1102
  if (a->keypart != b->keypart)
1103
    return (int) (a->keypart - b->keypart);
1104
  // Place const values before other ones
1105
  if ((res= test((a->used_tables & ~OUTER_REF_TABLE_BIT)) -
1106
       test((b->used_tables & ~OUTER_REF_TABLE_BIT))))
1107
    return res;
1108
  /* Place rows that are not 'OPTIMIZE_REF_OR_NULL' first */
1109
  return (int) ((a->optimize & KEY_OPTIMIZE_REF_OR_NULL) -
1110
		(b->optimize & KEY_OPTIMIZE_REF_OR_NULL));
1111
}
1112
1113
/*
1114
  Add to KEY_FIELD array all 'ref' access candidates within nested join.
1115
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1116
    This function populates KEY_FIELD array with entries generated from the
1117
    ON condition of the given nested join, and does the same for nested joins
1 by brian
clean slate
1118
    contained within this nested join.
1119
1120
  @param[in]      nested_join_table   Nested join pseudo-table to process
1121
  @param[in,out]  end                 End of the key field array
1122
  @param[in,out]  and_level           And-level
1123
  @param[in,out]  sargables           Array of found sargable candidates
1124
1125
1126
  @note
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1127
    We can add accesses to the tables that are direct children of this nested
1 by brian
clean slate
1128
    join (1), and are not inner tables w.r.t their neighbours (2).
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1129
1130
    Example for #1 (outer brackets pair denotes nested join this function is
1 by brian
clean slate
1131
    invoked for):
1132
    @code
1133
     ... LEFT JOIN (t1 LEFT JOIN (t2 ... ) ) ON cond
1134
    @endcode
1135
    Example for #2:
1136
    @code
1137
     ... LEFT JOIN (t1 LEFT JOIN t2 ) ON cond
1138
    @endcode
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1139
    In examples 1-2 for condition cond, we can add 'ref' access candidates to
1 by brian
clean slate
1140
    t1 only.
1141
    Example #3:
1142
    @code
1143
     ... LEFT JOIN (t1, t2 LEFT JOIN t3 ON inner_cond) ON cond
1144
    @endcode
1145
    Here we can add 'ref' access candidates for t1 and t2, but not for t3.
1146
*/
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
1147
static void add_key_fields_for_nj(JOIN *join,
1148
                                  TableList *nested_join_table,
1149
                                  KEY_FIELD **end,
1150
                                  uint32_t *and_level,
1 by brian
clean slate
1151
                                  SARGABLE_PARAM **sargables)
1152
{
327.2.4 by Brian Aker
Refactoring table.h
1153
  List_iterator<TableList> li(nested_join_table->nested_join->join_list);
1154
  List_iterator<TableList> li2(nested_join_table->nested_join->join_list);
55 by brian
Update for using real bool types.
1155
  bool have_another = false;
1 by brian
clean slate
1156
  table_map tables= 0;
327.2.4 by Brian Aker
Refactoring table.h
1157
  TableList *table;
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
1158
  assert(nested_join_table->nested_join);
1 by brian
clean slate
1159
55 by brian
Update for using real bool types.
1160
  while ((table= li++) || (have_another && (li=li2, have_another=false,
1 by brian
clean slate
1161
                                            (table= li++))))
1162
  {
1163
    if (table->nested_join)
1164
    {
1165
      if (!table->on_expr)
1166
      {
1167
        /* It's a semi-join nest. Walk into it as if it wasn't a nest */
55 by brian
Update for using real bool types.
1168
        have_another= true;
1 by brian
clean slate
1169
        li2= li;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1170
        li= List_iterator<TableList>(table->nested_join->join_list);
1 by brian
clean slate
1171
      }
1172
      else
1173
        add_key_fields_for_nj(join, table, end, and_level, sargables);
1174
    }
1175
    else
1176
      if (!table->on_expr)
1177
        tables |= table->table->map;
1178
  }
1179
  if (nested_join_table->on_expr)
1180
    add_key_fields(join, end, and_level, nested_join_table->on_expr, tables,
1181
                   sargables);
1182
}
1183
1184
/**
1185
  Update keyuse array with all possible keys we can use to fetch rows.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1186
1187
  @param       session
1089.1.8 by Brian Aker
Shuffled around a few structures.
1188
  @param[out]  keyuse         Put here ordered array of KeyUse structures
1 by brian
clean slate
1189
  @param       join_tab       Array in tablenr_order
1190
  @param       tables         Number of tables in join
1191
  @param       cond           WHERE condition (note that the function analyzes
1192
                              join_tab[i]->on_expr too)
1193
  @param       normal_tables  Tables not inner w.r.t some outer join (ones
1194
                              for which we can make ref access based the WHERE
1195
                              clause)
1196
  @param       select_lex     current SELECT
1197
  @param[out]  sargables      Array of found sargable candidates
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1198
1 by brian
clean slate
1199
   @retval
1200
     0  OK
1201
   @retval
1202
     1  Out of memory.
1203
*/
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
1204
bool update_ref_and_keys(Session *session,
1205
                         DYNAMIC_ARRAY *keyuse,
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
1206
                         JoinTable *join_tab,
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
1207
                         uint32_t tables,
1208
                         COND *cond, 
1209
                         COND_EQUAL *,
1210
                         table_map normal_tables,
1211
                         Select_Lex *select_lex,
1212
                         SARGABLE_PARAM **sargables)
1 by brian
clean slate
1213
{
1214
  uint	and_level,i,found_eq_constant;
1215
  KEY_FIELD *key_fields, *end, *field;
482 by Brian Aker
Remove uint.
1216
  uint32_t sz;
1067.4.7 by Nathan Williams
The remaining files using cmax have been converted to std::max.
1217
  uint32_t m= max(select_lex->max_equal_elems,(uint32_t)1);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1218
1219
  /*
1220
    We use the same piece of memory to store both  KEY_FIELD
1 by brian
clean slate
1221
    and SARGABLE_PARAM structure.
1222
    KEY_FIELD values are placed at the beginning this memory
1223
    while  SARGABLE_PARAM values are put at the end.
1224
    All predicates that are used to fill arrays of KEY_FIELD
1225
    and SARGABLE_PARAM structures have at most 2 arguments
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1226
    except BETWEEN predicates that have 3 arguments and
1 by brian
clean slate
1227
    IN predicates.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1228
    This any predicate if it's not BETWEEN/IN can be used
1 by brian
clean slate
1229
    directly to fill at most 2 array elements, either of KEY_FIELD
1230
    or SARGABLE_PARAM type. For a BETWEEN predicate 3 elements
1231
    can be filled as this predicate is considered as
1232
    saragable with respect to each of its argument.
1233
    An IN predicate can require at most 1 element as currently
1234
    it is considered as sargable only for its first argument.
1235
    Multiple equality can add  elements that are filled after
1236
    substitution of field arguments by equal fields. There
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1237
    can be not more than select_lex->max_equal_elems such
1 by brian
clean slate
1238
    substitutions.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1239
  */
1067.4.7 by Nathan Williams
The remaining files using cmax have been converted to std::max.
1240
  sz= max(sizeof(KEY_FIELD),sizeof(SARGABLE_PARAM))*
520.1.22 by Brian Aker
Second pass of thd cleanup
1241
      (((session->lex->current_select->cond_count+1)*2 +
1242
	session->lex->current_select->between_count)*m+1);
1243
  if (!(key_fields=(KEY_FIELD*)	session->alloc(sz)))
55 by brian
Update for using real bool types.
1244
    return true; /* purecov: inspected */
1 by brian
clean slate
1245
  and_level= 0;
1246
  field= end= key_fields;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1247
  *sargables= (SARGABLE_PARAM *) key_fields +
1 by brian
clean slate
1248
                (sz - sizeof((*sargables)[0].field))/sizeof(SARGABLE_PARAM);
1249
  /* set a barrier for the array of SARGABLE_PARAM */
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1250
  (*sargables)[0].field= 0;
1 by brian
clean slate
1251
1089.1.8 by Brian Aker
Shuffled around a few structures.
1252
  if (my_init_dynamic_array(keyuse,sizeof(KeyUse),20,64))
55 by brian
Update for using real bool types.
1253
    return true;
1 by brian
clean slate
1254
  if (cond)
1255
  {
1256
    add_key_fields(join_tab->join, &end, &and_level, cond, normal_tables,
1257
                   sargables);
1258
    for (; field != end ; field++)
1259
    {
1260
      add_key_part(keyuse,field);
1261
      /* Mark that we can optimize LEFT JOIN */
1262
      if (field->val->type() == Item::NULL_ITEM &&
1263
	  !field->field->real_maybe_null())
1264
	field->field->table->reginfo.not_exists_optimize=1;
1265
    }
1266
  }
1267
  for (i=0 ; i < tables ; i++)
1268
  {
1269
    /*
1270
      Block the creation of keys for inner tables of outer joins.
1271
      Here only the outer joins that can not be converted to
1272
      inner joins are left and all nests that can be eliminated
1273
      are flattened.
1274
      In the future when we introduce conditional accesses
1275
      for inner tables in outer joins these keys will be taken
1276
      into account as well.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1277
    */
1 by brian
clean slate
1278
    if (*join_tab[i].on_expr_ref)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1279
      add_key_fields(join_tab->join, &end, &and_level,
1 by brian
clean slate
1280
                     *join_tab[i].on_expr_ref,
1281
                     join_tab[i].table->map, sargables);
1282
  }
1283
1284
  /* Process ON conditions for the nested joins */
1285
  {
327.2.4 by Brian Aker
Refactoring table.h
1286
    List_iterator<TableList> li(*join_tab->join->join_list);
1287
    TableList *table;
1 by brian
clean slate
1288
    while ((table= li++))
1289
    {
1290
      if (table->nested_join)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1291
        add_key_fields_for_nj(join_tab->join, table, &end, &and_level,
1 by brian
clean slate
1292
                              sargables);
1293
    }
1294
  }
1295
1296
  /* fill keyuse with found key parts */
1297
  for ( ; field != end ; field++)
1298
    add_key_part(keyuse,field);
1299
1300
  /*
1301
    Sort the array of possible keys and remove the following key parts:
1302
    - ref if there is a keypart which is a ref and a const.
1303
      (e.g. if there is a key(a,b) and the clause is a=3 and b=7 and b=t2.d,
1304
      then we skip the key part corresponding to b=t2.d)
1305
    - keyparts without previous keyparts
1306
      (e.g. if there is a key(a,b,c) but only b < 5 (or a=2 and c < 3) is
1307
      used in the query, we drop the partial key parts from consideration).
1308
  */
1309
  if (keyuse->elements)
1310
  {
1089.1.8 by Brian Aker
Shuffled around a few structures.
1311
    KeyUse key_end,*prev,*save_pos,*use;
1 by brian
clean slate
1312
1089.1.8 by Brian Aker
Shuffled around a few structures.
1313
    my_qsort(keyuse->buffer,keyuse->elements,sizeof(KeyUse),
1 by brian
clean slate
1314
	  (qsort_cmp) sort_keyuse);
1315
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
1316
    memset(&key_end, 0, sizeof(key_end)); /* Add for easy testing */
481 by Brian Aker
Remove all of uchar.
1317
    insert_dynamic(keyuse,(unsigned char*) &key_end);
1 by brian
clean slate
1318
1089.1.8 by Brian Aker
Shuffled around a few structures.
1319
    use=save_pos=dynamic_element(keyuse,0,KeyUse*);
1 by brian
clean slate
1320
    prev= &key_end;
1321
    found_eq_constant=0;
1322
    for (i=0 ; i < keyuse->elements-1 ; i++,use++)
1323
    {
1324
      if (!use->used_tables && use->optimize != KEY_OPTIMIZE_REF_OR_NULL)
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
1325
        use->table->const_key_parts[use->key]|= use->keypart_map;
1326
      if (use->key == prev->key && use->table == prev->table)
1 by brian
clean slate
1327
      {
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
1328
        if (prev->keypart+1 < use->keypart || ((prev->keypart == use->keypart) && found_eq_constant))
1329
          continue;				/* remove */
1 by brian
clean slate
1330
      }
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
1331
      else if (use->keypart != 0)		// First found must be 0
1332
        continue;
1 by brian
clean slate
1333
1334
#ifdef HAVE_purify
1335
      /* Valgrind complains about overlapped memcpy when save_pos==use. */
1336
      if (save_pos != use)
1337
#endif
1338
        *save_pos= *use;
1339
      prev=use;
1340
      found_eq_constant= !use->used_tables;
1341
      /* Save ptr to first use */
1342
      if (!use->table->reginfo.join_tab->keyuse)
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
1343
        use->table->reginfo.join_tab->keyuse=save_pos;
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
1344
      use->table->reginfo.join_tab->checked_keys.set(use->key);
1 by brian
clean slate
1345
      save_pos++;
1346
    }
1089.1.8 by Brian Aker
Shuffled around a few structures.
1347
    i=(uint32_t) (save_pos-(KeyUse*) keyuse->buffer);
481 by Brian Aker
Remove all of uchar.
1348
    set_dynamic(keyuse,(unsigned char*) &key_end,i);
982.1.11 by Padraig O'Sullivan
Reverted my changes for replacing Bitmap<> for the moment. Going to fix up
1349
    keyuse->elements=i;
1 by brian
clean slate
1350
  }
55 by brian
Update for using real bool types.
1351
  return false;
1 by brian
clean slate
1352
}
1353
1354
/**
1355
  Update some values in keyuse for faster choose_plan() loop.
1356
*/
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
1357
void optimize_keyuse(JOIN *join, DYNAMIC_ARRAY *keyuse_array)
1 by brian
clean slate
1358
{
1089.1.8 by Brian Aker
Shuffled around a few structures.
1359
  KeyUse *end,*keyuse= dynamic_element(keyuse_array, 0, KeyUse*);
1 by brian
clean slate
1360
1361
  for (end= keyuse+ keyuse_array->elements ; keyuse < end ; keyuse++)
1362
  {
1363
    table_map map;
1364
    /*
1365
      If we find a ref, assume this table matches a proportional
1366
      part of this table.
1367
      For example 100 records matching a table with 5000 records
1368
      gives 5000/100 = 50 records per key
1369
      Constant tables are ignored.
1370
      To avoid bad matches, we don't make ref_table_rows less than 100.
1371
    */
1372
    keyuse->ref_table_rows= ~(ha_rows) 0;	// If no ref
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
1373
    if (keyuse->used_tables & (map= (keyuse->used_tables & ~join->const_table_map & ~OUTER_REF_TABLE_BIT)))
1 by brian
clean slate
1374
    {
482 by Brian Aker
Remove uint.
1375
      uint32_t tablenr;
1 by brian
clean slate
1376
      for (tablenr=0 ; ! (map & 1) ; map>>=1, tablenr++) ;
1377
      if (map == 1)			// Only one table
1378
      {
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
1379
        Table *tmp_table=join->all_tables[tablenr];
1067.4.7 by Nathan Williams
The remaining files using cmax have been converted to std::max.
1380
        keyuse->ref_table_rows= max(tmp_table->file->stats.records, (ha_rows)100);
1 by brian
clean slate
1381
      }
1382
    }
1383
    /*
1384
      Outer reference (external field) is constant for single executing
1385
      of subquery
1386
    */
1387
    if (keyuse->used_tables == OUTER_REF_TABLE_BIT)
1388
      keyuse->ref_table_rows= 1;
1389
  }
1390
}
1391
1392
1393
/**
1394
  Discover the indexes that can be used for GROUP BY or DISTINCT queries.
1395
1396
  If the query has a GROUP BY clause, find all indexes that contain all
1397
  GROUP BY fields, and add those indexes to join->const_keys.
1398
1399
  If the query has a DISTINCT clause, find all indexes that contain all
1400
  SELECT fields, and add those indexes to join->const_keys.
1401
  This allows later on such queries to be processed by a
1402
  QUICK_GROUP_MIN_MAX_SELECT.
1403
1404
  @param join
1405
  @param join_tab
1406
1407
  @return
1408
    None
1409
*/
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
1410
void add_group_and_distinct_keys(JOIN *join, JoinTable *join_tab)
1 by brian
clean slate
1411
{
1412
  List<Item_field> indexed_fields;
1413
  List_iterator<Item_field> indexed_fields_it(indexed_fields);
327.2.3 by Brian Aker
Refactoring of class Table
1414
  order_st      *cur_group;
1 by brian
clean slate
1415
  Item_field *cur_item;
1416
  key_map possible_keys(0);
1417
1418
  if (join->group_list)
1419
  { /* Collect all query fields referenced in the GROUP clause. */
1420
    for (cur_group= join->group_list; cur_group; cur_group= cur_group->next)
1421
      (*cur_group->item)->walk(&Item::collect_item_field_processor, 0,
481 by Brian Aker
Remove all of uchar.
1422
                               (unsigned char*) &indexed_fields);
1 by brian
clean slate
1423
  }
1424
  else if (join->select_distinct)
1425
  { /* Collect all query fields referenced in the SELECT clause. */
1426
    List<Item> &select_items= join->fields_list;
1427
    List_iterator<Item> select_items_it(select_items);
1428
    Item *item;
1429
    while ((item= select_items_it++))
1430
      item->walk(&Item::collect_item_field_processor, 0,
481 by Brian Aker
Remove all of uchar.
1431
                 (unsigned char*) &indexed_fields);
1 by brian
clean slate
1432
  }
1433
  else
1434
    return;
1435
1436
  if (indexed_fields.elements == 0)
1437
    return;
1438
1439
  /* Intersect the keys of all group fields. */
1440
  cur_item= indexed_fields_it++;
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
1441
  possible_keys|= cur_item->field->part_of_key;
1 by brian
clean slate
1442
  while ((cur_item= indexed_fields_it++))
1443
  {
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
1444
    possible_keys&= cur_item->field->part_of_key;
1 by brian
clean slate
1445
  }
1446
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
1447
  if (possible_keys.any())
1448
    join_tab->const_keys|= possible_keys;
1 by brian
clean slate
1449
}
1450
1451
/**
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
1452
  Compare two JoinTable objects based on the number of accessed records.
1 by brian
clean slate
1453
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
1454
  @param ptr1 pointer to first JoinTable object
1455
  @param ptr2 pointer to second JoinTable object
1 by brian
clean slate
1456
1457
  NOTES
1458
    The order relation implemented by join_tab_cmp() is not transitive,
1459
    i.e. it is possible to choose such a, b and c that (a < b) && (b < c)
1460
    but (c < a). This implies that result of a sort using the relation
1461
    implemented by join_tab_cmp() depends on the order in which
1462
    elements are compared, i.e. the result is implementation-specific.
1463
    Example:
1464
      a: dependent = 0x0 table->map = 0x1 found_records = 3 ptr = 0x907e6b0
1465
      b: dependent = 0x0 table->map = 0x2 found_records = 3 ptr = 0x907e838
1466
      c: dependent = 0x6 table->map = 0x10 found_records = 2 ptr = 0x907ecd0
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1467
1 by brian
clean slate
1468
  @retval
1469
    1  if first is bigger
1470
  @retval
1471
    -1  if second is bigger
1472
  @retval
1473
    0  if equal
1474
*/
873.2.34 by Monty Taylor
Fixed a Solaris Warnings.
1475
int join_tab_cmp(const void* ptr1, const void* ptr2)
1 by brian
clean slate
1476
{
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
1477
  JoinTable *jt1= *(JoinTable**) ptr1;
1478
  JoinTable *jt2= *(JoinTable**) ptr2;
1 by brian
clean slate
1479
1480
  if (jt1->dependent & jt2->table->map)
1481
    return 1;
1482
  if (jt2->dependent & jt1->table->map)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1483
    return -1;
1 by brian
clean slate
1484
  if (jt1->found_records > jt2->found_records)
1485
    return 1;
1486
  if (jt1->found_records < jt2->found_records)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1487
    return -1;
1 by brian
clean slate
1488
  return jt1 > jt2 ? 1 : (jt1 < jt2 ? -1 : 0);
1489
}
1490
1491
/**
1492
  Same as join_tab_cmp, but for use with SELECT_STRAIGHT_JOIN.
1493
*/
873.2.34 by Monty Taylor
Fixed a Solaris Warnings.
1494
int join_tab_cmp_straight(const void* ptr1, const void* ptr2)
1 by brian
clean slate
1495
{
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
1496
  JoinTable *jt1= *(JoinTable**) ptr1;
1497
  JoinTable *jt2= *(JoinTable**) ptr2;
1 by brian
clean slate
1498
1499
  if (jt1->dependent & jt2->table->map)
1500
    return 1;
1501
  if (jt2->dependent & jt1->table->map)
1502
    return -1;
1503
  return jt1 > jt2 ? 1 : (jt1 < jt2 ? -1 : 0);
1504
}
1505
1506
/**
1507
  Find how much space the prevous read not const tables takes in cache.
1508
*/
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
1509
void calc_used_field_length(Session *, JoinTable *join_tab)
1 by brian
clean slate
1510
{
482 by Brian Aker
Remove uint.
1511
  uint32_t null_fields,blobs,fields,rec_length;
1 by brian
clean slate
1512
  Field **f_ptr,*field;
1513
1514
  null_fields= blobs= fields= rec_length=0;
1515
  for (f_ptr=join_tab->table->field ; (field= *f_ptr) ; f_ptr++)
1516
  {
1003.1.12 by Brian Aker
Begin of abstract out the bitmap from direct reference.
1517
    if (field->isReadSet())
1 by brian
clean slate
1518
    {
482 by Brian Aker
Remove uint.
1519
      uint32_t flags=field->flags;
1 by brian
clean slate
1520
      fields++;
1521
      rec_length+=field->pack_length();
1522
      if (flags & BLOB_FLAG)
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
1523
        blobs++;
1 by brian
clean slate
1524
      if (!(flags & NOT_NULL_FLAG))
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
1525
        null_fields++;
1 by brian
clean slate
1526
    }
1527
  }
1528
  if (null_fields)
327.1.1 by Brian Aker
First pass in encapsulating table (it is now an object, no longer a structure).
1529
    rec_length+=(join_tab->table->getNullFields() + 7)/8;
1 by brian
clean slate
1530
  if (join_tab->table->maybe_null)
148 by Brian Aker
my_bool cleanup
1531
    rec_length+=sizeof(bool);
1 by brian
clean slate
1532
  if (blobs)
1533
  {
895 by Brian Aker
Completion (?) of uint conversion.
1534
    uint32_t blob_length=(uint32_t) (join_tab->table->file->stats.mean_rec_length-
1067.4.7 by Nathan Williams
The remaining files using cmax have been converted to std::max.
1535
                                     (join_tab->table->getRecordLength()- rec_length));
1536
    rec_length+= max((uint32_t)4,blob_length);
1 by brian
clean slate
1537
  }
1005.2.16 by Monty Taylor
Removed stored_fields
1538
  join_tab->used_fields= fields;
1539
  join_tab->used_fieldlength= rec_length;
1540
  join_tab->used_blobs= blobs;
1 by brian
clean slate
1541
}
1542
1039.2.3 by Jay Pipes
Phase 3 of refactoring JOIN
1543
StoredKey *get_store_key(Session *session,
1089.1.8 by Brian Aker
Shuffled around a few structures.
1544
                         KeyUse *keyuse,
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
1545
                         table_map used_tables,
1546
	                       KEY_PART_INFO *key_part,
1547
                         unsigned char *key_buff,
1548
                         uint32_t maybe_null)
1549
{
1550
  if (!((~used_tables) & keyuse->used_tables))		// if const item
1551
  {
1552
    return new store_key_const_item(session,
1553
				    key_part->field,
1554
				    key_buff + maybe_null,
1555
				    maybe_null ? key_buff : 0,
1556
				    key_part->length,
1557
				    keyuse->val);
1558
  }
1559
  else if (keyuse->val->type() == Item::FIELD_ITEM ||
1560
           (keyuse->val->type() == Item::REF_ITEM &&
1561
            ((Item_ref*)keyuse->val)->ref_type() == Item_ref::OUTER_REF &&
1562
            (*(Item_ref**)((Item_ref*)keyuse->val)->ref)->ref_type() ==
1563
             Item_ref::DIRECT_REF &&
1564
            keyuse->val->real_item()->type() == Item::FIELD_ITEM))
1565
    return new store_key_field(session,
1566
			       key_part->field,
1567
			       key_buff + maybe_null,
1568
			       maybe_null ? key_buff : 0,
1569
			       key_part->length,
1570
			       ((Item_field*) keyuse->val->real_item())->field,
1571
			       keyuse->val->full_name());
1572
  return new store_key_item(session,
1573
			    key_part->field,
1574
			    key_buff + maybe_null,
1575
			    maybe_null ? key_buff : 0,
1576
			    key_part->length,
1577
			    keyuse->val);
1578
}
1 by brian
clean slate
1579
1580
/**
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
1581
  This function is only called for const items on fields which are keys.
1582
1583
  @return
1584
    returns 1 if there was some conversion made when the field was stored.
1 by brian
clean slate
1585
*/
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
1586
bool store_val_in_field(Field *field, Item *item, enum_check_fields check_flag)
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
1587
{
1588
  bool error;
1589
  Table *table= field->table;
1590
  Session *session= table->in_use;
1591
  ha_rows cuted_fields=session->cuted_fields;
1592
1593
  /*
1594
    we should restore old value of count_cuted_fields because
1595
    store_val_in_field can be called from mysql_insert
1596
    with select_insert, which make count_cuted_fields= 1
1597
   */
1598
  enum_check_fields old_count_cuted_fields= session->count_cuted_fields;
1599
  session->count_cuted_fields= check_flag;
1600
  error= item->save_in_field(field, 1);
1601
  session->count_cuted_fields= old_count_cuted_fields;
1602
  return error || cuted_fields != session->cuted_fields;
1603
}
1604
1605
inline void add_cond_and_fix(Item **e1, Item *e2)
1606
{
1607
  if (*e1)
1 by brian
clean slate
1608
  {
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
1609
    Item *res;
1610
    if ((res= new Item_cond_and(*e1, e2)))
1 by brian
clean slate
1611
    {
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
1612
      *e1= res;
1613
      res->quick_fix_field();
1 by brian
clean slate
1614
    }
1615
  }
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
1616
  else
1617
    *e1= e2;
1 by brian
clean slate
1618
}
1619
1089.1.8 by Brian Aker
Shuffled around a few structures.
1620
bool create_ref_for_key(JOIN *join, JoinTable *j, KeyUse *org_keyuse,
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
1621
             table_map used_tables)
1 by brian
clean slate
1622
{
1089.1.8 by Brian Aker
Shuffled around a few structures.
1623
  KeyUse *keyuse=org_keyuse;
520.1.22 by Brian Aker
Second pass of thd cleanup
1624
  Session  *session= join->session;
482 by Brian Aker
Remove uint.
1625
  uint32_t keyparts,length,key;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1626
  Table *table;
1 by brian
clean slate
1627
  KEY *keyinfo;
1628
1629
  /*  Use best key from find_best */
1630
  table=j->table;
1631
  key=keyuse->key;
1632
  keyinfo=table->key_info+key;
1633
1634
  {
1635
    keyparts=length=0;
482 by Brian Aker
Remove uint.
1636
    uint32_t found_part_ref_or_null= 0;
1 by brian
clean slate
1637
    /*
1638
      Calculate length for the used key
1639
      Stop if there is a missing key part or when we find second key_part
1640
      with KEY_OPTIMIZE_REF_OR_NULL
1641
    */
1642
    do
1643
    {
1644
      if (!(~used_tables & keyuse->used_tables))
1645
      {
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
1646
        if (keyparts == keyuse->keypart &&
1647
            !(found_part_ref_or_null & keyuse->optimize))
1648
        {
1649
          keyparts++;
1650
          length+= keyinfo->key_part[keyuse->keypart].store_length;
1651
          found_part_ref_or_null|= keyuse->optimize;
1652
        }
1 by brian
clean slate
1653
      }
1654
      keyuse++;
1655
    } while (keyuse->table == table && keyuse->key == key);
1656
  }
1657
1658
  /* set up fieldref */
1659
  keyinfo=table->key_info+key;
1660
  j->ref.key_parts=keyparts;
1661
  j->ref.key_length=length;
1662
  j->ref.key=(int) key;
520.1.22 by Brian Aker
Second pass of thd cleanup
1663
  if (!(j->ref.key_buff= (unsigned char*) session->calloc(ALIGN_SIZE(length)*2)) ||
1039.2.3 by Jay Pipes
Phase 3 of refactoring JOIN
1664
      !(j->ref.key_copy= (StoredKey**) session->alloc((sizeof(StoredKey*) *
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
1665
               (keyparts+1)))) ||
520.1.22 by Brian Aker
Second pass of thd cleanup
1666
      !(j->ref.items=    (Item**) session->alloc(sizeof(Item*)*keyparts)) ||
1667
      !(j->ref.cond_guards= (bool**) session->alloc(sizeof(uint*)*keyparts)))
1 by brian
clean slate
1668
  {
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
1669
    return(true);
1 by brian
clean slate
1670
  }
1671
  j->ref.key_buff2=j->ref.key_buff+ALIGN_SIZE(length);
1672
  j->ref.key_err=1;
1673
  j->ref.null_rejecting= 0;
55 by brian
Update for using real bool types.
1674
  j->ref.disable_cache= false;
1 by brian
clean slate
1675
  keyuse=org_keyuse;
1676
1039.2.3 by Jay Pipes
Phase 3 of refactoring JOIN
1677
  StoredKey **ref_key= j->ref.key_copy;
481 by Brian Aker
Remove all of uchar.
1678
  unsigned char *key_buff=j->ref.key_buff, *null_ref_key= 0;
55 by brian
Update for using real bool types.
1679
  bool keyuse_uses_no_tables= true;
1 by brian
clean slate
1680
  {
482 by Brian Aker
Remove uint.
1681
    uint32_t i;
1 by brian
clean slate
1682
    for (i=0 ; i < keyparts ; keyuse++,i++)
1683
    {
1684
      while (keyuse->keypart != i ||
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
1685
       ((~used_tables) & keyuse->used_tables))
1686
        keyuse++;       /* Skip other parts */
1 by brian
clean slate
1687
482 by Brian Aker
Remove uint.
1688
      uint32_t maybe_null= test(keyinfo->key_part[i].null_bit);
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
1689
      j->ref.items[i]=keyuse->val;    // Save for cond removal
1 by brian
clean slate
1690
      j->ref.cond_guards[i]= keyuse->cond_guard;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1691
      if (keyuse->null_rejecting)
1 by brian
clean slate
1692
        j->ref.null_rejecting |= 1 << i;
1693
      keyuse_uses_no_tables= keyuse_uses_no_tables && !keyuse->used_tables;
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
1694
      if (!keyuse->used_tables &&  !(join->select_options & SELECT_DESCRIBE))
1695
      {         // Compare against constant
1696
        store_key_item tmp(session, keyinfo->key_part[i].field,
1 by brian
clean slate
1697
                           key_buff + maybe_null,
1698
                           maybe_null ?  key_buff : 0,
1699
                           keyinfo->key_part[i].length, keyuse->val);
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
1700
        if (session->is_fatal_error)
1701
          return(true);
1702
        tmp.copy();
1 by brian
clean slate
1703
      }
1704
      else
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
1705
        *ref_key++= get_store_key(session,
1706
          keyuse,join->const_table_map,
1707
          &keyinfo->key_part[i],
1708
          key_buff, maybe_null);
1 by brian
clean slate
1709
      /*
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
1710
        Remember if we are going to use REF_OR_NULL
1108.6.20 by Padraig O'Sullivan
Renamed access_type to access_method due to conflicts on Solaris.
1711
        But only if field _really_ can be null i.e. we force AM_REF
1712
        instead of AM_REF_OR_NULL in case if field can't be null
1 by brian
clean slate
1713
      */
1714
      if ((keyuse->optimize & KEY_OPTIMIZE_REF_OR_NULL) && maybe_null)
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
1715
        null_ref_key= key_buff;
1 by brian
clean slate
1716
      key_buff+=keyinfo->key_part[i].store_length;
1717
    }
1718
  }
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
1719
  *ref_key=0;       // end_marker
1108.6.20 by Padraig O'Sullivan
Renamed access_type to access_method due to conflicts on Solaris.
1720
  if (j->type == AM_CONST)
1 by brian
clean slate
1721
    j->table->const_table= 1;
53.2.14 by Monty Taylor
Removed HA_END_SPACE_KEY and references to it. It was _supposed_ to be gone anyway, but the ifdef around it was broken (MYSQL_VERSION_ID was actually undefined.)
1722
  else if (((keyinfo->flags & (HA_NOSAME | HA_NULL_PART_KEY)) != HA_NOSAME) ||
1723
           keyparts != keyinfo->key_parts || null_ref_key)
1 by brian
clean slate
1724
  {
1725
    /* Must read with repeat */
1108.6.20 by Padraig O'Sullivan
Renamed access_type to access_method due to conflicts on Solaris.
1726
    j->type= null_ref_key ? AM_REF_OR_NULL : AM_REF;
1 by brian
clean slate
1727
    j->ref.null_ref_key= null_ref_key;
1728
  }
1729
  else if (keyuse_uses_no_tables)
1730
  {
1731
    /*
1732
      This happen if we are using a constant expression in the ON part
1733
      of an LEFT JOIN.
1734
      SELECT * FROM a LEFT JOIN b ON b.key=30
1735
      Here we should not mark the table as a 'const' as a field may
1736
      have a 'normal' value or a NULL value.
1737
    */
1108.6.20 by Padraig O'Sullivan
Renamed access_type to access_method due to conflicts on Solaris.
1738
    j->type= AM_CONST;
1 by brian
clean slate
1739
  }
1740
  else
1108.6.20 by Padraig O'Sullivan
Renamed access_type to access_method due to conflicts on Solaris.
1741
    j->type= AM_EQ_REF;
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
1742
  return(0);
1 by brian
clean slate
1743
}
1744
1745
/**
1746
  Add to join_tab->select_cond[i] "table.field IS NOT NULL" conditions
1747
  we've inferred from ref/eq_ref access performed.
1748
1749
    This function is a part of "Early NULL-values filtering for ref access"
1750
    optimization.
1751
1752
    Example of this optimization:
1753
    For query SELECT * FROM t1,t2 WHERE t2.key=t1.field @n
1754
    and plan " any-access(t1), ref(t2.key=t1.field) " @n
1755
    add "t1.field IS NOT NULL" to t1's table condition. @n
1756
1757
    Description of the optimization:
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1758
1 by brian
clean slate
1759
      We look through equalities choosen to perform ref/eq_ref access,
1760
      pick equalities that have form "tbl.part_of_key = othertbl.field"
1761
      (where othertbl is a non-const table and othertbl.field may be NULL)
1762
      and add them to conditions on correspoding tables (othertbl in this
1763
      example).
1764
1765
      Exception from that is the case when referred_tab->join != join.
1766
      I.e. don't add NOT NULL constraints from any embedded subquery.
1767
      Consider this query:
1768
      @code
1769
      SELECT A.f2 FROM t1 LEFT JOIN t2 A ON A.f2 = f1
1770
      WHERE A.f3=(SELECT MIN(f3) FROM  t2 C WHERE A.f4 = C.f4) OR A.f3 IS NULL;
1771
      @endocde
1772
      Here condition A.f3 IS NOT NULL is going to be added to the WHERE
1773
      condition of the embedding query.
1774
      Another example:
1775
      SELECT * FROM t10, t11 WHERE (t10.a < 10 OR t10.a IS NULL)
1776
      AND t11.b <=> t10.b AND (t11.a = (SELECT MAX(a) FROM t12
1777
      WHERE t12.b = t10.a ));
1778
      Here condition t10.a IS NOT NULL is going to be added.
1779
      In both cases addition of NOT NULL condition will erroneously reject
1780
      some rows of the result set.
1781
      referred_tab->join != join constraint would disallow such additions.
1782
1783
      This optimization doesn't affect the choices that ref, range, or join
1784
      optimizer make. This was intentional because this was added after 4.1
1785
      was GA.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1786
1 by brian
clean slate
1787
    Implementation overview
1788
      1. update_ref_and_keys() accumulates info about null-rejecting
1789
         predicates in in KEY_FIELD::null_rejecting
1089.1.8 by Brian Aker
Shuffled around a few structures.
1790
      1.1 add_key_part saves these to KeyUse.
1089.1.14 by Brian Aker
Fix TABLE_REF structure
1791
      2. create_ref_for_key copies them to table_reference_st.
1 by brian
clean slate
1792
      3. add_not_null_conds adds "x IS NOT NULL" to join_tab->select_cond of
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
1793
         appropiate JoinTable members.
1 by brian
clean slate
1794
*/
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
1795
void add_not_null_conds(JOIN *join)
1 by brian
clean slate
1796
{
482 by Brian Aker
Remove uint.
1797
  for (uint32_t i=join->const_tables ; i < join->tables ; i++)
1 by brian
clean slate
1798
  {
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
1799
    JoinTable *tab=join->join_tab+i;
1108.6.20 by Padraig O'Sullivan
Renamed access_type to access_method due to conflicts on Solaris.
1800
    if ((tab->type == AM_REF || tab->type == AM_EQ_REF ||
1801
         tab->type == AM_REF_OR_NULL) &&
1 by brian
clean slate
1802
        !tab->table->maybe_null)
1803
    {
482 by Brian Aker
Remove uint.
1804
      for (uint32_t keypart= 0; keypart < tab->ref.key_parts; keypart++)
1 by brian
clean slate
1805
      {
1806
        if (tab->ref.null_rejecting & (1 << keypart))
1807
        {
1808
          Item *item= tab->ref.items[keypart];
1809
          Item *notnull;
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
1810
          assert(item->type() == Item::FIELD_ITEM);
1 by brian
clean slate
1811
          Item_field *not_null_item= (Item_field*)item;
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
1812
          JoinTable *referred_tab= not_null_item->field->table->reginfo.join_tab;
1 by brian
clean slate
1813
          /*
1814
            For UPDATE queries such as:
1815
            UPDATE t1 SET t1.f2=(SELECT MAX(t2.f4) FROM t2 WHERE t2.f3=t1.f1);
1816
            not_null_item is the t1.f1, but it's referred_tab is 0.
1817
          */
1818
          if (!referred_tab || referred_tab->join != join)
1819
            continue;
1820
          if (!(notnull= new Item_func_isnotnull(not_null_item)))
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
1821
            return;
1 by brian
clean slate
1822
          /*
1823
            We need to do full fix_fields() call here in order to have correct
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1824
            notnull->const_item(). This is needed e.g. by test_quick_select
1825
            when it is called from make_join_select after this function is
1 by brian
clean slate
1826
            called.
1827
          */
520.1.22 by Brian Aker
Second pass of thd cleanup
1828
          if (notnull->fix_fields(join->session, &notnull))
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
1829
            return;
1 by brian
clean slate
1830
          add_cond_and_fix(&referred_tab->select_cond, notnull);
1831
        }
1832
      }
1833
    }
1834
  }
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
1835
  return;
1 by brian
clean slate
1836
}
1837
1838
/**
1839
  Build a predicate guarded by match variables for embedding outer joins.
1840
  The function recursively adds guards for predicate cond
1841
  assending from tab to the first inner table  next embedding
1842
  nested outer join and so on until it reaches root_tab
1843
  (root_tab can be 0).
1844
1845
  @param tab       the first inner table for most nested outer join
1846
  @param cond      the predicate to be guarded (must be set)
1847
  @param root_tab  the first inner table to stop
1848
1849
  @return
1850
    -  pointer to the guarded predicate, if success
1851
    -  0, otherwise
1852
*/
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
1853
COND *add_found_match_trig_cond(JoinTable *tab, COND *cond, JoinTable *root_tab)
1 by brian
clean slate
1854
{
1855
  COND *tmp;
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
1856
  assert(cond != 0);
1 by brian
clean slate
1857
  if (tab == root_tab)
1858
    return cond;
1859
  if ((tmp= add_found_match_trig_cond(tab->first_upper, cond, root_tab)))
1860
    tmp= new Item_func_trig_cond(tmp, &tab->found);
1861
  if (tmp)
1862
  {
1863
    tmp->quick_fix_field();
1864
    tmp->update_used_tables();
1865
  }
1866
  return tmp;
1867
}
1868
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1869
/*
1 by brian
clean slate
1870
  Check if given expression uses only table fields covered by the given index
1871
1872
  SYNOPSIS
1873
    uses_index_fields_only()
1874
      item           Expression to check
1875
      tbl            The table having the index
1876
      keyno          The index number
55 by brian
Update for using real bool types.
1877
      other_tbls_ok  true <=> Fields of other non-const tables are allowed
1 by brian
clean slate
1878
1879
  DESCRIPTION
1880
    Check if given expression only uses fields covered by index #keyno in the
1881
    table tbl. The expression can use any fields in any other tables.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1882
1883
    The expression is guaranteed not to be AND or OR - those constructs are
1 by brian
clean slate
1884
    handled outside of this function.
1885
1886
  RETURN
55 by brian
Update for using real bool types.
1887
    true   Yes
1888
    false  No
1 by brian
clean slate
1889
*/
1085.1.2 by Monty Taylor
Fixed -Wmissing-declarations
1890
static bool uses_index_fields_only(Item *item, Table *tbl, uint32_t keyno, bool other_tbls_ok)
1 by brian
clean slate
1891
{
1892
  if (item->const_item())
55 by brian
Update for using real bool types.
1893
    return true;
1 by brian
clean slate
1894
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1895
  /*
1896
    Don't push down the triggered conditions. Nested outer joins execution
1 by brian
clean slate
1897
    code may need to evaluate a condition several times (both triggered and
1898
    untriggered), and there is no way to put thi
1899
    TODO: Consider cloning the triggered condition and using the copies for:
1900
      1. push the first copy down, to have most restrictive index condition
1901
         possible
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1902
      2. Put the second copy into tab->select_cond.
1 by brian
clean slate
1903
  */
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1904
  if (item->type() == Item::FUNC_ITEM &&
1 by brian
clean slate
1905
      ((Item_func*)item)->functype() == Item_func::TRIG_COND_FUNC)
55 by brian
Update for using real bool types.
1906
    return false;
1 by brian
clean slate
1907
1908
  if (!(item->used_tables() & tbl->map))
1909
    return other_tbls_ok;
1910
1911
  Item::Type item_type= item->type();
1912
  switch (item_type) {
1913
  case Item::FUNC_ITEM:
1914
    {
1915
      /* This is a function, apply condition recursively to arguments */
1916
      Item_func *item_func= (Item_func*)item;
1917
      Item **child;
1918
      Item **item_end= (item_func->arguments()) + item_func->argument_count();
1919
      for (child= item_func->arguments(); child != item_end; child++)
1920
      {
1921
        if (!uses_index_fields_only(*child, tbl, keyno, other_tbls_ok))
55 by brian
Update for using real bool types.
1922
          return false;
1 by brian
clean slate
1923
      }
55 by brian
Update for using real bool types.
1924
      return true;
1 by brian
clean slate
1925
    }
1926
  case Item::COND_ITEM:
1927
    {
1928
      /* This is a function, apply condition recursively to arguments */
1929
      List_iterator<Item> li(*((Item_cond*)item)->argument_list());
779.3.10 by Monty Taylor
Turned on -Wshadow.
1930
      Item *list_item;
1931
      while ((list_item=li++))
1 by brian
clean slate
1932
      {
1933
        if (!uses_index_fields_only(item, tbl, keyno, other_tbls_ok))
55 by brian
Update for using real bool types.
1934
          return false;
1 by brian
clean slate
1935
      }
55 by brian
Update for using real bool types.
1936
      return true;
1 by brian
clean slate
1937
    }
1938
  case Item::FIELD_ITEM:
1939
    {
1940
      Item_field *item_field= (Item_field*)item;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1941
      if (item_field->field->table != tbl)
55 by brian
Update for using real bool types.
1942
        return true;
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
1943
      return item_field->field->part_of_key.test(keyno);
1 by brian
clean slate
1944
    }
1945
  case Item::REF_ITEM:
1946
    return uses_index_fields_only(item->real_item(), tbl, keyno,
1947
                                  other_tbls_ok);
1948
  default:
55 by brian
Update for using real bool types.
1949
    return false; /* Play it safe, don't push unknown non-const items */
1 by brian
clean slate
1950
  }
1951
}
1952
1953
#define ICP_COND_USES_INDEX_ONLY 10
1954
1955
/*
1956
  Get a part of the condition that can be checked using only index fields
1957
1958
  SYNOPSIS
1959
    make_cond_for_index()
1960
      cond           The source condition
1961
      table          The table that is partially available
1962
      keyno          The index in the above table. Only fields covered by the index
1963
                     are available
55 by brian
Update for using real bool types.
1964
      other_tbls_ok  true <=> Fields of other non-const tables are allowed
1 by brian
clean slate
1965
1966
  DESCRIPTION
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1967
    Get a part of the condition that can be checked when for the given table
1 by brian
clean slate
1968
    we have values only of fields covered by some index. The condition may
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1969
    refer to other tables, it is assumed that we have values of all of their
1 by brian
clean slate
1970
    fields.
1971
1972
    Example:
1973
      make_cond_for_index(
1974
         "cond(t1.field) AND cond(t2.key1) AND cond(t2.non_key) AND cond(t2.key2)",
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1975
          t2, keyno(t2.key1))
1 by brian
clean slate
1976
      will return
1977
        "cond(t1.field) AND cond(t2.key2)"
1978
1979
  RETURN
1980
    Index condition, or NULL if no condition could be inferred.
1981
*/
1085.1.2 by Monty Taylor
Fixed -Wmissing-declarations
1982
static Item *make_cond_for_index(Item *cond, Table *table, uint32_t keyno, bool other_tbls_ok)
1 by brian
clean slate
1983
{
1984
  if (!cond)
1985
    return NULL;
1986
  if (cond->type() == Item::COND_ITEM)
1987
  {
482 by Brian Aker
Remove uint.
1988
    uint32_t n_marked= 0;
1 by brian
clean slate
1989
    if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
1990
    {
1991
      Item_cond_and *new_cond=new Item_cond_and;
1992
      if (!new_cond)
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
1993
        return (COND*) 0;
1 by brian
clean slate
1994
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
1995
      Item *item;
1996
      while ((item=li++))
1997
      {
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
1998
        Item *fix= make_cond_for_index(item, table, keyno, other_tbls_ok);
1999
        if (fix)
2000
          new_cond->argument_list()->push_back(fix);
1 by brian
clean slate
2001
        n_marked += test(item->marker == ICP_COND_USES_INDEX_ONLY);
2002
      }
2003
      if (n_marked ==((Item_cond*)cond)->argument_list()->elements)
2004
        cond->marker= ICP_COND_USES_INDEX_ONLY;
2005
      switch (new_cond->argument_list()->elements) {
2006
      case 0:
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
2007
        return (COND*) 0;
1 by brian
clean slate
2008
      case 1:
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
2009
        return new_cond->argument_list()->head();
1 by brian
clean slate
2010
      default:
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
2011
        new_cond->quick_fix_field();
2012
        return new_cond;
1 by brian
clean slate
2013
      }
2014
    }
2015
    else /* It's OR */
2016
    {
2017
      Item_cond_or *new_cond=new Item_cond_or;
2018
      if (!new_cond)
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
2019
        return (COND*) 0;
1 by brian
clean slate
2020
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
2021
      Item *item;
2022
      while ((item=li++))
2023
      {
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
2024
        Item *fix= make_cond_for_index(item, table, keyno, other_tbls_ok);
2025
        if (!fix)
2026
          return (COND*) 0;
2027
        new_cond->argument_list()->push_back(fix);
1 by brian
clean slate
2028
        n_marked += test(item->marker == ICP_COND_USES_INDEX_ONLY);
2029
      }
2030
      if (n_marked ==((Item_cond*)cond)->argument_list()->elements)
2031
        cond->marker= ICP_COND_USES_INDEX_ONLY;
2032
      new_cond->quick_fix_field();
2033
      new_cond->top_level_item();
2034
      return new_cond;
2035
    }
2036
  }
2037
2038
  if (!uses_index_fields_only(cond, table, keyno, other_tbls_ok))
2039
    return (COND*) 0;
2040
  cond->marker= ICP_COND_USES_INDEX_ONLY;
2041
  return cond;
2042
}
2043
2044
1085.1.2 by Monty Taylor
Fixed -Wmissing-declarations
2045
static Item *make_cond_remainder(Item *cond, bool exclude_index)
1 by brian
clean slate
2046
{
2047
  if (exclude_index && cond->marker == ICP_COND_USES_INDEX_ONLY)
2048
    return 0; /* Already checked */
2049
2050
  if (cond->type() == Item::COND_ITEM)
2051
  {
2052
    table_map tbl_map= 0;
2053
    if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
2054
    {
2055
      /* Create new top level AND item */
2056
      Item_cond_and *new_cond=new Item_cond_and;
2057
      if (!new_cond)
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
2058
        return (COND*) 0;
1 by brian
clean slate
2059
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
2060
      Item *item;
2061
      while ((item=li++))
2062
      {
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
2063
        Item *fix= make_cond_remainder(item, exclude_index);
2064
        if (fix)
1 by brian
clean slate
2065
        {
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
2066
          new_cond->argument_list()->push_back(fix);
1 by brian
clean slate
2067
          tbl_map |= fix->used_tables();
2068
        }
2069
      }
2070
      switch (new_cond->argument_list()->elements) {
2071
      case 0:
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
2072
        return (COND*) 0;
1 by brian
clean slate
2073
      case 1:
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
2074
        return new_cond->argument_list()->head();
1 by brian
clean slate
2075
      default:
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
2076
        new_cond->quick_fix_field();
1 by brian
clean slate
2077
        ((Item_cond*)new_cond)->used_tables_cache= tbl_map;
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
2078
        return new_cond;
1 by brian
clean slate
2079
      }
2080
    }
2081
    else /* It's OR */
2082
    {
2083
      Item_cond_or *new_cond=new Item_cond_or;
2084
      if (!new_cond)
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
2085
        return (COND*) 0;
1 by brian
clean slate
2086
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
2087
      Item *item;
2088
      while ((item=li++))
2089
      {
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
2090
        Item *fix= make_cond_remainder(item, false);
2091
        if (!fix)
2092
          return (COND*) 0;
2093
        new_cond->argument_list()->push_back(fix);
1 by brian
clean slate
2094
        tbl_map |= fix->used_tables();
2095
      }
2096
      new_cond->quick_fix_field();
2097
      ((Item_cond*)new_cond)->used_tables_cache= tbl_map;
2098
      new_cond->top_level_item();
2099
      return new_cond;
2100
    }
2101
  }
2102
  return cond;
2103
}
2104
2105
/**
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
2106
  cleanup JoinTable.
1 by brian
clean slate
2107
*/
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
2108
void JoinTable::cleanup()
1 by brian
clean slate
2109
{
2110
  delete select;
2111
  select= 0;
2112
  delete quick;
2113
  quick= 0;
460 by Monty Taylor
Removed x_free calls.
2114
  if (cache.buff)
2115
    free(cache.buff);
1 by brian
clean slate
2116
  cache.buff= 0;
2117
  limit= 0;
2118
  if (table)
2119
  {
2120
    if (table->key_read)
2121
    {
2122
      table->key_read= 0;
2123
      table->file->extra(HA_EXTRA_NO_KEYREAD);
2124
    }
2125
    table->file->ha_index_or_rnd_end();
2126
    /*
2127
      We need to reset this for next select
2128
      (Tested in part_of_refkey)
2129
    */
2130
    table->reginfo.join_tab= 0;
2131
  }
2132
  end_read_record(&read_record);
2133
}
2134
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
2135
bool only_eq_ref_tables(JOIN *join,order_st *order,table_map tables)
2136
{
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
2137
  for (JoinTable **tab=join->map2table ; tables ; tab++, tables>>=1)
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
2138
  {
2139
    if (tables & 1 && !eq_ref_table(join, order, *tab))
2140
      return 0;
2141
  }
2142
  return 1;
2143
}
1 by brian
clean slate
2144
2145
/**
327.2.3 by Brian Aker
Refactoring of class Table
2146
  Remove the following expressions from order_st BY and GROUP BY:
1 by brian
clean slate
2147
  Constant expressions @n
2148
  Expression that only uses tables that are of type EQ_REF and the reference
327.2.3 by Brian Aker
Refactoring of class Table
2149
  is in the order_st list or if all refereed tables are of the above type.
1 by brian
clean slate
2150
2151
  In the following, the X field can be removed:
2152
  @code
327.2.3 by Brian Aker
Refactoring of class Table
2153
  SELECT * FROM t1,t2 WHERE t1.a=t2.a order_st BY t1.a,t2.X
2154
  SELECT * FROM t1,t2,t3 WHERE t1.a=t2.a AND t2.b=t3.b order_st BY t1.a,t3.X
1 by brian
clean slate
2155
  @endcode
2156
2157
  These can't be optimized:
2158
  @code
327.2.3 by Brian Aker
Refactoring of class Table
2159
  SELECT * FROM t1,t2 WHERE t1.a=t2.a order_st BY t2.X,t1.a
2160
  SELECT * FROM t1,t2 WHERE t1.a=t2.a AND t1.b=t2.b order_st BY t1.a,t2.c
2161
  SELECT * FROM t1,t2 WHERE t1.a=t2.a order_st BY t2.b,t1.a
1 by brian
clean slate
2162
  @endcode
2163
*/
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
2164
bool eq_ref_table(JOIN *join, order_st *start_order, JoinTable *tab)
1 by brian
clean slate
2165
{
2166
  if (tab->cached_eq_ref_table)			// If cached
2167
    return tab->eq_ref_table;
2168
  tab->cached_eq_ref_table=1;
2169
  /* We can skip const tables only if not an outer table */
1108.6.20 by Padraig O'Sullivan
Renamed access_type to access_method due to conflicts on Solaris.
2170
  if (tab->type == AM_CONST && !tab->first_inner)
1 by brian
clean slate
2171
    return (tab->eq_ref_table=1);		/* purecov: inspected */
1108.6.20 by Padraig O'Sullivan
Renamed access_type to access_method due to conflicts on Solaris.
2172
  if (tab->type != AM_EQ_REF || tab->table->maybe_null)
1 by brian
clean slate
2173
    return (tab->eq_ref_table=0);		// We must use this
2174
  Item **ref_item=tab->ref.items;
2175
  Item **end=ref_item+tab->ref.key_parts;
482 by Brian Aker
Remove uint.
2176
  uint32_t found=0;
1 by brian
clean slate
2177
  table_map map=tab->table->map;
2178
2179
  for (; ref_item != end ; ref_item++)
2180
  {
2181
    if (! (*ref_item)->const_item())
2182
    {						// Not a const ref
327.2.3 by Brian Aker
Refactoring of class Table
2183
      order_st *order;
1 by brian
clean slate
2184
      for (order=start_order ; order ; order=order->next)
2185
      {
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
2186
        if ((*ref_item)->eq(order->item[0],0))
2187
          break;
1 by brian
clean slate
2188
      }
2189
      if (order)
2190
      {
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
2191
        found++;
2192
        assert(!(order->used & map));
2193
        order->used|=map;
2194
        continue;				// Used in order_st BY
1 by brian
clean slate
2195
      }
2196
      if (!only_eq_ref_tables(join,start_order, (*ref_item)->used_tables()))
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
2197
        return (tab->eq_ref_table= 0);
1 by brian
clean slate
2198
    }
2199
  }
2200
  /* Check that there was no reference to table before sort order */
2201
  for (; found && start_order ; start_order=start_order->next)
2202
  {
2203
    if (start_order->used & map)
2204
    {
2205
      found--;
2206
      continue;
2207
    }
2208
    if (start_order->depend_map & map)
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
2209
      return (tab->eq_ref_table= 0);
1 by brian
clean slate
2210
  }
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
2211
  return tab->eq_ref_table= 1;
1 by brian
clean slate
2212
}
2213
2214
/**
2215
  Find the multiple equality predicate containing a field.
2216
2217
  The function retrieves the multiple equalities accessed through
2218
  the con_equal structure from current level and up looking for
2219
  an equality containing field. It stops retrieval as soon as the equality
55 by brian
Update for using real bool types.
2220
  is found and set up inherited_fl to true if it's found on upper levels.
1 by brian
clean slate
2221
2222
  @param cond_equal          multiple equalities to search in
2223
  @param field               field to look for
55 by brian
Update for using real bool types.
2224
  @param[out] inherited_fl   set up to true if multiple equality is found
1 by brian
clean slate
2225
                             on upper levels (not on current level of
2226
                             cond_equal)
2227
2228
  @return
2229
    - Item_equal for the found multiple equality predicate if a success;
2230
    - NULL otherwise.
2231
*/
1085.1.2 by Monty Taylor
Fixed -Wmissing-declarations
2232
static Item_equal *find_item_equal(COND_EQUAL *cond_equal, Field *field, bool *inherited_fl)
1 by brian
clean slate
2233
{
2234
  Item_equal *item= 0;
55 by brian
Update for using real bool types.
2235
  bool in_upper_level= false;
1 by brian
clean slate
2236
  while (cond_equal)
2237
  {
2238
    List_iterator_fast<Item_equal> li(cond_equal->current_level);
2239
    while ((item= li++))
2240
    {
2241
      if (item->contains(field))
2242
        goto finish;
2243
    }
55 by brian
Update for using real bool types.
2244
    in_upper_level= true;
1 by brian
clean slate
2245
    cond_equal= cond_equal->upper_levels;
2246
  }
55 by brian
Update for using real bool types.
2247
  in_upper_level= false;
1 by brian
clean slate
2248
finish:
2249
  *inherited_fl= in_upper_level;
2250
  return item;
2251
}
2252
2253
/**
2254
  Check whether an equality can be used to build multiple equalities.
2255
2256
    This function first checks whether the equality (left_item=right_item)
2257
    is a simple equality i.e. the one that equates a field with another field
2258
    or a constant (field=field_item or field=const_item).
2259
    If this is the case the function looks for a multiple equality
2260
    in the lists referenced directly or indirectly by cond_equal inferring
2261
    the given simple equality. If it doesn't find any, it builds a multiple
2262
    equality that covers the predicate, i.e. the predicate can be inferred
2263
    from this multiple equality.
2264
    The built multiple equality could be obtained in such a way:
2265
    create a binary  multiple equality equivalent to the predicate, then
2266
    merge it, if possible, with one of old multiple equalities.
2267
    This guarantees that the set of multiple equalities covering equality
2268
    predicates will be minimal.
2269
2270
  EXAMPLE:
2271
    For the where condition
2272
    @code
2273
      WHERE a=b AND b=c AND
2274
            (b=2 OR f=e)
2275
    @endcode
2276
    the check_equality will be called for the following equality
2277
    predicates a=b, b=c, b=2 and f=e.
2278
    - For a=b it will be called with *cond_equal=(0,[]) and will transform
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2279
      *cond_equal into (0,[Item_equal(a,b)]).
1 by brian
clean slate
2280
    - For b=c it will be called with *cond_equal=(0,[Item_equal(a,b)])
2281
      and will transform *cond_equal into CE=(0,[Item_equal(a,b,c)]).
2282
    - For b=2 it will be called with *cond_equal=(ptr(CE),[])
2283
      and will transform *cond_equal into (ptr(CE),[Item_equal(2,a,b,c)]).
2284
    - For f=e it will be called with *cond_equal=(ptr(CE), [])
2285
      and will transform *cond_equal into (ptr(CE),[Item_equal(f,e)]).
2286
2287
  @note
2288
    Now only fields that have the same type definitions (verified by
2289
    the Field::eq_def method) are placed to the same multiple equalities.
2290
    Because of this some equality predicates are not eliminated and
2291
    can be used in the constant propagation procedure.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2292
    We could weeken the equlity test as soon as at least one of the
2293
    equal fields is to be equal to a constant. It would require a
1 by brian
clean slate
2294
    more complicated implementation: we would have to store, in
2295
    general case, its own constant for each fields from the multiple
2296
    equality. But at the same time it would allow us to get rid
2297
    of constant propagation completely: it would be done by the call
2298
    to build_equal_items_for_cond.
2299
2300
2301
    The implementation does not follow exactly the above rules to
2302
    build a new multiple equality for the equality predicate.
2303
    If it processes the equality of the form field1=field2, it
2304
    looks for multiple equalities me1 containig field1 and me2 containing
2305
    field2. If only one of them is found the fuction expands it with
2306
    the lacking field. If multiple equalities for both fields are
2307
    found they are merged. If both searches fail a new multiple equality
2308
    containing just field1 and field2 is added to the existing
2309
    multiple equalities.
2310
    If the function processes the predicate of the form field1=const,
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2311
    it looks for a multiple equality containing field1. If found, the
1 by brian
clean slate
2312
    function checks the constant of the multiple equality. If the value
2313
    is unknown, it is setup to const. Otherwise the value is compared with
2314
    const and the evaluation of the equality predicate is performed.
2315
    When expanding/merging equality predicates from the upper levels
2316
    the function first copies them for the current level. It looks
2317
    acceptable, as this happens rarely. The implementation without
2318
    copying would be much more complicated.
2319
2320
  @param left_item   left term of the quality to be checked
2321
  @param right_item  right term of the equality to be checked
2322
  @param item        equality item if the equality originates from a condition
2323
                     predicate, 0 if the equality is the result of row
2324
                     elimination
2325
  @param cond_equal  multiple equalities that must hold together with the
2326
                     equality
2327
2328
  @retval
55 by brian
Update for using real bool types.
2329
    true    if the predicate is a simple equality predicate to be used
1 by brian
clean slate
2330
    for building multiple equalities
2331
  @retval
55 by brian
Update for using real bool types.
2332
    false   otherwise
1 by brian
clean slate
2333
*/
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
2334
static bool check_simple_equality(Item *left_item,
2335
                                  Item *right_item,
2336
                                  Item *item,
2337
                                  COND_EQUAL *cond_equal)
1 by brian
clean slate
2338
{
2339
  if (left_item->type() == Item::FIELD_ITEM &&
2340
      right_item->type() == Item::FIELD_ITEM &&
2341
      !((Item_field*)left_item)->depended_from &&
2342
      !((Item_field*)right_item)->depended_from)
2343
  {
2344
    /* The predicate the form field1=field2 is processed */
2345
2346
    Field *left_field= ((Item_field*) left_item)->field;
2347
    Field *right_field= ((Item_field*) right_item)->field;
2348
2349
    if (!left_field->eq_def(right_field))
55 by brian
Update for using real bool types.
2350
      return false;
1 by brian
clean slate
2351
2352
    /* Search for multiple equalities containing field1 and/or field2 */
2353
    bool left_copyfl, right_copyfl;
2354
    Item_equal *left_item_equal=
2355
               find_item_equal(cond_equal, left_field, &left_copyfl);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2356
    Item_equal *right_item_equal=
1 by brian
clean slate
2357
               find_item_equal(cond_equal, right_field, &right_copyfl);
2358
55 by brian
Update for using real bool types.
2359
    /* As (NULL=NULL) != true we can't just remove the predicate f=f */
1 by brian
clean slate
2360
    if (left_field->eq(right_field)) /* f = f */
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2361
      return (!(left_field->maybe_null() && !left_item_equal));
1 by brian
clean slate
2362
2363
    if (left_item_equal && left_item_equal == right_item_equal)
2364
    {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2365
      /*
1 by brian
clean slate
2366
        The equality predicate is inference of one of the existing
2367
        multiple equalities, i.e the condition is already covered
2368
        by upper level equalities
2369
      */
55 by brian
Update for using real bool types.
2370
       return true;
1 by brian
clean slate
2371
    }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2372
2373
    bool copy_item_name= test(item && item->name >= subq_sj_cond_name &&
1 by brian
clean slate
2374
                              item->name < subq_sj_cond_name + 64);
2375
    /* Copy the found multiple equalities at the current level if needed */
2376
    if (left_copyfl)
2377
    {
2378
      /* left_item_equal of an upper level contains left_item */
2379
      left_item_equal= new Item_equal(left_item_equal);
2380
      cond_equal->current_level.push_back(left_item_equal);
2381
      if (copy_item_name)
2382
        left_item_equal->name = item->name;
2383
    }
2384
    if (right_copyfl)
2385
    {
2386
      /* right_item_equal of an upper level contains right_item */
2387
      right_item_equal= new Item_equal(right_item_equal);
2388
      cond_equal->current_level.push_back(right_item_equal);
2389
      if (copy_item_name)
2390
        right_item_equal->name = item->name;
2391
    }
2392
2393
    if (left_item_equal)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2394
    {
1 by brian
clean slate
2395
      /* left item was found in the current or one of the upper levels */
2396
      if (! right_item_equal)
2397
        left_item_equal->add((Item_field *) right_item);
2398
      else
2399
      {
2400
        /* Merge two multiple equalities forming a new one */
2401
        left_item_equal->merge(right_item_equal);
2402
        /* Remove the merged multiple equality from the list */
2403
        List_iterator<Item_equal> li(cond_equal->current_level);
2404
        while ((li++) != right_item_equal) {};
2405
        li.remove();
2406
      }
2407
    }
2408
    else
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2409
    {
1 by brian
clean slate
2410
      /* left item was not found neither the current nor in upper levels  */
2411
      if (right_item_equal)
2412
      {
2413
        right_item_equal->add((Item_field *) left_item);
2414
        if (copy_item_name)
2415
          right_item_equal->name = item->name;
2416
      }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2417
      else
1 by brian
clean slate
2418
      {
2419
        /* None of the fields was found in multiple equalities */
2420
        Item_equal *item_equal= new Item_equal((Item_field *) left_item,
2421
                                               (Item_field *) right_item);
2422
        cond_equal->current_level.push_back(item_equal);
2423
        if (copy_item_name)
2424
          item_equal->name = item->name;
2425
      }
2426
    }
55 by brian
Update for using real bool types.
2427
    return true;
1 by brian
clean slate
2428
  }
2429
2430
  {
2431
    /* The predicate of the form field=const/const=field is processed */
2432
    Item *const_item= 0;
2433
    Item_field *field_item= 0;
2434
    if (left_item->type() == Item::FIELD_ITEM &&
2435
        !((Item_field*)left_item)->depended_from &&
2436
        right_item->const_item())
2437
    {
2438
      field_item= (Item_field*) left_item;
2439
      const_item= right_item;
2440
    }
2441
    else if (right_item->type() == Item::FIELD_ITEM &&
2442
             !((Item_field*)right_item)->depended_from &&
2443
             left_item->const_item())
2444
    {
2445
      field_item= (Item_field*) right_item;
2446
      const_item= left_item;
2447
    }
2448
2449
    if (const_item &&
2450
        field_item->result_type() == const_item->result_type())
2451
    {
2452
      bool copyfl;
2453
2454
      if (field_item->result_type() == STRING_RESULT)
2455
      {
264.2.6 by Andrey Hristov
Constify the usage of CHARSET_INFO almost to the last place in the code.
2456
        const CHARSET_INFO * const cs= ((Field_str*) field_item->field)->charset();
1 by brian
clean slate
2457
        if (!item)
2458
        {
2459
          Item_func_eq *eq_item;
2460
          if ((eq_item= new Item_func_eq(left_item, right_item)))
55 by brian
Update for using real bool types.
2461
            return false;
1 by brian
clean slate
2462
          eq_item->set_cmp_func();
2463
          eq_item->quick_fix_field();
2464
          item= eq_item;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2465
        }
1 by brian
clean slate
2466
        if ((cs != ((Item_func *) item)->compare_collation()) ||
2467
            !cs->coll->propagate(cs, 0, 0))
55 by brian
Update for using real bool types.
2468
          return false;
1 by brian
clean slate
2469
      }
2470
2471
      Item_equal *item_equal = find_item_equal(cond_equal,
2472
                                               field_item->field, &copyfl);
2473
      if (copyfl)
2474
      {
2475
        item_equal= new Item_equal(item_equal);
2476
        cond_equal->current_level.push_back(item_equal);
2477
      }
2478
      if (item_equal)
2479
      {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2480
        /*
1 by brian
clean slate
2481
          The flag cond_false will be set to 1 after this, if item_equal
2482
          already contains a constant and its value is  not equal to
2483
          the value of const_item.
2484
        */
2485
        item_equal->add(const_item);
2486
      }
2487
      else
2488
      {
2489
        item_equal= new Item_equal(const_item, field_item);
2490
        cond_equal->current_level.push_back(item_equal);
2491
      }
55 by brian
Update for using real bool types.
2492
      return true;
1 by brian
clean slate
2493
    }
2494
  }
55 by brian
Update for using real bool types.
2495
  return false;
1 by brian
clean slate
2496
}
2497
2498
/**
2499
  Convert row equalities into a conjunction of regular equalities.
2500
2501
    The function converts a row equality of the form (E1,...,En)=(E'1,...,E'n)
2502
    into a list of equalities E1=E'1,...,En=E'n. For each of these equalities
2503
    Ei=E'i the function checks whether it is a simple equality or a row
2504
    equality. If it is a simple equality it is used to expand multiple
2505
    equalities of cond_equal. If it is a row equality it converted to a
2506
    sequence of equalities between row elements. If Ei=E'i is neither a
2507
    simple equality nor a row equality the item for this predicate is added
2508
    to eq_list.
2509
520.1.22 by Brian Aker
Second pass of thd cleanup
2510
  @param session        thread handle
1 by brian
clean slate
2511
  @param left_row   left term of the row equality to be processed
2512
  @param right_row  right term of the row equality to be processed
2513
  @param cond_equal multiple equalities that must hold together with the
2514
                    predicate
2515
  @param eq_list    results of conversions of row equalities that are not
2516
                    simple enough to form multiple equalities
2517
2518
  @retval
55 by brian
Update for using real bool types.
2519
    true    if conversion has succeeded (no fatal error)
1 by brian
clean slate
2520
  @retval
55 by brian
Update for using real bool types.
2521
    false   otherwise
1 by brian
clean slate
2522
*/
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
2523
static bool check_row_equality(Session *session,
2524
                               Item *left_row, 
2525
                               Item_row *right_row,
2526
                               COND_EQUAL *cond_equal,
2527
                               List<Item>* eq_list)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2528
{
482 by Brian Aker
Remove uint.
2529
  uint32_t n= left_row->cols();
2530
  for (uint32_t i= 0 ; i < n; i++)
1 by brian
clean slate
2531
  {
2532
    bool is_converted;
2533
    Item *left_item= left_row->element_index(i);
2534
    Item *right_item= right_row->element_index(i);
2535
    if (left_item->type() == Item::ROW_ITEM &&
2536
        right_item->type() == Item::ROW_ITEM)
2537
    {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2538
      is_converted= check_row_equality(session,
1 by brian
clean slate
2539
                                       (Item_row *) left_item,
2540
                                       (Item_row *) right_item,
2541
			               cond_equal, eq_list);
2542
      if (!is_converted)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2543
        session->lex->current_select->cond_count++;
1 by brian
clean slate
2544
    }
2545
    else
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2546
    {
1 by brian
clean slate
2547
      is_converted= check_simple_equality(left_item, right_item, 0, cond_equal);
520.1.22 by Brian Aker
Second pass of thd cleanup
2548
      session->lex->current_select->cond_count++;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2549
    }
2550
1 by brian
clean slate
2551
    if (!is_converted)
2552
    {
2553
      Item_func_eq *eq_item;
2554
      if (!(eq_item= new Item_func_eq(left_item, right_item)))
55 by brian
Update for using real bool types.
2555
        return false;
1 by brian
clean slate
2556
      eq_item->set_cmp_func();
2557
      eq_item->quick_fix_field();
2558
      eq_list->push_back(eq_item);
2559
    }
2560
  }
55 by brian
Update for using real bool types.
2561
  return true;
1 by brian
clean slate
2562
}
2563
2564
/**
2565
  Eliminate row equalities and form multiple equalities predicates.
2566
2567
    This function checks whether the item is a simple equality
2568
    i.e. the one that equates a field with another field or a constant
2569
    (field=field_item or field=constant_item), or, a row equality.
2570
    For a simple equality the function looks for a multiple equality
2571
    in the lists referenced directly or indirectly by cond_equal inferring
2572
    the given simple equality. If it doesn't find any, it builds/expands
2573
    multiple equality that covers the predicate.
2574
    Row equalities are eliminated substituted for conjunctive regular
2575
    equalities which are treated in the same way as original equality
2576
    predicates.
2577
520.1.22 by Brian Aker
Second pass of thd cleanup
2578
  @param session        thread handle
1 by brian
clean slate
2579
  @param item       predicate to process
2580
  @param cond_equal multiple equalities that must hold together with the
2581
                    predicate
2582
  @param eq_list    results of conversions of row equalities that are not
2583
                    simple enough to form multiple equalities
2584
2585
  @retval
55 by brian
Update for using real bool types.
2586
    true   if re-writing rules have been applied
1 by brian
clean slate
2587
  @retval
55 by brian
Update for using real bool types.
2588
    false  otherwise, i.e.
1 by brian
clean slate
2589
           if the predicate is not an equality,
2590
           or, if the equality is neither a simple one nor a row equality,
2591
           or, if the procedure fails by a fatal error.
2592
*/
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
2593
static bool check_equality(Session *session, Item *item, COND_EQUAL *cond_equal, List<Item> *eq_list)
1 by brian
clean slate
2594
{
2595
  if (item->type() == Item::FUNC_ITEM &&
2596
         ((Item_func*) item)->functype() == Item_func::EQ_FUNC)
2597
  {
2598
    Item *left_item= ((Item_func*) item)->arguments()[0];
2599
    Item *right_item= ((Item_func*) item)->arguments()[1];
2600
2601
    if (left_item->type() == Item::ROW_ITEM &&
2602
        right_item->type() == Item::ROW_ITEM)
2603
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
2604
      session->lex->current_select->cond_count--;
2605
      return check_row_equality(session,
1 by brian
clean slate
2606
                                (Item_row *) left_item,
2607
                                (Item_row *) right_item,
2608
                                cond_equal, eq_list);
2609
    }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2610
    else
1 by brian
clean slate
2611
      return check_simple_equality(left_item, right_item, item, cond_equal);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2612
  }
55 by brian
Update for using real bool types.
2613
  return false;
1 by brian
clean slate
2614
}
2615
2616
/**
2617
  Replace all equality predicates in a condition by multiple equality items.
2618
2619
    At each 'and' level the function detects items for equality predicates
2620
    and replaced them by a set of multiple equality items of class Item_equal,
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2621
    taking into account inherited equalities from upper levels.
1 by brian
clean slate
2622
    If an equality predicate is used not in a conjunction it's just
2623
    replaced by a multiple equality predicate.
2624
    For each 'and' level the function set a pointer to the inherited
2625
    multiple equalities in the cond_equal field of the associated
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2626
    object of the type Item_cond_and.
1 by brian
clean slate
2627
    The function also traverses the cond tree and and for each field reference
2628
    sets a pointer to the multiple equality item containing the field, if there
2629
    is any. If this multiple equality equates fields to a constant the
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2630
    function replaces the field reference by the constant in the cases
1 by brian
clean slate
2631
    when the field is not of a string type or when the field reference is
2632
    just an argument of a comparison predicate.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2633
    The function also determines the maximum number of members in
1 by brian
clean slate
2634
    equality lists of each Item_cond_and object assigning it to
520.1.22 by Brian Aker
Second pass of thd cleanup
2635
    session->lex->current_select->max_equal_elems.
1 by brian
clean slate
2636
2637
  @note
2638
    Multiple equality predicate =(f1,..fn) is equivalent to the conjuction of
2639
    f1=f2, .., fn-1=fn. It substitutes any inference from these
2640
    equality predicates that is equivalent to the conjunction.
2641
    Thus, =(a1,a2,a3) can substitute for ((a1=a3) AND (a2=a3) AND (a2=a1)) as
2642
    it is equivalent to ((a1=a2) AND (a2=a3)).
2643
    The function always makes a substitution of all equality predicates occured
2644
    in a conjuction for a minimal set of multiple equality predicates.
2645
    This set can be considered as a canonical representation of the
2646
    sub-conjunction of the equality predicates.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2647
    E.g. (t1.a=t2.b AND t2.b>5 AND t1.a=t3.c) is replaced by
1 by brian
clean slate
2648
    (=(t1.a,t2.b,t3.c) AND t2.b>5), not by
2649
    (=(t1.a,t2.b) AND =(t1.a,t3.c) AND t2.b>5);
2650
    while (t1.a=t2.b AND t2.b>5 AND t3.c=t4.d) is replaced by
2651
    (=(t1.a,t2.b) AND =(t3.c=t4.d) AND t2.b>5),
2652
    but if additionally =(t4.d,t2.b) is inherited, it
2653
    will be replaced by (=(t1.a,t2.b,t3.c,t4.d) AND t2.b>5)
2654
2655
    The function performs the substitution in a recursive descent by
2656
    the condtion tree, passing to the next AND level a chain of multiple
2657
    equality predicates which have been built at the upper levels.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2658
    The Item_equal items built at the level are attached to other
1 by brian
clean slate
2659
    non-equality conjucts as a sublist. The pointer to the inherited
2660
    multiple equalities is saved in the and condition object (Item_cond_and).
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2661
    This chain allows us for any field reference occurence easyly to find a
1 by brian
clean slate
2662
    multiple equality that must be held for this occurence.
2663
    For each AND level we do the following:
2664
    - scan it for all equality predicate (=) items
2665
    - join them into disjoint Item_equal() groups
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2666
    - process the included OR conditions recursively to do the same for
2667
      lower AND levels.
1 by brian
clean slate
2668
2669
    We need to do things in this order as lower AND levels need to know about
2670
    all possible Item_equal objects in upper levels.
2671
520.1.22 by Brian Aker
Second pass of thd cleanup
2672
  @param session        thread handle
1 by brian
clean slate
2673
  @param cond       condition(expression) where to make replacement
2674
  @param inherited  path to all inherited multiple equality items
2675
2676
  @return
2677
    pointer to the transformed condition
2678
*/
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
2679
static COND *build_equal_items_for_cond(Session *session, COND *cond, COND_EQUAL *inherited)
1 by brian
clean slate
2680
{
2681
  Item_equal *item_equal;
2682
  COND_EQUAL cond_equal;
2683
  cond_equal.upper_levels= inherited;
2684
2685
  if (cond->type() == Item::COND_ITEM)
2686
  {
2687
    List<Item> eq_list;
2688
    bool and_level= ((Item_cond*) cond)->functype() ==
2689
      Item_func::COND_AND_FUNC;
2690
    List<Item> *args= ((Item_cond*) cond)->argument_list();
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2691
1 by brian
clean slate
2692
    List_iterator<Item> li(*args);
2693
    Item *item;
2694
2695
    if (and_level)
2696
    {
2697
      /*
2698
         Retrieve all conjucts of this level detecting the equality
2699
         that are subject to substitution by multiple equality items and
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2700
         removing each such predicate from the conjunction after having
1 by brian
clean slate
2701
         found/created a multiple equality whose inference the predicate is.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2702
     */
1 by brian
clean slate
2703
      while ((item= li++))
2704
      {
2705
        /*
2706
          PS/SP note: we can safely remove a node from AND-OR
2707
          structure here because it's restored before each
2708
          re-execution of any prepared statement/stored procedure.
2709
        */
520.1.22 by Brian Aker
Second pass of thd cleanup
2710
        if (check_equality(session, item, &cond_equal, &eq_list))
1 by brian
clean slate
2711
          li.remove();
2712
      }
2713
2714
      List_iterator_fast<Item_equal> it(cond_equal.current_level);
2715
      while ((item_equal= it++))
2716
      {
2717
        item_equal->fix_length_and_dec();
2718
        item_equal->update_used_tables();
520.1.22 by Brian Aker
Second pass of thd cleanup
2719
        set_if_bigger(session->lex->current_select->max_equal_elems,
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2720
                      item_equal->members());
1 by brian
clean slate
2721
      }
2722
2723
      ((Item_cond_and*)cond)->cond_equal= cond_equal;
2724
      inherited= &(((Item_cond_and*)cond)->cond_equal);
2725
    }
2726
    /*
2727
       Make replacement of equality predicates for lower levels
2728
       of the condition expression.
2729
    */
2730
    li.rewind();
2731
    while ((item= li++))
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2732
    {
1 by brian
clean slate
2733
      Item *new_item;
520.1.22 by Brian Aker
Second pass of thd cleanup
2734
      if ((new_item= build_equal_items_for_cond(session, item, inherited)) != item)
1 by brian
clean slate
2735
      {
2736
        /* This replacement happens only for standalone equalities */
2737
        /*
2738
          This is ok with PS/SP as the replacement is done for
2739
          arguments of an AND/OR item, which are restored for each
2740
          execution of PS/SP.
2741
        */
2742
        li.replace(new_item);
2743
      }
2744
    }
2745
    if (and_level)
2746
    {
2747
      args->concat(&eq_list);
2748
      args->concat((List<Item> *)&cond_equal.current_level);
2749
    }
2750
  }
2751
  else if (cond->type() == Item::FUNC_ITEM)
2752
  {
2753
    List<Item> eq_list;
2754
    /*
2755
      If an equality predicate forms the whole and level,
2756
      we call it standalone equality and it's processed here.
2757
      E.g. in the following where condition
2758
      WHERE a=5 AND (b=5 or a=c)
2759
      (b=5) and (a=c) are standalone equalities.
2760
      In general we can't leave alone standalone eqalities:
2761
      for WHERE a=b AND c=d AND (b=c OR d=5)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2762
      b=c is replaced by =(a,b,c,d).
1 by brian
clean slate
2763
     */
520.1.22 by Brian Aker
Second pass of thd cleanup
2764
    if (check_equality(session, cond, &cond_equal, &eq_list))
1 by brian
clean slate
2765
    {
2766
      int n= cond_equal.current_level.elements + eq_list.elements;
2767
      if (n == 0)
152 by Brian Aker
longlong replacement
2768
        return new Item_int((int64_t) 1,1);
1 by brian
clean slate
2769
      else if (n == 1)
2770
      {
2771
        if ((item_equal= cond_equal.current_level.pop()))
2772
        {
2773
          item_equal->fix_length_and_dec();
2774
          item_equal->update_used_tables();
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
2775
        }
1 by brian
clean slate
2776
        else
2777
          item_equal= (Item_equal *) eq_list.pop();
520.1.22 by Brian Aker
Second pass of thd cleanup
2778
        set_if_bigger(session->lex->current_select->max_equal_elems,
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2779
                      item_equal->members());
1 by brian
clean slate
2780
        return item_equal;
2781
      }
2782
      else
2783
      {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2784
        /*
1 by brian
clean slate
2785
          Here a new AND level must be created. It can happen only
2786
          when a row equality is processed as a standalone predicate.
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
2787
        */
1 by brian
clean slate
2788
        Item_cond_and *and_cond= new Item_cond_and(eq_list);
2789
        and_cond->quick_fix_field();
2790
        List<Item> *args= and_cond->argument_list();
2791
        List_iterator_fast<Item_equal> it(cond_equal.current_level);
2792
        while ((item_equal= it++))
2793
        {
2794
          item_equal->fix_length_and_dec();
2795
          item_equal->update_used_tables();
520.1.22 by Brian Aker
Second pass of thd cleanup
2796
          set_if_bigger(session->lex->current_select->max_equal_elems,
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2797
                        item_equal->members());
1 by brian
clean slate
2798
        }
2799
        and_cond->cond_equal= cond_equal;
2800
        args->concat((List<Item> *)&cond_equal.current_level);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2801
1 by brian
clean slate
2802
        return and_cond;
2803
      }
2804
    }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2805
    /*
1 by brian
clean slate
2806
      For each field reference in cond, not from equal item predicates,
2807
      set a pointer to the multiple equality it belongs to (if there is any)
2808
      as soon the field is not of a string type or the field reference is
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2809
      an argument of a comparison predicate.
2810
    */
481 by Brian Aker
Remove all of uchar.
2811
    unsigned char *is_subst_valid= (unsigned char *) 1;
1 by brian
clean slate
2812
    cond= cond->compile(&Item::subst_argument_checker,
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2813
                        &is_subst_valid,
1 by brian
clean slate
2814
                        &Item::equal_fields_propagator,
481 by Brian Aker
Remove all of uchar.
2815
                        (unsigned char *) inherited);
1 by brian
clean slate
2816
    cond->update_used_tables();
2817
  }
2818
  return cond;
2819
}
2820
2821
/**
2822
  Build multiple equalities for a condition and all on expressions that
2823
  inherit these multiple equalities.
2824
2825
    The function first applies the build_equal_items_for_cond function
2826
    to build all multiple equalities for condition cond utilizing equalities
2827
    referred through the parameter inherited. The extended set of
2828
    equalities is returned in the structure referred by the cond_equal_ref
2829
    parameter. After this the function calls itself recursively for
2830
    all on expressions whose direct references can be found in join_list
2831
    and who inherit directly the multiple equalities just having built.
2832
2833
  @note
2834
    The on expression used in an outer join operation inherits all equalities
2835
    from the on expression of the embedding join, if there is any, or
2836
    otherwise - from the where condition.
2837
    This fact is not obvious, but presumably can be proved.
2838
    Consider the following query:
2839
    @code
2840
      SELECT * FROM (t1,t2) LEFT JOIN (t3,t4) ON t1.a=t3.a AND t2.a=t4.a
2841
        WHERE t1.a=t2.a;
2842
    @endcode
2843
    If the on expression in the query inherits =(t1.a,t2.a), then we
2844
    can build the multiple equality =(t1.a,t2.a,t3.a,t4.a) that infers
2845
    the equality t3.a=t4.a. Although the on expression
2846
    t1.a=t3.a AND t2.a=t4.a AND t3.a=t4.a is not equivalent to the one
2847
    in the query the latter can be replaced by the former: the new query
2848
    will return the same result set as the original one.
2849
2850
    Interesting that multiple equality =(t1.a,t2.a,t3.a,t4.a) allows us
2851
    to use t1.a=t3.a AND t3.a=t4.a under the on condition:
2852
    @code
2853
      SELECT * FROM (t1,t2) LEFT JOIN (t3,t4) ON t1.a=t3.a AND t3.a=t4.a
2854
        WHERE t1.a=t2.a
2855
    @endcode
2856
    This query equivalent to:
2857
    @code
2858
      SELECT * FROM (t1 LEFT JOIN (t3,t4) ON t1.a=t3.a AND t3.a=t4.a),t2
2859
        WHERE t1.a=t2.a
2860
    @endcode
2861
    Similarly the original query can be rewritten to the query:
2862
    @code
2863
      SELECT * FROM (t1,t2) LEFT JOIN (t3,t4) ON t2.a=t4.a AND t3.a=t4.a
2864
        WHERE t1.a=t2.a
2865
    @endcode
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2866
    that is equivalent to:
1 by brian
clean slate
2867
    @code
2868
      SELECT * FROM (t2 LEFT JOIN (t3,t4)ON t2.a=t4.a AND t3.a=t4.a), t1
2869
        WHERE t1.a=t2.a
2870
    @endcode
2871
    Thus, applying equalities from the where condition we basically
2872
    can get more freedom in performing join operations.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2873
    Althogh we don't use this property now, it probably makes sense to use
2874
    it in the future.
520.1.22 by Brian Aker
Second pass of thd cleanup
2875
  @param session		      Thread handler
1 by brian
clean slate
2876
  @param cond                condition to build the multiple equalities for
2877
  @param inherited           path to all inherited multiple equality items
2878
  @param join_list           list of join tables to which the condition
2879
                             refers to
2880
  @param[out] cond_equal_ref pointer to the structure to place built
2881
                             equalities in
2882
2883
  @return
2884
    pointer to the transformed condition containing multiple equalities
2885
*/
520.1.22 by Brian Aker
Second pass of thd cleanup
2886
static COND *build_equal_items(Session *session, COND *cond,
1 by brian
clean slate
2887
                               COND_EQUAL *inherited,
327.2.4 by Brian Aker
Refactoring table.h
2888
                               List<TableList> *join_list,
1 by brian
clean slate
2889
                               COND_EQUAL **cond_equal_ref)
2890
{
2891
  COND_EQUAL *cond_equal= 0;
2892
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2893
  if (cond)
1 by brian
clean slate
2894
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
2895
    cond= build_equal_items_for_cond(session, cond, inherited);
1 by brian
clean slate
2896
    cond->update_used_tables();
2897
    if (cond->type() == Item::COND_ITEM &&
2898
        ((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
2899
      cond_equal= &((Item_cond_and*) cond)->cond_equal;
2900
    else if (cond->type() == Item::FUNC_ITEM &&
2901
             ((Item_cond*) cond)->functype() == Item_func::MULT_EQUAL_FUNC)
2902
    {
2903
      cond_equal= new COND_EQUAL;
2904
      cond_equal->current_level.push_back((Item_equal *) cond);
2905
    }
2906
  }
2907
  if (cond_equal)
2908
  {
2909
    cond_equal->upper_levels= inherited;
2910
    inherited= cond_equal;
2911
  }
2912
  *cond_equal_ref= cond_equal;
2913
2914
  if (join_list)
2915
  {
327.2.4 by Brian Aker
Refactoring table.h
2916
    TableList *table;
2917
    List_iterator<TableList> li(*join_list);
1 by brian
clean slate
2918
2919
    while ((table= li++))
2920
    {
2921
      if (table->on_expr)
2922
      {
327.2.4 by Brian Aker
Refactoring table.h
2923
        List<TableList> *nested_join_list= table->nested_join ?
1 by brian
clean slate
2924
          &table->nested_join->join_list : NULL;
2925
        /*
2926
          We can modify table->on_expr because its old value will
2927
          be restored before re-execution of PS/SP.
2928
        */
520.1.22 by Brian Aker
Second pass of thd cleanup
2929
        table->on_expr= build_equal_items(session, table->on_expr, inherited,
1 by brian
clean slate
2930
                                          nested_join_list,
2931
                                          &table->cond_equal);
2932
      }
2933
    }
2934
  }
2935
2936
  return cond;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2937
}
1 by brian
clean slate
2938
2939
/**
2940
  Compare field items by table order in the execution plan.
2941
2942
    field1 considered as better than field2 if the table containing
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2943
    field1 is accessed earlier than the table containing field2.
1 by brian
clean slate
2944
    The function finds out what of two fields is better according
2945
    this criteria.
2946
2947
  @param field1          first field item to compare
2948
  @param field2          second field item to compare
2949
  @param table_join_idx  index to tables determining table order
2950
2951
  @retval
2952
    1  if field1 is better than field2
2953
  @retval
2954
    -1  if field2 is better than field1
2955
  @retval
2956
    0  otherwise
2957
*/
2958
static int compare_fields_by_table_order(Item_field *field1,
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
2959
                                         Item_field *field2,
2960
                                         void *table_join_idx)
1 by brian
clean slate
2961
{
2962
  int cmp= 0;
2963
  bool outer_ref= 0;
2964
  if (field2->used_tables() & OUTER_REF_TABLE_BIT)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2965
  {
1 by brian
clean slate
2966
    outer_ref= 1;
2967
    cmp= -1;
2968
  }
2969
  if (field2->used_tables() & OUTER_REF_TABLE_BIT)
2970
  {
2971
    outer_ref= 1;
2972
    cmp++;
2973
  }
2974
  if (outer_ref)
2975
    return cmp;
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
2976
  JoinTable **idx= (JoinTable **) table_join_idx;
1 by brian
clean slate
2977
  cmp= idx[field2->field->table->tablenr]-idx[field1->field->table->tablenr];
2978
  return cmp < 0 ? -1 : (cmp ? 1 : 0);
2979
}
2980
2981
/**
2982
  Generate minimal set of simple equalities equivalent to a multiple equality.
2983
2984
    The function retrieves the fields of the multiple equality item
2985
    item_equal and  for each field f:
2986
    - if item_equal contains const it generates the equality f=const_item;
2987
    - otherwise, if f is not the first field, generates the equality
2988
      f=item_equal->get_first().
2989
    All generated equality are added to the cond conjunction.
2990
2991
  @param cond            condition to add the generated equality to
2992
  @param upper_levels    structure to access multiple equality of upper levels
2993
  @param item_equal      multiple equality to generate simple equality from
2994
2995
  @note
2996
    Before generating an equality function checks that it has not
2997
    been generated for multiple equalities of the upper levels.
2998
    E.g. for the following where condition
2999
    WHERE a=5 AND ((a=b AND b=c) OR  c>4)
3000
    the upper level AND condition will contain =(5,a),
3001
    while the lower level AND condition will contain =(5,a,b,c).
3002
    When splitting =(5,a,b,c) into a separate equality predicates
3003
    we should omit 5=a, as we have it already in the upper level.
3004
    The following where condition gives us a more complicated case:
3005
    WHERE t1.a=t2.b AND t3.c=t4.d AND (t2.b=t3.c OR t4.e>5 ...) AND ...
3006
    Given the tables are accessed in the order t1->t2->t3->t4 for
3007
    the selected query execution plan the lower level multiple
3008
    equality =(t1.a,t2.b,t3.c,t4.d) formally  should be converted to
3009
    t1.a=t2.b AND t1.a=t3.c AND t1.a=t4.d. But t1.a=t2.a will be
3010
    generated for the upper level. Also t3.c=t4.d will be generated there.
3011
    So only t1.a=t3.c should be left in the lower level.
3012
    If cond is equal to 0, then not more then one equality is generated
3013
    and a pointer to it is returned as the result of the function.
3014
3015
  @return
3016
    - The condition with generated simple equalities or
3017
    a pointer to the simple generated equality, if success.
3018
    - 0, otherwise.
3019
*/
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
3020
static Item *eliminate_item_equal(COND *cond, COND_EQUAL *upper_levels, Item_equal *item_equal)
1 by brian
clean slate
3021
{
3022
  List<Item> eq_list;
3023
  Item_func_eq *eq_item= 0;
3024
  if (((Item *) item_equal)->const_item() && !item_equal->val_int())
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3025
    return new Item_int((int64_t) 0,1);
1 by brian
clean slate
3026
  Item *item_const= item_equal->get_const();
3027
  Item_equal_iterator it(*item_equal);
3028
  Item *head;
3029
  if (item_const)
3030
    head= item_const;
3031
  else
3032
  {
3033
    head= item_equal->get_first();
3034
    it++;
3035
  }
3036
  Item_field *item_field;
3037
  while ((item_field= it++))
3038
  {
3039
    Item_equal *upper= item_field->find_item_equal(upper_levels);
3040
    Item_field *item= item_field;
3041
    if (upper)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3042
    {
1 by brian
clean slate
3043
      if (item_const && upper->get_const())
3044
        item= 0;
3045
      else
3046
      {
3047
        Item_equal_iterator li(*item_equal);
3048
        while ((item= li++) != item_field)
3049
        {
3050
          if (item->find_item_equal(upper_levels) == upper)
3051
            break;
3052
        }
3053
      }
3054
    }
3055
    if (item == item_field)
3056
    {
3057
      if (eq_item)
3058
        eq_list.push_back(eq_item);
3059
      eq_item= new Item_func_eq(item_field, head);
3060
      if (!eq_item)
3061
        return 0;
3062
      eq_item->set_cmp_func();
3063
      eq_item->quick_fix_field();
3064
   }
3065
  }
3066
3067
  if (!cond && !eq_list.head())
3068
  {
3069
    if (!eq_item)
152 by Brian Aker
longlong replacement
3070
      return new Item_int((int64_t) 1,1);
1 by brian
clean slate
3071
    return eq_item;
3072
  }
3073
3074
  if (eq_item)
3075
    eq_list.push_back(eq_item);
3076
  if (!cond)
3077
    cond= new Item_cond_and(eq_list);
3078
  else
3079
  {
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
3080
    assert(cond->type() == Item::COND_ITEM);
1 by brian
clean slate
3081
    ((Item_cond *) cond)->add_at_head(&eq_list);
3082
  }
3083
3084
  cond->quick_fix_field();
3085
  cond->update_used_tables();
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3086
1 by brian
clean slate
3087
  return cond;
3088
}
3089
3090
/**
3091
  Substitute every field reference in a condition by the best equal field
3092
  and eliminate all multiple equality predicates.
3093
3094
    The function retrieves the cond condition and for each encountered
3095
    multiple equality predicate it sorts the field references in it
3096
    according to the order of tables specified by the table_join_idx
3097
    parameter. Then it eliminates the multiple equality predicate it
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3098
    replacing it by the conjunction of simple equality predicates
1 by brian
clean slate
3099
    equating every field from the multiple equality to the first
3100
    field in it, or to the constant, if there is any.
3101
    After this the function retrieves all other conjuncted
3102
    predicates substitute every field reference by the field reference
3103
    to the first equal field or equal constant if there are any.
3104
  @param cond            condition to process
3105
  @param cond_equal      multiple equalities to take into consideration
3106
  @param table_join_idx  index to tables determining field preference
3107
3108
  @note
3109
    At the first glance full sort of fields in multiple equality
3110
    seems to be an overkill. Yet it's not the case due to possible
3111
    new fields in multiple equality item of lower levels. We want
3112
    the order in them to comply with the order of upper levels.
3113
3114
  @return
3115
    The transformed condition
3116
*/
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
3117
COND* substitute_for_best_equal_field(COND *cond, COND_EQUAL *cond_equal, void *table_join_idx)
1 by brian
clean slate
3118
{
3119
  Item_equal *item_equal;
3120
3121
  if (cond->type() == Item::COND_ITEM)
3122
  {
3123
    List<Item> *cond_list= ((Item_cond*) cond)->argument_list();
3124
3125
    bool and_level= ((Item_cond*) cond)->functype() ==
3126
                      Item_func::COND_AND_FUNC;
3127
    if (and_level)
3128
    {
3129
      cond_equal= &((Item_cond_and *) cond)->cond_equal;
3130
      cond_list->disjoin((List<Item> *) &cond_equal->current_level);
3131
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3132
      List_iterator_fast<Item_equal> it(cond_equal->current_level);
1 by brian
clean slate
3133
      while ((item_equal= it++))
3134
      {
3135
        item_equal->sort(&compare_fields_by_table_order, table_join_idx);
3136
      }
3137
    }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3138
1 by brian
clean slate
3139
    List_iterator<Item> li(*cond_list);
3140
    Item *item;
3141
    while ((item= li++))
3142
    {
3143
      Item *new_item =substitute_for_best_equal_field(item, cond_equal,
3144
                                                      table_join_idx);
3145
      /*
3146
        This works OK with PS/SP re-execution as changes are made to
3147
        the arguments of AND/OR items only
3148
      */
3149
      if (new_item != item)
3150
        li.replace(new_item);
3151
    }
3152
3153
    if (and_level)
3154
    {
3155
      List_iterator_fast<Item_equal> it(cond_equal->current_level);
3156
      while ((item_equal= it++))
3157
      {
3158
        cond= eliminate_item_equal(cond, cond_equal->upper_levels, item_equal);
3159
        // This occurs when eliminate_item_equal() founds that cond is
3160
        // always false and substitutes it with Item_int 0.
3161
        // Due to this, value of item_equal will be 0, so just return it.
3162
        if (cond->type() != Item::COND_ITEM)
3163
          break;
3164
      }
3165
    }
3166
    if (cond->type() == Item::COND_ITEM &&
3167
        !((Item_cond*)cond)->argument_list()->elements)
205 by Brian Aker
uint32 -> uin32_t
3168
      cond= new Item_int((int32_t)cond->val_bool());
1 by brian
clean slate
3169
3170
  }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3171
  else if (cond->type() == Item::FUNC_ITEM &&
1 by brian
clean slate
3172
           ((Item_cond*) cond)->functype() == Item_func::MULT_EQUAL_FUNC)
3173
  {
3174
    item_equal= (Item_equal *) cond;
3175
    item_equal->sort(&compare_fields_by_table_order, table_join_idx);
3176
    if (cond_equal && cond_equal->current_level.head() == item_equal)
3177
      cond_equal= 0;
3178
    return eliminate_item_equal(0, cond_equal, item_equal);
3179
  }
3180
  else
3181
    cond->transform(&Item::replace_equal_field, 0);
3182
  return cond;
3183
}
3184
3185
/**
3186
  Check appearance of new constant items in multiple equalities
3187
  of a condition after reading a constant table.
3188
3189
    The function retrieves the cond condition and for each encountered
3190
    multiple equality checks whether new constants have appeared after
3191
    reading the constant (single row) table tab. If so it adjusts
3192
    the multiple equality appropriately.
3193
3194
  @param cond       condition whose multiple equalities are to be checked
3195
  @param table      constant table that has been read
3196
*/
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
3197
static void update_const_equal_items(COND *cond, JoinTable *tab)
1 by brian
clean slate
3198
{
3199
  if (!(cond->used_tables() & tab->table->map))
3200
    return;
3201
3202
  if (cond->type() == Item::COND_ITEM)
3203
  {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3204
    List<Item> *cond_list= ((Item_cond*) cond)->argument_list();
1 by brian
clean slate
3205
    List_iterator_fast<Item> li(*cond_list);
3206
    Item *item;
3207
    while ((item= li++))
3208
      update_const_equal_items(item, tab);
3209
  }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3210
  else if (cond->type() == Item::FUNC_ITEM &&
1 by brian
clean slate
3211
           ((Item_cond*) cond)->functype() == Item_func::MULT_EQUAL_FUNC)
3212
  {
3213
    Item_equal *item_equal= (Item_equal *) cond;
3214
    bool contained_const= item_equal->get_const() != NULL;
3215
    item_equal->update_const();
3216
    if (!contained_const && item_equal->get_const())
3217
    {
3218
      /* Update keys for range analysis */
3219
      Item_equal_iterator it(*item_equal);
3220
      Item_field *item_field;
3221
      while ((item_field= it++))
3222
      {
3223
        Field *field= item_field->field;
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
3224
        JoinTable *stat= field->table->reginfo.join_tab;
1 by brian
clean slate
3225
        key_map possible_keys= field->key_start;
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
3226
        possible_keys&= field->table->keys_in_use_for_query;
3227
        stat[0].const_keys|= possible_keys;
1 by brian
clean slate
3228
3229
        /*
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3230
          For each field in the multiple equality (for which we know that it
3231
          is a constant) we have to find its corresponding key part, and set
1 by brian
clean slate
3232
          that key part in const_key_parts.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3233
        */
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
3234
        if (possible_keys.any())
1 by brian
clean slate
3235
        {
779.3.10 by Monty Taylor
Turned on -Wshadow.
3236
          Table *field_tab= field->table;
1089.1.8 by Brian Aker
Shuffled around a few structures.
3237
          KeyUse *use;
779.3.10 by Monty Taylor
Turned on -Wshadow.
3238
          for (use= stat->keyuse; use && use->table == field_tab; use++)
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
3239
            if (possible_keys.test(use->key) &&
779.3.10 by Monty Taylor
Turned on -Wshadow.
3240
                field_tab->key_info[use->key].key_part[use->keypart].field ==
1 by brian
clean slate
3241
                field)
779.3.10 by Monty Taylor
Turned on -Wshadow.
3242
              field_tab->const_key_parts[use->key]|= use->keypart_map;
1 by brian
clean slate
3243
        }
3244
      }
3245
    }
3246
  }
3247
}
3248
3249
/*
3250
  change field = field to field = const for each found field = const in the
3251
  and_level
3252
*/
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
3253
static void change_cond_ref_to_const(Session *session,
1046.2.1 by Nathan Williams
Changed all instances of I_List<COND_CMP> to vector<COND_CMP>
3254
                                     vector<COND_CMP>& save_list,
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
3255
                                     Item *and_father,
3256
                                     Item *cond,
3257
                                     Item *field,
3258
                                     Item *value)
1 by brian
clean slate
3259
{
3260
  if (cond->type() == Item::COND_ITEM)
3261
  {
1046.2.1 by Nathan Williams
Changed all instances of I_List<COND_CMP> to vector<COND_CMP>
3262
    bool and_level= ((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC;
1 by brian
clean slate
3263
    List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
3264
    Item *item;
3265
    while ((item=li++))
1046.2.1 by Nathan Williams
Changed all instances of I_List<COND_CMP> to vector<COND_CMP>
3266
      change_cond_ref_to_const(session, save_list, and_level ? cond : item, item, field, value);
1 by brian
clean slate
3267
    return;
3268
  }
3269
  if (cond->eq_cmp_result() == Item::COND_OK)
3270
    return;					// Not a boolean function
3271
3272
  Item_bool_func2 *func=  (Item_bool_func2*) cond;
3273
  Item **args= func->arguments();
3274
  Item *left_item=  args[0];
3275
  Item *right_item= args[1];
3276
  Item_func::Functype functype=  func->functype();
3277
3278
  if (right_item->eq(field,0) && left_item != value &&
3279
      right_item->cmp_context == field->cmp_context &&
3280
      (left_item->result_type() != STRING_RESULT ||
3281
       value->result_type() != STRING_RESULT ||
3282
       left_item->collation.collation == value->collation.collation))
3283
  {
3284
    Item *tmp=value->clone_item();
3285
    tmp->collation.set(right_item->collation);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3286
1 by brian
clean slate
3287
    if (tmp)
3288
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
3289
      session->change_item_tree(args + 1, tmp);
1 by brian
clean slate
3290
      func->update_used_tables();
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
3291
      if ((functype == Item_func::EQ_FUNC || functype == Item_func::EQUAL_FUNC) &&
3292
	        and_father != cond && 
3293
          ! left_item->const_item())
1 by brian
clean slate
3294
      {
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
3295
        cond->marker=1;
1046.2.1 by Nathan Williams
Changed all instances of I_List<COND_CMP> to vector<COND_CMP>
3296
        save_list.push_back( COND_CMP(and_father, func) );
1 by brian
clean slate
3297
      }
3298
      func->set_cmp_func();
3299
    }
3300
  }
3301
  else if (left_item->eq(field,0) && right_item != value &&
3302
           left_item->cmp_context == field->cmp_context &&
3303
           (right_item->result_type() != STRING_RESULT ||
3304
            value->result_type() != STRING_RESULT ||
3305
            right_item->collation.collation == value->collation.collation))
3306
  {
3307
    Item *tmp= value->clone_item();
3308
    tmp->collation.set(left_item->collation);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3309
1 by brian
clean slate
3310
    if (tmp)
3311
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
3312
      session->change_item_tree(args, tmp);
1 by brian
clean slate
3313
      value= tmp;
3314
      func->update_used_tables();
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
3315
      if ((functype == Item_func::EQ_FUNC || functype == Item_func::EQUAL_FUNC) &&
3316
          and_father != cond && 
3317
          ! right_item->const_item())
1 by brian
clean slate
3318
      {
3319
        args[0]= args[1];                       // For easy check
520.1.22 by Brian Aker
Second pass of thd cleanup
3320
        session->change_item_tree(args + 1, value);
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
3321
        cond->marker=1;
1046.2.1 by Nathan Williams
Changed all instances of I_List<COND_CMP> to vector<COND_CMP>
3322
        save_list.push_back( COND_CMP(and_father, func) );
1 by brian
clean slate
3323
      }
3324
      func->set_cmp_func();
3325
    }
3326
  }
3327
}
3328
3329
/**
3330
  Remove additional condition inserted by IN/ALL/ANY transformation.
3331
3332
  @param conds   condition for processing
3333
3334
  @return
3335
    new conditions
3336
*/
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
3337
Item *remove_additional_cond(Item* conds)
1 by brian
clean slate
3338
{
3339
  if (conds->name == in_additional_cond)
3340
    return 0;
3341
  if (conds->type() == Item::COND_ITEM)
3342
  {
3343
    Item_cond *cnd= (Item_cond*) conds;
3344
    List_iterator<Item> li(*(cnd->argument_list()));
3345
    Item *item;
3346
    while ((item= li++))
3347
    {
3348
      if (item->name == in_additional_cond)
3349
      {
3350
	li.remove();
3351
	if (cnd->argument_list()->elements == 1)
3352
	  return cnd->argument_list()->head();
3353
	return conds;
3354
      }
3355
    }
3356
  }
3357
  return conds;
3358
}
3359
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
3360
static void propagate_cond_constants(Session *session, 
1046.2.1 by Nathan Williams
Changed all instances of I_List<COND_CMP> to vector<COND_CMP>
3361
                                     vector<COND_CMP>& save_list, 
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
3362
                                     COND *and_father, 
3363
                                     COND *cond)
1 by brian
clean slate
3364
{
3365
  if (cond->type() == Item::COND_ITEM)
3366
  {
1046.2.2 by Nathan Williams
Fixed a . vs -> typo.
3367
    bool and_level= ((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC;
1 by brian
clean slate
3368
    List_iterator_fast<Item> li(*((Item_cond*) cond)->argument_list());
3369
    Item *item;
1046.2.1 by Nathan Williams
Changed all instances of I_List<COND_CMP> to vector<COND_CMP>
3370
    vector<COND_CMP> save;
1 by brian
clean slate
3371
    while ((item=li++))
3372
    {
1046.2.1 by Nathan Williams
Changed all instances of I_List<COND_CMP> to vector<COND_CMP>
3373
      propagate_cond_constants(session, save, and_level ? cond : item, item);
1 by brian
clean slate
3374
    }
3375
    if (and_level)
1046.2.1 by Nathan Williams
Changed all instances of I_List<COND_CMP> to vector<COND_CMP>
3376
    {
3377
      // Handle other found items
3378
      for (vector<COND_CMP>::iterator iter= save.begin(); iter != save.end(); ++iter)
1 by brian
clean slate
3379
      {
1046.2.2 by Nathan Williams
Fixed a . vs -> typo.
3380
        Item **args= iter->cmp_func->arguments();
1 by brian
clean slate
3381
        if (!args[0]->const_item())
1046.2.1 by Nathan Williams
Changed all instances of I_List<COND_CMP> to vector<COND_CMP>
3382
        {
3383
          change_cond_ref_to_const( session, save, iter->and_level,
3384
                                    iter->and_level, args[0], args[1] );
3385
        }
1 by brian
clean slate
3386
      }
3387
    }
3388
  }
3389
  else if (and_father != cond && !cond->marker)		// In a AND group
3390
  {
3391
    if (cond->type() == Item::FUNC_ITEM &&
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
3392
        (((Item_func*) cond)->functype() == Item_func::EQ_FUNC ||
3393
        ((Item_func*) cond)->functype() == Item_func::EQUAL_FUNC))
1 by brian
clean slate
3394
    {
3395
      Item_func_eq *func=(Item_func_eq*) cond;
3396
      Item **args= func->arguments();
3397
      bool left_const= args[0]->const_item();
3398
      bool right_const= args[1]->const_item();
3399
      if (!(left_const && right_const) &&
3400
          args[0]->result_type() == args[1]->result_type())
3401
      {
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
3402
        if (right_const)
3403
        {
3404
                resolve_const_item(session, &args[1], args[0]);
3405
          func->update_used_tables();
3406
                change_cond_ref_to_const(session, save_list, and_father, and_father,
3407
                                        args[0], args[1]);
3408
        }
3409
        else if (left_const)
3410
        {
3411
                resolve_const_item(session, &args[0], args[1]);
3412
          func->update_used_tables();
3413
                change_cond_ref_to_const(session, save_list, and_father, and_father,
3414
                                        args[1], args[0]);
3415
        }
1 by brian
clean slate
3416
      }
3417
    }
3418
  }
3419
}
3420
3421
/**
3422
  Check interleaving with an inner tables of an outer join for
3423
  extension table.
3424
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3425
    Check if table next_tab can be added to current partial join order, and
1 by brian
clean slate
3426
    if yes, record that it has been added.
3427
3428
    The function assumes that both current partial join order and its
3429
    extension with next_tab are valid wrt table dependencies.
3430
3431
  @verbatim
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3432
     IMPLEMENTATION
327.2.3 by Brian Aker
Refactoring of class Table
3433
       LIMITATIONS ON JOIN order_st
1 by brian
clean slate
3434
         The nested [outer] joins executioner algorithm imposes these limitations
3435
         on join order:
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3436
         1. "Outer tables first" -  any "outer" table must be before any
1 by brian
clean slate
3437
             corresponding "inner" table.
3438
         2. "No interleaving" - tables inside a nested join must form a continuous
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3439
            sequence in join order (i.e. the sequence must not be interrupted by
1 by brian
clean slate
3440
            tables that are outside of this nested join).
3441
3442
         #1 is checked elsewhere, this function checks #2 provided that #1 has
3443
         been already checked.
3444
3445
       WHY NEED NON-INTERLEAVING
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3446
         Consider an example:
1 by brian
clean slate
3447
3448
           select * from t0 join t1 left join (t2 join t3) on cond1
3449
3450
         The join order "t1 t2 t0 t3" is invalid:
3451
3452
         table t0 is outside of the nested join, so WHERE condition for t0 is
3453
         attached directly to t0 (without triggers, and it may be used to access
3454
         t0). Applying WHERE(t0) to (t2,t0,t3) record is invalid as we may miss
3455
         combinations of (t1, t2, t3) that satisfy condition cond1, and produce a
3456
         null-complemented (t1, t2.NULLs, t3.NULLs) row, which should not have
3457
         been produced.
3458
3459
         If table t0 is not between t2 and t3, the problem doesn't exist:
3460
          If t0 is located after (t2,t3), WHERE(t0) is applied after nested join
3461
           processing has finished.
3462
          If t0 is located before (t2,t3), predicates like WHERE_cond(t0, t2) are
3463
           wrapped into condition triggers, which takes care of correct nested
3464
           join processing.
3465
3466
       HOW IT IS IMPLEMENTED
3467
         The limitations on join order can be rephrased as follows: for valid
3468
         join order one must be able to:
3469
           1. write down the used tables in the join order on one line.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3470
           2. for each nested join, put one '(' and one ')' on the said line
1 by brian
clean slate
3471
           3. write "LEFT JOIN" and "ON (...)" where appropriate
3472
           4. get a query equivalent to the query we're trying to execute.
3473
3474
         Calls to check_interleaving_with_nj() are equivalent to writing the
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3475
         above described line from left to right.
3476
         A single check_interleaving_with_nj(A,B) call is equivalent to writing
1 by brian
clean slate
3477
         table B and appropriate brackets on condition that table A and
3478
         appropriate brackets is the last what was written. Graphically the
3479
         transition is as follows:
3480
3481
                              +---- current position
3482
                              |
3483
             ... last_tab ))) | ( next_tab )  )..) | ...
3484
                                X          Y   Z   |
3485
                                                   +- need to move to this
3486
                                                      position.
3487
3488
         Notes about the position:
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3489
           The caller guarantees that there is no more then one X-bracket by
3490
           checking "!(remaining_tables & s->dependent)" before calling this
1 by brian
clean slate
3491
           function. X-bracket may have a pair in Y-bracket.
3492
3493
         When "writing" we store/update this auxilary info about the current
3494
         position:
3495
          1. join->cur_embedding_map - bitmap of pairs of brackets (aka nested
3496
             joins) we've opened but didn't close.
327.2.4 by Brian Aker
Refactoring table.h
3497
          2. {each nested_join_st structure not simplified away}->counter - number
1 by brian
clean slate
3498
             of this nested join's children that have already been added to to
3499
             the partial join order.
3500
  @endverbatim
3501
3502
  @param join       Join being processed
3503
  @param last_tab   Last table in current partial join order (this function is
3504
                    not called for empty partial join orders)
3505
  @param next_tab   Table we're going to extend the current partial join with
3506
3507
  @retval
55 by brian
Update for using real bool types.
3508
    false  Join order extended, nested joins info about current join
1 by brian
clean slate
3509
    order (see NOTE section) updated.
3510
  @retval
55 by brian
Update for using real bool types.
3511
    true   Requested join order extension not allowed.
1 by brian
clean slate
3512
*/
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
3513
bool check_interleaving_with_nj(JoinTable *last_tab, JoinTable *next_tab)
1 by brian
clean slate
3514
{
327.2.4 by Brian Aker
Refactoring table.h
3515
  TableList *next_emb= next_tab->table->pos_in_table_list->embedding;
1 by brian
clean slate
3516
  JOIN *join= last_tab->join;
3517
1100.4.1 by Padraig O'Sullivan
Modified the nested_join_map typedef to be std::bitset instead of uint64_t.
3518
  if ((join->cur_embedding_map & ~next_tab->embedding_map).any())
1 by brian
clean slate
3519
  {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3520
    /*
1 by brian
clean slate
3521
      next_tab is outside of the "pair of brackets" we're currently in.
3522
      Cannot add it.
3523
    */
55 by brian
Update for using real bool types.
3524
    return true;
1 by brian
clean slate
3525
  }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3526
1 by brian
clean slate
3527
  /*
3528
    Do update counters for "pairs of brackets" that we've left (marked as
3529
    X,Y,Z in the above picture)
3530
  */
3531
  for (;next_emb; next_emb= next_emb->embedding)
3532
  {
3533
    next_emb->nested_join->counter_++;
3534
    if (next_emb->nested_join->counter_ == 1)
3535
    {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3536
      /*
1 by brian
clean slate
3537
        next_emb is the first table inside a nested join we've "entered". In
3538
        the picture above, we're looking at the 'X' bracket. Don't exit yet as
3539
        X bracket might have Y pair bracket.
3540
      */
3541
      join->cur_embedding_map |= next_emb->nested_join->nj_map;
3542
    }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3543
1 by brian
clean slate
3544
    if (next_emb->nested_join->join_list.elements !=
3545
        next_emb->nested_join->counter_)
3546
      break;
3547
3548
    /*
3549
      We're currently at Y or Z-bracket as depicted in the above picture.
3550
      Mark that we've left it and continue walking up the brackets hierarchy.
3551
    */
3552
    join->cur_embedding_map &= ~next_emb->nested_join->nj_map;
3553
  }
55 by brian
Update for using real bool types.
3554
  return false;
1 by brian
clean slate
3555
}
3556
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
3557
COND *optimize_cond(JOIN *join, COND *conds, List<TableList> *join_list, Item::cond_result *cond_value)
1 by brian
clean slate
3558
{
520.1.22 by Brian Aker
Second pass of thd cleanup
3559
  Session *session= join->session;
1 by brian
clean slate
3560
3561
  if (!conds)
3562
    *cond_value= Item::COND_TRUE;
3563
  else
3564
  {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3565
    /*
1 by brian
clean slate
3566
      Build all multiple equality predicates and eliminate equality
3567
      predicates that can be inferred from these multiple equalities.
3568
      For each reference of a field included into a multiple equality
3569
      that occurs in a function set a pointer to the multiple equality
3570
      predicate. Substitute a constant instead of this field if the
3571
      multiple equality contains a constant.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3572
    */
520.1.22 by Brian Aker
Second pass of thd cleanup
3573
    conds= build_equal_items(join->session, conds, NULL, join_list,
1 by brian
clean slate
3574
                             &join->cond_equal);
3575
3576
    /* change field = field to field = const for each found field = const */
1046.2.2 by Nathan Williams
Fixed a . vs -> typo.
3577
    vector<COND_CMP> temp;
3578
    propagate_cond_constants(session, temp, conds, conds);
1 by brian
clean slate
3579
    /*
3580
      Remove all instances of item == item
3581
      Remove all and-levels where CONST item != CONST item
3582
    */
520.1.22 by Brian Aker
Second pass of thd cleanup
3583
    conds= remove_eq_conds(session, conds, cond_value) ;
1 by brian
clean slate
3584
  }
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
3585
  return(conds);
1 by brian
clean slate
3586
}
3587
3588
/**
3589
  Remove const and eq items.
3590
3591
  @return
3592
    Return new item, or NULL if no condition @n
3593
    cond_value is set to according:
3594
    - COND_OK     : query is possible (field = constant)
3595
    - COND_TRUE   : always true	( 1 = 1 )
3596
    - COND_FALSE  : always false	( 1 = 2 )
3597
*/
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
3598
COND *remove_eq_conds(Session *session, COND *cond, Item::cond_result *cond_value)
1 by brian
clean slate
3599
{
3600
  if (cond->type() == Item::COND_ITEM)
3601
  {
873.1.7 by Jay Pipes
Fixes Field_datetime::store(NUMBER) to throw an error when invalid
3602
    bool and_level= (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC);
3603
1 by brian
clean slate
3604
    List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
3605
    Item::cond_result tmp_cond_value;
873.1.7 by Jay Pipes
Fixes Field_datetime::store(NUMBER) to throw an error when invalid
3606
    bool should_fix_fields= false;
1 by brian
clean slate
3607
873.1.7 by Jay Pipes
Fixes Field_datetime::store(NUMBER) to throw an error when invalid
3608
    *cond_value= Item::COND_UNDEF;
1 by brian
clean slate
3609
    Item *item;
873.1.7 by Jay Pipes
Fixes Field_datetime::store(NUMBER) to throw an error when invalid
3610
    while ((item= li++))
1 by brian
clean slate
3611
    {
873.1.7 by Jay Pipes
Fixes Field_datetime::store(NUMBER) to throw an error when invalid
3612
      Item *new_item= remove_eq_conds(session, item, &tmp_cond_value);
3613
      if (! new_item)
3614
	      li.remove();
1 by brian
clean slate
3615
      else if (item != new_item)
3616
      {
873.1.7 by Jay Pipes
Fixes Field_datetime::store(NUMBER) to throw an error when invalid
3617
        li.replace(new_item);
3618
        should_fix_fields= true;
1 by brian
clean slate
3619
      }
3620
      if (*cond_value == Item::COND_UNDEF)
873.1.7 by Jay Pipes
Fixes Field_datetime::store(NUMBER) to throw an error when invalid
3621
	      *cond_value= tmp_cond_value;
3622
3623
      switch (tmp_cond_value) 
3624
      {
3625
        case Item::COND_OK:			/* Not true or false */
3626
          if (and_level || (*cond_value == Item::COND_FALSE))
3627
            *cond_value= tmp_cond_value;
3628
          break;
3629
        case Item::COND_FALSE:
3630
          if (and_level)
3631
          {
3632
            *cond_value= tmp_cond_value;
3633
            return (COND *) NULL;			/* Always false */
3634
          }
3635
          break;
3636
        case Item::COND_TRUE:
3637
          if (! and_level)
3638
          {
3639
            *cond_value= tmp_cond_value;
3640
            return (COND *) NULL;			/* Always true */
3641
          }
3642
          break;
3643
        case Item::COND_UNDEF:			/* Impossible */
3644
          break; /* purecov: deadcode */
1 by brian
clean slate
3645
      }
3646
    }
873.1.7 by Jay Pipes
Fixes Field_datetime::store(NUMBER) to throw an error when invalid
3647
1 by brian
clean slate
3648
    if (should_fix_fields)
3649
      cond->update_used_tables();
3650
873.1.7 by Jay Pipes
Fixes Field_datetime::store(NUMBER) to throw an error when invalid
3651
    if (! ((Item_cond*) cond)->argument_list()->elements || *cond_value != Item::COND_OK)
3652
      return (COND*) NULL;
3653
1 by brian
clean slate
3654
    if (((Item_cond*) cond)->argument_list()->elements == 1)
873.1.7 by Jay Pipes
Fixes Field_datetime::store(NUMBER) to throw an error when invalid
3655
    {						
3656
      /* Argument list contains only one element, so reduce it so a single item, then remove list */
1 by brian
clean slate
3657
      item= ((Item_cond*) cond)->argument_list()->head();
3658
      ((Item_cond*) cond)->argument_list()->empty();
3659
      return item;
3660
    }
3661
  }
873.1.7 by Jay Pipes
Fixes Field_datetime::store(NUMBER) to throw an error when invalid
3662
  else if (cond->type() == Item::FUNC_ITEM && ((Item_func*) cond)->functype() == Item_func::ISNULL_FUNC)
1 by brian
clean slate
3663
  {
3664
    /*
3665
      Handles this special case for some ODBC applications:
3666
      The are requesting the row that was just updated with a auto_increment
3667
      value with this construct:
3668
3669
      SELECT * from table_name where auto_increment_column IS NULL
3670
      This will be changed to:
3671
      SELECT * from table_name where auto_increment_column = LAST_INSERT_ID
3672
    */
3673
873.1.7 by Jay Pipes
Fixes Field_datetime::store(NUMBER) to throw an error when invalid
3674
    Item_func_isnull *func= (Item_func_isnull*) cond;
1 by brian
clean slate
3675
    Item **args= func->arguments();
3676
    if (args[0]->type() == Item::FIELD_ITEM)
3677
    {
873.1.7 by Jay Pipes
Fixes Field_datetime::store(NUMBER) to throw an error when invalid
3678
      Field *field= ((Item_field*) args[0])->field;
3679
      if (field->flags & AUTO_INCREMENT_FLAG 
3680
          && ! field->table->maybe_null 
3681
          && session->options & OPTION_AUTO_IS_NULL
3682
          && (
3683
            session->first_successful_insert_id_in_prev_stmt > 0 
3684
            && session->substitute_null_with_insert_id
3685
            )
3686
          )
1 by brian
clean slate
3687
      {
873.1.7 by Jay Pipes
Fixes Field_datetime::store(NUMBER) to throw an error when invalid
3688
        COND *new_cond;
3689
        if ((new_cond= new Item_func_eq(args[0], new Item_int("last_insert_id()",
3690
                                                          session->read_first_successful_insert_id_in_prev_stmt(),
3691
                                                          MY_INT64_NUM_DECIMAL_DIGITS))))
3692
        {
3693
          cond= new_cond;
1 by brian
clean slate
3694
          /*
3695
            Item_func_eq can't be fixed after creation so we do not check
3696
            cond->fixed, also it do not need tables so we use 0 as second
3697
            argument.
3698
          */
873.1.7 by Jay Pipes
Fixes Field_datetime::store(NUMBER) to throw an error when invalid
3699
          cond->fix_fields(session, &cond);
3700
        }
1 by brian
clean slate
3701
        /*
3702
          IS NULL should be mapped to LAST_INSERT_ID only for first row, so
3703
          clear for next row
3704
        */
520.1.22 by Brian Aker
Second pass of thd cleanup
3705
        session->substitute_null_with_insert_id= false;
1 by brian
clean slate
3706
      }
873.1.7 by Jay Pipes
Fixes Field_datetime::store(NUMBER) to throw an error when invalid
3707
#ifdef NOTDEFINED
1 by brian
clean slate
3708
      /* fix to replace 'NULL' dates with '0' (shreeve@uci.edu) */
873.1.7 by Jay Pipes
Fixes Field_datetime::store(NUMBER) to throw an error when invalid
3709
      else if (
3710
          ((field->type() == DRIZZLE_TYPE_DATE) || (field->type() == DRIZZLE_TYPE_DATETIME)) 
3711
          && (field->flags & NOT_NULL_FLAG) 
3712
          && ! field->table->maybe_null)
1 by brian
clean slate
3713
      {
873.1.7 by Jay Pipes
Fixes Field_datetime::store(NUMBER) to throw an error when invalid
3714
        COND *new_cond;
3715
        if ((new_cond= new Item_func_eq(args[0],new Item_int("0", 0, 2))))
3716
        {
3717
          cond= new_cond;
1 by brian
clean slate
3718
          /*
3719
            Item_func_eq can't be fixed after creation so we do not check
3720
            cond->fixed, also it do not need tables so we use 0 as second
3721
            argument.
3722
          */
873.1.7 by Jay Pipes
Fixes Field_datetime::store(NUMBER) to throw an error when invalid
3723
          cond->fix_fields(session, &cond);
3724
        }
1 by brian
clean slate
3725
      }
873.1.7 by Jay Pipes
Fixes Field_datetime::store(NUMBER) to throw an error when invalid
3726
#endif /* NOTDEFINED */
1 by brian
clean slate
3727
    }
3728
    if (cond->const_item())
3729
    {
3730
      *cond_value= eval_const_cond(cond) ? Item::COND_TRUE : Item::COND_FALSE;
873.1.7 by Jay Pipes
Fixes Field_datetime::store(NUMBER) to throw an error when invalid
3731
      return (COND *) NULL;
1 by brian
clean slate
3732
    }
3733
  }
3734
  else if (cond->const_item() && !cond->is_expensive())
3735
  /*
3736
    TODO:
3737
    Excluding all expensive functions is too restritive we should exclude only
3738
    materialized IN because it is created later than this phase, and cannot be
3739
    evaluated at this point.
3740
    The condition should be something as (need to fix member access):
3741
      !(cond->type() == Item::FUNC_ITEM &&
3742
        ((Item_func*)cond)->func_name() == "<in_optimizer>" &&
3743
        ((Item_in_optimizer*)cond)->is_expensive()))
3744
  */
3745
  {
3746
    *cond_value= eval_const_cond(cond) ? Item::COND_TRUE : Item::COND_FALSE;
873.1.7 by Jay Pipes
Fixes Field_datetime::store(NUMBER) to throw an error when invalid
3747
    return (COND *) NULL;
1 by brian
clean slate
3748
  }
3749
  else if ((*cond_value= cond->eq_cmp_result()) != Item::COND_OK)
873.1.7 by Jay Pipes
Fixes Field_datetime::store(NUMBER) to throw an error when invalid
3750
  {						
3751
    /* boolan compare function */
1 by brian
clean slate
3752
    Item *left_item=	((Item_func*) cond)->arguments()[0];
3753
    Item *right_item= ((Item_func*) cond)->arguments()[1];
3754
    if (left_item->eq(right_item,1))
3755
    {
873.1.7 by Jay Pipes
Fixes Field_datetime::store(NUMBER) to throw an error when invalid
3756
      if (!left_item->maybe_null || ((Item_func*) cond)->functype() == Item_func::EQUAL_FUNC)
3757
	      return (COND*) NULL;			/* Comparison of identical items */
1 by brian
clean slate
3758
    }
3759
  }
873.1.7 by Jay Pipes
Fixes Field_datetime::store(NUMBER) to throw an error when invalid
3760
  *cond_value= Item::COND_OK;
3761
  return cond;					/* Point at next and return into recursion */
1 by brian
clean slate
3762
}
3763
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3764
/*
1 by brian
clean slate
3765
  Check if equality can be used in removing components of GROUP BY/DISTINCT
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3766
1 by brian
clean slate
3767
  SYNOPSIS
3768
    test_if_equality_guarantees_uniqueness()
3769
      l          the left comparison argument (a field if any)
3770
      r          the right comparison argument (a const of any)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3771
3772
  DESCRIPTION
3773
    Checks if an equality predicate can be used to take away
3774
    DISTINCT/GROUP BY because it is known to be true for exactly one
1 by brian
clean slate
3775
    distinct value (e.g. <expr> == <const>).
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3776
    Arguments must be of the same type because e.g.
3777
    <string_field> = <int_const> may match more than 1 distinct value from
3778
    the column.
3779
    We must take into consideration and the optimization done for various
1 by brian
clean slate
3780
    string constants when compared to dates etc (see Item_int_with_ref) as
3781
    well as the collation of the arguments.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3782
3783
  RETURN VALUE
55 by brian
Update for using real bool types.
3784
    true    can be used
3785
    false   cannot be used
1 by brian
clean slate
3786
*/
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
3787
static bool test_if_equality_guarantees_uniqueness(Item *l, Item *r)
1 by brian
clean slate
3788
{
3789
  return r->const_item() &&
3790
    /* elements must be compared as dates */
3791
     (Arg_comparator::can_compare_as_dates(l, r, 0) ||
3792
      /* or of the same result type */
3793
      (r->result_type() == l->result_type() &&
3794
       /* and must have the same collation if compared as strings */
3795
       (l->result_type() != STRING_RESULT ||
3796
        l->collation.collation == r->collation.collation)));
3797
}
3798
3799
/**
55 by brian
Update for using real bool types.
3800
  Return true if the item is a const value in all the WHERE clause.
1 by brian
clean slate
3801
*/
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
3802
bool const_expression_in_where(COND *cond, Item *comp_item, Item **const_item)
1 by brian
clean slate
3803
{
3804
  if (cond->type() == Item::COND_ITEM)
3805
  {
3806
    bool and_level= (((Item_cond*) cond)->functype()
3807
		     == Item_func::COND_AND_FUNC);
3808
    List_iterator_fast<Item> li(*((Item_cond*) cond)->argument_list());
3809
    Item *item;
3810
    while ((item=li++))
3811
    {
3812
      bool res=const_expression_in_where(item, comp_item, const_item);
3813
      if (res)					// Is a const value
3814
      {
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
3815
        if (and_level)
3816
          return 1;
1 by brian
clean slate
3817
      }
3818
      else if (!and_level)
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
3819
        return 0;
1 by brian
clean slate
3820
    }
3821
    return and_level ? 0 : 1;
3822
  }
3823
  else if (cond->eq_cmp_result() != Item::COND_OK)
3824
  {						// boolan compare function
3825
    Item_func* func= (Item_func*) cond;
3826
    if (func->functype() != Item_func::EQUAL_FUNC &&
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
3827
	      func->functype() != Item_func::EQ_FUNC)
1 by brian
clean slate
3828
      return 0;
3829
    Item *left_item=	((Item_func*) cond)->arguments()[0];
3830
    Item *right_item= ((Item_func*) cond)->arguments()[1];
3831
    if (left_item->eq(comp_item,1))
3832
    {
3833
      if (test_if_equality_guarantees_uniqueness (left_item, right_item))
3834
      {
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
3835
        if (*const_item)
3836
          return right_item->eq(*const_item, 1);
3837
        *const_item=right_item;
3838
        return 1;
1 by brian
clean slate
3839
      }
3840
    }
3841
    else if (right_item->eq(comp_item,1))
3842
    {
3843
      if (test_if_equality_guarantees_uniqueness (right_item, left_item))
3844
      {
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
3845
        if (*const_item)
3846
          return left_item->eq(*const_item, 1);
3847
        *const_item=left_item;
3848
        return 1;
1 by brian
clean slate
3849
      }
3850
    }
3851
  }
3852
  return 0;
3853
}
3854
3855
/**
3856
  @details
3857
  Rows produced by a join sweep may end up in a temporary table or be sent
3858
  to a client. Setup the function of the nested loop join algorithm which
3859
  handles final fully constructed and matched records.
3860
3861
  @param join   join to setup the function for.
3862
3863
  @return
3864
    end_select function to use. This function can't fail.
3865
*/
3866
Next_select_func setup_end_select_func(JOIN *join)
3867
{
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
3868
  Table *table= join->tmp_table;
851 by Brian Aker
Class rewrite of Session (aka get all of the junk out)
3869
  Tmp_Table_Param *tmp_tbl= &join->tmp_table_param;
1 by brian
clean slate
3870
  Next_select_func end_select;
3871
3872
  /* Set up select_end */
3873
  if (table)
3874
  {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3875
    if (table->group && tmp_tbl->sum_func_count &&
1 by brian
clean slate
3876
        !tmp_tbl->precomputed_group_by)
3877
    {
3878
      if (table->s->keys)
3879
      {
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
3880
        end_select= end_update;
1 by brian
clean slate
3881
      }
3882
      else
3883
      {
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
3884
        end_select= end_unique_update;
1 by brian
clean slate
3885
      }
3886
    }
3887
    else if (join->sort_and_group && !tmp_tbl->precomputed_group_by)
3888
    {
3889
      end_select=end_write_group;
3890
    }
3891
    else
3892
    {
3893
      end_select=end_write;
3894
      if (tmp_tbl->precomputed_group_by)
3895
      {
3896
        /*
3897
          A preceding call to create_tmp_table in the case when loose
3898
          index scan is used guarantees that
851 by Brian Aker
Class rewrite of Session (aka get all of the junk out)
3899
          Tmp_Table_Param::items_to_copy has enough space for the group
1 by brian
clean slate
3900
          by functions. It is OK here to use memcpy since we copy
3901
          Item_sum pointers into an array of Item pointers.
3902
        */
3903
        memcpy(tmp_tbl->items_to_copy + tmp_tbl->func_count,
3904
               join->sum_funcs,
3905
               sizeof(Item*)*tmp_tbl->sum_func_count);
3906
        tmp_tbl->items_to_copy[tmp_tbl->func_count+tmp_tbl->sum_func_count]= 0;
3907
      }
3908
    }
3909
  }
3910
  else
3911
  {
3912
    if ((join->sort_and_group) &&
3913
        !tmp_tbl->precomputed_group_by)
3914
      end_select= end_send_group;
3915
    else
3916
      end_select= end_send;
3917
  }
3918
  return end_select;
3919
}
3920
3921
/**
3922
  Make a join of all tables and write it on socket or to table.
3923
3924
  @retval
3925
    0  if ok
3926
  @retval
3927
    1  if error is sent
3928
  @retval
3929
    -1  if error should be sent
3930
*/
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
3931
int do_select(JOIN *join, List<Item> *fields, Table *table)
1 by brian
clean slate
3932
{
3933
  int rc= 0;
3934
  enum_nested_loop_state error= NESTED_LOOP_OK;
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
3935
  JoinTable *join_tab= NULL;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3936
1 by brian
clean slate
3937
  join->tmp_table= table;			/* Save for easy recursion */
3938
  join->fields= fields;
3939
3940
  if (table)
3941
  {
398.1.10 by Monty Taylor
Actually removed VOID() this time.
3942
    table->file->extra(HA_EXTRA_WRITE_CACHE);
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
3943
    table->emptyRecord();
1 by brian
clean slate
3944
    if (table->group && join->tmp_table_param.sum_func_count &&
3945
        table->s->keys && !table->file->inited)
3946
      table->file->ha_index_init(0, 0);
3947
  }
3948
  /* Set up select_end */
3949
  Next_select_func end_select= setup_end_select_func(join);
3950
  if (join->tables)
3951
  {
3952
    join->join_tab[join->tables-1].next_select= end_select;
3953
3954
    join_tab=join->join_tab+join->const_tables;
3955
  }
3956
  join->send_records=0;
3957
  if (join->tables == join->const_tables)
3958
  {
3959
    /*
3960
      HAVING will be checked after processing aggregate functions,
3961
      But WHERE should checkd here (we alredy have read tables)
3962
    */
3963
    if (!join->conds || join->conds->val_int())
3964
    {
3965
      error= (*end_select)(join, 0, 0);
3966
      if (error == NESTED_LOOP_OK || error == NESTED_LOOP_QUERY_LIMIT)
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
3967
	      error= (*end_select)(join, 0, 1);
1 by brian
clean slate
3968
3969
      /*
3970
        If we don't go through evaluate_join_record(), do the counting
3971
        here.  join->send_records is increased on success in end_send(),
3972
        so we don't touch it here.
3973
      */
3974
      join->examined_rows++;
520.1.22 by Brian Aker
Second pass of thd cleanup
3975
      join->session->row_count++;
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
3976
      assert(join->examined_rows <= 1);
1 by brian
clean slate
3977
    }
3978
    else if (join->send_row_on_empty_set())
3979
    {
3980
      List<Item> *columns_list= fields;
3981
      rc= join->result->send_data(*columns_list);
3982
    }
3983
  }
3984
  else
3985
  {
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
3986
    assert(join->tables);
1 by brian
clean slate
3987
    error= sub_select(join,join_tab,0);
3988
    if (error == NESTED_LOOP_OK || error == NESTED_LOOP_NO_MORE_ROWS)
3989
      error= sub_select(join,join_tab,1);
3990
    if (error == NESTED_LOOP_QUERY_LIMIT)
3991
      error= NESTED_LOOP_OK;                    /* select_limit used */
3992
  }
3993
  if (error == NESTED_LOOP_NO_MORE_ROWS)
3994
    error= NESTED_LOOP_OK;
3995
3996
  if (error == NESTED_LOOP_OK)
3997
  {
3998
    /*
3999
      Sic: this branch works even if rc != 0, e.g. when
4000
      send_data above returns an error.
4001
    */
4002
    if (!table)					// If sending data to client
4003
    {
4004
      /*
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
4005
        The following will unlock all cursors if the command wasn't an
4006
        update command
1 by brian
clean slate
4007
      */
4008
      join->join_free();			// Unlock all cursors
4009
      if (join->result->send_eof())
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
4010
        rc= 1;                                  // Don't send error
1 by brian
clean slate
4011
    }
4012
  }
4013
  else
4014
    rc= -1;
4015
  if (table)
4016
  {
4017
    int tmp, new_errno= 0;
4018
    if ((tmp=table->file->extra(HA_EXTRA_NO_CACHE)))
4019
    {
4020
      new_errno= tmp;
4021
    }
4022
    if ((tmp=table->file->ha_index_or_rnd_end()))
4023
    {
4024
      new_errno= tmp;
4025
    }
4026
    if (new_errno)
4027
      table->file->print_error(new_errno,MYF(0));
4028
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
4029
  return(join->session->is_error() ? -1 : rc);
1 by brian
clean slate
4030
}
4031
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
4032
enum_nested_loop_state sub_select_cache(JOIN *join, JoinTable *join_tab, bool end_of_records)
1 by brian
clean slate
4033
{
4034
  enum_nested_loop_state rc;
4035
4036
  if (end_of_records)
4037
  {
55 by brian
Update for using real bool types.
4038
    rc= flush_cached_records(join,join_tab,false);
1 by brian
clean slate
4039
    if (rc == NESTED_LOOP_OK || rc == NESTED_LOOP_NO_MORE_ROWS)
4040
      rc= sub_select(join,join_tab,end_of_records);
4041
    return rc;
4042
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
4043
  if (join->session->killed)		// If aborted by user
1 by brian
clean slate
4044
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
4045
    join->session->send_kill_message();
1 by brian
clean slate
4046
    return NESTED_LOOP_KILLED;                   /* purecov: inspected */
4047
  }
4048
  if (join_tab->use_quick != 2 || test_if_quick_select(join_tab) <= 0)
4049
  {
1039.2.7 by Jay Pipes
Yet more style and indentation cleanups.
4050
    if (! store_record_in_cache(&join_tab->cache))
1 by brian
clean slate
4051
      return NESTED_LOOP_OK;                     // There is more room in cache
55 by brian
Update for using real bool types.
4052
    return flush_cached_records(join,join_tab,false);
1 by brian
clean slate
4053
  }
55 by brian
Update for using real bool types.
4054
  rc= flush_cached_records(join, join_tab, true);
1 by brian
clean slate
4055
  if (rc == NESTED_LOOP_OK || rc == NESTED_LOOP_NO_MORE_ROWS)
4056
    rc= sub_select(join, join_tab, end_of_records);
4057
  return rc;
4058
}
4059
4060
/**
4061
  Retrieve records ends with a given beginning from the result of a join.
4062
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
4063
    For a given partial join record consisting of records from the tables
1 by brian
clean slate
4064
    preceding the table join_tab in the execution plan, the function
4065
    retrieves all matching full records from the result set and
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
4066
    send them to the result set stream.
1 by brian
clean slate
4067
4068
  @note
4069
    The function effectively implements the  final (n-k) nested loops
4070
    of nested loops join algorithm, where k is the ordinal number of
4071
    the join_tab table and n is the total number of tables in the join query.
4072
    It performs nested loops joins with all conjunctive predicates from
4073
    the where condition pushed as low to the tables as possible.
4074
    E.g. for the query
4075
    @code
4076
      SELECT * FROM t1,t2,t3
4077
      WHERE t1.a=t2.a AND t2.b=t3.b AND t1.a BETWEEN 5 AND 9
4078
    @endcode
4079
    the predicate (t1.a BETWEEN 5 AND 9) will be pushed to table t1,
4080
    given the selected plan prescribes to nest retrievals of the
4081
    joined tables in the following order: t1,t2,t3.
4082
    A pushed down predicate are attached to the table which it pushed to,
4083
    at the field join_tab->select_cond.
4084
    When executing a nested loop of level k the function runs through
4085
    the rows of 'join_tab' and for each row checks the pushed condition
4086
    attached to the table.
4087
    If it is false the function moves to the next row of the
4088
    table. If the condition is true the function recursively executes (n-k-1)
4089
    remaining embedded nested loops.
4090
    The situation becomes more complicated if outer joins are involved in
4091
    the execution plan. In this case the pushed down predicates can be
4092
    checked only at certain conditions.
4093
    Suppose for the query
4094
    @code
4095
      SELECT * FROM t1 LEFT JOIN (t2,t3) ON t3.a=t1.a
4096
      WHERE t1>2 AND (t2.b>5 OR t2.b IS NULL)
4097
    @endcode
4098
    the optimizer has chosen a plan with the table order t1,t2,t3.
4099
    The predicate P1=t1>2 will be pushed down to the table t1, while the
4100
    predicate P2=(t2.b>5 OR t2.b IS NULL) will be attached to the table
4101
    t2. But the second predicate can not be unconditionally tested right
4102
    after a row from t2 has been read. This can be done only after the
4103
    first row with t3.a=t1.a has been encountered.
4104
    Thus, the second predicate P2 is supplied with a guarded value that are
4105
    stored in the field 'found' of the first inner table for the outer join
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
4106
    (table t2). When the first row with t3.a=t1.a for the  current row
1 by brian
clean slate
4107
    of table t1  appears, the value becomes true. For now on the predicate
4108
    is evaluated immediately after the row of table t2 has been read.
4109
    When the first row with t3.a=t1.a has been encountered all
4110
    conditions attached to the inner tables t2,t3 must be evaluated.
4111
    Only when all of them are true the row is sent to the output stream.
4112
    If not, the function returns to the lowest nest level that has a false
4113
    attached condition.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
4114
    The predicates from on expressions are also pushed down. If in the
1 by brian
clean slate
4115
    the above example the on expression were (t3.a=t1.a AND t2.a=t1.a),
4116
    then t1.a=t2.a would be pushed down to table t2, and without any
4117
    guard.
4118
    If after the run through all rows of table t2, the first inner table
4119
    for the outer join operation, it turns out that no matches are
4120
    found for the current row of t1, then current row from table t1
4121
    is complemented by nulls  for t2 and t3. Then the pushed down predicates
4122
    are checked for the composed row almost in the same way as it had
4123
    been done for the first row with a match. The only difference is
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
4124
    the predicates from on expressions are not checked.
1 by brian
clean slate
4125
4126
  @par
4127
  @b IMPLEMENTATION
4128
  @par
4129
    The function forms output rows for a current partial join of k
4130
    tables tables recursively.
4131
    For each partial join record ending with a certain row from
4132
    join_tab it calls sub_select that builds all possible matching
4133
    tails from the result set.
4134
    To be able  check predicates conditionally items of the class
4135
    Item_func_trig_cond are employed.
4136
    An object of  this class is constructed from an item of class COND
4137
    and a pointer to a guarding boolean variable.
4138
    When the value of the guard variable is true the value of the object
4139
    is the same as the value of the predicate, otherwise it's just returns
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
4140
    true.
4141
    To carry out a return to a nested loop level of join table t the pointer
1 by brian
clean slate
4142
    to t is remembered in the field 'return_tab' of the join structure.
4143
    Consider the following query:
4144
    @code
4145
        SELECT * FROM t1,
4146
                      LEFT JOIN
4147
                      (t2, t3 LEFT JOIN (t4,t5) ON t5.a=t3.a)
4148
                      ON t4.a=t2.a
4149
           WHERE (t2.b=5 OR t2.b IS NULL) AND (t4.b=2 OR t4.b IS NULL)
4150
    @endcode
4151
    Suppose the chosen execution plan dictates the order t1,t2,t3,t4,t5
4152
    and suppose for a given joined rows from tables t1,t2,t3 there are
4153
    no rows in the result set yet.
4154
    When first row from t5 that satisfies the on condition
4155
    t5.a=t3.a is found, the pushed down predicate t4.b=2 OR t4.b IS NULL
4156
    becomes 'activated', as well the predicate t4.a=t2.a. But
4157
    the predicate (t2.b=5 OR t2.b IS NULL) can not be checked until
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
4158
    t4.a=t2.a becomes true.
1 by brian
clean slate
4159
    In order not to re-evaluate the predicates that were already evaluated
4160
    as attached pushed down predicates, a pointer to the the first
4161
    most inner unmatched table is maintained in join_tab->first_unmatched.
4162
    Thus, when the first row from t5 with t5.a=t3.a is found
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
4163
    this pointer for t5 is changed from t4 to t2.
1 by brian
clean slate
4164
4165
    @par
4166
    @b STRUCTURE @b NOTES
4167
    @par
4168
    join_tab->first_unmatched points always backwards to the first inner
4169
    table of the embedding nested join, if any.
4170
4171
  @param join      pointer to the structure providing all context info for
4172
                   the query
4173
  @param join_tab  the first next table of the execution plan to be retrieved
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
4174
  @param end_records  true when we need to perform final steps of retrival
1 by brian
clean slate
4175
4176
  @return
4177
    return one of enum_nested_loop_state, except NESTED_LOOP_NO_MORE_ROWS.
4178
*/
1089.1.13 by Brian Aker
Sorting methods into class files.
4179
enum_nested_loop_state sub_select(JOIN *join, JoinTable *join_tab, bool end_of_records)
1 by brian
clean slate
4180
{
4181
  join_tab->table->null_row=0;
4182
  if (end_of_records)
4183
    return (*join_tab->next_select)(join,join_tab+1,end_of_records);
4184
4185
  int error;
4186
  enum_nested_loop_state rc;
4187
  READ_RECORD *info= &join_tab->read_record;
4188
4189
  if (join->resume_nested_loop)
4190
  {
4191
    /* If not the last table, plunge down the nested loop */
4192
    if (join_tab < join->join_tab + join->tables - 1)
4193
      rc= (*join_tab->next_select)(join, join_tab + 1, 0);
4194
    else
4195
    {
55 by brian
Update for using real bool types.
4196
      join->resume_nested_loop= false;
1 by brian
clean slate
4197
      rc= NESTED_LOOP_OK;
4198
    }
4199
  }
4200
  else
4201
  {
4202
    join->return_tab= join_tab;
4203
4204
    if (join_tab->last_inner)
4205
    {
4206
      /* join_tab is the first inner table for an outer join operation. */
4207
4208
      /* Set initial state of guard variables for this table.*/
4209
      join_tab->found=0;
4210
      join_tab->not_null_compl= 1;
4211
4212
      /* Set first_unmatched for the last inner table of this group */
4213
      join_tab->last_inner->first_unmatched= join_tab;
4214
    }
520.1.22 by Brian Aker
Second pass of thd cleanup
4215
    join->session->row_count= 0;
1 by brian
clean slate
4216
4217
    error= (*join_tab->read_first_record)(join_tab);
4218
    rc= evaluate_join_record(join, join_tab, error);
4219
  }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
4220
4221
  /*
4222
    Note: psergey has added the 2nd part of the following condition; the
1 by brian
clean slate
4223
    change should probably be made in 5.1, too.
4224
  */
4225
  while (rc == NESTED_LOOP_OK && join->return_tab >= join_tab)
4226
  {
4227
    error= info->read_record(info);
4228
    rc= evaluate_join_record(join, join_tab, error);
4229
  }
4230
4231
  if (rc == NESTED_LOOP_NO_MORE_ROWS &&
4232
      join_tab->last_inner && !join_tab->found)
4233
    rc= evaluate_null_complemented_join_record(join, join_tab);
4234
4235
  if (rc == NESTED_LOOP_NO_MORE_ROWS)
4236
    rc= NESTED_LOOP_OK;
4237
  return rc;
4238
}
4239
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
4240
int safe_index_read(JoinTable *tab)
1 by brian
clean slate
4241
{
4242
  int error;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
4243
  Table *table= tab->table;
1 by brian
clean slate
4244
  if ((error=table->file->index_read_map(table->record[0],
4245
                                         tab->ref.key_buff,
4246
                                         make_prev_keypart_map(tab->ref.key_parts),
4247
                                         HA_READ_KEY_EXACT)))
354 by Brian Aker
Refactor of Table methods.
4248
    return table->report_error(error);
1 by brian
clean slate
4249
  return 0;
4250
}
4251
1108.6.3 by Padraig O'Sullivan
Converted the POSITION struct to a class named Position.
4252
int join_read_const_table(JoinTable *tab, Position *pos)
1 by brian
clean slate
4253
{
4254
  int error;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
4255
  Table *table=tab->table;
1 by brian
clean slate
4256
  table->const_table=1;
4257
  table->null_row=0;
4258
  table->status=STATUS_NO_RECORD;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
4259
1108.6.20 by Padraig O'Sullivan
Renamed access_type to access_method due to conflicts on Solaris.
4260
  if (tab->type == AM_SYSTEM)
1 by brian
clean slate
4261
  {
4262
    if ((error=join_read_system(tab)))
4263
    {						// Info for DESCRIBE
4264
      tab->info="const row not found";
4265
      /* Mark for EXPLAIN that the row was not found */
4266
      pos->records_read=0.0;
4267
      pos->ref_depend_map= 0;
4268
      if (!table->maybe_null || error > 0)
1039.2.5 by Jay Pipes
Style cleanups and moves JOIN_TAB definition out into its own header.
4269
        return(error);
1 by brian
clean slate
4270
    }
4271
  }
4272
  else
4273
  {
1039.2.5 by Jay Pipes
Style cleanups and moves JOIN_TAB definition out into its own header.
4274
    if (!table->key_read && 
4275
        table->covering_keys.test(tab->ref.key) && 
4276
        !table->no_keyread &&
1008.1.4 by Brian Aker
Removed TL_READ_HIGH_PRIORITY
4277
        (int) table->reginfo.lock_type <= (int) TL_READ_WITH_SHARED_LOCKS)
1 by brian
clean slate
4278
    {
4279
      table->key_read=1;
4280
      table->file->extra(HA_EXTRA_KEYREAD);
4281
      tab->index= tab->ref.key;
4282
    }
4283
    error=join_read_const(tab);
4284
    if (table->key_read)
4285
    {
4286
      table->key_read=0;
4287
      table->file->extra(HA_EXTRA_NO_KEYREAD);
4288
    }
4289
    if (error)
4290
    {
4291
      tab->info="unique row not found";
4292
      /* Mark for EXPLAIN that the row was not found */
4293
      pos->records_read=0.0;
4294
      pos->ref_depend_map= 0;
4295
      if (!table->maybe_null || error > 0)
1039.2.5 by Jay Pipes
Style cleanups and moves JOIN_TAB definition out into its own header.
4296
        return(error);
1 by brian
clean slate
4297
    }
4298
  }
4299
  if (*tab->on_expr_ref && !table->null_row)
4300
  {
4301
    if ((table->null_row= test((*tab->on_expr_ref)->val_int() == 0)))
934.1.1 by Brian Aker
Moved two functions in classes.
4302
      table->mark_as_null_row();
1 by brian
clean slate
4303
  }
4304
  if (!table->null_row)
4305
    table->maybe_null=0;
4306
4307
  /* Check appearance of new constant items in Item_equal objects */
4308
  JOIN *join= tab->join;
4309
  if (join->conds)
4310
    update_const_equal_items(join->conds, tab);
327.2.4 by Brian Aker
Refactoring table.h
4311
  TableList *tbl;
1 by brian
clean slate
4312
  for (tbl= join->select_lex->leaf_tables; tbl; tbl= tbl->next_leaf)
4313
  {
327.2.4 by Brian Aker
Refactoring table.h
4314
    TableList *embedded;
4315
    TableList *embedding= tbl;
1 by brian
clean slate
4316
    do
4317
    {
4318
      embedded= embedding;
4319
      if (embedded->on_expr)
4320
         update_const_equal_items(embedded->on_expr, tab);
4321
      embedding= embedded->embedding;
4322
    }
4323
    while (embedding &&
4324
           embedding->nested_join->join_list.head() == embedded);
4325
  }
4326
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
4327
  return(0);
1 by brian
clean slate
4328
}
4329
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
4330
int join_read_system(JoinTable *tab)
1 by brian
clean slate
4331
{
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
4332
  Table *table= tab->table;
1 by brian
clean slate
4333
  int error;
4334
  if (table->status & STATUS_GARBAGE)		// If first read
4335
  {
4336
    if ((error=table->file->read_first_row(table->record[0],
4337
					   table->s->primary_key)))
4338
    {
4339
      if (error != HA_ERR_END_OF_FILE)
1039.2.5 by Jay Pipes
Style cleanups and moves JOIN_TAB definition out into its own header.
4340
        return table->report_error(error);
934.1.1 by Brian Aker
Moved two functions in classes.
4341
      tab->table->mark_as_null_row();
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
4342
      table->emptyRecord();			// Make empty record
1 by brian
clean slate
4343
      return -1;
4344
    }
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
4345
    table->storeRecord();
1 by brian
clean slate
4346
  }
4347
  else if (!table->status)			// Only happens with left join
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
4348
    table->restoreRecord();			// restore old record
1 by brian
clean slate
4349
  table->null_row=0;
4350
  return table->status ? -1 : 0;
4351
}
4352
4353
/**
4354
  Read a (constant) table when there is at most one matching row.
4355
4356
  @param tab			Table to read
4357
4358
  @retval
4359
    0	Row was found
4360
  @retval
4361
    -1   Row was not found
4362
  @retval
4363
    1   Got an error (other than row not found) during read
4364
*/
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
4365
int join_read_const(JoinTable *tab)
1 by brian
clean slate
4366
{
4367
  int error;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
4368
  Table *table= tab->table;
1 by brian
clean slate
4369
  if (table->status & STATUS_GARBAGE)		// If first read
4370
  {
4371
    table->status= 0;
520.1.22 by Brian Aker
Second pass of thd cleanup
4372
    if (cp_buffer_from_ref(tab->join->session, &tab->ref))
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
4373
      error= HA_ERR_KEY_NOT_FOUND;
1 by brian
clean slate
4374
    else
4375
    {
4376
      error=table->file->index_read_idx_map(table->record[0],tab->ref.key,
481 by Brian Aker
Remove all of uchar.
4377
                                            (unsigned char*) tab->ref.key_buff,
1 by brian
clean slate
4378
                                            make_prev_keypart_map(tab->ref.key_parts),
4379
                                            HA_READ_KEY_EXACT);
4380
    }
4381
    if (error)
4382
    {
4383
      table->status= STATUS_NOT_FOUND;
934.1.1 by Brian Aker
Moved two functions in classes.
4384
      tab->table->mark_as_null_row();
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
4385
      table->emptyRecord();
1 by brian
clean slate
4386
      if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
1039.2.5 by Jay Pipes
Style cleanups and moves JOIN_TAB definition out into its own header.
4387
        return table->report_error(error);
1 by brian
clean slate
4388
      return -1;
4389
    }
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
4390
    table->storeRecord();
1 by brian
clean slate
4391
  }
4392
  else if (!(table->status & ~STATUS_NULL_ROW))	// Only happens with left join
4393
  {
4394
    table->status=0;
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
4395
    table->restoreRecord();			// restore old record
1 by brian
clean slate
4396
  }
4397
  table->null_row=0;
4398
  return table->status ? -1 : 0;
4399
}
4400
4401
/*
4402
  eq_ref access method implementation: "read_first" function
4403
4404
  SYNOPSIS
4405
    join_read_key()
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
4406
      tab  JoinTable of the accessed table
1 by brian
clean slate
4407
4408
  DESCRIPTION
4409
    This is "read_fist" function for the "ref" access method. The difference
4410
    from "ref" is that it has a one-element "cache" (see cmp_buffer_with_ref)
4411
4412
  RETURN
4413
    0  - Ok
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
4414
   -1  - Row not found
1 by brian
clean slate
4415
    1  - Error
4416
*/
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
4417
int join_read_key(JoinTable *tab)
1 by brian
clean slate
4418
{
4419
  int error;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
4420
  Table *table= tab->table;
1 by brian
clean slate
4421
4422
  if (!table->file->inited)
4423
  {
4424
    table->file->ha_index_init(tab->ref.key, tab->sorted);
4425
  }
4426
4427
  /* TODO: Why don't we do "Late NULLs Filtering" here? */
4428
  if (cmp_buffer_with_ref(tab) ||
4429
      (table->status & (STATUS_GARBAGE | STATUS_NO_PARENT | STATUS_NULL_ROW)))
4430
  {
4431
    if (tab->ref.key_err)
4432
    {
4433
      table->status=STATUS_NOT_FOUND;
4434
      return -1;
4435
    }
4436
    error=table->file->index_read_map(table->record[0],
4437
                                      tab->ref.key_buff,
4438
                                      make_prev_keypart_map(tab->ref.key_parts),
4439
                                      HA_READ_KEY_EXACT);
4440
    if (error && error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
354 by Brian Aker
Refactor of Table methods.
4441
      return table->report_error(error);
1 by brian
clean slate
4442
  }
4443
  table->null_row=0;
4444
  return table->status ? -1 : 0;
4445
}
4446
4447
/*
4448
  ref access method implementation: "read_first" function
4449
4450
  SYNOPSIS
4451
    join_read_always_key()
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
4452
      tab  JoinTable of the accessed table
1 by brian
clean slate
4453
4454
  DESCRIPTION
1039.2.5 by Jay Pipes
Style cleanups and moves JOIN_TAB definition out into its own header.
4455
    This is "read_first" function for the "ref" access method.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
4456
1 by brian
clean slate
4457
    The functon must leave the index initialized when it returns.
4458
    ref_or_null access implementation depends on that.
4459
4460
  RETURN
4461
    0  - Ok
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
4462
   -1  - Row not found
1 by brian
clean slate
4463
    1  - Error
4464
*/
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
4465
int join_read_always_key(JoinTable *tab)
1 by brian
clean slate
4466
{
4467
  int error;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
4468
  Table *table= tab->table;
1 by brian
clean slate
4469
4470
  /* Initialize the index first */
4471
  if (!table->file->inited)
4472
    table->file->ha_index_init(tab->ref.key, tab->sorted);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
4473
1 by brian
clean slate
4474
  /* Perform "Late NULLs Filtering" (see internals manual for explanations) */
482 by Brian Aker
Remove uint.
4475
  for (uint32_t i= 0 ; i < tab->ref.key_parts ; i++)
1 by brian
clean slate
4476
  {
4477
    if ((tab->ref.null_rejecting & 1 << i) && tab->ref.items[i]->is_null())
4478
        return -1;
4479
  }
4480
520.1.22 by Brian Aker
Second pass of thd cleanup
4481
  if (cp_buffer_from_ref(tab->join->session, &tab->ref))
1 by brian
clean slate
4482
    return -1;
4483
  if ((error=table->file->index_read_map(table->record[0],
4484
                                         tab->ref.key_buff,
4485
                                         make_prev_keypart_map(tab->ref.key_parts),
4486
                                         HA_READ_KEY_EXACT)))
4487
  {
4488
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
354 by Brian Aker
Refactor of Table methods.
4489
      return table->report_error(error);
1 by brian
clean slate
4490
    return -1; /* purecov: inspected */
4491
  }
998.1.2 by Brian Aker
First pass on removing virt columns
4492
1 by brian
clean slate
4493
  return 0;
4494
}
4495
4496
/**
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
4497
  This function is used when optimizing away order_st BY in
327.2.3 by Brian Aker
Refactoring of class Table
4498
  SELECT * FROM t1 WHERE a=1 order_st BY a DESC,b DESC.
1 by brian
clean slate
4499
*/
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
4500
int join_read_last_key(JoinTable *tab)
1 by brian
clean slate
4501
{
4502
  int error;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
4503
  Table *table= tab->table;
1 by brian
clean slate
4504
4505
  if (!table->file->inited)
4506
    table->file->ha_index_init(tab->ref.key, tab->sorted);
520.1.22 by Brian Aker
Second pass of thd cleanup
4507
  if (cp_buffer_from_ref(tab->join->session, &tab->ref))
1 by brian
clean slate
4508
    return -1;
4509
  if ((error=table->file->index_read_last_map(table->record[0],
4510
                                              tab->ref.key_buff,
4511
                                              make_prev_keypart_map(tab->ref.key_parts))))
4512
  {
4513
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
354 by Brian Aker
Refactor of Table methods.
4514
      return table->report_error(error);
1 by brian
clean slate
4515
    return -1; /* purecov: inspected */
4516
  }
4517
  return 0;
4518
}
4519
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
4520
int join_no_more_records(READ_RECORD *)
1 by brian
clean slate
4521
{
4522
  return -1;
4523
}
4524
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
4525
int join_read_next_same_diff(READ_RECORD *info)
1 by brian
clean slate
4526
{
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
4527
  Table *table= info->table;
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
4528
  JoinTable *tab=table->reginfo.join_tab;
1 by brian
clean slate
4529
  if (tab->insideout_match_tab->found_match)
4530
  {
4531
    KEY *key= tab->table->key_info + tab->index;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
4532
    do
1 by brian
clean slate
4533
    {
4534
      int error;
4535
      /* Save index tuple from record to the buffer */
4536
      key_copy(tab->insideout_buf, info->record, key, 0);
4537
4538
      if ((error=table->file->index_next_same(table->record[0],
4539
                                              tab->ref.key_buff,
4540
                                              tab->ref.key_length)))
4541
      {
4542
        if (error != HA_ERR_END_OF_FILE)
354 by Brian Aker
Refactor of Table methods.
4543
          return table->report_error(error);
1 by brian
clean slate
4544
        table->status= STATUS_GARBAGE;
4545
        return -1;
4546
      }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
4547
    } while (!key_cmp(tab->table->key_info[tab->index].key_part,
1 by brian
clean slate
4548
                      tab->insideout_buf, key->key_length));
4549
    tab->insideout_match_tab->found_match= 0;
4550
    return 0;
4551
  }
4552
  else
4553
    return join_read_next_same(info);
4554
}
4555
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
4556
int join_read_next_same(READ_RECORD *info)
1 by brian
clean slate
4557
{
4558
  int error;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
4559
  Table *table= info->table;
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
4560
  JoinTable *tab=table->reginfo.join_tab;
1 by brian
clean slate
4561
4562
  if ((error=table->file->index_next_same(table->record[0],
4563
					  tab->ref.key_buff,
4564
					  tab->ref.key_length)))
4565
  {
4566
    if (error != HA_ERR_END_OF_FILE)
354 by Brian Aker
Refactor of Table methods.
4567
      return table->report_error(error);
1 by brian
clean slate
4568
    table->status= STATUS_GARBAGE;
4569
    return -1;
4570
  }
998.1.2 by Brian Aker
First pass on removing virt columns
4571
1 by brian
clean slate
4572
  return 0;
4573
}
4574
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
4575
int join_read_prev_same(READ_RECORD *info)
1 by brian
clean slate
4576
{
4577
  int error;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
4578
  Table *table= info->table;
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
4579
  JoinTable *tab=table->reginfo.join_tab;
1 by brian
clean slate
4580
4581
  if ((error=table->file->index_prev(table->record[0])))
354 by Brian Aker
Refactor of Table methods.
4582
    return table->report_error(error);
1 by brian
clean slate
4583
  if (key_cmp_if_same(table, tab->ref.key_buff, tab->ref.key,
4584
                      tab->ref.key_length))
4585
  {
4586
    table->status=STATUS_NOT_FOUND;
4587
    error= -1;
4588
  }
4589
  return error;
4590
}
4591
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
4592
int join_init_quick_read_record(JoinTable *tab)
1 by brian
clean slate
4593
{
4594
  if (test_if_quick_select(tab) == -1)
4595
    return -1;					/* No possible records */
4596
  return join_init_read_record(tab);
4597
}
4598
4599
int rr_sequential(READ_RECORD *info);
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
4600
int init_read_record_seq(JoinTable *tab)
1 by brian
clean slate
4601
{
4602
  tab->read_record.read_record= rr_sequential;
4603
  if (tab->read_record.file->ha_rnd_init(1))
4604
    return 1;
4605
  return (*tab->read_record.read_record)(&tab->read_record);
4606
}
4607
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
4608
int test_if_quick_select(JoinTable *tab)
1 by brian
clean slate
4609
{
4610
  delete tab->select->quick;
1039.2.5 by Jay Pipes
Style cleanups and moves JOIN_TAB definition out into its own header.
4611
  tab->select->quick= 0;
520.1.22 by Brian Aker
Second pass of thd cleanup
4612
  return tab->select->test_quick_select(tab->join->session, tab->keys,
1039.2.5 by Jay Pipes
Style cleanups and moves JOIN_TAB definition out into its own header.
4613
					(table_map) 0, HA_POS_ERROR, 0, false);
1 by brian
clean slate
4614
}
4615
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
4616
int join_init_read_record(JoinTable *tab)
1 by brian
clean slate
4617
{
4618
  if (tab->select && tab->select->quick && tab->select->quick->reset())
4619
    return 1;
520.1.22 by Brian Aker
Second pass of thd cleanup
4620
  init_read_record(&tab->read_record, tab->join->session, tab->table,
1 by brian
clean slate
4621
		   tab->select,1,1);
4622
  return (*tab->read_record.read_record)(&tab->read_record);
4623
}
4624
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
4625
int join_read_first(JoinTable *tab)
1 by brian
clean slate
4626
{
4627
  int error;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
4628
  Table *table=tab->table;
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
4629
  if (!table->key_read && table->covering_keys.test(tab->index) &&
1 by brian
clean slate
4630
      !table->no_keyread)
4631
  {
4632
    table->key_read=1;
4633
    table->file->extra(HA_EXTRA_KEYREAD);
4634
  }
4635
  tab->table->status=0;
4636
  tab->read_record.table=table;
4637
  tab->read_record.file=table->file;
4638
  tab->read_record.index=tab->index;
4639
  tab->read_record.record=table->record[0];
4640
  if (tab->insideout_match_tab)
4641
  {
4642
    tab->read_record.do_insideout_scan= tab;
4643
    tab->read_record.read_record=join_read_next_different;
4644
    tab->insideout_match_tab->found_match= 0;
4645
  }
4646
  else
4647
  {
4648
    tab->read_record.read_record=join_read_next;
4649
    tab->read_record.do_insideout_scan= 0;
4650
  }
4651
4652
  if (!table->file->inited)
4653
    table->file->ha_index_init(tab->index, tab->sorted);
4654
  if ((error=tab->table->file->index_first(tab->table->record[0])))
4655
  {
4656
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
354 by Brian Aker
Refactor of Table methods.
4657
      table->report_error(error);
1 by brian
clean slate
4658
    return -1;
4659
  }
998.1.2 by Brian Aker
First pass on removing virt columns
4660
1 by brian
clean slate
4661
  return 0;
4662
}
4663
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
4664
int join_read_next_different(READ_RECORD *info)
1 by brian
clean slate
4665
{
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
4666
  JoinTable *tab= info->do_insideout_scan;
1 by brian
clean slate
4667
  if (tab->insideout_match_tab->found_match)
4668
  {
4669
    KEY *key= tab->table->key_info + tab->index;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
4670
    do
1 by brian
clean slate
4671
    {
4672
      int error;
4673
      /* Save index tuple from record to the buffer */
4674
      key_copy(tab->insideout_buf, info->record, key, 0);
4675
4676
      if ((error=info->file->index_next(info->record)))
354 by Brian Aker
Refactor of Table methods.
4677
        return info->table->report_error(error);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
4678
    } while (!key_cmp(tab->table->key_info[tab->index].key_part,
1 by brian
clean slate
4679
                      tab->insideout_buf, key->key_length));
4680
    tab->insideout_match_tab->found_match= 0;
4681
    return 0;
4682
  }
4683
  else
4684
    return join_read_next(info);
4685
}
4686
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
4687
int join_read_next(READ_RECORD *info)
1 by brian
clean slate
4688
{
4689
  int error;
4690
  if ((error=info->file->index_next(info->record)))
354 by Brian Aker
Refactor of Table methods.
4691
    return info->table->report_error(error);
1 by brian
clean slate
4692
  return 0;
4693
}
4694
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
4695
int join_read_last(JoinTable *tab)
1 by brian
clean slate
4696
{
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
4697
  Table *table=tab->table;
1 by brian
clean slate
4698
  int error;
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
4699
  if (!table->key_read && table->covering_keys.test(tab->index) &&
1 by brian
clean slate
4700
      !table->no_keyread)
4701
  {
4702
    table->key_read=1;
4703
    table->file->extra(HA_EXTRA_KEYREAD);
4704
  }
4705
  tab->table->status=0;
4706
  tab->read_record.read_record=join_read_prev;
4707
  tab->read_record.table=table;
4708
  tab->read_record.file=table->file;
4709
  tab->read_record.index=tab->index;
4710
  tab->read_record.record=table->record[0];
4711
  if (!table->file->inited)
4712
    table->file->ha_index_init(tab->index, 1);
4713
  if ((error= tab->table->file->index_last(tab->table->record[0])))
354 by Brian Aker
Refactor of Table methods.
4714
    return table->report_error(error);
998.1.2 by Brian Aker
First pass on removing virt columns
4715
1 by brian
clean slate
4716
  return 0;
4717
}
4718
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
4719
int join_read_prev(READ_RECORD *info)
1 by brian
clean slate
4720
{
4721
  int error;
4722
  if ((error= info->file->index_prev(info->record)))
354 by Brian Aker
Refactor of Table methods.
4723
    return info->table->report_error(error);
998.1.2 by Brian Aker
First pass on removing virt columns
4724
1 by brian
clean slate
4725
  return 0;
4726
}
4727
4728
/**
4729
  Reading of key with key reference and one part that may be NULL.
4730
*/
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
4731
int join_read_always_key_or_null(JoinTable *tab)
1 by brian
clean slate
4732
{
4733
  int res;
4734
4735
  /* First read according to key which is NOT NULL */
4736
  *tab->ref.null_ref_key= 0;			// Clear null byte
4737
  if ((res= join_read_always_key(tab)) >= 0)
4738
    return res;
4739
4740
  /* Then read key with null value */
4741
  *tab->ref.null_ref_key= 1;			// Set null byte
4742
  return safe_index_read(tab);
4743
}
4744
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
4745
int join_read_next_same_or_null(READ_RECORD *info)
1 by brian
clean slate
4746
{
4747
  int error;
4748
  if ((error= join_read_next_same(info)) >= 0)
4749
    return error;
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
4750
  JoinTable *tab= info->table->reginfo.join_tab;
1 by brian
clean slate
4751
4752
  /* Test if we have already done a read after null key */
4753
  if (*tab->ref.null_ref_key)
4754
    return -1;					// All keys read
4755
  *tab->ref.null_ref_key= 1;			// Set null byte
4756
  return safe_index_read(tab);			// then read null keys
4757
}
4758
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
4759
enum_nested_loop_state end_send_group(JOIN *join, JoinTable *, bool end_of_records)
1 by brian
clean slate
4760
{
4761
  int idx= -1;
4762
  enum_nested_loop_state ok_code= NESTED_LOOP_OK;
4763
4764
  if (!join->first_record || end_of_records ||
4765
      (idx=test_if_item_cache_changed(join->group_fields)) >= 0)
4766
  {
575.1.2 by Monty Taylor
Changed a bunch of __attribute__((unused)) to removing the parameter name instead.
4767
    if (join->first_record ||
1 by brian
clean slate
4768
        (end_of_records && !join->group && !join->group_optimized_away))
4769
    {
4770
      if (idx < (int) join->send_group_parts)
4771
      {
1039.2.5 by Jay Pipes
Style cleanups and moves JOIN_TAB definition out into its own header.
4772
        int error=0;
4773
        {
4774
          if (!join->first_record)
4775
          {
4776
                  List_iterator_fast<Item> it(*join->fields);
4777
                  Item *item;
4778
            /* No matching rows for group function */
4779
            join->clear();
1 by brian
clean slate
4780
4781
            while ((item= it++))
4782
              item->no_rows_in_result();
1039.2.5 by Jay Pipes
Style cleanups and moves JOIN_TAB definition out into its own header.
4783
          }
4784
          if (join->having && join->having->val_int() == 0)
4785
            error= -1;				// Didn't satisfy having
4786
          else
4787
          {
4788
            if (join->do_send_rows)
4789
              error=join->result->send_data(*join->fields) ? 1 : 0;
4790
            join->send_records++;
4791
          }
4792
          if (join->rollup.state != ROLLUP::STATE_NONE && error <= 0)
4793
          {
4794
            if (join->rollup_send_data((uint32_t) (idx+1)))
4795
              error= 1;
4796
          }
4797
        }
4798
        if (error > 0)
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
4799
          return(NESTED_LOOP_ERROR);        /* purecov: inspected */
1039.2.5 by Jay Pipes
Style cleanups and moves JOIN_TAB definition out into its own header.
4800
        if (end_of_records)
4801
          return(NESTED_LOOP_OK);
4802
        if (join->send_records >= join->unit->select_limit_cnt &&
4803
            join->do_send_rows)
4804
        {
4805
          if (!(join->select_options & OPTION_FOUND_ROWS))
4806
            return(NESTED_LOOP_QUERY_LIMIT); // Abort nicely
4807
          join->do_send_rows=0;
4808
          join->unit->select_limit_cnt = HA_POS_ERROR;
1 by brian
clean slate
4809
        }
4810
        else if (join->send_records >= join->fetch_limit)
4811
        {
4812
          /*
4813
            There is a server side cursor and all rows
4814
            for this fetch request are sent.
4815
          */
4816
          /*
4817
            Preventing code duplication. When finished with the group reset
4818
            the group functions and copy_fields. We fall through. bug #11904
4819
          */
4820
          ok_code= NESTED_LOOP_CURSOR_LIMIT;
4821
        }
4822
      }
4823
    }
4824
    else
4825
    {
4826
      if (end_of_records)
1039.2.5 by Jay Pipes
Style cleanups and moves JOIN_TAB definition out into its own header.
4827
        return(NESTED_LOOP_OK);
1 by brian
clean slate
4828
      join->first_record=1;
398.1.10 by Monty Taylor
Actually removed VOID() this time.
4829
      test_if_item_cache_changed(join->group_fields);
1 by brian
clean slate
4830
    }
4831
    if (idx < (int) join->send_group_parts)
4832
    {
4833
      /*
4834
        This branch is executed also for cursors which have finished their
4835
        fetch limit - the reason for ok_code.
4836
      */
4837
      copy_fields(&join->tmp_table_param);
4838
      if (init_sum_functions(join->sum_funcs, join->sum_funcs_end[idx+1]))
1039.2.5 by Jay Pipes
Style cleanups and moves JOIN_TAB definition out into its own header.
4839
        return(NESTED_LOOP_ERROR);
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
4840
      return(ok_code);
1 by brian
clean slate
4841
    }
4842
  }
4843
  if (update_sum_func(join->sum_funcs))
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
4844
    return(NESTED_LOOP_ERROR);
4845
  return(NESTED_LOOP_OK);
1 by brian
clean slate
4846
}
4847
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
4848
enum_nested_loop_state end_write_group(JOIN *join, JoinTable *, bool end_of_records)
1 by brian
clean slate
4849
{
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
4850
  Table *table=join->tmp_table;
1 by brian
clean slate
4851
  int	  idx= -1;
4852
520.1.22 by Brian Aker
Second pass of thd cleanup
4853
  if (join->session->killed)
1 by brian
clean slate
4854
  {						// Aborted by user
520.1.22 by Brian Aker
Second pass of thd cleanup
4855
    join->session->send_kill_message();
1039.2.5 by Jay Pipes
Style cleanups and moves JOIN_TAB definition out into its own header.
4856
    return NESTED_LOOP_KILLED;             /* purecov: inspected */
1 by brian
clean slate
4857
  }
4858
  if (!join->first_record || end_of_records ||
4859
      (idx=test_if_item_cache_changed(join->group_fields)) >= 0)
4860
  {
4861
    if (join->first_record || (end_of_records && !join->group))
4862
    {
4863
      int send_group_parts= join->send_group_parts;
4864
      if (idx < send_group_parts)
4865
      {
1039.2.5 by Jay Pipes
Style cleanups and moves JOIN_TAB definition out into its own header.
4866
        if (!join->first_record)
4867
        {
4868
          /* No matching rows for group function */
4869
          join->clear();
4870
        }
4871
        copy_sum_funcs(join->sum_funcs, join->sum_funcs_end[send_group_parts]);
4872
        if (!join->having || join->having->val_int())
4873
        {
1 by brian
clean slate
4874
          int error= table->file->ha_write_row(table->record[0]);
520.1.22 by Brian Aker
Second pass of thd cleanup
4875
          if (error && create_myisam_from_heap(join->session, table,
1039.2.5 by Jay Pipes
Style cleanups and moves JOIN_TAB definition out into its own header.
4876
                                              join->tmp_table_param.start_recinfo,
1 by brian
clean slate
4877
                                                &join->tmp_table_param.recinfo,
1039.2.5 by Jay Pipes
Style cleanups and moves JOIN_TAB definition out into its own header.
4878
                                              error, 0))
4879
          return NESTED_LOOP_ERROR;
1 by brian
clean slate
4880
        }
4881
        if (join->rollup.state != ROLLUP::STATE_NONE)
1039.2.5 by Jay Pipes
Style cleanups and moves JOIN_TAB definition out into its own header.
4882
        {
4883
          if (join->rollup_write_data((uint32_t) (idx+1), table))
4884
            return NESTED_LOOP_ERROR;
4885
        }
4886
        if (end_of_records)
4887
          return NESTED_LOOP_OK;
1 by brian
clean slate
4888
      }
4889
    }
4890
    else
4891
    {
4892
      if (end_of_records)
1039.2.5 by Jay Pipes
Style cleanups and moves JOIN_TAB definition out into its own header.
4893
        return NESTED_LOOP_OK;
1 by brian
clean slate
4894
      join->first_record=1;
398.1.10 by Monty Taylor
Actually removed VOID() this time.
4895
      test_if_item_cache_changed(join->group_fields);
1 by brian
clean slate
4896
    }
4897
    if (idx < (int) join->send_group_parts)
4898
    {
4899
      copy_fields(&join->tmp_table_param);
4900
      copy_funcs(join->tmp_table_param.items_to_copy);
4901
      if (init_sum_functions(join->sum_funcs, join->sum_funcs_end[idx+1]))
1039.2.5 by Jay Pipes
Style cleanups and moves JOIN_TAB definition out into its own header.
4902
        return NESTED_LOOP_ERROR;
4903
      return NESTED_LOOP_OK;
1 by brian
clean slate
4904
    }
4905
  }
4906
  if (update_sum_func(join->sum_funcs))
1039.2.5 by Jay Pipes
Style cleanups and moves JOIN_TAB definition out into its own header.
4907
    return NESTED_LOOP_ERROR;
4908
  return NESTED_LOOP_OK;
1 by brian
clean slate
4909
}
4910
4911
/*****************************************************************************
4912
  Remove calculation with tables that aren't yet read. Remove also tests
4913
  against fields that are read through key where the table is not a
4914
  outer join table.
4915
  We can't remove tests that are made against columns which are stored
4916
  in sorted order.
4917
*****************************************************************************/
4918
4919
/**
4920
  @return
4921
    1 if right_item is used removable reference key on left_item
4922
*/
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
4923
bool test_if_ref(Item_field *left_item,Item *right_item)
1 by brian
clean slate
4924
{
4925
  Field *field=left_item->field;
4926
  // No need to change const test. We also have to keep tests on LEFT JOIN
4927
  if (!field->table->const_table && !field->table->maybe_null)
4928
  {
4929
    Item *ref_item=part_of_refkey(field->table,field);
4930
    if (ref_item && ref_item->eq(right_item,1))
4931
    {
4932
      right_item= right_item->real_item();
4933
      if (right_item->type() == Item::FIELD_ITEM)
1039.2.5 by Jay Pipes
Style cleanups and moves JOIN_TAB definition out into its own header.
4934
        return (field->eq_def(((Item_field *) right_item)->field));
1 by brian
clean slate
4935
      /* remove equalities injected by IN->EXISTS transformation */
4936
      else if (right_item->type() == Item::CACHE_ITEM)
4937
        return ((Item_cache *)right_item)->eq_def (field);
4938
      if (right_item->const_item() && !(right_item->is_null()))
4939
      {
1039.2.5 by Jay Pipes
Style cleanups and moves JOIN_TAB definition out into its own header.
4940
        /*
4941
          We can remove binary fields and numerical fields except float,
4942
          as float comparison isn't 100 % secure
4943
          We have to keep normal strings to be able to check for end spaces
1 by brian
clean slate
4944
1039.2.5 by Jay Pipes
Style cleanups and moves JOIN_TAB definition out into its own header.
4945
                sergefp: the above seems to be too restrictive. Counterexample:
4946
                  create table t100 (v varchar(10), key(v)) default charset=latin1;
4947
                  insert into t100 values ('a'),('a ');
4948
                  explain select * from t100 where v='a';
4949
                The EXPLAIN shows 'using Where'. Running the query returns both
4950
                rows, so it seems there are no problems with endspace in the most
4951
                frequent case?
4952
        */
4953
        if (field->binary() &&
4954
            field->real_type() != DRIZZLE_TYPE_VARCHAR &&
4955
            field->decimals() == 0)
4956
        {
4957
          return ! store_val_in_field(field, right_item, CHECK_FIELD_WARN);
4958
        }
1 by brian
clean slate
4959
      }
4960
    }
4961
  }
1039.2.5 by Jay Pipes
Style cleanups and moves JOIN_TAB definition out into its own header.
4962
  return 0;
1 by brian
clean slate
4963
}
4964
4965
/*
4966
  Extract a condition that can be checked after reading given table
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
4967
1 by brian
clean slate
4968
  SYNOPSIS
4969
    make_cond_for_table()
4970
      cond         Condition to analyze
4971
      tables       Tables for which "current field values" are available
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
4972
      used_table   Table that we're extracting the condition for (may
1 by brian
clean slate
4973
                   also include PSEUDO_TABLE_BITS
4974
4975
  DESCRIPTION
4976
    Extract the condition that can be checked after reading the table
4977
    specified in 'used_table', given that current-field values for tables
4978
    specified in 'tables' bitmap are available.
4979
4980
    The function assumes that
4981
      - Constant parts of the condition has already been checked.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
4982
      - Condition that could be checked for tables in 'tables' has already
1 by brian
clean slate
4983
        been checked.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
4984
1 by brian
clean slate
4985
    The function takes into account that some parts of the condition are
4986
    guaranteed to be true by employed 'ref' access methods (the code that
4987
    does this is located at the end, search down for "EQ_FUNC").
4988
4989
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
4990
  SEE ALSO
1 by brian
clean slate
4991
    make_cond_for_info_schema uses similar algorithm
4992
4993
  RETURN
4994
    Extracted condition
4995
*/
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
4996
COND *make_cond_for_table(COND *cond, table_map tables, table_map used_table, bool exclude_expensive_cond)
1 by brian
clean slate
4997
{
4998
  if (used_table && !(cond->used_tables() & used_table) &&
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
4999
    /*
5000
      Exclude constant conditions not checked at optimization time if
5001
      the table we are pushing conditions to is the first one.
5002
      As a result, such conditions are not considered as already checked
5003
      and will be checked at execution time, attached to the first table.
5004
    */
5005
    !((used_table & 1) && cond->is_expensive()))
1 by brian
clean slate
5006
    return (COND*) 0;				// Already checked
5007
  if (cond->type() == Item::COND_ITEM)
5008
  {
5009
    if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
5010
    {
5011
      /* Create new top level AND item */
5012
      Item_cond_and *new_cond=new Item_cond_and;
5013
      if (!new_cond)
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
5014
        return (COND*) 0;			// OOM /* purecov: inspected */
1 by brian
clean slate
5015
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
5016
      Item *item;
5017
      while ((item=li++))
5018
      {
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
5019
        Item *fix= make_cond_for_table(item,tables,used_table,
5020
                                            exclude_expensive_cond);
5021
        if (fix)
5022
          new_cond->argument_list()->push_back(fix);
1 by brian
clean slate
5023
      }
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
5024
      switch (new_cond->argument_list()->elements) 
5025
      {
5026
        case 0:
5027
          return (COND*) 0;			// Always true
5028
        case 1:
5029
          return new_cond->argument_list()->head();
5030
        default:
5031
          /*
5032
            Item_cond_and do not need fix_fields for execution, its parameters
5033
            are fixed or do not need fix_fields, too
5034
          */
5035
          new_cond->quick_fix_field();
5036
          new_cond->used_tables_cache= ((Item_cond_and*) cond)->used_tables_cache & tables;
5037
          return new_cond;
1 by brian
clean slate
5038
      }
5039
    }
5040
    else
5041
    {						// Or list
5042
      Item_cond_or *new_cond=new Item_cond_or;
5043
      if (!new_cond)
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
5044
        return (COND*) 0;			// OOM /* purecov: inspected */
1 by brian
clean slate
5045
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
5046
      Item *item;
5047
      while ((item=li++))
5048
      {
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
5049
        Item *fix= make_cond_for_table(item,tables,0L, exclude_expensive_cond);
5050
        if (!fix)
5051
          return (COND*) 0;			// Always true
5052
        new_cond->argument_list()->push_back(fix);
1 by brian
clean slate
5053
      }
5054
      /*
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
5055
        Item_cond_and do not need fix_fields for execution, its parameters
5056
        are fixed or do not need fix_fields, too
1 by brian
clean slate
5057
      */
5058
      new_cond->quick_fix_field();
5059
      new_cond->used_tables_cache= ((Item_cond_or*) cond)->used_tables_cache;
5060
      new_cond->top_level_item();
5061
      return new_cond;
5062
    }
5063
  }
5064
5065
  /*
5066
    Because the following test takes a while and it can be done
5067
    table_count times, we mark each item that we have examined with the result
5068
    of the test
5069
  */
5070
5071
  if (cond->marker == 3 || (cond->used_tables() & ~tables) ||
5072
      /*
5073
        When extracting constant conditions, treat expensive conditions as
5074
        non-constant, so that they are not evaluated at optimization time.
5075
      */
5076
      (!used_table && exclude_expensive_cond && cond->is_expensive()))
5077
    return (COND*) 0;				// Can't check this yet
5078
  if (cond->marker == 2 || cond->eq_cmp_result() == Item::COND_OK)
5079
    return cond;				// Not boolean op
5080
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5081
  /*
1 by brian
clean slate
5082
    Remove equalities that are guaranteed to be true by use of 'ref' access
5083
    method
5084
  */
5085
  if (((Item_func*) cond)->functype() == Item_func::EQ_FUNC)
5086
  {
5087
    Item *left_item=	((Item_func*) cond)->arguments()[0];
5088
    Item *right_item= ((Item_func*) cond)->arguments()[1];
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
5089
    if (left_item->type() == Item::FIELD_ITEM && test_if_ref((Item_field*) left_item,right_item))
1 by brian
clean slate
5090
    {
5091
      cond->marker=3;			// Checked when read
5092
      return (COND*) 0;
5093
    }
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
5094
    if (right_item->type() == Item::FIELD_ITEM &&	test_if_ref((Item_field*) right_item,left_item))
1 by brian
clean slate
5095
    {
5096
      cond->marker=3;			// Checked when read
5097
      return (COND*) 0;
5098
    }
5099
  }
5100
  cond->marker=2;
5101
  return cond;
5102
}
5103
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
5104
static Item *part_of_refkey(Table *table,Field *field)
1 by brian
clean slate
5105
{
5106
  if (!table->reginfo.join_tab)
5107
    return (Item*) 0;             // field from outer non-select (UPDATE,...)
5108
482 by Brian Aker
Remove uint.
5109
  uint32_t ref_parts=table->reginfo.join_tab->ref.key_parts;
1 by brian
clean slate
5110
  if (ref_parts)
5111
  {
5112
    KEY_PART_INFO *key_part=
5113
      table->key_info[table->reginfo.join_tab->ref.key].key_part;
482 by Brian Aker
Remove uint.
5114
    uint32_t part;
1 by brian
clean slate
5115
5116
    for (part=0 ; part < ref_parts ; part++)
5117
    {
5118
      if (table->reginfo.join_tab->ref.cond_guards[part])
5119
        return 0;
5120
    }
5121
5122
    for (part=0 ; part < ref_parts ; part++,key_part++)
5123
      if (field->eq(key_part->field) &&
5124
	  !(key_part->key_part_flag & HA_PART_KEY_SEG))
5125
	return table->reginfo.join_tab->ref.items[part];
5126
  }
5127
  return (Item*) 0;
5128
}
5129
5130
/**
327.2.3 by Brian Aker
Refactoring of class Table
5131
  Test if one can use the key to resolve order_st BY.
1 by brian
clean slate
5132
5133
  @param order                 Sort order
5134
  @param table                 Table to sort
5135
  @param idx                   Index to check
5136
  @param used_key_parts        Return value for used key parts.
5137
5138
5139
  @note
5140
    used_key_parts is set to correct key parts used if return value != 0
5141
    (On other cases, used_key_part may be changed)
5142
5143
  @retval
5144
    1   key is ok.
5145
  @retval
5146
    0   Key can't be used
5147
  @retval
5148
    -1   Reverse key can be used
5149
*/
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
5150
static int test_if_order_by_key(order_st *order, Table *table, uint32_t idx, uint32_t *used_key_parts)
1 by brian
clean slate
5151
{
5152
  KEY_PART_INFO *key_part,*key_part_end;
5153
  key_part=table->key_info[idx].key_part;
5154
  key_part_end=key_part+table->key_info[idx].key_parts;
5155
  key_part_map const_key_parts=table->const_key_parts[idx];
5156
  int reverse=0;
148 by Brian Aker
my_bool cleanup
5157
  bool on_primary_key= false;
1 by brian
clean slate
5158
5159
  for (; order ; order=order->next, const_key_parts>>=1)
5160
  {
5161
    Field *field=((Item_field*) (*order->item)->real_item())->field;
5162
    int flag;
5163
5164
    /*
5165
      Skip key parts that are constants in the WHERE clause.
327.2.3 by Brian Aker
Refactoring of class Table
5166
      These are already skipped in the order_st BY by const_expression_in_where()
1 by brian
clean slate
5167
    */
5168
    for (; const_key_parts & 1 ; const_key_parts>>= 1)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5169
      key_part++;
1 by brian
clean slate
5170
5171
    if (key_part == key_part_end)
5172
    {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5173
      /*
1 by brian
clean slate
5174
        We are at the end of the key. Check if the engine has the primary
5175
        key as a suffix to the secondary keys. If it has continue to check
5176
        the primary key as a suffix.
5177
      */
5178
      if (!on_primary_key &&
5179
          (table->file->ha_table_flags() & HA_PRIMARY_KEY_IN_READ_INDEX) &&
5180
          table->s->primary_key != MAX_KEY)
5181
      {
55 by brian
Update for using real bool types.
5182
        on_primary_key= true;
1 by brian
clean slate
5183
        key_part= table->key_info[table->s->primary_key].key_part;
5184
        key_part_end=key_part+table->key_info[table->s->primary_key].key_parts;
5185
        const_key_parts=table->const_key_parts[table->s->primary_key];
5186
5187
        for (; const_key_parts & 1 ; const_key_parts>>= 1)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5188
          key_part++;
1 by brian
clean slate
5189
        /*
5190
         The primary and secondary key parts were all const (i.e. there's
5191
         one row).  The sorting doesn't matter.
5192
        */
5193
        if (key_part == key_part_end && reverse == 0)
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
5194
          return(1);
1 by brian
clean slate
5195
      }
5196
      else
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
5197
        return(0);
1 by brian
clean slate
5198
    }
5199
5200
    if (key_part->field != field)
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
5201
      return(0);
1 by brian
clean slate
5202
5203
    /* set flag to 1 if we can use read-next on key, else to -1 */
5204
    flag= ((order->asc == !(key_part->key_part_flag & HA_REVERSE_SORT)) ?
5205
           1 : -1);
5206
    if (reverse && flag != reverse)
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
5207
      return(0);
1 by brian
clean slate
5208
    reverse=flag;				// Remember if reverse
5209
    key_part++;
5210
  }
5211
  *used_key_parts= on_primary_key ? table->key_info[idx].key_parts :
895 by Brian Aker
Completion (?) of uint conversion.
5212
    (uint32_t) (key_part - table->key_info[idx].key_part);
1 by brian
clean slate
5213
  if (reverse == -1 && !(table->file->index_flags(idx, *used_key_parts-1, 1) &
5214
                         HA_READ_PREV))
5215
    reverse= 0;                                 // Index can't be used
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
5216
  return(reverse);
1 by brian
clean slate
5217
}
5218
5219
/**
5220
  Test if a second key is the subkey of the first one.
5221
5222
  @param key_part              First key parts
5223
  @param ref_key_part          Second key parts
5224
  @param ref_key_part_end      Last+1 part of the second key
5225
5226
  @note
5227
    Second key MUST be shorter than the first one.
5228
5229
  @retval
5230
    1	is a subkey
5231
  @retval
5232
    0	no sub key
5233
*/
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
5234
inline bool is_subkey(KEY_PART_INFO *key_part,
5235
                      KEY_PART_INFO *ref_key_part,
5236
	                    KEY_PART_INFO *ref_key_part_end)
1 by brian
clean slate
5237
{
5238
  for (; ref_key_part < ref_key_part_end; key_part++, ref_key_part++)
5239
    if (!key_part->field->eq(ref_key_part->field))
5240
      return 0;
5241
  return 1;
5242
}
5243
5244
/**
5245
  Test if we can use one of the 'usable_keys' instead of 'ref' key
5246
  for sorting.
5247
5248
  @param ref			Number of key, used for WHERE clause
5249
  @param usable_keys		Keys for testing
5250
5251
  @return
5252
    - MAX_KEY			If we can't use other key
5253
    - the number of found key	Otherwise
5254
*/
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
5255
static uint32_t test_if_subkey(order_st *order,
5256
                               Table *table,
5257
                               uint32_t ref,
5258
                               uint32_t ref_key_parts,
5259
	                             const key_map *usable_keys)
1 by brian
clean slate
5260
{
365.2.6 by Monty Taylor
Undid some stupid int->int16_t conversions.
5261
  uint32_t nr;
5262
  uint32_t min_length= UINT32_MAX;
5263
  uint32_t best= MAX_KEY;
5264
  uint32_t not_used;
1 by brian
clean slate
5265
  KEY_PART_INFO *ref_key_part= table->key_info[ref].key_part;
5266
  KEY_PART_INFO *ref_key_part_end= ref_key_part + ref_key_parts;
5267
5268
  for (nr= 0 ; nr < table->s->keys ; nr++)
5269
  {
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
5270
    if (usable_keys->test(nr) &&
1 by brian
clean slate
5271
	table->key_info[nr].key_length < min_length &&
5272
	table->key_info[nr].key_parts >= ref_key_parts &&
5273
	is_subkey(table->key_info[nr].key_part, ref_key_part,
5274
		  ref_key_part_end) &&
5275
	test_if_order_by_key(order, table, nr, &not_used))
5276
    {
5277
      min_length= table->key_info[nr].key_length;
5278
      best= nr;
5279
    }
5280
  }
5281
  return best;
5282
}
5283
5284
/**
5285
  Check if GROUP BY/DISTINCT can be optimized away because the set is
5286
  already known to be distinct.
5287
5288
  Used in removing the GROUP BY/DISTINCT of the following types of
5289
  statements:
5290
  @code
5291
    SELECT [DISTINCT] <unique_key_cols>... FROM <single_table_ref>
5292
      [GROUP BY <unique_key_cols>,...]
5293
  @endcode
5294
5295
    If (a,b,c is distinct)
5296
    then <any combination of a,b,c>,{whatever} is also distinct
5297
5298
    This function checks if all the key parts of any of the unique keys
5299
    of the table are referenced by a list : either the select list
5300
    through find_field_in_item_list or GROUP BY list through
5301
    find_field_in_order_list.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5302
    If the above holds and the key parts cannot contain NULLs then we
1 by brian
clean slate
5303
    can safely remove the GROUP BY/DISTINCT,
5304
    as no result set can be more distinct than an unique key.
5305
5306
  @param table                The table to operate on.
5307
  @param find_func            function to iterate over the list and search
5308
                              for a field
5309
5310
  @retval
5311
    1                    found
5312
  @retval
5313
    0                    not found.
5314
*/
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
5315
bool list_contains_unique_index(Table *table, bool (*find_func) (Field *, void *), void *data)
1 by brian
clean slate
5316
{
482 by Brian Aker
Remove uint.
5317
  for (uint32_t keynr= 0; keynr < table->s->keys; keynr++)
1 by brian
clean slate
5318
  {
5319
    if (keynr == table->s->primary_key ||
5320
         (table->key_info[keynr].flags & HA_NOSAME))
5321
    {
5322
      KEY *keyinfo= table->key_info + keynr;
5323
      KEY_PART_INFO *key_part, *key_part_end;
5324
5325
      for (key_part=keyinfo->key_part,
5326
           key_part_end=key_part+ keyinfo->key_parts;
5327
           key_part < key_part_end;
5328
           key_part++)
5329
      {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5330
        if (key_part->field->maybe_null() ||
1 by brian
clean slate
5331
            !find_func(key_part->field, data))
5332
          break;
5333
      }
5334
      if (key_part == key_part_end)
5335
        return 1;
5336
    }
5337
  }
5338
  return 0;
5339
}
5340
5341
/**
5342
  Helper function for list_contains_unique_index.
327.2.3 by Brian Aker
Refactoring of class Table
5343
  Find a field reference in a list of order_st structures.
1 by brian
clean slate
5344
  Finds a direct reference of the Field in the list.
5345
5346
  @param field                The field to search for.
327.2.3 by Brian Aker
Refactoring of class Table
5347
  @param data                 order_st *.The list to search in
1 by brian
clean slate
5348
5349
  @retval
5350
    1                    found
5351
  @retval
5352
    0                    not found.
5353
*/
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
5354
bool find_field_in_order_list (Field *field, void *data)
1 by brian
clean slate
5355
{
327.2.3 by Brian Aker
Refactoring of class Table
5356
  order_st *group= (order_st *) data;
1 by brian
clean slate
5357
  bool part_found= 0;
327.2.3 by Brian Aker
Refactoring of class Table
5358
  for (order_st *tmp_group= group; tmp_group; tmp_group=tmp_group->next)
1 by brian
clean slate
5359
  {
5360
    Item *item= (*tmp_group->item)->real_item();
5361
    if (item->type() == Item::FIELD_ITEM &&
5362
        ((Item_field*) item)->field->eq(field))
5363
    {
5364
      part_found= 1;
5365
      break;
5366
    }
5367
  }
5368
  return part_found;
5369
}
5370
5371
/**
5372
  Helper function for list_contains_unique_index.
5373
  Find a field reference in a dynamic list of Items.
5374
  Finds a direct reference of the Field in the list.
5375
5376
  @param[in] field             The field to search for.
5377
  @param[in] data              List<Item> *.The list to search in
5378
5379
  @retval
5380
    1                    found
5381
  @retval
5382
    0                    not found.
5383
*/
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
5384
bool find_field_in_item_list (Field *field, void *data)
1 by brian
clean slate
5385
{
5386
  List<Item> *fields= (List<Item> *) data;
5387
  bool part_found= 0;
5388
  List_iterator<Item> li(*fields);
5389
  Item *item;
5390
5391
  while ((item= li++))
5392
  {
5393
    if (item->type() == Item::FIELD_ITEM &&
5394
        ((Item_field*) item)->field->eq(field))
5395
    {
5396
      part_found= 1;
5397
      break;
5398
    }
5399
  }
5400
  return part_found;
5401
}
5402
5403
/**
327.2.3 by Brian Aker
Refactoring of class Table
5404
  Test if we can skip the order_st BY by using an index.
1 by brian
clean slate
5405
5406
  SYNOPSIS
5407
    test_if_skip_sort_order()
5408
      tab
5409
      order
5410
      select_limit
5411
      no_changes
5412
      map
5413
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
5414
  If we can use an index, the JoinTable / tab->select struct
1 by brian
clean slate
5415
  is changed to use the index.
5416
5417
  The index must cover all fields in <order>, or it will not be considered.
5418
5419
  @todo
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5420
    - sergeyp: Results of all index merge selects actually are ordered
1 by brian
clean slate
5421
    by clustered PK values.
5422
5423
  @retval
5424
    0    We have to use filesort to do the sorting
5425
  @retval
5426
    1    We can use an index.
5427
*/
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
5428
bool test_if_skip_sort_order(JoinTable *tab, order_st *order, ha_rows select_limit, bool no_changes, const key_map *map)
1 by brian
clean slate
5429
{
365.2.6 by Monty Taylor
Undid some stupid int->int16_t conversions.
5430
  int32_t ref_key;
482 by Brian Aker
Remove uint.
5431
  uint32_t ref_key_parts;
1 by brian
clean slate
5432
  int order_direction;
365.2.6 by Monty Taylor
Undid some stupid int->int16_t conversions.
5433
  uint32_t used_key_parts;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
5434
  Table *table=tab->table;
1 by brian
clean slate
5435
  SQL_SELECT *select=tab->select;
5436
  key_map usable_keys;
5437
  QUICK_SELECT_I *save_quick= 0;
5438
5439
  /*
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
5440
    Keys disabled by ALTER Table ... DISABLE KEYS should have already
1 by brian
clean slate
5441
    been taken into account.
5442
  */
5443
  usable_keys= *map;
5444
327.2.3 by Brian Aker
Refactoring of class Table
5445
  for (order_st *tmp_order=order; tmp_order ; tmp_order=tmp_order->next)
1 by brian
clean slate
5446
  {
5447
    Item *item= (*tmp_order->item)->real_item();
5448
    if (item->type() != Item::FIELD_ITEM)
5449
    {
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
5450
      usable_keys.reset();
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
5451
      return(0);
1 by brian
clean slate
5452
    }
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
5453
    usable_keys&= ((Item_field*) item)->field->part_of_sortkey;
5454
    if (usable_keys.none())
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
5455
      return(0);					// No usable keys
1 by brian
clean slate
5456
  }
5457
5458
  ref_key= -1;
5459
  /* Test if constant range in WHERE */
5460
  if (tab->ref.key >= 0 && tab->ref.key_parts)
5461
  {
5462
    ref_key=	   tab->ref.key;
5463
    ref_key_parts= tab->ref.key_parts;
1108.6.20 by Padraig O'Sullivan
Renamed access_type to access_method due to conflicts on Solaris.
5464
    if (tab->type == AM_REF_OR_NULL)
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
5465
      return(0);
1 by brian
clean slate
5466
  }
5467
  else if (select && select->quick)		// Range found by opt_range
5468
  {
5469
    int quick_type= select->quick->get_type();
5470
    save_quick= select->quick;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5471
    /*
5472
      assume results are not ordered when index merge is used
5473
      TODO: sergeyp: Results of all index merge selects actually are ordered
1 by brian
clean slate
5474
      by clustered PK values.
5475
    */
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5476
5477
    if (quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE ||
5478
        quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION ||
1 by brian
clean slate
5479
        quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT)
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
5480
      return(0);
1 by brian
clean slate
5481
    ref_key=	   select->quick->index;
5482
    ref_key_parts= select->quick->used_key_parts;
5483
  }
5484
5485
  if (ref_key >= 0)
5486
  {
5487
    /*
5488
      We come here when there is a REF key.
5489
    */
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
5490
    if (! usable_keys.test(ref_key))
1 by brian
clean slate
5491
    {
5492
      /*
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
5493
        We come here when ref_key is not among usable_keys
1 by brian
clean slate
5494
      */
482 by Brian Aker
Remove uint.
5495
      uint32_t new_ref_key;
1 by brian
clean slate
5496
      /*
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
5497
        If using index only read, only consider other possible index only
5498
        keys
1 by brian
clean slate
5499
      */
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
5500
      if (table->covering_keys.test(ref_key))
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
5501
        usable_keys&= table->covering_keys;
1 by brian
clean slate
5502
      if (tab->pre_idx_push_select_cond)
5503
        tab->select_cond= tab->select->cond= tab->pre_idx_push_select_cond;
5504
      if ((new_ref_key= test_if_subkey(order, table, ref_key, ref_key_parts,
5505
				       &usable_keys)) < MAX_KEY)
5506
      {
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
5507
        /* Found key that can be used to retrieve data in sorted order */
5508
        if (tab->ref.key >= 0)
5509
        {
1 by brian
clean slate
5510
          /*
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5511
            We'll use ref access method on key new_ref_key. In general case
1 by brian
clean slate
5512
            the index search tuple for new_ref_key will be different (e.g.
5513
            when one index is defined as (part1, part2, ...) and another as
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5514
            (part1, part2(N), ...) and the WHERE clause contains
5515
            "part1 = const1 AND part2=const2".
1 by brian
clean slate
5516
            So we build tab->ref from scratch here.
5517
          */
1089.1.8 by Brian Aker
Shuffled around a few structures.
5518
          KeyUse *keyuse= tab->keyuse;
1 by brian
clean slate
5519
          while (keyuse->key != new_ref_key && keyuse->table == tab->table)
5520
            keyuse++;
5521
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5522
          if (create_ref_for_key(tab->join, tab, keyuse,
1 by brian
clean slate
5523
                                 tab->join->const_table_map))
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
5524
            return(0);
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
5525
        }
5526
        else
5527
        {
1 by brian
clean slate
5528
          /*
5529
            The range optimizer constructed QUICK_RANGE for ref_key, and
5530
            we want to use instead new_ref_key as the index. We can't
5531
            just change the index of the quick select, because this may
5532
            result in an incosistent QUICK_SELECT object. Below we
5533
            create a new QUICK_SELECT from scratch so that all its
5534
            parameres are set correctly by the range optimizer.
5535
           */
5536
          key_map new_ref_key_map;
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
5537
          new_ref_key_map.reset();  // Force the creation of quick select
5538
          new_ref_key_map.set(new_ref_key); // only for new_ref_key.
1 by brian
clean slate
5539
520.1.22 by Brian Aker
Second pass of thd cleanup
5540
          if (select->test_quick_select(tab->join->session, new_ref_key_map, 0,
1 by brian
clean slate
5541
                                        (tab->join->select_options &
5542
                                         OPTION_FOUND_ROWS) ?
5543
                                        HA_POS_ERROR :
5544
                                        tab->join->unit->select_limit_cnt,0,
55 by brian
Update for using real bool types.
5545
                                        true) <=
1 by brian
clean slate
5546
              0)
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
5547
            return(0);
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
5548
        }
1 by brian
clean slate
5549
        ref_key= new_ref_key;
5550
      }
5551
    }
5552
    /* Check if we get the rows in requested sorted order by using the key */
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
5553
    if (usable_keys.test(ref_key) &&
1 by brian
clean slate
5554
        (order_direction= test_if_order_by_key(order,table,ref_key,
5555
					       &used_key_parts)))
5556
      goto check_reverse_order;
5557
  }
5558
  {
5559
    /*
5560
      Check whether there is an index compatible with the given order
5561
      usage of which is cheaper than usage of the ref_key index (ref_key>=0)
5562
      or a table scan.
327.2.3 by Brian Aker
Refactoring of class Table
5563
      It may be the case if order_st/GROUP BY is used with LIMIT.
1 by brian
clean slate
5564
    */
482 by Brian Aker
Remove uint.
5565
    uint32_t nr;
1 by brian
clean slate
5566
    key_map keys;
482 by Brian Aker
Remove uint.
5567
    uint32_t best_key_parts= 0;
1 by brian
clean slate
5568
    int best_key_direction= 0;
5569
    ha_rows best_records= 0;
5570
    double read_time;
5571
    int best_key= -1;
55 by brian
Update for using real bool types.
5572
    bool is_best_covering= false;
1 by brian
clean slate
5573
    double fanout= 1;
5574
    JOIN *join= tab->join;
482 by Brian Aker
Remove uint.
5575
    uint32_t tablenr= tab - join->join_tab;
1 by brian
clean slate
5576
    ha_rows table_records= table->file->stats.records;
5577
    bool group= join->group && order == join->group_list;
1108.6.4 by Padraig O'Sullivan
Made the best_positions member of the JOIN class private and added any
5578
    Position cur_pos;
1 by brian
clean slate
5579
5580
    /*
5581
      If not used with LIMIT, only use keys if the whole query can be
5582
      resolved with a key;  This is because filesort() is usually faster than
5583
      retrieving all rows through an index.
5584
    */
5585
    if (select_limit >= table_records)
5586
    {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5587
      /*
5588
        filesort() and join cache are usually faster than reading in
1 by brian
clean slate
5589
        index order and not using join cache
5590
        */
1108.6.20 by Padraig O'Sullivan
Renamed access_type to access_method due to conflicts on Solaris.
5591
      if (tab->type == AM_ALL && tab->join->tables > tab->join->const_tables + 1)
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
5592
        return(0);
1 by brian
clean slate
5593
      keys= *table->file->keys_to_use_for_scanning();
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
5594
      keys|= table->covering_keys;
1 by brian
clean slate
5595
5596
      /*
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
5597
        We are adding here also the index specified in FORCE INDEX clause,
5598
        if any.
327.2.3 by Brian Aker
Refactoring of class Table
5599
        This is to allow users to use index in order_st BY.
1 by brian
clean slate
5600
      */
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5601
      if (table->force_index)
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
5602
        keys|= (group ? table->keys_in_use_for_group_by :
5603
                                table->keys_in_use_for_order_by);
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
5604
      keys&= usable_keys;
1 by brian
clean slate
5605
    }
5606
    else
5607
      keys= usable_keys;
5608
1108.6.4 by Padraig O'Sullivan
Made the best_positions member of the JOIN class private and added any
5609
    cur_pos= join->getPosFromOptimalPlan(tablenr);
5610
    read_time= cur_pos.read_time;
482 by Brian Aker
Remove uint.
5611
    for (uint32_t i= tablenr+1; i < join->tables; i++)
1108.6.4 by Padraig O'Sullivan
Made the best_positions member of the JOIN class private and added any
5612
    {
5613
      cur_pos= join->getPosFromOptimalPlan(i);
5614
      fanout*= cur_pos.records_read; // fanout is always >= 1
5615
    }
1 by brian
clean slate
5616
5617
    for (nr=0; nr < table->s->keys ; nr++)
5618
    {
5619
      int direction;
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
5620
      if (keys.test(nr) &&
1 by brian
clean slate
5621
          (direction= test_if_order_by_key(order, table, nr, &used_key_parts)))
5622
      {
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
5623
        bool is_covering= table->covering_keys.test(nr) || (nr == table->s->primary_key && table->file->primary_key_is_clustered());
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5624
5625
        /*
327.2.3 by Brian Aker
Refactoring of class Table
5626
          Don't use an index scan with order_st BY without limit.
1 by brian
clean slate
5627
          For GROUP BY without limit always use index scan
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5628
          if there is a suitable index.
1 by brian
clean slate
5629
          Why we hold to this asymmetry hardly can be explained
5630
          rationally. It's easy to demonstrate that using
5631
          temporary table + filesort could be cheaper for grouping
5632
          queries too.
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
5633
        */
1 by brian
clean slate
5634
        if (is_covering ||
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5635
            select_limit != HA_POS_ERROR ||
1 by brian
clean slate
5636
            (ref_key < 0 && (group || table->force_index)))
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5637
        {
1 by brian
clean slate
5638
          double rec_per_key;
5639
          double index_scan_time;
5640
          KEY *keyinfo= tab->table->key_info+nr;
5641
          if (select_limit == HA_POS_ERROR)
5642
            select_limit= table_records;
5643
          if (group)
5644
          {
5645
            rec_per_key= keyinfo->rec_per_key[used_key_parts-1];
937.2.6 by Stewart Smith
make set_if_bigger typesafe for C and C++. Fix up everywhere.
5646
            set_if_bigger(rec_per_key, 1.0);
1 by brian
clean slate
5647
            /*
5648
              With a grouping query each group containing on average
5649
              rec_per_key records produces only one row that will
5650
              be included into the result set.
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
5651
            */
1 by brian
clean slate
5652
            if (select_limit > table_records/rec_per_key)
5653
                select_limit= table_records;
5654
            else
5655
              select_limit= (ha_rows) (select_limit*rec_per_key);
5656
          }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5657
          /*
1 by brian
clean slate
5658
            If tab=tk is not the last joined table tn then to get first
5659
            L records from the result set we can expect to retrieve
5660
            only L/fanout(tk,tn) where fanout(tk,tn) says how many
5661
            rows in the record set on average will match each row tk.
5662
            Usually our estimates for fanouts are too pessimistic.
5663
            So the estimate for L/fanout(tk,tn) will be too optimistic
5664
            and as result we'll choose an index scan when using ref/range
5665
            access + filesort will be cheaper.
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
5666
          */
1 by brian
clean slate
5667
          select_limit= (ha_rows) (select_limit < fanout ?
5668
                                   1 : select_limit/fanout);
5669
          /*
5670
            We assume that each of the tested indexes is not correlated
5671
            with ref_key. Thus, to select first N records we have to scan
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5672
            N/selectivity(ref_key) index entries.
1 by brian
clean slate
5673
            selectivity(ref_key) = #scanned_records/#table_records =
5674
            table->quick_condition_rows/table_records.
5675
            In any case we can't select more than #table_records.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5676
            N/(table->quick_condition_rows/table_records) > table_records
1 by brian
clean slate
5677
            <=> N > table->quick_condition_rows.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5678
          */
1 by brian
clean slate
5679
          if (select_limit > table->quick_condition_rows)
5680
            select_limit= table_records;
5681
          else
5682
            select_limit= (ha_rows) (select_limit *
5683
                                     (double) table_records /
5684
                                      table->quick_condition_rows);
5685
          rec_per_key= keyinfo->rec_per_key[keyinfo->key_parts-1];
937.2.6 by Stewart Smith
make set_if_bigger typesafe for C and C++. Fix up everywhere.
5686
          set_if_bigger(rec_per_key, 1.0);
1 by brian
clean slate
5687
          /*
5688
            Here we take into account the fact that rows are
5689
            accessed in sequences rec_per_key records in each.
5690
            Rows in such a sequence are supposed to be ordered
5691
            by rowid/primary key. When reading the data
5692
            in a sequence we'll touch not more pages than the
5693
            table file contains.
5694
            TODO. Use the formula for a disk sweep sequential access
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5695
            to calculate the cost of accessing data rows for one
1 by brian
clean slate
5696
            index entry.
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
5697
          */
1 by brian
clean slate
5698
          index_scan_time= select_limit/rec_per_key *
1067.4.4 by Nathan Williams
The rest of the files in the drizzled directory were purged of the cmin macro and replace with std::min (except for the definition in globals.h and 1 usage in stacktrace.cc).
5699
                           min(rec_per_key, table->file->scan_time());
1 by brian
clean slate
5700
          if (is_covering || (ref_key < 0 && (group || table->force_index)) ||
5701
              index_scan_time < read_time)
5702
          {
5703
            ha_rows quick_records= table_records;
5704
            if (is_best_covering && !is_covering)
5705
              continue;
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
5706
            if (table->quick_keys.test(nr))
1 by brian
clean slate
5707
              quick_records= table->quick_rows[nr];
5708
            if (best_key < 0 ||
1067.4.4 by Nathan Williams
The rest of the files in the drizzled directory were purged of the cmin macro and replace with std::min (except for the definition in globals.h and 1 usage in stacktrace.cc).
5709
                (select_limit <= min(quick_records,best_records) ?
1 by brian
clean slate
5710
                 keyinfo->key_parts < best_key_parts :
5711
                 quick_records < best_records))
5712
            {
5713
              best_key= nr;
5714
              best_key_parts= keyinfo->key_parts;
5715
              best_records= quick_records;
5716
              is_best_covering= is_covering;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5717
              best_key_direction= direction;
1 by brian
clean slate
5718
            }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5719
          }
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
5720
        }
1 by brian
clean slate
5721
      }
5722
    }
5723
    if (best_key >= 0)
5724
    {
55 by brian
Update for using real bool types.
5725
      bool quick_created= false;
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
5726
      if (table->quick_keys.test(best_key) && best_key != ref_key)
1 by brian
clean slate
5727
      {
779.3.10 by Monty Taylor
Turned on -Wshadow.
5728
        key_map test_map;
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
5729
        test_map.reset();       // Force the creation of quick select
5730
        test_map.set(best_key); // only best_key.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5731
        quick_created=
779.3.10 by Monty Taylor
Turned on -Wshadow.
5732
          select->test_quick_select(join->session, test_map, 0,
1 by brian
clean slate
5733
                                    join->select_options & OPTION_FOUND_ROWS ?
5734
                                    HA_POS_ERROR :
5735
                                    join->unit->select_limit_cnt,
55 by brian
Update for using real bool types.
5736
                                    true, false) > 0;
1 by brian
clean slate
5737
      }
5738
      if (!no_changes)
5739
      {
5740
        if (!quick_created)
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
5741
        {
1 by brian
clean slate
5742
          tab->index= best_key;
5743
          tab->read_first_record= best_key_direction > 0 ?
5744
                                  join_read_first:join_read_last;
1108.6.20 by Padraig O'Sullivan
Renamed access_type to access_method due to conflicts on Solaris.
5745
          tab->type= AM_NEXT;           // Read with index_first(), index_next()
1 by brian
clean slate
5746
          if (select && select->quick)
5747
          {
5748
            delete select->quick;
5749
            select->quick= 0;
5750
          }
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
5751
          if (table->covering_keys.test(best_key))
1 by brian
clean slate
5752
          {
5753
            table->key_read=1;
5754
            table->file->extra(HA_EXTRA_KEYREAD);
5755
          }
5756
          table->file->ha_index_or_rnd_end();
5757
          if (join->select_options & SELECT_DESCRIBE)
5758
          {
5759
            tab->ref.key= -1;
5760
            tab->ref.key_parts= 0;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5761
            if (select_limit < table_records)
1 by brian
clean slate
5762
              tab->limit= select_limit;
5763
          }
5764
        }
1108.6.20 by Padraig O'Sullivan
Renamed access_type to access_method due to conflicts on Solaris.
5765
        else if (tab->type != AM_ALL)
1 by brian
clean slate
5766
        {
5767
          /*
5768
            We're about to use a quick access to the table.
5769
            We need to change the access method so as the quick access
5770
            method is actually used.
5771
          */
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
5772
          assert(tab->select->quick);
1108.6.20 by Padraig O'Sullivan
Renamed access_type to access_method due to conflicts on Solaris.
5773
          tab->type= AM_ALL;
1 by brian
clean slate
5774
          tab->use_quick=1;
5775
          tab->ref.key= -1;
5776
          tab->ref.key_parts=0;		// Don't use ref key.
5777
          tab->read_first_record= join_init_read_record;
5778
          /*
5779
            TODO: update the number of records in join->best_positions[tablenr]
5780
          */
5781
        }
5782
      }
5783
      used_key_parts= best_key_parts;
5784
      order_direction= best_key_direction;
5785
    }
5786
    else
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5787
      return(0);
5788
  }
1 by brian
clean slate
5789
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5790
check_reverse_order:
327.2.3 by Brian Aker
Refactoring of class Table
5791
  if (order_direction == -1)		// If order_st BY ... DESC
1 by brian
clean slate
5792
  {
5793
    if (select && select->quick)
5794
    {
5795
      /*
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
5796
        Don't reverse the sort order, if it's already done.
1 by brian
clean slate
5797
        (In some cases test_if_order_by_key() can be called multiple times
5798
      */
5799
      if (!select->quick->reverse_sorted())
5800
      {
5801
        QUICK_SELECT_DESC *tmp;
55 by brian
Update for using real bool types.
5802
        bool error= false;
1 by brian
clean slate
5803
        int quick_type= select->quick->get_type();
5804
        if (quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE ||
5805
            quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT ||
5806
            quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION ||
5807
            quick_type == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX)
5808
        {
5809
          tab->limit= 0;
5810
          select->quick= save_quick;
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
5811
          return(0);                   // Use filesort
1 by brian
clean slate
5812
        }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5813
327.2.3 by Brian Aker
Refactoring of class Table
5814
        /* order_st BY range_key DESC */
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
5815
        tmp= new QUICK_SELECT_DESC((QUICK_RANGE_SELECT*)(select->quick),
5816
                                          used_key_parts, &error);
5817
        if (!tmp || error)
5818
        {
5819
          delete tmp;
5820
                select->quick= save_quick;
5821
                tab->limit= 0;
5822
          return(0);		// Reverse sort not supported
5823
        }
5824
        select->quick=tmp;
1 by brian
clean slate
5825
      }
5826
    }
1108.6.20 by Padraig O'Sullivan
Renamed access_type to access_method due to conflicts on Solaris.
5827
    else if (tab->type != AM_NEXT &&
1 by brian
clean slate
5828
             tab->ref.key >= 0 && tab->ref.key_parts <= used_key_parts)
5829
    {
5830
      /*
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
5831
        SELECT * FROM t1 WHERE a=1 order_st BY a DESC,b DESC
1 by brian
clean slate
5832
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
5833
        Use a traversal function that starts by reading the last row
5834
        with key part (A) and then traverse the index backwards.
1 by brian
clean slate
5835
      */
5836
      tab->read_first_record= join_read_last_key;
5837
      tab->read_record.read_record= join_read_prev_same;
5838
    }
5839
  }
5840
  else if (select && select->quick)
5841
    select->quick->sorted= 1;
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
5842
  return(1);
1 by brian
clean slate
5843
}
5844
5845
/*
5846
  If not selecting by given key, create an index how records should be read
5847
5848
  SYNOPSIS
5849
   create_sort_index()
520.1.22 by Brian Aker
Second pass of thd cleanup
5850
     session		Thread handler
1 by brian
clean slate
5851
     tab		Table to sort (in join structure)
5852
     order		How table should be sorted
5853
     filesort_limit	Max number of rows that needs to be sorted
5854
     select_limit	Max number of rows in final output
5855
		        Used to decide if we should use index or not
327.2.3 by Brian Aker
Refactoring of class Table
5856
     is_order_by        true if we are sorting on order_st BY, false if GROUP BY
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5857
                        Used to decide if we should use index or not
1 by brian
clean slate
5858
5859
5860
  IMPLEMENTATION
5861
   - If there is an index that can be used, 'tab' is modified to use
5862
     this index.
5863
   - If no index, create with filesort() an index file that can be used to
5864
     retrieve rows in order (should be done with 'read_record').
5865
     The sorted data is stored in tab->table and will be freed when calling
1109.1.4 by Brian Aker
More Table refactor
5866
     tab->table->free_io_cache().
1 by brian
clean slate
5867
5868
  RETURN VALUES
5869
    0		ok
5870
    -1		Some fatal error
5871
    1		No records
5872
*/
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
5873
int create_sort_index(Session *session, JOIN *join, order_st *order, ha_rows filesort_limit, ha_rows select_limit, bool is_order_by)
1 by brian
clean slate
5874
{
482 by Brian Aker
Remove uint.
5875
  uint32_t length= 0;
1 by brian
clean slate
5876
  ha_rows examined_rows;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
5877
  Table *table;
1 by brian
clean slate
5878
  SQL_SELECT *select;
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
5879
  JoinTable *tab;
1 by brian
clean slate
5880
5881
  if (join->tables == join->const_tables)
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
5882
    return(0);				// One row, no need to sort
1 by brian
clean slate
5883
  tab=    join->join_tab + join->const_tables;
5884
  table=  tab->table;
5885
  select= tab->select;
5886
5887
  /*
5888
    When there is SQL_BIG_RESULT do not sort using index for GROUP BY,
5889
    and thus force sorting on disk unless a group min-max optimization
5890
    is going to be used as it is applied now only for one table queries
5891
    with covering indexes.
5892
  */
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5893
  if ((order != join->group_list ||
1 by brian
clean slate
5894
       !(join->select_options & SELECT_BIG_RESULT) ||
5895
       (select && select->quick && (select->quick->get_type() == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX))) &&
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5896
      test_if_skip_sort_order(tab,order,select_limit,0,
1 by brian
clean slate
5897
                              is_order_by ?  &table->keys_in_use_for_order_by :
5898
                              &table->keys_in_use_for_group_by))
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
5899
    return(0);
327.2.3 by Brian Aker
Refactoring of class Table
5900
  for (order_st *ord= join->order; ord; ord= ord->next)
1 by brian
clean slate
5901
    length++;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5902
  if (!(join->sortorder=
1 by brian
clean slate
5903
        make_unireg_sortorder(order, &length, join->sortorder)))
5904
    goto err;				/* purecov: inspected */
5905
684 by Brian Aker
Mass cleanup for casting.
5906
  table->sort.io_cache= new IO_CACHE;
641.3.7 by Monty Taylor
More my_malloc removal.
5907
  memset(table->sort.io_cache, 0, sizeof(IO_CACHE));
1 by brian
clean slate
5908
  table->status=0;				// May be wrong if quick_select
5909
5910
  // If table has a range, move it to select
5911
  if (select && !select->quick && tab->ref.key >= 0)
5912
  {
5913
    if (tab->quick)
5914
    {
5915
      select->quick=tab->quick;
5916
      tab->quick=0;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5917
      /*
1 by brian
clean slate
5918
        We can only use 'Only index' if quick key is same as ref_key
5919
        and in index_merge 'Only index' cannot be used
5920
      */
895 by Brian Aker
Completion (?) of uint conversion.
5921
      if (table->key_read && ((uint32_t) tab->ref.key != select->quick->index))
1 by brian
clean slate
5922
      {
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
5923
        table->key_read=0;
5924
        table->file->extra(HA_EXTRA_NO_KEYREAD);
1 by brian
clean slate
5925
      }
5926
    }
5927
    else
5928
    {
5929
      /*
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
5930
        We have a ref on a const;  Change this to a range that filesort
5931
        can use.
5932
        For impossible ranges (like when doing a lookup on NULL on a NOT NULL
5933
        field, quick will contain an empty record set.
1 by brian
clean slate
5934
      */
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
5935
      if (!(select->quick= (get_quick_select_for_ref(session, table, &tab->ref,
1 by brian
clean slate
5936
                                                     tab->found_records))))
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
5937
        goto err;
1 by brian
clean slate
5938
    }
5939
  }
5940
5941
  /* Fill schema tables with data before filesort if it's necessary */
5942
  if ((join->select_lex->options & OPTION_SCHEMA_TABLE) &&
5943
      get_schema_tables_result(join, PROCESSED_BY_CREATE_SORT_INDEX))
5944
    goto err;
5945
5946
  if (table->s->tmp_table)
5947
    table->file->info(HA_STATUS_VARIABLE);	// Get record count
520.1.22 by Brian Aker
Second pass of thd cleanup
5948
  table->sort.found_records=filesort(session, table,join->sortorder, length,
1 by brian
clean slate
5949
                                     select, filesort_limit, 0,
5950
                                     &examined_rows);
5951
  tab->records= table->sort.found_records;	// For SQL_CALC_ROWS
5952
  if (select)
5953
  {
5954
    select->cleanup();				// filesort did select
5955
    tab->select= 0;
5956
  }
5957
  tab->select_cond=0;
5958
  tab->last_inner= 0;
5959
  tab->first_unmatched= 0;
1108.6.20 by Padraig O'Sullivan
Renamed access_type to access_method due to conflicts on Solaris.
5960
  tab->type= AM_ALL;				// Read with normal read_record
1 by brian
clean slate
5961
  tab->read_first_record= join_init_read_record;
5962
  tab->join->examined_rows+=examined_rows;
5963
  if (table->key_read)				// Restore if we used indexes
5964
  {
5965
    table->key_read=0;
5966
    table->file->extra(HA_EXTRA_NO_KEYREAD);
5967
  }
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
5968
  return(table->sort.found_records == HA_POS_ERROR);
1 by brian
clean slate
5969
err:
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
5970
  return(-1);
1 by brian
clean slate
5971
}
5972
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
5973
int remove_dup_with_compare(Session *session, Table *table, Field **first_field, uint32_t offset, Item *having)
1 by brian
clean slate
5974
{
5975
  handler *file=table->file;
5976
  char *org_record,*new_record;
481 by Brian Aker
Remove all of uchar.
5977
  unsigned char *record;
1 by brian
clean slate
5978
  int error;
574 by Brian Aker
Cleaning up ulong. Doing this while listening to Jimmy explain memcached...
5979
  uint32_t reclength= table->s->reclength-offset;
1 by brian
clean slate
5980
5981
  org_record=(char*) (record=table->record[0])+offset;
5982
  new_record=(char*) table->record[1]+offset;
5983
5984
  file->ha_rnd_init(1);
5985
  error=file->rnd_next(record);
5986
  for (;;)
5987
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
5988
    if (session->killed)
1 by brian
clean slate
5989
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
5990
      session->send_kill_message();
1 by brian
clean slate
5991
      error=0;
5992
      goto err;
5993
    }
5994
    if (error)
5995
    {
5996
      if (error == HA_ERR_RECORD_DELETED)
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
5997
        continue;
1 by brian
clean slate
5998
      if (error == HA_ERR_END_OF_FILE)
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
5999
        break;
1 by brian
clean slate
6000
      goto err;
6001
    }
6002
    if (having && !having->val_int())
6003
    {
6004
      if ((error=file->ha_delete_row(record)))
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
6005
        goto err;
1 by brian
clean slate
6006
      error=file->rnd_next(record);
6007
      continue;
6008
    }
6009
    if (copy_blobs(first_field))
6010
    {
6011
      my_message(ER_OUTOFMEMORY, ER(ER_OUTOFMEMORY), MYF(0));
6012
      error=0;
6013
      goto err;
6014
    }
6015
    memcpy(new_record,org_record,reclength);
6016
6017
    /* Read through rest of file and mark duplicated rows deleted */
6018
    bool found=0;
6019
    for (;;)
6020
    {
6021
      if ((error=file->rnd_next(record)))
6022
      {
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
6023
        if (error == HA_ERR_RECORD_DELETED)
6024
          continue;
6025
        if (error == HA_ERR_END_OF_FILE)
6026
          break;
6027
        goto err;
1 by brian
clean slate
6028
      }
355 by Brian Aker
More Table cleanup
6029
      if (table->compare_record(first_field) == 0)
1 by brian
clean slate
6030
      {
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
6031
        if ((error=file->ha_delete_row(record)))
6032
          goto err;
1 by brian
clean slate
6033
      }
6034
      else if (!found)
6035
      {
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
6036
        found= 1;
6037
        file->position(record);	// Remember position
1 by brian
clean slate
6038
      }
6039
    }
6040
    if (!found)
6041
      break;					// End of file
6042
    /* Restart search on next row */
6043
    error=file->restart_rnd_next(record,file->ref);
6044
  }
6045
6046
  file->extra(HA_EXTRA_NO_CACHE);
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
6047
  return(0);
1 by brian
clean slate
6048
err:
6049
  file->extra(HA_EXTRA_NO_CACHE);
6050
  if (error)
6051
    file->print_error(error,MYF(0));
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
6052
  return(1);
1 by brian
clean slate
6053
}
6054
6055
/**
6056
  Generate a hash index for each row to quickly find duplicate rows.
6057
6058
  @note
6059
    Note that this will not work on tables with blobs!
6060
*/
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
6061
int remove_dup_with_hash_index(Session *session, 
6062
                               Table *table,
6063
                               uint32_t field_count,
6064
                               Field **first_field,
6065
                               uint32_t key_length,
6066
                               Item *having)
1 by brian
clean slate
6067
{
481 by Brian Aker
Remove all of uchar.
6068
  unsigned char *key_buffer, *key_pos, *record=table->record[0];
1 by brian
clean slate
6069
  int error;
6070
  handler *file= table->file;
574 by Brian Aker
Cleaning up ulong. Doing this while listening to Jimmy explain memcached...
6071
  uint32_t extra_length= ALIGN_SIZE(key_length)-key_length;
482 by Brian Aker
Remove uint.
6072
  uint32_t *field_lengths,*field_length;
1 by brian
clean slate
6073
  HASH hash;
6074
6075
  if (!my_multi_malloc(MYF(MY_WME),
6076
		       &key_buffer,
895 by Brian Aker
Completion (?) of uint conversion.
6077
		       (uint32_t) ((key_length + extra_length) *
1 by brian
clean slate
6078
			       (long) file->stats.records),
6079
		       &field_lengths,
895 by Brian Aker
Completion (?) of uint conversion.
6080
		       (uint32_t) (field_count*sizeof(*field_lengths)),
461 by Monty Taylor
Removed NullS. bu-bye.
6081
		       NULL))
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
6082
    return(1);
1 by brian
clean slate
6083
6084
  {
6085
    Field **ptr;
574 by Brian Aker
Cleaning up ulong. Doing this while listening to Jimmy explain memcached...
6086
    uint32_t total_length= 0;
1 by brian
clean slate
6087
    for (ptr= first_field, field_length=field_lengths ; *ptr ; ptr++)
6088
    {
482 by Brian Aker
Remove uint.
6089
      uint32_t length= (*ptr)->sort_length();
1 by brian
clean slate
6090
      (*field_length++)= length;
6091
      total_length+= length;
6092
    }
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
6093
    assert(total_length <= key_length);
1 by brian
clean slate
6094
    key_length= total_length;
6095
    extra_length= ALIGN_SIZE(key_length)-key_length;
6096
  }
6097
895 by Brian Aker
Completion (?) of uint conversion.
6098
  if (hash_init(&hash, &my_charset_bin, (uint32_t) file->stats.records, 0,
1 by brian
clean slate
6099
		key_length, (hash_get_key) 0, 0, 0))
6100
  {
477 by Monty Taylor
Removed my_free(). It turns out that it had been def'd to ignore the flags passed to it in the second arg anyway. Gotta love that.
6101
    free((char*) key_buffer);
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
6102
    return(1);
1 by brian
clean slate
6103
  }
6104
6105
  file->ha_rnd_init(1);
6106
  key_pos=key_buffer;
6107
  for (;;)
6108
  {
481 by Brian Aker
Remove all of uchar.
6109
    unsigned char *org_key_pos;
520.1.22 by Brian Aker
Second pass of thd cleanup
6110
    if (session->killed)
1 by brian
clean slate
6111
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
6112
      session->send_kill_message();
1 by brian
clean slate
6113
      error=0;
6114
      goto err;
6115
    }
6116
    if ((error=file->rnd_next(record)))
6117
    {
6118
      if (error == HA_ERR_RECORD_DELETED)
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
6119
        continue;
1 by brian
clean slate
6120
      if (error == HA_ERR_END_OF_FILE)
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
6121
        break;
1 by brian
clean slate
6122
      goto err;
6123
    }
6124
    if (having && !having->val_int())
6125
    {
6126
      if ((error=file->ha_delete_row(record)))
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
6127
        goto err;
1 by brian
clean slate
6128
      continue;
6129
    }
6130
6131
    /* copy fields to key buffer */
6132
    org_key_pos= key_pos;
6133
    field_length=field_lengths;
6134
    for (Field **ptr= first_field ; *ptr ; ptr++)
6135
    {
6136
      (*ptr)->sort_string(key_pos,*field_length);
6137
      key_pos+= *field_length++;
6138
    }
6139
    /* Check if it exists before */
6140
    if (hash_search(&hash, org_key_pos, key_length))
6141
    {
6142
      /* Duplicated found ; Remove the row */
6143
      if ((error=file->ha_delete_row(record)))
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
6144
        goto err;
1 by brian
clean slate
6145
    }
6146
    else
6147
      (void) my_hash_insert(&hash, org_key_pos);
6148
    key_pos+=extra_length;
6149
  }
477 by Monty Taylor
Removed my_free(). It turns out that it had been def'd to ignore the flags passed to it in the second arg anyway. Gotta love that.
6150
  free((char*) key_buffer);
1 by brian
clean slate
6151
  hash_free(&hash);
6152
  file->extra(HA_EXTRA_NO_CACHE);
6153
  (void) file->ha_rnd_end();
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
6154
  return(0);
1 by brian
clean slate
6155
6156
err:
477 by Monty Taylor
Removed my_free(). It turns out that it had been def'd to ignore the flags passed to it in the second arg anyway. Gotta love that.
6157
  free((char*) key_buffer);
1 by brian
clean slate
6158
  hash_free(&hash);
6159
  file->extra(HA_EXTRA_NO_CACHE);
6160
  (void) file->ha_rnd_end();
6161
  if (error)
6162
    file->print_error(error,MYF(0));
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
6163
  return(1);
1 by brian
clean slate
6164
}
6165
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
6166
SORT_FIELD *make_unireg_sortorder(order_st *order, uint32_t *length, SORT_FIELD *sortorder)
1 by brian
clean slate
6167
{
482 by Brian Aker
Remove uint.
6168
  uint32_t count;
1 by brian
clean slate
6169
  SORT_FIELD *sort,*pos;
6170
6171
  count=0;
327.2.3 by Brian Aker
Refactoring of class Table
6172
  for (order_st *tmp = order; tmp; tmp=tmp->next)
1 by brian
clean slate
6173
    count++;
6174
  if (!sortorder)
6175
    sortorder= (SORT_FIELD*) sql_alloc(sizeof(SORT_FIELD) *
1067.4.7 by Nathan Williams
The remaining files using cmax have been converted to std::max.
6176
                                       (max(count, *length) + 1));
1 by brian
clean slate
6177
  pos= sort= sortorder;
6178
6179
  if (!pos)
6180
    return 0;
6181
6182
  for (;order;order=order->next,pos++)
6183
  {
6184
    Item *item= order->item[0]->real_item();
6185
    pos->field= 0; pos->item= 0;
6186
    if (item->type() == Item::FIELD_ITEM)
6187
      pos->field= ((Item_field*) item)->field;
6188
    else if (item->type() == Item::SUM_FUNC_ITEM && !item->const_item())
6189
      pos->field= ((Item_sum*) item)->get_tmp_table_field();
6190
    else if (item->type() == Item::COPY_STR_ITEM)
6191
    {						// Blob patch
6192
      pos->item= ((Item_copy_string*) item)->item;
6193
    }
6194
    else
6195
      pos->item= *order->item;
6196
    pos->reverse=! order->asc;
6197
  }
6198
  *length=count;
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
6199
  return(sort);
1 by brian
clean slate
6200
}
6201
6202
/*
6203
  eq_ref: Create the lookup key and check if it is the same as saved key
6204
6205
  SYNOPSIS
6206
    cmp_buffer_with_ref()
6207
      tab  Join tab of the accessed table
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
6208
6209
  DESCRIPTION
6210
    Used by eq_ref access method: create the index lookup key and check if
1 by brian
clean slate
6211
    we've used this key at previous lookup (If yes, we don't need to repeat
6212
    the lookup - the record has been already fetched)
6213
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
6214
  RETURN
55 by brian
Update for using real bool types.
6215
    true   No cached record for the key, or failed to create the key (due to
1 by brian
clean slate
6216
           out-of-domain error)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
6217
    false  The created key is the same as the previous one (and the record
1 by brian
clean slate
6218
           is already in table->record)
6219
*/
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
6220
static bool cmp_buffer_with_ref(JoinTable *tab)
1 by brian
clean slate
6221
{
6222
  bool no_prev_key;
6223
  if (!tab->ref.disable_cache)
6224
  {
6225
    if (!(no_prev_key= tab->ref.key_err))
6226
    {
6227
      /* Previous access found a row. Copy its key */
6228
      memcpy(tab->ref.key_buff2, tab->ref.key_buff, tab->ref.key_length);
6229
    }
6230
  }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
6231
  else
55 by brian
Update for using real bool types.
6232
    no_prev_key= true;
520.1.22 by Brian Aker
Second pass of thd cleanup
6233
  if ((tab->ref.key_err= cp_buffer_from_ref(tab->join->session, &tab->ref)) ||
1 by brian
clean slate
6234
      no_prev_key)
6235
    return 1;
6236
  return memcmp(tab->ref.key_buff2, tab->ref.key_buff, tab->ref.key_length)
6237
    != 0;
6238
}
6239
1089.1.14 by Brian Aker
Fix TABLE_REF structure
6240
bool cp_buffer_from_ref(Session *session, table_reference_st *ref)
1 by brian
clean slate
6241
{
520.1.22 by Brian Aker
Second pass of thd cleanup
6242
  enum enum_check_fields save_count_cuted_fields= session->count_cuted_fields;
6243
  session->count_cuted_fields= CHECK_FIELD_IGNORE;
1 by brian
clean slate
6244
  bool result= 0;
6245
1039.2.3 by Jay Pipes
Phase 3 of refactoring JOIN
6246
  for (StoredKey **copy=ref->key_copy ; *copy ; copy++)
1 by brian
clean slate
6247
  {
6248
    if ((*copy)->copy() & 1)
6249
    {
6250
      result= 1;
6251
      break;
6252
    }
6253
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
6254
  session->count_cuted_fields= save_count_cuted_fields;
1 by brian
clean slate
6255
  return result;
6256
}
6257
6258
/*****************************************************************************
6259
  Group and order functions
6260
*****************************************************************************/
6261
6262
/**
327.2.3 by Brian Aker
Refactoring of class Table
6263
  Resolve an order_st BY or GROUP BY column reference.
1 by brian
clean slate
6264
327.2.3 by Brian Aker
Refactoring of class Table
6265
  Given a column reference (represented by 'order') from a GROUP BY or order_st
1 by brian
clean slate
6266
  BY clause, find the actual column it represents. If the column being
6267
  resolved is from the GROUP BY clause, the procedure searches the SELECT
6268
  list 'fields' and the columns in the FROM list 'tables'. If 'order' is from
327.2.3 by Brian Aker
Refactoring of class Table
6269
  the order_st BY clause, only the SELECT list is being searched.
1 by brian
clean slate
6270
6271
  If 'order' is resolved to an Item, then order->item is set to the found
6272
  Item. If there is no item for the found column (that is, it was resolved
6273
  into a table field), order->item is 'fixed' and is added to all_fields and
6274
  ref_pointer_array.
6275
6276
  ref_pointer_array and all_fields are updated.
6277
520.1.22 by Brian Aker
Second pass of thd cleanup
6278
  @param[in] session		     Pointer to current thread structure
1 by brian
clean slate
6279
  @param[in,out] ref_pointer_array  All select, group and order by fields
6280
  @param[in] tables                 List of tables to search in (usually
6281
    FROM clause)
6282
  @param[in] order                  Column reference to be resolved
6283
  @param[in] fields                 List of fields to search in (usually
6284
    SELECT list)
6285
  @param[in,out] all_fields         All select, group and order by fields
6286
  @param[in] is_group_field         True if order is a GROUP field, false if
327.2.3 by Brian Aker
Refactoring of class Table
6287
    order_st by field
1 by brian
clean slate
6288
6289
  @retval
55 by brian
Update for using real bool types.
6290
    false if OK
1 by brian
clean slate
6291
  @retval
55 by brian
Update for using real bool types.
6292
    true  if error occurred
1 by brian
clean slate
6293
*/
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
6294
static bool find_order_in_list(Session *session, 
6295
                               Item **ref_pointer_array, 
6296
                               TableList *tables,
6297
                               order_st *order,
6298
                               List<Item> &fields,
6299
                               List<Item> &all_fields,
6300
                               bool is_group_field)
1 by brian
clean slate
6301
{
327.2.3 by Brian Aker
Refactoring of class Table
6302
  Item *order_item= *order->item; /* The item from the GROUP/order_st caluse. */
1 by brian
clean slate
6303
  Item::Type order_item_type;
6304
  Item **select_item; /* The corresponding item from the SELECT clause. */
6305
  Field *from_field;  /* The corresponding field from the FROM clause. */
482 by Brian Aker
Remove uint.
6306
  uint32_t counter;
1 by brian
clean slate
6307
  enum_resolution_type resolution;
6308
6309
  /*
6310
    Local SP variables may be int but are expressions, not positions.
6311
    (And they can't be used before fix_fields is called for them).
6312
  */
6313
  if (order_item->type() == Item::INT_ITEM && order_item->basic_const_item())
6314
  {						/* Order by position */
895 by Brian Aker
Completion (?) of uint conversion.
6315
    uint32_t count= (uint32_t) order_item->val_int();
1 by brian
clean slate
6316
    if (!count || count > fields.elements)
6317
    {
6318
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
520.1.22 by Brian Aker
Second pass of thd cleanup
6319
               order_item->full_name(), session->where);
55 by brian
Update for using real bool types.
6320
      return true;
1 by brian
clean slate
6321
    }
6322
    order->item= ref_pointer_array + count - 1;
6323
    order->in_field_list= 1;
6324
    order->counter= count;
6325
    order->counter_used= 1;
55 by brian
Update for using real bool types.
6326
    return false;
1 by brian
clean slate
6327
  }
327.2.3 by Brian Aker
Refactoring of class Table
6328
  /* Lookup the current GROUP/order_st field in the SELECT clause. */
1 by brian
clean slate
6329
  select_item= find_item_in_list(order_item, fields, &counter,
6330
                                 REPORT_EXCEPT_NOT_FOUND, &resolution);
6331
  if (!select_item)
55 by brian
Update for using real bool types.
6332
    return true; /* The item is not unique, or some other error occured. */
1 by brian
clean slate
6333
6334
6335
  /* Check whether the resolved field is not ambiguos. */
6336
  if (select_item != not_found_item)
6337
  {
6338
    Item *view_ref= NULL;
6339
    /*
6340
      If we have found field not by its alias in select list but by its
6341
      original field name, we should additionaly check if we have conflict
6342
      for this name (in case if we would perform lookup in all tables).
6343
    */
6344
    if (resolution == RESOLVED_BEHIND_ALIAS && !order_item->fixed &&
520.1.22 by Brian Aker
Second pass of thd cleanup
6345
        order_item->fix_fields(session, order->item))
55 by brian
Update for using real bool types.
6346
      return true;
1 by brian
clean slate
6347
6348
    /* Lookup the current GROUP field in the FROM clause. */
6349
    order_item_type= order_item->type();
6350
    from_field= (Field*) not_found_field;
6351
    if ((is_group_field && order_item_type == Item::FIELD_ITEM) ||
6352
        order_item_type == Item::REF_ITEM)
6353
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
6354
      from_field= find_field_in_tables(session, (Item_ident*) order_item, tables,
1113.1.1 by Brian Aker
Dead code removal around LCOV finds.
6355
                                       NULL, &view_ref, IGNORE_ERRORS, false);
1 by brian
clean slate
6356
      if (!from_field)
6357
        from_field= (Field*) not_found_field;
6358
    }
6359
6360
    if (from_field == not_found_field ||
6361
        (from_field != view_ref_found ?
6362
         /* it is field of base table => check that fields are same */
6363
         ((*select_item)->type() == Item::FIELD_ITEM &&
6364
          ((Item_field*) (*select_item))->field->eq(from_field)) :
6365
         /*
6366
           in is field of view table => check that references on translation
6367
           table are same
6368
         */
6369
         ((*select_item)->type() == Item::REF_ITEM &&
6370
          view_ref->type() == Item::REF_ITEM &&
6371
          ((Item_ref *) (*select_item))->ref ==
6372
          ((Item_ref *) view_ref)->ref)))
6373
    {
6374
      /*
6375
        If there is no such field in the FROM clause, or it is the same field
6376
        as the one found in the SELECT clause, then use the Item created for
6377
        the SELECT field. As a result if there was a derived field that
6378
        'shadowed' a table field with the same name, the table field will be
6379
        chosen over the derived field.
6380
      */
6381
      order->item= ref_pointer_array + counter;
6382
      order->in_field_list=1;
55 by brian
Update for using real bool types.
6383
      return false;
1 by brian
clean slate
6384
    }
6385
    else
6386
    {
6387
      /*
6388
        There is a field with the same name in the FROM clause. This
6389
        is the field that will be chosen. In this case we issue a
6390
        warning so the user knows that the field from the FROM clause
6391
        overshadows the column reference from the SELECT list.
6392
      */
520.1.22 by Brian Aker
Second pass of thd cleanup
6393
      push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_WARN, ER_NON_UNIQ_ERROR,
1 by brian
clean slate
6394
                          ER(ER_NON_UNIQ_ERROR),
6395
                          ((Item_ident*) order_item)->field_name,
520.1.22 by Brian Aker
Second pass of thd cleanup
6396
                          current_session->where);
1 by brian
clean slate
6397
    }
6398
  }
6399
6400
  order->in_field_list=0;
6401
  /*
6402
    The call to order_item->fix_fields() means that here we resolve
6403
    'order_item' to a column from a table in the list 'tables', or to
6404
    a column in some outer query. Exactly because of the second case
6405
    we come to this point even if (select_item == not_found_item),
6406
    inspite of that fix_fields() calls find_item_in_list() one more
6407
    time.
6408
6409
    We check order_item->fixed because Item_func_group_concat can put
6410
    arguments for which fix_fields already was called.
6411
  */
6412
  if (!order_item->fixed &&
520.1.22 by Brian Aker
Second pass of thd cleanup
6413
      (order_item->fix_fields(session, order->item) ||
1 by brian
clean slate
6414
       (order_item= *order->item)->check_cols(1) ||
520.1.22 by Brian Aker
Second pass of thd cleanup
6415
       session->is_fatal_error))
55 by brian
Update for using real bool types.
6416
    return true; /* Wrong field. */
1 by brian
clean slate
6417
482 by Brian Aker
Remove uint.
6418
  uint32_t el= all_fields.elements;
1 by brian
clean slate
6419
  all_fields.push_front(order_item); /* Add new field to field list. */
6420
  ref_pointer_array[el]= order_item;
6421
  order->item= ref_pointer_array + el;
55 by brian
Update for using real bool types.
6422
  return false;
1 by brian
clean slate
6423
}
6424
6425
/**
6426
  Change order to point at item in select list.
6427
6428
  If item isn't a number and doesn't exits in the select list, add it the
6429
  the field list.
6430
*/
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
6431
int setup_order(Session *session,
6432
                Item **ref_pointer_array,
6433
                TableList *tables,
6434
		            List<Item> &fields,
6435
                List<Item> &all_fields,
6436
                order_st *order)
1 by brian
clean slate
6437
{
520.1.22 by Brian Aker
Second pass of thd cleanup
6438
  session->where="order clause";
1 by brian
clean slate
6439
  for (; order; order=order->next)
6440
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
6441
    if (find_order_in_list(session, ref_pointer_array, tables, order, fields,
55 by brian
Update for using real bool types.
6442
			   all_fields, false))
1 by brian
clean slate
6443
      return 1;
6444
  }
6445
  return 0;
6446
}
6447
6448
/**
6449
  Intitialize the GROUP BY list.
6450
520.1.22 by Brian Aker
Second pass of thd cleanup
6451
  @param session			Thread handler
1 by brian
clean slate
6452
  @param ref_pointer_array	We store references to all fields that was
6453
                               not in 'fields' here.
6454
  @param fields		All fields in the select part. Any item in
6455
                               'order' that is part of these list is replaced
6456
                               by a pointer to this fields.
6457
  @param all_fields		Total list of all unique fields used by the
6458
                               select. All items in 'order' that was not part
6459
                               of fields will be added first to this list.
6460
  @param order			The fields we should do GROUP BY on.
6461
  @param hidden_group_fields	Pointer to flag that is set to 1 if we added
6462
                               any fields to all_fields.
6463
6464
  @todo
6465
    change ER_WRONG_FIELD_WITH_GROUP to more detailed
6466
    ER_NON_GROUPING_FIELD_USED
6467
6468
  @retval
6469
    0  ok
6470
  @retval
6471
    1  error (probably out of memory)
6472
*/
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
6473
int setup_group(Session *session,
6474
                Item **ref_pointer_array,
6475
                TableList *tables,
6476
	              List<Item> &fields,
6477
                List<Item> &all_fields,
6478
                order_st *order,
6479
	              bool *hidden_group_fields)
1 by brian
clean slate
6480
{
6481
  *hidden_group_fields=0;
327.2.3 by Brian Aker
Refactoring of class Table
6482
  order_st *ord;
1 by brian
clean slate
6483
6484
  if (!order)
6485
    return 0;				/* Everything is ok */
6486
482 by Brian Aker
Remove uint.
6487
  uint32_t org_fields=all_fields.elements;
1 by brian
clean slate
6488
520.1.22 by Brian Aker
Second pass of thd cleanup
6489
  session->where="group statement";
1 by brian
clean slate
6490
  for (ord= order; ord; ord= ord->next)
6491
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
6492
    if (find_order_in_list(session, ref_pointer_array, tables, ord, fields,
55 by brian
Update for using real bool types.
6493
			   all_fields, true))
1 by brian
clean slate
6494
      return 1;
6495
    (*ord->item)->marker= UNDEF_POS;		/* Mark found */
6496
    if ((*ord->item)->with_sum_func)
6497
    {
6498
      my_error(ER_WRONG_GROUP_FIELD, MYF(0), (*ord->item)->full_name());
6499
      return 1;
6500
    }
6501
  }
6502
  /* MODE_ONLY_FULL_GROUP_BY */
6503
  {
6504
    /*
6505
      Don't allow one to use fields that is not used in GROUP BY
6506
      For each select a list of field references that aren't under an
6507
      aggregate function is created. Each field in this list keeps the
6508
      position of the select list expression which it belongs to.
6509
6510
      First we check an expression from the select list against the GROUP BY
6511
      list. If it's found there then it's ok. It's also ok if this expression
6512
      is a constant or an aggregate function. Otherwise we scan the list
6513
      of non-aggregated fields and if we'll find at least one field reference
6514
      that belongs to this expression and doesn't occur in the GROUP BY list
6515
      we throw an error. If there are no fields in the created list for a
6516
      select list expression this means that all fields in it are used under
6517
      aggregate functions.
6518
    */
6519
    Item *item;
6520
    Item_field *field;
6521
    int cur_pos_in_select_list= 0;
6522
    List_iterator<Item> li(fields);
520.1.22 by Brian Aker
Second pass of thd cleanup
6523
    List_iterator<Item_field> naf_it(session->lex->current_select->non_agg_fields);
1 by brian
clean slate
6524
6525
    field= naf_it++;
6526
    while (field && (item=li++))
6527
    {
6528
      if (item->type() != Item::SUM_FUNC_ITEM && item->marker >= 0 &&
6529
          !item->const_item() &&
6530
          !(item->real_item()->type() == Item::FIELD_ITEM &&
6531
            item->used_tables() & OUTER_REF_TABLE_BIT))
6532
      {
6533
        while (field)
6534
        {
6535
          /* Skip fields from previous expressions. */
6536
          if (field->marker < cur_pos_in_select_list)
6537
            goto next_field;
6538
          /* Found a field from the next expression. */
6539
          if (field->marker > cur_pos_in_select_list)
6540
            break;
6541
          /*
6542
            Check whether the field occur in the GROUP BY list.
6543
            Throw the error later if the field isn't found.
6544
          */
6545
          for (ord= order; ord; ord= ord->next)
6546
            if ((*ord->item)->eq((Item*)field, 0))
6547
              goto next_field;
6548
          /*
6549
            TODO: change ER_WRONG_FIELD_WITH_GROUP to more detailed
6550
            ER_NON_GROUPING_FIELD_USED
6551
          */
6552
          my_error(ER_WRONG_FIELD_WITH_GROUP, MYF(0), field->full_name());
6553
          return 1;
6554
next_field:
6555
          field= naf_it++;
6556
        }
6557
      }
6558
      cur_pos_in_select_list++;
6559
    }
6560
  }
6561
  if (org_fields != all_fields.elements)
6562
    *hidden_group_fields=1;			// group fields is not used
6563
  return 0;
6564
}
6565
6566
/**
6567
  Create a group by that consist of all non const fields.
6568
6569
  Try to use the fields in the order given by 'order' to allow one to
6570
  optimize away 'order by'.
6571
*/
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
6572
order_st *create_distinct_group(Session *session,
6573
                                Item **ref_pointer_array,
6574
                                order_st *order_list,
6575
                                List<Item> &fields,
6576
                                List<Item> &,
6577
                                bool *all_order_by_fields_used)
1 by brian
clean slate
6578
{
6579
  List_iterator<Item> li(fields);
77.1.45 by Monty Taylor
Warning fixes.
6580
  Item *item;
327.2.3 by Brian Aker
Refactoring of class Table
6581
  order_st *order,*group,**prev;
1 by brian
clean slate
6582
6583
  *all_order_by_fields_used= 1;
6584
  while ((item=li++))
6585
    item->marker=0;			/* Marker that field is not used */
6586
6587
  prev= &group;  group=0;
6588
  for (order=order_list ; order; order=order->next)
6589
  {
6590
    if (order->in_field_list)
6591
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
6592
      order_st *ord=(order_st*) session->memdup((char*) order,sizeof(order_st));
1 by brian
clean slate
6593
      if (!ord)
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
6594
        return 0;
1 by brian
clean slate
6595
      *prev=ord;
6596
      prev= &ord->next;
6597
      (*ord->item)->marker=1;
6598
    }
6599
    else
6600
      *all_order_by_fields_used= 0;
6601
  }
6602
6603
  li.rewind();
6604
  while ((item=li++))
6605
  {
6606
    if (!item->const_item() && !item->with_sum_func && !item->marker)
6607
    {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
6608
      /*
6609
        Don't put duplicate columns from the SELECT list into the
1 by brian
clean slate
6610
        GROUP BY list.
6611
      */
327.2.3 by Brian Aker
Refactoring of class Table
6612
      order_st *ord_iter;
1 by brian
clean slate
6613
      for (ord_iter= group; ord_iter; ord_iter= ord_iter->next)
6614
        if ((*ord_iter->item)->eq(item, 1))
6615
          goto next_item;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
6616
520.1.22 by Brian Aker
Second pass of thd cleanup
6617
      order_st *ord=(order_st*) session->calloc(sizeof(order_st));
1 by brian
clean slate
6618
      if (!ord)
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
6619
        return 0;
1 by brian
clean slate
6620
62 by Brian Aker
First pass of removing BIT_TYPE
6621
      /*
6622
        We have here only field_list (not all_field_list), so we can use
6623
        simple indexing of ref_pointer_array (order in the array and in the
6624
        list are same)
6625
      */
6626
      ord->item= ref_pointer_array;
1 by brian
clean slate
6627
      ord->asc=1;
6628
      *prev=ord;
6629
      prev= &ord->next;
6630
    }
6631
next_item:
6632
    ref_pointer_array++;
6633
  }
6634
  *prev=0;
6635
  return group;
6636
}
6637
6638
/**
6639
  Update join with count of the different type of fields.
6640
*/
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
6641
void count_field_types(Select_Lex *select_lex, Tmp_Table_Param *param, List<Item> &fields, bool reset_with_sum_func)
1 by brian
clean slate
6642
{
6643
  List_iterator<Item> li(fields);
6644
  Item *field;
6645
6646
  param->field_count=param->sum_func_count=param->func_count=
6647
    param->hidden_field_count=0;
6648
  param->quick_group=1;
6649
  while ((field=li++))
6650
  {
6651
    Item::Type real_type= field->real_item()->type();
6652
    if (real_type == Item::FIELD_ITEM)
6653
      param->field_count++;
6654
    else if (real_type == Item::SUM_FUNC_ITEM)
6655
    {
6656
      if (! field->const_item())
6657
      {
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
6658
        Item_sum *sum_item=(Item_sum*) field->real_item();
1 by brian
clean slate
6659
        if (!sum_item->depended_from() ||
6660
            sum_item->depended_from() == select_lex)
6661
        {
6662
          if (!sum_item->quick_group)
6663
            param->quick_group=0;			// UDF SUM function
6664
          param->sum_func_count++;
6665
482 by Brian Aker
Remove uint.
6666
          for (uint32_t i=0 ; i < sum_item->arg_count ; i++)
1 by brian
clean slate
6667
          {
6668
            if (sum_item->args[0]->real_item()->type() == Item::FIELD_ITEM)
6669
              param->field_count++;
6670
            else
6671
              param->func_count++;
6672
          }
6673
        }
6674
        param->func_count++;
6675
      }
6676
    }
6677
    else
6678
    {
6679
      param->func_count++;
6680
      if (reset_with_sum_func)
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
6681
        field->with_sum_func=0;
6682
    }
6683
  }
6684
}
1 by brian
clean slate
6685
6686
/*
6687
  Test if a single-row cache of items changed, and update the cache.
6688
6689
  @details Test if a list of items that typically represents a result
6690
  row has changed. If the value of some item changed, update the cached
6691
  value for this item.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
6692
1 by brian
clean slate
6693
  @param list list of <item, cached_value> pairs stored as Cached_item.
6694
6695
  @return -1 if no item changed
6696
  @return index of the first item that changed
6697
*/
1101.1.16 by Monty Taylor
Reverted 1103
6698
int test_if_item_cache_changed(List<Cached_item> &list)
1 by brian
clean slate
6699
{
1101.1.16 by Monty Taylor
Reverted 1103
6700
  List_iterator<Cached_item> li(list);
6701
  int idx= -1,i;
6702
  Cached_item *buff;
1 by brian
clean slate
6703
1101.1.16 by Monty Taylor
Reverted 1103
6704
  for (i=(int) list.elements-1 ; (buff=li++) ; i--)
1 by brian
clean slate
6705
  {
1101.1.16 by Monty Taylor
Reverted 1103
6706
    if (buff->cmp())
6707
      idx=i;
1 by brian
clean slate
6708
  }
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
6709
  return(idx);
1 by brian
clean slate
6710
}
6711
6712
/**
6713
  Setup copy_fields to save fields at start of new group.
6714
6715
  Setup copy_fields to save fields at start of new group
6716
6717
  Only FIELD_ITEM:s and FUNC_ITEM:s needs to be saved between groups.
6718
  Change old item_field to use a new field with points at saved fieldvalue
6719
  This function is only called before use of send_fields.
6720
520.1.22 by Brian Aker
Second pass of thd cleanup
6721
  @param session                   Session pointer
1 by brian
clean slate
6722
  @param param                 temporary table parameters
6723
  @param ref_pointer_array     array of pointers to top elements of filed list
6724
  @param res_selected_fields   new list of items of select item list
6725
  @param res_all_fields        new list of all items
6726
  @param elements              number of elements in select item list
6727
  @param all_fields            all fields list
6728
6729
  @todo
6730
    In most cases this result will be sent to the user.
6731
    This should be changed to use copy_int or copy_real depending
6732
    on how the value is to be used: In some cases this may be an
6733
    argument in a group function, like: IF(ISNULL(col),0,COUNT(*))
6734
6735
  @retval
6736
    0     ok
6737
  @retval
6738
    !=0   error
6739
*/
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
6740
bool setup_copy_fields(Session *session,
6741
                       Tmp_Table_Param *param,
6742
                       Item **ref_pointer_array,
6743
                       List<Item> &res_selected_fields,
6744
                       List<Item> &res_all_fields,
6745
                       uint32_t elements,
6746
                       List<Item> &all_fields)
1 by brian
clean slate
6747
{
6748
  Item *pos;
6749
  List_iterator_fast<Item> li(all_fields);
1052.2.2 by Nathan Williams
No actual code changes. Changed Copy_field to CopyField, to reflect the coding standards.
6750
  CopyField *copy= NULL;
1 by brian
clean slate
6751
  res_selected_fields.empty();
6752
  res_all_fields.empty();
6753
  List_iterator_fast<Item> itr(res_all_fields);
1101.1.16 by Monty Taylor
Reverted 1103
6754
  List<Item> extra_funcs;
482 by Brian Aker
Remove uint.
6755
  uint32_t i, border= all_fields.elements - elements;
1 by brian
clean slate
6756
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
6757
  if (param->field_count &&
1052.2.2 by Nathan Williams
No actual code changes. Changed Copy_field to CopyField, to reflect the coding standards.
6758
      !(copy=param->copy_field= new CopyField[param->field_count]))
1 by brian
clean slate
6759
    goto err2;
6760
1101.1.16 by Monty Taylor
Reverted 1103
6761
  param->copy_funcs.empty();
1 by brian
clean slate
6762
  for (i= 0; (pos= li++); i++)
6763
  {
6764
    Field *field;
481 by Brian Aker
Remove all of uchar.
6765
    unsigned char *tmp;
1 by brian
clean slate
6766
    Item *real_pos= pos->real_item();
6767
    if (real_pos->type() == Item::FIELD_ITEM)
6768
    {
6769
      Item_field *item;
520.1.22 by Brian Aker
Second pass of thd cleanup
6770
      if (!(item= new Item_field(session, ((Item_field*) real_pos))))
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
6771
        goto err;
1 by brian
clean slate
6772
      if (pos->type() == Item::REF_ITEM)
6773
      {
6774
        /* preserve the names of the ref when dereferncing */
6775
        Item_ref *ref= (Item_ref *) pos;
6776
        item->db_name= ref->db_name;
6777
        item->table_name= ref->table_name;
6778
        item->name= ref->name;
6779
      }
6780
      pos= item;
6781
      if (item->field->flags & BLOB_FLAG)
6782
      {
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
6783
        if (!(pos= new Item_copy_string(pos)))
6784
          goto err;
1101.1.16 by Monty Taylor
Reverted 1103
6785
            /*
6786
              Item_copy_string::copy for function can call
6787
              Item_copy_string::val_int for blob via Item_ref.
6788
              But if Item_copy_string::copy for blob isn't called before,
6789
              it's value will be wrong
6790
              so let's insert Item_copy_string for blobs in the beginning of
6791
              copy_funcs
6792
              (to see full test case look at having.test, BUG #4358)
6793
            */
6794
        if (param->copy_funcs.push_front(pos))
6795
          goto err;
1 by brian
clean slate
6796
      }
6797
      else
6798
      {
6799
        /*
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
6800
          set up save buffer and change result_field to point at
6801
          saved value
1 by brian
clean slate
6802
        */
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
6803
        field= item->field;
6804
        item->result_field=field->new_field(session->mem_root,field->table, 1);
6805
              /*
6806
                We need to allocate one extra byte for null handling and
6807
                another extra byte to not get warnings from purify in
6808
                Field_varstring::val_int
6809
              */
6810
        if (!(tmp= (unsigned char*) sql_alloc(field->pack_length()+2)))
6811
          goto err;
1 by brian
clean slate
6812
        if (copy)
6813
        {
6814
          copy->set(tmp, item->result_field);
6815
          item->result_field->move_field(copy->to_ptr,copy->to_null_ptr,1);
6816
#ifdef HAVE_purify
6817
          copy->to_ptr[copy->from_length]= 0;
6818
#endif
6819
          copy++;
6820
        }
6821
      }
6822
    }
6823
    else if ((real_pos->type() == Item::FUNC_ITEM ||
6824
	      real_pos->type() == Item::SUBSELECT_ITEM ||
6825
	      real_pos->type() == Item::CACHE_ITEM ||
6826
	      real_pos->type() == Item::COND_ITEM) &&
6827
	     !real_pos->with_sum_func)
6828
    {						// Save for send fields
6829
      pos= real_pos;
6830
      /* TODO:
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
6831
        In most cases this result will be sent to the user.
6832
        This should be changed to use copy_int or copy_real depending
6833
        on how the value is to be used: In some cases this may be an
6834
        argument in a group function, like: IF(ISNULL(col),0,COUNT(*))
1 by brian
clean slate
6835
      */
6836
      if (!(pos=new Item_copy_string(pos)))
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
6837
        goto err;
327.2.3 by Brian Aker
Refactoring of class Table
6838
      if (i < border)                           // HAVING, order_st and GROUP BY
1 by brian
clean slate
6839
      {
1101.1.16 by Monty Taylor
Reverted 1103
6840
        if (extra_funcs.push_back(pos))
6841
          goto err;
6842
      }
6843
      else if (param->copy_funcs.push_back(pos))
6844
        goto err;
1 by brian
clean slate
6845
    }
6846
    res_all_fields.push_back(pos);
6847
    ref_pointer_array[((i < border)? all_fields.elements-i-1 : i-border)]=
6848
      pos;
6849
  }
6850
  param->copy_field_end= copy;
6851
6852
  for (i= 0; i < border; i++)
6853
    itr++;
6854
  itr.sublist(res_selected_fields, elements);
6855
  /*
327.2.3 by Brian Aker
Refactoring of class Table
6856
    Put elements from HAVING, order_st BY and GROUP BY last to ensure that any
1 by brian
clean slate
6857
    reference used in these will resolve to a item that is already calculated
6858
  */
1101.1.16 by Monty Taylor
Reverted 1103
6859
  param->copy_funcs.concat(&extra_funcs);
1 by brian
clean slate
6860
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
6861
  return(0);
1 by brian
clean slate
6862
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
6863
err:
1 by brian
clean slate
6864
  if (copy)
6865
    delete [] param->copy_field;			// This is never 0
6866
  param->copy_field=0;
6867
err2:
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
6868
  return(true);
1 by brian
clean slate
6869
}
6870
6871
/**
6872
  Make a copy of all simple SELECT'ed items.
6873
6874
  This is done at the start of a new group so that we can retrieve
6875
  these later when the group changes.
6876
*/
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
6877
void copy_fields(Tmp_Table_Param *param)
1 by brian
clean slate
6878
{
1052.2.6 by Nathan Williams
More style cleanup in files associated with Copy_field to CopyField change. Primarily spacing after = operator.
6879
  CopyField *ptr= param->copy_field;
6880
  CopyField *end= param->copy_field_end;
1 by brian
clean slate
6881
6882
  for (; ptr != end; ptr++)
6883
    (*ptr->do_copy)(ptr);
6884
1101.1.16 by Monty Taylor
Reverted 1103
6885
  List_iterator_fast<Item> it(param->copy_funcs);
6886
  Item_copy_string *item;
6887
  while ((item = (Item_copy_string*) it++))
1 by brian
clean slate
6888
    item->copy();
6889
}
6890
6891
/**
6892
  Change all funcs and sum_funcs to fields in tmp table, and create
6893
  new list of all items.
6894
520.1.22 by Brian Aker
Second pass of thd cleanup
6895
  @param session                   Session pointer
1 by brian
clean slate
6896
  @param ref_pointer_array     array of pointers to top elements of filed list
6897
  @param res_selected_fields   new list of items of select item list
6898
  @param res_all_fields        new list of all items
6899
  @param elements              number of elements in select item list
6900
  @param all_fields            all fields list
6901
6902
  @retval
6903
    0     ok
6904
  @retval
6905
    !=0   error
6906
*/
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
6907
bool change_to_use_tmp_fields(Session *session,
6908
                              Item **ref_pointer_array,
6909
			                        List<Item> &res_selected_fields,
6910
			                        List<Item> &res_all_fields,
6911
			                        uint32_t elements,
6912
                              List<Item> &all_fields)
1 by brian
clean slate
6913
{
6914
  List_iterator_fast<Item> it(all_fields);
6915
  Item *item_field,*item;
6916
6917
  res_selected_fields.empty();
6918
  res_all_fields.empty();
6919
482 by Brian Aker
Remove uint.
6920
  uint32_t i, border= all_fields.elements - elements;
1 by brian
clean slate
6921
  for (i= 0; (item= it++); i++)
6922
  {
6923
    Field *field;
6924
6925
    if ((item->with_sum_func && item->type() != Item::SUM_FUNC_ITEM) ||
6926
        (item->type() == Item::FUNC_ITEM &&
6927
         ((Item_func*)item)->functype() == Item_func::SUSERVAR_FUNC))
6928
      item_field= item;
6929
    else
6930
    {
6931
      if (item->type() == Item::FIELD_ITEM)
6932
      {
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
6933
        item_field= item->get_tmp_table_item(session);
1 by brian
clean slate
6934
      }
6935
      else if ((field= item->get_tmp_table_field()))
6936
      {
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
6937
        if (item->type() == Item::SUM_FUNC_ITEM && field->table->group)
6938
          item_field= ((Item_sum*) item)->result_item(field);
6939
        else
6940
          item_field= (Item*) new Item_field(field);
6941
        if (!item_field)
6942
          return(true);                    // Fatal error
1 by brian
clean slate
6943
6944
        if (item->real_item()->type() != Item::FIELD_ITEM)
6945
          field->orig_table= 0;
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
6946
        item_field->name= item->name;
1 by brian
clean slate
6947
        if (item->type() == Item::REF_ITEM)
6948
        {
6949
          Item_field *ifield= (Item_field *) item_field;
6950
          Item_ref *iref= (Item_ref *) item;
6951
          ifield->table_name= iref->table_name;
6952
          ifield->db_name= iref->db_name;
6953
        }
6954
      }
6955
      else
1039.2.6 by Jay Pipes
No code changes...only indentation and style cleanup.
6956
        item_field= item;
1 by brian
clean slate
6957
    }
6958
    res_all_fields.push_back(item_field);
6959
    ref_pointer_array[((i < border)? all_fields.elements-i-1 : i-border)]=
6960
      item_field;
6961
  }
6962
6963
  List_iterator_fast<Item> itr(res_all_fields);
6964
  for (i= 0; i < border; i++)
6965
    itr++;
6966
  itr.sublist(res_selected_fields, elements);
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
6967
  return(false);
1 by brian
clean slate
6968
}
6969
6970
/**
6971
  Change all sum_func refs to fields to point at fields in tmp table.
6972
  Change all funcs to be fields in tmp table.
6973
520.1.22 by Brian Aker
Second pass of thd cleanup
6974
  @param session                   Session pointer
1 by brian
clean slate
6975
  @param ref_pointer_array     array of pointers to top elements of filed list
6976
  @param res_selected_fields   new list of items of select item list
6977
  @param res_all_fields        new list of all items
6978
  @param elements              number of elements in select item list
6979
  @param all_fields            all fields list
6980
6981
  @retval
6982
    0	ok
6983
  @retval
6984
    1	error
6985
*/
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
6986
bool change_refs_to_tmp_fields(Session *session,
6987
                               Item **ref_pointer_array,
6988
                               List<Item> &res_selected_fields,
6989
                               List<Item> &res_all_fields,
6990
                               uint32_t elements,
6991
			                         List<Item> &all_fields)
1 by brian
clean slate
6992
{
6993
  List_iterator_fast<Item> it(all_fields);
6994
  Item *item, *new_item;
6995
  res_selected_fields.empty();
6996
  res_all_fields.empty();
6997
482 by Brian Aker
Remove uint.
6998
  uint32_t i, border= all_fields.elements - elements;
1 by brian
clean slate
6999
  for (i= 0; (item= it++); i++)
7000
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
7001
    res_all_fields.push_back(new_item= item->get_tmp_table_item(session));
1 by brian
clean slate
7002
    ref_pointer_array[((i < border)? all_fields.elements-i-1 : i-border)]=
7003
      new_item;
7004
  }
7005
7006
  List_iterator_fast<Item> itr(res_all_fields);
7007
  for (i= 0; i < border; i++)
7008
    itr++;
7009
  itr.sublist(res_selected_fields, elements);
7010
520.1.22 by Brian Aker
Second pass of thd cleanup
7011
  return session->is_fatal_error;
1 by brian
clean slate
7012
}
7013
7014
/******************************************************************************
7015
  Code for calculating functions
7016
******************************************************************************/
7017
7018
/**
7019
  Call ::setup for all sum functions.
7020
520.1.22 by Brian Aker
Second pass of thd cleanup
7021
  @param session           thread handler
1 by brian
clean slate
7022
  @param func_ptr      sum function list
7023
7024
  @retval
55 by brian
Update for using real bool types.
7025
    false  ok
1 by brian
clean slate
7026
  @retval
55 by brian
Update for using real bool types.
7027
    true   error
1 by brian
clean slate
7028
*/
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
7029
bool setup_sum_funcs(Session *session, Item_sum **func_ptr)
1 by brian
clean slate
7030
{
7031
  Item_sum *func;
7032
  while ((func= *(func_ptr++)))
7033
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
7034
    if (func->setup(session))
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
7035
      return(true);
1 by brian
clean slate
7036
  }
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
7037
  return(false);
1 by brian
clean slate
7038
}
7039
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
7040
void init_tmptable_sum_functions(Item_sum **func_ptr)
1 by brian
clean slate
7041
{
7042
  Item_sum *func;
7043
  while ((func= *(func_ptr++)))
7044
    func->reset_field();
7045
}
7046
7047
/** Update record 0 in tmp_table from record 1. */
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
7048
void update_tmptable_sum_func(Item_sum **func_ptr, Table *)
1 by brian
clean slate
7049
{
7050
  Item_sum *func;
7051
  while ((func= *(func_ptr++)))
7052
    func->update_field();
7053
}
7054
7055
/** Copy result of sum functions to record in tmp_table. */
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
7056
void copy_sum_funcs(Item_sum **func_ptr, Item_sum **end_ptr)
1 by brian
clean slate
7057
{
7058
  for (; func_ptr != end_ptr ; func_ptr++)
7059
    (void) (*func_ptr)->save_in_result_field(1);
7060
  return;
7061
}
7062
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
7063
bool init_sum_functions(Item_sum **func_ptr, Item_sum **end_ptr)
1 by brian
clean slate
7064
{
7065
  for (; func_ptr != end_ptr ;func_ptr++)
7066
  {
7067
    if ((*func_ptr)->reset())
7068
      return 1;
7069
  }
7070
  /* If rollup, calculate the upper sum levels */
7071
  for ( ; *func_ptr ; func_ptr++)
7072
  {
7073
    if ((*func_ptr)->add())
7074
      return 1;
7075
  }
7076
  return 0;
7077
}
7078
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
7079
bool update_sum_func(Item_sum **func_ptr)
1 by brian
clean slate
7080
{
7081
  Item_sum *func;
7082
  for (; (func= (Item_sum*) *func_ptr) ; func_ptr++)
7083
    if (func->add())
7084
      return 1;
7085
  return 0;
7086
}
7087
7088
/** Copy result of functions to record in tmp_table. */
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
7089
void copy_funcs(Item **func_ptr)
1 by brian
clean slate
7090
{
7091
  Item *func;
7092
  for (; (func = *func_ptr) ; func_ptr++)
7093
    func->save_in_result_field(1);
7094
}
7095
7096
/**
7097
  Free joins of subselect of this select.
7098
520.1.22 by Brian Aker
Second pass of thd cleanup
7099
  @param session      Session pointer
846 by Brian Aker
Removing on typedeffed class.
7100
  @param select   pointer to Select_Lex which subselects joins we will free
1 by brian
clean slate
7101
*/
846 by Brian Aker
Removing on typedeffed class.
7102
void free_underlaid_joins(Session *, Select_Lex *select)
1 by brian
clean slate
7103
{
848 by Brian Aker
typdef class removal (just... use the name of the class).
7104
  for (Select_Lex_Unit *unit= select->first_inner_unit();
1 by brian
clean slate
7105
       unit;
7106
       unit= unit->next_unit())
7107
    unit->cleanup();
7108
}
7109
7110
/****************************************************************************
7111
  ROLLUP handling
7112
****************************************************************************/
7113
7114
/**
7115
  Replace occurences of group by fields in an expression by ref items.
7116
7117
  The function replaces occurrences of group by fields in expr
7118
  by ref objects for these fields unless they are under aggregate
7119
  functions.
7120
  The function also corrects value of the the maybe_null attribute
7121
  for the items of all subexpressions containing group by fields.
7122
7123
  @b EXAMPLES
7124
    @code
7125
      SELECT a+1 FROM t1 GROUP BY a WITH ROLLUP
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
7126
      SELECT SUM(a)+a FROM t1 GROUP BY a WITH ROLLUP
1 by brian
clean slate
7127
  @endcode
7128
7129
  @b IMPLEMENTATION
7130
7131
    The function recursively traverses the tree of the expr expression,
7132
    looks for occurrences of the group by fields that are not under
7133
    aggregate functions and replaces them for the corresponding ref items.
7134
7135
  @note
7136
    This substitution is needed GROUP BY queries with ROLLUP if
7137
    SELECT list contains expressions over group by attributes.
7138
520.1.22 by Brian Aker
Second pass of thd cleanup
7139
  @param session                  reference to the context
1 by brian
clean slate
7140
  @param expr                 expression to make replacement
7141
  @param group_list           list of references to group by items
7142
  @param changed        out:  returns 1 if item contains a replaced field item
7143
7144
  @todo
7145
    - TODO: Some functions are not null-preserving. For those functions
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
7146
    updating of the maybe_null attribute is an overkill.
1 by brian
clean slate
7147
7148
  @retval
7149
    0	if ok
7150
  @retval
7151
    1   on error
7152
*/
1039.2.2 by Jay Pipes
Phase 2 of JOIN refactoring.
7153
bool change_group_ref(Session *session, Item_func *expr, order_st *group_list, bool *changed)
1 by brian
clean slate
7154
{
7155
  if (expr->arg_count)
7156
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
7157
    Name_resolution_context *context= &session->lex->current_select->context;
1 by brian
clean slate
7158
    Item **arg,**arg_end;
55 by brian
Update for using real bool types.
7159
    bool arg_changed= false;
1 by brian
clean slate
7160
    for (arg= expr->arguments(),
7161
         arg_end= expr->arguments()+expr->arg_count;
7162
         arg != arg_end; arg++)
7163
    {
7164
      Item *item= *arg;
7165
      if (item->type() == Item::FIELD_ITEM || item->type() == Item::REF_ITEM)
7166
      {
327.2.3 by Brian Aker
Refactoring of class Table
7167
        order_st *group_tmp;
1 by brian
clean slate
7168
        for (group_tmp= group_list; group_tmp; group_tmp= group_tmp->next)
7169
        {
7170
          if (item->eq(*group_tmp->item,0))
7171
          {
7172
            Item *new_item;
7173
            if (!(new_item= new Item_ref(context, group_tmp->item, 0,
7174
                                        item->name)))
7175
              return 1;                                 // fatal_error is set
520.1.22 by Brian Aker
Second pass of thd cleanup
7176
            session->change_item_tree(arg, new_item);
55 by brian
Update for using real bool types.
7177
            arg_changed= true;
1 by brian
clean slate
7178
          }
7179
        }
7180
      }
7181
      else if (item->type() == Item::FUNC_ITEM)
7182
      {
520.1.22 by Brian Aker
Second pass of thd cleanup
7183
        if (change_group_ref(session, (Item_func *) item, group_list, &arg_changed))
1 by brian
clean slate
7184
          return 1;
7185
      }
7186
    }
7187
    if (arg_changed)
7188
    {
7189
      expr->maybe_null= 1;
55 by brian
Update for using real bool types.
7190
      *changed= true;
1 by brian
clean slate
7191
    }
7192
  }
7193
  return 0;
7194
}
7195
7196
/**
7197
  EXPLAIN handling.
7198
7199
  Send a description about what how the select will be done to stdout.
7200
*/
7201
void select_describe(JOIN *join, bool need_tmp_table, bool need_order,
7202
                     bool distinct,const char *message)
7203
{
7204
  List<Item> field_list;
7205
  List<Item> item_list;
520.1.22 by Brian Aker
Second pass of thd cleanup
7206
  Session *session=join->session;
1 by brian
clean slate
7207
  select_result *result=join->result;
7208
  Item *item_null= new Item_null();
264.2.6 by Andrey Hristov
Constify the usage of CHARSET_INFO almost to the last place in the code.
7209
  const CHARSET_INFO * const cs= system_charset_info;
1 by brian
clean slate
7210
  int quick_type;
7211
  /* Don't log this into the slow query log */
520.1.22 by Brian Aker
Second pass of thd cleanup
7212
  session->server_status&= ~(SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED);
1 by brian
clean slate
7213
  join->unit->offset_limit_cnt= 0;
7214
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
7215
  /*
1 by brian
clean slate
7216
    NOTE: the number/types of items pushed into item_list must be in sync with
520.1.21 by Brian Aker
THD -> Session rename
7217
    EXPLAIN column types as they're "defined" in Session::send_explain_fields()
1 by brian
clean slate
7218
  */
7219
  if (message)
7220
  {
205 by Brian Aker
uint32 -> uin32_t
7221
    item_list.push_back(new Item_int((int32_t)
1 by brian
clean slate
7222
				     join->select_lex->select_number));
7223
    item_list.push_back(new Item_string(join->select_lex->type,
7224
					strlen(join->select_lex->type), cs));
482 by Brian Aker
Remove uint.
7225
    for (uint32_t i=0 ; i < 7; i++)
1 by brian
clean slate
7226
      item_list.push_back(item_null);
520.1.22 by Brian Aker
Second pass of thd cleanup
7227
    if (join->session->lex->describe & DESCRIBE_EXTENDED)
1 by brian
clean slate
7228
      item_list.push_back(item_null);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
7229
1 by brian
clean slate
7230
    item_list.push_back(new Item_string(message,strlen(message),cs));
7231
    if (result->send_data(item_list))
7232
      join->error= 1;
7233
  }
7234
  else if (join->select_lex == join->unit->fake_select_lex)
7235
  {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
7236
    /*
1 by brian
clean slate
7237
      here we assume that the query will return at least two rows, so we
7238
      show "filesort" in EXPLAIN. Of course, sometimes we'll be wrong
7239
      and no filesort will be actually done, but executing all selects in
7240
      the UNION to provide precise EXPLAIN information will hardly be
7241
      appreciated :)
7242
    */
7243
    char table_name_buffer[NAME_LEN];
7244
    item_list.empty();
7245
    /* id */
7246
    item_list.push_back(new Item_null);
7247
    /* select_type */
7248
    item_list.push_back(new Item_string(join->select_lex->type,
7249
					strlen(join->select_lex->type),
7250
					cs));
7251
    /* table */
7252
    {
846 by Brian Aker
Removing on typedeffed class.
7253
      Select_Lex *sl= join->unit->first_select();
482 by Brian Aker
Remove uint.
7254
      uint32_t len= 6, lastop= 0;
1 by brian
clean slate
7255
      memcpy(table_name_buffer, STRING_WITH_LEN("<union"));
7256
      for (; sl && len + lastop + 5 < NAME_LEN; sl= sl->next_select())
7257
      {
7258
        len+= lastop;
77.1.18 by Monty Taylor
Removed my_vsnprintf and my_snprintf.
7259
        lastop= snprintf(table_name_buffer + len, NAME_LEN - len,
7260
                         "%u,", sl->select_number);
1 by brian
clean slate
7261
      }
7262
      if (sl || len + lastop >= NAME_LEN)
7263
      {
7264
        memcpy(table_name_buffer + len, STRING_WITH_LEN("...>") + 1);
7265
        len+= 4;
7266
      }
7267
      else
7268
      {
7269
        len+= lastop;
7270
        table_name_buffer[len - 1]= '>';  // change ',' to '>'
7271
      }
7272
      item_list.push_back(new Item_string(table_name_buffer, len, cs));
7273
    }
7274
    /* type */
1108.6.20 by Padraig O'Sullivan
Renamed access_type to access_method due to conflicts on Solaris.
7275
    item_list.push_back(new Item_string(access_method_str[AM_ALL].c_str(),
7276
					access_method_str[AM_ALL].length(),
1108.6.1 by Padraig O'Sullivan
Changed the name of the enum join_type to access_type. It makes much more
7277
					cs));
1 by brian
clean slate
7278
    /* possible_keys */
7279
    item_list.push_back(item_null);
7280
    /* key*/
7281
    item_list.push_back(item_null);
7282
    /* key_len */
7283
    item_list.push_back(item_null);
7284
    /* ref */
7285
    item_list.push_back(item_null);
7286
    /* in_rows */
520.1.22 by Brian Aker
Second pass of thd cleanup
7287
    if (join->session->lex->describe & DESCRIBE_EXTENDED)
1 by brian
clean slate
7288
      item_list.push_back(item_null);
7289
    /* rows */
7290
    item_list.push_back(item_null);
7291
    /* extra */
7292
    if (join->unit->global_parameters->order_list.first)
7293
      item_list.push_back(new Item_string("Using filesort",
7294
					  14, cs));
7295
    else
7296
      item_list.push_back(new Item_string("", 0, cs));
7297
7298
    if (result->send_data(item_list))
7299
      join->error= 1;
7300
  }
7301
  else
7302
  {
7303
    table_map used_tables=0;
482 by Brian Aker
Remove uint.
7304
    for (uint32_t i=0 ; i < join->tables ; i++)
1 by brian
clean slate
7305
    {
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
7306
      JoinTable *tab=join->join_tab+i;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
7307
      Table *table=tab->table;
327.2.4 by Brian Aker
Refactoring table.h
7308
      TableList *table_list= tab->table->pos_in_table_list;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
7309
      char buff[512];
1 by brian
clean slate
7310
      char buff1[512], buff2[512], buff3[512];
7311
      char keylen_str_buf[64];
7312
      String extra(buff, sizeof(buff),cs);
7313
      char table_name_buffer[NAME_LEN];
7314
      String tmp1(buff1,sizeof(buff1),cs);
7315
      String tmp2(buff2,sizeof(buff2),cs);
7316
      String tmp3(buff3,sizeof(buff3),cs);
7317
      extra.length(0);
7318
      tmp1.length(0);
7319
      tmp2.length(0);
7320
      tmp3.length(0);
7321
7322
      quick_type= -1;
7323
      item_list.empty();
7324
      /* id */
205 by Brian Aker
uint32 -> uin32_t
7325
      item_list.push_back(new Item_uint((uint32_t)
1 by brian
clean slate
7326
				       join->select_lex->select_number));
7327
      /* select_type */
7328
      item_list.push_back(new Item_string(join->select_lex->type,
7329
					  strlen(join->select_lex->type),
7330
					  cs));
1108.6.20 by Padraig O'Sullivan
Renamed access_type to access_method due to conflicts on Solaris.
7331
      if (tab->type == AM_ALL && tab->select && tab->select->quick)
1 by brian
clean slate
7332
      {
7333
        quick_type= tab->select->quick->get_type();
7334
        if ((quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE) ||
7335
            (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT) ||
7336
            (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION))
1108.6.20 by Padraig O'Sullivan
Renamed access_type to access_method due to conflicts on Solaris.
7337
          tab->type = AM_INDEX_MERGE;
1 by brian
clean slate
7338
        else
1108.6.20 by Padraig O'Sullivan
Renamed access_type to access_method due to conflicts on Solaris.
7339
	  tab->type = AM_RANGE;
1 by brian
clean slate
7340
      }
7341
      /* table */
7342
      if (table->derived_select_number)
7343
      {
7344
	/* Derived table name generation */
77.1.18 by Monty Taylor
Removed my_vsnprintf and my_snprintf.
7345
	int len= snprintf(table_name_buffer, sizeof(table_name_buffer)-1,
7346
		          "<derived%u>",
7347
                          table->derived_select_number);
1 by brian
clean slate
7348
	item_list.push_back(new Item_string(table_name_buffer, len, cs));
7349
      }
7350
      else
7351
      {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
7352
        TableList *real_table= table->pos_in_table_list;
1 by brian
clean slate
7353
	item_list.push_back(new Item_string(real_table->alias,
7354
					    strlen(real_table->alias),
7355
					    cs));
7356
      }
7357
      /* "type" column */
1108.6.20 by Padraig O'Sullivan
Renamed access_type to access_method due to conflicts on Solaris.
7358
      item_list.push_back(new Item_string(access_method_str[tab->type].c_str(),
7359
					  access_method_str[tab->type].length(),
1 by brian
clean slate
7360
					  cs));
7361
      /* Build "possible_keys" value and add it to item_list */
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
7362
      if (tab->keys.any())
1 by brian
clean slate
7363
      {
482 by Brian Aker
Remove uint.
7364
        uint32_t j;
1 by brian
clean slate
7365
        for (j=0 ; j < table->s->keys ; j++)
7366
        {
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
7367
          if (tab->keys.test(j))
1 by brian
clean slate
7368
          {
7369
            if (tmp1.length())
7370
              tmp1.append(',');
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
7371
            tmp1.append(table->key_info[j].name,
1 by brian
clean slate
7372
			strlen(table->key_info[j].name),
7373
			system_charset_info);
7374
          }
7375
        }
7376
      }
7377
      if (tmp1.length())
7378
	item_list.push_back(new Item_string(tmp1.ptr(),tmp1.length(),cs));
7379
      else
7380
	item_list.push_back(item_null);
7381
7382
      /* Build "key", "key_len", and "ref" values and add them to item_list */
7383
      if (tab->ref.key_parts)
7384
      {
7385
	KEY *key_info=table->key_info+ tab->ref.key;
482 by Brian Aker
Remove uint.
7386
        register uint32_t length;
1 by brian
clean slate
7387
	item_list.push_back(new Item_string(key_info->name,
7388
					    strlen(key_info->name),
7389
					    system_charset_info));
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
7390
        length= int64_t2str(tab->ref.key_length, keylen_str_buf, 10) -
1 by brian
clean slate
7391
                keylen_str_buf;
7392
        item_list.push_back(new Item_string(keylen_str_buf, length,
7393
                                            system_charset_info));
1039.2.3 by Jay Pipes
Phase 3 of refactoring JOIN
7394
	for (StoredKey **ref=tab->ref.key_copy ; *ref ; ref++)
1 by brian
clean slate
7395
	{
7396
	  if (tmp2.length())
7397
	    tmp2.append(',');
7398
	  tmp2.append((*ref)->name(), strlen((*ref)->name()),
7399
		      system_charset_info);
7400
	}
7401
	item_list.push_back(new Item_string(tmp2.ptr(),tmp2.length(),cs));
7402
      }
1108.6.20 by Padraig O'Sullivan
Renamed access_type to access_method due to conflicts on Solaris.
7403
      else if (tab->type == AM_NEXT)
1 by brian
clean slate
7404
      {
7405
	KEY *key_info=table->key_info+ tab->index;
482 by Brian Aker
Remove uint.
7406
        register uint32_t length;
1 by brian
clean slate
7407
	item_list.push_back(new Item_string(key_info->name,
7408
					    strlen(key_info->name),cs));
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
7409
        length= int64_t2str(key_info->key_length, keylen_str_buf, 10) -
1 by brian
clean slate
7410
                keylen_str_buf;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
7411
        item_list.push_back(new Item_string(keylen_str_buf,
1 by brian
clean slate
7412
                                            length,
7413
                                            system_charset_info));
7414
	item_list.push_back(item_null);
7415
      }
7416
      else if (tab->select && tab->select->quick)
7417
      {
7418
        tab->select->quick->add_keys_and_lengths(&tmp2, &tmp3);
7419
	item_list.push_back(new Item_string(tmp2.ptr(),tmp2.length(),cs));
7420
	item_list.push_back(new Item_string(tmp3.ptr(),tmp3.length(),cs));
7421
	item_list.push_back(item_null);
7422
      }
7423
      else
7424
      {
1063.4.1 by Padraig O'Sullivan
Re-factored the InfoSchemaTable structure to now be a class. Made all data
7425
        if (table_list->schema_table && 
7426
            table_list->schema_table->getRequestedObject() & OPTIMIZE_I_S_TABLE)
1 by brian
clean slate
7427
        {
7428
          if (table_list->has_db_lookup_value)
7429
          {
1076.2.1 by Padraig O'Sullivan
Converted the const char * members of ColumnInfo to be std::string instead.
7430
            int f_idx= table_list->schema_table->getFirstColumnIndex();
7431
            const string &tmp_buff= table_list->schema_table->getColumnName(f_idx);
7432
            tmp2.append(tmp_buff.c_str(), tmp_buff.length(), cs);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
7433
          }
1 by brian
clean slate
7434
          if (table_list->has_table_lookup_value)
7435
          {
7436
            if (table_list->has_db_lookup_value)
7437
              tmp2.append(',');
1076.2.1 by Padraig O'Sullivan
Converted the const char * members of ColumnInfo to be std::string instead.
7438
            int f_idx= table_list->schema_table->getSecondColumnIndex();
7439
            const string &tmp_buff= table_list->schema_table->getColumnName(f_idx);
7440
            tmp2.append(tmp_buff.c_str(), tmp_buff.length(), cs);
1 by brian
clean slate
7441
          }
7442
          if (tmp2.length())
7443
            item_list.push_back(new Item_string(tmp2.ptr(),tmp2.length(),cs));
7444
          else
7445
            item_list.push_back(item_null);
7446
        }
7447
        else
7448
          item_list.push_back(item_null);
7449
	item_list.push_back(item_null);
7450
	item_list.push_back(item_null);
7451
      }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
7452
1 by brian
clean slate
7453
      /* Add "rows" field to item_list. */
7454
      if (table_list->schema_table)
7455
      {
7456
        /* in_rows */
520.1.22 by Brian Aker
Second pass of thd cleanup
7457
        if (join->session->lex->describe & DESCRIBE_EXTENDED)
1 by brian
clean slate
7458
          item_list.push_back(item_null);
7459
        /* rows */
7460
        item_list.push_back(item_null);
7461
      }
7462
      else
7463
      {
7464
        double examined_rows;
7465
        if (tab->select && tab->select->quick)
7466
          examined_rows= rows2double(tab->select->quick->records);
1108.6.20 by Padraig O'Sullivan
Renamed access_type to access_method due to conflicts on Solaris.
7467
        else if (tab->type == AM_NEXT || tab->type == AM_ALL)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
7468
          examined_rows= rows2double(tab->limit ? tab->limit :
1 by brian
clean slate
7469
                                     tab->table->file->records());
7470
        else
1108.6.4 by Padraig O'Sullivan
Made the best_positions member of the JOIN class private and added any
7471
        {
7472
          Position cur_pos= join->getPosFromOptimalPlan(i);
7473
          examined_rows= cur_pos.records_read;
7474
        }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
7475
7476
        item_list.push_back(new Item_int((int64_t) (uint64_t) examined_rows,
1 by brian
clean slate
7477
                                         MY_INT64_NUM_DECIMAL_DIGITS));
7478
7479
        /* Add "filtered" field to item_list. */
520.1.22 by Brian Aker
Second pass of thd cleanup
7480
        if (join->session->lex->describe & DESCRIBE_EXTENDED)
1 by brian
clean slate
7481
        {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
7482
          float f= 0.0;
1 by brian
clean slate
7483
          if (examined_rows)
1108.6.4 by Padraig O'Sullivan
Made the best_positions member of the JOIN class private and added any
7484
          {
7485
            Position cur_pos= join->getPosFromOptimalPlan(i);
7486
            f= (float) (100.0 * cur_pos.records_read /
1 by brian
clean slate
7487
                        examined_rows);
1108.6.4 by Padraig O'Sullivan
Made the best_positions member of the JOIN class private and added any
7488
          }
1 by brian
clean slate
7489
          item_list.push_back(new Item_float(f, 2));
7490
        }
7491
      }
7492
7493
      /* Build "Extra" field and add it to item_list. */
148 by Brian Aker
my_bool cleanup
7494
      bool key_read=table->key_read;
1108.6.20 by Padraig O'Sullivan
Renamed access_type to access_method due to conflicts on Solaris.
7495
      if ((tab->type == AM_NEXT || tab->type == AM_CONST) &&
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
7496
          table->covering_keys.test(tab->index))
1 by brian
clean slate
7497
	key_read=1;
7498
      if (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT &&
7499
          !((QUICK_ROR_INTERSECT_SELECT*)tab->select->quick)->need_to_fetch_row)
7500
        key_read=1;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
7501
1 by brian
clean slate
7502
      if (tab->info)
7503
	item_list.push_back(new Item_string(tab->info,strlen(tab->info),cs));
7504
      else if (tab->packed_info & TAB_INFO_HAVE_VALUE)
7505
      {
7506
        if (tab->packed_info & TAB_INFO_USING_INDEX)
7507
          extra.append(STRING_WITH_LEN("; Using index"));
7508
        if (tab->packed_info & TAB_INFO_USING_WHERE)
7509
          extra.append(STRING_WITH_LEN("; Using where"));
7510
        if (tab->packed_info & TAB_INFO_FULL_SCAN_ON_NULL)
7511
          extra.append(STRING_WITH_LEN("; Full scan on NULL key"));
7512
        /* Skip initial "; "*/
7513
        const char *str= extra.ptr();
205 by Brian Aker
uint32 -> uin32_t
7514
        uint32_t len= extra.length();
1 by brian
clean slate
7515
        if (len)
7516
        {
7517
          str += 2;
7518
          len -= 2;
7519
        }
7520
	item_list.push_back(new Item_string(str, len, cs));
7521
      }
7522
      else
7523
      {
482 by Brian Aker
Remove uint.
7524
        uint32_t keyno= MAX_KEY;
1 by brian
clean slate
7525
        if (tab->ref.key_parts)
7526
          keyno= tab->ref.key;
7527
        else if (tab->select && tab->select->quick)
7528
          keyno = tab->select->quick->index;
7529
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
7530
        if (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION ||
1 by brian
clean slate
7531
            quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT ||
7532
            quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE)
7533
        {
7534
          extra.append(STRING_WITH_LEN("; Using "));
7535
          tab->select->quick->add_info_string(&extra);
7536
        }
7537
          if (tab->select)
7538
	{
7539
	  if (tab->use_quick == 2)
7540
	  {
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
7541
            /*
7542
             * To print out the bitset in tab->keys, we go through
7543
             * it 32 bits at a time. We need to do this to ensure
7544
             * that the to_ulong() method will not throw an
7545
             * out_of_range exception at runtime which would happen
7546
             * if the bitset we were working with was larger than 64
7547
             * bits on a 64-bit platform (for example).
7548
             */
7549
            stringstream s, w;
7550
            string str;
7551
            w << tab->keys;
7552
            w >> str;
7553
            for (uint32_t pos= 0; pos < tab->keys.size(); pos+= 32)
7554
            {
7555
              bitset<32> tmp(str, pos, 32);
7556
              if (tmp.any())
7557
                s << uppercase << hex << tmp.to_ulong();
7558
            }
1 by brian
clean slate
7559
            extra.append(STRING_WITH_LEN("; Range checked for each "
7560
                                         "record (index map: 0x"));
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
7561
            extra.append(s.str().c_str());
1 by brian
clean slate
7562
            extra.append(')');
7563
	  }
7564
	  else if (tab->select->cond)
7565
          {
1108.3.1 by Brian Aker
Remove Insane Clown Posse (AKA... ICP...just generates bugs).
7566
            extra.append(STRING_WITH_LEN("; Using where"));
1 by brian
clean slate
7567
          }
7568
        }
7569
        if (key_read)
7570
        {
7571
          if (quick_type == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX)
7572
            extra.append(STRING_WITH_LEN("; Using index for group-by"));
7573
          else
7574
            extra.append(STRING_WITH_LEN("; Using index"));
7575
        }
7576
        if (table->reginfo.not_exists_optimize)
7577
          extra.append(STRING_WITH_LEN("; Not exists"));
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
7578
1 by brian
clean slate
7579
        if (table_list->schema_table &&
1063.4.1 by Padraig O'Sullivan
Re-factored the InfoSchemaTable structure to now be a class. Made all data
7580
            table_list->schema_table->getRequestedObject() & OPTIMIZE_I_S_TABLE)
1 by brian
clean slate
7581
        {
7582
          if (!table_list->table_open_method)
7583
            extra.append(STRING_WITH_LEN("; Skip_open_table"));
7584
          else if (table_list->table_open_method == OPEN_FRM_ONLY)
7585
            extra.append(STRING_WITH_LEN("; Open_frm_only"));
7586
          else
7587
            extra.append(STRING_WITH_LEN("; Open_full_table"));
7588
          if (table_list->has_db_lookup_value &&
7589
              table_list->has_table_lookup_value)
7590
            extra.append(STRING_WITH_LEN("; Scanned 0 databases"));
7591
          else if (table_list->has_db_lookup_value ||
7592
                   table_list->has_table_lookup_value)
7593
            extra.append(STRING_WITH_LEN("; Scanned 1 database"));
7594
          else
7595
            extra.append(STRING_WITH_LEN("; Scanned all databases"));
7596
        }
7597
        if (need_tmp_table)
7598
        {
7599
          need_tmp_table=0;
7600
          extra.append(STRING_WITH_LEN("; Using temporary"));
7601
        }
7602
        if (need_order)
7603
        {
7604
          need_order=0;
7605
          extra.append(STRING_WITH_LEN("; Using filesort"));
7606
        }
520.1.22 by Brian Aker
Second pass of thd cleanup
7607
        if (distinct & test_all_bits(used_tables,session->used_tables))
1 by brian
clean slate
7608
          extra.append(STRING_WITH_LEN("; Distinct"));
7609
7610
        if (tab->insideout_match_tab)
7611
        {
7612
          extra.append(STRING_WITH_LEN("; LooseScan"));
7613
        }
7614
482 by Brian Aker
Remove uint.
7615
        for (uint32_t part= 0; part < tab->ref.key_parts; part++)
1 by brian
clean slate
7616
        {
7617
          if (tab->ref.cond_guards[part])
7618
          {
7619
            extra.append(STRING_WITH_LEN("; Full scan on NULL key"));
7620
            break;
7621
          }
7622
        }
7623
7624
        if (i > 0 && tab[-1].next_select == sub_select_cache)
7625
          extra.append(STRING_WITH_LEN("; Using join buffer"));
7626
7627
        /* Skip initial "; "*/
7628
        const char *str= extra.ptr();
205 by Brian Aker
uint32 -> uin32_t
7629
        uint32_t len= extra.length();
1 by brian
clean slate
7630
        if (len)
7631
        {
7632
          str += 2;
7633
          len -= 2;
7634
        }
7635
        item_list.push_back(new Item_string(str, len, cs));
7636
      }
7637
      // For next iteration
7638
      used_tables|=table->map;
7639
      if (result->send_data(item_list))
7640
	join->error= 1;
7641
    }
7642
  }
848 by Brian Aker
typdef class removal (just... use the name of the class).
7643
  for (Select_Lex_Unit *unit= join->select_lex->first_inner_unit();
1 by brian
clean slate
7644
       unit;
7645
       unit= unit->next_unit())
7646
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
7647
    if (mysql_explain_union(session, unit, result))
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
7648
      return;
1 by brian
clean slate
7649
  }
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
7650
  return;
1 by brian
clean slate
7651
}
7652
848 by Brian Aker
typdef class removal (just... use the name of the class).
7653
bool mysql_explain_union(Session *session, Select_Lex_Unit *unit, select_result *result)
1 by brian
clean slate
7654
{
894 by Brian Aker
Dead test suites.
7655
  bool res= false;
846 by Brian Aker
Removing on typedeffed class.
7656
  Select_Lex *first= unit->first_select();
1 by brian
clean slate
7657
846 by Brian Aker
Removing on typedeffed class.
7658
  for (Select_Lex *sl= first;
1 by brian
clean slate
7659
       sl;
7660
       sl= sl->next_select())
7661
  {
7662
    // drop UNCACHEABLE_EXPLAIN, because it is for internal usage only
206 by Brian Aker
Removed final uint dead types.
7663
    uint8_t uncacheable= (sl->uncacheable & ~UNCACHEABLE_EXPLAIN);
520.1.22 by Brian Aker
Second pass of thd cleanup
7664
    sl->type= (((&session->lex->select_lex)==sl)?
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
7665
	       (sl->first_inner_unit() || sl->next_select() ?
1 by brian
clean slate
7666
		"PRIMARY" : "SIMPLE"):
7667
	       ((sl == first)?
7668
		((sl->linkage == DERIVED_TABLE_TYPE) ?
7669
		 "DERIVED":
7670
		 ((uncacheable & UNCACHEABLE_DEPENDENT) ?
7671
		  "DEPENDENT SUBQUERY":
7672
		  (uncacheable?"UNCACHEABLE SUBQUERY":
7673
		   "SUBQUERY"))):
7674
		((uncacheable & UNCACHEABLE_DEPENDENT) ?
7675
		 "DEPENDENT UNION":
7676
		 uncacheable?"UNCACHEABLE UNION":
7677
		 "UNION")));
7678
    sl->options|= SELECT_DESCRIBE;
7679
  }
7680
  if (unit->is_union())
7681
  {
7682
    unit->fake_select_lex->select_number= UINT_MAX; // jost for initialization
7683
    unit->fake_select_lex->type= "UNION RESULT";
7684
    unit->fake_select_lex->options|= SELECT_DESCRIBE;
520.1.22 by Brian Aker
Second pass of thd cleanup
7685
    if (!(res= unit->prepare(session, result, SELECT_NO_UNLOCK | SELECT_DESCRIBE)))
1 by brian
clean slate
7686
      res= unit->exec();
7687
    res|= unit->cleanup();
7688
  }
7689
  else
7690
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
7691
    session->lex->current_select= first;
1 by brian
clean slate
7692
    unit->set_limit(unit->global_parameters);
520.1.22 by Brian Aker
Second pass of thd cleanup
7693
    res= mysql_select(session, &first->ref_pointer_array,
327.2.4 by Brian Aker
Refactoring table.h
7694
			(TableList*) first->table_list.first,
1 by brian
clean slate
7695
			first->with_wild, first->item_list,
7696
			first->where,
7697
			first->order_list.elements +
7698
			first->group_list.elements,
327.2.3 by Brian Aker
Refactoring of class Table
7699
			(order_st*) first->order_list.first,
7700
			(order_st*) first->group_list.first,
1 by brian
clean slate
7701
			first->having,
520.1.22 by Brian Aker
Second pass of thd cleanup
7702
			first->options | session->options | SELECT_DESCRIBE,
1 by brian
clean slate
7703
			result, unit, first);
7704
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
7705
  return(res || session->is_error());
1 by brian
clean slate
7706
}
7707
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
7708
static void print_table_array(Session *session, String *str, TableList **table,
327.2.4 by Brian Aker
Refactoring table.h
7709
                              TableList **end)
1 by brian
clean slate
7710
{
520.1.22 by Brian Aker
Second pass of thd cleanup
7711
  (*table)->print(session, str, QT_ORDINARY);
1 by brian
clean slate
7712
327.2.4 by Brian Aker
Refactoring table.h
7713
  for (TableList **tbl= table + 1; tbl < end; tbl++)
1 by brian
clean slate
7714
  {
327.2.4 by Brian Aker
Refactoring table.h
7715
    TableList *curr= *tbl;
1 by brian
clean slate
7716
    if (curr->outer_join)
7717
    {
7718
      /* MySQL converts right to left joins */
7719
      str->append(STRING_WITH_LEN(" left join "));
7720
    }
7721
    else if (curr->straight)
7722
      str->append(STRING_WITH_LEN(" straight_join "));
7723
    else
7724
      str->append(STRING_WITH_LEN(" join "));
520.1.22 by Brian Aker
Second pass of thd cleanup
7725
    curr->print(session, str, QT_ORDINARY);
1 by brian
clean slate
7726
    if (curr->on_expr)
7727
    {
7728
      str->append(STRING_WITH_LEN(" on("));
7729
      curr->on_expr->print(str, QT_ORDINARY);
7730
      str->append(')');
7731
    }
7732
  }
7733
}
7734
7735
/**
7736
  Print joins from the FROM clause.
520.1.22 by Brian Aker
Second pass of thd cleanup
7737
  @param session     thread handler
1 by brian
clean slate
7738
  @param str     string where table should be printed
7739
  @param tables  list of tables in join
7740
  @query_type    type of the query is being generated
7741
*/
1054.1.7 by Brian Aker
Refactor TableList methods.
7742
void print_join(Session *session, String *str,
7743
                List<TableList> *tables, enum_query_type)
1 by brian
clean slate
7744
{
7745
  /* List is reversed => we should reverse it before using */
327.2.4 by Brian Aker
Refactoring table.h
7746
  List_iterator_fast<TableList> ti(*tables);
520.1.22 by Brian Aker
Second pass of thd cleanup
7747
  TableList **table= (TableList **)session->alloc(sizeof(TableList*) *
1 by brian
clean slate
7748
                                                tables->elements);
7749
  if (table == 0)
7750
    return;  // out of memory
7751
327.2.4 by Brian Aker
Refactoring table.h
7752
  for (TableList **t= table + (tables->elements - 1); t >= table; t--)
1 by brian
clean slate
7753
    *t= ti++;
51.1.66 by Jay Pipes
Removed/replaced BUG symbols and standardized TRUE/FALSE
7754
  assert(tables->elements >= 1);
520.1.22 by Brian Aker
Second pass of thd cleanup
7755
  print_table_array(session, str, table, table + tables->elements);
1 by brian
clean slate
7756
}
7757
846 by Brian Aker
Removing on typedeffed class.
7758
void Select_Lex::print(Session *session, String *str, enum_query_type query_type)
1 by brian
clean slate
7759
{
520.1.22 by Brian Aker
Second pass of thd cleanup
7760
  /* QQ: session may not be set for sub queries, but this should be fixed */
7761
  if (!session)
7762
    session= current_session;
1 by brian
clean slate
7763
7764
  str->append(STRING_WITH_LEN("select "));
7765
7766
  /* First add options */
7767
  if (options & SELECT_STRAIGHT_JOIN)
7768
    str->append(STRING_WITH_LEN("straight_join "));
7769
  if (options & SELECT_DISTINCT)
7770
    str->append(STRING_WITH_LEN("distinct "));
7771
  if (options & SELECT_SMALL_RESULT)
7772
    str->append(STRING_WITH_LEN("sql_small_result "));
7773
  if (options & SELECT_BIG_RESULT)
7774
    str->append(STRING_WITH_LEN("sql_big_result "));
7775
  if (options & OPTION_BUFFER_RESULT)
7776
    str->append(STRING_WITH_LEN("sql_buffer_result "));
7777
  if (options & OPTION_FOUND_ROWS)
7778
    str->append(STRING_WITH_LEN("sql_calc_found_rows "));
7779
7780
  //Item List
7781
  bool first= 1;
7782
  List_iterator_fast<Item> it(item_list);
7783
  Item *item;
7784
  while ((item= it++))
7785
  {
7786
    if (first)
7787
      first= 0;
7788
    else
7789
      str->append(',');
7790
    item->print_item_w_name(str, query_type);
7791
  }
7792
7793
  /*
7794
    from clause
7795
    TODO: support USING/FORCE/IGNORE index
7796
  */
7797
  if (table_list.elements)
7798
  {
7799
    str->append(STRING_WITH_LEN(" from "));
7800
    /* go through join tree */
520.1.22 by Brian Aker
Second pass of thd cleanup
7801
    print_join(session, str, &top_join_list, query_type);
1 by brian
clean slate
7802
  }
7803
  else if (where)
7804
  {
7805
    /*
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
7806
      "SELECT 1 FROM DUAL WHERE 2" should not be printed as
1 by brian
clean slate
7807
      "SELECT 1 WHERE 2": the 1st syntax is valid, but the 2nd is not.
7808
    */
7809
    str->append(STRING_WITH_LEN(" from DUAL "));
7810
  }
7811
7812
  // Where
7813
  Item *cur_where= where;
7814
  if (join)
7815
    cur_where= join->conds;
7816
  if (cur_where || cond_value != Item::COND_UNDEF)
7817
  {
7818
    str->append(STRING_WITH_LEN(" where "));
7819
    if (cur_where)
7820
      cur_where->print(str, query_type);
7821
    else
7822
      str->append(cond_value != Item::COND_FALSE ? "1" : "0");
7823
  }
7824
7825
  // group by & olap
7826
  if (group_list.elements)
7827
  {
7828
    str->append(STRING_WITH_LEN(" group by "));
327.2.3 by Brian Aker
Refactoring of class Table
7829
    print_order(str, (order_st *) group_list.first, query_type);
1 by brian
clean slate
7830
    switch (olap)
7831
    {
7832
      case CUBE_TYPE:
7833
	str->append(STRING_WITH_LEN(" with cube"));
7834
	break;
7835
      case ROLLUP_TYPE:
7836
	str->append(STRING_WITH_LEN(" with rollup"));
7837
	break;
7838
      default:
7839
	;  //satisfy compiler
7840
    }
7841
  }
7842
7843
  // having
7844
  Item *cur_having= having;
7845
  if (join)
7846
    cur_having= join->having;
7847
7848
  if (cur_having || having_value != Item::COND_UNDEF)
7849
  {
7850
    str->append(STRING_WITH_LEN(" having "));
7851
    if (cur_having)
7852
      cur_having->print(str, query_type);
7853
    else
7854
      str->append(having_value != Item::COND_FALSE ? "1" : "0");
7855
  }
7856
7857
  if (order_list.elements)
7858
  {
7859
    str->append(STRING_WITH_LEN(" order by "));
327.2.3 by Brian Aker
Refactoring of class Table
7860
    print_order(str, (order_st *) order_list.first, query_type);
1 by brian
clean slate
7861
  }
7862
7863
  // limit
520.1.22 by Brian Aker
Second pass of thd cleanup
7864
  print_limit(session, str, query_type);
1 by brian
clean slate
7865
7866
  // PROCEDURE unsupported here
7867
}
7868
7869
/**
7870
  @} (end of group Query_Optimizer)
7871
*/