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