~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/join.cc

  • Committer: Brian Aker
  • Date: 2009-06-03 19:30:45 UTC
  • mfrom: (1046.1.6 merge)
  • Revision ID: brian@gaz-20090603193045-4xgeczyfixh07beg
MergeĀ forĀ Brian

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