~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/join.cc

  • Committer: Joe Daly
  • Date: 2010-05-21 02:16:56 UTC
  • mto: This revision was merged to the branch mainline in revision 1555.
  • Revision ID: skinny.moey@gmail.com-20100521021656-bx6piitfh77jnl28
add statistics_variables.h

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
/* - mode: c; c-basic-offset: 2; indent-tabs-mode: nil; -*-
2
2
 *  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
3
3
 *
4
 
 *  Copyright (C) 2008-2009 Sun Microsystems, Inc.
 
4
 *  Copyright (C) 2008-2009 Sun Microsystems
5
5
 *
6
6
 *  This program is free software; you can redistribute it and/or modify
7
7
 *  it under the terms of the GNU General Public License as published by
21
21
/**
22
22
 * @file
23
23
 *
24
 
 * Implementation of the Join class
 
24
 * Implementation of the JOIN class
25
25
 * 
26
26
 * @defgroup Query_Optimizer  Query Optimizer
27
27
 * @{
28
28
 */
29
29
 
30
 
#include <config.h>
 
30
#include "config.h"
31
31
 
32
32
#include <float.h>
33
33
#include <math.h>
34
34
 
35
 
#include <drizzled/item/cache.h>
36
 
#include <drizzled/item/cmpfunc.h>
37
 
#include <drizzled/item/copy_string.h>
38
 
#include <drizzled/item/uint.h>
39
 
#include <drizzled/cached_item.h>
40
 
#include <drizzled/sql_base.h>
41
 
#include <drizzled/sql_select.h> /* include join.h */
42
 
#include <drizzled/lock.h>
43
 
#include <drizzled/nested_join.h>
44
 
#include <drizzled/join.h>
45
 
#include <drizzled/join_cache.h>
46
 
#include <drizzled/show.h>
47
 
#include <drizzled/field/blob.h>
48
 
#include <drizzled/optimizer/position.h>
49
 
#include <drizzled/optimizer/sargable_param.h>
50
 
#include <drizzled/optimizer/key_use.h>
51
 
#include <drizzled/optimizer/range.h>
52
 
#include <drizzled/optimizer/sum.h>
53
 
#include <drizzled/optimizer/explain_plan.h>
54
 
#include <drizzled/optimizer/access_method_factory.h>
55
 
#include <drizzled/optimizer/access_method.h>
56
 
#include <drizzled/records.h>
57
 
#include <drizzled/probes.h>
58
 
#include <drizzled/internal/my_bit.h>
59
 
#include <drizzled/internal/my_sys.h>
60
 
#include <drizzled/internal/iocache.h>
61
 
#include <drizzled/plugin/storage_engine.h>
62
 
#include <drizzled/session.h>
63
 
#include <drizzled/select_result.h>
64
 
 
65
 
#include <drizzled/debug.h>
 
35
#include "drizzled/item/cache.h"
 
36
#include "drizzled/item/cmpfunc.h"
 
37
#include "drizzled/item/copy_string.h"
 
38
#include "drizzled/item/uint.h"
 
39
#include "drizzled/cached_item.h"
 
40
#include "drizzled/sql_base.h"
 
41
#include "drizzled/sql_select.h" /* include join.h */
 
42
#include "drizzled/lock.h"
 
43
#include "drizzled/nested_join.h"
 
44
#include "drizzled/join.h"
 
45
#include "drizzled/join_cache.h"
 
46
#include "drizzled/show.h"
 
47
#include "drizzled/field/blob.h"
 
48
#include "drizzled/optimizer/position.h"
 
49
#include "drizzled/optimizer/sargable_param.h"
 
50
#include "drizzled/optimizer/key_use.h"
 
51
#include "drizzled/optimizer/range.h"
 
52
#include "drizzled/optimizer/sum.h"
 
53
#include "drizzled/optimizer/explain_plan.h"
 
54
#include "drizzled/optimizer/access_method_factory.h"
 
55
#include "drizzled/optimizer/access_method.h"
 
56
#include "drizzled/records.h"
 
57
#include "drizzled/probes.h"
 
58
#include "drizzled/internal/my_bit.h"
 
59
#include "drizzled/internal/my_sys.h"
 
60
#include "drizzled/internal/iocache.h"
66
61
 
67
62
#include <algorithm>
68
63
 
70
65
 
71
66
namespace drizzled
72
67
{
 
68
 
73
69
extern plugin::StorageEngine *heap_engine;
 
70
extern std::bitset<12> test_flags;
74
71
 
75
72
/** Declarations of static functions used in this source file. */
76
 
static bool make_group_fields(Join *main_join, Join *curr_join);
77
 
static void calc_group_buffer(Join *join, Order *group);
78
 
static bool alloc_group_fields(Join *join, Order *group);
79
 
static uint32_t cache_record_length(Join *join, uint32_t index);
80
 
static double prev_record_reads(Join *join, uint32_t idx, table_map found_ref);
81
 
static bool get_best_combination(Join *join);
82
 
static void set_position(Join *join,
 
73
static bool make_group_fields(JOIN *main_join, JOIN *curr_join);
 
74
static void calc_group_buffer(JOIN *join,order_st *group);
 
75
static bool alloc_group_fields(JOIN *join,order_st *group);
 
76
static uint32_t cache_record_length(JOIN *join, uint32_t index);
 
77
static double prev_record_reads(JOIN *join, uint32_t idx, table_map found_ref);
 
78
static bool get_best_combination(JOIN *join);
 
79
static void set_position(JOIN *join,
83
80
                         uint32_t index,
84
81
                         JoinTable *table,
85
82
                         optimizer::KeyUse *key);
86
 
static bool choose_plan(Join *join,table_map join_tables);
87
 
static void best_access_path(Join *join, JoinTable *s,
 
83
static bool choose_plan(JOIN *join,table_map join_tables);
 
84
static void best_access_path(JOIN *join, JoinTable *s,
88
85
                             Session *session,
89
86
                             table_map remaining_tables,
90
87
                             uint32_t idx,
91
88
                             double record_count,
92
89
                             double read_time);
93
 
static void optimize_straight_join(Join *join, table_map join_tables);
94
 
static bool greedy_search(Join *join, table_map remaining_tables, uint32_t depth, uint32_t prune_level);
95
 
static bool best_extension_by_limited_search(Join *join,
 
90
static void optimize_straight_join(JOIN *join, table_map join_tables);
 
91
static bool greedy_search(JOIN *join, table_map remaining_tables, uint32_t depth, uint32_t prune_level);
 
92
static bool best_extension_by_limited_search(JOIN *join,
96
93
                                             table_map remaining_tables,
97
94
                                             uint32_t idx,
98
95
                                             double record_count,
99
96
                                             double read_time,
100
97
                                             uint32_t depth,
101
98
                                             uint32_t prune_level);
102
 
static uint32_t determine_search_depth(Join* join);
103
 
static bool make_simple_join(Join *join,Table *tmp_table);
104
 
static void make_outerjoin_info(Join *join);
105
 
static bool make_join_select(Join *join, optimizer::SqlSelect *select,COND *item);
106
 
static bool make_join_readinfo(Join *join);
107
 
static void update_depend_map(Join *join);
108
 
static void update_depend_map(Join *join, Order *order);
109
 
static Order *remove_constants(Join *join,Order *first_order,COND *cond, bool change_list, bool *simple_order);
110
 
static int return_zero_rows(Join *join,
 
99
static uint32_t determine_search_depth(JOIN* join);
 
100
static bool make_simple_join(JOIN *join,Table *tmp_table);
 
101
static void make_outerjoin_info(JOIN *join);
 
102
static bool make_join_select(JOIN *join, optimizer::SqlSelect *select,COND *item);
 
103
static bool make_join_readinfo(JOIN *join);
 
104
static void update_depend_map(JOIN *join);
 
105
static void update_depend_map(JOIN *join, order_st *order);
 
106
static order_st *remove_constants(JOIN *join,order_st *first_order,COND *cond, bool change_list, bool *simple_order);
 
107
static int return_zero_rows(JOIN *join,
111
108
                            select_result *res,
112
109
                            TableList *tables,
113
110
                            List<Item> &fields,
115
112
                            uint64_t select_options,
116
113
                            const char *info,
117
114
                            Item *having);
118
 
static COND *simplify_joins(Join *join, List<TableList> *join_list, COND *conds, bool top);
119
 
static int remove_duplicates(Join *join,Table *entry,List<Item> &fields, Item *having);
 
115
static COND *simplify_joins(JOIN *join, List<TableList> *join_list, COND *conds, bool top);
 
116
static int remove_duplicates(JOIN *join,Table *entry,List<Item> &fields, Item *having);
120
117
static int setup_without_group(Session *session, 
121
118
                               Item **ref_pointer_array,
122
119
                               TableList *tables,
124
121
                               List<Item> &fields,
125
122
                               List<Item> &all_fields,
126
123
                               COND **conds,
127
 
                               Order *order,
128
 
                               Order *group,
 
124
                               order_st *order,
 
125
                               order_st *group,
129
126
                               bool *hidden_group_fields);
130
 
static bool make_join_statistics(Join *join, TableList *leaves, COND *conds, DYNAMIC_ARRAY *keyuse);
 
127
static bool make_join_statistics(JOIN *join, TableList *leaves, COND *conds, DYNAMIC_ARRAY *keyuse);
131
128
static uint32_t build_bitmap_for_nested_joins(List<TableList> *join_list, uint32_t first_unused);
132
 
static Table *get_sort_by_table(Order *a, Order *b,TableList *tables);
 
129
static Table *get_sort_by_table(order_st *a,order_st *b,TableList *tables);
133
130
static void reset_nj_counters(List<TableList> *join_list);
134
 
static bool test_if_subpart(Order *a,Order *b);
 
131
static bool test_if_subpart(order_st *a,order_st *b);
135
132
static void restore_prev_nj_state(JoinTable *last);
136
133
static bool add_ref_to_table_cond(Session *session, JoinTable *join_tab);
137
134
static void free_blobs(Field **ptr); /* Rename this method...conflicts with another in global namespace... */
138
135
 
139
 
Join::Join(Session *session_arg, 
140
 
           List<Item> &fields_arg, 
141
 
           uint64_t select_options_arg,
142
 
           select_result *result_arg) :
143
 
  join_tab(NULL),
144
 
  best_ref(NULL),
145
 
  map2table(NULL),
146
 
  join_tab_save(NULL),
147
 
  table(NULL),
148
 
  all_tables(NULL),
149
 
  sort_by_table(NULL),
150
 
  tables(0),
151
 
  outer_tables(0),
152
 
  const_tables(0),
153
 
  send_group_parts(0),
154
 
  sort_and_group(false),
155
 
  first_record(false),
156
 
  full_join(false),
157
 
  group(false),
158
 
  no_field_update(false),
159
 
  do_send_rows(true),
160
 
  resume_nested_loop(false),
161
 
  no_const_tables(false),
162
 
  select_distinct(false),
163
 
  group_optimized_away(false),
164
 
  simple_order(false),
165
 
  simple_group(false),
166
 
  no_order(false),
167
 
  skip_sort_order(false),
168
 
  union_part(false),
169
 
  optimized(false),
170
 
  need_tmp(false),
171
 
  hidden_group_fields(false),
172
 
  const_table_map(0),
173
 
  found_const_table_map(0),
174
 
  outer_join(0),
175
 
  send_records(0),
176
 
  found_records(0),
177
 
  examined_rows(0),
178
 
  row_limit(0),
179
 
  select_limit(0),
180
 
  fetch_limit(HA_POS_ERROR),
181
 
  session(session_arg),
182
 
  fields_list(fields_arg), 
183
 
  join_list(NULL),
184
 
  unit(NULL),
185
 
  select_lex(NULL),
186
 
  select(NULL),
187
 
  exec_tmp_table1(NULL),
188
 
  exec_tmp_table2(NULL),
189
 
  sum_funcs(NULL),
190
 
  sum_funcs2(NULL),
191
 
  having(NULL),
192
 
  tmp_having(NULL),
193
 
  having_history(NULL),
194
 
  select_options(select_options_arg),
195
 
  result(result_arg),
196
 
  lock(session_arg->lock),
197
 
  tmp_join(NULL),
198
 
  all_fields(fields_arg),
199
 
  error(0),
200
 
  cond_equal(NULL),
201
 
  return_tab(NULL),
202
 
  ref_pointer_array(NULL),
203
 
  items0(NULL),
204
 
  items1(NULL),
205
 
  items2(NULL),
206
 
  items3(NULL),
207
 
  ref_pointer_array_size(0),
208
 
  zero_result_cause(NULL),
209
 
  sortorder(NULL),
210
 
  table_reexec(NULL),
211
 
  join_tab_reexec(NULL)
212
 
{
213
 
  select_distinct= test(select_options & SELECT_DISTINCT);
214
 
  if (&fields_list != &fields_arg) /* only copy if not same*/
215
 
    fields_list= fields_arg;
216
 
  memset(&keyuse, 0, sizeof(keyuse));
217
 
  tmp_table_param.init();
218
 
  tmp_table_param.end_write_records= HA_POS_ERROR;
219
 
  rollup.setState(Rollup::STATE_NONE);
220
 
}
221
 
 
222
 
  /** 
223
 
   * This method is currently only used when a subselect EXPLAIN is performed.
224
 
   * I pulled out the init() method and have simply reset the values to what
225
 
   * was previously in the init() method.  See the note about the hack in 
226
 
   * sql_union.cc...
227
 
   */
228
 
void Join::reset(Session *session_arg, 
229
 
                 List<Item> &fields_arg, 
230
 
                 uint64_t select_options_arg,
231
 
                 select_result *result_arg)
232
 
{
233
 
  join_tab= NULL;
234
 
  best_ref= NULL;
235
 
  map2table= NULL;
236
 
  join_tab_save= NULL;
237
 
  table= NULL;
238
 
  all_tables= NULL;
239
 
  sort_by_table= NULL;
240
 
  tables= 0;
241
 
  outer_tables= 0;
242
 
  const_tables= 0;
243
 
  send_group_parts= 0;
244
 
  sort_and_group= false;
245
 
  first_record= false;
246
 
  full_join= false;
247
 
  group= false;
248
 
  no_field_update= false;
249
 
  do_send_rows= true;
250
 
  resume_nested_loop= false;
251
 
  no_const_tables= false;
252
 
  select_distinct= false;
253
 
  group_optimized_away= false;
254
 
  simple_order= false;
255
 
  simple_group= false;
256
 
  no_order= false;
257
 
  skip_sort_order= false;
258
 
  union_part= false;
259
 
  optimized= false;
260
 
  need_tmp= false;
261
 
  hidden_group_fields= false;
262
 
  const_table_map= 0;
263
 
  found_const_table_map= 0;
264
 
  outer_join= 0;
265
 
  send_records= 0;
266
 
  found_records= 0;
267
 
  examined_rows= 0;
268
 
  row_limit= 0;
269
 
  select_limit= 0;
270
 
  fetch_limit= HA_POS_ERROR;
271
 
  session= session_arg;
272
 
  fields_list= fields_arg; 
273
 
  join_list= NULL;
274
 
  unit= NULL;
275
 
  select_lex= NULL;
276
 
  select= NULL;
277
 
  exec_tmp_table1= NULL;
278
 
  exec_tmp_table2= NULL;
279
 
  sum_funcs= NULL;
280
 
  sum_funcs2= NULL;
281
 
  having= NULL;
282
 
  tmp_having= NULL;
283
 
  having_history= NULL;
284
 
  select_options= select_options_arg;
285
 
  result= result_arg;
286
 
  lock= session_arg->lock;
287
 
  tmp_join= NULL;
288
 
  all_fields= fields_arg;
289
 
  error= 0;
290
 
  cond_equal= NULL;
291
 
  return_tab= NULL;
292
 
  ref_pointer_array= NULL;
293
 
  items0= NULL;
294
 
  items1= NULL;
295
 
  items2= NULL;
296
 
  items3= NULL;
297
 
  ref_pointer_array_size= 0;
298
 
  zero_result_cause= NULL;
299
 
  sortorder= NULL;
300
 
  table_reexec= NULL;
301
 
  join_tab_reexec= NULL;
302
 
  select_distinct= test(select_options & SELECT_DISTINCT);
303
 
  if (&fields_list != &fields_arg) /* only copy if not same*/
304
 
    fields_list= fields_arg;
305
 
  memset(&keyuse, 0, sizeof(keyuse));
306
 
  tmp_table_param.init();
307
 
  tmp_table_param.end_write_records= HA_POS_ERROR;
308
 
  rollup.setState(Rollup::STATE_NONE);
309
 
}
310
 
 
311
 
bool Join::is_top_level_join() const
312
 
{
313
 
  return (unit == &session->getLex()->unit && (unit->fake_select_lex == 0 ||
314
 
                                          select_lex == unit->fake_select_lex));
315
 
}
316
 
 
317
136
/**
318
137
  Prepare of whole select (including sub queries in future).
319
138
 
326
145
  @retval
327
146
    0   on success
328
147
*/
329
 
int Join::prepare(Item ***rref_pointer_array,
 
148
int JOIN::prepare(Item ***rref_pointer_array,
330
149
                  TableList *tables_init,
331
150
                  uint32_t wild_num,
332
151
                  COND *conds_init,
333
152
                  uint32_t og_num,
334
 
                  Order *order_init,
335
 
                  Order *group_init,
 
153
                  order_st *order_init,
 
154
                  order_st *group_init,
336
155
                  Item *having_init,
337
156
                  Select_Lex *select_lex_arg,
338
157
                  Select_Lex_Unit *unit_arg)
351
170
  join_list= &select_lex->top_join_list;
352
171
  union_part= unit_arg->is_union();
353
172
 
354
 
  session->getLex()->current_select->is_item_list_lookup= 1;
 
173
  session->lex->current_select->is_item_list_lookup= 1;
355
174
  /*
356
175
    If we have already executed SELECT, then it have not sense to prevent
357
176
    its table from update (see unique_table())
365
184
      setup_tables_and_check_access(session, &select_lex->context, join_list,
366
185
                                    tables_list, &select_lex->leaf_tables,
367
186
                                    false))
368
 
  {
369
187
      return(-1);
370
 
  }
371
188
 
372
189
  TableList *table_ptr;
373
190
  for (table_ptr= select_lex->leaf_tables;
374
191
       table_ptr;
375
192
       table_ptr= table_ptr->next_leaf)
376
 
  {
377
193
    tables++;
378
 
  }
379
 
 
380
194
 
381
195
  if (setup_wild(session, fields_list, &all_fields, wild_num) ||
382
196
      select_lex->setup_ref_array(session, og_num) ||
392
206
 
393
207
  if (having)
394
208
  {
395
 
    nesting_map save_allow_sum_func= session->getLex()->allow_sum_func;
396
 
    session->setWhere("having clause");
397
 
    session->getLex()->allow_sum_func|= 1 << select_lex_arg->nest_level;
 
209
    nesting_map save_allow_sum_func= session->lex->allow_sum_func;
 
210
    session->where="having clause";
 
211
    session->lex->allow_sum_func|= 1 << select_lex_arg->nest_level;
398
212
    select_lex->having_fix_field= 1;
399
213
    bool having_fix_rc= (!having->fixed &&
400
214
       (having->fix_fields(session, &having) ||
402
216
    select_lex->having_fix_field= 0;
403
217
    if (having_fix_rc || session->is_error())
404
218
      return(-1);
405
 
    session->getLex()->allow_sum_func= save_allow_sum_func;
 
219
    session->lex->allow_sum_func= save_allow_sum_func;
406
220
  }
407
221
 
408
222
  {
452
266
            in_subs  &&                                                   // 1
453
267
            !select_lex->master_unit()->first_select()->next_select() &&  // 2
454
268
            select_lex->master_unit()->first_select()->leaf_tables &&     // 3
455
 
            session->getLex()->sql_command == SQLCOM_SELECT)                       // *
 
269
            session->lex->sql_command == SQLCOM_SELECT)                       // *
456
270
        {
457
271
          if (in_subs->is_top_level_item() &&                             // 4
458
272
              !in_subs->is_correlated &&                                  // 5
472
286
 
473
287
  if (order)
474
288
  {
475
 
    Order *ord;
 
289
    order_st *ord;
476
290
    for (ord= order; ord; ord= ord->next)
477
291
    {
478
292
      Item *item= *ord->item;
517
331
  {
518
332
    /* Caclulate the number of groups */
519
333
    send_group_parts= 0;
520
 
    for (Order *group_tmp= group_list ; group_tmp ; group_tmp= group_tmp->next)
 
334
    for (order_st *group_tmp= group_list ; group_tmp ; group_tmp= group_tmp->next)
521
335
      send_group_parts++;
522
336
  }
523
337
 
524
338
  if (error)
525
 
    return(-1);
 
339
    goto err;
526
340
 
527
341
  /* 
528
342
   * The below will create the new table for
531
345
   * @see create_table_from_items() in drizzled/sql_insert.cc
532
346
   */
533
347
  if (result && result->prepare(fields_list, unit_arg))
534
 
    return(-1);
 
348
    goto err;
535
349
 
536
350
  /* Init join struct */
537
351
  count_field_types(select_lex, &tmp_table_param, all_fields, 0);
543
357
  if (sum_func_count && !group_list && (func_count || field_count))
544
358
  {
545
359
    my_message(ER_WRONG_SUM_SELECT,ER(ER_WRONG_SUM_SELECT),MYF(0));
546
 
    return(-1);
 
360
    goto err;
547
361
  }
548
362
#endif
549
363
  if (select_lex->olap == ROLLUP_TYPE && rollup_init())
550
 
    return(-1);
551
 
 
 
364
    goto err;
552
365
  if (alloc_func_list())
553
 
    return(-1);
554
 
 
555
 
  return 0; // All OK
 
366
    goto err;
 
367
 
 
368
  return(0); // All OK
 
369
 
 
370
err:
 
371
  return(-1);
556
372
}
557
373
 
558
374
/*
559
375
  Remove the predicates pushed down into the subquery
560
376
 
561
377
  SYNOPSIS
562
 
    Join::remove_subq_pushed_predicates()
 
378
    JOIN::remove_subq_pushed_predicates()
563
379
      where   IN  Must be NULL
564
380
              OUT The remaining WHERE condition, or NULL
565
381
 
584
400
    that is searched in a byte. But this requires homogenization of the return
585
401
    codes of all Field*::store() methods.
586
402
*/
587
 
void Join::remove_subq_pushed_predicates(Item **where)
 
403
void JOIN::remove_subq_pushed_predicates(Item **where)
588
404
{
589
405
  if (conds->type() == Item::FUNC_ITEM &&
590
406
      ((Item_func *)this->conds)->functype() == Item_func::EQ_FUNC &&
609
425
  @retval
610
426
    1   error
611
427
*/
612
 
int Join::optimize()
 
428
int JOIN::optimize()
613
429
{
614
430
  // to prevent double initialization on EXPLAIN
615
431
  if (optimized)
625
441
    select_limit= HA_POS_ERROR;
626
442
  do_send_rows = (unit->select_limit_cnt) ? 1 : 0;
627
443
  // Ignore errors of execution if option IGNORE present
628
 
  if (session->getLex()->ignore)
629
 
    session->getLex()->current_select->no_error= 1;
 
444
  if (session->lex->ignore)
 
445
    session->lex->current_select->no_error= 1;
630
446
 
631
447
#ifdef HAVE_REF_TO_FIELDS     // Not done yet
632
448
  /* Add HAVING to WHERE if possible */
679
495
    {           /* Impossible cond */
680
496
      zero_result_cause=  having_value == Item::COND_FALSE ?
681
497
                           "Impossible HAVING" : "Impossible WHERE";
682
 
      tables = 0;
683
 
      goto setup_subq_exit;
 
498
      error= 0;
 
499
      return(0);
684
500
    }
685
501
  }
686
502
 
699
515
      if (res == HA_ERR_KEY_NOT_FOUND)
700
516
      {
701
517
        zero_result_cause= "No matching min/max row";
702
 
        tables = 0;
703
 
        goto setup_subq_exit;
 
518
        error=0;
 
519
        return(0);
704
520
      }
705
521
      if (res > 1)
706
522
      {
710
526
      if (res < 0)
711
527
      {
712
528
        zero_result_cause= "No matching min/max row";
713
 
        tables = 0;
714
 
        goto setup_subq_exit;
 
529
        error=0;
 
530
        return(0);
715
531
      }
716
532
      zero_result_cause= "Select tables optimized away";
717
533
      tables_list= 0;       // All tables resolved
718
 
      const_tables= tables;
719
534
      /*
720
535
        Extract all table-independent conditions and replace the WHERE
721
536
        clause with them. All other conditions were computed by optimizer::sum_query
726
541
        conjunctions.
727
542
        Preserve conditions for EXPLAIN.
728
543
      */
729
 
      if (conds && !(session->getLex()->describe & DESCRIBE_EXTENDED))
 
544
      if (conds && !(session->lex->describe & DESCRIBE_EXTENDED))
730
545
      {
731
546
        COND *table_independent_conds= make_cond_for_table(conds, PSEUDO_TABLE_BITS, 0, 0);
732
547
        conds= table_independent_conds;
733
548
      }
734
 
      goto setup_subq_exit;
735
549
    }
736
550
  }
737
551
  if (!tables_list)
761
575
      !(select_options & SELECT_DESCRIBE) &&
762
576
      (!conds ||
763
577
       !(conds->used_tables() & RAND_TABLE_BIT) ||
764
 
       select_lex->master_unit() == &session->getLex()->unit)) // upper level SELECT
 
578
       select_lex->master_unit() == &session->lex->unit)) // upper level SELECT
765
579
  {
766
580
    zero_result_cause= "no matching row in const table";
767
 
    goto setup_subq_exit;
 
581
    error= 0;
 
582
    return(0);
768
583
  }
769
584
  if (!(session->options & OPTION_BIG_SELECTS) &&
770
585
      best_read > (double) session->variables.max_join_size &&
775
590
    return 1;
776
591
  }
777
592
  if (const_tables && !(select_options & SELECT_NO_UNLOCK))
778
 
    session->unlockSomeTables(table, const_tables);
 
593
    mysql_unlock_some_tables(session, table, const_tables);
779
594
  if (!conds && outer_join)
780
595
  {
781
596
    /* Handle the case where we have an OUTER JOIN without a WHERE */
821
636
 
822
637
  if (conds &&!outer_join && const_table_map != found_const_table_map &&
823
638
      (select_options & SELECT_DESCRIBE) &&
824
 
      select_lex->master_unit() == &session->getLex()->unit) // upper level SELECT
 
639
      select_lex->master_unit() == &session->lex->unit) // upper level SELECT
825
640
  {
826
641
    conds=new Item_int((int64_t) 0,1);  // Always false
827
642
  }
830
645
  {
831
646
    zero_result_cause=
832
647
      "Impossible WHERE noticed after reading const tables";
833
 
    goto setup_subq_exit;
 
648
    return(0);        // error == 0
834
649
  }
835
650
 
836
651
  error= -1;          /* if goto err */
837
652
 
838
653
  /* Optimize distinct away if possible */
839
654
  {
840
 
    Order *org_order= order;
 
655
    order_st *org_order= order;
841
656
    order= remove_constants(this, order,conds,1, &simple_order);
842
657
    if (session->is_error())
843
658
    {
909
724
  }
910
725
  if (group_list || tmp_table_param.sum_func_count)
911
726
  {
912
 
    if (! hidden_group_fields && rollup.getState() == Rollup::STATE_NONE)
 
727
    if (! hidden_group_fields && rollup.state == ROLLUP::STATE_NONE)
913
728
      select_distinct=0;
914
729
  }
915
730
  else if (select_distinct && tables - const_tables == 1)
971
786
  }
972
787
  simple_group= 0;
973
788
  {
974
 
    Order *old_group_list;
 
789
    order_st *old_group_list;
975
790
    group_list= remove_constants(this, (old_group_list= group_list), conds,
976
 
                                 rollup.getState() == Rollup::STATE_NONE,
 
791
                                 rollup.state == ROLLUP::STATE_NONE,
977
792
                                 &simple_group);
978
793
    if (session->is_error())
979
794
    {
1049
864
        save_index_subquery_explain_info(join_tab, where);
1050
865
        join_tab[0].type= AM_UNIQUE_SUBQUERY;
1051
866
        error= 0;
1052
 
        return(unit->item->change_engine(new subselect_uniquesubquery_engine(session, join_tab, unit->item, where)));
 
867
        return(unit->item->
 
868
                    change_engine(new
 
869
                                  subselect_uniquesubquery_engine(session,
 
870
                                                                  join_tab,
 
871
                                                                  unit->item,
 
872
                                                                  where)));
1053
873
      }
1054
874
      else if (join_tab[0].type == AM_REF &&
1055
875
         join_tab[0].ref.items[0]->name == in_left_expr_name)
1058
878
        save_index_subquery_explain_info(join_tab, where);
1059
879
        join_tab[0].type= AM_INDEX_SUBQUERY;
1060
880
        error= 0;
1061
 
        return(unit->item->change_engine(new subselect_indexsubquery_engine(session, join_tab, unit->item, where, NULL, 0)));
 
881
        return(unit->item->
 
882
                    change_engine(new
 
883
                                  subselect_indexsubquery_engine(session,
 
884
                                                                 join_tab,
 
885
                                                                 unit->item,
 
886
                                                                 where,
 
887
                                                                 NULL,
 
888
                                                                 0)));
1062
889
      }
1063
890
    } 
1064
891
    else if (join_tab[0].type == AM_REF_OR_NULL &&
1069
896
      error= 0;
1070
897
      conds= remove_additional_cond(conds);
1071
898
      save_index_subquery_explain_info(join_tab, conds);
1072
 
      return(unit->item->change_engine(new subselect_indexsubquery_engine(session, join_tab, unit->item, conds, having, 1)));
 
899
      return(unit->item->
 
900
      change_engine(new subselect_indexsubquery_engine(session,
 
901
                   join_tab,
 
902
                   unit->item,
 
903
                   conds,
 
904
                                                                   having,
 
905
                   1)));
1073
906
    }
1074
907
 
1075
908
  }
1121
954
        Force using of tmp table if sorting by a SP or UDF function due to
1122
955
        their expensive and probably non-deterministic nature.
1123
956
      */
1124
 
      for (Order *tmp_order= order; tmp_order ; tmp_order=tmp_order->next)
 
957
      for (order_st *tmp_order= order; tmp_order ; tmp_order=tmp_order->next)
1125
958
      {
1126
959
        Item *item= *tmp_order->item;
1127
960
        if (item->is_expensive())
1165
998
 
1166
999
    tmp_table_param.hidden_field_count= (all_fields.elements -
1167
1000
           fields_list.elements);
1168
 
    Order *tmp_group= (((not simple_group) or not (getDebug().test(debug::NO_KEY_GROUP))) ? group_list : (Order*) 0);
1169
 
 
 
1001
    order_st *tmp_group= ((!simple_group && 
 
1002
                           ! (test_flags.test(TEST_NO_KEY_GROUP))) ? group_list :
 
1003
                                                                     (order_st*) 0);
1170
1004
    /*
1171
1005
      Pushing LIMIT to the temporary table creation is not applicable
1172
1006
      when there is ORDER BY or GROUP BY or there is no GROUP BY, but
1175
1009
    */
1176
1010
    ha_rows tmp_rows_limit= ((order == 0 || skip_sort_order) &&
1177
1011
                             !tmp_group &&
1178
 
                             !session->getLex()->current_select->with_sum_func) ?
 
1012
                             !session->lex->current_select->with_sum_func) ?
1179
1013
                            select_limit : HA_POS_ERROR;
1180
1014
 
1181
1015
    if (!(exec_tmp_table1=
1269
1103
      If this join belongs to an uncacheable subquery save
1270
1104
      the original join
1271
1105
    */
1272
 
    if (select_lex->uncacheable.any() && 
1273
 
        ! is_top_level_join() &&
 
1106
    if (select_lex->uncacheable && !is_top_level_join() &&
1274
1107
        init_save_join_tab())
1275
 
    {
1276
 
      return -1;
1277
 
    }
 
1108
      return(-1);
1278
1109
  }
1279
1110
 
1280
1111
  error= 0;
1281
 
  return 0;
1282
 
 
1283
 
setup_subq_exit:
1284
 
  /* Even with zero matching rows, subqueries in the HAVING clause
1285
 
     may need to be evaluated if there are aggregate functions in the query.
1286
 
  */
1287
 
  if (setup_subquery_materialization())
1288
 
    return 1;
1289
 
  error= 0;
1290
 
  return 0;
 
1112
  return(0);
1291
1113
}
1292
1114
 
1293
1115
/**
1294
1116
  Restore values in temporary join.
1295
1117
*/
1296
 
void Join::restore_tmp()
 
1118
void JOIN::restore_tmp()
1297
1119
{
1298
 
  memcpy(tmp_join, this, (size_t) sizeof(Join));
 
1120
  memcpy(tmp_join, this, (size_t) sizeof(JOIN));
1299
1121
}
1300
1122
 
1301
 
int Join::reinit()
 
1123
int JOIN::reinit()
1302
1124
{
1303
1125
  unit->offset_limit_cnt= (ha_rows)(select_lex->offset_limit ?
1304
1126
                                    select_lex->offset_limit->val_uint() :
1350
1172
   @retval 0      success.
1351
1173
   @retval 1      error occurred.
1352
1174
*/
1353
 
bool Join::init_save_join_tab()
 
1175
bool JOIN::init_save_join_tab()
1354
1176
{
1355
 
  if (!(tmp_join= (Join*)session->getMemRoot()->allocate(sizeof(Join))))
 
1177
  if (!(tmp_join= (JOIN*)session->alloc(sizeof(JOIN))))
1356
1178
    return 1;
1357
 
 
1358
1179
  error= 0;              // Ensure that tmp_join.error= 0
1359
1180
  restore_tmp();
1360
 
 
1361
1181
  return 0;
1362
1182
}
1363
1183
 
1364
 
bool Join::save_join_tab()
 
1184
bool JOIN::save_join_tab()
1365
1185
{
1366
 
  if (! join_tab_save && select_lex->master_unit()->uncacheable.any())
 
1186
  if (!join_tab_save && select_lex->master_unit()->uncacheable)
1367
1187
  {
1368
 
    if (!(join_tab_save= (JoinTable*)session->getMemRoot()->duplicate((unsigned char*) join_tab,
 
1188
    if (!(join_tab_save= (JoinTable*)session->memdup((unsigned char*) join_tab,
1369
1189
            sizeof(JoinTable) * tables)))
1370
1190
      return 1;
1371
1191
  }
1383
1203
  @todo
1384
1204
    When can we have here session->net.report_error not zero?
1385
1205
*/
1386
 
void Join::exec()
 
1206
void JOIN::exec()
1387
1207
{
1388
1208
  List<Item> *columns_list= &fields_list;
1389
1209
  int      tmp_error;
1484
1304
    return;
1485
1305
  }
1486
1306
 
1487
 
  Join *curr_join= this;
 
1307
  JOIN *curr_join= this;
1488
1308
  List<Item> *curr_all_fields= &all_fields;
1489
1309
  List<Item> *curr_fields_list= &fields_list;
1490
1310
  Table *curr_tmp_table= 0;
1594
1414
                                                   - curr_join->tmp_fields_list1.elements;
1595
1415
 
1596
1416
      if (exec_tmp_table2)
1597
 
      {
1598
1417
        curr_tmp_table= exec_tmp_table2;
1599
 
      }
1600
1418
      else
1601
1419
      {
1602
1420
        /* group data to new table */
1604
1422
        /*
1605
1423
          If the access method is loose index scan then all MIN/MAX
1606
1424
          functions are precomputed, and should be treated as regular
1607
 
          functions. See extended comment in Join::exec.
 
1425
          functions. See extended comment in JOIN::exec.
1608
1426
        */
1609
1427
        if (curr_join->join_tab->is_using_loose_index_scan())
1610
1428
          curr_join->tmp_table_param.precomputed_group_by= true;
1613
1431
              exec_tmp_table2= create_tmp_table(session,
1614
1432
                                                &curr_join->tmp_table_param,
1615
1433
                                                *curr_all_fields,
1616
 
                                                (Order*) 0,
 
1434
                                                (order_st*) 0,
1617
1435
                                                curr_join->select_distinct &&
1618
1436
                                                !curr_join->group_list,
1619
1437
                                                1, curr_join->select_options,
1620
1438
                                                HA_POS_ERROR,
1621
1439
                                                (char *) "")))
1622
 
        {
1623
1440
          return;
1624
 
        }
1625
 
 
1626
1441
        curr_join->exec_tmp_table2= exec_tmp_table2;
1627
1442
      }
1628
1443
      if (curr_join->group_list)
1670
1485
        error= tmp_error;
1671
1486
        return;
1672
1487
      }
1673
 
      curr_join->join_tab->read_record.end_read_record();
 
1488
      end_read_record(&curr_join->join_tab->read_record);
1674
1489
      curr_join->const_tables= curr_join->tables; // Mark free for cleanup()
1675
1490
      curr_join->join_tab[0].table= 0;           // Table is freed
1676
1491
 
1767
1582
      if (sort_table_cond)
1768
1583
      {
1769
1584
        if (!curr_table->select)
1770
 
          if (!(curr_table->select= new optimizer::SqlSelect()))
 
1585
          if (!(curr_table->select= new optimizer::SqlSelect))
1771
1586
            return;
1772
1587
        if (!curr_table->select->cond)
1773
1588
          curr_table->select->cond= sort_table_cond;
1871
1686
    for a derived table which is always materialized.
1872
1687
    Otherwise we would not be able to print the query  correctly.
1873
1688
  */
1874
 
  if (items0 && (session->getLex()->describe & DESCRIBE_EXTENDED) && select_lex->linkage == DERIVED_TABLE_TYPE)
 
1689
  if (items0 && (session->lex->describe & DESCRIBE_EXTENDED) && select_lex->linkage == DERIVED_TABLE_TYPE)
1875
1690
    set_items_ref_array(items0);
1876
1691
 
1877
1692
  return;
1881
1696
  Clean up join.
1882
1697
 
1883
1698
  @return
1884
 
    Return error that hold Join.
 
1699
    Return error that hold JOIN.
1885
1700
*/
1886
 
int Join::destroy()
 
1701
int JOIN::destroy()
1887
1702
{
1888
1703
  select_lex->join= 0;
1889
1704
 
1902
1717
  cond_equal= 0;
1903
1718
 
1904
1719
  cleanup(1);
1905
 
  exec_tmp_table1= NULL;
1906
 
  exec_tmp_table2= NULL;
 
1720
  if (exec_tmp_table1)
 
1721
    exec_tmp_table1->free_tmp_table(session);
 
1722
  if (exec_tmp_table2)
 
1723
    exec_tmp_table2->free_tmp_table(session);
1907
1724
  delete select;
1908
1725
  delete_dynamic(&keyuse);
1909
 
 
1910
1726
  return(error);
1911
1727
}
1912
1728
 
1919
1735
  - try to initialize all data structures needed for the materialized execution
1920
1736
    of the IN predicate,
1921
1737
  - if this fails, then perform the IN=>EXISTS transformation which was
1922
 
    previously blocked during Join::prepare.
 
1738
    previously blocked during JOIN::prepare.
1923
1739
 
1924
1740
  This method is part of the "code generation" query processing phase.
1925
1741
 
1932
1748
  @retval false     success.
1933
1749
  @retval true      error occurred.
1934
1750
*/
1935
 
bool Join::setup_subquery_materialization()
 
1751
bool JOIN::setup_subquery_materialization()
1936
1752
{
1937
1753
  for (Select_Lex_Unit *un= select_lex->first_inner_unit(); un;
1938
1754
       un= un->next_unit())
1954
1770
}
1955
1771
 
1956
1772
/**
1957
 
  Partially cleanup Join after it has executed: close index or rnd read
 
1773
  Partially cleanup JOIN after it has executed: close index or rnd read
1958
1774
  (table cursors), free quick selects.
1959
1775
 
1960
 
    This function is called in the end of execution of a Join, before the used
 
1776
    This function is called in the end of execution of a JOIN, before the used
1961
1777
    tables are unlocked and closed.
1962
1778
 
1963
1779
    For a join that is resolved using a temporary table, the first sweep is
1971
1787
    is called after all rows are sent, but before EOF packet is sent.
1972
1788
 
1973
1789
    For a simple SELECT with no subqueries this function performs a full
1974
 
    cleanup of the Join and calls unlockReadTables to free used base
 
1790
    cleanup of the JOIN and calls mysql_unlock_read_tables to free used base
1975
1791
    tables.
1976
1792
 
1977
 
    If a Join is executed for a subquery or if it has a subquery, we can't
 
1793
    If a JOIN is executed for a subquery or if it has a subquery, we can't
1978
1794
    do the full cleanup and need to do a partial cleanup only.
1979
 
    - If a Join is not the top level join, we must not unlock the tables
 
1795
    - If a JOIN is not the top level join, we must not unlock the tables
1980
1796
    because the outer select may not have been evaluated yet, and we
1981
1797
    can't unlock only selected tables of a query.
1982
 
    - Additionally, if this Join corresponds to a correlated subquery, we
 
1798
    - Additionally, if this JOIN corresponds to a correlated subquery, we
1983
1799
    should not free quick selects and join buffers because they will be
1984
1800
    needed for the next execution of the correlated subquery.
1985
 
    - However, if this is a Join for a [sub]select, which is not
 
1801
    - However, if this is a JOIN for a [sub]select, which is not
1986
1802
    a correlated subquery itself, but has subqueries, we can free it
1987
 
    fully and also free Joins of all its subqueries. The exception
 
1803
    fully and also free JOINs of all its subqueries. The exception
1988
1804
    is a subquery in SELECT list, e.g: @n
1989
1805
    SELECT a, (select cmax(b) from t1) group by c @n
1990
1806
    This subquery will not be evaluated at first sweep and its value will
1995
1811
  @todo
1996
1812
    Unlock tables even if the join isn't top level select in the tree
1997
1813
*/
1998
 
void Join::join_free()
 
1814
void JOIN::join_free()
1999
1815
{
2000
1816
  Select_Lex_Unit *tmp_unit;
2001
1817
  Select_Lex *sl;
2002
1818
  /*
2003
 
    Optimization: if not EXPLAIN and we are done with the Join,
 
1819
    Optimization: if not EXPLAIN and we are done with the JOIN,
2004
1820
    free all tables.
2005
1821
  */
2006
 
  bool full= (select_lex->uncacheable.none() && ! session->getLex()->describe);
 
1822
  bool full= (!select_lex->uncacheable && !session->lex->describe);
2007
1823
  bool can_unlock= full;
2008
1824
 
2009
1825
  cleanup(full);
2014
1830
    for (sl= tmp_unit->first_select(); sl; sl= sl->next_select())
2015
1831
    {
2016
1832
      Item_subselect *subselect= sl->master_unit()->item;
2017
 
      bool full_local= full && (!subselect || 
2018
 
                                (subselect->is_evaluated() &&
2019
 
                                !subselect->is_uncacheable()));
 
1833
      bool full_local= full && (!subselect || subselect->is_evaluated());
2020
1834
      /*
2021
1835
        If this join is evaluated, we can fully clean it up and clean up all
2022
1836
        its underlying joins even if they are correlated -- they will not be
2027
1841
        but all table cursors must be closed before the unlock.
2028
1842
      */
2029
1843
      sl->cleanup_all_joins(full_local);
2030
 
      /* Can't unlock if at least one Join is still needed */
 
1844
      /* Can't unlock if at least one JOIN is still needed */
2031
1845
      can_unlock= can_unlock && full_local;
2032
1846
    }
2033
1847
 
2038
1852
  if (can_unlock && lock && session->lock &&
2039
1853
      !(select_options & SELECT_NO_UNLOCK) &&
2040
1854
      !select_lex->subquery_in_having &&
2041
 
      (select_lex == (session->getLex()->unit.fake_select_lex ?
2042
 
                      session->getLex()->unit.fake_select_lex : &session->getLex()->select_lex)))
 
1855
      (select_lex == (session->lex->unit.fake_select_lex ?
 
1856
                      session->lex->unit.fake_select_lex : &session->lex->select_lex)))
2043
1857
  {
2044
1858
    /*
2045
1859
      TODO: unlock tables even if the join isn't top level select in the
2046
1860
      tree.
2047
1861
    */
2048
 
    session->unlockReadTables(lock);           // Don't free join->lock
 
1862
    mysql_unlock_read_tables(session, lock);           // Don't free join->lock
2049
1863
    lock= 0;
2050
1864
  }
2051
1865
 
2064
1878
    With subquery this function definitely will be called several times,
2065
1879
    but even for simple query it can be called several times.
2066
1880
*/
2067
 
void Join::cleanup(bool full)
 
1881
void JOIN::cleanup(bool full)
2068
1882
{
2069
1883
  if (table)
2070
1884
  {
 
1885
    JoinTable *tab,*end;
2071
1886
    /*
2072
1887
      Only a sorted table may be cached.  This sorted table is always the
2073
1888
      first non const table in join->table
2077
1892
      table[const_tables]->free_io_cache();
2078
1893
      table[const_tables]->filesort_free_buffers(full);
2079
1894
    }
2080
 
  }
2081
 
 
2082
 
  if (join_tab)
2083
 
  {
2084
 
    JoinTable *tab,*end;
2085
1895
 
2086
1896
    if (full)
2087
1897
    {
2098
1908
      }
2099
1909
    }
2100
1910
  }
2101
 
 
2102
1911
  /*
2103
1912
    We are not using tables anymore
2104
1913
    Unlock all tables. We may be in an INSERT .... SELECT statement.
2112
1921
      We can't call delete_elements() on copy_funcs as this will cause
2113
1922
      problems in free_elements() as some of the elements are then deleted.
2114
1923
    */
2115
 
    tmp_table_param.copy_funcs.clear();
 
1924
    tmp_table_param.copy_funcs.empty();
2116
1925
    /*
2117
 
      If we have tmp_join and 'this' Join is not tmp_join and
 
1926
      If we have tmp_join and 'this' JOIN is not tmp_join and
2118
1927
      tmp_table_param.copy_field's  of them are equal then we have to remove
2119
1928
      pointer to  tmp_table_param.copy_field from tmp_join, because it qill
2120
1929
      be removed in tmp_table_param.cleanup().
2133
1942
}
2134
1943
 
2135
1944
/*
2136
 
  used only in Join::clear
 
1945
  used only in JOIN::clear
2137
1946
*/
2138
 
static void clear_tables(Join *join)
 
1947
static void clear_tables(JOIN *join)
2139
1948
{
2140
1949
  /*
2141
1950
    must clear only the non-const tables, as const tables
2142
1951
    are not re-calculated.
2143
1952
  */
2144
1953
  for (uint32_t i= join->const_tables; i < join->tables; i++)
2145
 
  {
2146
1954
    join->table[i]->mark_as_null_row();   // All fields are NULL
2147
 
  }
2148
1955
}
2149
1956
 
2150
1957
/**
2156
1963
  @retval
2157
1964
    1 Error
2158
1965
*/
2159
 
bool Join::alloc_func_list()
 
1966
bool JOIN::alloc_func_list()
2160
1967
{
2161
1968
  uint32_t func_count, group_parts;
2162
1969
 
2165
1972
    If we are using rollup, we need a copy of the summary functions for
2166
1973
    each level
2167
1974
  */
2168
 
  if (rollup.getState() != Rollup::STATE_NONE)
 
1975
  if (rollup.state != ROLLUP::STATE_NONE)
2169
1976
    func_count*= (send_group_parts+1);
2170
1977
 
2171
1978
  group_parts= send_group_parts;
2182
1989
    */
2183
1990
    if (order)
2184
1991
    {
2185
 
      Order *ord;
 
1992
      order_st *ord;
2186
1993
      for (ord= order; ord; ord= ord->next)
2187
1994
        group_parts++;
2188
1995
    }
2208
2015
  @retval
2209
2016
    1  error
2210
2017
*/
2211
 
bool Join::make_sum_func_list(List<Item> &field_list, 
 
2018
bool JOIN::make_sum_func_list(List<Item> &field_list, 
2212
2019
                              List<Item> &send_fields,
2213
2020
                              bool before_group_by, 
2214
2021
                              bool recompute)
2215
2022
{
2216
 
  List<Item>::iterator it(field_list.begin());
 
2023
  List_iterator_fast<Item> it(field_list);
2217
2024
  Item_sum **func;
2218
2025
  Item *item;
2219
2026
 
2228
2035
         ((Item_sum *)item)->depended_from() == select_lex))
2229
2036
      *func++= (Item_sum*) item;
2230
2037
  }
2231
 
  if (before_group_by && rollup.getState() == Rollup::STATE_INITED)
 
2038
  if (before_group_by && rollup.state == ROLLUP::STATE_INITED)
2232
2039
  {
2233
 
    rollup.setState(Rollup::STATE_READY);
 
2040
    rollup.state= ROLLUP::STATE_READY;
2234
2041
    if (rollup_make_fields(field_list, send_fields, &func))
2235
 
      return true;     // Should never happen
 
2042
      return(true);     // Should never happen
2236
2043
  }
2237
 
  else if (rollup.getState() == Rollup::STATE_NONE)
 
2044
  else if (rollup.state == ROLLUP::STATE_NONE)
2238
2045
  {
2239
2046
    for (uint32_t i=0 ; i <= send_group_parts ;i++)
2240
2047
      sum_funcs_end[i]= func;
2241
2048
  }
2242
 
  else if (rollup.getState() == Rollup::STATE_READY)
 
2049
  else if (rollup.state == ROLLUP::STATE_READY)
2243
2050
    return(false);                         // Don't put end marker
2244
2051
  *func=0;          // End marker
2245
2052
  return(false);
2246
2053
}
2247
2054
 
2248
2055
/** Allocate memory needed for other rollup functions. */
2249
 
bool Join::rollup_init()
 
2056
bool JOIN::rollup_init()
2250
2057
{
 
2058
  uint32_t i,j;
2251
2059
  Item **ref_array;
2252
2060
 
2253
2061
  tmp_table_param.quick_group= 0; // Can't create groups in tmp table
2254
 
  rollup.setState(Rollup::STATE_INITED);
 
2062
  rollup.state= ROLLUP::STATE_INITED;
2255
2063
 
2256
2064
  /*
2257
2065
    Create pointers to the different sum function groups
2259
2067
  */
2260
2068
  tmp_table_param.group_parts= send_group_parts;
2261
2069
 
2262
 
  rollup.setNullItems((Item_null_result**) session->getMemRoot()->allocate((sizeof(Item*) +
2263
 
                                                                sizeof(Item**) +
2264
 
                                                                sizeof(List<Item>) +
2265
 
                                                                ref_pointer_array_size)
2266
 
                                                               * send_group_parts ));
2267
 
  if (! rollup.getNullItems())
2268
 
  {
 
2070
  if (!(rollup.null_items= (Item_null_result**) session->alloc((sizeof(Item*) +
 
2071
                                                sizeof(Item**) +
 
2072
                                                sizeof(List<Item>) +
 
2073
                        ref_pointer_array_size)
 
2074
                        * send_group_parts )))
2269
2075
    return 1;
2270
 
  }
2271
2076
 
2272
 
  rollup.setFields((List<Item>*) (rollup.getNullItems() + send_group_parts));
2273
 
  rollup.setRefPointerArrays((Item***) (rollup.getFields() + send_group_parts));
2274
 
  ref_array= (Item**) (rollup.getRefPointerArrays()+send_group_parts);
 
2077
  rollup.fields= (List<Item>*) (rollup.null_items + send_group_parts);
 
2078
  rollup.ref_pointer_arrays= (Item***) (rollup.fields + send_group_parts);
 
2079
  ref_array= (Item**) (rollup.ref_pointer_arrays+send_group_parts);
2275
2080
 
2276
2081
  /*
2277
2082
    Prepare space for field list for the different levels
2278
2083
    These will be filled up in rollup_make_fields()
2279
2084
  */
2280
 
  for (uint32_t i= 0 ; i < send_group_parts ; i++)
 
2085
  for (i= 0 ; i < send_group_parts ; i++)
2281
2086
  {
2282
 
    rollup.getNullItems()[i]= new (session->mem_root) Item_null_result();
2283
 
    List<Item> *rollup_fields= &rollup.getFields()[i];
2284
 
    rollup_fields->clear();
2285
 
    rollup.getRefPointerArrays()[i]= ref_array;
 
2087
    rollup.null_items[i]= new (session->mem_root) Item_null_result();
 
2088
    List<Item> *rollup_fields= &rollup.fields[i];
 
2089
    rollup_fields->empty();
 
2090
    rollup.ref_pointer_arrays[i]= ref_array;
2286
2091
    ref_array+= all_fields.elements;
2287
2092
  }
2288
 
 
2289
 
  for (uint32_t i= 0 ; i < send_group_parts; i++)
 
2093
  for (i= 0 ; i < send_group_parts; i++)
2290
2094
  {
2291
 
    for (uint32_t j= 0 ; j < fields_list.elements ; j++)
2292
 
    {
2293
 
      rollup.getFields()[i].push_back(rollup.getNullItems()[i]);
2294
 
    }
 
2095
    for (j=0 ; j < fields_list.elements ; j++)
 
2096
      rollup.fields[i].push_back(rollup.null_items[i]);
2295
2097
  }
2296
 
 
2297
 
  List<Item>::iterator it(all_fields.begin());
 
2098
  List_iterator<Item> it(all_fields);
2298
2099
  Item *item;
2299
2100
  while ((item= it++))
2300
2101
  {
2301
 
    Order *group_tmp;
 
2102
    order_st *group_tmp;
2302
2103
    bool found_in_group= 0;
2303
2104
 
2304
2105
    for (group_tmp= group_list; group_tmp; group_tmp= group_tmp->next)
2327
2128
            return 1;
2328
2129
          new_item->fix_fields(session, (Item **) 0);
2329
2130
          session->change_item_tree(it.ref(), new_item);
2330
 
          for (Order *tmp= group_tmp; tmp; tmp= tmp->next)
 
2131
          for (order_st *tmp= group_tmp; tmp; tmp= tmp->next)
2331
2132
          {
2332
2133
            if (*tmp->item == item)
2333
2134
              session->change_item_tree(tmp->item, new_item);
2367
2168
  @retval
2368
2169
    1    on error
2369
2170
*/
2370
 
bool Join::rollup_make_fields(List<Item> &fields_arg, List<Item> &sel_fields, Item_sum ***func)
 
2171
bool JOIN::rollup_make_fields(List<Item> &fields_arg, List<Item> &sel_fields, Item_sum ***func)
2371
2172
{
2372
 
  List<Item>::iterator it(fields_arg.begin());
 
2173
  List_iterator_fast<Item> it(fields_arg);
2373
2174
  Item *first_field= sel_fields.head();
2374
2175
  uint32_t level;
2375
2176
 
2400
2201
    uint32_t pos= send_group_parts - level -1;
2401
2202
    bool real_fields= 0;
2402
2203
    Item *item;
2403
 
    List<Item>::iterator new_it(rollup.getFields()[pos].begin());
2404
 
    Item **ref_array_start= rollup.getRefPointerArrays()[pos];
2405
 
    Order *start_group;
 
2204
    List_iterator<Item> new_it(rollup.fields[pos]);
 
2205
    Item **ref_array_start= rollup.ref_pointer_arrays[pos];
 
2206
    order_st *start_group;
2406
2207
 
2407
2208
    /* Point to first hidden field */
2408
2209
    Item **ref_array= ref_array_start + fields_arg.elements-1;
2414
2215
    for (i= 0, start_group= group_list ;i++ < pos ;start_group= start_group->next)
2415
2216
    {}
2416
2217
 
2417
 
    it= fields_arg.begin();
 
2218
    it.rewind();
2418
2219
    while ((item= it++))
2419
2220
    {
2420
2221
      if (item == first_field)
2444
2245
      else
2445
2246
      {
2446
2247
        /* Check if this is something that is part of this group by */
2447
 
        Order *group_tmp;
 
2248
        order_st *group_tmp;
2448
2249
        for (group_tmp= start_group, i= pos ;
2449
2250
                  group_tmp ; group_tmp= group_tmp->next, i++)
2450
2251
        {
2497
2298
  @retval
2498
2299
    1   If send_data_failed()
2499
2300
*/
2500
 
int Join::rollup_send_data(uint32_t idx)
 
2301
int JOIN::rollup_send_data(uint32_t idx)
2501
2302
{
2502
 
  for (uint32_t i= send_group_parts ; i-- > idx ; )
 
2303
  uint32_t i;
 
2304
  for (i= send_group_parts ; i-- > idx ; )
2503
2305
  {
2504
2306
    /* Get reference pointers to sum functions in place */
2505
 
    memcpy(ref_pointer_array, rollup.getRefPointerArrays()[i], ref_pointer_array_size);
2506
 
 
 
2307
    memcpy(ref_pointer_array, rollup.ref_pointer_arrays[i],
 
2308
     ref_pointer_array_size);
2507
2309
    if ((!having || having->val_int()))
2508
2310
    {
2509
 
      if (send_records < unit->select_limit_cnt && do_send_rows && result->send_data(rollup.getFields()[i]))
2510
 
      {
2511
 
        return 1;
2512
 
      }
 
2311
      if (send_records < unit->select_limit_cnt && do_send_rows &&
 
2312
    result->send_data(rollup.fields[i]))
 
2313
  return 1;
2513
2314
      send_records++;
2514
2315
    }
2515
2316
  }
2516
2317
  /* Restore ref_pointer_array */
2517
2318
  set_items_ref_array(current_ref_pointer_array);
2518
 
 
2519
2319
  return 0;
2520
2320
}
2521
2321
 
2538
2338
  @retval
2539
2339
    1   if write_data_failed()
2540
2340
*/
2541
 
int Join::rollup_write_data(uint32_t idx, Table *table_arg)
 
2341
int JOIN::rollup_write_data(uint32_t idx, Table *table_arg)
2542
2342
{
2543
 
  for (uint32_t i= send_group_parts ; i-- > idx ; )
 
2343
  uint32_t i;
 
2344
  for (i= send_group_parts ; i-- > idx ; )
2544
2345
  {
2545
2346
    /* Get reference pointers to sum functions in place */
2546
 
    memcpy(ref_pointer_array, rollup.getRefPointerArrays()[i],
 
2347
    memcpy(ref_pointer_array, rollup.ref_pointer_arrays[i],
2547
2348
           ref_pointer_array_size);
2548
2349
    if ((!having || having->val_int()))
2549
2350
    {
2550
2351
      int write_error;
2551
2352
      Item *item;
2552
 
      List<Item>::iterator it(rollup.getFields()[i].begin());
 
2353
      List_iterator_fast<Item> it(rollup.fields[i]);
2553
2354
      while ((item= it++))
2554
2355
      {
2555
2356
        if (item->type() == Item::NULL_ITEM && item->is_result_field())
2556
2357
          item->save_in_result_field(1);
2557
2358
      }
2558
2359
      copy_sum_funcs(sum_funcs_end[i+1], sum_funcs_end[i]);
2559
 
      if ((write_error= table_arg->cursor->insertRecord(table_arg->getInsertRecord())))
 
2360
      if ((write_error= table_arg->cursor->insertRecord(table_arg->record[0])))
2560
2361
      {
2561
2362
        my_error(ER_USE_SQL_BIG_RESULT, MYF(0));
2562
2363
        return 1;
2565
2366
  }
2566
2367
  /* Restore ref_pointer_array */
2567
2368
  set_items_ref_array(current_ref_pointer_array);
2568
 
 
2569
2369
  return 0;
2570
2370
}
2571
2371
 
2573
2373
  clear results if there are not rows found for group
2574
2374
  (end_send_group/end_write_group)
2575
2375
*/
2576
 
void Join::clear()
 
2376
void JOIN::clear()
2577
2377
{
2578
2378
  clear_tables(this);
2579
2379
  copy_fields(&tmp_table_param);
2587
2387
}
2588
2388
 
2589
2389
/**
2590
 
  change select_result object of Join.
 
2390
  change select_result object of JOIN.
2591
2391
 
2592
2392
  @param res    new select_result object
2593
2393
 
2596
2396
  @retval
2597
2397
    true    error
2598
2398
*/
2599
 
bool Join::change_result(select_result *res)
 
2399
bool JOIN::change_result(select_result *res)
2600
2400
{
2601
2401
  result= res;
2602
2402
  if (result->prepare(fields_list, select_lex->master_unit()))
2610
2410
  Cache constant expressions in WHERE, HAVING, ON conditions.
2611
2411
*/
2612
2412
 
2613
 
void Join::cache_const_exprs()
 
2413
void JOIN::cache_const_exprs()
2614
2414
{
2615
2415
  bool cache_flag= false;
2616
2416
  bool *analyzer_arg= &cache_flag;
2651
2451
  applicable to the partial record on hand and in case of success
2652
2452
  submit this record to the next level of the nested loop.
2653
2453
*/
2654
 
enum_nested_loop_state evaluate_join_record(Join *join, JoinTable *join_tab, int error)
 
2454
enum_nested_loop_state evaluate_join_record(JOIN *join, JoinTable *join_tab, int error)
2655
2455
{
2656
2456
  bool not_used_in_distinct= join_tab->not_used_in_distinct;
2657
2457
  ha_rows found_records= join->found_records;
2661
2461
    return NESTED_LOOP_ERROR;
2662
2462
  if (error < 0)
2663
2463
    return NESTED_LOOP_NO_MORE_ROWS;
2664
 
  if (join->session->getKilled())                       // Aborted by user
 
2464
  if (join->session->killed)                    // Aborted by user
2665
2465
  {
2666
2466
    join->session->send_kill_message();
2667
2467
    return NESTED_LOOP_KILLED;
2775
2575
    level of the nested loop. This function is used in case we have
2776
2576
    an OUTER join and no matching record was found.
2777
2577
*/
2778
 
enum_nested_loop_state evaluate_null_complemented_join_record(Join *join, JoinTable *join_tab)
 
2578
enum_nested_loop_state evaluate_null_complemented_join_record(JOIN *join, JoinTable *join_tab)
2779
2579
{
2780
2580
  /*
2781
2581
    The table join_tab is the first inner table of a outer join operation
2831
2631
  return (*join_tab->next_select)(join, join_tab+1, 0);
2832
2632
}
2833
2633
 
2834
 
enum_nested_loop_state flush_cached_records(Join *join, JoinTable *join_tab, bool skip_last)
 
2634
enum_nested_loop_state flush_cached_records(JOIN *join, JoinTable *join_tab, bool skip_last)
2835
2635
{
2836
2636
  enum_nested_loop_state rc= NESTED_LOOP_OK;
2837
2637
  int error;
2838
 
  ReadRecord *info;
 
2638
  READ_RECORD *info;
2839
2639
 
2840
2640
  join_tab->table->null_row= 0;
2841
2641
  if (!join_tab->cache.records)
2842
 
  {
2843
2642
    return NESTED_LOOP_OK;                      /* Nothing to do */
2844
 
  }
2845
 
 
2846
2643
  if (skip_last)
2847
 
  {
2848
 
    (void) join_tab->cache.store_record_in_cache(); // Must save this for later
2849
 
  }
2850
 
 
2851
 
 
 
2644
    (void) store_record_in_cache(&join_tab->cache); // Must save this for later
2852
2645
  if (join_tab->use_quick == 2)
2853
2646
  {
2854
2647
    if (join_tab->select->quick)
2860
2653
  /* read through all records */
2861
2654
  if ((error=join_init_read_record(join_tab)))
2862
2655
  {
2863
 
    join_tab->cache.reset_cache_write();
 
2656
    reset_cache_write(&join_tab->cache);
2864
2657
    return error < 0 ? NESTED_LOOP_NO_MORE_ROWS: NESTED_LOOP_ERROR;
2865
2658
  }
2866
2659
 
2873
2666
  info= &join_tab->read_record;
2874
2667
  do
2875
2668
  {
2876
 
    if (join->session->getKilled())
 
2669
    if (join->session->killed)
2877
2670
    {
2878
2671
      join->session->send_kill_message();
2879
2672
      return NESTED_LOOP_KILLED;
2883
2676
        (!join_tab->cache.select || !join_tab->cache.select->skip_record()))
2884
2677
    {
2885
2678
      uint32_t i;
2886
 
      join_tab->cache.reset_cache_read();
 
2679
      reset_cache_read(&join_tab->cache);
2887
2680
      for (i=(join_tab->cache.records- (skip_last ? 1 : 0)) ; i-- > 0 ;)
2888
2681
      {
2889
2682
              join_tab->readCachedRecord();
2894
2687
          rc= (join_tab->next_select)(join,join_tab+1,0);
2895
2688
          if (rc != NESTED_LOOP_OK && rc != NESTED_LOOP_NO_MORE_ROWS)
2896
2689
          {
2897
 
            join_tab->cache.reset_cache_write();
 
2690
            reset_cache_write(&join_tab->cache);
2898
2691
            return rc;
2899
2692
          }
2900
2693
 
2907
2700
 
2908
2701
  if (skip_last)
2909
2702
    join_tab->readCachedRecord();               // Restore current record
2910
 
  join_tab->cache.reset_cache_write();
 
2703
  reset_cache_write(&join_tab->cache);
2911
2704
  if (error > 0)                                // Fatal error
2912
2705
    return NESTED_LOOP_ERROR;
2913
2706
  for (JoinTable *tmp2=join->join_tab; tmp2 != join_tab ; tmp2++)
2939
2732
                               operation.
2940
2733
   All return values except NESTED_LOOP_OK abort the nested loop.
2941
2734
*****************************************************************************/
2942
 
enum_nested_loop_state end_send(Join *join, JoinTable *, bool end_of_records)
 
2735
enum_nested_loop_state end_send(JOIN *join, JoinTable *, bool end_of_records)
2943
2736
{
2944
2737
  if (! end_of_records)
2945
2738
  {
3001
2794
  return NESTED_LOOP_OK;
3002
2795
}
3003
2796
 
3004
 
enum_nested_loop_state end_write(Join *join, JoinTable *, bool end_of_records)
 
2797
enum_nested_loop_state end_write(JOIN *join, JoinTable *, bool end_of_records)
3005
2798
{
3006
2799
  Table *table= join->tmp_table;
3007
2800
 
3008
 
  if (join->session->getKilled())                       // Aborted by user
 
2801
  if (join->session->killed)                    // Aborted by user
3009
2802
  {
3010
2803
    join->session->send_kill_message();
3011
2804
    return NESTED_LOOP_KILLED;
3013
2806
  if (!end_of_records)
3014
2807
  {
3015
2808
    copy_fields(&join->tmp_table_param);
3016
 
    if (copy_funcs(join->tmp_table_param.items_to_copy, join->session))
3017
 
      return NESTED_LOOP_ERROR;
 
2809
    copy_funcs(join->tmp_table_param.items_to_copy);
3018
2810
    if (!join->having || join->having->val_int())
3019
2811
    {
3020
2812
      int error;
3021
2813
      join->found_records++;
3022
 
      if ((error=table->cursor->insertRecord(table->getInsertRecord())))
 
2814
      if ((error=table->cursor->insertRecord(table->record[0])))
3023
2815
      {
3024
2816
        if (!table->cursor->is_fatal_error(error, HA_CHECK_DUP))
3025
 
        {
3026
 
          return NESTED_LOOP_OK;
3027
 
        }
 
2817
          goto end;
3028
2818
 
3029
2819
        my_error(ER_USE_SQL_BIG_RESULT, MYF(0));
3030
2820
        return NESTED_LOOP_ERROR;        // Table is_full error
3039
2829
      }
3040
2830
    }
3041
2831
  }
3042
 
 
 
2832
end:
3043
2833
  return NESTED_LOOP_OK;
3044
2834
}
3045
2835
 
3046
2836
/** Group by searching after group record and updating it if possible. */
3047
 
enum_nested_loop_state end_update(Join *join, JoinTable *, bool end_of_records)
 
2837
enum_nested_loop_state end_update(JOIN *join, JoinTable *, bool end_of_records)
3048
2838
{
3049
2839
  Table *table= join->tmp_table;
3050
 
  Order *group;
 
2840
  order_st *group;
3051
2841
  int   error;
3052
2842
 
3053
2843
  if (end_of_records)
3054
2844
    return NESTED_LOOP_OK;
3055
 
  if (join->session->getKilled())                       // Aborted by user
 
2845
  if (join->session->killed)                    // Aborted by user
3056
2846
  {
3057
2847
    join->session->send_kill_message();
3058
2848
    return NESTED_LOOP_KILLED;
3069
2859
    if (item->maybe_null)
3070
2860
      group->buff[-1]= (char) group->field->is_null();
3071
2861
  }
3072
 
  if (!table->cursor->index_read_map(table->getUpdateRecord(),
 
2862
  if (!table->cursor->index_read_map(table->record[1],
3073
2863
                                   join->tmp_table_param.group_buff,
3074
2864
                                   HA_WHOLE_KEY,
3075
2865
                                   HA_READ_KEY_EXACT))
3076
2866
  {                                             /* Update old record */
3077
2867
    table->restoreRecord();
3078
2868
    update_tmptable_sum_func(join->sum_funcs,table);
3079
 
    if ((error= table->cursor->updateRecord(table->getUpdateRecord(),
3080
 
                                          table->getInsertRecord())))
 
2869
    if ((error= table->cursor->updateRecord(table->record[1],
 
2870
                                          table->record[0])))
3081
2871
    {
3082
2872
      table->print_error(error,MYF(0));
3083
2873
      return NESTED_LOOP_ERROR;
3096
2886
       group=group->next,key_part++)
3097
2887
  {
3098
2888
    if (key_part->null_bit)
3099
 
      memcpy(table->getInsertRecord()+key_part->offset, group->buff, 1);
 
2889
      memcpy(table->record[0]+key_part->offset, group->buff, 1);
3100
2890
  }
3101
2891
  init_tmptable_sum_functions(join->sum_funcs);
3102
 
  if (copy_funcs(join->tmp_table_param.items_to_copy, join->session))
3103
 
    return NESTED_LOOP_ERROR;
3104
 
  if ((error=table->cursor->insertRecord(table->getInsertRecord())))
 
2892
  copy_funcs(join->tmp_table_param.items_to_copy);
 
2893
  if ((error=table->cursor->insertRecord(table->record[0])))
3105
2894
  {
3106
2895
    my_error(ER_USE_SQL_BIG_RESULT, MYF(0));
3107
2896
    return NESTED_LOOP_ERROR;        // Table is_full error
3111
2900
}
3112
2901
 
3113
2902
/** Like end_update, but this is done with unique constraints instead of keys.  */
3114
 
enum_nested_loop_state end_unique_update(Join *join, JoinTable *, bool end_of_records)
 
2903
enum_nested_loop_state end_unique_update(JOIN *join, JoinTable *, bool end_of_records)
3115
2904
{
3116
2905
  Table *table= join->tmp_table;
3117
2906
  int   error;
3118
2907
 
3119
2908
  if (end_of_records)
3120
2909
    return NESTED_LOOP_OK;
3121
 
  if (join->session->getKilled())                       // Aborted by user
 
2910
  if (join->session->killed)                    // Aborted by user
3122
2911
  {
3123
2912
    join->session->send_kill_message();
3124
2913
    return NESTED_LOOP_KILLED;
3126
2915
 
3127
2916
  init_tmptable_sum_functions(join->sum_funcs);
3128
2917
  copy_fields(&join->tmp_table_param);          // Groups are copied twice.
3129
 
  if (copy_funcs(join->tmp_table_param.items_to_copy, join->session))
3130
 
    return NESTED_LOOP_ERROR;
 
2918
  copy_funcs(join->tmp_table_param.items_to_copy);
3131
2919
 
3132
 
  if (!(error= table->cursor->insertRecord(table->getInsertRecord())))
 
2920
  if (!(error= table->cursor->insertRecord(table->record[0])))
3133
2921
    join->send_records++;                       // New group
3134
2922
  else
3135
2923
  {
3138
2926
      table->print_error(error,MYF(0));
3139
2927
      return NESTED_LOOP_ERROR;
3140
2928
    }
3141
 
    if (table->cursor->rnd_pos(table->getUpdateRecord(),table->cursor->dup_ref))
 
2929
    if (table->cursor->rnd_pos(table->record[1],table->cursor->dup_ref))
3142
2930
    {
3143
2931
      table->print_error(error,MYF(0));
3144
2932
      return NESTED_LOOP_ERROR;
3145
2933
    }
3146
2934
    table->restoreRecord();
3147
2935
    update_tmptable_sum_func(join->sum_funcs,table);
3148
 
    if ((error= table->cursor->updateRecord(table->getUpdateRecord(),
3149
 
                                          table->getInsertRecord())))
 
2936
    if ((error= table->cursor->updateRecord(table->record[1],
 
2937
                                          table->record[0])))
3150
2938
    {
3151
2939
      table->print_error(error,MYF(0));
3152
2940
      return NESTED_LOOP_ERROR;
3167
2955
  @retval
3168
2956
    1   failed
3169
2957
*/
3170
 
static bool make_group_fields(Join *main_join, Join *curr_join)
 
2958
static bool make_group_fields(JOIN *main_join, JOIN *curr_join)
3171
2959
{
3172
2960
  if (main_join->group_fields_cache.elements)
3173
2961
  {
3186
2974
/**
3187
2975
  calc how big buffer we need for comparing group entries.
3188
2976
*/
3189
 
static void calc_group_buffer(Join *join, Order *group)
 
2977
static void calc_group_buffer(JOIN *join,order_st *group)
3190
2978
{
3191
2979
  uint32_t key_length=0, parts=0, null_parts=0;
3192
2980
 
3212
3000
      case REAL_RESULT:
3213
3001
        key_length+= sizeof(double);
3214
3002
        break;
3215
 
 
3216
3003
      case INT_RESULT:
3217
3004
        key_length+= sizeof(int64_t);
3218
3005
        break;
3219
 
 
3220
3006
      case DECIMAL_RESULT:
3221
 
        key_length+= class_decimal_get_binary_size(group_item->max_length -
 
3007
        key_length+= my_decimal_get_binary_size(group_item->max_length -
3222
3008
                                                (group_item->decimals ? 1 : 0),
3223
3009
                                                group_item->decimals);
3224
3010
        break;
3225
 
 
3226
3011
      case STRING_RESULT:
3227
 
        {
3228
 
          enum enum_field_types type= group_item->field_type();
 
3012
      {
 
3013
        enum enum_field_types type= group_item->field_type();
 
3014
        /*
 
3015
          As items represented as DATE/TIME fields in the group buffer
 
3016
          have STRING_RESULT result type, we increase the length
 
3017
          by 8 as maximum pack length of such fields.
 
3018
        */
 
3019
        if (type == DRIZZLE_TYPE_DATE ||
 
3020
            type == DRIZZLE_TYPE_DATETIME ||
 
3021
            type == DRIZZLE_TYPE_TIMESTAMP)
 
3022
        {
 
3023
          key_length+= 8;
 
3024
        }
 
3025
        else
 
3026
        {
3229
3027
          /*
3230
 
            As items represented as DATE/TIME fields in the group buffer
3231
 
            have STRING_RESULT result type, we increase the length
3232
 
            by 8 as maximum pack length of such fields.
 
3028
            Group strings are taken as varstrings and require an length field.
 
3029
            A field is not yet created by create_tmp_field()
 
3030
            and the sizes should match up.
3233
3031
          */
3234
 
          if (field::isDateTime(type))
3235
 
          {
3236
 
            key_length+= 8;
3237
 
          }
3238
 
          else
3239
 
          {
3240
 
            /*
3241
 
              Group strings are taken as varstrings and require an length field.
3242
 
              A field is not yet created by create_tmp_field()
3243
 
              and the sizes should match up.
3244
 
            */
3245
 
            key_length+= group_item->max_length + HA_KEY_BLOB_LENGTH;
3246
 
          }
3247
 
 
3248
 
          break;
 
3032
          key_length+= group_item->max_length + HA_KEY_BLOB_LENGTH;
3249
3033
        }
3250
 
 
3251
 
      case ROW_RESULT:
 
3034
        break;
 
3035
      }
 
3036
      default:
3252
3037
        /* This case should never be choosen */
3253
3038
        assert(0);
3254
3039
        my_error(ER_OUT_OF_RESOURCES, MYF(ME_FATALERROR));
3255
3040
      }
3256
3041
    }
3257
 
 
3258
3042
    parts++;
3259
 
 
3260
3043
    if (group_item->maybe_null)
3261
3044
      null_parts++;
3262
3045
  }
3263
 
 
3264
3046
  join->tmp_table_param.group_length=key_length+null_parts;
3265
3047
  join->tmp_table_param.group_parts=parts;
3266
3048
  join->tmp_table_param.group_null_parts=null_parts;
3271
3053
 
3272
3054
  Groups are saved in reverse order for easyer check loop.
3273
3055
*/
3274
 
static bool alloc_group_fields(Join *join, Order *group)
 
3056
static bool alloc_group_fields(JOIN *join,order_st *group)
3275
3057
{
3276
3058
  if (group)
3277
3059
  {
3286
3068
  return false;
3287
3069
}
3288
3070
 
3289
 
static uint32_t cache_record_length(Join *join,uint32_t idx)
 
3071
static uint32_t cache_record_length(JOIN *join,uint32_t idx)
3290
3072
{
3291
3073
  uint32_t length=0;
3292
3074
  JoinTable **pos,**end;
3354
3136
  RETURN
3355
3137
    Expected number of row combinations
3356
3138
*/
3357
 
static double prev_record_reads(Join *join, uint32_t idx, table_map found_ref)
 
3139
static double prev_record_reads(JOIN *join, uint32_t idx, table_map found_ref)
3358
3140
{
3359
3141
  double found=1.0;
3360
3142
  optimizer::Position *pos_end= join->getSpecificPosInPartialPlan(-1);
3366
3148
    {
3367
3149
      found_ref|= pos->getRefDependMap();
3368
3150
      /*
3369
 
        For the case of "t1 LEFT Join t2 ON ..." where t2 is a const table
 
3151
        For the case of "t1 LEFT JOIN t2 ON ..." where t2 is a const table
3370
3152
        with no matching row we will get position[t2].records_read==0.
3371
3153
        Actually the size of output is one null-complemented row, therefore
3372
3154
        we will use value of 1 whenever we get records_read==0.
3391
3173
/**
3392
3174
  Set up join struct according to best position.
3393
3175
*/
3394
 
static bool get_best_combination(Join *join)
 
3176
static bool get_best_combination(JOIN *join)
3395
3177
{
3396
3178
  uint32_t i,tablenr;
3397
3179
  table_map used_tables;
3403
3185
 
3404
3186
  table_count=join->tables;
3405
3187
  if (!(join->join_tab=join_tab=
3406
 
  (JoinTable*) session->getMemRoot()->allocate(sizeof(JoinTable)*table_count)))
 
3188
  (JoinTable*) session->alloc(sizeof(JoinTable)*table_count)))
3407
3189
    return(true);
3408
3190
 
3409
 
  for (i= 0; i < table_count; i++)
3410
 
    new (join_tab+i) JoinTable();
3411
 
 
3412
3191
  join->full_join=0;
3413
3192
 
3414
3193
  used_tables= OUTER_REF_TABLE_BIT;   // Outer row is already read
3421
3200
    used_tables|= form->map;
3422
3201
    form->reginfo.join_tab=j;
3423
3202
    if (!*j->on_expr_ref)
3424
 
      form->reginfo.not_exists_optimize=0;  // Only with LEFT Join
 
3203
      form->reginfo.not_exists_optimize=0;  // Only with LEFT JOIN
3425
3204
    if (j->type == AM_CONST)
3426
3205
      continue;         // Handled in make_join_stat..
3427
3206
 
3447
3226
}
3448
3227
 
3449
3228
/** Save const tables first as used tables. */
3450
 
static void set_position(Join *join,
 
3229
static void set_position(JOIN *join,
3451
3230
                         uint32_t idx,
3452
3231
                         JoinTable *table,
3453
3232
                         optimizer::KeyUse *key)
3489
3268
  @retval
3490
3269
    true        Fatal error
3491
3270
*/
3492
 
static bool choose_plan(Join *join, table_map join_tables)
 
3271
static bool choose_plan(JOIN *join, table_map join_tables)
3493
3272
{
3494
3273
  uint32_t search_depth= join->session->variables.optimizer_search_depth;
3495
3274
  uint32_t prune_level=  join->session->variables.optimizer_prune_level;
3527
3306
    i.e. they have subqueries, unions or call stored procedures.
3528
3307
    TODO: calculate a correct cost for a query with subqueries and UNIONs.
3529
3308
  */
3530
 
  if (join->session->getLex()->is_single_level_stmt())
 
3309
  if (join->session->lex->is_single_level_stmt())
3531
3310
    join->session->status_var.last_query_cost= join->best_read;
3532
3311
  return(false);
3533
3312
}
3556
3335
  @return
3557
3336
    None
3558
3337
*/
3559
 
static void best_access_path(Join *join,
 
3338
static void best_access_path(JOIN *join,
3560
3339
                             JoinTable *s,
3561
3340
                             Session *session,
3562
3341
                             table_map remaining_tables,
3702
3481
                records=
3703
3482
                  ((double) s->records / (double) rec *
3704
3483
                   (1.0 +
3705
 
                    ((double) (table->getShare()->max_key_length-keyinfo->key_length) /
3706
 
                     (double) table->getShare()->max_key_length)));
 
3484
                    ((double) (table->s->max_key_length-keyinfo->key_length) /
 
3485
                     (double) table->s->max_key_length)));
3707
3486
                if (records < 2.0)
3708
3487
                  records=2.0;               /* Can't be as good as a unique */
3709
3488
              }
4040
3819
        will ensure that this will be used
4041
3820
      */
4042
3821
      best= tmp;
4043
 
      records= rnd_records;
 
3822
      records= rows2double(rnd_records);
4044
3823
      best_key= 0;
4045
3824
      /* range/index_merge/ALL/index access method are "independent", so: */
4046
3825
      best_ref_depends_map= 0;
4086
3865
    Thus 'optimize_straight_join' can be used at any stage of the query
4087
3866
    optimization process to finalize a QEP as it is.
4088
3867
*/
4089
 
static void optimize_straight_join(Join *join, table_map join_tables)
 
3868
static void optimize_straight_join(JOIN *join, table_map join_tables)
4090
3869
{
4091
3870
  JoinTable *s;
4092
3871
  optimizer::Position partial_pos;
4196
3975
  @retval
4197
3976
    true        Fatal error
4198
3977
*/
4199
 
static bool greedy_search(Join      *join,
 
3978
static bool greedy_search(JOIN      *join,
4200
3979
              table_map remaining_tables,
4201
3980
              uint32_t      search_depth,
4202
3981
              uint32_t      prune_level)
4238
4017
    */
4239
4018
    join->setPosInPartialPlan(idx, best_pos);
4240
4019
 
4241
 
    /*
4242
 
      We need to make best_extension_by_limited_search aware of the fact
4243
 
      that it's not starting from top level, but from a rather specific
4244
 
      position in the list of nested joins.
4245
 
    */
4246
 
    check_interleaving_with_nj (best_table);
4247
 
    
4248
 
      
4249
 
 
4250
4020
    /* find the position of 'best_table' in 'join->best_ref' */
4251
4021
    best_idx= idx;
4252
4022
    JoinTable *pos= join->best_ref[best_idx];
4384
4154
  @retval
4385
4155
    true        Fatal error
4386
4156
*/
4387
 
static bool best_extension_by_limited_search(Join *join,
 
4157
static bool best_extension_by_limited_search(JOIN *join,
4388
4158
                                             table_map remaining_tables,
4389
4159
                                             uint32_t idx,
4390
4160
                                             double record_count,
4393
4163
                                             uint32_t prune_level)
4394
4164
{
4395
4165
  Session *session= join->session;
4396
 
  if (session->getKilled())  // Abort
 
4166
  if (session->killed)  // Abort
4397
4167
    return(true);
4398
4168
 
4399
4169
  /*
4408
4178
  for (JoinTable **pos= join->best_ref + idx ; (s= *pos) ; pos++)
4409
4179
  {
4410
4180
    table_map real_table_bit= s->table->map;
 
4181
    if (idx)
 
4182
    {
 
4183
      partial_pos= join->getPosFromPartialPlan(idx - 1);
 
4184
    }
4411
4185
    if ((remaining_tables & real_table_bit) &&
4412
4186
        ! (remaining_tables & s->dependent) &&
4413
 
        (! idx || ! check_interleaving_with_nj(s)))
 
4187
        (! idx || ! check_interleaving_with_nj(partial_pos.getJoinTable(), s)))
4414
4188
    {
4415
4189
      double current_record_count, current_read_time;
4416
4190
 
4531
4305
    exhaustiveness) of the depth-first search algorithm used by
4532
4306
    'greedy_search'.
4533
4307
*/
4534
 
static uint32_t determine_search_depth(Join *join)
 
4308
static uint32_t determine_search_depth(JOIN *join)
4535
4309
{
4536
4310
  uint32_t table_count=  join->tables - join->const_tables;
4537
4311
  uint32_t search_depth;
4550
4324
  return search_depth;
4551
4325
}
4552
4326
 
4553
 
static bool make_simple_join(Join *join,Table *tmp_table)
 
4327
static bool make_simple_join(JOIN *join,Table *tmp_table)
4554
4328
{
4555
4329
  Table **tableptr;
4556
4330
  JoinTable *join_tab;
4557
4331
 
4558
4332
  /*
4559
4333
    Reuse Table * and JoinTable if already allocated by a previous call
4560
 
    to this function through Join::exec (may happen for sub-queries).
 
4334
    to this function through JOIN::exec (may happen for sub-queries).
4561
4335
  */
4562
4336
  if (!join->table_reexec)
4563
4337
  {
4564
 
    if (!(join->table_reexec= (Table**) join->session->getMemRoot()->allocate(sizeof(Table*))))
 
4338
    if (!(join->table_reexec= (Table**) join->session->alloc(sizeof(Table*))))
4565
4339
      return(true);
4566
4340
    if (join->tmp_join)
4567
4341
      join->tmp_join->table_reexec= join->table_reexec;
4569
4343
  if (!join->join_tab_reexec)
4570
4344
  {
4571
4345
    if (!(join->join_tab_reexec=
4572
 
          (JoinTable*) join->session->getMemRoot()->allocate(sizeof(JoinTable))))
 
4346
          (JoinTable*) join->session->alloc(sizeof(JoinTable))))
4573
4347
      return(true);
4574
 
    new (join->join_tab_reexec) JoinTable();
4575
4348
    if (join->tmp_join)
4576
4349
      join->tmp_join->join_tab_reexec= join->join_tab_reexec;
4577
4350
  }
4592
4365
  join->row_limit=join->unit->select_limit_cnt;
4593
4366
  join->do_send_rows = (join->row_limit) ? 1 : 0;
4594
4367
 
 
4368
  join_tab->cache.buff=0;                       /* No caching */
4595
4369
  join_tab->table=tmp_table;
4596
4370
  join_tab->select=0;
4597
4371
  join_tab->select_cond=0;
4607
4381
  join_tab->read_first_record= join_init_read_record;
4608
4382
  join_tab->join=join;
4609
4383
  join_tab->ref.key_parts= 0;
4610
 
  join_tab->read_record.init();
 
4384
  memset(&join_tab->read_record, 0, sizeof(join_tab->read_record));
4611
4385
  tmp_table->status=0;
4612
4386
  tmp_table->null_row=0;
4613
 
 
4614
 
  return false;
 
4387
  return(false);
4615
4388
}
4616
4389
 
4617
4390
/**
4655
4428
    This function can be called only after the execution plan
4656
4429
    has been chosen.
4657
4430
*/
4658
 
static void make_outerjoin_info(Join *join)
 
4431
static void make_outerjoin_info(JOIN *join)
4659
4432
{
4660
4433
  for (uint32_t i=join->const_tables ; i < join->tables ; i++)
4661
4434
  {
4662
4435
    JoinTable *tab=join->join_tab+i;
4663
4436
    Table *table=tab->table;
4664
4437
    TableList *tbl= table->pos_in_table_list;
4665
 
    TableList *embedding= tbl->getEmbedding();
 
4438
    TableList *embedding= tbl->embedding;
4666
4439
 
4667
4440
    if (tbl->outer_join)
4668
4441
    {
4675
4448
      tab->on_expr_ref= &tbl->on_expr;
4676
4449
      tab->cond_equal= tbl->cond_equal;
4677
4450
      if (embedding)
4678
 
        tab->first_upper= embedding->getNestedJoin()->first_nested;
 
4451
        tab->first_upper= embedding->nested_join->first_nested;
4679
4452
    }
4680
 
    for ( ; embedding ; embedding= embedding->getEmbedding())
 
4453
    for ( ; embedding ; embedding= embedding->embedding)
4681
4454
    {
4682
4455
      /* Ignore sj-nests: */
4683
4456
      if (!embedding->on_expr)
4684
4457
        continue;
4685
 
      NestedJoin *nested_join= embedding->getNestedJoin();
 
4458
      nested_join_st *nested_join= embedding->nested_join;
4686
4459
      if (!nested_join->counter_)
4687
4460
      {
4688
4461
        /*
4692
4465
        nested_join->first_nested= tab;
4693
4466
        tab->on_expr_ref= &embedding->on_expr;
4694
4467
        tab->cond_equal= tbl->cond_equal;
4695
 
        if (embedding->getEmbedding())
4696
 
          tab->first_upper= embedding->getEmbedding()->getNestedJoin()->first_nested;
 
4468
        if (embedding->embedding)
 
4469
          tab->first_upper= embedding->embedding->nested_join->first_nested;
4697
4470
      }
4698
4471
      if (!tab->first_inner)
4699
4472
        tab->first_inner= nested_join->first_nested;
4706
4479
  return;
4707
4480
}
4708
4481
 
4709
 
static bool make_join_select(Join *join,
 
4482
static bool make_join_select(JOIN *join,
4710
4483
                             optimizer::SqlSelect *select,
4711
4484
                             COND *cond)
4712
4485
{
4721
4494
      if (join->tables > 1)
4722
4495
        cond->update_used_tables();             // Tablenr may have changed
4723
4496
      if (join->const_tables == join->tables &&
4724
 
          session->getLex()->current_select->master_unit() ==
4725
 
          &session->getLex()->unit)             // not upper level SELECT
 
4497
          session->lex->current_select->master_unit() ==
 
4498
          &session->lex->unit)          // not upper level SELECT
4726
4499
        join->const_table_map|=RAND_TABLE_BIT;
4727
4500
      {                                         // Check const tables
4728
4501
        COND *const_cond=
4791
4564
        tab->ref.key= -1;
4792
4565
        tab->ref.key_parts= 0;          // Don't use ref key.
4793
4566
        cur_pos= join->getPosFromOptimalPlan(i);
4794
 
        cur_pos.setFanout(tab->quick->records);
 
4567
        cur_pos.setFanout(rows2double(tab->quick->records));
4795
4568
        /*
4796
4569
           We will use join cache here : prevent sorting of the first
4797
4570
           table only and sort at the end.
4800
4573
          join->full_join= 1;
4801
4574
      }
4802
4575
 
4803
 
      if (join->full_join and not session->getLex()->current_select->is_cross and not cond)
4804
 
      {
4805
 
        my_error(ER_CARTESIAN_JOIN_ATTEMPTED, MYF(0));
4806
 
        return 1;
4807
 
      }
4808
 
 
4809
4576
      tmp= NULL;
4810
4577
      if (cond)
4811
4578
        tmp= make_cond_for_table(cond,used_tables,current_map, 0);
4836
4603
          tab->type == AM_EQ_REF)
4837
4604
      {
4838
4605
        optimizer::SqlSelect *sel= tab->select= ((optimizer::SqlSelect*)
4839
 
            session->getMemRoot()->duplicate((unsigned char*) select,
 
4606
            session->memdup((unsigned char*) select,
4840
4607
              sizeof(*select)));
4841
4608
        if (! sel)
4842
4609
          return 1;                     // End of memory
4974
4741
                                         current_map, 0)))
4975
4742
            {
4976
4743
              tab->cache.select= (optimizer::SqlSelect*)
4977
 
                session->getMemRoot()->duplicate((unsigned char*) sel, sizeof(optimizer::SqlSelect));
 
4744
                session->memdup((unsigned char*) sel, sizeof(optimizer::SqlSelect));
4978
4745
              tab->cache.select->cond= tmp;
4979
4746
              tab->cache.select->read_tables= join->const_table_map;
4980
4747
            }
5090
4857
    false - OK
5091
4858
    true  - Out of memory
5092
4859
*/
5093
 
static bool make_join_readinfo(Join *join)
 
4860
static bool make_join_readinfo(JOIN *join)
5094
4861
{
5095
4862
  bool sorted= true;
5096
4863
 
5110
4877
 
5111
4878
    if (tab->insideout_match_tab)
5112
4879
    {
5113
 
      if (! (tab->insideout_buf= (unsigned char*) join->session->getMemRoot()->allocate(tab->table->key_info
 
4880
      if (! (tab->insideout_buf= (unsigned char*) join->session->alloc(tab->table->key_info
5114
4881
                                                                       [tab->index].
5115
4882
                                                                       key_length)))
5116
4883
        return true;
5138
4905
}
5139
4906
 
5140
4907
/** Update the dependency map for the tables. */
5141
 
static void update_depend_map(Join *join)
 
4908
static void update_depend_map(JOIN *join)
5142
4909
{
5143
4910
  JoinTable *join_tab=join->join_tab, *end=join_tab+join->tables;
5144
4911
 
5161
4928
}
5162
4929
 
5163
4930
/** Update the dependency map for the sort order. */
5164
 
static void update_depend_map(Join *join, Order *order)
 
4931
static void update_depend_map(JOIN *join, order_st *order)
5165
4932
{
5166
4933
  for (; order ; order=order->next)
5167
4934
  {
5199
4966
  @return
5200
4967
    Returns new sort order
5201
4968
*/
5202
 
static Order *remove_constants(Join *join,Order *first_order, COND *cond, bool change_list, bool *simple_order)
 
4969
static order_st *remove_constants(JOIN *join,order_st *first_order, COND *cond, bool change_list, bool *simple_order)
5203
4970
{
5204
4971
  if (join->tables == join->const_tables)
5205
4972
    return change_list ? 0 : first_order;               // No need to sort
5206
4973
 
5207
 
  Order *order,**prev_ptr;
 
4974
  order_st *order,**prev_ptr;
5208
4975
  table_map first_table= join->join_tab[join->const_tables].table->map;
5209
4976
  table_map not_const_tables= ~join->const_table_map;
5210
4977
  table_map ref;
5259
5026
  return(first_order);
5260
5027
}
5261
5028
 
5262
 
static int return_zero_rows(Join *join,
 
5029
static int return_zero_rows(JOIN *join,
5263
5030
                            select_result *result,
5264
5031
                            TableList *tables,
5265
5032
                                        List<Item> &fields,
5292
5059
  {
5293
5060
    if (send_row)
5294
5061
    {
5295
 
      List<Item>::iterator it(fields.begin());
 
5062
      List_iterator_fast<Item> it(fields);
5296
5063
      Item *item;
5297
5064
      while ((item= it++))
5298
5065
        item->no_rows_in_result();
5425
5192
    - The new condition, if success
5426
5193
    - 0, otherwise
5427
5194
*/
5428
 
static COND *simplify_joins(Join *join, List<TableList> *join_list, COND *conds, bool top)
 
5195
static COND *simplify_joins(JOIN *join, List<TableList> *join_list, COND *conds, bool top)
5429
5196
{
5430
5197
  TableList *table;
5431
 
  NestedJoin *nested_join;
 
5198
  nested_join_st *nested_join;
5432
5199
  TableList *prev_table= 0;
5433
 
  List<TableList>::iterator li(join_list->begin());
 
5200
  List_iterator<TableList> li(*join_list);
5434
5201
 
5435
5202
  /*
5436
5203
    Try to simplify join operations from join_list.
5441
5208
    table_map used_tables;
5442
5209
    table_map not_null_tables= (table_map) 0;
5443
5210
 
5444
 
    if ((nested_join= table->getNestedJoin()))
 
5211
    if ((nested_join= table->nested_join))
5445
5212
    {
5446
5213
      /*
5447
5214
         If the element of join_list is a nested join apply
5483
5250
        not_null_tables= conds->not_null_tables();
5484
5251
    }
5485
5252
 
5486
 
    if (table->getEmbedding())
 
5253
    if (table->embedding)
5487
5254
    {
5488
 
      table->getEmbedding()->getNestedJoin()->used_tables|= used_tables;
5489
 
      table->getEmbedding()->getNestedJoin()->not_null_tables|= not_null_tables;
 
5255
      table->embedding->nested_join->used_tables|= used_tables;
 
5256
      table->embedding->nested_join->not_null_tables|= not_null_tables;
5490
5257
    }
5491
5258
 
5492
5259
    if (!table->outer_join || (used_tables & not_null_tables))
5522
5289
    */
5523
5290
    if (table->on_expr)
5524
5291
    {
5525
 
      table->setDepTables(table->getDepTables() | table->on_expr->used_tables());
5526
 
      if (table->getEmbedding())
 
5292
      table->dep_tables|= table->on_expr->used_tables();
 
5293
      if (table->embedding)
5527
5294
      {
5528
 
        table->setDepTables(table->getDepTables() & ~table->getEmbedding()->getNestedJoin()->used_tables);
 
5295
        table->dep_tables&= ~table->embedding->nested_join->used_tables;
5529
5296
        /*
5530
5297
           Embedding table depends on tables used
5531
5298
           in embedded on expressions.
5532
5299
        */
5533
 
        table->getEmbedding()->setOnExprDepTables(table->getEmbedding()->getOnExprDepTables() & table->on_expr->used_tables());
 
5300
        table->embedding->on_expr_dep_tables|= table->on_expr->used_tables();
5534
5301
      }
5535
5302
      else
5536
 
        table->setDepTables(table->getDepTables() & ~table->table->map);
 
5303
        table->dep_tables&= ~table->table->map;
5537
5304
    }
5538
5305
 
5539
5306
    if (prev_table)
5540
5307
    {
5541
 
      //If this is straight join, set prev table to be dependent on all tables
5542
 
      //from this nested join, so that correct join order is selected.
5543
 
      if ((test(join->select_options & SELECT_STRAIGHT_JOIN)) ||
5544
 
          prev_table->straight)
5545
 
        prev_table->setDepTables(prev_table->getDepTables() | used_tables);
 
5308
      /* The order of tables is reverse: prev_table follows table */
 
5309
      if (prev_table->straight)
 
5310
        prev_table->dep_tables|= used_tables;
5546
5311
      if (prev_table->on_expr)
5547
5312
      {
5548
 
        prev_table->setDepTables(prev_table->getDepTables() | table->getOnExprDepTables());
5549
 
        table_map prev_used_tables= prev_table->getNestedJoin() ?
5550
 
                                    prev_table->getNestedJoin()->used_tables :
 
5313
        prev_table->dep_tables|= table->on_expr_dep_tables;
 
5314
        table_map prev_used_tables= prev_table->nested_join ?
 
5315
                                    prev_table->nested_join->used_tables :
5551
5316
                                    prev_table->table->map;
5552
5317
        /*
5553
5318
          If on expression contains only references to inner tables
5556
5321
          for them. Yet this is really a rare case.
5557
5322
              */
5558
5323
        if (!(prev_table->on_expr->used_tables() & ~prev_used_tables))
5559
 
          prev_table->setDepTables(prev_table->getDepTables() | used_tables);
 
5324
          prev_table->dep_tables|= used_tables;
5560
5325
      }
5561
5326
    }
5562
5327
    prev_table= table;
5566
5331
    Flatten nested joins that can be flattened.
5567
5332
    no ON expression and not a semi-join => can be flattened.
5568
5333
  */
5569
 
  li= join_list->begin();
 
5334
  li.rewind();
5570
5335
  while ((table= li++))
5571
5336
  {
5572
 
    nested_join= table->getNestedJoin();
 
5337
    nested_join= table->nested_join;
5573
5338
    if (nested_join && !table->on_expr)
5574
5339
    {
5575
5340
      TableList *tbl;
5576
 
      List<TableList>::iterator it(nested_join->join_list.begin());
 
5341
      List_iterator<TableList> it(nested_join->join_list);
5577
5342
      while ((tbl= it++))
5578
5343
      {
5579
 
        tbl->setEmbedding(table->getEmbedding());
5580
 
        tbl->setJoinList(table->getJoinList());
 
5344
        tbl->embedding= table->embedding;
 
5345
        tbl->join_list= table->join_list;
5581
5346
      }
5582
5347
      li.replace(nested_join->join_list);
5583
5348
    }
5585
5350
  return(conds);
5586
5351
}
5587
5352
 
5588
 
static int remove_duplicates(Join *join, Table *entry,List<Item> &fields, Item *having)
 
5353
static int remove_duplicates(JOIN *join, Table *entry,List<Item> &fields, Item *having)
5589
5354
{
5590
5355
  int error;
5591
5356
  uint32_t reclength,offset;
5596
5361
 
5597
5362
  /* Calculate how many saved fields there is in list */
5598
5363
  field_count=0;
5599
 
  List<Item>::iterator it(fields.begin());
 
5364
  List_iterator<Item> it(fields);
5600
5365
  Item *item;
5601
5366
  while ((item=it++))
5602
5367
  {
5609
5374
    join->unit->select_limit_cnt= 1;            // Only send first row
5610
5375
    return(0);
5611
5376
  }
5612
 
  Field **first_field=entry->getFields() + entry->getShare()->sizeFields() - field_count;
 
5377
  Field **first_field=entry->field+entry->s->fields - field_count;
5613
5378
  offset= (field_count ?
5614
 
           entry->getField(entry->getShare()->sizeFields() - field_count)->offset(entry->getInsertRecord()) : 0);
5615
 
  reclength= entry->getShare()->getRecordLength() - offset;
 
5379
           entry->field[entry->s->fields - field_count]->
 
5380
           offset(entry->record[0]) : 0);
 
5381
  reclength= entry->s->reclength-offset;
5616
5382
 
5617
5383
  entry->free_io_cache();                               // Safety
5618
5384
  entry->cursor->info(HA_STATUS_VARIABLE);
5619
 
  if (entry->getShare()->db_type() == heap_engine ||
5620
 
      (!entry->getShare()->blob_fields &&
 
5385
  if (entry->s->db_type() == heap_engine ||
 
5386
      (!entry->s->blob_fields &&
5621
5387
       ((ALIGN_SIZE(reclength) + HASH_OVERHEAD) * entry->cursor->stats.records <
5622
 
        session->variables.sortbuff_size)))
5623
 
  {
 
5388
        session->variables.sortbuff_size)))
5624
5389
    error= remove_dup_with_hash_index(join->session, entry,
5625
 
                                      field_count, first_field,
5626
 
                                      reclength, having);
5627
 
  }
 
5390
                                     field_count, first_field,
 
5391
                                     reclength, having);
5628
5392
  else
5629
 
  {
5630
 
    error= remove_dup_with_compare(join->session, entry, first_field, offset, having);
5631
 
  }
 
5393
    error= remove_dup_with_compare(join->session, entry, first_field, offset,
 
5394
                                  having);
5632
5395
 
5633
5396
  free_blobs(first_field);
5634
 
 
5635
5397
  return(error);
5636
5398
}
5637
5399
 
5645
5407
                               List<Item> &fields,
5646
5408
                               List<Item> &all_fields,
5647
5409
                               COND **conds,
5648
 
                               Order *order,
5649
 
                               Order *group,
 
5410
                               order_st *order,
 
5411
                               order_st *group,
5650
5412
                               bool *hidden_group_fields)
5651
5413
{
5652
5414
  int res;
5653
 
  nesting_map save_allow_sum_func=session->getLex()->allow_sum_func ;
 
5415
  nesting_map save_allow_sum_func=session->lex->allow_sum_func ;
5654
5416
 
5655
 
  session->getLex()->allow_sum_func&= ~(1 << session->getLex()->current_select->nest_level);
 
5417
  session->lex->allow_sum_func&= ~(1 << session->lex->current_select->nest_level);
5656
5418
  res= session->setup_conds(tables, conds);
5657
5419
 
5658
 
  session->getLex()->allow_sum_func|= 1 << session->getLex()->current_select->nest_level;
 
5420
  session->lex->allow_sum_func|= 1 << session->lex->current_select->nest_level;
5659
5421
  res= res || setup_order(session, ref_pointer_array, tables, fields, all_fields,
5660
5422
                          order);
5661
 
  session->getLex()->allow_sum_func&= ~(1 << session->getLex()->current_select->nest_level);
 
5423
  session->lex->allow_sum_func&= ~(1 << session->lex->current_select->nest_level);
5662
5424
  res= res || setup_group(session, ref_pointer_array, tables, fields, all_fields,
5663
5425
                          group, hidden_group_fields);
5664
 
  session->getLex()->allow_sum_func= save_allow_sum_func;
 
5426
  session->lex->allow_sum_func= save_allow_sum_func;
5665
5427
  return(res);
5666
5428
}
5667
5429
 
5673
5435
  @retval
5674
5436
    1   Fatal error
5675
5437
*/
5676
 
static bool make_join_statistics(Join *join, TableList *tables, COND *conds, DYNAMIC_ARRAY *keyuse_array)
 
5438
static bool make_join_statistics(JOIN *join, TableList *tables, COND *conds, DYNAMIC_ARRAY *keyuse_array)
5677
5439
{
5678
5440
  int error;
5679
5441
  Table *table;
5701
5463
 
5702
5464
  table_count= join->tables;
5703
5465
  stat= (JoinTable*) join->session->calloc(sizeof(JoinTable)*table_count);
5704
 
  stat_ref= (JoinTable**) join->session->getMemRoot()->allocate(sizeof(JoinTable*)*MAX_TABLES);
5705
 
  table_vector= (Table**) join->session->getMemRoot()->allocate(sizeof(Table*)*(table_count*2));
 
5466
  stat_ref= (JoinTable**) join->session->alloc(sizeof(JoinTable*)*MAX_TABLES);
 
5467
  table_vector= (Table**) join->session->alloc(sizeof(Table*)*(table_count*2));
5706
5468
  if (! stat || ! stat_ref || ! table_vector)
5707
5469
    return 1;
5708
5470
 
5716
5478
       tables;
5717
5479
       s++, tables= tables->next_leaf, i++)
5718
5480
  {
5719
 
    TableList *embedding= tables->getEmbedding();
 
5481
    TableList *embedding= tables->embedding;
5720
5482
    stat_vector[i]=s;
5721
5483
    s->keys.reset();
5722
5484
    s->const_keys.reset();
5724
5486
    s->needed_reg.reset();
5725
5487
    table_vector[i]=s->table=table=tables->table;
5726
5488
    table->pos_in_table_list= tables;
5727
 
    assert(table->cursor);
5728
5489
    error= table->cursor->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);
5729
5490
    if (error)
5730
5491
    {
5735
5496
    table->reginfo.join_tab=s;
5736
5497
    table->reginfo.not_exists_optimize=0;
5737
5498
    memset(table->const_key_parts, 0,
5738
 
           sizeof(key_part_map)*table->getShare()->sizeKeys());
 
5499
           sizeof(key_part_map)*table->s->keys);
5739
5500
    all_table_map|= table->map;
5740
5501
    s->join=join;
5741
5502
    s->info=0;                                  // For describe
5742
5503
 
5743
 
    s->dependent= tables->getDepTables();
 
5504
    s->dependent= tables->dep_tables;
5744
5505
    s->key_dependent= 0;
5745
5506
    table->quick_condition_rows= table->cursor->stats.records;
5746
5507
 
5756
5517
      }
5757
5518
      outer_join|= table->map;
5758
5519
      s->embedding_map.reset();
5759
 
      for (;embedding; embedding= embedding->getEmbedding())
5760
 
        s->embedding_map|= embedding->getNestedJoin()->nj_map;
 
5520
      for (;embedding; embedding= embedding->embedding)
 
5521
        s->embedding_map|= embedding->nested_join->nj_map;
5761
5522
      continue;
5762
5523
    }
5763
 
    if (embedding && !(false && ! embedding->getEmbedding()))
 
5524
    if (embedding && !(false && ! embedding->embedding))
5764
5525
    {
5765
5526
      /* s belongs to a nested join, maybe to several embedded joins */
5766
5527
      s->embedding_map.reset();
5767
5528
      do
5768
5529
      {
5769
 
        NestedJoin *nested_join= embedding->getNestedJoin();
 
5530
        nested_join_st *nested_join= embedding->nested_join;
5770
5531
        s->embedding_map|= nested_join->nj_map;
5771
 
        s->dependent|= embedding->getDepTables();
5772
 
        embedding= embedding->getEmbedding();
 
5532
        s->dependent|= embedding->dep_tables;
 
5533
        embedding= embedding->embedding;
5773
5534
        outer_join|= nested_join->used_tables;
5774
5535
      }
5775
5536
      while (embedding);
5795
5556
       As we use bitmaps to represent the relation the complexity
5796
5557
       of the algorithm is O((number of tables)^2).
5797
5558
    */
5798
 
    for (i= 0; i < table_count; i++)
 
5559
    for (i= 0, s= stat ; i < table_count ; i++, s++)
5799
5560
    {
5800
 
      uint32_t j;
5801
 
      table= stat[i].table;
5802
 
 
5803
 
      if (!table->reginfo.join_tab->dependent)
5804
 
        continue;
5805
 
 
5806
 
      for (j= 0, s= stat; j < table_count; j++, s++)
 
5561
      for (uint32_t j= 0 ; j < table_count ; j++)
5807
5562
      {
 
5563
        table= stat[j].table;
5808
5564
        if (s->dependent & table->map)
5809
 
        {
5810
 
          table_map was_dependent= s->dependent;
5811
5565
          s->dependent |= table->reginfo.join_tab->dependent;
5812
 
          if (i > j && s->dependent != was_dependent)
5813
 
          {
5814
 
            i= j= 1;
5815
 
            break;
5816
 
          }
5817
 
        }
5818
5566
      }
 
5567
      if (s->dependent)
 
5568
        s->table->maybe_null= 1;
5819
5569
    }
5820
5570
    /* Catch illegal cross references for outer joins */
5821
5571
    for (i= 0, s= stat ; i < table_count ; i++, s++)
5826
5576
        my_message(ER_WRONG_OUTER_JOIN, ER(ER_WRONG_OUTER_JOIN), MYF(0));
5827
5577
        return 1;
5828
5578
      }
5829
 
      if (outer_join & s->table->map)
5830
 
        s->table->maybe_null= 1;
5831
 
 
5832
5579
      s->key_dependent= s->dependent;
5833
5580
    }
5834
5581
  }
5850
5597
    s= p_pos->getJoinTable();
5851
5598
    s->type= AM_SYSTEM;
5852
5599
    join->const_table_map|=s->table->map;
5853
 
    if ((tmp= s->joinReadConstTable(p_pos)))
 
5600
    if ((tmp= join_read_const_table(s, p_pos)))
5854
5601
    {
5855
5602
      if (tmp > 0)
5856
5603
        return 1;                       // Fatal error
5917
5664
          continue;
5918
5665
        if (table->cursor->stats.records <= 1L &&
5919
5666
            (table->cursor->getEngine()->check_flag(HTON_BIT_STATS_RECORDS_IS_EXACT)) &&
5920
 
                  !table->pos_in_table_list->getEmbedding())
 
5667
                  !table->pos_in_table_list->embedding)
5921
5668
        {                                       // system table
5922
5669
          int tmp= 0;
5923
5670
          s->type= AM_SYSTEM;
5924
5671
          join->const_table_map|=table->map;
5925
5672
          set_position(join, const_count++, s, (optimizer::KeyUse*) 0);
5926
5673
          partial_pos= join->getSpecificPosInPartialPlan(const_count - 1);
5927
 
          if ((tmp= s->joinReadConstTable(partial_pos)))
 
5674
          if ((tmp= join_read_const_table(s, partial_pos)))
5928
5675
          {
5929
5676
            if (tmp > 0)
5930
5677
              return 1;                 // Fatal error
5962
5709
          } while (keyuse->getTable() == table && keyuse->getKey() == key);
5963
5710
 
5964
5711
          if (is_keymap_prefix(eq_part, table->key_info[key].key_parts) &&
5965
 
              ! table->pos_in_table_list->getEmbedding())
 
5712
              ! table->pos_in_table_list->embedding)
5966
5713
          {
5967
5714
            if ((table->key_info[key].flags & (HA_NOSAME)) == HA_NOSAME)
5968
5715
            {
5976
5723
                if (create_ref_for_key(join, s, start_keyuse, found_const_table_map))
5977
5724
                  return 1;
5978
5725
                partial_pos= join->getSpecificPosInPartialPlan(const_count - 1);
5979
 
                if ((tmp=s->joinReadConstTable(partial_pos)))
 
5726
                if ((tmp=join_read_const_table(s, partial_pos)))
5980
5727
                {
5981
5728
                  if (tmp > 0)
5982
5729
                    return 1;                   // Fatal error
6006
5753
    while (iter != sargables.end())
6007
5754
    {
6008
5755
      Field *field= (*iter).getField();
6009
 
      JoinTable *join_tab= field->getTable()->reginfo.join_tab;
 
5756
      JoinTable *join_tab= field->table->reginfo.join_tab;
6010
5757
      key_map possible_keys= field->key_start;
6011
 
      possible_keys&= field->getTable()->keys_in_use_for_query;
 
5758
      possible_keys&= field->table->keys_in_use_for_query;
6012
5759
      bool is_const= true;
6013
5760
      for (uint32_t j= 0; j < (*iter).getNumValues(); j++)
6014
5761
        is_const&= (*iter).isConstItem(j);
6049
5796
    add_group_and_distinct_keys(join, s);
6050
5797
 
6051
5798
    if (s->const_keys.any() &&
6052
 
        !s->table->pos_in_table_list->getEmbedding())
 
5799
        !s->table->pos_in_table_list->embedding)
6053
5800
    {
6054
5801
      ha_rows records;
6055
5802
      optimizer::SqlSelect *select= NULL;
6060
5807
      s->quick=select->quick;
6061
5808
      s->needed_reg=select->needed_reg;
6062
5809
      select->quick=0;
6063
 
 
6064
5810
      if (records == 0 && s->table->reginfo.impossible_range)
6065
5811
      {
6066
5812
        /*
6100
5846
  if (join->const_tables != join->tables)
6101
5847
  {
6102
5848
    optimize_keyuse(join, keyuse_array);
6103
 
    // @note c_str() is not likely to be valid here if dtrace expects it to
6104
 
    // exist for any period of time.
6105
 
    DRIZZLE_QUERY_OPT_CHOOSE_PLAN_START(join->session->getQueryString()->c_str(), join->session->thread_id);
 
5849
    DRIZZLE_QUERY_OPT_CHOOSE_PLAN_START(join->session->query.c_str(), join->session->thread_id);
6106
5850
    bool res= choose_plan(join, all_table_map & ~join->const_table_map);
6107
5851
    DRIZZLE_QUERY_OPT_CHOOSE_PLAN_DONE(res ? 1 : 0);
6108
5852
    if (res)
6114
5858
    join->best_read= 1.0;
6115
5859
  }
6116
5860
  /* Generate an execution plan from the found optimal join order. */
6117
 
  return (join->session->getKilled() || get_best_combination(join));
 
5861
  return (join->session->killed || get_best_combination(join));
6118
5862
}
6119
5863
 
6120
5864
/**
6138
5882
*/
6139
5883
static uint32_t build_bitmap_for_nested_joins(List<TableList> *join_list, uint32_t first_unused)
6140
5884
{
6141
 
  List<TableList>::iterator li(join_list->begin());
 
5885
  List_iterator<TableList> li(*join_list);
6142
5886
  TableList *table;
6143
5887
  while ((table= li++))
6144
5888
  {
6145
 
    NestedJoin *nested_join;
6146
 
    if ((nested_join= table->getNestedJoin()))
 
5889
    nested_join_st *nested_join;
 
5890
    if ((nested_join= table->nested_join))
6147
5891
    {
6148
5892
      /*
6149
5893
        It is guaranteed by simplify_joins() function that a nested join
6174
5918
  Return table number if there is only one table in sort order
6175
5919
  and group and order is compatible, else return 0.
6176
5920
*/
6177
 
static Table *get_sort_by_table(Order *a, Order *b,TableList *tables)
 
5921
static Table *get_sort_by_table(order_st *a,order_st *b,TableList *tables)
6178
5922
{
6179
5923
  table_map map= (table_map) 0;
6180
5924
 
6199
5943
}
6200
5944
 
6201
5945
/**
6202
 
  Set NestedJoin::counter=0 in all nested joins in passed list.
 
5946
  Set nested_join_st::counter=0 in all nested joins in passed list.
6203
5947
 
6204
 
    Recursively set NestedJoin::counter=0 for all nested joins contained in
 
5948
    Recursively set nested_join_st::counter=0 for all nested joins contained in
6205
5949
    the passed join_list.
6206
5950
 
6207
5951
  @param join_list  List of nested joins to process. It may also contain base
6209
5953
*/
6210
5954
static void reset_nj_counters(List<TableList> *join_list)
6211
5955
{
6212
 
  List<TableList>::iterator li(join_list->begin());
 
5956
  List_iterator<TableList> li(*join_list);
6213
5957
  TableList *table;
6214
5958
  while ((table= li++))
6215
5959
  {
6216
 
    NestedJoin *nested_join;
6217
 
    if ((nested_join= table->getNestedJoin()))
 
5960
    nested_join_st *nested_join;
 
5961
    if ((nested_join= table->nested_join))
6218
5962
    {
6219
5963
      nested_join->counter_= 0;
6220
5964
      reset_nj_counters(&nested_join->join_list);
6229
5973
  If first parts has different direction, change it to second part
6230
5974
  (group is sorted like order)
6231
5975
*/
6232
 
static bool test_if_subpart(Order *a, Order *b)
 
5976
static bool test_if_subpart(order_st *a,order_st *b)
6233
5977
{
6234
5978
  for (; a && b; a=a->next,b=b->next)
6235
5979
  {
6244
5988
/**
6245
5989
  Nested joins perspective: Remove the last table from the join order.
6246
5990
 
6247
 
  The algorithm is the reciprocal of check_interleaving_with_nj(), hence
6248
 
  parent join nest nodes are updated only when the last table in its child
6249
 
  node is removed. The ASCII graphic below will clarify.
6250
 
 
6251
 
  %A table nesting such as <tt> t1 x [ ( t2 x t3 ) x ( t4 x t5 ) ] </tt>is
6252
 
  represented by the below join nest tree.
6253
 
 
6254
 
  @verbatim
6255
 
                     NJ1
6256
 
                  _/ /  \
6257
 
                _/  /    NJ2
6258
 
              _/   /     / \ 
6259
 
             /    /     /   \
6260
 
   t1 x [ (t2 x t3) x (t4 x t5) ]
6261
 
  @endverbatim
6262
 
 
6263
 
  At the point in time when check_interleaving_with_nj() adds the table t5 to
6264
 
  the query execution plan, QEP, it also directs the node named NJ2 to mark
6265
 
  the table as covered. NJ2 does so by incrementing its @c counter
6266
 
  member. Since all of NJ2's tables are now covered by the QEP, the algorithm
6267
 
  proceeds up the tree to NJ1, incrementing its counter as well. All join
6268
 
  nests are now completely covered by the QEP.
6269
 
 
6270
 
  restore_prev_nj_state() does the above in reverse. As seen above, the node
6271
 
  NJ1 contains the nodes t2, t3, and NJ2. Its counter being equal to 3 means
6272
 
  that the plan covers t2, t3, and NJ2, @e and that the sub-plan (t4 x t5)
6273
 
  completely covers NJ2. The removal of t5 from the partial plan will first
6274
 
  decrement NJ2's counter to 1. It will then detect that NJ2 went from being
6275
 
  completely to partially covered, and hence the algorithm must continue
6276
 
  upwards to NJ1 and decrement its counter to 2. %A subsequent removal of t4
6277
 
  will however not influence NJ1 since it did not un-cover the last table in
6278
 
  NJ2.
6279
 
 
6280
 
  SYNOPSIS
6281
 
    restore_prev_nj_state()
6282
 
      last  join table to remove, it is assumed to be the last in current 
6283
 
            partial join order.
6284
 
     
6285
 
  DESCRIPTION
6286
 
 
6287
5991
    Remove the last table from the partial join order and update the nested
6288
 
    joins counters and join->cur_embedding_map. It is ok to call this 
6289
 
    function for the first table in join order (for which 
 
5992
    joins counters and join->cur_embedding_map. It is ok to call this
 
5993
    function for the first table in join order (for which
6290
5994
    check_interleaving_with_nj has not been called)
6291
5995
 
6292
5996
  @param last  join table to remove, it is assumed to be the last in current
6293
5997
               partial join order.
6294
5998
*/
6295
 
 
6296
5999
static void restore_prev_nj_state(JoinTable *last)
6297
6000
{
6298
 
  TableList *last_emb= last->table->pos_in_table_list->getEmbedding();
6299
 
  Join *join= last->join;
6300
 
  for (;last_emb != NULL; last_emb= last_emb->getEmbedding())
 
6001
  TableList *last_emb= last->table->pos_in_table_list->embedding;
 
6002
  JOIN *join= last->join;
 
6003
  while (last_emb)
6301
6004
  {
6302
 
    NestedJoin *nest= last_emb->getNestedJoin();
6303
 
    
6304
 
    bool was_fully_covered= nest->is_fully_covered();
6305
 
    
6306
 
    if (--nest->counter_ == 0)
6307
 
      join->cur_embedding_map&= ~nest->nj_map;
6308
 
    
6309
 
    if (!was_fully_covered)
6310
 
      break;
6311
 
    
6312
 
    join->cur_embedding_map|= nest->nj_map;
 
6005
    if (last_emb->on_expr)
 
6006
    {
 
6007
      if (!(--last_emb->nested_join->counter_))
 
6008
        join->cur_embedding_map&= ~last_emb->nested_join->nj_map;
 
6009
      else if (last_emb->nested_join->join_list.elements-1 ==
 
6010
               last_emb->nested_join->counter_)
 
6011
        join->cur_embedding_map|= last_emb->nested_join->nj_map;
 
6012
      else
 
6013
        break;
 
6014
    }
 
6015
    last_emb= last_emb->embedding;
6313
6016
  }
6314
6017
}
6315
6018
 
 
6019
 
6316
6020
/**
6317
6021
  Create a condition for a const reference and add this to the
6318
6022
  currenct select for the table.
6330
6034
 
6331
6035
  for (uint32_t i=0 ; i < join_tab->ref.key_parts ; i++)
6332
6036
  {
6333
 
    Field *field=table->getField(table->key_info[join_tab->ref.key].key_part[i].fieldnr - 1);
 
6037
    Field *field=table->field[table->key_info[join_tab->ref.key].key_part[i].
 
6038
                              fieldnr-1];
6334
6039
    Item *value=join_tab->ref.items[i];
6335
6040
    cond->add(new Item_func_equal(new Item_field(field), value));
6336
6041
  }