~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/join.cc

  • Committer: devananda
  • Date: 2009-07-01 17:38:47 UTC
  • mto: (1093.1.7 captain)
  • mto: This revision was merged to the branch mainline in revision 1095.
  • Revision ID: devananda.vdv@gmail.com-20090701173847-3n3mbtessg5ff35e
refactored function/benchmark into plugin/benchmark

Show diffs side-by-side

added added

removed removed

Lines of Context:
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"
31
 
 
32
 
#include <float.h>
33
 
#include <math.h>
34
 
 
 
30
#include "drizzled/server_includes.h"
 
31
#include "drizzled/sj_tmp_table.h"
 
32
#include "drizzled/table_map_iterator.h"
35
33
#include "drizzled/item/cache.h"
36
34
#include "drizzled/item/cmpfunc.h"
37
35
#include "drizzled/item/copy_string.h"
45
43
#include "drizzled/join_cache.h"
46
44
#include "drizzled/show.h"
47
45
#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
 
 
62
 
#include <algorithm>
63
 
 
64
 
using namespace std;
65
 
 
66
 
namespace drizzled
67
 
{
68
 
 
69
 
extern plugin::StorageEngine *heap_engine;
70
 
extern std::bitset<12> test_flags;
 
46
#include "mysys/my_bit.h"
71
47
 
72
48
/** Declarations of static functions used in this source file. */
73
 
static bool make_group_fields(Join *main_join, Join *curr_join);
74
 
static void calc_group_buffer(Join *join, Order *group);
75
 
static bool alloc_group_fields(Join *join, Order *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,
80
 
                         uint32_t index,
81
 
                         JoinTable *table,
82
 
                         optimizer::KeyUse *key);
83
 
static bool choose_plan(Join *join,table_map join_tables);
84
 
static void best_access_path(Join *join, JoinTable *s,
 
49
static bool make_group_fields(JOIN *main_join, JOIN *curr_join);
 
50
static void calc_group_buffer(JOIN *join,order_st *group);
 
51
static bool alloc_group_fields(JOIN *join,order_st *group);
 
52
/*
 
53
  TODO: 'find_best' is here only temporarily until 'greedy_search' is
 
54
  tested and approved.
 
55
*/
 
56
static bool find_best(JOIN *join,table_map rest_tables,uint32_t index, double record_count,double read_time);
 
57
static uint32_t cache_record_length(JOIN *join, uint32_t index);
 
58
static double prev_record_reads(JOIN *join, uint32_t idx, table_map found_ref);
 
59
static bool get_best_combination(JOIN *join);
 
60
static void set_position(JOIN *join,uint32_t index,JOIN_TAB *table,KEYUSE *key);
 
61
static bool choose_plan(JOIN *join,table_map join_tables);
 
62
static void best_access_path(JOIN *join, JOIN_TAB *s,
85
63
                             Session *session,
86
64
                             table_map remaining_tables,
87
65
                             uint32_t idx,
88
66
                             double record_count,
89
67
                             double read_time);
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,
 
68
static void optimize_straight_join(JOIN *join, table_map join_tables);
 
69
static bool greedy_search(JOIN *join, table_map remaining_tables, uint32_t depth, uint32_t prune_level);
 
70
static bool best_extension_by_limited_search(JOIN *join,
93
71
                                             table_map remaining_tables,
94
72
                                             uint32_t idx,
95
73
                                             double record_count,
96
74
                                             double read_time,
97
75
                                             uint32_t depth,
98
76
                                             uint32_t prune_level);
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 *order);
106
 
static Order *remove_constants(Join *join,Order *first_order,COND *cond, bool change_list, bool *simple_order);
107
 
static int return_zero_rows(Join *join,
 
77
static uint32_t determine_search_depth(JOIN* join);
 
78
static bool make_simple_join(JOIN *join,Table *tmp_table);
 
79
static void make_outerjoin_info(JOIN *join);
 
80
static bool make_join_select(JOIN *join,SQL_SELECT *select,COND *item);
 
81
static bool make_join_readinfo(JOIN *join, uint64_t options, uint32_t no_jbuf_after);
 
82
static void update_depend_map(JOIN *join);
 
83
static void update_depend_map(JOIN *join, order_st *order);
 
84
static order_st *remove_constants(JOIN *join,order_st *first_order,COND *cond, bool change_list, bool *simple_order);
 
85
static int return_zero_rows(JOIN *join,
108
86
                            select_result *res,
109
87
                            TableList *tables,
110
88
                            List<Item> &fields,
112
90
                            uint64_t select_options,
113
91
                            const char *info,
114
92
                            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);
 
93
static COND *simplify_joins(JOIN *join, List<TableList> *join_list, COND *conds, bool top, bool in_sj);
 
94
static int remove_duplicates(JOIN *join,Table *entry,List<Item> &fields, Item *having);
117
95
static int setup_without_group(Session *session, 
118
96
                               Item **ref_pointer_array,
119
97
                               TableList *tables,
121
99
                               List<Item> &fields,
122
100
                               List<Item> &all_fields,
123
101
                               COND **conds,
124
 
                               Order *order,
125
 
                               Order *group,
 
102
                               order_st *order,
 
103
                               order_st *group,
126
104
                               bool *hidden_group_fields);
127
 
static bool make_join_statistics(Join *join, TableList *leaves, COND *conds, DYNAMIC_ARRAY *keyuse);
 
105
static bool make_join_statistics(JOIN *join, TableList *leaves, COND *conds, DYNAMIC_ARRAY *keyuse);
128
106
static uint32_t build_bitmap_for_nested_joins(List<TableList> *join_list, uint32_t first_unused);
129
 
static Table *get_sort_by_table(Order *a, Order *b,TableList *tables);
 
107
static Table *get_sort_by_table(order_st *a,order_st *b,TableList *tables);
130
108
static void reset_nj_counters(List<TableList> *join_list);
131
 
static bool test_if_subpart(Order *a,Order *b);
132
 
static void restore_prev_nj_state(JoinTable *last);
133
 
static bool add_ref_to_table_cond(Session *session, JoinTable *join_tab);
 
109
static bool test_if_subpart(order_st *a,order_st *b);
 
110
static void restore_prev_nj_state(JOIN_TAB *last);
 
111
static uint32_t make_join_orderinfo(JOIN *join);
 
112
static int setup_semijoin_dups_elimination(JOIN *join, uint64_t options, uint32_t no_jbuf_after);
 
113
static void cleanup_sj_tmp_tables(JOIN *join);
 
114
static bool add_ref_to_table_cond(Session *session, JOIN_TAB *join_tab);
 
115
static bool replace_where_subcondition(JOIN *join, Item *old_cond, Item *new_cond, bool fix_fields);
 
116
static int pull_out_semijoin_tables(JOIN *join);
 
117
static int do_sj_dups_weedout(Session *session, SJ_TMP_TABLE *sjtbl);
134
118
static void free_blobs(Field **ptr); /* Rename this method...conflicts with another in global namespace... */
 
119
static bool bitmap_covers(const table_map x, const table_map y);
 
120
static bool sj_table_is_included(JOIN *join, JOIN_TAB *join_tab);
135
121
 
136
122
/**
137
123
  Prepare of whole select (including sub queries in future).
145
131
  @retval
146
132
    0   on success
147
133
*/
148
 
int Join::prepare(Item ***rref_pointer_array,
 
134
int JOIN::prepare(Item ***rref_pointer_array,
149
135
                  TableList *tables_init,
150
136
                  uint32_t wild_num,
151
137
                  COND *conds_init,
152
138
                  uint32_t og_num,
153
 
                  Order *order_init,
154
 
                  Order *group_init,
 
139
                  order_st *order_init,
 
140
                  order_st *group_init,
155
141
                  Item *having_init,
156
142
                  Select_Lex *select_lex_arg,
157
143
                  Select_Lex_Unit *unit_arg)
184
170
      setup_tables_and_check_access(session, &select_lex->context, join_list,
185
171
                                    tables_list, &select_lex->leaf_tables,
186
172
                                    false))
187
 
  {
188
173
      return(-1);
189
 
  }
190
174
 
191
175
  TableList *table_ptr;
192
176
  for (table_ptr= select_lex->leaf_tables;
193
177
       table_ptr;
194
178
       table_ptr= table_ptr->next_leaf)
195
 
  {
196
179
    tables++;
197
 
  }
198
 
 
199
180
 
200
181
  if (setup_wild(session, fields_list, &all_fields, wild_num) ||
201
182
      select_lex->setup_ref_array(session, og_num) ||
205
186
        select_lex->leaf_tables, fields_list,
206
187
        all_fields, &conds, order, group_list,
207
188
        &hidden_group_fields))
208
 
    return(-1);
 
189
    return(-1);       /* purecov: inspected */
209
190
 
210
191
  ref_pointer_array= *rref_pointer_array;
211
192
 
220
201
        having->check_cols(1)));
221
202
    select_lex->having_fix_field= 0;
222
203
    if (having_fix_rc || session->is_error())
223
 
      return(-1);
 
204
      return(-1);       /* purecov: inspected */
224
205
    session->lex->allow_sum_func= save_allow_sum_func;
225
206
  }
226
207
 
233
214
    */
234
215
    if ((subselect= select_lex->master_unit()->item))
235
216
    {
 
217
      bool do_semijoin= !test(session->variables.optimizer_switch &
 
218
                              OPTIMIZER_SWITCH_NO_SEMIJOIN);
236
219
      if (subselect->substype() == Item_subselect::IN_SUBS)
237
220
        in_subs= (Item_in_subselect*)subselect;
238
221
 
239
 
      {
240
 
        bool do_materialize= true;
 
222
      /*
 
223
        Check if we're in subquery that is a candidate for flattening into a
 
224
        semi-join (which is done done in flatten_subqueries()). The
 
225
        requirements are:
 
226
          1. Subquery predicate is an IN/=ANY subq predicate
 
227
          2. Subquery is a single SELECT (not a UNION)
 
228
          3. Subquery does not have GROUP BY or order_st BY
 
229
          4. Subquery does not use aggregate functions or HAVING
 
230
          5. Subquery predicate is at the AND-top-level of ON/WHERE clause
 
231
          6. No execution method was already chosen (by a prepared statement).
 
232
 
 
233
          (*). We are not in a subquery of a single table UPDATE/DELETE that
 
234
               doesn't have a JOIN (TODO: We should handle this at some
 
235
               point by switching to multi-table UPDATE/DELETE)
 
236
 
 
237
          (**). We're not in a confluent table-less subquery, like
 
238
                "SELECT 1".
 
239
      */
 
240
      if (in_subs &&                                                    // 1
 
241
          !select_lex->master_unit()->first_select()->next_select() &&  // 2
 
242
          !select_lex->group_list.elements && !order &&                 // 3
 
243
          !having && !select_lex->with_sum_func &&                      // 4
 
244
          session->session_marker &&                                            // 5
 
245
          select_lex->outer_select()->join &&                           // (*)
 
246
          select_lex->master_unit()->first_select()->leaf_tables &&     // (**)
 
247
          do_semijoin &&
 
248
          in_subs->exec_method == Item_in_subselect::NOT_TRANSFORMED)   // 6
 
249
      {
 
250
        {
 
251
          if (!in_subs->left_expr->fixed &&
 
252
               in_subs->left_expr->fix_fields(session, &in_subs->left_expr))
 
253
          {
 
254
            return(-1);
 
255
          }
 
256
          /*
 
257
            Check that the right part of the subselect contains no more than one
 
258
            column. E.g. in SELECT 1 IN (SELECT * ..) the right part is (SELECT * ...)
 
259
          */
 
260
          if (subselect->substype() == Item_subselect::IN_SUBS &&
 
261
             (select_lex->item_list.elements !=
 
262
              ((Item_in_subselect*)subselect)->left_expr->cols()))
 
263
          {
 
264
            my_error(ER_OPERAND_COLUMNS, MYF(0), ((Item_in_subselect*)subselect)->left_expr->cols());
 
265
            return(-1);
 
266
          }
 
267
        }
 
268
 
 
269
        /* Register the subquery for further processing */
 
270
        select_lex->outer_select()->join->sj_subselects.append(session->mem_root, in_subs);
 
271
        in_subs->expr_join_nest= (TableList*)session->session_marker;
 
272
      }
 
273
      else
 
274
      {
 
275
        bool do_materialize= !test(session->variables.optimizer_switch &
 
276
                                   OPTIMIZER_SWITCH_NO_MATERIALIZATION);
241
277
        /*
242
278
          Check if the subquery predicate can be executed via materialization.
243
279
          The required conditions are:
255
291
             (Subquery is non-correlated ||
256
292
              Subquery is correlated to any query outer to IN predicate ||
257
293
              (Subquery is correlated to the immediate outer query &&
258
 
               Subquery !contains {GROUP BY, ORDER BY [LIMIT],
 
294
               Subquery !contains {GROUP BY, order_st BY [LIMIT],
259
295
               aggregate functions) && subquery predicate is not under "NOT IN"))
260
296
          6. No execution method was already chosen (by a prepared statement).
261
297
 
291
327
 
292
328
  if (order)
293
329
  {
294
 
    Order *ord;
 
330
    order_st *ord;
295
331
    for (ord= order; ord; ord= ord->next)
296
332
    {
297
333
      Item *item= *ord->item;
325
361
 
326
362
    MODE_ONLY_FULL_GROUP_BY is enabled here by default
327
363
  */
328
 
  if (! group_list && 
329
 
      select_lex->full_group_by_flag.test(NON_AGG_FIELD_USED) &&
330
 
      select_lex->full_group_by_flag.test(SUM_FUNC_USED))
 
364
  if (!group_list && select_lex->full_group_by_flag == (NON_AGG_FIELD_USED | SUM_FUNC_USED))
331
365
  {
332
366
    my_message(ER_MIX_OF_GROUP_FUNC_AND_FIELDS,
333
367
               ER(ER_MIX_OF_GROUP_FUNC_AND_FIELDS), MYF(0));
336
370
  {
337
371
    /* Caclulate the number of groups */
338
372
    send_group_parts= 0;
339
 
    for (Order *group_tmp= group_list ; group_tmp ; group_tmp= group_tmp->next)
 
373
    for (order_st *group_tmp= group_list ; group_tmp ; group_tmp= group_tmp->next)
340
374
      send_group_parts++;
341
375
  }
342
376
 
343
377
  if (error)
344
 
    return(-1);
 
378
    goto err;         /* purecov: inspected */
345
379
 
346
 
  /* 
347
 
   * The below will create the new table for
348
 
   * CREATE TABLE ... SELECT
349
 
   *
350
 
   * @see create_table_from_items() in drizzled/sql_insert.cc
351
 
   */
352
380
  if (result && result->prepare(fields_list, unit_arg))
353
 
    return(-1);
 
381
    goto err;         /* purecov: inspected */
354
382
 
355
383
  /* Init join struct */
356
384
  count_field_types(select_lex, &tmp_table_param, all_fields, 0);
362
390
  if (sum_func_count && !group_list && (func_count || field_count))
363
391
  {
364
392
    my_message(ER_WRONG_SUM_SELECT,ER(ER_WRONG_SUM_SELECT),MYF(0));
365
 
    return(-1);
 
393
    goto err;
366
394
  }
367
395
#endif
368
396
  if (select_lex->olap == ROLLUP_TYPE && rollup_init())
369
 
    return(-1);
370
 
 
 
397
    goto err;
371
398
  if (alloc_func_list())
372
 
    return(-1);
373
 
 
374
 
  return 0; // All OK
 
399
    goto err;
 
400
 
 
401
  return(0); // All OK
 
402
 
 
403
err:
 
404
  return(-1);       /* purecov: inspected */
375
405
}
376
406
 
377
407
/*
378
408
  Remove the predicates pushed down into the subquery
379
409
 
380
410
  SYNOPSIS
381
 
    Join::remove_subq_pushed_predicates()
 
411
    JOIN::remove_subq_pushed_predicates()
382
412
      where   IN  Must be NULL
383
413
              OUT The remaining WHERE condition, or NULL
384
414
 
403
433
    that is searched in a byte. But this requires homogenization of the return
404
434
    codes of all Field*::store() methods.
405
435
*/
406
 
void Join::remove_subq_pushed_predicates(Item **where)
 
436
void JOIN::remove_subq_pushed_predicates(Item **where)
407
437
{
408
438
  if (conds->type() == Item::FUNC_ITEM &&
409
439
      ((Item_func *)this->conds)->functype() == Item_func::EQ_FUNC &&
428
458
  @retval
429
459
    1   error
430
460
*/
431
 
int Join::optimize()
 
461
int JOIN::optimize()
432
462
{
433
463
  // to prevent double initialization on EXPLAIN
434
464
  if (optimized)
435
 
    return 0;
 
465
    return(0);
436
466
  optimized= 1;
437
467
 
438
468
  session->set_proc_info("optimizing");
471
501
#endif
472
502
 
473
503
  /* Convert all outer joins to inner joins if possible */
474
 
  conds= simplify_joins(this, join_list, conds, true);
 
504
  conds= simplify_joins(this, join_list, conds, true, false);
475
505
  build_bitmap_for_nested_joins(join_list, 0);
476
506
 
477
507
  conds= optimize_cond(this, conds, join_list, &cond_value);
478
508
  if (session->is_error())
479
509
  {
480
510
    error= 1;
481
 
    return 1;
 
511
    return(1);
482
512
  }
483
513
 
484
514
  {
486
516
    if (session->is_error())
487
517
    {
488
518
      error= 1;
489
 
      return 1;
 
519
      return(1);
490
520
    }
491
521
    if (select_lex->where)
492
522
      select_lex->cond_value= cond_value;
498
528
    {           /* Impossible cond */
499
529
      zero_result_cause=  having_value == Item::COND_FALSE ?
500
530
                           "Impossible HAVING" : "Impossible WHERE";
501
 
      tables = 0;
502
 
      goto setup_subq_exit;
 
531
      error= 0;
 
532
      return(0);
503
533
    }
504
534
  }
505
535
 
508
538
  {
509
539
    int res;
510
540
    /*
511
 
      optimizer::sum_query() returns HA_ERR_KEY_NOT_FOUND if no rows match
 
541
      opt_sum_query() returns HA_ERR_KEY_NOT_FOUND if no rows match
512
542
      to the WHERE conditions,
513
543
      or 1 if all items were resolved,
514
544
      or 0, or an error number HA_ERR_...
515
545
    */
516
 
    if ((res= optimizer::sum_query(select_lex->leaf_tables, all_fields, conds)))
 
546
    if ((res=opt_sum_query(select_lex->leaf_tables, all_fields, conds)))
517
547
    {
518
548
      if (res == HA_ERR_KEY_NOT_FOUND)
519
549
      {
520
550
        zero_result_cause= "No matching min/max row";
521
 
        tables = 0;
522
 
        goto setup_subq_exit;
 
551
        error=0;
 
552
        return(0);
523
553
      }
524
554
      if (res > 1)
525
555
      {
526
556
        error= res;
527
 
        return 1;
 
557
        return(1);
528
558
      }
529
559
      if (res < 0)
530
560
      {
531
561
        zero_result_cause= "No matching min/max row";
532
 
        tables = 0;
533
 
        goto setup_subq_exit;
 
562
        error=0;
 
563
        return(0);
534
564
      }
535
565
      zero_result_cause= "Select tables optimized away";
536
566
      tables_list= 0;       // All tables resolved
537
 
      const_tables= tables;
538
567
      /*
539
568
        Extract all table-independent conditions and replace the WHERE
540
 
        clause with them. All other conditions were computed by optimizer::sum_query
 
569
        clause with them. All other conditions were computed by opt_sum_query
541
570
        and the MIN/MAX/COUNT function(s) have been replaced by constants,
542
571
        so there is no need to compute the whole WHERE clause again.
543
572
        Notice that make_cond_for_table() will always succeed to remove all
544
 
        computed conditions, because optimizer::sum_query() is applicable only to
 
573
        computed conditions, because opt_sum_query() is applicable only to
545
574
        conjunctions.
546
575
        Preserve conditions for EXPLAIN.
547
576
      */
550
579
        COND *table_independent_conds= make_cond_for_table(conds, PSEUDO_TABLE_BITS, 0, 0);
551
580
        conds= table_independent_conds;
552
581
      }
553
 
      goto setup_subq_exit;
554
582
    }
555
583
  }
556
584
  if (!tables_list)
566
594
  if (make_join_statistics(this, select_lex->leaf_tables, conds, &keyuse) ||
567
595
      session->is_fatal_error)
568
596
  {
569
 
    return 1;
 
597
    return(1);
570
598
  }
571
599
 
572
600
  /* Remove distinct if only const tables */
574
602
  session->set_proc_info("preparing");
575
603
  if (result->initialize_tables(this))
576
604
  {
577
 
    return 1;        // error == -1
 
605
    return(1);        // error == -1
578
606
  }
579
607
  if (const_table_map != found_const_table_map &&
580
608
      !(select_options & SELECT_DESCRIBE) &&
583
611
       select_lex->master_unit() == &session->lex->unit)) // upper level SELECT
584
612
  {
585
613
    zero_result_cause= "no matching row in const table";
586
 
    goto setup_subq_exit;
 
614
    error= 0;
 
615
    return(0);
587
616
  }
588
617
  if (!(session->options & OPTION_BIG_SELECTS) &&
589
618
      best_read > (double) session->variables.max_join_size &&
590
619
      !(select_options & SELECT_DESCRIBE))
591
 
  {
 
620
  {           /* purecov: inspected */
592
621
    my_message(ER_TOO_BIG_SELECT, ER(ER_TOO_BIG_SELECT), MYF(0));
593
622
    error= -1;
594
 
    return 1;
 
623
    return(1);
595
624
  }
596
625
  if (const_tables && !(select_options & SELECT_NO_UNLOCK))
597
 
    session->unlockSomeTables(table, const_tables);
 
626
    mysql_unlock_some_tables(session, table, const_tables);
598
627
  if (!conds && outer_join)
599
628
  {
600
629
    /* Handle the case where we have an OUTER JOIN without a WHERE */
601
630
    conds=new Item_int((int64_t) 1,1);  // Always true
602
631
  }
603
 
  select= optimizer::make_select(*table, const_table_map,
604
 
                                 const_table_map, conds, 1, &error);
 
632
  select= make_select(*table, const_table_map,
 
633
                      const_table_map, conds, 1, &error);
605
634
  if (error)
606
 
  {
607
 
    error= -1;
608
 
    return 1;
 
635
  {           /* purecov: inspected */
 
636
    error= -1;          /* purecov: inspected */
 
637
    return(1);
609
638
  }
610
639
 
611
640
  reset_nj_counters(join_list);
627
656
    Permorm the the optimization on fields evaluation mentioned above
628
657
    for all on expressions.
629
658
  */
630
 
  for (JoinTable *tab= join_tab + const_tables; tab < join_tab + tables ; tab++)
 
659
  for (JOIN_TAB *tab= join_tab + const_tables; tab < join_tab + tables ; tab++)
631
660
  {
632
661
    if (*tab->on_expr_ref)
633
662
    {
644
673
  {
645
674
    conds=new Item_int((int64_t) 0,1);  // Always false
646
675
  }
647
 
 
648
676
  if (make_join_select(this, select, conds))
649
677
  {
650
678
    zero_result_cause=
651
679
      "Impossible WHERE noticed after reading const tables";
652
 
    goto setup_subq_exit;
 
680
    return(0);        // error == 0
653
681
  }
654
682
 
655
683
  error= -1;          /* if goto err */
656
684
 
657
685
  /* Optimize distinct away if possible */
658
686
  {
659
 
    Order *org_order= order;
 
687
    order_st *org_order= order;
660
688
    order= remove_constants(this, order,conds,1, &simple_order);
661
689
    if (session->is_error())
662
690
    {
663
691
      error= 1;
664
 
      return 1;
 
692
      return(1);
665
693
    }
666
694
 
667
695
    /*
668
 
      If we are using ORDER BY NULL or ORDER BY const_expression,
 
696
      If we are using order_st BY NULL or order_st BY const_expression,
669
697
      return result in any order (even if we are using a GROUP BY)
670
698
    */
671
699
    if (!order && org_order)
684
712
     The FROM clause must contain a single non-constant table.
685
713
  */
686
714
  if (tables - const_tables == 1 && (group_list || select_distinct) &&
687
 
      ! tmp_table_param.sum_func_count &&
688
 
      (! join_tab[const_tables].select ||
689
 
       ! join_tab[const_tables].select->quick ||
 
715
      !tmp_table_param.sum_func_count &&
 
716
      (!join_tab[const_tables].select ||
 
717
       !join_tab[const_tables].select->quick ||
690
718
       join_tab[const_tables].select->quick->get_type() !=
691
 
       optimizer::QuickSelectInterface::QS_TYPE_GROUP_MIN_MAX))
 
719
       QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX))
692
720
  {
693
721
    if (group_list && list_contains_unique_index(join_tab[const_tables].table, find_field_in_order_list, (void *) group_list))
694
722
    {
696
724
        We have found that grouping can be removed since groups correspond to
697
725
        only one row anyway, but we still have to guarantee correct result
698
726
        order. The line below effectively rewrites the query from GROUP BY
699
 
        <fields> to ORDER BY <fields>. There are two exceptions:
 
727
        <fields> to order_st BY <fields>. There are two exceptions:
700
728
        - if skip_sort_order is set (see above), then we can simply skip
701
729
          GROUP BY;
702
 
        - we can only rewrite ORDER BY if the ORDER BY fields are 'compatible'
 
730
        - we can only rewrite order_st BY if the order_st BY fields are 'compatible'
703
731
          with the GROUP BY ones, i.e. either one is a prefix of another.
704
 
          We only check if the ORDER BY is a prefix of GROUP BY. In this case
 
732
          We only check if the order_st BY is a prefix of GROUP BY. In this case
705
733
          test_if_subpart() copies the ASC/DESC attributes from the original
706
 
          ORDER BY fields.
 
734
          order_st BY fields.
707
735
          If GROUP BY is a prefix of order_st BY, then it is safe to leave
708
736
          'order' as is.
709
737
       */
710
 
      if (! order || test_if_subpart(group_list, order))
 
738
      if (!order || test_if_subpart(group_list, order))
711
739
          order= skip_sort_order ? 0 : group_list;
712
740
      /*
713
741
        If we have an IGNORE INDEX FOR GROUP BY(fields) clause, this must be
742
770
      - We are scanning the whole table without LIMIT
743
771
        This can happen if:
744
772
        - We are using CALC_FOUND_ROWS
745
 
        - We are using an ORDER BY that can't be optimized away.
 
773
        - We are using an order_st BY that can't be optimized away.
746
774
 
747
775
      We don't want to use this optimization when we are using LIMIT
748
776
      because in this case we can just create a temporary table that
749
777
      holds LIMIT rows and stop when this table is full.
750
778
    */
751
 
    JoinTable *tab= &join_tab[const_tables];
 
779
    JOIN_TAB *tab= &join_tab[const_tables];
752
780
    bool all_order_fields_used;
753
781
    if (order)
754
782
      skip_sort_order= test_if_skip_sort_order(tab, order, select_limit, 1,
774
802
          {
775
803
            /*
776
804
              Force MySQL to read the table in sorted order to get result in
777
 
              ORDER BY order.
 
805
              order_st BY order.
778
806
            */
779
807
            tmp_table_param.quick_group=0;
780
808
          }
786
814
        group_list= 0;
787
815
    }
788
816
    else if (session->is_fatal_error)     // End of memory
789
 
      return 1;
 
817
      return(1);
790
818
  }
791
819
  simple_group= 0;
792
820
  {
793
 
    Order *old_group_list;
 
821
    order_st *old_group_list;
794
822
    group_list= remove_constants(this, (old_group_list= group_list), conds,
795
823
                                 rollup.state == ROLLUP::STATE_NONE,
796
824
                                 &simple_group);
797
825
    if (session->is_error())
798
826
    {
799
827
      error= 1;
800
 
      return 1;
 
828
      return(1);
801
829
    }
802
830
    if (old_group_list && !group_list)
803
831
      select_distinct= 0;
831
859
    This has to be done if all tables are not already read (const tables)
832
860
    and one of the following conditions holds:
833
861
    - We are using DISTINCT (simple distinct's are already optimized away)
834
 
    - We are using an ORDER BY or GROUP BY on fields not in the first table
835
 
    - We are using different ORDER BY and GROUP BY orders
 
862
    - We are using an order_st BY or GROUP BY on fields not in the first table
 
863
    - We are using different order_st BY and GROUP BY orders
836
864
    - The user wants us to buffer the result.
837
865
  */
838
866
  need_tmp= (const_tables != tables &&
840
868
        (group_list && order) ||
841
869
        test(select_options & OPTION_BUFFER_RESULT)));
842
870
 
 
871
  uint32_t no_jbuf_after= make_join_orderinfo(this);
 
872
  uint64_t select_opts_for_readinfo=
 
873
    (select_options & (SELECT_DESCRIBE | SELECT_NO_JOIN_CACHE)) | (0);
 
874
 
 
875
  sj_tmp_tables= NULL;
 
876
  if (!select_lex->sj_nests.is_empty())
 
877
    setup_semijoin_dups_elimination(this, select_opts_for_readinfo, no_jbuf_after);
 
878
 
843
879
  // No cache for MATCH == 'Don't use join buffering when we use MATCH'.
844
 
  if (make_join_readinfo(this))
845
 
    return 1;
 
880
  if (make_join_readinfo(this, select_opts_for_readinfo, no_jbuf_after))
 
881
    return(1);
846
882
 
847
883
  /* Create all structures needed for materialized subquery execution. */
848
884
  if (setup_subquery_materialization())
849
 
    return 1;
850
 
 
851
 
  /* Cache constant expressions in WHERE, HAVING, ON clauses. */
852
 
  cache_const_exprs();
 
885
    return(1);
853
886
 
854
887
  /*
855
888
    is this simple IN subquery?
862
895
    if (!having)
863
896
    {
864
897
      Item *where= conds;
865
 
      if (join_tab[0].type == AM_EQ_REF && join_tab[0].ref.items[0]->name == in_left_expr_name)
 
898
      if (join_tab[0].type == JT_EQ_REF && join_tab[0].ref.items[0]->name == in_left_expr_name)
866
899
      {
867
900
        remove_subq_pushed_predicates(&where);
868
901
        save_index_subquery_explain_info(join_tab, where);
869
 
        join_tab[0].type= AM_UNIQUE_SUBQUERY;
 
902
        join_tab[0].type= JT_UNIQUE_SUBQUERY;
870
903
        error= 0;
871
 
        return(unit->item->change_engine(new subselect_uniquesubquery_engine(session, join_tab, unit->item, where)));
 
904
        return(unit->item->
 
905
                    change_engine(new
 
906
                                  subselect_uniquesubquery_engine(session,
 
907
                                                                  join_tab,
 
908
                                                                  unit->item,
 
909
                                                                  where)));
872
910
      }
873
 
      else if (join_tab[0].type == AM_REF &&
 
911
      else if (join_tab[0].type == JT_REF &&
874
912
         join_tab[0].ref.items[0]->name == in_left_expr_name)
875
913
      {
876
914
        remove_subq_pushed_predicates(&where);
877
915
        save_index_subquery_explain_info(join_tab, where);
878
 
        join_tab[0].type= AM_INDEX_SUBQUERY;
 
916
        join_tab[0].type= JT_INDEX_SUBQUERY;
879
917
        error= 0;
880
 
        return(unit->item->change_engine(new subselect_indexsubquery_engine(session, join_tab, unit->item, where, NULL, 0)));
 
918
        return(unit->item->
 
919
                    change_engine(new
 
920
                                  subselect_indexsubquery_engine(session,
 
921
                                                                 join_tab,
 
922
                                                                 unit->item,
 
923
                                                                 where,
 
924
                                                                 NULL,
 
925
                                                                 0)));
881
926
      }
882
927
    } 
883
 
    else if (join_tab[0].type == AM_REF_OR_NULL &&
 
928
    else if (join_tab[0].type == JT_REF_OR_NULL &&
884
929
         join_tab[0].ref.items[0]->name == in_left_expr_name &&
885
930
               having->name == in_having_cond)
886
931
    {
887
 
      join_tab[0].type= AM_INDEX_SUBQUERY;
 
932
      join_tab[0].type= JT_INDEX_SUBQUERY;
888
933
      error= 0;
889
934
      conds= remove_additional_cond(conds);
890
935
      save_index_subquery_explain_info(join_tab, conds);
891
 
      return(unit->item->change_engine(new subselect_indexsubquery_engine(session, join_tab, unit->item, conds, having, 1)));
 
936
      return(unit->item->
 
937
      change_engine(new subselect_indexsubquery_engine(session,
 
938
                   join_tab,
 
939
                   unit->item,
 
940
                   conds,
 
941
                                                                   having,
 
942
                   1)));
892
943
    }
893
944
 
894
945
  }
913
964
      as in other cases the join is done before the sort.
914
965
    */
915
966
    if ((order || group_list) &&
916
 
        (join_tab[const_tables].type != AM_ALL) &&
917
 
        (join_tab[const_tables].type != AM_REF_OR_NULL) &&
 
967
        (join_tab[const_tables].type != JT_ALL) &&
 
968
        (join_tab[const_tables].type != JT_REF_OR_NULL) &&
918
969
        ((order && simple_order) || (group_list && simple_group)))
919
970
    {
920
971
      if (add_ref_to_table_cond(session,&join_tab[const_tables])) {
921
 
        return 1;
 
972
        return(1);
922
973
      }
923
974
    }
924
975
 
940
991
        Force using of tmp table if sorting by a SP or UDF function due to
941
992
        their expensive and probably non-deterministic nature.
942
993
      */
943
 
      for (Order *tmp_order= order; tmp_order ; tmp_order=tmp_order->next)
 
994
      for (order_st *tmp_order= order; tmp_order ; tmp_order=tmp_order->next)
944
995
      {
945
996
        Item *item= *tmp_order->item;
946
997
        if (item->is_expensive())
984
1035
 
985
1036
    tmp_table_param.hidden_field_count= (all_fields.elements -
986
1037
           fields_list.elements);
987
 
    Order *tmp_group= ((!simple_group &&
988
 
                           ! (test_flags.test(TEST_NO_KEY_GROUP))) ? group_list :
989
 
                                                                     (Order*) 0);
 
1038
    order_st *tmp_group= ((!simple_group && !(test_flags & TEST_NO_KEY_GROUP)) ? group_list :
 
1039
                                                             (order_st*) 0);
990
1040
    /*
991
1041
      Pushing LIMIT to the temporary table creation is not applicable
992
 
      when there is ORDER BY or GROUP BY or there is no GROUP BY, but
 
1042
      when there is order_st BY or GROUP BY or there is no GROUP BY, but
993
1043
      there are aggregate functions, because in all these cases we need
994
1044
      all result rows.
995
1045
    */
999
1049
                            select_limit : HA_POS_ERROR;
1000
1050
 
1001
1051
    if (!(exec_tmp_table1=
1002
 
          create_tmp_table(session, &tmp_table_param, all_fields,
 
1052
    create_tmp_table(session, &tmp_table_param, all_fields,
1003
1053
                           tmp_group,
1004
 
                           group_list ? 0 : select_distinct,
1005
 
                           group_list && simple_group,
1006
 
                           select_options,
 
1054
         group_list ? 0 : select_distinct,
 
1055
         group_list && simple_group,
 
1056
         select_options,
1007
1057
                           tmp_rows_limit,
1008
 
                           (char *) "")))
 
1058
         (char *) "")))
1009
1059
    {
1010
 
      return 1;
 
1060
      return(1);
1011
1061
    }
1012
1062
 
1013
1063
    /*
1033
1083
          make_sum_func_list(all_fields, fields_list, 1) ||
1034
1084
          setup_sum_funcs(session, sum_funcs))
1035
1085
      {
1036
 
        return 1;
 
1086
        return(1);
1037
1087
      }
1038
1088
      group_list=0;
1039
1089
    }
1042
1092
      if (make_sum_func_list(all_fields, fields_list, 0) ||
1043
1093
          setup_sum_funcs(session, sum_funcs))
1044
1094
      {
1045
 
        return 1;
 
1095
        return(1);
1046
1096
      }
1047
1097
 
1048
1098
      if (!group_list && ! exec_tmp_table1->distinct && order && simple_order)
1051
1101
        if (create_sort_index(session, this, order,
1052
1102
                              HA_POS_ERROR, HA_POS_ERROR, true))
1053
1103
        {
1054
 
          return 1;
 
1104
          return(1);
1055
1105
        }
1056
1106
        order=0;
1057
1107
      }
1066
1116
    if (exec_tmp_table1->distinct)
1067
1117
    {
1068
1118
      table_map used_tables= session->used_tables;
1069
 
      JoinTable *last_join_tab= join_tab+tables-1;
 
1119
      JOIN_TAB *last_join_tab= join_tab+tables-1;
1070
1120
      do
1071
1121
      {
1072
1122
        if (used_tables & last_join_tab->table->map)
1089
1139
      If this join belongs to an uncacheable subquery save
1090
1140
      the original join
1091
1141
    */
1092
 
    if (select_lex->uncacheable.any() && 
1093
 
        ! is_top_level_join() &&
 
1142
    if (select_lex->uncacheable && !is_top_level_join() &&
1094
1143
        init_save_join_tab())
1095
 
    {
1096
 
      return -1;
1097
 
    }
 
1144
      return(-1);                         /* purecov: inspected */
1098
1145
  }
1099
1146
 
1100
1147
  error= 0;
1101
 
  return 0;
1102
 
 
1103
 
setup_subq_exit:
1104
 
  /* Even with zero matching rows, subqueries in the HAVING clause
1105
 
     may need to be evaluated if there are aggregate functions in the query.
1106
 
  */
1107
 
  if (setup_subquery_materialization())
1108
 
    return 1;
1109
 
  error= 0;
1110
 
  return 0;
 
1148
  return(0);
1111
1149
}
1112
1150
 
1113
1151
/**
1114
1152
  Restore values in temporary join.
1115
1153
*/
1116
 
void Join::restore_tmp()
 
1154
void JOIN::restore_tmp()
1117
1155
{
1118
 
  memcpy(tmp_join, this, (size_t) sizeof(Join));
 
1156
  memcpy(tmp_join, this, (size_t) sizeof(JOIN));
1119
1157
}
1120
1158
 
1121
 
int Join::reinit()
 
1159
int JOIN::reinit()
1122
1160
{
1123
1161
  unit->offset_limit_cnt= (ha_rows)(select_lex->offset_limit ?
1124
1162
                                    select_lex->offset_limit->val_uint() :
1128
1166
 
1129
1167
  if (exec_tmp_table1)
1130
1168
  {
1131
 
    exec_tmp_table1->cursor->extra(HA_EXTRA_RESET_STATE);
1132
 
    exec_tmp_table1->cursor->ha_delete_all_rows();
1133
 
    exec_tmp_table1->free_io_cache();
1134
 
    exec_tmp_table1->filesort_free_buffers();
 
1169
    exec_tmp_table1->file->extra(HA_EXTRA_RESET_STATE);
 
1170
    exec_tmp_table1->file->ha_delete_all_rows();
 
1171
    free_io_cache(exec_tmp_table1);
 
1172
    filesort_free_buffers(exec_tmp_table1,0);
1135
1173
  }
1136
1174
  if (exec_tmp_table2)
1137
1175
  {
1138
 
    exec_tmp_table2->cursor->extra(HA_EXTRA_RESET_STATE);
1139
 
    exec_tmp_table2->cursor->ha_delete_all_rows();
1140
 
    exec_tmp_table2->free_io_cache();
1141
 
    exec_tmp_table2->filesort_free_buffers();
 
1176
    exec_tmp_table2->file->extra(HA_EXTRA_RESET_STATE);
 
1177
    exec_tmp_table2->file->ha_delete_all_rows();
 
1178
    free_io_cache(exec_tmp_table2);
 
1179
    filesort_free_buffers(exec_tmp_table2,0);
1142
1180
  }
1143
1181
  if (items0)
1144
1182
    set_items_ref_array(items0);
1145
1183
 
1146
1184
  if (join_tab_save)
1147
 
    memcpy(join_tab, join_tab_save, sizeof(JoinTable) * tables);
 
1185
    memcpy(join_tab, join_tab_save, sizeof(JOIN_TAB) * tables);
1148
1186
 
1149
1187
  if (tmp_join)
1150
1188
    restore_tmp();
1170
1208
   @retval 0      success.
1171
1209
   @retval 1      error occurred.
1172
1210
*/
1173
 
bool Join::init_save_join_tab()
 
1211
bool JOIN::init_save_join_tab()
1174
1212
{
1175
 
  if (!(tmp_join= (Join*)session->alloc(sizeof(Join))))
1176
 
    return 1;
1177
 
 
 
1213
  if (!(tmp_join= (JOIN*)session->alloc(sizeof(JOIN))))
 
1214
    return 1;                                  /* purecov: inspected */
1178
1215
  error= 0;              // Ensure that tmp_join.error= 0
1179
1216
  restore_tmp();
1180
 
 
1181
1217
  return 0;
1182
1218
}
1183
1219
 
1184
 
bool Join::save_join_tab()
 
1220
bool JOIN::save_join_tab()
1185
1221
{
1186
 
  if (! join_tab_save && select_lex->master_unit()->uncacheable.any())
 
1222
  if (!join_tab_save && select_lex->master_unit()->uncacheable)
1187
1223
  {
1188
 
    if (!(join_tab_save= (JoinTable*)session->memdup((unsigned char*) join_tab,
1189
 
            sizeof(JoinTable) * tables)))
 
1224
    if (!(join_tab_save= (JOIN_TAB*)session->memdup((unsigned char*) join_tab,
 
1225
            sizeof(JOIN_TAB) * tables)))
1190
1226
      return 1;
1191
1227
  }
1192
1228
  return 0;
1203
1239
  @todo
1204
1240
    When can we have here session->net.report_error not zero?
1205
1241
*/
1206
 
void Join::exec()
 
1242
void JOIN::exec()
1207
1243
{
1208
1244
  List<Item> *columns_list= &fields_list;
1209
1245
  int      tmp_error;
1215
1251
  {                                           
1216
1252
    /* Only test of functions */
1217
1253
    if (select_options & SELECT_DESCRIBE)
1218
 
    {
1219
 
      optimizer::ExplainPlan planner(this, 
1220
 
                                     false,
1221
 
                                     false,
1222
 
                                     false,
1223
 
                                     (zero_result_cause ? zero_result_cause : "No tables used"));
1224
 
      planner.printPlan();
1225
 
    }
 
1254
      select_describe(this, false, false, false, (zero_result_cause?zero_result_cause:"No tables used"));
1226
1255
    else
1227
1256
    {
1228
 
      result->send_fields(*columns_list);
 
1257
      result->send_fields(*columns_list, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF);
1229
1258
      /*
1230
1259
        We have to test for 'conds' here as the WHERE may not be constant
1231
1260
        even if we don't have any tables for prepared statements or if
1273
1302
    return;
1274
1303
  }
1275
1304
 
 
1305
  if ((this->select_lex->options & OPTION_SCHEMA_TABLE) && get_schema_tables_result(this, PROCESSED_BY_JOIN_EXEC))
 
1306
    return;
 
1307
 
1276
1308
  if (select_options & SELECT_DESCRIBE)
1277
1309
  {
1278
1310
    /*
1279
 
      Check if we managed to optimize ORDER BY away and don't use temporary
 
1311
      Check if we managed to optimize order_st BY away and don't use temporary
1280
1312
      table to resolve order_st BY: in that case, we only may need to do
1281
1313
      filesort for GROUP BY.
1282
1314
    */
1295
1327
      order= 0;
1296
1328
    }
1297
1329
    having= tmp_having;
1298
 
    optimizer::ExplainPlan planner(this,
1299
 
                                   need_tmp,
1300
 
                                   order != 0 && ! skip_sort_order,
1301
 
                                   select_distinct,
1302
 
                                   ! tables ? "No tables used" : NULL);
1303
 
    planner.printPlan();
 
1330
    select_describe(this, need_tmp, order != 0 && !skip_sort_order,  select_distinct, !tables ? "No tables used" : NULL);
1304
1331
    return;
1305
1332
  }
1306
1333
 
1307
 
  Join *curr_join= this;
 
1334
  JOIN *curr_join= this;
1308
1335
  List<Item> *curr_all_fields= &all_fields;
1309
1336
  List<Item> *curr_fields_list= &fields_list;
1310
1337
  Table *curr_tmp_table= 0;
1339
1366
      error= tmp_error;
1340
1367
      return;
1341
1368
    }
1342
 
    curr_tmp_table->cursor->info(HA_STATUS_VARIABLE);
 
1369
    curr_tmp_table->file->info(HA_STATUS_VARIABLE);
1343
1370
 
1344
1371
    if (curr_join->having)
1345
1372
      curr_join->having= curr_join->tmp_having= 0; // Allready done
1414
1441
                                                   - curr_join->tmp_fields_list1.elements;
1415
1442
 
1416
1443
      if (exec_tmp_table2)
1417
 
      {
1418
1444
        curr_tmp_table= exec_tmp_table2;
1419
 
      }
1420
1445
      else
1421
1446
      {
1422
1447
        /* group data to new table */
1424
1449
        /*
1425
1450
          If the access method is loose index scan then all MIN/MAX
1426
1451
          functions are precomputed, and should be treated as regular
1427
 
          functions. See extended comment in Join::exec.
 
1452
          functions. See extended comment in JOIN::exec.
1428
1453
        */
1429
1454
        if (curr_join->join_tab->is_using_loose_index_scan())
1430
1455
          curr_join->tmp_table_param.precomputed_group_by= true;
1433
1458
              exec_tmp_table2= create_tmp_table(session,
1434
1459
                                                &curr_join->tmp_table_param,
1435
1460
                                                *curr_all_fields,
1436
 
                                                (Order*) 0,
 
1461
                                                (order_st*) 0,
1437
1462
                                                curr_join->select_distinct &&
1438
1463
                                                !curr_join->group_list,
1439
1464
                                                1, curr_join->select_options,
1440
1465
                                                HA_POS_ERROR,
1441
1466
                                                (char *) "")))
1442
 
        {
1443
1467
          return;
1444
 
        }
1445
 
 
1446
1468
        curr_join->exec_tmp_table2= exec_tmp_table2;
1447
1469
      }
1448
1470
      if (curr_join->group_list)
1490
1512
        error= tmp_error;
1491
1513
        return;
1492
1514
      }
1493
 
      curr_join->join_tab->read_record.end_read_record();
 
1515
      end_read_record(&curr_join->join_tab->read_record);
1494
1516
      curr_join->const_tables= curr_join->tables; // Mark free for cleanup()
1495
1517
      curr_join->join_tab[0].table= 0;           // Table is freed
1496
1518
 
1579
1601
    {
1580
1602
      // Some tables may have been const
1581
1603
      curr_join->tmp_having->update_used_tables();
1582
 
      JoinTable *curr_table= &curr_join->join_tab[curr_join->const_tables];
 
1604
      JOIN_TAB *curr_table= &curr_join->join_tab[curr_join->const_tables];
1583
1605
      table_map used_tables= (curr_join->const_table_map |
1584
1606
            curr_table->table->map);
1585
1607
 
1587
1609
      if (sort_table_cond)
1588
1610
      {
1589
1611
        if (!curr_table->select)
1590
 
          if (!(curr_table->select= new optimizer::SqlSelect))
 
1612
          if (!(curr_table->select= new SQL_SELECT))
1591
1613
            return;
1592
1614
        if (!curr_table->select->cond)
1593
1615
          curr_table->select->cond= sort_table_cond;
1619
1641
          We can abort sorting after session->select_limit rows if we there is no
1620
1642
          WHERE clause for any tables after the sorted one.
1621
1643
        */
1622
 
        JoinTable *curr_table= &curr_join->join_tab[curr_join->const_tables+1];
1623
 
        JoinTable *end_table= &curr_join->join_tab[curr_join->tables];
 
1644
        JOIN_TAB *curr_table= &curr_join->join_tab[curr_join->const_tables+1];
 
1645
        JOIN_TAB *end_table= &curr_join->join_tab[curr_join->tables];
1624
1646
        for (; curr_table < end_table ; curr_table++)
1625
1647
        {
1626
1648
          /*
1679
1701
  curr_join->fields= curr_fields_list;
1680
1702
 
1681
1703
  session->set_proc_info("Sending data");
1682
 
  result->send_fields(*curr_fields_list);
 
1704
  result->send_fields(*curr_fields_list,
 
1705
                      Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF);
1683
1706
  error= do_select(curr_join, curr_fields_list, NULL);
1684
1707
  session->limit_found_rows= curr_join->send_records;
1685
1708
 
1701
1724
  Clean up join.
1702
1725
 
1703
1726
  @return
1704
 
    Return error that hold Join.
 
1727
    Return error that hold JOIN.
1705
1728
*/
1706
 
int Join::destroy()
 
1729
int JOIN::destroy()
1707
1730
{
1708
1731
  select_lex->join= 0;
1709
1732
 
1711
1734
  {
1712
1735
    if (join_tab != tmp_join->join_tab)
1713
1736
    {
1714
 
      JoinTable *tab, *end;
 
1737
      JOIN_TAB *tab, *end;
1715
1738
      for (tab= join_tab, end= tab+tables ; tab != end ; tab++)
1716
1739
        tab->cleanup();
1717
1740
    }
1722
1745
  cond_equal= 0;
1723
1746
 
1724
1747
  cleanup(1);
1725
 
  exec_tmp_table1= NULL;
1726
 
  exec_tmp_table2= NULL;
 
1748
  if (exec_tmp_table1)
 
1749
    exec_tmp_table1->free_tmp_table(session);
 
1750
  if (exec_tmp_table2)
 
1751
    exec_tmp_table2->free_tmp_table(session);
1727
1752
  delete select;
1728
1753
  delete_dynamic(&keyuse);
1729
 
 
1730
1754
  return(error);
1731
1755
}
1732
1756
 
 
1757
/*
 
1758
  Convert candidate subquery predicates to semi-joins
 
1759
 
 
1760
  SYNOPSIS
 
1761
    JOIN::flatten_subqueries()
 
1762
 
 
1763
  DESCRIPTION
 
1764
    Convert candidate subquery predicates to semi-joins.
 
1765
 
 
1766
  RETURN
 
1767
    false  OK
 
1768
    true   Error
 
1769
*/
 
1770
bool JOIN::flatten_subqueries()
 
1771
{
 
1772
  Item_in_subselect **in_subq;
 
1773
  Item_in_subselect **in_subq_end;
 
1774
 
 
1775
  if (sj_subselects.elements() == 0)
 
1776
    return(false);
 
1777
 
 
1778
  /* 1. Fix children subqueries */
 
1779
  for (in_subq= sj_subselects.front(), in_subq_end= sj_subselects.back();
 
1780
       in_subq != in_subq_end; in_subq++)
 
1781
  {
 
1782
    JOIN *child_join= (*in_subq)->unit->first_select()->join;
 
1783
    child_join->outer_tables = child_join->tables;
 
1784
    if (child_join->flatten_subqueries())
 
1785
      return(true);
 
1786
    (*in_subq)->sj_convert_priority=
 
1787
      (*in_subq)->is_correlated * MAX_TABLES + child_join->outer_tables;
 
1788
  }
 
1789
  
 
1790
  bool outer_join_disable_semi_join= false;
 
1791
  /*
 
1792
   * Temporary measure: disable semi-joins when they are together with outer
 
1793
   * joins.
 
1794
   *
 
1795
   * @see LP Bug #314911
 
1796
   */
 
1797
  for (TableList *tbl= select_lex->leaf_tables; tbl; tbl=tbl->next_leaf)
 
1798
  {
 
1799
    TableList *embedding= tbl->embedding;
 
1800
    if (tbl->on_expr || (tbl->embedding && !(embedding->sj_on_expr && 
 
1801
                                            !embedding->embedding)))
 
1802
    {
 
1803
      in_subq= sj_subselects.front();
 
1804
      outer_join_disable_semi_join= true;
 
1805
    }
 
1806
  }
 
1807
 
 
1808
  if (! outer_join_disable_semi_join)
 
1809
  {
 
1810
    /*
 
1811
      2. Pick which subqueries to convert:
 
1812
        sort the subquery array
 
1813
        - prefer correlated subqueries over uncorrelated;
 
1814
        - prefer subqueries that have greater number of outer tables;
 
1815
    */
 
1816
    sj_subselects.sort(subq_sj_candidate_cmp);
 
1817
    // #tables-in-parent-query + #tables-in-subquery < MAX_TABLES
 
1818
    /* Replace all subqueries to be flattened with Item_int(1) */
 
1819
    for (in_subq= sj_subselects.front();
 
1820
        in_subq != in_subq_end &&
 
1821
        tables + ((*in_subq)->sj_convert_priority % MAX_TABLES) < MAX_TABLES;
 
1822
        in_subq++)
 
1823
    {
 
1824
      if (replace_where_subcondition(this, *in_subq, new Item_int(1), false))
 
1825
        return(true);
 
1826
    }
 
1827
 
 
1828
    for (in_subq= sj_subselects.front();
 
1829
        in_subq != in_subq_end &&
 
1830
        tables + ((*in_subq)->sj_convert_priority % MAX_TABLES) < MAX_TABLES;
 
1831
        in_subq++)
 
1832
    {
 
1833
      if (convert_subq_to_sj(this, *in_subq))
 
1834
        return(true);
 
1835
    }
 
1836
  }
 
1837
 
 
1838
  /* 3. Finalize those we didn't convert */
 
1839
  for (; in_subq!= in_subq_end; in_subq++)
 
1840
  {
 
1841
    JOIN *child_join= (*in_subq)->unit->first_select()->join;
 
1842
    Item_subselect::trans_res res;
 
1843
    (*in_subq)->changed= 0;
 
1844
    (*in_subq)->fixed= 0;
 
1845
    res= (*in_subq)->select_transformer(child_join);
 
1846
    if (res == Item_subselect::RES_ERROR)
 
1847
      return(true);
 
1848
 
 
1849
    (*in_subq)->changed= 1;
 
1850
    (*in_subq)->fixed= 1;
 
1851
 
 
1852
    Item *substitute= (*in_subq)->substitution;
 
1853
    bool do_fix_fields= !(*in_subq)->substitution->fixed;
 
1854
    if (replace_where_subcondition(this, *in_subq, substitute, do_fix_fields))
 
1855
      return(true);
 
1856
 
 
1857
    //if ((*in_subq)->fix_fields(session, (*in_subq)->ref_ptr))
 
1858
    //  return(true);
 
1859
  }
 
1860
  sj_subselects.clear();
 
1861
  return(false);
 
1862
}
 
1863
 
1733
1864
/**
1734
1865
  Setup for execution all subqueries of a query, for which the optimizer
1735
1866
  chose hash semi-join.
1739
1870
  - try to initialize all data structures needed for the materialized execution
1740
1871
    of the IN predicate,
1741
1872
  - if this fails, then perform the IN=>EXISTS transformation which was
1742
 
    previously blocked during Join::prepare.
 
1873
    previously blocked during JOIN::prepare.
1743
1874
 
1744
1875
  This method is part of the "code generation" query processing phase.
1745
1876
 
1752
1883
  @retval false     success.
1753
1884
  @retval true      error occurred.
1754
1885
*/
1755
 
bool Join::setup_subquery_materialization()
 
1886
bool JOIN::setup_subquery_materialization()
1756
1887
{
1757
1888
  for (Select_Lex_Unit *un= select_lex->first_inner_unit(); un;
1758
1889
       un= un->next_unit())
1774
1905
}
1775
1906
 
1776
1907
/**
1777
 
  Partially cleanup Join after it has executed: close index or rnd read
 
1908
  Partially cleanup JOIN after it has executed: close index or rnd read
1778
1909
  (table cursors), free quick selects.
1779
1910
 
1780
 
    This function is called in the end of execution of a Join, before the used
 
1911
    This function is called in the end of execution of a JOIN, before the used
1781
1912
    tables are unlocked and closed.
1782
1913
 
1783
1914
    For a join that is resolved using a temporary table, the first sweep is
1791
1922
    is called after all rows are sent, but before EOF packet is sent.
1792
1923
 
1793
1924
    For a simple SELECT with no subqueries this function performs a full
1794
 
    cleanup of the Join and calls unlockReadTables to free used base
 
1925
    cleanup of the JOIN and calls mysql_unlock_read_tables to free used base
1795
1926
    tables.
1796
1927
 
1797
 
    If a Join is executed for a subquery or if it has a subquery, we can't
 
1928
    If a JOIN is executed for a subquery or if it has a subquery, we can't
1798
1929
    do the full cleanup and need to do a partial cleanup only.
1799
 
    - If a Join is not the top level join, we must not unlock the tables
 
1930
    - If a JOIN is not the top level join, we must not unlock the tables
1800
1931
    because the outer select may not have been evaluated yet, and we
1801
1932
    can't unlock only selected tables of a query.
1802
 
    - Additionally, if this Join corresponds to a correlated subquery, we
 
1933
    - Additionally, if this JOIN corresponds to a correlated subquery, we
1803
1934
    should not free quick selects and join buffers because they will be
1804
1935
    needed for the next execution of the correlated subquery.
1805
 
    - However, if this is a Join for a [sub]select, which is not
 
1936
    - However, if this is a JOIN for a [sub]select, which is not
1806
1937
    a correlated subquery itself, but has subqueries, we can free it
1807
 
    fully and also free Joins of all its subqueries. The exception
 
1938
    fully and also free JOINs of all its subqueries. The exception
1808
1939
    is a subquery in SELECT list, e.g: @n
1809
1940
    SELECT a, (select cmax(b) from t1) group by c @n
1810
1941
    This subquery will not be evaluated at first sweep and its value will
1815
1946
  @todo
1816
1947
    Unlock tables even if the join isn't top level select in the tree
1817
1948
*/
1818
 
void Join::join_free()
 
1949
void JOIN::join_free()
1819
1950
{
1820
1951
  Select_Lex_Unit *tmp_unit;
1821
1952
  Select_Lex *sl;
1822
1953
  /*
1823
 
    Optimization: if not EXPLAIN and we are done with the Join,
 
1954
    Optimization: if not EXPLAIN and we are done with the JOIN,
1824
1955
    free all tables.
1825
1956
  */
1826
 
  bool full= (select_lex->uncacheable.none() && ! session->lex->describe);
 
1957
  bool full= (!select_lex->uncacheable && !session->lex->describe);
1827
1958
  bool can_unlock= full;
1828
1959
 
1829
1960
  cleanup(full);
1845
1976
        but all table cursors must be closed before the unlock.
1846
1977
      */
1847
1978
      sl->cleanup_all_joins(full_local);
1848
 
      /* Can't unlock if at least one Join is still needed */
 
1979
      /* Can't unlock if at least one JOIN is still needed */
1849
1980
      can_unlock= can_unlock && full_local;
1850
1981
    }
1851
1982
 
1863
1994
      TODO: unlock tables even if the join isn't top level select in the
1864
1995
      tree.
1865
1996
    */
1866
 
    session->unlockReadTables(lock);           // Don't free join->lock
 
1997
    mysql_unlock_read_tables(session, lock);           // Don't free join->lock
1867
1998
    lock= 0;
1868
1999
  }
1869
2000
 
1882
2013
    With subquery this function definitely will be called several times,
1883
2014
    but even for simple query it can be called several times.
1884
2015
*/
1885
 
void Join::cleanup(bool full)
 
2016
void JOIN::cleanup(bool full)
1886
2017
{
1887
2018
  if (table)
1888
2019
  {
1889
 
    JoinTable *tab,*end;
 
2020
    JOIN_TAB *tab,*end;
1890
2021
    /*
1891
2022
      Only a sorted table may be cached.  This sorted table is always the
1892
2023
      first non const table in join->table
1893
2024
    */
1894
2025
    if (tables > const_tables) // Test for not-const tables
1895
2026
    {
1896
 
      table[const_tables]->free_io_cache();
1897
 
      table[const_tables]->filesort_free_buffers(full);
 
2027
      free_io_cache(table[const_tables]);
 
2028
      filesort_free_buffers(table[const_tables],full);
1898
2029
    }
1899
2030
 
1900
2031
    if (full)
1908
2039
      for (tab= join_tab, end= tab+tables; tab != end; tab++)
1909
2040
      {
1910
2041
        if (tab->table)
1911
 
          tab->table->cursor->ha_index_or_rnd_end();
 
2042
          tab->table->file->ha_index_or_rnd_end();
1912
2043
      }
1913
2044
    }
 
2045
    cleanup_sj_tmp_tables(this);//
1914
2046
  }
1915
2047
  /*
1916
2048
    We are not using tables anymore
1927
2059
    */
1928
2060
    tmp_table_param.copy_funcs.empty();
1929
2061
    /*
1930
 
      If we have tmp_join and 'this' Join is not tmp_join and
 
2062
      If we have tmp_join and 'this' JOIN is not tmp_join and
1931
2063
      tmp_table_param.copy_field's  of them are equal then we have to remove
1932
2064
      pointer to  tmp_table_param.copy_field from tmp_join, because it qill
1933
2065
      be removed in tmp_table_param.cleanup().
1946
2078
}
1947
2079
 
1948
2080
/*
1949
 
  used only in Join::clear
 
2081
  used only in JOIN::clear
1950
2082
*/
1951
 
static void clear_tables(Join *join)
 
2083
static void clear_tables(JOIN *join)
1952
2084
{
1953
2085
  /*
1954
2086
    must clear only the non-const tables, as const tables
1967
2099
  @retval
1968
2100
    1 Error
1969
2101
*/
1970
 
bool Join::alloc_func_list()
 
2102
bool JOIN::alloc_func_list()
1971
2103
{
1972
2104
  uint32_t func_count, group_parts;
1973
2105
 
1993
2125
    */
1994
2126
    if (order)
1995
2127
    {
1996
 
      Order *ord;
 
2128
      order_st *ord;
1997
2129
      for (ord= order; ord; ord= ord->next)
1998
2130
        group_parts++;
1999
2131
    }
2019
2151
  @retval
2020
2152
    1  error
2021
2153
*/
2022
 
bool Join::make_sum_func_list(List<Item> &field_list, 
 
2154
bool JOIN::make_sum_func_list(List<Item> &field_list, 
2023
2155
                              List<Item> &send_fields,
2024
2156
                              bool before_group_by, 
2025
2157
                              bool recompute)
2057
2189
}
2058
2190
 
2059
2191
/** Allocate memory needed for other rollup functions. */
2060
 
bool Join::rollup_init()
 
2192
bool JOIN::rollup_init()
2061
2193
{
2062
2194
  uint32_t i,j;
2063
2195
  Item **ref_array;
2103
2235
  Item *item;
2104
2236
  while ((item= it++))
2105
2237
  {
2106
 
    Order *group_tmp;
 
2238
    order_st *group_tmp;
2107
2239
    bool found_in_group= 0;
2108
2240
 
2109
2241
    for (group_tmp= group_list; group_tmp; group_tmp= group_tmp->next)
2132
2264
            return 1;
2133
2265
          new_item->fix_fields(session, (Item **) 0);
2134
2266
          session->change_item_tree(it.ref(), new_item);
2135
 
          for (Order *tmp= group_tmp; tmp; tmp= tmp->next)
 
2267
          for (order_st *tmp= group_tmp; tmp; tmp= tmp->next)
2136
2268
          {
2137
2269
            if (*tmp->item == item)
2138
2270
              session->change_item_tree(tmp->item, new_item);
2172
2304
  @retval
2173
2305
    1    on error
2174
2306
*/
2175
 
bool Join::rollup_make_fields(List<Item> &fields_arg, List<Item> &sel_fields, Item_sum ***func)
 
2307
bool JOIN::rollup_make_fields(List<Item> &fields_arg, List<Item> &sel_fields, Item_sum ***func)
2176
2308
{
2177
2309
  List_iterator_fast<Item> it(fields_arg);
2178
2310
  Item *first_field= sel_fields.head();
2207
2339
    Item *item;
2208
2340
    List_iterator<Item> new_it(rollup.fields[pos]);
2209
2341
    Item **ref_array_start= rollup.ref_pointer_arrays[pos];
2210
 
    Order *start_group;
 
2342
    order_st *start_group;
2211
2343
 
2212
2344
    /* Point to first hidden field */
2213
2345
    Item **ref_array= ref_array_start + fields_arg.elements-1;
2249
2381
      else
2250
2382
      {
2251
2383
        /* Check if this is something that is part of this group by */
2252
 
        Order *group_tmp;
 
2384
        order_st *group_tmp;
2253
2385
        for (group_tmp= start_group, i= pos ;
2254
2386
                  group_tmp ; group_tmp= group_tmp->next, i++)
2255
2387
        {
2302
2434
  @retval
2303
2435
    1   If send_data_failed()
2304
2436
*/
2305
 
int Join::rollup_send_data(uint32_t idx)
 
2437
int JOIN::rollup_send_data(uint32_t idx)
2306
2438
{
2307
2439
  uint32_t i;
2308
2440
  for (i= send_group_parts ; i-- > idx ; )
2342
2474
  @retval
2343
2475
    1   if write_data_failed()
2344
2476
*/
2345
 
int Join::rollup_write_data(uint32_t idx, Table *table_arg)
 
2477
int JOIN::rollup_write_data(uint32_t idx, Table *table_arg)
2346
2478
{
2347
2479
  uint32_t i;
2348
2480
  for (i= send_group_parts ; i-- > idx ; )
2349
2481
  {
2350
2482
    /* Get reference pointers to sum functions in place */
2351
2483
    memcpy(ref_pointer_array, rollup.ref_pointer_arrays[i],
2352
 
           ref_pointer_array_size);
 
2484
     ref_pointer_array_size);
2353
2485
    if ((!having || having->val_int()))
2354
2486
    {
2355
2487
      int write_error;
2361
2493
          item->save_in_result_field(1);
2362
2494
      }
2363
2495
      copy_sum_funcs(sum_funcs_end[i+1], sum_funcs_end[i]);
2364
 
      if ((write_error= table_arg->cursor->insertRecord(table_arg->getInsertRecord())))
 
2496
      if ((write_error= table_arg->file->ha_write_row(table_arg->record[0])))
2365
2497
      {
2366
 
        my_error(ER_USE_SQL_BIG_RESULT, MYF(0));
2367
 
        return 1;
 
2498
  if (create_myisam_from_heap(session, table_arg,
 
2499
                                    tmp_table_param.start_recinfo,
 
2500
                                    &tmp_table_param.recinfo,
 
2501
                                    write_error, 0))
 
2502
    return 1;
2368
2503
      }
2369
2504
    }
2370
2505
  }
2377
2512
  clear results if there are not rows found for group
2378
2513
  (end_send_group/end_write_group)
2379
2514
*/
2380
 
void Join::clear()
 
2515
void JOIN::clear()
2381
2516
{
2382
2517
  clear_tables(this);
2383
2518
  copy_fields(&tmp_table_param);
2391
2526
}
2392
2527
 
2393
2528
/**
2394
 
  change select_result object of Join.
 
2529
  change select_result object of JOIN.
2395
2530
 
2396
2531
  @param res    new select_result object
2397
2532
 
2400
2535
  @retval
2401
2536
    true    error
2402
2537
*/
2403
 
bool Join::change_result(select_result *res)
 
2538
bool JOIN::change_result(select_result *res)
2404
2539
{
2405
2540
  result= res;
2406
2541
  if (result->prepare(fields_list, select_lex->master_unit()))
2411
2546
}
2412
2547
 
2413
2548
/**
2414
 
  Cache constant expressions in WHERE, HAVING, ON conditions.
 
2549
  Give error if we some tables are done with a full join.
 
2550
 
 
2551
  This is used by multi_table_update and multi_table_delete when running
 
2552
  in safe mode.
 
2553
 
 
2554
  @param join           Join condition
 
2555
 
 
2556
  @retval
 
2557
    0   ok
 
2558
  @retval
 
2559
    1   Error (full join used)
2415
2560
*/
2416
 
 
2417
 
void Join::cache_const_exprs()
 
2561
bool error_if_full_join(JOIN *join)
2418
2562
{
2419
 
  bool cache_flag= false;
2420
 
  bool *analyzer_arg= &cache_flag;
2421
 
 
2422
 
  /* No need in cache if all tables are constant. */
2423
 
  if (const_tables == tables)
2424
 
    return;
2425
 
 
2426
 
  if (conds)
2427
 
    conds->compile(&Item::cache_const_expr_analyzer, (unsigned char **)&analyzer_arg,
2428
 
                  &Item::cache_const_expr_transformer, (unsigned char *)&cache_flag);
2429
 
  cache_flag= false;
2430
 
  if (having)
2431
 
    having->compile(&Item::cache_const_expr_analyzer, (unsigned char **)&analyzer_arg,
2432
 
                    &Item::cache_const_expr_transformer, (unsigned char *)&cache_flag);
2433
 
 
2434
 
  for (JoinTable *tab= join_tab + const_tables; tab < join_tab + tables ; tab++)
 
2563
  for (JOIN_TAB *tab= join->join_tab, *end= join->join_tab+join->tables; tab < end; tab++)
2435
2564
  {
2436
 
    if (*tab->on_expr_ref)
 
2565
    if (tab->type == JT_ALL && (!tab->select || !tab->select->quick))
2437
2566
    {
2438
 
      cache_flag= false;
2439
 
      (*tab->on_expr_ref)->compile(&Item::cache_const_expr_analyzer,
2440
 
                                 (unsigned char **)&analyzer_arg,
2441
 
                                 &Item::cache_const_expr_transformer,
2442
 
                                 (unsigned char *)&cache_flag);
 
2567
      my_message(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE,
 
2568
                 ER(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE), MYF(0));
 
2569
      return(1);
2443
2570
    }
2444
2571
  }
 
2572
  return(0);
2445
2573
}
2446
2574
 
2447
2575
/**
2455
2583
  applicable to the partial record on hand and in case of success
2456
2584
  submit this record to the next level of the nested loop.
2457
2585
*/
2458
 
enum_nested_loop_state evaluate_join_record(Join *join, JoinTable *join_tab, int error)
 
2586
enum_nested_loop_state evaluate_join_record(JOIN *join, JOIN_TAB *join_tab, int error)
2459
2587
{
2460
2588
  bool not_used_in_distinct= join_tab->not_used_in_distinct;
2461
2589
  ha_rows found_records= join->found_records;
2465
2593
    return NESTED_LOOP_ERROR;
2466
2594
  if (error < 0)
2467
2595
    return NESTED_LOOP_NO_MORE_ROWS;
2468
 
  if (join->session->getKilled())                       // Aborted by user
 
2596
  if (join->session->killed)                    // Aborted by user
2469
2597
  {
2470
2598
    join->session->send_kill_message();
2471
 
    return NESTED_LOOP_KILLED;
 
2599
    return NESTED_LOOP_KILLED;               /* purecov: inspected */
2472
2600
  }
2473
2601
  if (!select_cond || select_cond->val_int())
2474
2602
  {
2483
2611
        The while condition is always false if join_tab is not
2484
2612
        the last inner join table of an outer join operation.
2485
2613
      */
2486
 
      JoinTable *first_unmatched= join_tab->first_unmatched;
 
2614
      JOIN_TAB *first_unmatched= join_tab->first_unmatched;
2487
2615
      /*
2488
2616
        Mark that a match for current outer table is found.
2489
2617
        This activates push down conditional predicates attached
2490
2618
        to the all inner tables of the outer join.
2491
2619
      */
2492
2620
      first_unmatched->found= 1;
2493
 
      for (JoinTable *tab= first_unmatched; tab <= join_tab; tab++)
 
2621
      for (JOIN_TAB *tab= first_unmatched; tab <= join_tab; tab++)
2494
2622
      {
2495
2623
        if (tab->table->reginfo.not_exists_optimize)
2496
2624
          return NESTED_LOOP_NO_MORE_ROWS;
2526
2654
      join_tab->first_unmatched= first_unmatched;
2527
2655
    }
2528
2656
 
2529
 
    JoinTable *return_tab= join->return_tab;
 
2657
    JOIN_TAB *return_tab= join->return_tab;
2530
2658
    join_tab->found_match= true;
 
2659
    if (join_tab->check_weed_out_table)
 
2660
    {
 
2661
      int res= do_sj_dups_weedout(join->session, join_tab->check_weed_out_table);
 
2662
      if (res == -1)
 
2663
        return NESTED_LOOP_ERROR;
 
2664
      if (res == 1)
 
2665
        return NESTED_LOOP_OK;
 
2666
    }
 
2667
    else if (join_tab->do_firstmatch)
 
2668
    {
 
2669
      /*
 
2670
        We should return to the join_tab->do_firstmatch after we have
 
2671
        enumerated all the suffixes for current prefix row combination
 
2672
      */
 
2673
      return_tab= join_tab->do_firstmatch;
 
2674
    }
2531
2675
 
2532
2676
    /*
2533
2677
      It was not just a return to lower loop level when one
2558
2702
        return NESTED_LOOP_NO_MORE_ROWS;
2559
2703
    }
2560
2704
    else
2561
 
      join_tab->read_record.cursor->unlock_row();
 
2705
      join_tab->read_record.file->unlock_row();
2562
2706
  }
2563
2707
  else
2564
2708
  {
2568
2712
    */
2569
2713
    join->examined_rows++;
2570
2714
    join->session->row_count++;
2571
 
    join_tab->read_record.cursor->unlock_row();
 
2715
    join_tab->read_record.file->unlock_row();
2572
2716
  }
2573
2717
  return NESTED_LOOP_OK;
2574
2718
}
2579
2723
    level of the nested loop. This function is used in case we have
2580
2724
    an OUTER join and no matching record was found.
2581
2725
*/
2582
 
enum_nested_loop_state evaluate_null_complemented_join_record(Join *join, JoinTable *join_tab)
 
2726
enum_nested_loop_state evaluate_null_complemented_join_record(JOIN *join, JOIN_TAB *join_tab)
2583
2727
{
2584
2728
  /*
2585
2729
    The table join_tab is the first inner table of a outer join operation
2586
2730
    and no matches has been found for the current outer row.
2587
2731
  */
2588
 
  JoinTable *last_inner_tab= join_tab->last_inner;
 
2732
  JOIN_TAB *last_inner_tab= join_tab->last_inner;
2589
2733
  /* Cache variables for faster loop */
2590
2734
  COND *select_cond;
2591
2735
  for ( ; join_tab <= last_inner_tab ; join_tab++)
2610
2754
  */
2611
2755
  for ( ; ; )
2612
2756
  {
2613
 
    JoinTable *first_unmatched= join_tab->first_unmatched;
 
2757
    JOIN_TAB *first_unmatched= join_tab->first_unmatched;
2614
2758
    if ((first_unmatched= first_unmatched->first_upper) && first_unmatched->last_inner != join_tab)
2615
2759
      first_unmatched= 0;
2616
2760
    join_tab->first_unmatched= first_unmatched;
2617
2761
    if (! first_unmatched)
2618
2762
      break;
2619
2763
    first_unmatched->found= 1;
2620
 
    for (JoinTable *tab= first_unmatched; tab <= join_tab; tab++)
 
2764
    for (JOIN_TAB *tab= first_unmatched; tab <= join_tab; tab++)
2621
2765
    {
2622
2766
      if (tab->select_cond && !tab->select_cond->val_int())
2623
2767
      {
2635
2779
  return (*join_tab->next_select)(join, join_tab+1, 0);
2636
2780
}
2637
2781
 
2638
 
enum_nested_loop_state flush_cached_records(Join *join, JoinTable *join_tab, bool skip_last)
 
2782
enum_nested_loop_state flush_cached_records(JOIN *join, JOIN_TAB *join_tab, bool skip_last)
2639
2783
{
2640
2784
  enum_nested_loop_state rc= NESTED_LOOP_OK;
2641
2785
  int error;
2642
 
  ReadRecord *info;
 
2786
  READ_RECORD *info;
2643
2787
 
2644
2788
  join_tab->table->null_row= 0;
2645
2789
  if (!join_tab->cache.records)
2646
 
  {
2647
2790
    return NESTED_LOOP_OK;                      /* Nothing to do */
2648
 
  }
2649
 
 
2650
2791
  if (skip_last)
2651
 
  {
2652
 
    (void) join_tab->cache.store_record_in_cache(); // Must save this for later
2653
 
  }
2654
 
 
2655
 
 
 
2792
    (void) store_record_in_cache(&join_tab->cache); // Must save this for later
2656
2793
  if (join_tab->use_quick == 2)
2657
2794
  {
2658
2795
    if (join_tab->select->quick)
2664
2801
  /* read through all records */
2665
2802
  if ((error=join_init_read_record(join_tab)))
2666
2803
  {
2667
 
    join_tab->cache.reset_cache_write();
 
2804
    reset_cache_write(&join_tab->cache);
2668
2805
    return error < 0 ? NESTED_LOOP_NO_MORE_ROWS: NESTED_LOOP_ERROR;
2669
2806
  }
2670
2807
 
2671
 
  for (JoinTable *tmp=join->join_tab; tmp != join_tab ; tmp++)
 
2808
  for (JOIN_TAB *tmp=join->join_tab; tmp != join_tab ; tmp++)
2672
2809
  {
2673
2810
    tmp->status=tmp->table->status;
2674
2811
    tmp->table->status=0;
2677
2814
  info= &join_tab->read_record;
2678
2815
  do
2679
2816
  {
2680
 
    if (join->session->getKilled())
 
2817
    if (join->session->killed)
2681
2818
    {
2682
2819
      join->session->send_kill_message();
2683
 
      return NESTED_LOOP_KILLED;
 
2820
      return NESTED_LOOP_KILLED; // Aborted by user /* purecov: inspected */
2684
2821
    }
2685
 
    optimizer::SqlSelect *select= join_tab->select;
 
2822
    SQL_SELECT *select=join_tab->select;
2686
2823
    if (rc == NESTED_LOOP_OK &&
2687
2824
        (!join_tab->cache.select || !join_tab->cache.select->skip_record()))
2688
2825
    {
2689
2826
      uint32_t i;
2690
 
      join_tab->cache.reset_cache_read();
 
2827
      reset_cache_read(&join_tab->cache);
2691
2828
      for (i=(join_tab->cache.records- (skip_last ? 1 : 0)) ; i-- > 0 ;)
2692
2829
      {
2693
 
              join_tab->readCachedRecord();
 
2830
              read_cached_record(join_tab);
2694
2831
              if (!select || !select->skip_record())
2695
2832
        {
2696
2833
          int res= 0;
2697
 
 
2698
 
          rc= (join_tab->next_select)(join,join_tab+1,0);
2699
 
          if (rc != NESTED_LOOP_OK && rc != NESTED_LOOP_NO_MORE_ROWS)
 
2834
          if (!join_tab->check_weed_out_table ||
 
2835
              !(res= do_sj_dups_weedout(join->session, join_tab->check_weed_out_table)))
2700
2836
          {
2701
 
            join_tab->cache.reset_cache_write();
2702
 
            return rc;
 
2837
            rc= (join_tab->next_select)(join,join_tab+1,0);
 
2838
            if (rc != NESTED_LOOP_OK && rc != NESTED_LOOP_NO_MORE_ROWS)
 
2839
            {
 
2840
              reset_cache_write(&join_tab->cache);
 
2841
              return rc;
 
2842
            }
2703
2843
          }
2704
 
 
2705
2844
          if (res == -1)
2706
2845
            return NESTED_LOOP_ERROR;
2707
2846
        }
2710
2849
  } while (!(error=info->read_record(info)));
2711
2850
 
2712
2851
  if (skip_last)
2713
 
    join_tab->readCachedRecord();               // Restore current record
2714
 
  join_tab->cache.reset_cache_write();
 
2852
    read_cached_record(join_tab);               // Restore current record
 
2853
  reset_cache_write(&join_tab->cache);
2715
2854
  if (error > 0)                                // Fatal error
2716
 
    return NESTED_LOOP_ERROR;
2717
 
  for (JoinTable *tmp2=join->join_tab; tmp2 != join_tab ; tmp2++)
 
2855
    return NESTED_LOOP_ERROR;                   /* purecov: inspected */
 
2856
  for (JOIN_TAB *tmp2=join->join_tab; tmp2 != join_tab ; tmp2++)
2718
2857
    tmp2->table->status=tmp2->status;
2719
2858
  return NESTED_LOOP_OK;
2720
2859
}
2743
2882
                               operation.
2744
2883
   All return values except NESTED_LOOP_OK abort the nested loop.
2745
2884
*****************************************************************************/
2746
 
enum_nested_loop_state end_send(Join *join, JoinTable *, bool end_of_records)
 
2885
enum_nested_loop_state end_send(JOIN *join, JOIN_TAB *, bool end_of_records)
2747
2886
{
2748
2887
  if (! end_of_records)
2749
2888
  {
2754
2893
    if (join->do_send_rows)
2755
2894
      error=join->result->send_data(*join->fields);
2756
2895
    if (error)
2757
 
      return NESTED_LOOP_ERROR;
 
2896
      return NESTED_LOOP_ERROR; /* purecov: inspected */
2758
2897
    if (++join->send_records >= join->unit->select_limit_cnt && join->do_send_rows)
2759
2898
    {
2760
2899
      if (join->select_options & OPTION_FOUND_ROWS)
2761
2900
      {
2762
 
        JoinTable *jt=join->join_tab;
 
2901
        JOIN_TAB *jt=join->join_tab;
2763
2902
        if ((join->tables == 1) && !join->tmp_table && !join->sort_and_group
2764
2903
            && !join->send_group_parts && !join->having && !jt->select_cond &&
2765
2904
            !(jt->select && jt->select->quick) &&
2766
 
            (jt->table->cursor->getEngine()->check_flag(HTON_BIT_STATS_RECORDS_IS_EXACT)) &&
 
2905
            (jt->table->file->ha_table_flags() & HA_STATS_RECORDS_IS_EXACT) &&
2767
2906
                  (jt->ref.key < 0))
2768
2907
        {
2769
2908
          /* Join over all rows in table;  Return number of found rows */
2778
2917
          }
2779
2918
          else
2780
2919
          {
2781
 
            table->cursor->info(HA_STATUS_VARIABLE);
2782
 
            join->send_records= table->cursor->stats.records;
 
2920
            table->file->info(HA_STATUS_VARIABLE);
 
2921
            join->send_records= table->file->stats.records;
2783
2922
          }
2784
2923
        }
2785
2924
        else
2805
2944
  return NESTED_LOOP_OK;
2806
2945
}
2807
2946
 
2808
 
enum_nested_loop_state end_write(Join *join, JoinTable *, bool end_of_records)
 
2947
enum_nested_loop_state end_write(JOIN *join, JOIN_TAB *, bool end_of_records)
2809
2948
{
2810
2949
  Table *table= join->tmp_table;
2811
2950
 
2812
 
  if (join->session->getKilled())                       // Aborted by user
 
2951
  if (join->session->killed)                    // Aborted by user
2813
2952
  {
2814
2953
    join->session->send_kill_message();
2815
 
    return NESTED_LOOP_KILLED;
 
2954
    return NESTED_LOOP_KILLED;             /* purecov: inspected */
2816
2955
  }
2817
2956
  if (!end_of_records)
2818
2957
  {
2819
2958
    copy_fields(&join->tmp_table_param);
2820
 
    if (copy_funcs(join->tmp_table_param.items_to_copy, join->session))
2821
 
      return NESTED_LOOP_ERROR;
 
2959
    copy_funcs(join->tmp_table_param.items_to_copy);
2822
2960
    if (!join->having || join->having->val_int())
2823
2961
    {
2824
2962
      int error;
2825
2963
      join->found_records++;
2826
 
      if ((error=table->cursor->insertRecord(table->getInsertRecord())))
 
2964
      if ((error=table->file->ha_write_row(table->record[0])))
2827
2965
      {
2828
 
        if (!table->cursor->is_fatal_error(error, HA_CHECK_DUP))
2829
 
        {
2830
 
          return NESTED_LOOP_OK;
2831
 
        }
2832
 
 
2833
 
        my_error(ER_USE_SQL_BIG_RESULT, MYF(0));
2834
 
        return NESTED_LOOP_ERROR;        // Table is_full error
 
2966
        if (!table->file->is_fatal_error(error, HA_CHECK_DUP))
 
2967
          goto end;
 
2968
        if (create_myisam_from_heap(join->session, table,
 
2969
                                          join->tmp_table_param.start_recinfo,
 
2970
                                          &join->tmp_table_param.recinfo,
 
2971
                  error, 1))
 
2972
          return NESTED_LOOP_ERROR;        // Not a table_is_full error
 
2973
        table->s->uniques= 0;                   // To ensure rows are the same
2835
2974
      }
2836
2975
      if (++join->send_records >= join->tmp_table_param.end_write_records && join->do_send_rows)
2837
2976
      {
2843
2982
      }
2844
2983
    }
2845
2984
  }
2846
 
 
 
2985
end:
2847
2986
  return NESTED_LOOP_OK;
2848
2987
}
2849
2988
 
2850
2989
/** Group by searching after group record and updating it if possible. */
2851
 
enum_nested_loop_state end_update(Join *join, JoinTable *, bool end_of_records)
 
2990
enum_nested_loop_state end_update(JOIN *join, JOIN_TAB *, bool end_of_records)
2852
2991
{
2853
2992
  Table *table= join->tmp_table;
2854
 
  Order *group;
 
2993
  order_st *group;
2855
2994
  int   error;
2856
2995
 
2857
2996
  if (end_of_records)
2858
2997
    return NESTED_LOOP_OK;
2859
 
  if (join->session->getKilled())                       // Aborted by user
 
2998
  if (join->session->killed)                    // Aborted by user
2860
2999
  {
2861
3000
    join->session->send_kill_message();
2862
 
    return NESTED_LOOP_KILLED;
 
3001
    return NESTED_LOOP_KILLED;             /* purecov: inspected */
2863
3002
  }
2864
3003
 
2865
3004
  join->found_records++;
2873
3012
    if (item->maybe_null)
2874
3013
      group->buff[-1]= (char) group->field->is_null();
2875
3014
  }
2876
 
  if (!table->cursor->index_read_map(table->getUpdateRecord(),
 
3015
  if (!table->file->index_read_map(table->record[1],
2877
3016
                                   join->tmp_table_param.group_buff,
2878
3017
                                   HA_WHOLE_KEY,
2879
3018
                                   HA_READ_KEY_EXACT))
2880
3019
  {                                             /* Update old record */
2881
3020
    table->restoreRecord();
2882
3021
    update_tmptable_sum_func(join->sum_funcs,table);
2883
 
    if ((error= table->cursor->updateRecord(table->getUpdateRecord(),
2884
 
                                          table->getInsertRecord())))
 
3022
    if ((error= table->file->ha_update_row(table->record[1],
 
3023
                                          table->record[0])))
2885
3024
    {
2886
 
      table->print_error(error,MYF(0));
2887
 
      return NESTED_LOOP_ERROR;
 
3025
      table->file->print_error(error,MYF(0));   /* purecov: inspected */
 
3026
      return NESTED_LOOP_ERROR;            /* purecov: inspected */
2888
3027
    }
2889
3028
    return NESTED_LOOP_OK;
2890
3029
  }
2894
3033
    We can't copy all data as the key may have different format
2895
3034
    as the row data (for example as with VARCHAR keys)
2896
3035
  */
2897
 
  KeyPartInfo *key_part;
 
3036
  KEY_PART_INFO *key_part;
2898
3037
  for (group=table->group,key_part=table->key_info[0].key_part;
2899
3038
       group ;
2900
3039
       group=group->next,key_part++)
2901
3040
  {
2902
3041
    if (key_part->null_bit)
2903
 
      memcpy(table->getInsertRecord()+key_part->offset, group->buff, 1);
 
3042
      memcpy(table->record[0]+key_part->offset, group->buff, 1);
2904
3043
  }
2905
3044
  init_tmptable_sum_functions(join->sum_funcs);
2906
 
  if (copy_funcs(join->tmp_table_param.items_to_copy, join->session))
2907
 
    return NESTED_LOOP_ERROR;
2908
 
  if ((error=table->cursor->insertRecord(table->getInsertRecord())))
 
3045
  copy_funcs(join->tmp_table_param.items_to_copy);
 
3046
  if ((error=table->file->ha_write_row(table->record[0])))
2909
3047
  {
2910
 
    my_error(ER_USE_SQL_BIG_RESULT, MYF(0));
2911
 
    return NESTED_LOOP_ERROR;        // Table is_full error
 
3048
    if (create_myisam_from_heap(join->session, table,
 
3049
                                join->tmp_table_param.start_recinfo,
 
3050
                                &join->tmp_table_param.recinfo,
 
3051
                                error, 0))
 
3052
      return NESTED_LOOP_ERROR;            // Not a table_is_full error
 
3053
    /* Change method to update rows */
 
3054
    table->file->ha_index_init(0, 0);
 
3055
    join->join_tab[join->tables-1].next_select= end_unique_update;
2912
3056
  }
2913
3057
  join->send_records++;
2914
3058
  return NESTED_LOOP_OK;
2915
3059
}
2916
3060
 
2917
3061
/** Like end_update, but this is done with unique constraints instead of keys.  */
2918
 
enum_nested_loop_state end_unique_update(Join *join, JoinTable *, bool end_of_records)
 
3062
enum_nested_loop_state end_unique_update(JOIN *join, JOIN_TAB *, bool end_of_records)
2919
3063
{
2920
3064
  Table *table= join->tmp_table;
2921
3065
  int   error;
2922
3066
 
2923
3067
  if (end_of_records)
2924
3068
    return NESTED_LOOP_OK;
2925
 
  if (join->session->getKilled())                       // Aborted by user
 
3069
  if (join->session->killed)                    // Aborted by user
2926
3070
  {
2927
3071
    join->session->send_kill_message();
2928
 
    return NESTED_LOOP_KILLED;
 
3072
    return NESTED_LOOP_KILLED;             /* purecov: inspected */
2929
3073
  }
2930
3074
 
2931
3075
  init_tmptable_sum_functions(join->sum_funcs);
2932
3076
  copy_fields(&join->tmp_table_param);          // Groups are copied twice.
2933
 
  if (copy_funcs(join->tmp_table_param.items_to_copy, join->session))
2934
 
    return NESTED_LOOP_ERROR;
 
3077
  copy_funcs(join->tmp_table_param.items_to_copy);
2935
3078
 
2936
 
  if (!(error= table->cursor->insertRecord(table->getInsertRecord())))
 
3079
  if (!(error= table->file->ha_write_row(table->record[0])))
2937
3080
    join->send_records++;                       // New group
2938
3081
  else
2939
3082
  {
2940
 
    if ((int) table->get_dup_key(error) < 0)
 
3083
    if ((int) table->file->get_dup_key(error) < 0)
2941
3084
    {
2942
 
      table->print_error(error,MYF(0));
2943
 
      return NESTED_LOOP_ERROR;
 
3085
      table->file->print_error(error,MYF(0));   /* purecov: inspected */
 
3086
      return NESTED_LOOP_ERROR;            /* purecov: inspected */
2944
3087
    }
2945
 
    if (table->cursor->rnd_pos(table->getUpdateRecord(),table->cursor->dup_ref))
 
3088
    if (table->file->rnd_pos(table->record[1],table->file->dup_ref))
2946
3089
    {
2947
 
      table->print_error(error,MYF(0));
2948
 
      return NESTED_LOOP_ERROR;
 
3090
      table->file->print_error(error,MYF(0));   /* purecov: inspected */
 
3091
      return NESTED_LOOP_ERROR;            /* purecov: inspected */
2949
3092
    }
2950
3093
    table->restoreRecord();
2951
3094
    update_tmptable_sum_func(join->sum_funcs,table);
2952
 
    if ((error= table->cursor->updateRecord(table->getUpdateRecord(),
2953
 
                                          table->getInsertRecord())))
 
3095
    if ((error= table->file->ha_update_row(table->record[1],
 
3096
                                          table->record[0])))
2954
3097
    {
2955
 
      table->print_error(error,MYF(0));
2956
 
      return NESTED_LOOP_ERROR;
 
3098
      table->file->print_error(error,MYF(0));   /* purecov: inspected */
 
3099
      return NESTED_LOOP_ERROR;            /* purecov: inspected */
2957
3100
    }
2958
3101
  }
2959
3102
  return NESTED_LOOP_OK;
2971
3114
  @retval
2972
3115
    1   failed
2973
3116
*/
2974
 
static bool make_group_fields(Join *main_join, Join *curr_join)
 
3117
static bool make_group_fields(JOIN *main_join, JOIN *curr_join)
2975
3118
{
2976
3119
  if (main_join->group_fields_cache.elements)
2977
3120
  {
2981
3124
  else
2982
3125
  {
2983
3126
    if (alloc_group_fields(curr_join, curr_join->group_list))
2984
 
      return 1;
 
3127
      return (1);
2985
3128
    main_join->group_fields_cache= curr_join->group_fields;
2986
3129
  }
2987
3130
  return (0);
2990
3133
/**
2991
3134
  calc how big buffer we need for comparing group entries.
2992
3135
*/
2993
 
static void calc_group_buffer(Join *join, Order *group)
 
3136
static void calc_group_buffer(JOIN *join,order_st *group)
2994
3137
{
2995
3138
  uint32_t key_length=0, parts=0, null_parts=0;
2996
3139
 
3016
3159
      case REAL_RESULT:
3017
3160
        key_length+= sizeof(double);
3018
3161
        break;
3019
 
 
3020
3162
      case INT_RESULT:
3021
3163
        key_length+= sizeof(int64_t);
3022
3164
        break;
3023
 
 
3024
3165
      case DECIMAL_RESULT:
3025
3166
        key_length+= my_decimal_get_binary_size(group_item->max_length -
3026
3167
                                                (group_item->decimals ? 1 : 0),
3027
3168
                                                group_item->decimals);
3028
3169
        break;
3029
 
 
3030
3170
      case STRING_RESULT:
3031
 
        {
3032
 
          enum enum_field_types type= group_item->field_type();
 
3171
      {
 
3172
        enum enum_field_types type= group_item->field_type();
 
3173
        /*
 
3174
          As items represented as DATE/TIME fields in the group buffer
 
3175
          have STRING_RESULT result type, we increase the length
 
3176
          by 8 as maximum pack length of such fields.
 
3177
        */
 
3178
        if (type == DRIZZLE_TYPE_DATE ||
 
3179
            type == DRIZZLE_TYPE_DATETIME ||
 
3180
            type == DRIZZLE_TYPE_TIMESTAMP)
 
3181
        {
 
3182
          key_length+= 8;
 
3183
        }
 
3184
        else
 
3185
        {
3033
3186
          /*
3034
 
            As items represented as DATE/TIME fields in the group buffer
3035
 
            have STRING_RESULT result type, we increase the length
3036
 
            by 8 as maximum pack length of such fields.
 
3187
            Group strings are taken as varstrings and require an length field.
 
3188
            A field is not yet created by create_tmp_field()
 
3189
            and the sizes should match up.
3037
3190
          */
3038
 
          if (type == DRIZZLE_TYPE_DATE ||
3039
 
              type == DRIZZLE_TYPE_DATETIME ||
3040
 
              type == DRIZZLE_TYPE_TIMESTAMP)
3041
 
          {
3042
 
            key_length+= 8;
3043
 
          }
3044
 
          else
3045
 
          {
3046
 
            /*
3047
 
              Group strings are taken as varstrings and require an length field.
3048
 
              A field is not yet created by create_tmp_field()
3049
 
              and the sizes should match up.
3050
 
            */
3051
 
            key_length+= group_item->max_length + HA_KEY_BLOB_LENGTH;
3052
 
          }
3053
 
          break;
 
3191
          key_length+= group_item->max_length + HA_KEY_BLOB_LENGTH;
3054
3192
        }
3055
 
 
3056
 
      case ROW_RESULT:
 
3193
        break;
 
3194
      }
 
3195
      default:
3057
3196
        /* This case should never be choosen */
3058
3197
        assert(0);
3059
3198
        my_error(ER_OUT_OF_RESOURCES, MYF(ME_FATALERROR));
3060
3199
      }
3061
3200
    }
3062
 
 
3063
3201
    parts++;
3064
 
 
3065
3202
    if (group_item->maybe_null)
3066
3203
      null_parts++;
3067
3204
  }
3068
 
 
3069
3205
  join->tmp_table_param.group_length=key_length+null_parts;
3070
3206
  join->tmp_table_param.group_parts=parts;
3071
3207
  join->tmp_table_param.group_null_parts=null_parts;
3076
3212
 
3077
3213
  Groups are saved in reverse order for easyer check loop.
3078
3214
*/
3079
 
static bool alloc_group_fields(Join *join, Order *group)
 
3215
static bool alloc_group_fields(JOIN *join,order_st *group)
3080
3216
{
3081
3217
  if (group)
3082
3218
  {
3083
3219
    for (; group ; group=group->next)
3084
3220
    {
3085
 
      Cached_item *tmp= new_Cached_item(join->session, *group->item);
 
3221
      Cached_item *tmp=new_Cached_item(join->session, *group->item, false);
3086
3222
      if (!tmp || join->group_fields.push_front(tmp))
3087
3223
        return true;
3088
3224
    }
3091
3227
  return false;
3092
3228
}
3093
3229
 
3094
 
static uint32_t cache_record_length(Join *join,uint32_t idx)
 
3230
/**
 
3231
  @todo
 
3232
  - TODO: this function is here only temporarily until 'greedy_search' is
 
3233
  tested and accepted.
 
3234
 
 
3235
  RETURN VALUES
 
3236
    false       ok
 
3237
    true        Fatal error
 
3238
*/
 
3239
static bool find_best(JOIN *join,table_map rest_tables,uint32_t idx,double record_count, double read_time)
 
3240
{
 
3241
  Session *session= join->session;
 
3242
  if (session->killed)
 
3243
    return(true);
 
3244
  if (!rest_tables)
 
3245
  {
 
3246
    read_time+=record_count/(double) TIME_FOR_COMPARE;
 
3247
    if (join->sort_by_table &&
 
3248
  join->sort_by_table !=
 
3249
  join->positions[join->const_tables].table->table)
 
3250
      read_time+=record_count;      // We have to make a temp table
 
3251
    if (read_time < join->best_read)
 
3252
    {
 
3253
      memcpy(join->best_positions, join->positions, sizeof(POSITION)*idx);
 
3254
      join->best_read= read_time - 0.001;
 
3255
    }
 
3256
    return(false);
 
3257
  }
 
3258
  if (read_time+record_count/(double) TIME_FOR_COMPARE >= join->best_read)
 
3259
    return(false);          /* Found better before */
 
3260
 
 
3261
  JOIN_TAB *s;
 
3262
  double best_record_count=DBL_MAX,best_read_time=DBL_MAX;
 
3263
  for (JOIN_TAB **pos=join->best_ref+idx ; (s=*pos) ; pos++)
 
3264
  {
 
3265
    table_map real_table_bit=s->table->map;
 
3266
    if ((rest_tables & real_table_bit) && !(rest_tables & s->dependent) &&
 
3267
        (!idx|| !check_interleaving_with_nj(join->positions[idx-1].table, s)))
 
3268
    {
 
3269
      double records, best;
 
3270
      advance_sj_state(rest_tables, s);
 
3271
      best_access_path(join, s, session, rest_tables, idx, record_count,
 
3272
                       read_time);
 
3273
      records= join->positions[idx].records_read;
 
3274
      best= join->positions[idx].read_time;
 
3275
      /*
 
3276
  Go to the next level only if there hasn't been a better key on
 
3277
  this level! This will cut down the search for a lot simple cases!
 
3278
      */
 
3279
      double current_record_count=record_count*records;
 
3280
      double current_read_time=read_time+best;
 
3281
      if (best_record_count > current_record_count ||
 
3282
    best_read_time > current_read_time ||
 
3283
    (idx == join->const_tables && s->table == join->sort_by_table))
 
3284
      {
 
3285
  if (best_record_count >= current_record_count &&
 
3286
      best_read_time >= current_read_time &&
 
3287
      (!(s->key_dependent & rest_tables) || records < 2.0))
 
3288
  {
 
3289
    best_record_count=current_record_count;
 
3290
    best_read_time=current_read_time;
 
3291
  }
 
3292
        std::swap(join->best_ref[idx], *pos);
 
3293
  if (find_best(join,rest_tables & ~real_table_bit,idx+1,
 
3294
                      current_record_count,current_read_time))
 
3295
          return(true);
 
3296
        std::swap(join->best_ref[idx], *pos);
 
3297
      }
 
3298
      restore_prev_nj_state(s);
 
3299
      restore_prev_sj_state(rest_tables, s);
 
3300
      if (join->select_options & SELECT_STRAIGHT_JOIN)
 
3301
  break;        // Don't test all combinations
 
3302
    }
 
3303
  }
 
3304
  return(false);
 
3305
}
 
3306
 
 
3307
static uint32_t cache_record_length(JOIN *join,uint32_t idx)
3095
3308
{
3096
3309
  uint32_t length=0;
3097
 
  JoinTable **pos,**end;
 
3310
  JOIN_TAB **pos,**end;
3098
3311
  Session *session=join->session;
3099
3312
 
3100
3313
  for (pos=join->best_ref+join->const_tables,end=join->best_ref+idx ;
3101
3314
       pos != end ;
3102
3315
       pos++)
3103
3316
  {
3104
 
    JoinTable *join_tab= *pos;
 
3317
    JOIN_TAB *join_tab= *pos;
3105
3318
    if (!join_tab->used_fieldlength)    /* Not calced yet */
3106
3319
      calc_used_field_length(session, join_tab);
3107
3320
    length+=join_tab->used_fieldlength;
3159
3372
  RETURN
3160
3373
    Expected number of row combinations
3161
3374
*/
3162
 
static double prev_record_reads(Join *join, uint32_t idx, table_map found_ref)
 
3375
static double prev_record_reads(JOIN *join, uint32_t idx, table_map found_ref)
3163
3376
{
3164
3377
  double found=1.0;
3165
 
  optimizer::Position *pos_end= join->getSpecificPosInPartialPlan(-1);
3166
 
  for (optimizer::Position *pos= join->getSpecificPosInPartialPlan(idx - 1); 
3167
 
       pos != pos_end; 
3168
 
       pos--)
 
3378
  POSITION *pos_end= join->positions - 1;
 
3379
  for (POSITION *pos= join->positions + idx - 1; pos != pos_end; pos--)
3169
3380
  {
3170
 
    if (pos->examinePosition(found_ref))
 
3381
    if (pos->table->table->map & found_ref)
3171
3382
    {
3172
 
      found_ref|= pos->getRefDependMap();
 
3383
      found_ref|= pos->ref_depend_map;
3173
3384
      /*
3174
 
        For the case of "t1 LEFT Join t2 ON ..." where t2 is a const table
 
3385
        For the case of "t1 LEFT JOIN t2 ON ..." where t2 is a const table
3175
3386
        with no matching row we will get position[t2].records_read==0.
3176
3387
        Actually the size of output is one null-complemented row, therefore
3177
3388
        we will use value of 1 whenever we get records_read==0.
3186
3397
          is an inprecise estimate and adding 1 (or, in the worst case,
3187
3398
          #max_nested_outer_joins=64-1) will not make it any more precise.
3188
3399
      */
3189
 
      if (pos->getFanout() > DBL_EPSILON)
3190
 
        found*= pos->getFanout();
 
3400
      if (pos->records_read > DBL_EPSILON)
 
3401
        found*= pos->records_read;
3191
3402
    }
3192
3403
  }
3193
3404
  return found;
3196
3407
/**
3197
3408
  Set up join struct according to best position.
3198
3409
*/
3199
 
static bool get_best_combination(Join *join)
 
3410
static bool get_best_combination(JOIN *join)
3200
3411
{
3201
3412
  uint32_t i,tablenr;
3202
3413
  table_map used_tables;
3203
 
  JoinTable *join_tab,*j;
3204
 
  optimizer::KeyUse *keyuse;
 
3414
  JOIN_TAB *join_tab,*j;
 
3415
  KEYUSE *keyuse;
3205
3416
  uint32_t table_count;
3206
3417
  Session *session=join->session;
3207
 
  optimizer::Position cur_pos;
3208
3418
 
3209
3419
  table_count=join->tables;
3210
3420
  if (!(join->join_tab=join_tab=
3211
 
  (JoinTable*) session->alloc(sizeof(JoinTable)*table_count)))
 
3421
  (JOIN_TAB*) session->alloc(sizeof(JOIN_TAB)*table_count)))
3212
3422
    return(true);
3213
3423
 
3214
3424
  join->full_join=0;
3217
3427
  for (j=join_tab, tablenr=0 ; tablenr < table_count ; tablenr++,j++)
3218
3428
  {
3219
3429
    Table *form;
3220
 
    cur_pos= join->getPosFromOptimalPlan(tablenr);
3221
 
    *j= *cur_pos.getJoinTable();
 
3430
    *j= *join->best_positions[tablenr].table;
3222
3431
    form=join->table[tablenr]=j->table;
3223
3432
    used_tables|= form->map;
3224
3433
    form->reginfo.join_tab=j;
3225
3434
    if (!*j->on_expr_ref)
3226
 
      form->reginfo.not_exists_optimize=0;  // Only with LEFT Join
3227
 
    if (j->type == AM_CONST)
 
3435
      form->reginfo.not_exists_optimize=0;  // Only with LEFT JOIN
 
3436
    if (j->type == JT_CONST)
3228
3437
      continue;         // Handled in make_join_stat..
3229
3438
 
3230
3439
    j->ref.key = -1;
3231
3440
    j->ref.key_parts=0;
3232
3441
 
3233
 
    if (j->type == AM_SYSTEM)
 
3442
    if (j->type == JT_SYSTEM)
3234
3443
      continue;
3235
 
    if (j->keys.none() || ! (keyuse= cur_pos.getKeyUse()))
 
3444
    if (j->keys.none() || !(keyuse= join->best_positions[tablenr].key))
3236
3445
    {
3237
 
      j->type= AM_ALL;
 
3446
      j->type=JT_ALL;
3238
3447
      if (tablenr != join->const_tables)
3239
3448
        join->full_join=1;
3240
3449
    }
3249
3458
}
3250
3459
 
3251
3460
/** Save const tables first as used tables. */
3252
 
static void set_position(Join *join,
3253
 
                         uint32_t idx,
3254
 
                         JoinTable *table,
3255
 
                         optimizer::KeyUse *key)
 
3461
static void set_position(JOIN *join,uint32_t idx,JOIN_TAB *table,KEYUSE *key)
3256
3462
{
3257
 
  optimizer::Position tmp_pos(1.0, /* This is a const table */
3258
 
                              0.0,
3259
 
                              table,
3260
 
                              key,
3261
 
                              0);
3262
 
  join->setPosInPartialPlan(idx, tmp_pos);
 
3463
  join->positions[idx].table= table;
 
3464
  join->positions[idx].key=key;
 
3465
  join->positions[idx].records_read=1.0;  /* This is a const table */
 
3466
  join->positions[idx].ref_depend_map= 0;
3263
3467
 
3264
3468
  /* Move the const table as down as possible in best_ref */
3265
 
  JoinTable **pos=join->best_ref+idx+1;
3266
 
  JoinTable *next=join->best_ref[idx];
 
3469
  JOIN_TAB **pos=join->best_ref+idx+1;
 
3470
  JOIN_TAB *next=join->best_ref[idx];
3267
3471
  for (;next != table ; pos++)
3268
3472
  {
3269
 
    JoinTable *tmp=pos[0];
 
3473
    JOIN_TAB *tmp=pos[0];
3270
3474
    pos[0]=next;
3271
3475
    next=tmp;
3272
3476
  }
3286
3490
                      the query
3287
3491
  @param join_tables  set of the tables in the query
3288
3492
 
 
3493
  @todo
 
3494
    'MAX_TABLES+2' denotes the old implementation of find_best before
 
3495
    the greedy version. Will be removed when greedy_search is approved.
 
3496
 
3289
3497
  @retval
3290
3498
    false       ok
3291
3499
  @retval
3292
3500
    true        Fatal error
3293
3501
*/
3294
 
static bool choose_plan(Join *join, table_map join_tables)
 
3502
static bool choose_plan(JOIN *join, table_map join_tables)
3295
3503
{
3296
3504
  uint32_t search_depth= join->session->variables.optimizer_search_depth;
3297
3505
  uint32_t prune_level=  join->session->variables.optimizer_prune_level;
3298
3506
  bool straight_join= test(join->select_options & SELECT_STRAIGHT_JOIN);
3299
3507
 
3300
 
  join->cur_embedding_map.reset();
 
3508
  join->cur_embedding_map= 0;
3301
3509
  reset_nj_counters(join->join_list);
3302
3510
  /*
3303
3511
    if (SELECT_STRAIGHT_JOIN option is set)
3307
3515
      Apply heuristic: pre-sort all access plans with respect to the number of
3308
3516
      records accessed.
3309
3517
  */
3310
 
  internal::my_qsort(join->best_ref + join->const_tables,
3311
 
                     join->tables - join->const_tables, sizeof(JoinTable*),
3312
 
                     straight_join ? join_tab_cmp_straight : join_tab_cmp);
 
3518
  my_qsort(join->best_ref + join->const_tables,
 
3519
           join->tables - join->const_tables, sizeof(JOIN_TAB*),
 
3520
           straight_join ? join_tab_cmp_straight : join_tab_cmp);
 
3521
  join->cur_emb_sj_nests= 0;
3313
3522
  if (straight_join)
3314
3523
  {
3315
3524
    optimize_straight_join(join, join_tables);
3316
3525
  }
3317
3526
  else
3318
3527
  {
3319
 
    if (search_depth == 0)
3320
 
      /* Automatically determine a reasonable value for 'search_depth' */
3321
 
      search_depth= determine_search_depth(join);
3322
 
    if (greedy_search(join, join_tables, search_depth, prune_level))
3323
 
      return true;
 
3528
    if (search_depth == MAX_TABLES+2)
 
3529
    { /*
 
3530
        TODO: 'MAX_TABLES+2' denotes the old implementation of find_best before
 
3531
        the greedy version. Will be removed when greedy_search is approved.
 
3532
      */
 
3533
      join->best_read= DBL_MAX;
 
3534
      if (find_best(join, join_tables, join->const_tables, 1.0, 0.0))
 
3535
        return(true);
 
3536
    }
 
3537
    else
 
3538
    {
 
3539
      if (search_depth == 0)
 
3540
        /* Automatically determine a reasonable value for 'search_depth' */
 
3541
        search_depth= determine_search_depth(join);
 
3542
      if (greedy_search(join, join_tables, search_depth, prune_level))
 
3543
        return(true);
 
3544
    }
3324
3545
  }
3325
3546
 
3326
3547
  /*
3358
3579
  @return
3359
3580
    None
3360
3581
*/
3361
 
static void best_access_path(Join *join,
3362
 
                             JoinTable *s,
 
3582
static void best_access_path(JOIN *join,
 
3583
                             JOIN_TAB *s,
3363
3584
                             Session *session,
3364
3585
                             table_map remaining_tables,
3365
3586
                             uint32_t idx,
3366
3587
                             double record_count,
3367
3588
                             double)
3368
3589
{
3369
 
  optimizer::KeyUse *best_key= NULL;
3370
 
  uint32_t best_max_key_part= 0;
 
3590
  KEYUSE *best_key=         0;
 
3591
  uint32_t best_max_key_part=   0;
3371
3592
  bool found_constraint= 0;
3372
 
  double best= DBL_MAX;
3373
 
  double best_time= DBL_MAX;
3374
 
  double records= DBL_MAX;
 
3593
  double best=              DBL_MAX;
 
3594
  double best_time=         DBL_MAX;
 
3595
  double records=           DBL_MAX;
3375
3596
  table_map best_ref_depends_map= 0;
3376
3597
  double tmp;
3377
3598
  ha_rows rec;
 
3599
  uint32_t best_is_sj_inside_out=    0;
3378
3600
 
3379
3601
  if (s->keyuse)
3380
3602
  {                                            /* Use key if possible */
3381
3603
    Table *table= s->table;
3382
 
    optimizer::KeyUse *keyuse= NULL;
3383
 
    optimizer::KeyUse *start_key= NULL;
 
3604
    KEYUSE *keyuse,*start_key=0;
3384
3605
    double best_records= DBL_MAX;
3385
3606
    uint32_t max_key_part=0;
 
3607
    uint64_t bound_sj_equalities= 0;
 
3608
    bool try_sj_inside_out= false;
 
3609
    /*
 
3610
      Discover the bound equalites. We need to do this, if
 
3611
        1. The next table is an SJ-inner table, and
 
3612
        2. It is the first table from that semijoin, and
 
3613
        3. We're not within a semi-join range (i.e. all semi-joins either have
 
3614
           all or none of their tables in join_table_map), except
 
3615
           s->emb_sj_nest (which we've just entered).
 
3616
        3. All correlation references from this sj-nest are bound
 
3617
    */
 
3618
    if (s->emb_sj_nest &&                                                 // (1)
 
3619
        s->emb_sj_nest->sj_in_exprs < 64 &&
 
3620
        ((remaining_tables & s->emb_sj_nest->sj_inner_tables) ==           // (2)
 
3621
         s->emb_sj_nest->sj_inner_tables) &&                               // (2)
 
3622
        join->cur_emb_sj_nests == s->emb_sj_nest->sj_inner_tables &&       // (3)
 
3623
        !(remaining_tables & s->emb_sj_nest->nested_join->sj_corr_tables)) // (4)
 
3624
    {
 
3625
      /* This table is an InsideOut scan candidate */
 
3626
      bound_sj_equalities= get_bound_sj_equalities(s->emb_sj_nest,
 
3627
                                                   remaining_tables);
 
3628
      try_sj_inside_out= true;
 
3629
    }
3386
3630
 
3387
3631
    /* Test how we can use keys */
3388
3632
    rec= s->records/MATCHING_ROWS_IN_OTHER_TABLE;  // Assumed records/key
3389
 
    for (keyuse= s->keyuse; keyuse->getTable() == table; )
 
3633
    for (keyuse=s->keyuse ; keyuse->table == table ;)
3390
3634
    {
3391
3635
      key_part_map found_part= 0;
3392
3636
      table_map found_ref= 0;
3393
 
      uint32_t key= keyuse->getKey();
3394
 
      KeyInfo *keyinfo= table->key_info + key;
 
3637
      uint32_t key= keyuse->key;
 
3638
      KEY *keyinfo= table->key_info+key;
3395
3639
      /* Bitmap of keyparts where the ref access is over 'keypart=const': */
3396
3640
      key_part_map const_part= 0;
3397
3641
      /* The or-null keypart in ref-or-null access: */
3399
3643
 
3400
3644
      /* Calculate how many key segments of the current key we can use */
3401
3645
      start_key= keyuse;
 
3646
      uint64_t handled_sj_equalities=0;
 
3647
      key_part_map sj_insideout_map= 0;
3402
3648
 
3403
3649
      do /* For each keypart */
3404
3650
      {
3405
 
        uint32_t keypart= keyuse->getKeypart();
 
3651
        uint32_t keypart= keyuse->keypart;
3406
3652
        table_map best_part_found_ref= 0;
3407
3653
        double best_prev_record_reads= DBL_MAX;
3408
3654
 
3413
3659
            if 1. expression doesn't refer to forward tables
3414
3660
               2. we won't get two ref-or-null's
3415
3661
          */
3416
 
          if (! (remaining_tables & keyuse->getUsedTables()) &&
3417
 
              ! (ref_or_null_part && (keyuse->getOptimizeFlags() &
3418
 
                                      KEY_OPTIMIZE_REF_OR_NULL)))
 
3662
          if (!(remaining_tables & keyuse->used_tables) &&
 
3663
              !(ref_or_null_part && (keyuse->optimize &
 
3664
                                     KEY_OPTIMIZE_REF_OR_NULL)))
3419
3665
          {
3420
 
            found_part|= keyuse->getKeypartMap();
3421
 
            if (! (keyuse->getUsedTables() & ~join->const_table_map))
3422
 
              const_part|= keyuse->getKeypartMap();
 
3666
            found_part|= keyuse->keypart_map;
 
3667
            if (!(keyuse->used_tables & ~join->const_table_map))
 
3668
              const_part|= keyuse->keypart_map;
3423
3669
 
3424
3670
            double tmp2= prev_record_reads(join, idx, (found_ref |
3425
 
                                                       keyuse->getUsedTables()));
 
3671
                                                      keyuse->used_tables));
3426
3672
            if (tmp2 < best_prev_record_reads)
3427
3673
            {
3428
 
              best_part_found_ref= keyuse->getUsedTables() & ~join->const_table_map;
 
3674
              best_part_found_ref= keyuse->used_tables & ~join->const_table_map;
3429
3675
              best_prev_record_reads= tmp2;
3430
3676
            }
3431
 
            if (rec > keyuse->getTableRows())
3432
 
              rec= keyuse->getTableRows();
 
3677
            if (rec > keyuse->ref_table_rows)
 
3678
              rec= keyuse->ref_table_rows;
3433
3679
      /*
3434
3680
        If there is one 'key_column IS NULL' expression, we can
3435
3681
        use this ref_or_null optimisation of this field
3436
3682
      */
3437
 
            if (keyuse->getOptimizeFlags() & KEY_OPTIMIZE_REF_OR_NULL)
3438
 
              ref_or_null_part|= keyuse->getKeypartMap();
 
3683
            if (keyuse->optimize & KEY_OPTIMIZE_REF_OR_NULL)
 
3684
              ref_or_null_part |= keyuse->keypart_map;
 
3685
          }
 
3686
 
 
3687
          if (try_sj_inside_out && keyuse->sj_pred_no != UINT_MAX)
 
3688
          {
 
3689
            if (!(remaining_tables & keyuse->used_tables))
 
3690
              bound_sj_equalities |= 1UL << keyuse->sj_pred_no;
 
3691
            else
 
3692
            {
 
3693
              handled_sj_equalities |= 1UL << keyuse->sj_pred_no;
 
3694
              sj_insideout_map |= ((key_part_map)1) << keyuse->keypart;
 
3695
            }
3439
3696
          }
3440
3697
 
3441
3698
          keyuse++;
3442
 
        } while (keyuse->getTable() == table && keyuse->getKey() == key &&
3443
 
                 keyuse->getKeypart() == keypart);
3444
 
        found_ref|= best_part_found_ref;
3445
 
      } while (keyuse->getTable() == table && keyuse->getKey() == key);
 
3699
        } while (keyuse->table == table && keyuse->key == key &&
 
3700
                 keyuse->keypart == keypart);
 
3701
  found_ref|= best_part_found_ref;
 
3702
      } while (keyuse->table == table && keyuse->key == key);
3446
3703
 
3447
3704
      /*
3448
3705
        Assume that that each key matches a proportional part of table.
3449
3706
      */
3450
 
      if (!found_part)
 
3707
      if (!found_part && !handled_sj_equalities)
3451
3708
        continue;                               // Nothing usable found
3452
3709
 
3453
3710
      if (rec < MATCHING_ROWS_IN_OTHER_TABLE)
3454
3711
        rec= MATCHING_ROWS_IN_OTHER_TABLE;      // Fix for small tables
3455
3712
 
 
3713
      bool sj_inside_out_scan= false;
3456
3714
      {
3457
3715
        found_constraint= 1;
 
3716
        /*
 
3717
          Check if InsideOut scan is applicable:
 
3718
          1. All IN-equalities are either "bound" or "handled"
 
3719
          2. Index keyparts are
 
3720
             ...
 
3721
        */
 
3722
        if (try_sj_inside_out &&
 
3723
            table->covering_keys.test(key) &&
 
3724
            (handled_sj_equalities | bound_sj_equalities) ==     // (1)
 
3725
            PREV_BITS(uint64_t, s->emb_sj_nest->sj_in_exprs)) // (1)
 
3726
        {
 
3727
          uint32_t n_fixed_parts= max_part_bit(found_part);
 
3728
          if (n_fixed_parts != keyinfo->key_parts &&
 
3729
              (PREV_BITS(uint, n_fixed_parts) | sj_insideout_map) ==
 
3730
               PREV_BITS(uint, keyinfo->key_parts))
 
3731
          {
 
3732
            /*
 
3733
              Not all parts are fixed. Produce bitmap of remaining bits and
 
3734
              check if all of them are covered.
 
3735
            */
 
3736
            sj_inside_out_scan= true;
 
3737
            if (!n_fixed_parts)
 
3738
            {
 
3739
              /*
 
3740
                It's a confluent ref scan.
 
3741
 
 
3742
                That is, all found KEYUSE elements refer to IN-equalities,
 
3743
                and there is really no ref access because there is no
 
3744
                  t.keypart0 = {bound expression}
 
3745
 
 
3746
                Calculate the cost of complete loose index scan.
 
3747
              */
 
3748
              records= (double)s->table->file->stats.records;
 
3749
 
 
3750
              /* The cost is entire index scan cost (divided by 2) */
 
3751
              best_time= s->table->file->index_only_read_time(key, records);
 
3752
 
 
3753
              /* Now figure how many different keys we will get */
 
3754
              ulong rpc;
 
3755
              if ((rpc= keyinfo->rec_per_key[keyinfo->key_parts-1]))
 
3756
                records= records / rpc;
 
3757
              start_key= NULL;
 
3758
            }
 
3759
          }
 
3760
        }
3458
3761
 
3459
3762
        /*
3460
3763
          Check if we found full key
3504
3807
                records=
3505
3808
                  ((double) s->records / (double) rec *
3506
3809
                   (1.0 +
3507
 
                    ((double) (table->getShare()->max_key_length-keyinfo->key_length) /
3508
 
                     (double) table->getShare()->max_key_length)));
 
3810
                    ((double) (table->s->max_key_length-keyinfo->key_length) /
 
3811
                     (double) table->s->max_key_length)));
3509
3812
                if (records < 2.0)
3510
3813
                  records=2.0;               /* Can't be as good as a unique */
3511
3814
              }
3533
3836
            if (table->covering_keys.test(key))
3534
3837
            {
3535
3838
              /* we can use only index tree */
3536
 
              tmp= record_count * table->cursor->index_only_read_time(key, tmp);
 
3839
              tmp= record_count * table->file->index_only_read_time(key, tmp);
3537
3840
            }
3538
3841
            else
3539
 
              tmp= record_count * min(tmp,s->worst_seeks);
 
3842
              tmp= record_count*cmin(tmp,s->worst_seeks);
3540
3843
          }
3541
3844
        }
3542
3845
        else
3547
3850
            Set tmp to (previous record count) * (records / combination)
3548
3851
          */
3549
3852
          if ((found_part & 1) &&
3550
 
              (!(table->index_flags(key) & HA_ONLY_WHOLE_INDEX) ||
3551
 
               found_part == PREV_BITS(uint, keyinfo->key_parts)))
 
3853
              (!(table->file->index_flags(key, 0, 0) & HA_ONLY_WHOLE_INDEX) ||
 
3854
               found_part == PREV_BITS(uint,keyinfo->key_parts)))
3552
3855
          {
3553
3856
            max_key_part= max_part_bit(found_part);
3554
3857
            /*
3627
3930
              else
3628
3931
              {
3629
3932
                /*
3630
 
                  Assume that the first key part matches 1% of the cursor
 
3933
                  Assume that the first key part matches 1% of the file
3631
3934
                  and that the whole key matches 10 (duplicates) or 1
3632
3935
                  (unique) records.
3633
3936
                  Assume also that more key matches proportionally more
3698
4001
            if (table->covering_keys.test(key))
3699
4002
            {
3700
4003
              /* we can use only index tree */
3701
 
              tmp= record_count * table->cursor->index_only_read_time(key, tmp);
 
4004
              tmp= record_count * table->file->index_only_read_time(key, tmp);
3702
4005
            }
3703
4006
            else
3704
 
              tmp= record_count * min(tmp,s->worst_seeks);
 
4007
              tmp= record_count * cmin(tmp,s->worst_seeks);
3705
4008
          }
3706
4009
          else
3707
4010
            tmp= best_time;                    // Do nothing
3708
4011
        }
3709
4012
 
 
4013
        if (sj_inside_out_scan && !start_key)
 
4014
        {
 
4015
          tmp= tmp/2;
 
4016
          if (records)
 
4017
            records= records/2;
 
4018
        }
 
4019
 
3710
4020
      }
3711
4021
      if (tmp < best_time - records/(double) TIME_FOR_COMPARE)
3712
4022
      {
3716
4026
        best_key= start_key;
3717
4027
        best_max_key_part= max_key_part;
3718
4028
        best_ref_depends_map= found_ref;
 
4029
        best_is_sj_inside_out= sj_inside_out_scan;
3719
4030
      }
3720
4031
    }
3721
4032
    records= best_records;
3750
4061
        scan.
3751
4062
  */
3752
4063
  if ((records >= s->found_records || best > s->read_time) &&            // (1)
3753
 
      ! (s->quick && best_key && s->quick->index == best_key->getKey() &&      // (2)
3754
 
        best_max_key_part >= s->table->quick_key_parts[best_key->getKey()]) &&// (2)
3755
 
      ! ((s->table->cursor->getEngine()->check_flag(HTON_BIT_TABLE_SCAN_ON_INDEX)) &&   // (3)
3756
 
        ! s->table->covering_keys.none() && best_key && !s->quick) && // (3)
3757
 
      ! (s->table->force_index && best_key && !s->quick))                 // (4)
 
4064
      !(s->quick && best_key && s->quick->index == best_key->key &&      // (2)
 
4065
        best_max_key_part >= s->table->quick_key_parts[best_key->key]) &&// (2)
 
4066
      !((s->table->file->ha_table_flags() & HA_TABLE_SCAN_ON_INDEX) &&   // (3)
 
4067
        ! s->table->covering_keys.none() && best_key && !s->quick) &&// (3)
 
4068
      !(s->table->force_index && best_key && !s->quick))                 // (4)
3758
4069
  {                                             // Check full join
3759
4070
    ha_rows rnd_records= s->found_records;
3760
4071
    /*
3799
4110
    else
3800
4111
    {
3801
4112
      /* Estimate cost of reading table. */
3802
 
      tmp= s->table->cursor->scan_time();
 
4113
      tmp= s->table->file->scan_time();
3803
4114
      if (s->table->map & join->outer_join)     // Can't use join cache
3804
4115
      {
3805
4116
        /*
3846
4157
      best_key= 0;
3847
4158
      /* range/index_merge/ALL/index access method are "independent", so: */
3848
4159
      best_ref_depends_map= 0;
 
4160
      best_is_sj_inside_out= false;
3849
4161
    }
3850
4162
  }
3851
4163
 
3852
4164
  /* Update the cost information for the current partial plan */
3853
 
  optimizer::Position tmp_pos(records,
3854
 
                              best,
3855
 
                              s,
3856
 
                              best_key,
3857
 
                              best_ref_depends_map);
3858
 
  join->setPosInPartialPlan(idx, tmp_pos);
 
4165
  join->positions[idx].records_read= records;
 
4166
  join->positions[idx].read_time=    best;
 
4167
  join->positions[idx].key=          best_key;
 
4168
  join->positions[idx].table=        s;
 
4169
  join->positions[idx].ref_depend_map= best_ref_depends_map;
 
4170
  join->positions[idx].use_insideout_scan= best_is_sj_inside_out;
3859
4171
 
3860
4172
  if (!best_key &&
3861
4173
      idx == join->const_tables &&
3888
4200
    Thus 'optimize_straight_join' can be used at any stage of the query
3889
4201
    optimization process to finalize a QEP as it is.
3890
4202
*/
3891
 
static void optimize_straight_join(Join *join, table_map join_tables)
 
4203
static void optimize_straight_join(JOIN *join, table_map join_tables)
3892
4204
{
3893
 
  JoinTable *s;
3894
 
  optimizer::Position partial_pos;
 
4205
  JOIN_TAB *s;
3895
4206
  uint32_t idx= join->const_tables;
3896
4207
  double    record_count= 1.0;
3897
4208
  double    read_time=    0.0;
3898
4209
 
3899
 
  for (JoinTable **pos= join->best_ref + idx ; (s= *pos) ; pos++)
 
4210
  for (JOIN_TAB **pos= join->best_ref + idx ; (s= *pos) ; pos++)
3900
4211
  {
3901
4212
    /* Find the best access method from 's' to the current partial plan */
 
4213
    advance_sj_state(join_tables, s);
3902
4214
    best_access_path(join, s, join->session, join_tables, idx,
3903
4215
                     record_count, read_time);
3904
4216
    /* compute the cost of the new plan extended with 's' */
3905
 
    partial_pos= join->getPosFromPartialPlan(idx);
3906
 
    record_count*= partial_pos.getFanout();
3907
 
    read_time+=    partial_pos.getCost();
 
4217
    record_count*= join->positions[idx].records_read;
 
4218
    read_time+=    join->positions[idx].read_time;
3908
4219
    join_tables&= ~(s->table->map);
3909
4220
    ++idx;
3910
4221
  }
3911
4222
 
3912
4223
  read_time+= record_count / (double) TIME_FOR_COMPARE;
3913
 
  partial_pos= join->getPosFromPartialPlan(join->const_tables);
3914
4224
  if (join->sort_by_table &&
3915
 
      partial_pos.hasTableForSorting(join->sort_by_table))
 
4225
      join->sort_by_table != join->positions[join->const_tables].table->table)
3916
4226
    read_time+= record_count;  // We have to make a temp table
3917
 
  join->copyPartialPlanIntoOptimalPlan(idx);
 
4227
  memcpy(join->best_positions, join->positions, sizeof(POSITION)*idx);
3918
4228
  join->best_read= read_time;
3919
4229
}
3920
4230
 
3998
4308
  @retval
3999
4309
    true        Fatal error
4000
4310
*/
4001
 
static bool greedy_search(Join      *join,
 
4311
static bool greedy_search(JOIN      *join,
4002
4312
              table_map remaining_tables,
4003
4313
              uint32_t      search_depth,
4004
4314
              uint32_t      prune_level)
4008
4318
  uint32_t      idx= join->const_tables; // index into 'join->best_ref'
4009
4319
  uint32_t      best_idx;
4010
4320
  uint32_t      size_remain;    // cardinality of remaining_tables
4011
 
  optimizer::Position best_pos;
4012
 
  JoinTable  *best_table; // the next plan node to be added to the curr QEP
 
4321
  POSITION  best_pos;
 
4322
  JOIN_TAB  *best_table; // the next plan node to be added to the curr QEP
4013
4323
 
4014
4324
  /* number of tables that remain to be optimized */
4015
 
  size_remain= internal::my_count_bits(remaining_tables);
 
4325
  size_remain= my_count_bits(remaining_tables);
4016
4326
 
4017
4327
  do {
4018
4328
    /* Find the extension of the current QEP with the lowest cost */
4031
4341
    }
4032
4342
 
4033
4343
    /* select the first table in the optimal extension as most promising */
4034
 
    best_pos= join->getPosFromOptimalPlan(idx);
4035
 
    best_table= best_pos.getJoinTable();
 
4344
    best_pos= join->best_positions[idx];
 
4345
    best_table= best_pos.table;
4036
4346
    /*
4037
4347
      Each subsequent loop of 'best_extension_by_limited_search' uses
4038
4348
      'join->positions' for cost estimates, therefore we have to update its
4039
4349
      value.
4040
4350
    */
4041
 
    join->setPosInPartialPlan(idx, best_pos);
4042
 
 
4043
 
    /*
4044
 
      We need to make best_extension_by_limited_search aware of the fact
4045
 
      that it's not starting from top level, but from a rather specific
4046
 
      position in the list of nested joins.
4047
 
    */
4048
 
    check_interleaving_with_nj (best_table);
4049
 
    
4050
 
      
 
4351
    join->positions[idx]= best_pos;
4051
4352
 
4052
4353
    /* find the position of 'best_table' in 'join->best_ref' */
4053
4354
    best_idx= idx;
4054
 
    JoinTable *pos= join->best_ref[best_idx];
 
4355
    JOIN_TAB *pos= join->best_ref[best_idx];
4055
4356
    while (pos && best_table != pos)
4056
4357
      pos= join->best_ref[++best_idx];
4057
4358
    assert((pos != NULL)); // should always find 'best_table'
4059
4360
    std::swap(join->best_ref[idx], join->best_ref[best_idx]);
4060
4361
 
4061
4362
    /* compute the cost of the new plan extended with 'best_table' */
4062
 
    optimizer::Position partial_pos= join->getPosFromPartialPlan(idx);
4063
 
    record_count*= partial_pos.getFanout();
4064
 
    read_time+=    partial_pos.getCost();
 
4363
    record_count*= join->positions[idx].records_read;
 
4364
    read_time+=    join->positions[idx].read_time;
4065
4365
 
4066
4366
    remaining_tables&= ~(best_table->table->map);
4067
4367
    --size_remain;
4186
4486
  @retval
4187
4487
    true        Fatal error
4188
4488
*/
4189
 
static bool best_extension_by_limited_search(Join *join,
 
4489
static bool best_extension_by_limited_search(JOIN *join,
4190
4490
                                             table_map remaining_tables,
4191
4491
                                             uint32_t idx,
4192
4492
                                             double record_count,
4195
4495
                                             uint32_t prune_level)
4196
4496
{
4197
4497
  Session *session= join->session;
4198
 
  if (session->getKilled())  // Abort
 
4498
  if (session->killed)  // Abort
4199
4499
    return(true);
4200
4500
 
4201
4501
  /*
4202
4502
     'join' is a partial plan with lower cost than the best plan so far,
4203
4503
     so continue expanding it further with the tables in 'remaining_tables'.
4204
4504
  */
4205
 
  JoinTable *s;
 
4505
  JOIN_TAB *s;
4206
4506
  double best_record_count= DBL_MAX;
4207
4507
  double best_read_time=    DBL_MAX;
4208
 
  optimizer::Position partial_pos;
4209
4508
 
4210
 
  for (JoinTable **pos= join->best_ref + idx ; (s= *pos) ; pos++)
 
4509
  for (JOIN_TAB **pos= join->best_ref + idx ; (s= *pos) ; pos++)
4211
4510
  {
4212
4511
    table_map real_table_bit= s->table->map;
4213
4512
    if ((remaining_tables & real_table_bit) &&
4214
 
        ! (remaining_tables & s->dependent) &&
4215
 
        (! idx || ! check_interleaving_with_nj(s)))
 
4513
        !(remaining_tables & s->dependent) &&
 
4514
        (!idx || !check_interleaving_with_nj(join->positions[idx-1].table, s)))
4216
4515
    {
4217
4516
      double current_record_count, current_read_time;
 
4517
      advance_sj_state(remaining_tables, s);
4218
4518
 
4219
4519
      /*
4220
4520
        psergey-insideout-todo:
4227
4527
      best_access_path(join, s, session, remaining_tables, idx,
4228
4528
                       record_count, read_time);
4229
4529
      /* Compute the cost of extending the plan with 's' */
4230
 
      partial_pos= join->getPosFromPartialPlan(idx);
4231
 
      current_record_count= record_count * partial_pos.getFanout();
4232
 
      current_read_time=    read_time + partial_pos.getCost();
 
4530
      current_record_count= record_count * join->positions[idx].records_read;
 
4531
      current_read_time=    read_time + join->positions[idx].read_time;
4233
4532
 
4234
4533
      /* Expand only partial plans with lower cost than the best QEP so far */
4235
4534
      if ((current_read_time +
4236
4535
           current_record_count / (double) TIME_FOR_COMPARE) >= join->best_read)
4237
4536
      {
4238
4537
        restore_prev_nj_state(s);
 
4538
        restore_prev_sj_state(remaining_tables, s);
4239
4539
        continue;
4240
4540
      }
4241
4541
 
4252
4552
          if (best_record_count >= current_record_count &&
4253
4553
              best_read_time >= current_read_time &&
4254
4554
              /* TODO: What is the reasoning behind this condition? */
4255
 
              (! (s->key_dependent & remaining_tables) ||
4256
 
               partial_pos.isConstTable()))
 
4555
              (!(s->key_dependent & remaining_tables) ||
 
4556
               join->positions[idx].records_read < 2.0))
4257
4557
          {
4258
4558
            best_record_count= current_record_count;
4259
4559
            best_read_time=    current_read_time;
4262
4562
        else
4263
4563
        {
4264
4564
          restore_prev_nj_state(s);
 
4565
          restore_prev_sj_state(remaining_tables, s);
4265
4566
          continue;
4266
4567
        }
4267
4568
      }
4284
4585
          'join' is either the best partial QEP with 'search_depth' relations,
4285
4586
          or the best complete QEP so far, whichever is smaller.
4286
4587
        */
4287
 
        partial_pos= join->getPosFromPartialPlan(join->const_tables);
4288
4588
        current_read_time+= current_record_count / (double) TIME_FOR_COMPARE;
4289
4589
        if (join->sort_by_table &&
4290
 
            partial_pos.hasTableForSorting(join->sort_by_table))
 
4590
            join->sort_by_table !=
 
4591
            join->positions[join->const_tables].table->table)
4291
4592
          /* We have to make a temp table */
4292
4593
          current_read_time+= current_record_count;
4293
4594
        if ((search_depth == 1) || (current_read_time < join->best_read))
4294
4595
        {
4295
 
          join->copyPartialPlanIntoOptimalPlan(idx + 1);
 
4596
          memcpy(join->best_positions, join->positions,
 
4597
                 sizeof(POSITION) * (idx + 1));
4296
4598
          join->best_read= current_read_time - 0.001;
4297
4599
        }
4298
4600
      }
4299
4601
      restore_prev_nj_state(s);
 
4602
      restore_prev_sj_state(remaining_tables, s);
4300
4603
    }
4301
4604
  }
4302
4605
  return(false);
4333
4636
    exhaustiveness) of the depth-first search algorithm used by
4334
4637
    'greedy_search'.
4335
4638
*/
4336
 
static uint32_t determine_search_depth(Join *join)
 
4639
static uint32_t determine_search_depth(JOIN *join)
4337
4640
{
4338
4641
  uint32_t table_count=  join->tables - join->const_tables;
4339
4642
  uint32_t search_depth;
4352
4655
  return search_depth;
4353
4656
}
4354
4657
 
4355
 
static bool make_simple_join(Join *join,Table *tmp_table)
 
4658
static bool make_simple_join(JOIN *join,Table *tmp_table)
4356
4659
{
4357
4660
  Table **tableptr;
4358
 
  JoinTable *join_tab;
 
4661
  JOIN_TAB *join_tab;
4359
4662
 
4360
4663
  /*
4361
 
    Reuse Table * and JoinTable if already allocated by a previous call
4362
 
    to this function through Join::exec (may happen for sub-queries).
 
4664
    Reuse Table * and JOIN_TAB if already allocated by a previous call
 
4665
    to this function through JOIN::exec (may happen for sub-queries).
4363
4666
  */
4364
4667
  if (!join->table_reexec)
4365
4668
  {
4366
4669
    if (!(join->table_reexec= (Table**) join->session->alloc(sizeof(Table*))))
4367
 
      return(true);
 
4670
      return(true);                        /* purecov: inspected */
4368
4671
    if (join->tmp_join)
4369
4672
      join->tmp_join->table_reexec= join->table_reexec;
4370
4673
  }
4371
4674
  if (!join->join_tab_reexec)
4372
4675
  {
4373
4676
    if (!(join->join_tab_reexec=
4374
 
          (JoinTable*) join->session->alloc(sizeof(JoinTable))))
4375
 
      return(true);
 
4677
          (JOIN_TAB*) join->session->alloc(sizeof(JOIN_TAB))))
 
4678
      return(true);                        /* purecov: inspected */
4376
4679
    if (join->tmp_join)
4377
4680
      join->tmp_join->join_tab_reexec= join->join_tab_reexec;
4378
4681
  }
4398
4701
  join_tab->select=0;
4399
4702
  join_tab->select_cond=0;
4400
4703
  join_tab->quick=0;
4401
 
  join_tab->type= AM_ALL;                       /* Map through all records */
 
4704
  join_tab->type= JT_ALL;                       /* Map through all records */
4402
4705
  join_tab->keys.set();                     /* test everything in quick */
4403
4706
  join_tab->info=0;
4404
4707
  join_tab->on_expr_ref=0;
4409
4712
  join_tab->read_first_record= join_init_read_record;
4410
4713
  join_tab->join=join;
4411
4714
  join_tab->ref.key_parts= 0;
4412
 
  join_tab->read_record.init();
 
4715
  join_tab->flush_weedout_table= join_tab->check_weed_out_table= NULL;
 
4716
  join_tab->do_firstmatch= NULL;
 
4717
  memset(&join_tab->read_record, 0, sizeof(join_tab->read_record));
4413
4718
  tmp_table->status=0;
4414
4719
  tmp_table->null_row=0;
4415
 
 
4416
 
  return false;
 
4720
  return(false);
4417
4721
}
4418
4722
 
4419
4723
/**
4431
4735
    through the field t0->first_upper.
4432
4736
    The on expression for the outer join operation is attached to the
4433
4737
    corresponding first inner table through the field t0->on_expr_ref.
4434
 
    Here ti are structures of the JoinTable type.
 
4738
    Here ti are structures of the JOIN_TAB type.
4435
4739
 
4436
4740
  EXAMPLE. For the query:
4437
4741
  @code
4457
4761
    This function can be called only after the execution plan
4458
4762
    has been chosen.
4459
4763
*/
4460
 
static void make_outerjoin_info(Join *join)
 
4764
static void make_outerjoin_info(JOIN *join)
4461
4765
{
4462
4766
  for (uint32_t i=join->const_tables ; i < join->tables ; i++)
4463
4767
  {
4464
 
    JoinTable *tab=join->join_tab+i;
 
4768
    JOIN_TAB *tab=join->join_tab+i;
4465
4769
    Table *table=tab->table;
4466
4770
    TableList *tbl= table->pos_in_table_list;
4467
 
    TableList *embedding= tbl->getEmbedding();
 
4771
    TableList *embedding= tbl->embedding;
4468
4772
 
4469
4773
    if (tbl->outer_join)
4470
4774
    {
4477
4781
      tab->on_expr_ref= &tbl->on_expr;
4478
4782
      tab->cond_equal= tbl->cond_equal;
4479
4783
      if (embedding)
4480
 
        tab->first_upper= embedding->getNestedJoin()->first_nested;
 
4784
        tab->first_upper= embedding->nested_join->first_nested;
4481
4785
    }
4482
 
    for ( ; embedding ; embedding= embedding->getEmbedding())
 
4786
    for ( ; embedding ; embedding= embedding->embedding)
4483
4787
    {
4484
4788
      /* Ignore sj-nests: */
4485
4789
      if (!embedding->on_expr)
4486
4790
        continue;
4487
 
      nested_join_st *nested_join= embedding->getNestedJoin();
 
4791
      nested_join_st *nested_join= embedding->nested_join;
4488
4792
      if (!nested_join->counter_)
4489
4793
      {
4490
4794
        /*
4494
4798
        nested_join->first_nested= tab;
4495
4799
        tab->on_expr_ref= &embedding->on_expr;
4496
4800
        tab->cond_equal= tbl->cond_equal;
4497
 
        if (embedding->getEmbedding())
4498
 
          tab->first_upper= embedding->getEmbedding()->getNestedJoin()->first_nested;
 
4801
        if (embedding->embedding)
 
4802
          tab->first_upper= embedding->embedding->nested_join->first_nested;
4499
4803
      }
4500
4804
      if (!tab->first_inner)
4501
4805
        tab->first_inner= nested_join->first_nested;
4508
4812
  return;
4509
4813
}
4510
4814
 
4511
 
static bool make_join_select(Join *join,
4512
 
                             optimizer::SqlSelect *select,
4513
 
                             COND *cond)
 
4815
static bool make_join_select(JOIN *join,SQL_SELECT *select,COND *cond)
4514
4816
{
4515
4817
  Session *session= join->session;
4516
 
  optimizer::Position cur_pos;
4517
4818
  if (select)
4518
4819
  {
4519
4820
    add_not_null_conds(join);
4523
4824
      if (join->tables > 1)
4524
4825
        cond->update_used_tables();             // Tablenr may have changed
4525
4826
      if (join->const_tables == join->tables &&
4526
 
          session->lex->current_select->master_unit() ==
4527
 
          &session->lex->unit)          // not upper level SELECT
 
4827
          session->lex->current_select->master_unit() ==
 
4828
          &session->lex->unit)          // not upper level SELECT
4528
4829
        join->const_table_map|=RAND_TABLE_BIT;
4529
4830
      {                                         // Check const tables
4530
4831
        COND *const_cond=
4531
 
          make_cond_for_table(cond,
4532
 
              join->const_table_map,
4533
 
              (table_map) 0, 1);
4534
 
        for (JoinTable *tab= join->join_tab+join->const_tables;
4535
 
            tab < join->join_tab+join->tables ; tab++)
 
4832
          make_cond_for_table(cond,
 
4833
                              join->const_table_map,
 
4834
                              (table_map) 0, 1);
 
4835
        for (JOIN_TAB *tab= join->join_tab+join->const_tables;
 
4836
             tab < join->join_tab+join->tables ; tab++)
4536
4837
        {
4537
4838
          if (*tab->on_expr_ref)
4538
4839
          {
4539
 
            JoinTable *cond_tab= tab->first_inner;
 
4840
            JOIN_TAB *cond_tab= tab->first_inner;
4540
4841
            COND *tmp= make_cond_for_table(*tab->on_expr_ref,
4541
 
                join->const_table_map,
4542
 
                (  table_map) 0, 0);
 
4842
                                           join->const_table_map,
 
4843
                                           (  table_map) 0, 0);
4543
4844
            if (!tmp)
4544
4845
              continue;
4545
4846
            tmp= new Item_func_trig_cond(tmp, &cond_tab->not_null_compl);
4546
 
            if (! tmp)
4547
 
              return 1;
 
4847
            if (!tmp)
 
4848
              return(1);
4548
4849
            tmp->quick_fix_field();
4549
4850
            cond_tab->select_cond= !cond_tab->select_cond ? tmp :
4550
 
              new Item_cond_and(cond_tab->select_cond,
4551
 
                  tmp);
4552
 
            if (! cond_tab->select_cond)
4553
 
              return 1;
 
4851
                                    new Item_cond_and(cond_tab->select_cond,
 
4852
                                                      tmp);
 
4853
            if (!cond_tab->select_cond)
 
4854
              return(1);
4554
4855
            cond_tab->select_cond->quick_fix_field();
4555
4856
          }
4556
4857
        }
4557
 
        if (const_cond && ! const_cond->val_int())
 
4858
        if (const_cond && !const_cond->val_int())
4558
4859
        {
4559
 
          return 1;      // Impossible const condition
 
4860
          return(1);     // Impossible const condition
4560
4861
        }
4561
4862
      }
4562
4863
    }
4563
4864
    used_tables=((select->const_tables=join->const_table_map) |
4564
 
        OUTER_REF_TABLE_BIT | RAND_TABLE_BIT);
 
4865
                 OUTER_REF_TABLE_BIT | RAND_TABLE_BIT);
4565
4866
    for (uint32_t i=join->const_tables ; i < join->tables ; i++)
4566
4867
    {
4567
 
      JoinTable *tab=join->join_tab+i;
 
4868
      JOIN_TAB *tab=join->join_tab+i;
4568
4869
      /*
4569
 
         first_inner is the X in queries like:
4570
 
         SELECT * FROM t1 LEFT OUTER JOIN (t2 JOIN t3) ON X
4571
 
       */
4572
 
      JoinTable *first_inner_tab= tab->first_inner;
 
4870
        first_inner is the X in queries like:
 
4871
        SELECT * FROM t1 LEFT OUTER JOIN (t2 JOIN t3) ON X
 
4872
      */
 
4873
      JOIN_TAB *first_inner_tab= tab->first_inner;
4573
4874
      table_map current_map= tab->table->map;
4574
4875
      bool use_quick_range=0;
4575
4876
      COND *tmp;
4576
4877
 
4577
4878
      /*
4578
 
         Following force including random expression in last table condition.
4579
 
         It solve problem with select like SELECT * FROM t1 WHERE rand() > 0.5
4580
 
       */
 
4879
        Following force including random expression in last table condition.
 
4880
        It solve problem with select like SELECT * FROM t1 WHERE rand() > 0.5
 
4881
      */
4581
4882
      if (i == join->tables-1)
4582
 
        current_map|= OUTER_REF_TABLE_BIT | RAND_TABLE_BIT;
 
4883
        current_map|= OUTER_REF_TABLE_BIT | RAND_TABLE_BIT;
4583
4884
      used_tables|=current_map;
4584
4885
 
4585
 
      if (tab->type == AM_REF && tab->quick &&
4586
 
          (uint32_t) tab->ref.key == tab->quick->index &&
4587
 
          tab->ref.key_length < tab->quick->max_used_key_length)
 
4886
      if (tab->type == JT_REF && tab->quick &&
 
4887
          (uint32_t) tab->ref.key == tab->quick->index &&
 
4888
          tab->ref.key_length < tab->quick->max_used_key_length)
4588
4889
      {
4589
 
        /* Range uses longer key;  Use this instead of ref on key */
4590
 
        tab->type= AM_ALL;
4591
 
        use_quick_range= 1;
4592
 
        tab->use_quick= 1;
 
4890
        /* Range uses longer key;  Use this instead of ref on key */
 
4891
        tab->type=JT_ALL;
 
4892
        use_quick_range=1;
 
4893
        tab->use_quick=1;
4593
4894
        tab->ref.key= -1;
4594
 
        tab->ref.key_parts= 0;          // Don't use ref key.
4595
 
        cur_pos= join->getPosFromOptimalPlan(i);
4596
 
        cur_pos.setFanout(rows2double(tab->quick->records));
 
4895
        tab->ref.key_parts=0;           // Don't use ref key.
 
4896
        join->best_positions[i].records_read= rows2double(tab->quick->records);
4597
4897
        /*
4598
 
           We will use join cache here : prevent sorting of the first
4599
 
           table only and sort at the end.
4600
 
         */
 
4898
          We will use join cache here : prevent sorting of the first
 
4899
          table only and sort at the end.
 
4900
        */
4601
4901
        if (i != join->const_tables && join->tables > join->const_tables + 1)
4602
4902
          join->full_join= 1;
4603
4903
      }
4607
4907
        tmp= make_cond_for_table(cond,used_tables,current_map, 0);
4608
4908
      if (cond && !tmp && tab->quick)
4609
4909
      {                                         // Outer join
4610
 
        if (tab->type != AM_ALL)
 
4910
        if (tab->type != JT_ALL)
4611
4911
        {
4612
4912
          /*
4613
 
             Don't use the quick method
4614
 
             We come here in the case where we have 'key=constant' and
4615
 
             the test is removed by make_cond_for_table()
4616
 
           */
 
4913
            Don't use the quick method
 
4914
            We come here in the case where we have 'key=constant' and
 
4915
            the test is removed by make_cond_for_table()
 
4916
          */
4617
4917
          delete tab->quick;
4618
4918
          tab->quick= 0;
4619
4919
        }
4620
4920
        else
4621
4921
        {
4622
4922
          /*
4623
 
             Hack to handle the case where we only refer to a table
4624
 
             in the ON part of an OUTER JOIN. In this case we want the code
4625
 
             below to check if we should use 'quick' instead.
4626
 
           */
 
4923
            Hack to handle the case where we only refer to a table
 
4924
            in the ON part of an OUTER JOIN. In this case we want the code
 
4925
            below to check if we should use 'quick' instead.
 
4926
          */
4627
4927
          tmp= new Item_int((int64_t) 1,1);     // Always true
4628
4928
        }
4629
4929
 
4630
4930
      }
4631
 
      if (tmp || !cond || tab->type == AM_REF || tab->type == AM_REF_OR_NULL ||
4632
 
          tab->type == AM_EQ_REF)
 
4931
      if (tmp || !cond || tab->type == JT_REF || tab->type == JT_REF_OR_NULL ||
 
4932
          tab->type == JT_EQ_REF)
4633
4933
      {
4634
 
        optimizer::SqlSelect *sel= tab->select= ((optimizer::SqlSelect*)
4635
 
            session->memdup((unsigned char*) select,
4636
 
              sizeof(*select)));
4637
 
        if (! sel)
4638
 
          return 1;                     // End of memory
 
4934
        SQL_SELECT *sel= tab->select= ((SQL_SELECT*)
 
4935
                                       session->memdup((unsigned char*) select,
 
4936
                                                   sizeof(*select)));
 
4937
        if (!sel)
 
4938
          return(1);                    // End of memory
4639
4939
        /*
4640
 
           If tab is an inner table of an outer join operation,
4641
 
           add a match guard to the pushed down predicate.
4642
 
           The guard will turn the predicate on only after
4643
 
           the first match for outer tables is encountered.
4644
 
         */
 
4940
          If tab is an inner table of an outer join operation,
 
4941
          add a match guard to the pushed down predicate.
 
4942
          The guard will turn the predicate on only after
 
4943
          the first match for outer tables is encountered.
 
4944
        */
4645
4945
        if (cond && tmp)
4646
4946
        {
4647
4947
          /*
4648
 
             Because of QUICK_GROUP_MIN_MAX_SELECT there may be a select without
4649
 
             a cond, so neutralize the hack above.
4650
 
           */
4651
 
          if (! (tmp= add_found_match_trig_cond(first_inner_tab, tmp, 0)))
4652
 
            return 1;
 
4948
            Because of QUICK_GROUP_MIN_MAX_SELECT there may be a select without
 
4949
            a cond, so neutralize the hack above.
 
4950
          */
 
4951
          if (!(tmp= add_found_match_trig_cond(first_inner_tab, tmp, 0)))
 
4952
            return(1);
4653
4953
          tab->select_cond=sel->cond=tmp;
 
4954
          /* Push condition to storage engine if this is enabled
 
4955
             and the condition is not guarded */
 
4956
          tab->table->file->pushed_cond= NULL;
 
4957
          if (session->variables.engine_condition_pushdown)
 
4958
          {
 
4959
            COND *push_cond=
 
4960
              make_cond_for_table(tmp, current_map, current_map, 0);
 
4961
            if (push_cond)
 
4962
            {
 
4963
              /* Push condition to handler */
 
4964
              if (!tab->table->file->cond_push(push_cond))
 
4965
                tab->table->file->pushed_cond= push_cond;
 
4966
            }
 
4967
          }
4654
4968
        }
4655
4969
        else
4656
4970
          tab->select_cond= sel->cond= NULL;
4657
4971
 
4658
 
        sel->head=tab->table;
4659
 
        if (tab->quick)
4660
 
        {
4661
 
          /* Use quick key read if it's a constant and it's not used
4662
 
             with key reading */
4663
 
          if (tab->needed_reg.none() && tab->type != AM_EQ_REF
4664
 
              && (tab->type != AM_REF || (uint32_t) tab->ref.key == tab->quick->index))
4665
 
          {
4666
 
            sel->quick=tab->quick;              // Use value from get_quick_...
4667
 
            sel->quick_keys.reset();
4668
 
            sel->needed_reg.reset();
4669
 
          }
4670
 
          else
4671
 
          {
4672
 
            delete tab->quick;
4673
 
          }
4674
 
          tab->quick= 0;
4675
 
        }
4676
 
        uint32_t ref_key= static_cast<uint32_t>(sel->head->reginfo.join_tab->ref.key + 1);
4677
 
        if (i == join->const_tables && ref_key)
4678
 
        {
4679
 
          if (tab->const_keys.any() &&
4680
 
              tab->table->reginfo.impossible_range)
4681
 
            return 1;
4682
 
        }
4683
 
        else if (tab->type == AM_ALL && ! use_quick_range)
4684
 
        {
4685
 
          if (tab->const_keys.any() &&
4686
 
              tab->table->reginfo.impossible_range)
4687
 
            return 1;                           // Impossible range
4688
 
          /*
4689
 
             We plan to scan all rows.
4690
 
             Check again if we should use an index.
4691
 
             We could have used an column from a previous table in
4692
 
             the index if we are using limit and this is the first table
4693
 
           */
4694
 
 
4695
 
          cur_pos= join->getPosFromOptimalPlan(i);
4696
 
          if ((cond && (! ((tab->keys & tab->const_keys) == tab->keys) && i > 0)) ||
4697
 
              (! tab->const_keys.none() && (i == join->const_tables) &&
4698
 
              (join->unit->select_limit_cnt < cur_pos.getFanout()) && ((join->select_options & OPTION_FOUND_ROWS) == false)))
4699
 
          {
4700
 
            /* Join with outer join condition */
4701
 
            COND *orig_cond= sel->cond;
4702
 
            sel->cond= and_conds(sel->cond, *tab->on_expr_ref);
4703
 
 
4704
 
            /*
4705
 
               We can't call sel->cond->fix_fields,
4706
 
               as it will break tab->on_expr if it's AND condition
4707
 
               (fix_fields currently removes extra AND/OR levels).
4708
 
               Yet attributes of the just built condition are not needed.
4709
 
               Thus we call sel->cond->quick_fix_field for safety.
4710
 
             */
4711
 
            if (sel->cond && ! sel->cond->fixed)
4712
 
              sel->cond->quick_fix_field();
4713
 
 
4714
 
            if (sel->test_quick_select(session, tab->keys,
4715
 
                  used_tables & ~ current_map,
4716
 
                  (join->select_options &
4717
 
                   OPTION_FOUND_ROWS ?
4718
 
                   HA_POS_ERROR :
4719
 
                   join->unit->select_limit_cnt), 0,
4720
 
                  false) < 0)
 
4972
        sel->head=tab->table;
 
4973
        if (tab->quick)
 
4974
        {
 
4975
          /* Use quick key read if it's a constant and it's not used
 
4976
             with key reading */
 
4977
          if (tab->needed_reg.none() && tab->type != JT_EQ_REF
 
4978
              && (tab->type != JT_REF || (uint32_t) tab->ref.key == tab->quick->index))
 
4979
          {
 
4980
            sel->quick=tab->quick;              // Use value from get_quick_...
 
4981
            sel->quick_keys.reset();
 
4982
            sel->needed_reg.reset();
 
4983
          }
 
4984
          else
 
4985
          {
 
4986
            delete tab->quick;
 
4987
          }
 
4988
          tab->quick=0;
 
4989
        }
 
4990
        uint32_t ref_key=(uint32_t) sel->head->reginfo.join_tab->ref.key+1;
 
4991
        if (i == join->const_tables && ref_key)
 
4992
        {
 
4993
          if (tab->const_keys.any() &&
 
4994
              tab->table->reginfo.impossible_range)
 
4995
            return(1);
 
4996
        }
 
4997
        else if (tab->type == JT_ALL && ! use_quick_range)
 
4998
        {
 
4999
          if (tab->const_keys.any() &&
 
5000
              tab->table->reginfo.impossible_range)
 
5001
            return(1);                          // Impossible range
 
5002
          /*
 
5003
            We plan to scan all rows.
 
5004
            Check again if we should use an index.
 
5005
            We could have used an column from a previous table in
 
5006
            the index if we are using limit and this is the first table
 
5007
          */
 
5008
 
 
5009
          if ((cond && (!((tab->keys & tab->const_keys) == tab->keys) && i > 0)) ||
 
5010
              (!tab->const_keys.none() && (i == join->const_tables) && (join->unit->select_limit_cnt < join->best_positions[i].records_read) && ((join->select_options & OPTION_FOUND_ROWS) == false)))
 
5011
          {
 
5012
            /* Join with outer join condition */
 
5013
            COND *orig_cond=sel->cond;
 
5014
            sel->cond= and_conds(sel->cond, *tab->on_expr_ref);
 
5015
 
 
5016
            /*
 
5017
              We can't call sel->cond->fix_fields,
 
5018
              as it will break tab->on_expr if it's AND condition
 
5019
              (fix_fields currently removes extra AND/OR levels).
 
5020
              Yet attributes of the just built condition are not needed.
 
5021
              Thus we call sel->cond->quick_fix_field for safety.
 
5022
            */
 
5023
            if (sel->cond && !sel->cond->fixed)
 
5024
              sel->cond->quick_fix_field();
 
5025
 
 
5026
            if (sel->test_quick_select(session, tab->keys,
 
5027
                                       used_tables & ~ current_map,
 
5028
                                       (join->select_options &
 
5029
                                        OPTION_FOUND_ROWS ?
 
5030
                                        HA_POS_ERROR :
 
5031
                                        join->unit->select_limit_cnt), 0,
 
5032
                                        false) < 0)
4721
5033
            {
4722
 
              /*
4723
 
                 Before reporting "Impossible WHERE" for the whole query
4724
 
                 we have to check isn't it only "impossible ON" instead
4725
 
               */
 
5034
              /*
 
5035
                Before reporting "Impossible WHERE" for the whole query
 
5036
                we have to check isn't it only "impossible ON" instead
 
5037
              */
4726
5038
              sel->cond=orig_cond;
4727
 
              if (! *tab->on_expr_ref ||
 
5039
              if (!*tab->on_expr_ref ||
4728
5040
                  sel->test_quick_select(session, tab->keys,
4729
 
                    used_tables & ~ current_map,
4730
 
                    (join->select_options &
4731
 
                     OPTION_FOUND_ROWS ?
4732
 
                     HA_POS_ERROR :
4733
 
                     join->unit->select_limit_cnt),0,
4734
 
                    false) < 0)
4735
 
                return 1;                       // Impossible WHERE
 
5041
                                         used_tables & ~ current_map,
 
5042
                                         (join->select_options &
 
5043
                                          OPTION_FOUND_ROWS ?
 
5044
                                          HA_POS_ERROR :
 
5045
                                          join->unit->select_limit_cnt),0,
 
5046
                                          false) < 0)
 
5047
                return(1);                      // Impossible WHERE
4736
5048
            }
4737
5049
            else
4738
 
              sel->cond=orig_cond;
 
5050
              sel->cond=orig_cond;
4739
5051
 
4740
 
            /* Fix for EXPLAIN */
4741
 
            if (sel->quick)
4742
 
            {
4743
 
              cur_pos= join->getPosFromOptimalPlan(i);
4744
 
              cur_pos.setFanout(static_cast<double>(sel->quick->records));
4745
 
            }
4746
 
          }
4747
 
          else
4748
 
          {
4749
 
            sel->needed_reg= tab->needed_reg;
4750
 
            sel->quick_keys.reset();
4751
 
          }
 
5052
            /* Fix for EXPLAIN */
 
5053
            if (sel->quick)
 
5054
              join->best_positions[i].records_read= (double)sel->quick->records;
 
5055
          }
 
5056
          else
 
5057
          {
 
5058
            sel->needed_reg=tab->needed_reg;
 
5059
            sel->quick_keys.reset();
 
5060
          }
4752
5061
          if (!((tab->checked_keys & sel->quick_keys) == sel->quick_keys) ||
4753
5062
              !((tab->checked_keys & sel->needed_reg) == sel->needed_reg))
4754
 
          {
4755
 
            tab->keys= sel->quick_keys;
 
5063
          {
 
5064
            tab->keys= sel->quick_keys;
4756
5065
            tab->keys|= sel->needed_reg;
4757
 
            tab->use_quick= (!sel->needed_reg.none() &&
4758
 
                (select->quick_keys.none() ||
4759
 
                 (select->quick &&
4760
 
                  (select->quick->records >= 100L)))) ?
4761
 
              2 : 1;
4762
 
            sel->read_tables= used_tables & ~current_map;
4763
 
          }
4764
 
          if (i != join->const_tables && tab->use_quick != 2)
4765
 
          {                                     /* Read with cache */
4766
 
            if (cond &&
 
5066
            tab->use_quick= (!sel->needed_reg.none() &&
 
5067
                             (select->quick_keys.none() ||
 
5068
                              (select->quick &&
 
5069
                               (select->quick->records >= 100L)))) ?
 
5070
              2 : 1;
 
5071
            sel->read_tables= used_tables & ~current_map;
 
5072
          }
 
5073
          if (i != join->const_tables && tab->use_quick != 2)
 
5074
          {                                     /* Read with cache */
 
5075
            if (cond &&
4767
5076
                (tmp=make_cond_for_table(cond,
4768
 
                                         join->const_table_map |
4769
 
                                         current_map,
4770
 
                                         current_map, 0)))
4771
 
            {
4772
 
              tab->cache.select= (optimizer::SqlSelect*)
4773
 
                session->memdup((unsigned char*) sel, sizeof(optimizer::SqlSelect));
4774
 
              tab->cache.select->cond= tmp;
4775
 
              tab->cache.select->read_tables= join->const_table_map;
4776
 
            }
4777
 
          }
4778
 
        }
 
5077
                                         join->const_table_map |
 
5078
                                         current_map,
 
5079
                                         current_map, 0)))
 
5080
            {
 
5081
              tab->cache.select=(SQL_SELECT*)
 
5082
                session->memdup((unsigned char*) sel, sizeof(SQL_SELECT));
 
5083
              tab->cache.select->cond=tmp;
 
5084
              tab->cache.select->read_tables=join->const_table_map;
 
5085
            }
 
5086
          }
 
5087
        }
4779
5088
      }
4780
5089
 
4781
5090
      /*
4782
 
         Push down conditions from all on expressions.
4783
 
         Each of these conditions are guarded by a variable
4784
 
         that turns if off just before null complemented row for
4785
 
         outer joins is formed. Thus, the condition from an
4786
 
         'on expression' are guaranteed not to be checked for
4787
 
         the null complemented row.
4788
 
       */
 
5091
        Push down conditions from all on expressions.
 
5092
        Each of these conditions are guarded by a variable
 
5093
        that turns if off just before null complemented row for
 
5094
        outer joins is formed. Thus, the condition from an
 
5095
        'on expression' are guaranteed not to be checked for
 
5096
        the null complemented row.
 
5097
      */
4789
5098
 
4790
5099
      /* First push down constant conditions from on expressions */
4791
 
      for (JoinTable *join_tab= join->join_tab+join->const_tables;
4792
 
          join_tab < join->join_tab+join->tables ; join_tab++)
 
5100
      for (JOIN_TAB *join_tab= join->join_tab+join->const_tables;
 
5101
           join_tab < join->join_tab+join->tables ; join_tab++)
4793
5102
      {
4794
5103
        if (*join_tab->on_expr_ref)
4795
5104
        {
4796
 
          JoinTable *cond_tab= join_tab->first_inner;
 
5105
          JOIN_TAB *cond_tab= join_tab->first_inner;
4797
5106
          tmp= make_cond_for_table(*join_tab->on_expr_ref,
4798
 
              join->const_table_map,
4799
 
              (table_map) 0, 0);
 
5107
                                   join->const_table_map,
 
5108
                                   (table_map) 0, 0);
4800
5109
          if (!tmp)
4801
5110
            continue;
4802
5111
          tmp= new Item_func_trig_cond(tmp, &cond_tab->not_null_compl);
4803
 
          if (! tmp)
4804
 
            return 1;
 
5112
          if (!tmp)
 
5113
            return(1);
4805
5114
          tmp->quick_fix_field();
4806
5115
          cond_tab->select_cond= !cond_tab->select_cond ? tmp :
4807
 
            new Item_cond_and(cond_tab->select_cond,tmp);
4808
 
          if (! cond_tab->select_cond)
4809
 
            return 1;
 
5116
                                    new Item_cond_and(cond_tab->select_cond,tmp);
 
5117
          if (!cond_tab->select_cond)
 
5118
            return(1);
4810
5119
          cond_tab->select_cond->quick_fix_field();
4811
5120
        }
4812
5121
      }
4813
5122
 
4814
5123
      /* Push down non-constant conditions from on expressions */
4815
 
      JoinTable *last_tab= tab;
 
5124
      JOIN_TAB *last_tab= tab;
4816
5125
      while (first_inner_tab && first_inner_tab->last_inner == last_tab)
4817
5126
      {
4818
5127
        /*
4819
 
           Table tab is the last inner table of an outer join.
4820
 
           An on expression is always attached to it.
4821
 
         */
 
5128
          Table tab is the last inner table of an outer join.
 
5129
          An on expression is always attached to it.
 
5130
        */
4822
5131
        COND *on_expr= *first_inner_tab->on_expr_ref;
4823
5132
 
4824
5133
        table_map used_tables2= (join->const_table_map |
4825
 
            OUTER_REF_TABLE_BIT | RAND_TABLE_BIT);
4826
 
        for (tab= join->join_tab+join->const_tables; tab <= last_tab ; tab++)
 
5134
                                 OUTER_REF_TABLE_BIT | RAND_TABLE_BIT);
 
5135
        for (tab= join->join_tab+join->const_tables; tab <= last_tab ; tab++)
4827
5136
        {
4828
5137
          current_map= tab->table->map;
4829
5138
          used_tables2|= current_map;
4830
5139
          COND *tmp_cond= make_cond_for_table(on_expr, used_tables2,
4831
 
              current_map, 0);
 
5140
                                              current_map, 0);
4832
5141
          if (tmp_cond)
4833
5142
          {
4834
 
            JoinTable *cond_tab= tab < first_inner_tab ? first_inner_tab : tab;
 
5143
            JOIN_TAB *cond_tab= tab < first_inner_tab ? first_inner_tab : tab;
4835
5144
            /*
4836
 
               First add the guards for match variables of
4837
 
               all embedding outer join operations.
4838
 
             */
 
5145
              First add the guards for match variables of
 
5146
              all embedding outer join operations.
 
5147
            */
4839
5148
            if (!(tmp_cond= add_found_match_trig_cond(cond_tab->first_inner,
4840
 
                                                      tmp_cond,
4841
 
                                                      first_inner_tab)))
4842
 
              return 1;
 
5149
                                                     tmp_cond,
 
5150
                                                     first_inner_tab)))
 
5151
              return(1);
4843
5152
            /*
4844
 
               Now add the guard turning the predicate off for
4845
 
               the null complemented row.
4846
 
             */
 
5153
              Now add the guard turning the predicate off for
 
5154
              the null complemented row.
 
5155
            */
4847
5156
            tmp_cond= new Item_func_trig_cond(tmp_cond,
4848
 
                &first_inner_tab->
4849
 
                not_null_compl);
 
5157
                                              &first_inner_tab->
 
5158
                                              not_null_compl);
4850
5159
            if (tmp_cond)
4851
5160
              tmp_cond->quick_fix_field();
4852
 
            /* Add the predicate to other pushed down predicates */
 
5161
            /* Add the predicate to other pushed down predicates */
4853
5162
            cond_tab->select_cond= !cond_tab->select_cond ? tmp_cond :
4854
 
              new Item_cond_and(cond_tab->select_cond,
4855
 
                                tmp_cond);
4856
 
            if (! cond_tab->select_cond)
4857
 
              return 1;
 
5163
                                  new Item_cond_and(cond_tab->select_cond,
 
5164
                                                    tmp_cond);
 
5165
            if (!cond_tab->select_cond)
 
5166
              return(1);
4858
5167
            cond_tab->select_cond->quick_fix_field();
4859
5168
          }
4860
5169
        }
4886
5195
    false - OK
4887
5196
    true  - Out of memory
4888
5197
*/
4889
 
static bool make_join_readinfo(Join *join)
 
5198
static bool make_join_readinfo(JOIN *join, uint64_t options, uint32_t no_jbuf_after)
4890
5199
{
4891
 
  bool sorted= true;
 
5200
  uint32_t i;
 
5201
  bool statistics= test(!(join->select_options & SELECT_DESCRIBE));
 
5202
  bool sorted= 1;
4892
5203
 
4893
 
  for (uint32_t i= join->const_tables ; i < join->tables ; i++)
 
5204
  for (i=join->const_tables ; i < join->tables ; i++)
4894
5205
  {
4895
 
    JoinTable *tab=join->join_tab+i;
 
5206
    JOIN_TAB *tab=join->join_tab+i;
4896
5207
    Table *table=tab->table;
 
5208
    bool using_join_cache;
4897
5209
    tab->read_record.table= table;
4898
 
    tab->read_record.cursor= table->cursor;
 
5210
    tab->read_record.file=table->file;
4899
5211
    tab->next_select=sub_select;                /* normal select */
4900
5212
    /*
4901
5213
      TODO: don't always instruct first table's ref/range access method to
4902
5214
      produce sorted output.
4903
5215
    */
4904
5216
    tab->sorted= sorted;
4905
 
    sorted= false; // only first must be sorted
4906
 
 
 
5217
    sorted= 0;                                  // only first must be sorted
4907
5218
    if (tab->insideout_match_tab)
4908
5219
    {
4909
 
      if (! (tab->insideout_buf= (unsigned char*) join->session->alloc(tab->table->key_info
4910
 
                                                                       [tab->index].
4911
 
                                                                       key_length)))
 
5220
      if (!(tab->insideout_buf= (unsigned char*)join->session->alloc(tab->table->key_info
 
5221
                                                         [tab->index].
 
5222
                                                         key_length)))
4912
5223
        return true;
4913
5224
    }
4914
 
 
4915
 
    optimizer::AccessMethodFactory &factory= optimizer::AccessMethodFactory::singleton();
4916
 
    boost::shared_ptr<optimizer::AccessMethod> access_method(factory.createAccessMethod(tab->type));
4917
 
 
4918
 
    if (! access_method)
4919
 
    {
4920
 
      /**
4921
 
       * @todo
4922
 
       * Is abort() the correct thing to call here? I call this here because it was what was called in
4923
 
       * the default case for the switch statement that used to be here.
4924
 
       */
4925
 
      abort();
 
5225
    switch (tab->type) {
 
5226
    case JT_SYSTEM:                             // Only happens with left join
 
5227
      table->status=STATUS_NO_RECORD;
 
5228
      tab->read_first_record= join_read_system;
 
5229
      tab->read_record.read_record= join_no_more_records;
 
5230
      break;
 
5231
    case JT_CONST:                              // Only happens with left join
 
5232
      table->status=STATUS_NO_RECORD;
 
5233
      tab->read_first_record= join_read_const;
 
5234
      tab->read_record.read_record= join_no_more_records;
 
5235
      if (table->covering_keys.test(tab->ref.key) &&
 
5236
          !table->no_keyread)
 
5237
      {
 
5238
        table->key_read=1;
 
5239
        table->file->extra(HA_EXTRA_KEYREAD);
 
5240
      }
 
5241
      break;
 
5242
    case JT_EQ_REF:
 
5243
      table->status=STATUS_NO_RECORD;
 
5244
      if (tab->select)
 
5245
      {
 
5246
        delete tab->select->quick;
 
5247
        tab->select->quick=0;
 
5248
      }
 
5249
      delete tab->quick;
 
5250
      tab->quick=0;
 
5251
      tab->read_first_record= join_read_key;
 
5252
      tab->read_record.read_record= join_no_more_records;
 
5253
      if (table->covering_keys.test(tab->ref.key) && !table->no_keyread)
 
5254
      {
 
5255
        table->key_read=1;
 
5256
        table->file->extra(HA_EXTRA_KEYREAD);
 
5257
      }
 
5258
      else
 
5259
        push_index_cond(tab, tab->ref.key, true);
 
5260
      break;
 
5261
    case JT_REF_OR_NULL:
 
5262
    case JT_REF:
 
5263
      table->status=STATUS_NO_RECORD;
 
5264
      if (tab->select)
 
5265
      {
 
5266
        delete tab->select->quick;
 
5267
        tab->select->quick=0;
 
5268
      }
 
5269
      delete tab->quick;
 
5270
      tab->quick=0;
 
5271
      if (table->covering_keys.test(tab->ref.key) && !table->no_keyread)
 
5272
      {
 
5273
        table->key_read=1;
 
5274
        table->file->extra(HA_EXTRA_KEYREAD);
 
5275
      }
 
5276
      else
 
5277
        push_index_cond(tab, tab->ref.key, true);
 
5278
      if (tab->type == JT_REF)
 
5279
      {
 
5280
        tab->read_first_record= join_read_always_key;
 
5281
        tab->read_record.read_record= tab->insideout_match_tab?
 
5282
           join_read_next_same_diff : join_read_next_same;
 
5283
      }
 
5284
      else
 
5285
      {
 
5286
        tab->read_first_record= join_read_always_key_or_null;
 
5287
        tab->read_record.read_record= join_read_next_same_or_null;
 
5288
      }
 
5289
      break;
 
5290
    case JT_ALL:
 
5291
      /*
 
5292
        If previous table use cache
 
5293
        If the incoming data set is already sorted don't use cache.
 
5294
      */
 
5295
      table->status=STATUS_NO_RECORD;
 
5296
      using_join_cache= false;
 
5297
      if (i != join->const_tables && !(options & SELECT_NO_JOIN_CACHE) &&
 
5298
          tab->use_quick != 2 && !tab->first_inner && i <= no_jbuf_after &&
 
5299
          !tab->insideout_match_tab)
 
5300
      {
 
5301
        if ((options & SELECT_DESCRIBE) ||
 
5302
            !join_init_cache(join->session,join->join_tab+join->const_tables,
 
5303
                i-join->const_tables))
 
5304
        {
 
5305
                using_join_cache= true;
 
5306
          tab[-1].next_select=sub_select_cache; /* Patch previous */
 
5307
        }
 
5308
      }
 
5309
      /* These init changes read_record */
 
5310
      if (tab->use_quick == 2)
 
5311
      {
 
5312
        join->session->server_status|=SERVER_QUERY_NO_GOOD_INDEX_USED;
 
5313
        tab->read_first_record= join_init_quick_read_record;
 
5314
        if (statistics)
 
5315
          status_var_increment(join->session->status_var.select_range_check_count);
 
5316
      }
 
5317
      else
 
5318
      {
 
5319
        tab->read_first_record= join_init_read_record;
 
5320
        if (i == join->const_tables)
 
5321
        {
 
5322
          if (tab->select && tab->select->quick)
 
5323
          {
 
5324
            if (statistics)
 
5325
              status_var_increment(join->session->status_var.select_range_count);
 
5326
          }
 
5327
          else
 
5328
          {
 
5329
            join->session->server_status|=SERVER_QUERY_NO_INDEX_USED;
 
5330
            if (statistics)
 
5331
              status_var_increment(join->session->status_var.select_scan_count);
 
5332
          }
 
5333
        }
 
5334
        else
 
5335
        {
 
5336
          if (tab->select && tab->select->quick)
 
5337
          {
 
5338
            if (statistics)
 
5339
              status_var_increment(join->session->status_var.select_full_range_join_count);
 
5340
          }
 
5341
          else
 
5342
          {
 
5343
            join->session->server_status|=SERVER_QUERY_NO_INDEX_USED;
 
5344
            if (statistics)
 
5345
              status_var_increment(join->session->status_var.select_full_join_count);
 
5346
          }
 
5347
        }
 
5348
        if (!table->no_keyread)
 
5349
        {
 
5350
          if (tab->select && tab->select->quick &&
 
5351
                    tab->select->quick->index != MAX_KEY && //not index_merge
 
5352
              table->covering_keys.test(tab->select->quick->index))
 
5353
          {
 
5354
            table->key_read=1;
 
5355
            table->file->extra(HA_EXTRA_KEYREAD);
 
5356
          }
 
5357
          else if (!table->covering_keys.none() &&
 
5358
            !(tab->select && tab->select->quick))
 
5359
          {                                     // Only read index tree
 
5360
                  if (!tab->insideout_match_tab)
 
5361
                  {
 
5362
                    /*
 
5363
                      See bug #26447: "Using the clustered index for a table scan
 
5364
                      is always faster than using a secondary index".
 
5365
                    */
 
5366
                    if (table->s->primary_key != MAX_KEY &&
 
5367
                        table->file->primary_key_is_clustered())
 
5368
                      tab->index= table->s->primary_key;
 
5369
                    else
 
5370
                      tab->index= table->find_shortest_key(&table->covering_keys);
 
5371
                  }
 
5372
            tab->read_first_record= join_read_first;
 
5373
            tab->type=JT_NEXT;          // Read with index_first / index_next
 
5374
          }
 
5375
        }
 
5376
        if (tab->select && tab->select->quick &&
 
5377
            tab->select->quick->index != MAX_KEY && ! tab->table->key_read)
 
5378
          push_index_cond(tab, tab->select->quick->index, !using_join_cache);
 
5379
      }
 
5380
      break;
 
5381
    default:
 
5382
      break;                                    /* purecov: deadcode */
 
5383
    case JT_UNKNOWN:
 
5384
    case JT_MAYBE_REF:
 
5385
      abort();                                  /* purecov: deadcode */
4926
5386
    }
4927
 
 
4928
 
    access_method->getStats(table, tab);
4929
5387
  }
4930
 
 
4931
 
  join->join_tab[join->tables-1].next_select= NULL; /* Set by do_select */
4932
 
 
4933
 
  return false;
 
5388
  join->join_tab[join->tables-1].next_select=0; /* Set by do_select */
 
5389
  return(false);
4934
5390
}
4935
5391
 
4936
5392
/** Update the dependency map for the tables. */
4937
 
static void update_depend_map(Join *join)
 
5393
static void update_depend_map(JOIN *join)
4938
5394
{
4939
 
  JoinTable *join_tab=join->join_tab, *end=join_tab+join->tables;
 
5395
  JOIN_TAB *join_tab=join->join_tab, *end=join_tab+join->tables;
4940
5396
 
4941
5397
  for (; join_tab != end ; join_tab++)
4942
5398
  {
4943
 
    table_reference_st *ref= &join_tab->ref;
4944
 
    table_map depend_map= 0;
 
5399
    TABLE_REF *ref= &join_tab->ref;
 
5400
    table_map depend_map=0;
4945
5401
    Item **item=ref->items;
4946
5402
    uint32_t i;
4947
5403
    for (i=0 ; i < ref->key_parts ; i++,item++)
4948
5404
      depend_map|=(*item)->used_tables();
4949
5405
    ref->depend_map=depend_map & ~OUTER_REF_TABLE_BIT;
4950
5406
    depend_map&= ~OUTER_REF_TABLE_BIT;
4951
 
    for (JoinTable **tab=join->map2table; depend_map; tab++,depend_map>>=1 )
 
5407
    for (JOIN_TAB **tab=join->map2table; depend_map; tab++,depend_map>>=1 )
4952
5408
    {
4953
5409
      if (depend_map & 1)
4954
5410
        ref->depend_map|=(*tab)->ref.depend_map;
4957
5413
}
4958
5414
 
4959
5415
/** Update the dependency map for the sort order. */
4960
 
static void update_depend_map(Join *join, Order *order)
 
5416
static void update_depend_map(JOIN *join, order_st *order)
4961
5417
{
4962
5418
  for (; order ; order=order->next)
4963
5419
  {
4968
5424
    if (!(order->depend_map & (OUTER_REF_TABLE_BIT | RAND_TABLE_BIT))
4969
5425
        && !order->item[0]->with_sum_func)
4970
5426
    {
4971
 
      for (JoinTable **tab=join->map2table; depend_map; tab++, depend_map>>=1)
 
5427
      for (JOIN_TAB **tab=join->map2table; depend_map; tab++, depend_map>>=1)
4972
5428
      {
4973
5429
        if (depend_map & 1)
4974
5430
          order->depend_map|=(*tab)->ref.depend_map;
4995
5451
  @return
4996
5452
    Returns new sort order
4997
5453
*/
4998
 
static Order *remove_constants(Join *join,Order *first_order, COND *cond, bool change_list, bool *simple_order)
 
5454
static order_st *remove_constants(JOIN *join,order_st *first_order, COND *cond, bool change_list, bool *simple_order)
4999
5455
{
5000
5456
  if (join->tables == join->const_tables)
5001
5457
    return change_list ? 0 : first_order;               // No need to sort
5002
5458
 
5003
 
  Order *order,**prev_ptr;
 
5459
  order_st *order,**prev_ptr;
5004
5460
  table_map first_table= join->join_tab[join->const_tables].table->map;
5005
5461
  table_map not_const_tables= ~join->const_table_map;
5006
5462
  table_map ref;
5055
5511
  return(first_order);
5056
5512
}
5057
5513
 
5058
 
static int return_zero_rows(Join *join,
 
5514
static int return_zero_rows(JOIN *join,
5059
5515
                            select_result *result,
5060
5516
                            TableList *tables,
5061
5517
                                        List<Item> &fields,
5066
5522
{
5067
5523
  if (select_options & SELECT_DESCRIBE)
5068
5524
  {
5069
 
    optimizer::ExplainPlan planner(join,
5070
 
                                   false,
5071
 
                                   false,
5072
 
                                   false,
5073
 
                                   info);
5074
 
    planner.printPlan();
5075
 
    return 0;
 
5525
    select_describe(join, false, false, false, info);
 
5526
    return(0);
5076
5527
  }
5077
5528
 
5078
5529
  join->join_free();
5084
5535
    if (having && having->val_int() == 0)
5085
5536
      send_row=0;
5086
5537
  }
5087
 
  if (! (result->send_fields(fields)))
 
5538
  if (!(result->send_fields(fields, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)))
5088
5539
  {
5089
5540
    if (send_row)
5090
5541
    {
5221
5672
    - The new condition, if success
5222
5673
    - 0, otherwise
5223
5674
*/
5224
 
static COND *simplify_joins(Join *join, List<TableList> *join_list, COND *conds, bool top)
 
5675
static COND *simplify_joins(JOIN *join, List<TableList> *join_list, COND *conds, bool top, bool in_sj)
5225
5676
{
5226
5677
  TableList *table;
5227
5678
  nested_join_st *nested_join;
5237
5688
    table_map used_tables;
5238
5689
    table_map not_null_tables= (table_map) 0;
5239
5690
 
5240
 
    if ((nested_join= table->getNestedJoin()))
 
5691
    if ((nested_join= table->nested_join))
5241
5692
    {
5242
5693
      /*
5243
5694
         If the element of join_list is a nested join apply
5254
5705
           the outer join is converted to an inner join and
5255
5706
           the corresponding on expression is added to E.
5256
5707
              */
5257
 
        expr= simplify_joins(join, &nested_join->join_list, expr, false);
 
5708
        expr= simplify_joins(join, &nested_join->join_list,
 
5709
                             expr, false, in_sj || table->sj_on_expr);
5258
5710
 
5259
5711
        if (!table->prep_on_expr || expr != table->on_expr)
5260
5712
        {
5266
5718
      }
5267
5719
      nested_join->used_tables= (table_map) 0;
5268
5720
      nested_join->not_null_tables=(table_map) 0;
5269
 
      conds= simplify_joins(join, &nested_join->join_list, conds, top);
 
5721
      conds= simplify_joins(join, &nested_join->join_list, conds, top, in_sj || table->sj_on_expr);
5270
5722
      used_tables= nested_join->used_tables;
5271
5723
      not_null_tables= nested_join->not_null_tables;
5272
5724
    }
5279
5731
        not_null_tables= conds->not_null_tables();
5280
5732
    }
5281
5733
 
5282
 
    if (table->getEmbedding())
 
5734
    if (table->embedding)
5283
5735
    {
5284
 
      table->getEmbedding()->getNestedJoin()->used_tables|= used_tables;
5285
 
      table->getEmbedding()->getNestedJoin()->not_null_tables|= not_null_tables;
 
5736
      table->embedding->nested_join->used_tables|= used_tables;
 
5737
      table->embedding->nested_join->not_null_tables|= not_null_tables;
5286
5738
    }
5287
5739
 
5288
5740
    if (!table->outer_join || (used_tables & not_null_tables))
5318
5770
    */
5319
5771
    if (table->on_expr)
5320
5772
    {
5321
 
      table->setDepTables(table->getDepTables() | table->on_expr->used_tables());
5322
 
      if (table->getEmbedding())
 
5773
      table->dep_tables|= table->on_expr->used_tables();
 
5774
      if (table->embedding)
5323
5775
      {
5324
 
        table->setDepTables(table->getDepTables() & ~table->getEmbedding()->getNestedJoin()->used_tables);
 
5776
        table->dep_tables&= ~table->embedding->nested_join->used_tables;
5325
5777
        /*
5326
5778
           Embedding table depends on tables used
5327
5779
           in embedded on expressions.
5328
5780
        */
5329
 
        table->getEmbedding()->setOnExprDepTables(table->getEmbedding()->getOnExprDepTables() & table->on_expr->used_tables());
 
5781
        table->embedding->on_expr_dep_tables|= table->on_expr->used_tables();
5330
5782
      }
5331
5783
      else
5332
 
        table->setDepTables(table->getDepTables() & ~table->table->map);
 
5784
        table->dep_tables&= ~table->table->map;
5333
5785
    }
5334
5786
 
5335
5787
    if (prev_table)
5336
5788
    {
5337
 
      //If this is straight join, set prev table to be dependent on all tables
5338
 
      //from this nested join, so that correct join order is selected.
5339
 
      if ((test(join->select_options & SELECT_STRAIGHT_JOIN)) ||
5340
 
          prev_table->straight)
5341
 
        prev_table->setDepTables(prev_table->getDepTables() | used_tables);
 
5789
      /* The order of tables is reverse: prev_table follows table */
 
5790
      if (prev_table->straight)
 
5791
        prev_table->dep_tables|= used_tables;
5342
5792
      if (prev_table->on_expr)
5343
5793
      {
5344
 
        prev_table->setDepTables(prev_table->getDepTables() | table->getOnExprDepTables());
5345
 
        table_map prev_used_tables= prev_table->getNestedJoin() ?
5346
 
                                    prev_table->getNestedJoin()->used_tables :
 
5794
        prev_table->dep_tables|= table->on_expr_dep_tables;
 
5795
        table_map prev_used_tables= prev_table->nested_join ?
 
5796
                                    prev_table->nested_join->used_tables :
5347
5797
                                    prev_table->table->map;
5348
5798
        /*
5349
5799
          If on expression contains only references to inner tables
5352
5802
          for them. Yet this is really a rare case.
5353
5803
              */
5354
5804
        if (!(prev_table->on_expr->used_tables() & ~prev_used_tables))
5355
 
          prev_table->setDepTables(prev_table->getDepTables() | used_tables);
 
5805
          prev_table->dep_tables|= used_tables;
5356
5806
      }
5357
5807
    }
5358
5808
    prev_table= table;
5365
5815
  li.rewind();
5366
5816
  while ((table= li++))
5367
5817
  {
5368
 
    nested_join= table->getNestedJoin();
5369
 
    if (nested_join && !table->on_expr)
 
5818
    nested_join= table->nested_join;
 
5819
    if (table->sj_on_expr && !in_sj)
 
5820
    {
 
5821
       /*
 
5822
         If this is a semi-join that is not contained within another semi-join,
 
5823
         leave it intact (otherwise it is flattened)
 
5824
       */
 
5825
      join->select_lex->sj_nests.push_back(table);
 
5826
    }
 
5827
    else if (nested_join && !table->on_expr)
5370
5828
    {
5371
5829
      TableList *tbl;
5372
5830
      List_iterator<TableList> it(nested_join->join_list);
5373
5831
      while ((tbl= it++))
5374
5832
      {
5375
 
        tbl->setEmbedding(table->getEmbedding());
5376
 
        tbl->setJoinList(table->getJoinList());
 
5833
        tbl->embedding= table->embedding;
 
5834
        tbl->join_list= table->join_list;
5377
5835
      }
5378
5836
      li.replace(nested_join->join_list);
5379
5837
    }
5381
5839
  return(conds);
5382
5840
}
5383
5841
 
5384
 
static int remove_duplicates(Join *join, Table *entry,List<Item> &fields, Item *having)
 
5842
static int remove_duplicates(JOIN *join, Table *entry,List<Item> &fields, Item *having)
5385
5843
{
5386
5844
  int error;
5387
5845
  uint32_t reclength,offset;
5405
5863
    join->unit->select_limit_cnt= 1;            // Only send first row
5406
5864
    return(0);
5407
5865
  }
5408
 
  Field **first_field=entry->getFields() + entry->getShare()->sizeFields() - field_count;
 
5866
  Field **first_field=entry->field+entry->s->fields - field_count;
5409
5867
  offset= (field_count ?
5410
 
           entry->getField(entry->getShare()->sizeFields() - field_count)->offset(entry->getInsertRecord()) : 0);
5411
 
  reclength= entry->getShare()->getRecordLength() - offset;
 
5868
           entry->field[entry->s->fields - field_count]->
 
5869
           offset(entry->record[0]) : 0);
 
5870
  reclength= entry->s->reclength-offset;
5412
5871
 
5413
 
  entry->free_io_cache();                               // Safety
5414
 
  entry->cursor->info(HA_STATUS_VARIABLE);
5415
 
  if (entry->getShare()->db_type() == heap_engine ||
5416
 
      (!entry->getShare()->blob_fields &&
5417
 
       ((ALIGN_SIZE(reclength) + HASH_OVERHEAD) * entry->cursor->stats.records <
5418
 
        session->variables.sortbuff_size)))
5419
 
  {
 
5872
  free_io_cache(entry);                         // Safety
 
5873
  entry->file->info(HA_STATUS_VARIABLE);
 
5874
  if (entry->s->db_type() == heap_engine ||
 
5875
      (!entry->s->blob_fields &&
 
5876
       ((ALIGN_SIZE(reclength) + HASH_OVERHEAD) * entry->file->stats.records <
 
5877
        session->variables.sortbuff_size)))
5420
5878
    error= remove_dup_with_hash_index(join->session, entry,
5421
 
                                      field_count, first_field,
5422
 
                                      reclength, having);
5423
 
  }
 
5879
                                     field_count, first_field,
 
5880
                                     reclength, having);
5424
5881
  else
5425
 
  {
5426
 
    error= remove_dup_with_compare(join->session, entry, first_field, offset, having);
5427
 
  }
 
5882
    error= remove_dup_with_compare(join->session, entry, first_field, offset,
 
5883
                                  having);
5428
5884
 
5429
5885
  free_blobs(first_field);
5430
 
 
5431
5886
  return(error);
5432
5887
}
5433
5888
 
5441
5896
                               List<Item> &fields,
5442
5897
                               List<Item> &all_fields,
5443
5898
                               COND **conds,
5444
 
                               Order *order,
5445
 
                               Order *group,
 
5899
                               order_st *order,
 
5900
                               order_st *group,
5446
5901
                               bool *hidden_group_fields)
5447
5902
{
5448
5903
  int res;
5449
5904
  nesting_map save_allow_sum_func=session->lex->allow_sum_func ;
5450
5905
 
5451
5906
  session->lex->allow_sum_func&= ~(1 << session->lex->current_select->nest_level);
5452
 
  res= session->setup_conds(tables, conds);
 
5907
  res= setup_conds(session, tables, conds);
5453
5908
 
5454
5909
  session->lex->allow_sum_func|= 1 << session->lex->current_select->nest_level;
5455
5910
  res= res || setup_order(session, ref_pointer_array, tables, fields, all_fields,
5469
5924
  @retval
5470
5925
    1   Fatal error
5471
5926
*/
5472
 
static bool make_join_statistics(Join *join, TableList *tables, COND *conds, DYNAMIC_ARRAY *keyuse_array)
 
5927
static bool make_join_statistics(JOIN *join, TableList *tables, COND *conds, DYNAMIC_ARRAY *keyuse_array)
5473
5928
{
5474
5929
  int error;
5475
5930
  Table *table;
5476
 
  uint32_t i;
5477
 
  uint32_t table_count;
5478
 
  uint32_t const_count;
5479
 
  uint32_t key;
5480
 
  table_map found_const_table_map;
5481
 
  table_map all_table_map;
5482
 
  table_map found_ref;
5483
 
  table_map refs;
5484
 
  key_map const_ref;
5485
 
  key_map eq_part;
5486
 
  Table **table_vector= NULL;
5487
 
  JoinTable *stat= NULL;
5488
 
  JoinTable *stat_end= NULL;
5489
 
  JoinTable *s= NULL;
5490
 
  JoinTable **stat_ref= NULL;
5491
 
  optimizer::KeyUse *keyuse= NULL;
5492
 
  optimizer::KeyUse *start_keyuse= NULL;
5493
 
  table_map outer_join= 0;
5494
 
  vector<optimizer::SargableParam> sargables;
5495
 
  JoinTable *stat_vector[MAX_TABLES+1];
5496
 
  optimizer::Position *partial_pos;
 
5931
  uint32_t i,table_count,const_count,key;
 
5932
  table_map found_const_table_map, all_table_map, found_ref, refs;
 
5933
  key_map const_ref, eq_part;
 
5934
  Table **table_vector;
 
5935
  JOIN_TAB *stat,*stat_end,*s,**stat_ref;
 
5936
  KEYUSE *keyuse,*start_keyuse;
 
5937
  table_map outer_join=0;
 
5938
  SARGABLE_PARAM *sargables= 0;
 
5939
  JOIN_TAB *stat_vector[MAX_TABLES+1];
5497
5940
 
5498
 
  table_count= join->tables;
5499
 
  stat= (JoinTable*) join->session->calloc(sizeof(JoinTable)*table_count);
5500
 
  stat_ref= (JoinTable**) join->session->alloc(sizeof(JoinTable*)*MAX_TABLES);
5501
 
  table_vector= (Table**) join->session->alloc(sizeof(Table*)*(table_count*2));
5502
 
  if (! stat || ! stat_ref || ! table_vector)
5503
 
    return 1;
 
5941
  table_count=join->tables;
 
5942
  stat=(JOIN_TAB*) join->session->calloc(sizeof(JOIN_TAB)*table_count);
 
5943
  stat_ref=(JOIN_TAB**) join->session->alloc(sizeof(JOIN_TAB*)*MAX_TABLES);
 
5944
  table_vector=(Table**) join->session->alloc(sizeof(Table*)*(table_count*2));
 
5945
  if (!stat || !stat_ref || !table_vector)
 
5946
    return(1);                          // Eom /* purecov: inspected */
5504
5947
 
5505
5948
  join->best_ref=stat_vector;
5506
5949
 
5512
5955
       tables;
5513
5956
       s++, tables= tables->next_leaf, i++)
5514
5957
  {
5515
 
    TableList *embedding= tables->getEmbedding();
 
5958
    TableList *embedding= tables->embedding;
5516
5959
    stat_vector[i]=s;
5517
5960
    s->keys.reset();
5518
5961
    s->const_keys.reset();
5520
5963
    s->needed_reg.reset();
5521
5964
    table_vector[i]=s->table=table=tables->table;
5522
5965
    table->pos_in_table_list= tables;
5523
 
    assert(table->cursor);
5524
 
    error= table->cursor->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);
5525
 
    if (error)
 
5966
    error= table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);
 
5967
    if(error)
5526
5968
    {
5527
 
        table->print_error(error, MYF(0));
5528
 
        return 1;
 
5969
        table->file->print_error(error, MYF(0));
 
5970
        return(1);
5529
5971
    }
5530
5972
    table->quick_keys.reset();
5531
5973
    table->reginfo.join_tab=s;
5532
5974
    table->reginfo.not_exists_optimize=0;
5533
5975
    memset(table->const_key_parts, 0,
5534
 
           sizeof(key_part_map)*table->getShare()->sizeKeys());
 
5976
           sizeof(key_part_map)*table->s->keys);
5535
5977
    all_table_map|= table->map;
5536
5978
    s->join=join;
5537
5979
    s->info=0;                                  // For describe
5538
5980
 
5539
 
    s->dependent= tables->getDepTables();
 
5981
    s->dependent= tables->dep_tables;
5540
5982
    s->key_dependent= 0;
5541
 
    table->quick_condition_rows= table->cursor->stats.records;
 
5983
    if (tables->schema_table)
 
5984
      table->file->stats.records= 2;
 
5985
    table->quick_condition_rows= table->file->stats.records;
5542
5986
 
5543
5987
    s->on_expr_ref= &tables->on_expr;
5544
5988
    if (*s->on_expr_ref)
5545
5989
    {
5546
5990
      /* s is the only inner table of an outer join */
5547
 
      if (!table->cursor->stats.records && !embedding)
 
5991
      if (!table->file->stats.records && !embedding)
5548
5992
      {                                         // Empty table
5549
5993
        s->dependent= 0;                        // Ignore LEFT JOIN depend.
5550
 
        set_position(join, const_count++, s, (optimizer::KeyUse*) 0);
 
5994
        set_position(join,const_count++,s,(KEYUSE*) 0);
5551
5995
        continue;
5552
5996
      }
5553
5997
      outer_join|= table->map;
5554
 
      s->embedding_map.reset();
5555
 
      for (;embedding; embedding= embedding->getEmbedding())
5556
 
        s->embedding_map|= embedding->getNestedJoin()->nj_map;
 
5998
      s->embedding_map= 0;
 
5999
      for (;embedding; embedding= embedding->embedding)
 
6000
        s->embedding_map|= embedding->nested_join->nj_map;
5557
6001
      continue;
5558
6002
    }
5559
 
    if (embedding && !(false && ! embedding->getEmbedding()))
 
6003
    if (embedding && !(embedding->sj_on_expr && ! embedding->embedding))
5560
6004
    {
5561
6005
      /* s belongs to a nested join, maybe to several embedded joins */
5562
 
      s->embedding_map.reset();
 
6006
      s->embedding_map= 0;
5563
6007
      do
5564
6008
      {
5565
 
        nested_join_st *nested_join= embedding->getNestedJoin();
5566
 
        s->embedding_map|= nested_join->nj_map;
5567
 
        s->dependent|= embedding->getDepTables();
5568
 
        embedding= embedding->getEmbedding();
 
6009
        nested_join_st *nested_join= embedding->nested_join;
 
6010
        s->embedding_map|=nested_join->nj_map;
 
6011
        s->dependent|= embedding->dep_tables;
 
6012
        embedding= embedding->embedding;
5569
6013
        outer_join|= nested_join->used_tables;
5570
6014
      }
5571
6015
      while (embedding);
5572
6016
      continue;
5573
6017
    }
5574
 
    if ((table->cursor->stats.records <= 1) && !s->dependent &&
5575
 
              (table->cursor->getEngine()->check_flag(HTON_BIT_STATS_RECORDS_IS_EXACT)) &&
 
6018
    if ((table->file->stats.records <= 1) && !s->dependent &&
 
6019
              (table->file->ha_table_flags() & HA_STATS_RECORDS_IS_EXACT) && 
5576
6020
        !join->no_const_tables)
5577
6021
    {
5578
 
      set_position(join, const_count++, s, (optimizer::KeyUse*) 0);
 
6022
      set_position(join,const_count++,s,(KEYUSE*) 0);
5579
6023
    }
5580
6024
  }
5581
6025
  stat_vector[i]=0;
5609
6053
      {
5610
6054
        join->tables=0;                 // Don't use join->table
5611
6055
        my_message(ER_WRONG_OUTER_JOIN, ER(ER_WRONG_OUTER_JOIN), MYF(0));
5612
 
        return 1;
 
6056
        return(1);
5613
6057
      }
5614
6058
      s->key_dependent= s->dependent;
5615
6059
    }
5618
6062
  if (conds || outer_join)
5619
6063
    if (update_ref_and_keys(join->session, keyuse_array, stat, join->tables,
5620
6064
                            conds, join->cond_equal,
5621
 
                            ~outer_join, join->select_lex, sargables))
5622
 
      return 1;
 
6065
                            ~outer_join, join->select_lex, &sargables))
 
6066
      return(1);
5623
6067
 
5624
6068
  /* Read tables with 0 or 1 rows (system tables) */
5625
6069
  join->const_table_map= 0;
5626
6070
 
5627
 
  optimizer::Position *p_pos= join->getFirstPosInPartialPlan();
5628
 
  optimizer::Position *p_end= join->getSpecificPosInPartialPlan(const_count);
5629
 
  while (p_pos < p_end)
 
6071
  for (POSITION *p_pos=join->positions, *p_end=p_pos+const_count;
 
6072
       p_pos < p_end ;
 
6073
       p_pos++)
5630
6074
  {
5631
6075
    int tmp;
5632
 
    s= p_pos->getJoinTable();
5633
 
    s->type= AM_SYSTEM;
 
6076
    s= p_pos->table;
 
6077
    s->type=JT_SYSTEM;
5634
6078
    join->const_table_map|=s->table->map;
5635
 
    if ((tmp= join_read_const_table(s, p_pos)))
 
6079
    if ((tmp=join_read_const_table(s, p_pos)))
5636
6080
    {
5637
6081
      if (tmp > 0)
5638
 
        return 1;                       // Fatal error
 
6082
        return(1);                      // Fatal error
5639
6083
    }
5640
6084
    else
5641
6085
      found_const_table_map|= s->table->map;
5642
 
    p_pos++;
5643
6086
  }
5644
6087
 
5645
6088
  /* loop until no more const tables are found */
5655
6098
      set_position() will move all const_tables first in stat_vector
5656
6099
    */
5657
6100
 
5658
 
    for (JoinTable **pos= stat_vector+const_count; (s= *pos); pos++)
 
6101
    for (JOIN_TAB **pos=stat_vector+const_count ; (s= *pos) ; pos++)
5659
6102
    {
5660
 
      table= s->table;
 
6103
      table=s->table;
5661
6104
 
5662
6105
      /*
5663
6106
        If equi-join condition by a key is null rejecting and after a
5664
6107
        substitution of a const table the key value happens to be null
5665
6108
        then we can state that there are no matches for this equi-join.
5666
6109
      */
5667
 
      if ((keyuse= s->keyuse) && *s->on_expr_ref && s->embedding_map.none())
 
6110
      if ((keyuse= s->keyuse) && *s->on_expr_ref && !s->embedding_map)
5668
6111
      {
5669
6112
        /*
5670
6113
          When performing an outer join operation if there are no matching rows
5676
6119
          TODO. Apply single row substitution to null complemented inner tables
5677
6120
          for nested outer join operations.
5678
6121
        */
5679
 
        while (keyuse->getTable() == table)
 
6122
        while (keyuse->table == table)
5680
6123
        {
5681
 
          if (! (keyuse->getVal()->used_tables() & ~join->const_table_map) &&
5682
 
              keyuse->getVal()->is_null() && keyuse->isNullRejected())
 
6124
          if (!(keyuse->val->used_tables() & ~join->const_table_map) &&
 
6125
              keyuse->val->is_null() && keyuse->null_rejecting)
5683
6126
          {
5684
 
            s->type= AM_CONST;
 
6127
            s->type= JT_CONST;
5685
6128
            table->mark_as_null_row();
5686
6129
            found_const_table_map|= table->map;
5687
6130
            join->const_table_map|= table->map;
5688
 
            set_position(join, const_count++, s, (optimizer::KeyUse*) 0);
 
6131
            set_position(join,const_count++,s,(KEYUSE*) 0);
5689
6132
            goto more_const_tables_found;
5690
6133
           }
5691
6134
          keyuse++;
5697
6140
        // All dep. must be constants
5698
6141
        if (s->dependent & ~(found_const_table_map))
5699
6142
          continue;
5700
 
        if (table->cursor->stats.records <= 1L &&
5701
 
            (table->cursor->getEngine()->check_flag(HTON_BIT_STATS_RECORDS_IS_EXACT)) &&
5702
 
                  !table->pos_in_table_list->getEmbedding())
 
6143
        if (table->file->stats.records <= 1L &&
 
6144
            (table->file->ha_table_flags() & HA_STATS_RECORDS_IS_EXACT) &&
 
6145
                  !table->pos_in_table_list->embedding)
5703
6146
        {                                       // system table
5704
6147
          int tmp= 0;
5705
 
          s->type= AM_SYSTEM;
 
6148
          s->type=JT_SYSTEM;
5706
6149
          join->const_table_map|=table->map;
5707
 
          set_position(join, const_count++, s, (optimizer::KeyUse*) 0);
5708
 
          partial_pos= join->getSpecificPosInPartialPlan(const_count - 1);
5709
 
          if ((tmp= join_read_const_table(s, partial_pos)))
 
6150
          set_position(join,const_count++,s,(KEYUSE*) 0);
 
6151
          if ((tmp= join_read_const_table(s, join->positions+const_count-1)))
5710
6152
          {
5711
6153
            if (tmp > 0)
5712
 
              return 1;                 // Fatal error
 
6154
              return(1);                        // Fatal error
5713
6155
          }
5714
6156
          else
5715
6157
            found_const_table_map|= table->map;
5719
6161
      /* check if table can be read by key or table only uses const refs */
5720
6162
      if ((keyuse=s->keyuse))
5721
6163
      {
5722
 
        s->type= AM_REF;
5723
 
        while (keyuse->getTable() == table)
 
6164
        s->type= JT_REF;
 
6165
        while (keyuse->table == table)
5724
6166
        {
5725
 
          start_keyuse= keyuse;
5726
 
          key= keyuse->getKey();
 
6167
          start_keyuse=keyuse;
 
6168
          key=keyuse->key;
5727
6169
          s->keys.set(key);               // QQ: remove this ?
5728
6170
 
5729
 
          refs= 0;
5730
 
          const_ref.reset();
 
6171
          refs=0;
 
6172
                const_ref.reset();
5731
6173
          eq_part.reset();
5732
6174
          do
5733
6175
          {
5734
 
            if (keyuse->getVal()->type() != Item::NULL_ITEM && 
5735
 
                ! keyuse->getOptimizeFlags())
 
6176
            if (keyuse->val->type() != Item::NULL_ITEM && !keyuse->optimize)
5736
6177
            {
5737
 
              if (! ((~found_const_table_map) & keyuse->getUsedTables()))
5738
 
                const_ref.set(keyuse->getKeypart());
 
6178
              if (!((~found_const_table_map) & keyuse->used_tables))
 
6179
                const_ref.set(keyuse->keypart);
5739
6180
              else
5740
 
                refs|= keyuse->getUsedTables();
5741
 
              eq_part.set(keyuse->getKeypart());
 
6181
                refs|=keyuse->used_tables;
 
6182
              eq_part.set(keyuse->keypart);
5742
6183
            }
5743
6184
            keyuse++;
5744
 
          } while (keyuse->getTable() == table && keyuse->getKey() == key);
 
6185
          } while (keyuse->table == table && keyuse->key == key);
5745
6186
 
5746
6187
          if (is_keymap_prefix(eq_part, table->key_info[key].key_parts) &&
5747
 
              ! table->pos_in_table_list->getEmbedding())
 
6188
              !table->pos_in_table_list->embedding)
5748
6189
          {
5749
6190
            if ((table->key_info[key].flags & (HA_NOSAME)) == HA_NOSAME)
5750
6191
            {
5752
6193
              {                                 // Found everything for ref.
5753
6194
                int tmp;
5754
6195
                ref_changed = 1;
5755
 
                s->type= AM_CONST;
 
6196
                s->type= JT_CONST;
5756
6197
                join->const_table_map|= table->map;
5757
 
                set_position(join, const_count++, s, start_keyuse);
 
6198
                set_position(join,const_count++,s,start_keyuse);
5758
6199
                if (create_ref_for_key(join, s, start_keyuse, found_const_table_map))
5759
 
                  return 1;
5760
 
                partial_pos= join->getSpecificPosInPartialPlan(const_count - 1);
5761
 
                if ((tmp=join_read_const_table(s, partial_pos)))
 
6200
                  return(1);
 
6201
                if ((tmp=join_read_const_table(s, join->positions+const_count-1)))
5762
6202
                {
5763
6203
                  if (tmp > 0)
5764
 
                    return 1;                   // Fatal error
 
6204
                    return(1);                  // Fatal error
5765
6205
                }
5766
6206
                else
5767
6207
                  found_const_table_map|= table->map;
5782
6222
    Update info on indexes that can be used for search lookups as
5783
6223
    reading const tables may has added new sargable predicates.
5784
6224
  */
5785
 
  if (const_count && ! sargables.empty())
 
6225
  if (const_count && sargables)
5786
6226
  {
5787
 
    vector<optimizer::SargableParam>::iterator iter= sargables.begin();
5788
 
    while (iter != sargables.end())
 
6227
    for( ; sargables->field ; sargables++)
5789
6228
    {
5790
 
      Field *field= (*iter).getField();
5791
 
      JoinTable *join_tab= field->getTable()->reginfo.join_tab;
 
6229
      Field *field= sargables->field;
 
6230
      JOIN_TAB *join_tab= field->table->reginfo.join_tab;
5792
6231
      key_map possible_keys= field->key_start;
5793
 
      possible_keys&= field->getTable()->keys_in_use_for_query;
5794
 
      bool is_const= true;
5795
 
      for (uint32_t j= 0; j < (*iter).getNumValues(); j++)
5796
 
        is_const&= (*iter).isConstItem(j);
 
6232
      possible_keys&= field->table->keys_in_use_for_query;
 
6233
      bool is_const= 1;
 
6234
      for (uint32_t j=0; j < sargables->num_values; j++)
 
6235
        is_const&= sargables->arg_value[j]->const_item();
5797
6236
      if (is_const)
5798
6237
        join_tab[0].const_keys|= possible_keys;
5799
 
      ++iter;
5800
6238
    }
5801
6239
  }
5802
6240
 
 
6241
  if (pull_out_semijoin_tables(join))
 
6242
    return(true);
 
6243
 
5803
6244
  /* Calc how many (possible) matched records in each table */
5804
6245
 
5805
6246
  for (s=stat ; s < stat_end ; s++)
5806
6247
  {
5807
 
    if (s->type == AM_SYSTEM || s->type == AM_CONST)
 
6248
    if (s->type == JT_SYSTEM || s->type == JT_CONST)
5808
6249
    {
5809
6250
      /* Only one matching row */
5810
6251
      s->found_records=s->records=s->read_time=1; s->worst_seeks=1.0;
5811
6252
      continue;
5812
6253
    }
5813
6254
    /* Approximate found rows and time to read them */
5814
 
    s->found_records=s->records=s->table->cursor->stats.records;
5815
 
    s->read_time=(ha_rows) s->table->cursor->scan_time();
 
6255
    s->found_records=s->records=s->table->file->stats.records;
 
6256
    s->read_time=(ha_rows) s->table->file->scan_time();
5816
6257
 
5817
6258
    /*
5818
6259
      Set a max range of how many seeks we can expect when using keys
5819
6260
      This is can't be to high as otherwise we are likely to use
5820
6261
      table scan.
5821
6262
    */
5822
 
    s->worst_seeks= min((double) s->found_records / 10,
5823
 
                        (double) s->read_time*3);
 
6263
    s->worst_seeks= cmin((double) s->found_records / 10,
 
6264
                        (double) s->read_time*3);
5824
6265
    if (s->worst_seeks < 2.0)                   // Fix for small tables
5825
6266
      s->worst_seeks=2.0;
5826
6267
 
5831
6272
    add_group_and_distinct_keys(join, s);
5832
6273
 
5833
6274
    if (s->const_keys.any() &&
5834
 
        !s->table->pos_in_table_list->getEmbedding())
 
6275
        !s->table->pos_in_table_list->embedding)
5835
6276
    {
5836
6277
      ha_rows records;
5837
 
      optimizer::SqlSelect *select= NULL;
5838
 
      select= optimizer::make_select(s->table, found_const_table_map, found_const_table_map, *s->on_expr_ref ? *s->on_expr_ref : conds, 1, &error);
 
6278
      SQL_SELECT *select;
 
6279
      select= make_select(s->table, found_const_table_map, found_const_table_map, *s->on_expr_ref ? *s->on_expr_ref : conds, 1, &error);
5839
6280
      if (! select)
5840
 
        return 1;
 
6281
        return(1);
5841
6282
      records= get_quick_record_count(join->session, select, s->table, &s->const_keys, join->row_limit);
5842
6283
      s->quick=select->quick;
5843
6284
      s->needed_reg=select->needed_reg;
5851
6292
          caller to abort with a zero row result.
5852
6293
        */
5853
6294
        join->const_table_map|= s->table->map;
5854
 
        set_position(join, const_count++, s, (optimizer::KeyUse*) 0);
5855
 
        s->type= AM_CONST;
 
6295
        set_position(join,const_count++,s,(KEYUSE*) 0);
 
6296
        s->type= JT_CONST;
5856
6297
        if (*s->on_expr_ref)
5857
6298
        {
5858
6299
          /* Generate empty row */
5859
6300
          s->info= "Impossible ON condition";
5860
6301
          found_const_table_map|= s->table->map;
5861
 
          s->type= AM_CONST;
 
6302
          s->type= JT_CONST;
5862
6303
          s->table->mark_as_null_row();         // All fields are NULL
5863
6304
        }
5864
6305
      }
5881
6322
  if (join->const_tables != join->tables)
5882
6323
  {
5883
6324
    optimize_keyuse(join, keyuse_array);
5884
 
    // @note c_str() is not likely to be valid here if dtrace expects it to
5885
 
    // exist for any period of time.
5886
 
    DRIZZLE_QUERY_OPT_CHOOSE_PLAN_START(join->session->getQueryString()->c_str(), join->session->thread_id);
5887
 
    bool res= choose_plan(join, all_table_map & ~join->const_table_map);
5888
 
    DRIZZLE_QUERY_OPT_CHOOSE_PLAN_DONE(res ? 1 : 0);
5889
 
    if (res)
5890
 
      return true;
 
6325
    if (choose_plan(join, all_table_map & ~join->const_table_map))
 
6326
      return(true);
5891
6327
  }
5892
6328
  else
5893
6329
  {
5894
 
    join->copyPartialPlanIntoOptimalPlan(join->const_tables);
 
6330
    memcpy(join->best_positions, join->positions, sizeof(POSITION)*join->const_tables);
5895
6331
    join->best_read= 1.0;
5896
6332
  }
5897
6333
  /* Generate an execution plan from the found optimal join order. */
5898
 
  return (join->session->getKilled() || get_best_combination(join));
 
6334
  return (join->session->killed || get_best_combination(join));
5899
6335
}
5900
6336
 
5901
6337
/**
5902
 
  Assign each nested join structure a bit in the nested join bitset.
 
6338
  Assign each nested join structure a bit in nested_join_map.
5903
6339
 
5904
6340
    Assign each nested join structure (except "confluent" ones - those that
5905
 
    embed only one element) a bit in the nested join bitset.
 
6341
    embed only one element) a bit in nested_join_map.
5906
6342
 
5907
6343
  @param join          Join being processed
5908
6344
  @param join_list     List of tables
5909
 
  @param first_unused  Number of first unused bit in the nest joing bitset before the
 
6345
  @param first_unused  Number of first unused bit in nested_join_map before the
5910
6346
                       call
5911
6347
 
5912
6348
  @note
5913
6349
    This function is called after simplify_joins(), when there are no
5914
6350
    redundant nested joins, #non_confluent_nested_joins <= #tables_in_join so
5915
 
    we will not run out of bits in the nested join bitset.
 
6351
    we will not run out of bits in nested_join_map.
5916
6352
 
5917
6353
  @return
5918
 
    First unused bit in the nest join bitset after the call.
 
6354
    First unused bit in nested_join_map after the call.
5919
6355
*/
5920
6356
static uint32_t build_bitmap_for_nested_joins(List<TableList> *join_list, uint32_t first_unused)
5921
6357
{
5924
6360
  while ((table= li++))
5925
6361
  {
5926
6362
    nested_join_st *nested_join;
5927
 
    if ((nested_join= table->getNestedJoin()))
 
6363
    if ((nested_join= table->nested_join))
5928
6364
    {
5929
6365
      /*
5930
6366
        It is guaranteed by simplify_joins() function that a nested join
5935
6371
        We don't assign bits to such sj-nests because
5936
6372
        1. it is redundant (a "sequence" of one table cannot be interleaved
5937
6373
            with anything)
5938
 
        2. we could run out of bits in the nested join bitset otherwise.
 
6374
        2. we could run out bits in nested_join_map otherwise.
5939
6375
      */
5940
6376
      if (nested_join->join_list.elements != 1)
5941
6377
      {
5942
6378
        /* Don't assign bits to sj-nests */
5943
6379
        if (table->on_expr)
5944
 
          nested_join->nj_map.set(first_unused++);
 
6380
          nested_join->nj_map= (nested_join_map) 1 << first_unused++;
5945
6381
        first_unused= build_bitmap_for_nested_joins(&nested_join->join_list,
5946
6382
                                                    first_unused);
5947
6383
      }
5955
6391
  Return table number if there is only one table in sort order
5956
6392
  and group and order is compatible, else return 0.
5957
6393
*/
5958
 
static Table *get_sort_by_table(Order *a, Order *b,TableList *tables)
 
6394
static Table *get_sort_by_table(order_st *a,order_st *b,TableList *tables)
5959
6395
{
5960
6396
  table_map map= (table_map) 0;
5961
6397
 
5995
6431
  while ((table= li++))
5996
6432
  {
5997
6433
    nested_join_st *nested_join;
5998
 
    if ((nested_join= table->getNestedJoin()))
 
6434
    if ((nested_join= table->nested_join))
5999
6435
    {
6000
6436
      nested_join->counter_= 0;
6001
6437
      reset_nj_counters(&nested_join->join_list);
6010
6446
  If first parts has different direction, change it to second part
6011
6447
  (group is sorted like order)
6012
6448
*/
6013
 
static bool test_if_subpart(Order *a, Order *b)
 
6449
static bool test_if_subpart(order_st *a,order_st *b)
6014
6450
{
6015
6451
  for (; a && b; a=a->next,b=b->next)
6016
6452
  {
6025
6461
/**
6026
6462
  Nested joins perspective: Remove the last table from the join order.
6027
6463
 
6028
 
  The algorithm is the reciprocal of check_interleaving_with_nj(), hence
6029
 
  parent join nest nodes are updated only when the last table in its child
6030
 
  node is removed. The ASCII graphic below will clarify.
6031
 
 
6032
 
  %A table nesting such as <tt> t1 x [ ( t2 x t3 ) x ( t4 x t5 ) ] </tt>is
6033
 
  represented by the below join nest tree.
6034
 
 
6035
 
  @verbatim
6036
 
                     NJ1
6037
 
                  _/ /  \
6038
 
                _/  /    NJ2
6039
 
              _/   /     / \ 
6040
 
             /    /     /   \
6041
 
   t1 x [ (t2 x t3) x (t4 x t5) ]
6042
 
  @endverbatim
6043
 
 
6044
 
  At the point in time when check_interleaving_with_nj() adds the table t5 to
6045
 
  the query execution plan, QEP, it also directs the node named NJ2 to mark
6046
 
  the table as covered. NJ2 does so by incrementing its @c counter
6047
 
  member. Since all of NJ2's tables are now covered by the QEP, the algorithm
6048
 
  proceeds up the tree to NJ1, incrementing its counter as well. All join
6049
 
  nests are now completely covered by the QEP.
6050
 
 
6051
 
  restore_prev_nj_state() does the above in reverse. As seen above, the node
6052
 
  NJ1 contains the nodes t2, t3, and NJ2. Its counter being equal to 3 means
6053
 
  that the plan covers t2, t3, and NJ2, @e and that the sub-plan (t4 x t5)
6054
 
  completely covers NJ2. The removal of t5 from the partial plan will first
6055
 
  decrement NJ2's counter to 1. It will then detect that NJ2 went from being
6056
 
  completely to partially covered, and hence the algorithm must continue
6057
 
  upwards to NJ1 and decrement its counter to 2. %A subsequent removal of t4
6058
 
  will however not influence NJ1 since it did not un-cover the last table in
6059
 
  NJ2.
6060
 
 
6061
 
  SYNOPSIS
6062
 
    restore_prev_nj_state()
6063
 
      last  join table to remove, it is assumed to be the last in current 
6064
 
            partial join order.
6065
 
     
6066
 
  DESCRIPTION
6067
 
 
6068
6464
    Remove the last table from the partial join order and update the nested
6069
 
    joins counters and join->cur_embedding_map. It is ok to call this 
6070
 
    function for the first table in join order (for which 
 
6465
    joins counters and join->cur_embedding_map. It is ok to call this
 
6466
    function for the first table in join order (for which
6071
6467
    check_interleaving_with_nj has not been called)
6072
6468
 
6073
6469
  @param last  join table to remove, it is assumed to be the last in current
6074
6470
               partial join order.
6075
6471
*/
6076
 
 
6077
 
static void restore_prev_nj_state(JoinTable *last)
6078
 
{
6079
 
  TableList *last_emb= last->table->pos_in_table_list->getEmbedding();
6080
 
  Join *join= last->join;
6081
 
  for (;last_emb != NULL; last_emb= last_emb->getEmbedding())
6082
 
  {
6083
 
    nested_join_st *nest= last_emb->getNestedJoin();
6084
 
    
6085
 
    bool was_fully_covered= nest->is_fully_covered();
6086
 
    
6087
 
    if (--nest->counter_ == 0)
6088
 
      join->cur_embedding_map&= ~nest->nj_map;
6089
 
    
6090
 
    if (!was_fully_covered)
 
6472
static void restore_prev_nj_state(JOIN_TAB *last)
 
6473
{
 
6474
  TableList *last_emb= last->table->pos_in_table_list->embedding;
 
6475
  JOIN *join= last->join;
 
6476
  while (last_emb)
 
6477
  {
 
6478
    if (last_emb->on_expr)
 
6479
    {
 
6480
      if (!(--last_emb->nested_join->counter_))
 
6481
        join->cur_embedding_map&= ~last_emb->nested_join->nj_map;
 
6482
      else if (last_emb->nested_join->join_list.elements-1 ==
 
6483
               last_emb->nested_join->counter_)
 
6484
        join->cur_embedding_map|= last_emb->nested_join->nj_map;
 
6485
      else
 
6486
        break;
 
6487
    }
 
6488
    last_emb= last_emb->embedding;
 
6489
  }
 
6490
}
 
6491
 
 
6492
/**
 
6493
  Determine if the set is already ordered for order_st BY, so it can
 
6494
  disable join cache because it will change the ordering of the results.
 
6495
  Code handles sort table that is at any location (not only first after
 
6496
  the const tables) despite the fact that it's currently prohibited.
 
6497
  We must disable join cache if the first non-const table alone is
 
6498
  ordered. If there is a temp table the ordering is done as a last
 
6499
  operation and doesn't prevent join cache usage.
 
6500
*/
 
6501
static uint32_t make_join_orderinfo(JOIN *join)
 
6502
{
 
6503
  uint32_t i;
 
6504
  if (join->need_tmp)
 
6505
    return join->tables;
 
6506
 
 
6507
  for (i=join->const_tables ; i < join->tables ; i++)
 
6508
  {
 
6509
    JOIN_TAB *tab= join->join_tab+i;
 
6510
    Table *table= tab->table;
 
6511
    if ((table == join->sort_by_table &&
 
6512
        (!join->order || join->skip_sort_order)) ||
 
6513
        (join->sort_by_table == (Table *) 1 &&  i != join->const_tables))
 
6514
    {
6091
6515
      break;
6092
 
    
6093
 
    join->cur_embedding_map|= nest->nj_map;
6094
 
  }
 
6516
    }
 
6517
  }
 
6518
  return i;
 
6519
}
 
6520
 
 
6521
/**
 
6522
  Setup the strategies to eliminate semi-join duplicates.
 
6523
 
 
6524
  SYNOPSIS
 
6525
    setup_semijoin_dups_elimination()
 
6526
      join           Join to process
 
6527
      options        Join options (needed to see if join buffering will be
 
6528
                     used or not)
 
6529
      no_jbuf_after  Another bit of information re where join buffering will
 
6530
                     be used.
 
6531
 
 
6532
  DESCRIPTION
 
6533
    Setup the strategies to eliminate semi-join duplicates. ATM there are 3
 
6534
    strategies:
 
6535
 
 
6536
    1. DuplicateWeedout (use of temptable to remove duplicates based on rowids
 
6537
                         of row combinations)
 
6538
    2. FirstMatch (pick only the 1st matching row combination of inner tables)
 
6539
    3. InsideOut (scanning the sj-inner table in a way that groups duplicates
 
6540
                  together and picking the 1st one)
 
6541
 
 
6542
    The join order has "duplicate-generating ranges", and every range is
 
6543
    served by one strategy or a combination of FirstMatch with with some
 
6544
    other strategy.
 
6545
 
 
6546
    "Duplicate-generating range" is defined as a range within the join order
 
6547
    that contains all of the inner tables of a semi-join. All ranges must be
 
6548
    disjoint, if tables of several semi-joins are interleaved, then the ranges
 
6549
    are joined together, which is equivalent to converting
 
6550
      SELECT ... WHERE oe1 IN (SELECT ie1 ...) AND oe2 IN (SELECT ie2 )
 
6551
    to
 
6552
      SELECT ... WHERE (oe1, oe2) IN (SELECT ie1, ie2 ... ...)
 
6553
    .
 
6554
 
 
6555
    Applicability conditions are as follows:
 
6556
 
 
6557
    DuplicateWeedout strategy
 
6558
    ~~~~~~~~~~~~~~~~~~~~~~~~~
 
6559
 
 
6560
      (ot|nt)*  [ it ((it|ot|nt)* (it|ot))]  (nt)*
 
6561
      +------+  +=========================+  +---+
 
6562
        (1)                 (2)               (3)
 
6563
 
 
6564
       (1) - Prefix of OuterTables (those that participate in
 
6565
             IN-equality and/or are correlated with subquery) and outer
 
6566
             Noncorrelated Tables.
 
6567
       (2) - The handled range. The range starts with the first sj-inner
 
6568
             table, and covers all sj-inner and outer tables
 
6569
             Within the range,  Inner, Outer, outer Noncorrelated tables
 
6570
             may follow in any order.
 
6571
       (3) - The suffix of outer Noncorrelated tables.
 
6572
 
 
6573
    FirstMatch strategy
 
6574
    ~~~~~~~~~~~~~~~~~~~
 
6575
 
 
6576
      (ot|nt)*  [ it ((it|nt)* it) ]  (nt)*
 
6577
      +------+  +==================+  +---+
 
6578
        (1)             (2)          (3)
 
6579
 
 
6580
      (1) - Prefix of outer and non-correlated tables
 
6581
      (2) - The handled range, which may contain only inner and
 
6582
            non-correlated tables.
 
6583
      (3) - The suffix of outer Noncorrelated tables.
 
6584
 
 
6585
    InsideOut strategy
 
6586
    ~~~~~~~~~~~~~~~~~~
 
6587
 
 
6588
     (ot|ct|nt) [ insideout_tbl (ot|nt|it)* it ]  (ot|nt)*
 
6589
     +--------+   +===========+ +=============+   +------+
 
6590
        (1)           (2)          (3)              (4)
 
6591
 
 
6592
      (1) - Prefix that may contain any outer tables. The prefix must contain
 
6593
            all the non-trivially correlated outer tables. (non-trivially means
 
6594
            that the correlation is not just through the IN-equality).
 
6595
 
 
6596
      (2) - Inner table for which the InsideOut scan is performed.
 
6597
 
 
6598
      (3) - The remainder of the duplicate-generating range. It is served by
 
6599
            application of FirstMatch strategy, with the exception that
 
6600
            outer IN-correlated tables are considered to be non-correlated.
 
6601
 
 
6602
      (4) - THe suffix of outer and outer non-correlated tables.
 
6603
 
 
6604
    If several strategies are applicable, their relative priorities are:
 
6605
      1. InsideOut
 
6606
      2. FirstMatch
 
6607
      3. DuplicateWeedout
 
6608
 
 
6609
    This function walks over the join order and sets up the strategies by
 
6610
    setting appropriate members in join_tab structures.
 
6611
 
 
6612
  RETURN
 
6613
    false  OK
 
6614
    true   Out of memory error
 
6615
*/
 
6616
static int setup_semijoin_dups_elimination(JOIN *join, uint64_t options, uint32_t no_jbuf_after)
 
6617
{
 
6618
  table_map cur_map= join->const_table_map | PSEUDO_TABLE_BITS;
 
6619
  struct {
 
6620
    /*
 
6621
      0 - invalid (EOF marker),
 
6622
      1 - InsideOut,
 
6623
      2 - Temptable (maybe confluent),
 
6624
      3 - Temptable with join buffering
 
6625
    */
 
6626
    uint32_t strategy;
 
6627
    uint32_t start_idx; /* Left range bound */
 
6628
    uint32_t end_idx;   /* Right range bound */
 
6629
    /*
 
6630
      For Temptable strategy: Bitmap of all outer and correlated tables from
 
6631
      all involved join nests.
 
6632
    */
 
6633
    table_map outer_tables;
 
6634
  } dups_ranges [MAX_TABLES];
 
6635
 
 
6636
  TableList *emb_insideout_nest= NULL;
 
6637
  table_map emb_sj_map= 0;  /* A bitmap of sj-nests (that is, their sj-inner
 
6638
                               tables) whose ranges we're in */
 
6639
  table_map emb_outer_tables= 0; /* sj-outer tables for those sj-nests */
 
6640
  table_map range_start_map= 0; /* table_map at current range start */
 
6641
  bool dealing_with_jbuf= false; /* true <=> table within cur range uses join buf */
 
6642
  int cur_range= 0;
 
6643
  uint32_t i;
 
6644
 
 
6645
  /*
 
6646
    First pass: locate the duplicate-generating ranges and pick the strategies.
 
6647
  */
 
6648
  for (i=join->const_tables ; i < join->tables ; i++)
 
6649
  {
 
6650
    JOIN_TAB *tab=join->join_tab+i;
 
6651
    Table *table=tab->table;
 
6652
    cur_map |= table->map;
 
6653
 
 
6654
    if (tab->emb_sj_nest) // Encountered an sj-inner table
 
6655
    {
 
6656
      if (!emb_sj_map)
 
6657
      {
 
6658
        dups_ranges[cur_range].start_idx= i;
 
6659
        range_start_map= cur_map & ~table->map;
 
6660
        /*
 
6661
          Remember if this is a possible start of range that is covered by
 
6662
          the InsideOut strategy (the reason that it is not covered could
 
6663
          be that it overlaps with anther semi-join's range. we don't
 
6664
          support InsideOut for joined ranges)
 
6665
        */
 
6666
        if (join->best_positions[i].use_insideout_scan)
 
6667
          emb_insideout_nest= tab->emb_sj_nest;
 
6668
      }
 
6669
 
 
6670
      emb_sj_map |= tab->emb_sj_nest->sj_inner_tables;
 
6671
      emb_outer_tables |= tab->emb_sj_nest->nested_join->sj_depends_on;
 
6672
 
 
6673
      if (tab->emb_sj_nest != emb_insideout_nest)
 
6674
      {
 
6675
        /*
 
6676
          Two different semi-joins interleave. This cannot be handled by
 
6677
          InsideOut strategy.
 
6678
        */
 
6679
        emb_insideout_nest= NULL;
 
6680
      }
 
6681
    }
 
6682
 
 
6683
    if (emb_sj_map) /* We're in duplicate-generating range */
 
6684
    {
 
6685
      if (i != join->const_tables && !(options & SELECT_NO_JOIN_CACHE) &&
 
6686
          tab->type == JT_ALL && tab->use_quick != 2 && !tab->first_inner &&
 
6687
          i <= no_jbuf_after && !dealing_with_jbuf)
 
6688
      {
 
6689
        /*
 
6690
          This table uses join buffering, which makes use of FirstMatch or
 
6691
          InsideOut strategies impossible for the current and (we assume)
 
6692
          preceding duplicate-producing ranges.
 
6693
          That is, for the join order:
 
6694
 
 
6695
              x x [ x  x]  x  [x x x]  x  [x x X*  x] x
 
6696
                  |     |     |     |          | \
 
6697
                  +-----+     +-----+          |  join buffering use
 
6698
                     r1          r2         we're here
 
6699
 
 
6700
          we'll have to remove r1 and r2 and use duplicate-elimination
 
6701
          strategy that spans all the tables, starting from the very 1st
 
6702
          one.
 
6703
        */
 
6704
        dealing_with_jbuf= true;
 
6705
        emb_insideout_nest= false;
 
6706
 
 
6707
        /*
 
6708
          Absorb all preceding duplicate-eliminating ranges. Their strategies
 
6709
          do not matter:
 
6710
        */
 
6711
        for (int prev_range= 0; prev_range < cur_range; prev_range++)
 
6712
        {
 
6713
          dups_ranges[cur_range].outer_tables |=
 
6714
            dups_ranges[prev_range].outer_tables;
 
6715
        }
 
6716
        dups_ranges[0].start_idx= 0; /* Will need to start from the 1st table */
 
6717
        dups_ranges[0].outer_tables= dups_ranges[cur_range].outer_tables;
 
6718
        cur_range=  0;
 
6719
      }
 
6720
 
 
6721
      /*
 
6722
        Check if we are at the end of duplicate-producing range. We are if
 
6723
 
 
6724
        1. It's an InsideOut range (which presumes all correlated tables are
 
6725
           in the prefix), and all inner tables are in the join order prefix,
 
6726
           or
 
6727
        2. It's a DuplicateElimination range (possibly covering several
 
6728
           SJ-nests), and all inner, outer, and correlated tables of all
 
6729
           sj-nests are in the join order prefix.
 
6730
      */
 
6731
      bool end_of_range= false;
 
6732
      if (emb_insideout_nest &&
 
6733
          bitmap_covers(cur_map, emb_insideout_nest->sj_inner_tables))
 
6734
      {
 
6735
        /* Save that this range is handled with InsideOut: */
 
6736
        dups_ranges[cur_range].strategy= 1;
 
6737
        end_of_range= true;
 
6738
      }
 
6739
      else if (bitmap_covers(cur_map, emb_outer_tables | emb_sj_map))
 
6740
      {
 
6741
        /*
 
6742
          This is a complete range to be handled with either DuplicateWeedout
 
6743
          or FirstMatch
 
6744
        */
 
6745
        dups_ranges[cur_range].strategy= dealing_with_jbuf? 3 : 2;
 
6746
        /*
 
6747
          This will hold tables from within the range that need to be put
 
6748
          into the join buffer before we can use the FirstMatch on its tail.
 
6749
        */
 
6750
        dups_ranges[cur_range].outer_tables= emb_outer_tables &
 
6751
                                             ~range_start_map;
 
6752
        end_of_range= true;
 
6753
      }
 
6754
 
 
6755
      if (end_of_range)
 
6756
      {
 
6757
        dups_ranges[cur_range].end_idx= i+1;
 
6758
        emb_sj_map= emb_outer_tables= 0;
 
6759
        emb_insideout_nest= NULL;
 
6760
        dealing_with_jbuf= false;
 
6761
        dups_ranges[++cur_range].strategy= 0;
 
6762
      }
 
6763
    }
 
6764
  }
 
6765
 
 
6766
  Session *session= join->session;
 
6767
  SJ_TMP_TABLE **next_sjtbl_ptr= &join->sj_tmp_tables;
 
6768
  /*
 
6769
    Second pass: setup the chosen strategies
 
6770
  */
 
6771
  for (int j= 0; j < cur_range; j++)
 
6772
  {
 
6773
    JOIN_TAB *tab=join->join_tab + dups_ranges[j].start_idx;
 
6774
    JOIN_TAB *jump_to;
 
6775
    if (dups_ranges[j].strategy == 1)  // InsideOut strategy
 
6776
    {
 
6777
      tab->insideout_match_tab= join->join_tab + dups_ranges[j].end_idx - 1;
 
6778
      jump_to= tab++;
 
6779
    }
 
6780
    else // DuplicateWeedout strategy
 
6781
    {
 
6782
      SJ_TMP_TABLE::TAB sjtabs[MAX_TABLES];
 
6783
      table_map weed_cur_map= join->const_table_map | PSEUDO_TABLE_BITS;
 
6784
      uint32_t jt_rowid_offset= 0; // # tuple bytes are already occupied (w/o NULL bytes)
 
6785
      uint32_t jt_null_bits= 0;    // # null bits in tuple bytes
 
6786
      SJ_TMP_TABLE::TAB *last_tab= sjtabs;
 
6787
      uint32_t rowid_keep_flags= JOIN_TAB::CALL_POSITION | JOIN_TAB::KEEP_ROWID;
 
6788
      JOIN_TAB *last_outer_tab= tab - 1;
 
6789
      /*
 
6790
        Walk through the range and remember
 
6791
         - tables that need their rowids to be put into temptable
 
6792
         - the last outer table
 
6793
      */
 
6794
      for (; tab < join->join_tab + dups_ranges[j].end_idx; tab++)
 
6795
      {
 
6796
        if (sj_table_is_included(join, tab))
 
6797
        {
 
6798
          last_tab->join_tab= tab;
 
6799
          last_tab->rowid_offset= jt_rowid_offset;
 
6800
          jt_rowid_offset += tab->table->file->ref_length;
 
6801
          if (tab->table->maybe_null)
 
6802
          {
 
6803
            last_tab->null_byte= jt_null_bits / 8;
 
6804
            last_tab->null_bit= jt_null_bits++;
 
6805
          }
 
6806
          last_tab++;
 
6807
          tab->table->prepare_for_position();
 
6808
          tab->rowid_keep_flags= rowid_keep_flags;
 
6809
        }
 
6810
        weed_cur_map |= tab->table->map;
 
6811
        if (!tab->emb_sj_nest && bitmap_covers(weed_cur_map,
 
6812
                                               dups_ranges[j].outer_tables))
 
6813
          last_outer_tab= tab;
 
6814
      }
 
6815
 
 
6816
      if (jt_rowid_offset) /* Temptable has at least one rowid */
 
6817
      {
 
6818
        SJ_TMP_TABLE *sjtbl;
 
6819
        uint32_t tabs_size= (last_tab - sjtabs) * sizeof(SJ_TMP_TABLE::TAB);
 
6820
        if (!(sjtbl= (SJ_TMP_TABLE*)session->alloc(sizeof(SJ_TMP_TABLE))) ||
 
6821
            !(sjtbl->tabs= (SJ_TMP_TABLE::TAB*) session->alloc(tabs_size)))
 
6822
          return(true);
 
6823
        memcpy(sjtbl->tabs, sjtabs, tabs_size);
 
6824
        sjtbl->tabs_end= sjtbl->tabs + (last_tab - sjtabs);
 
6825
        sjtbl->rowid_len= jt_rowid_offset;
 
6826
        sjtbl->null_bits= jt_null_bits;
 
6827
        sjtbl->null_bytes= (jt_null_bits + 7)/8;
 
6828
 
 
6829
        *next_sjtbl_ptr= sjtbl;
 
6830
        next_sjtbl_ptr= &(sjtbl->next);
 
6831
        sjtbl->next= NULL;
 
6832
 
 
6833
        sjtbl->tmp_table=
 
6834
          create_duplicate_weedout_tmp_table(session,
 
6835
                                             sjtbl->rowid_len +
 
6836
                                             sjtbl->null_bytes,
 
6837
                                             sjtbl);
 
6838
 
 
6839
        join->join_tab[dups_ranges[j].start_idx].flush_weedout_table= sjtbl;
 
6840
        join->join_tab[dups_ranges[j].end_idx - 1].check_weed_out_table= sjtbl;
 
6841
      }
 
6842
      tab= last_outer_tab + 1;
 
6843
      jump_to= last_outer_tab;
 
6844
    }
 
6845
 
 
6846
    /* Create the FirstMatch tail */
 
6847
    for (; tab < join->join_tab + dups_ranges[j].end_idx; tab++)
 
6848
    {
 
6849
      if (tab->emb_sj_nest)
 
6850
        tab->do_firstmatch= jump_to;
 
6851
      else
 
6852
        jump_to= tab;
 
6853
    }
 
6854
  }
 
6855
  return(false);
 
6856
}
 
6857
 
 
6858
static void cleanup_sj_tmp_tables(JOIN *join)
 
6859
{
 
6860
  for (SJ_TMP_TABLE *sj_tbl= join->sj_tmp_tables; sj_tbl;
 
6861
       sj_tbl= sj_tbl->next)
 
6862
  {
 
6863
    if (sj_tbl->tmp_table)
 
6864
    {
 
6865
      sj_tbl->tmp_table->free_tmp_table(join->session);
 
6866
    }
 
6867
  }
 
6868
  join->sj_tmp_tables= NULL;
6095
6869
}
6096
6870
 
6097
6871
/**
6098
6872
  Create a condition for a const reference and add this to the
6099
6873
  currenct select for the table.
6100
6874
*/
6101
 
static bool add_ref_to_table_cond(Session *session, JoinTable *join_tab)
 
6875
static bool add_ref_to_table_cond(Session *session, JOIN_TAB *join_tab)
6102
6876
{
6103
6877
  if (!join_tab->ref.key_parts)
6104
6878
    return(false);
6111
6885
 
6112
6886
  for (uint32_t i=0 ; i < join_tab->ref.key_parts ; i++)
6113
6887
  {
6114
 
    Field *field=table->getField(table->key_info[join_tab->ref.key].key_part[i].fieldnr - 1);
 
6888
    Field *field=table->field[table->key_info[join_tab->ref.key].key_part[i].
 
6889
                              fieldnr-1];
6115
6890
    Item *value=join_tab->ref.items[i];
6116
6891
    cond->add(new Item_func_equal(new Item_field(field), value));
6117
6892
  }
6125
6900
    error=(int) cond->add(join_tab->select->cond);
6126
6901
    join_tab->select_cond=join_tab->select->cond=cond;
6127
6902
  }
6128
 
  else if ((join_tab->select= optimizer::make_select(join_tab->table, 0, 0, cond, 0,
6129
 
                                                     &error)))
 
6903
  else if ((join_tab->select= make_select(join_tab->table, 0, 0, cond, 0,
 
6904
                                          &error)))
6130
6905
    join_tab->select_cond=cond;
6131
6906
 
6132
6907
  return(error ? true : false);
6133
6908
}
6134
6909
 
 
6910
/**
 
6911
   @brief Replaces an expression destructively inside the expression tree of
 
6912
   the WHERE clase.
 
6913
 
 
6914
   @note Because of current requirements for semijoin flattening, we do not
 
6915
   need to recurse here, hence this function will only examine the top-level
 
6916
   AND conditions. (see JOIN::prepare, comment above the line
 
6917
   'if (do_materialize)'
 
6918
 
 
6919
   @param join The top-level query.
 
6920
   @param old_cond The expression to be replaced.
 
6921
   @param new_cond The expression to be substituted.
 
6922
   @param do_fix_fields If true, Item::fix_fields(Session*, Item**) is called for
 
6923
   the new expression.
 
6924
   @return <code>true</code> if there was an error, <code>false</code> if
 
6925
   successful.
 
6926
*/
 
6927
static bool replace_where_subcondition(JOIN *join, Item *old_cond,
 
6928
                                       Item *new_cond, bool do_fix_fields)
 
6929
{
 
6930
  if (join->conds == old_cond) {
 
6931
    join->conds= new_cond;
 
6932
    if (do_fix_fields)
 
6933
      new_cond->fix_fields(join->session, &join->conds);
 
6934
    return false;
 
6935
  }
 
6936
 
 
6937
  if (join->conds->type() == Item::COND_ITEM) {
 
6938
    List_iterator<Item> li(*((Item_cond*)join->conds)->argument_list());
 
6939
    Item *item;
 
6940
    while ((item= li++))
 
6941
      if (item == old_cond)
 
6942
      {
 
6943
        li.replace(new_cond);
 
6944
        if (do_fix_fields)
 
6945
          new_cond->fix_fields(join->session, li.ref());
 
6946
        return false;
 
6947
      }
 
6948
  }
 
6949
 
 
6950
  return true;
 
6951
}
 
6952
 
 
6953
/*
 
6954
  Pull tables out of semi-join nests, if possible
 
6955
 
 
6956
  SYNOPSIS
 
6957
    pull_out_semijoin_tables()
 
6958
      join  The join where to do the semi-join flattening
 
6959
 
 
6960
  DESCRIPTION
 
6961
    Try to pull tables out of semi-join nests.
 
6962
 
 
6963
    PRECONDITIONS
 
6964
    When this function is called, the join may have several semi-join nests
 
6965
    (possibly within different semi-join nests), but it is guaranteed that
 
6966
    one semi-join nest does not contain another.
 
6967
 
 
6968
    ACTION
 
6969
    A table can be pulled out of the semi-join nest if
 
6970
     - It is a constant table
 
6971
     - It is accessed
 
6972
 
 
6973
    POSTCONDITIONS
 
6974
     * Pulled out tables have JOIN_TAB::emb_sj_nest == NULL (like the outer
 
6975
       tables)
 
6976
     * Tables that were not pulled out have JOIN_TAB::emb_sj_nest.
 
6977
     * Semi-join nests TableList::sj_inner_tables
 
6978
 
 
6979
    This operation is (and should be) performed at each PS execution since
 
6980
    tables may become/cease to be constant across PS reexecutions.
 
6981
 
 
6982
  RETURN
 
6983
    0 - OK
 
6984
    1 - Out of memory error
 
6985
*/
 
6986
static int pull_out_semijoin_tables(JOIN *join)
 
6987
{
 
6988
  TableList *sj_nest;
 
6989
  List_iterator<TableList> sj_list_it(join->select_lex->sj_nests);
 
6990
 
 
6991
  /* Try pulling out of the each of the semi-joins */
 
6992
  while ((sj_nest= sj_list_it++))
 
6993
  {
 
6994
    /* Action #1: Mark the constant tables to be pulled out */
 
6995
    table_map pulled_tables= 0;
 
6996
 
 
6997
    List_iterator<TableList> child_li(sj_nest->nested_join->join_list);
 
6998
    TableList *tbl;
 
6999
    while ((tbl= child_li++))
 
7000
    {
 
7001
      if (tbl->table)
 
7002
      {
 
7003
        tbl->table->reginfo.join_tab->emb_sj_nest= sj_nest;
 
7004
        if (tbl->table->map & join->const_table_map)
 
7005
        {
 
7006
          pulled_tables |= tbl->table->map;
 
7007
        }
 
7008
      }
 
7009
    }
 
7010
 
 
7011
    /*
 
7012
      Action #2: Find which tables we can pull out based on
 
7013
      update_ref_and_keys() data. Note that pulling one table out can allow
 
7014
      us to pull out some other tables too.
 
7015
    */
 
7016
    bool pulled_a_table;
 
7017
    do
 
7018
    {
 
7019
      pulled_a_table= false;
 
7020
      child_li.rewind();
 
7021
      while ((tbl= child_li++))
 
7022
      {
 
7023
        if (tbl->table && !(pulled_tables & tbl->table->map))
 
7024
        {
 
7025
          if (find_eq_ref_candidate(tbl->table,
 
7026
                                    sj_nest->nested_join->used_tables &
 
7027
                                    ~pulled_tables))
 
7028
          {
 
7029
            pulled_a_table= true;
 
7030
            pulled_tables |= tbl->table->map;
 
7031
          }
 
7032
        }
 
7033
      }
 
7034
    } while (pulled_a_table);
 
7035
 
 
7036
    child_li.rewind();
 
7037
    if ((sj_nest)->nested_join->used_tables == pulled_tables)
 
7038
    {
 
7039
      (sj_nest)->sj_inner_tables= 0;
 
7040
      while ((tbl= child_li++))
 
7041
      {
 
7042
        if (tbl->table)
 
7043
          tbl->table->reginfo.join_tab->emb_sj_nest= NULL;
 
7044
      }
 
7045
    }
 
7046
    else
 
7047
    {
 
7048
      /* Record the bitmap of inner tables, mark the inner tables */
 
7049
      table_map inner_tables=(sj_nest)->nested_join->used_tables &
 
7050
                             ~pulled_tables;
 
7051
      (sj_nest)->sj_inner_tables= inner_tables;
 
7052
      while ((tbl= child_li++))
 
7053
      {
 
7054
        if (tbl->table)
 
7055
        {
 
7056
          if (inner_tables & tbl->table->map)
 
7057
            tbl->table->reginfo.join_tab->emb_sj_nest= (sj_nest);
 
7058
          else
 
7059
            tbl->table->reginfo.join_tab->emb_sj_nest= NULL;
 
7060
        }
 
7061
      }
 
7062
    }
 
7063
  }
 
7064
  return(0);
 
7065
}
 
7066
 
 
7067
/*
 
7068
  SemiJoinDuplicateElimination: Weed out duplicate row combinations
 
7069
 
 
7070
  SYNPOSIS
 
7071
    do_sj_dups_weedout()
 
7072
 
 
7073
  RETURN
 
7074
    -1  Error
 
7075
    1   The row combination is a duplicate (discard it)
 
7076
    0   The row combination is not a duplicate (continue)
 
7077
*/
 
7078
static int do_sj_dups_weedout(Session *session, SJ_TMP_TABLE *sjtbl)
 
7079
{
 
7080
  int error;
 
7081
  SJ_TMP_TABLE::TAB *tab= sjtbl->tabs;
 
7082
  SJ_TMP_TABLE::TAB *tab_end= sjtbl->tabs_end;
 
7083
  unsigned char *ptr= sjtbl->tmp_table->record[0] + 1;
 
7084
  unsigned char *nulls_ptr= ptr;
 
7085
 
 
7086
  /* Put the the rowids tuple into table->record[0]: */
 
7087
 
 
7088
  // 1. Store the length
 
7089
  if (((Field_varstring*)(sjtbl->tmp_table->field[0]))->length_bytes == 1)
 
7090
  {
 
7091
    *ptr= (unsigned char)(sjtbl->rowid_len + sjtbl->null_bytes);
 
7092
    ptr++;
 
7093
  }
 
7094
  else
 
7095
  {
 
7096
    int2store(ptr, sjtbl->rowid_len + sjtbl->null_bytes);
 
7097
    ptr += 2;
 
7098
  }
 
7099
 
 
7100
  // 2. Zero the null bytes
 
7101
  if (sjtbl->null_bytes)
 
7102
  {
 
7103
    memset(ptr, 0, sjtbl->null_bytes);
 
7104
    ptr += sjtbl->null_bytes;
 
7105
  }
 
7106
 
 
7107
  // 3. Put the rowids
 
7108
  for (uint32_t i=0; tab != tab_end; tab++, i++)
 
7109
  {
 
7110
    handler *h= tab->join_tab->table->file;
 
7111
    if (tab->join_tab->table->maybe_null && tab->join_tab->table->null_row)
 
7112
    {
 
7113
      /* It's a NULL-complemented row */
 
7114
      *(nulls_ptr + tab->null_byte) |= tab->null_bit;
 
7115
      memset(ptr + tab->rowid_offset, 0, h->ref_length);
 
7116
    }
 
7117
    else
 
7118
    {
 
7119
      /* Copy the rowid value */
 
7120
      if (tab->join_tab->rowid_keep_flags & JOIN_TAB::CALL_POSITION)
 
7121
        h->position(tab->join_tab->table->record[0]);
 
7122
      memcpy(ptr + tab->rowid_offset, h->ref, h->ref_length);
 
7123
    }
 
7124
  }
 
7125
 
 
7126
  error= sjtbl->tmp_table->file->ha_write_row(sjtbl->tmp_table->record[0]);
 
7127
  if (error)
 
7128
  {
 
7129
    /* create_myisam_from_heap will generate error if needed */
 
7130
    if (sjtbl->tmp_table->file->is_fatal_error(error, HA_CHECK_DUP) &&
 
7131
        create_myisam_from_heap(session, sjtbl->tmp_table, sjtbl->start_recinfo,
 
7132
                                &sjtbl->recinfo, error, 1))
 
7133
      return -1;
 
7134
    //return (error == HA_ERR_FOUND_DUPP_KEY || error== HA_ERR_FOUND_DUPP_UNIQUE) ? 1: -1;
 
7135
    return 1;
 
7136
  }
 
7137
  return 0;
 
7138
}
 
7139
 
6135
7140
static void free_blobs(Field **ptr)
6136
7141
{
6137
7142
  for (; *ptr ; ptr++)
6141
7146
  }
6142
7147
}
6143
7148
 
 
7149
static bool bitmap_covers(const table_map x, const table_map y)
 
7150
{
 
7151
  return !test(y & ~x);
 
7152
}
 
7153
 
 
7154
/*
 
7155
  Check if the table's rowid is included in the temptable
 
7156
 
 
7157
  SYNOPSIS
 
7158
    sj_table_is_included()
 
7159
      join      The join
 
7160
      join_tab  The table to be checked
 
7161
 
 
7162
  DESCRIPTION
 
7163
    SemiJoinDuplicateElimination: check the table's rowid should be included
 
7164
    in the temptable. This is so if
 
7165
 
 
7166
    1. The table is not embedded within some semi-join nest
 
7167
    2. The has been pulled out of a semi-join nest, or
 
7168
 
 
7169
    3. The table is functionally dependent on some previous table
 
7170
 
 
7171
    [4. This is also true for constant tables that can't be
 
7172
        NULL-complemented but this function is not called for such tables]
 
7173
 
 
7174
  RETURN
 
7175
    true  - Include table's rowid
 
7176
    false - Don't
 
7177
*/
 
7178
static bool sj_table_is_included(JOIN *join, JOIN_TAB *join_tab)
 
7179
{
 
7180
  if (join_tab->emb_sj_nest)
 
7181
    return false;
 
7182
 
 
7183
  /* Check if this table is functionally dependent on the tables that
 
7184
     are within the same outer join nest
 
7185
  */
 
7186
  TableList *embedding= join_tab->table->pos_in_table_list->embedding;
 
7187
  if (join_tab->type == JT_EQ_REF)
 
7188
  {
 
7189
    Table_map_iterator it(join_tab->ref.depend_map & ~PSEUDO_TABLE_BITS);
 
7190
    uint32_t idx;
 
7191
    while ((idx= it.next_bit())!=Table_map_iterator::BITMAP_END)
 
7192
    {
 
7193
      JOIN_TAB *ref_tab= join->join_tab + idx;
 
7194
      if (embedding == ref_tab->table->pos_in_table_list->embedding)
 
7195
        return true;
 
7196
    }
 
7197
    /* Ok, functionally dependent */
 
7198
    return false;
 
7199
  }
 
7200
  /* Not functionally dependent => need to include*/
 
7201
  return true;
 
7202
}
 
7203
 
6144
7204
/**
6145
7205
  @} (end of group Query_Optimizer)
6146
7206
*/
6147
 
 
6148
 
} /* namespace drizzled */