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