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