~ubuntu-branches/ubuntu/natty/mysql-5.1/natty-proposed

« back to all changes in this revision

Viewing changes to sql/sql_select.cc

  • Committer: Package Import Robot
  • Author(s): Marc Deslauriers
  • Date: 2012-02-22 08:30:45 UTC
  • mfrom: (1.4.1)
  • Revision ID: package-import@ubuntu.com-20120222083045-2rd53r4bnyx7qus4
Tags: 5.1.61-0ubuntu0.11.04.1
* SECURITY UPDATE: Update to 5.1.61 to fix multiple security issues
  (LP: #937869)
  - http://www.oracle.com/technetwork/topics/security/cpujan2012-366304.html
  - CVE-2011-2262
  - CVE-2012-0075
  - CVE-2012-0112
  - CVE-2012-0113
  - CVE-2012-0114
  - CVE-2012-0115
  - CVE-2012-0116
  - CVE-2012-0117
  - CVE-2012-0118
  - CVE-2012-0119
  - CVE-2012-0120
  - CVE-2012-0484
  - CVE-2012-0485
  - CVE-2012-0486
  - CVE-2012-0487
  - CVE-2012-0488
  - CVE-2012-0489
  - CVE-2012-0490
  - CVE-2012-0491
  - CVE-2012-0492
  - CVE-2012-0493
  - CVE-2012-0494
  - CVE-2012-0495
  - CVE-2012-0496

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/* Copyright (c) 2000, 2010 Oracle and/or its affiliates. All rights reserved.
 
1
/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
2
2
 
3
3
   This program is free software; you can redistribute it and/or modify
4
4
   it under the terms of the GNU General Public License as published by
278
278
}
279
279
 
280
280
 
281
 
/*
 
281
/**
282
282
  Fix fields referenced from inner selects.
283
283
 
284
 
  SYNOPSIS
285
 
    fix_inner_refs()
286
 
    thd               Thread handle
287
 
    all_fields        List of all fields used in select
288
 
    select            Current select
289
 
    ref_pointer_array Array of references to Items used in current select
290
 
    group_list        GROUP BY list (is NULL by default)
291
 
 
292
 
  DESCRIPTION
293
 
    The function serves 3 purposes - adds fields referenced from inner
294
 
    selects to the current select list, resolves which class to use
295
 
    to access referenced item (Item_ref of Item_direct_ref) and fixes
296
 
    references (Item_ref objects) to these fields.
297
 
 
298
 
    If a field isn't already in the select list and the ref_pointer_array
 
284
  @param thd               Thread handle
 
285
  @param all_fields        List of all fields used in select
 
286
  @param select            Current select
 
287
  @param ref_pointer_array Array of references to Items used in current select
 
288
  @param group_list        GROUP BY list (is NULL by default)
 
289
 
 
290
  @details
 
291
    The function serves 3 purposes
 
292
 
 
293
    - adds fields referenced from inner query blocks to the current select list
 
294
 
 
295
    - Decides which class to use to reference the items (Item_ref or
 
296
      Item_direct_ref)
 
297
 
 
298
    - fixes references (Item_ref objects) to these fields.
 
299
 
 
300
    If a field isn't already on the select list and the ref_pointer_array
299
301
    is provided then it is added to the all_fields list and the pointer to
300
302
    it is saved in the ref_pointer_array.
301
303
 
302
304
    The class to access the outer field is determined by the following rules:
303
 
    1. If the outer field isn't used under an aggregate function
304
 
      then the Item_ref class should be used.
305
 
    2. If the outer field is used under an aggregate function and this
306
 
      function is aggregated in the select where the outer field was
307
 
      resolved or in some more inner select then the Item_direct_ref
308
 
      class should be used.
309
 
      Also it should be used if we are grouping by a subquery containing
310
 
      the outer field.
 
305
 
 
306
    -#. If the outer field isn't used under an aggregate function then the
 
307
        Item_ref class should be used.
 
308
 
 
309
    -#. If the outer field is used under an aggregate function and this
 
310
        function is, in turn, aggregated in the query block where the outer
 
311
        field was resolved or some query nested therein, then the
 
312
        Item_direct_ref class should be used. Also it should be used if we are
 
313
        grouping by a subquery containing the outer field.
 
314
 
311
315
    The resolution is done here and not at the fix_fields() stage as
312
 
    it can be done only after sum functions are fixed and pulled up to
313
 
    selects where they are have to be aggregated.
 
316
    it can be done only after aggregate functions are fixed and pulled up to
 
317
    selects where they are to be aggregated.
 
318
 
314
319
    When the class is chosen it substitutes the original field in the
315
320
    Item_outer_ref object.
316
321
 
317
322
    After this we proceed with fixing references (Item_outer_ref objects) to
318
323
    this field from inner subqueries.
319
324
 
320
 
  RETURN
321
 
    TRUE  an error occured
322
 
    FALSE ok
323
 
*/
 
325
  @return Status
 
326
  @retval true An error occured.
 
327
  @retval false OK.
 
328
 */
324
329
 
325
330
bool
326
331
fix_inner_refs(THD *thd, List<Item> &all_fields, SELECT_LEX *select,
327
332
                 Item **ref_pointer_array, ORDER *group_list)
328
333
{
329
334
  Item_outer_ref *ref;
330
 
  bool res= FALSE;
331
 
  bool direct_ref= FALSE;
332
335
 
333
336
  List_iterator<Item_outer_ref> ref_it(select->inner_refs_list);
334
337
  while ((ref= ref_it++))
335
338
  {
 
339
    bool direct_ref= false;
336
340
    Item *item= ref->outer_ref;
337
341
    Item **item_ref= ref->ref;
338
342
    Item_ref *new_ref;
402
406
 
403
407
    if (!ref->fixed && ref->fix_fields(thd, 0))
404
408
      return TRUE;
405
 
    thd->used_tables|= item->used_tables();
 
409
    thd->lex->used_tables|= item->used_tables();
406
410
  }
407
 
  return res;
 
411
  return false;
408
412
}
409
413
 
410
414
/**
422
426
  int res;
423
427
  nesting_map save_allow_sum_func=thd->lex->allow_sum_func ;
424
428
  /* 
425
 
    Need to save the value, so we can turn off only the new NON_AGG_FIELD
 
429
    Need to save the value, so we can turn off only any new non_agg_field_used
426
430
    additions coming from the WHERE
427
431
  */
428
 
  uint8 saved_flag= thd->lex->current_select->full_group_by_flag;
 
432
  const bool saved_non_agg_field_used=
 
433
    thd->lex->current_select->non_agg_field_used();
429
434
  DBUG_ENTER("setup_without_group");
430
435
 
431
436
  thd->lex->allow_sum_func&= ~(1 << thd->lex->current_select->nest_level);
432
437
  res= setup_conds(thd, tables, leaves, conds);
433
438
 
434
439
  /* it's not wrong to have non-aggregated columns in a WHERE */
435
 
  if (thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY)
436
 
    thd->lex->current_select->full_group_by_flag= saved_flag |
437
 
      (thd->lex->current_select->full_group_by_flag & ~NON_AGG_FIELD_USED);
 
440
  thd->lex->current_select->set_non_agg_field_used(saved_non_agg_field_used);
438
441
 
439
442
  thd->lex->allow_sum_func|= 1 << thd->lex->current_select->nest_level;
440
443
  res= res || setup_order(thd, ref_pointer_array, tables, fields, all_fields,
538
541
    thd->lex->allow_sum_func= save_allow_sum_func;
539
542
  }
540
543
 
541
 
  if (!thd->lex->view_prepare_mode && !(select_options & SELECT_DESCRIBE))
 
544
  if (!(thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW) &&
 
545
      !(select_options & SELECT_DESCRIBE))
542
546
  {
543
547
    Item_subselect *subselect;
544
548
    /* Is it subselect? */
639
643
    aggregate functions with implicit grouping (there is no GROUP BY).
640
644
  */
641
645
  if (thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY && !group_list &&
642
 
      select_lex->full_group_by_flag == (NON_AGG_FIELD_USED | SUM_FUNC_USED))
 
646
      select_lex->non_agg_field_used() &&
 
647
      select_lex->agg_func_used())
643
648
  {
644
649
    my_message(ER_MIX_OF_GROUP_FUNC_AND_FIELDS,
645
650
               ER(ER_MIX_OF_GROUP_FUNC_AND_FIELDS), MYF(0));
956
961
      If all items were resolved by opt_sum_query, there is no need to
957
962
      open any tables.
958
963
    */
959
 
    if ((res=opt_sum_query(select_lex->leaf_tables, all_fields, conds)))
 
964
    if ((res=opt_sum_query(thd, select_lex->leaf_tables, all_fields, conds)))
960
965
    {
961
966
      if (res == HA_ERR_KEY_NOT_FOUND)
962
967
      {
1627
1632
 
1628
1633
    if (exec_tmp_table1->distinct)
1629
1634
    {
1630
 
      table_map used_tables= thd->used_tables;
 
1635
      table_map used_tables= thd->lex->used_tables;
1631
1636
      JOIN_TAB *last_join_tab= join_tab+tables-1;
1632
1637
      do
1633
1638
      {
1924
1929
    if (!curr_join->sort_and_group &&
1925
1930
        curr_join->const_tables != curr_join->tables)
1926
1931
      curr_join->join_tab[curr_join->const_tables].sorted= 0;
1927
 
    if ((tmp_error= do_select(curr_join, (List<Item> *) 0, curr_tmp_table, 0)))
 
1932
 
 
1933
    Procedure *save_proc= curr_join->procedure;
 
1934
    tmp_error= do_select(curr_join, (List<Item> *) 0, curr_tmp_table, 0);
 
1935
    curr_join->procedure= save_proc;
 
1936
    if (tmp_error)
1928
1937
    {
1929
1938
      error= tmp_error;
1930
1939
      DBUG_VOID_RETURN;
2206
2215
 
2207
2216
      Item* sort_table_cond= make_cond_for_table(curr_join->tmp_having,
2208
2217
                                                 used_tables,
2209
 
                                                 used_tables);
 
2218
                                                 (table_map) 0);
2210
2219
      if (sort_table_cond)
2211
2220
      {
2212
2221
        if (!curr_table->select)
2517
2526
    if (!(join= new JOIN(thd, fields, select_options, result)))
2518
2527
        DBUG_RETURN(TRUE);
2519
2528
    thd_proc_info(thd, "init");
2520
 
    thd->used_tables=0;                         // Updated by setup_fields
 
2529
    thd->lex->used_tables=0;                         // Updated by setup_fields
2521
2530
    err= join->prepare(rref_pointer_array, tables, wild_num,
2522
2531
                       conds, og_num, order, group, having, proc_param,
2523
2532
                       select_lex, unit);
2668
2677
    table_vector[i]=s->table=table=tables->table;
2669
2678
    table->pos_in_table_list= tables;
2670
2679
    error= table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);
 
2680
 
 
2681
    DBUG_EXECUTE_IF("bug11747970_raise_error",
 
2682
                    {
 
2683
                      if (!error)
 
2684
                      {
 
2685
                        my_error(ER_UNKNOWN_ERROR, MYF(0));
 
2686
                        goto error;
 
2687
                      }
 
2688
                    });
 
2689
 
2671
2690
    if (error)
2672
2691
    {
2673
2692
      table->file->print_error(error, MYF(0));
3348
3367
        eq_func is NEVER true when num_values > 1
3349
3368
       */
3350
3369
      if (!eq_func)
3351
 
      {
3352
 
        /* 
3353
 
          Additional optimization: if we're processing
3354
 
          "t.key BETWEEN c1 AND c1" then proceed as if we were processing
3355
 
          "t.key = c1".
3356
 
          TODO: This is a very limited fix. A more generic fix is possible. 
3357
 
          There are 2 options:
3358
 
          A) Make equality propagation code be able to handle BETWEEN
3359
 
             (including cases like t1.key BETWEEN t2.key AND t3.key)
3360
 
          B) Make range optimizer to infer additional "t.key = c" equalities
3361
 
             and use them in equality propagation process (see details in
3362
 
             OptimizerKBAndTodo)
3363
 
        */
3364
 
        if ((cond->functype() != Item_func::BETWEEN) ||
3365
 
            ((Item_func_between*) cond)->negated ||
3366
 
            !value[0]->eq(value[1], field->binary()))
3367
 
          return;
3368
 
        eq_func= TRUE;
3369
 
      }
3370
 
 
 
3370
        return;
3371
3371
      if (field->result_type() == STRING_RESULT)
3372
3372
      {
3373
3373
        if ((*value)->result_type() != STRING_RESULT)
3563
3563
  case Item_func::OPTIMIZE_KEY:
3564
3564
  {
3565
3565
    Item **values;
3566
 
    // BETWEEN, IN, NE
3567
 
    if (is_local_field (cond_func->key_item()) &&
3568
 
        !(cond_func->used_tables() & OUTER_REF_TABLE_BIT))
 
3566
    /*
 
3567
      Build list of possible keys for 'a BETWEEN low AND high'.
 
3568
      It is handled similar to the equivalent condition 
 
3569
      'a >= low AND a <= high':
 
3570
    */
 
3571
    if (cond_func->functype() == Item_func::BETWEEN)
 
3572
    {
 
3573
      Item_field *field_item;
 
3574
      bool equal_func= FALSE;
 
3575
      uint num_values= 2;
 
3576
      values= cond_func->arguments();
 
3577
 
 
3578
      bool binary_cmp= (values[0]->real_item()->type() == Item::FIELD_ITEM)
 
3579
            ? ((Item_field*)values[0]->real_item())->field->binary()
 
3580
            : TRUE;
 
3581
 
 
3582
      /*
 
3583
        Additional optimization: If 'low = high':
 
3584
        Handle as if the condition was "t.key = low".
 
3585
      */
 
3586
      if (!((Item_func_between*)cond_func)->negated &&
 
3587
          values[1]->eq(values[2], binary_cmp))
 
3588
      {
 
3589
        equal_func= TRUE;
 
3590
        num_values= 1;
 
3591
      }
 
3592
 
 
3593
      /*
 
3594
        Append keys for 'field <cmp> value[]' if the
 
3595
        condition is of the form::
 
3596
        '<field> BETWEEN value[1] AND value[2]'
 
3597
      */
 
3598
      if (is_local_field (values[0]))
 
3599
      {
 
3600
        field_item= (Item_field *) (values[0]->real_item());
 
3601
        add_key_equal_fields(key_fields, *and_level, cond_func,
 
3602
                             field_item, equal_func, &values[1],
 
3603
                             num_values, usable_tables, sargables);
 
3604
      }
 
3605
      /*
 
3606
        Append keys for 'value[0] <cmp> field' if the
 
3607
        condition is of the form:
 
3608
        'value[0] BETWEEN field1 AND field2'
 
3609
      */
 
3610
      for (uint i= 1; i <= num_values; i++)
 
3611
      {
 
3612
        if (is_local_field (values[i]))
 
3613
        {
 
3614
          field_item= (Item_field *) (values[i]->real_item());
 
3615
          add_key_equal_fields(key_fields, *and_level, cond_func,
 
3616
                               field_item, equal_func, values,
 
3617
                               1, usable_tables, sargables);
 
3618
        }
 
3619
      }
 
3620
    } // if ( ... Item_func::BETWEEN)
 
3621
 
 
3622
    // IN, NE
 
3623
    else if (is_local_field (cond_func->key_item()) &&
 
3624
            !(cond_func->used_tables() & OUTER_REF_TABLE_BIT))
3569
3625
    {
3570
3626
      values= cond_func->arguments()+1;
3571
3627
      if (cond_func->functype() == Item_func::NE_FUNC &&
3579
3635
                           cond_func->argument_count()-1,
3580
3636
                           usable_tables, sargables);
3581
3637
    }
3582
 
    if (cond_func->functype() == Item_func::BETWEEN)
3583
 
    {
3584
 
      values= cond_func->arguments();
3585
 
      for (uint i= 1 ; i < cond_func->argument_count() ; i++)
3586
 
      {
3587
 
        Item_field *field_item;
3588
 
        if (is_local_field (cond_func->arguments()[i]))
3589
 
        {
3590
 
          field_item= (Item_field *) (cond_func->arguments()[i]->real_item());
3591
 
          add_key_equal_fields(key_fields, *and_level, cond_func,
3592
 
                               field_item, 0, values, 1, usable_tables, 
3593
 
                               sargables);
3594
 
        }
3595
 
      }  
3596
 
    }
3597
3638
    break;
3598
3639
  }
3599
3640
  case Item_func::OPTIMIZE_OP:
6379
6420
          tab->select_cond=sel->cond=tmp;
6380
6421
          /* Push condition to storage engine if this is enabled
6381
6422
             and the condition is not guarded */
6382
 
          tab->table->file->pushed_cond= NULL;
6383
6423
          if (thd->variables.engine_condition_pushdown)
6384
6424
          {
6385
6425
            COND *push_cond= 
9816
9856
                                          convert_blob_length);
9817
9857
    if (orig_type == Item::REF_ITEM && orig_modify)
9818
9858
      ((Item_ref*)orig_item)->set_result_field(result);
9819
 
    if (field->field->eq_def(result))
 
9859
    /*
 
9860
      Fields that are used as arguments to the DEFAULT() function already have
 
9861
      their data pointers set to the default value during name resulotion. See
 
9862
      Item_default_value::fix_fields.
 
9863
    */
 
9864
    if (orig_type != Item::DEFAULT_VALUE_ITEM && field->field->eq_def(result))
9820
9865
      *default_field= field->field;
9821
9866
    return result;
9822
9867
  }
10602
10647
  if (open_tmp_table(table))
10603
10648
    goto err;
10604
10649
 
 
10650
  // Make empty record so random data is not written to disk
 
10651
  empty_record(table);
 
10652
 
10605
10653
  thd->mem_root= mem_root_save;
10606
10654
 
10607
10655
  DBUG_RETURN(table);
12323
12371
    int error;
12324
12372
    if (join->having && join->having->val_int() == 0)
12325
12373
      DBUG_RETURN(NESTED_LOOP_OK);               // Didn't match having
 
12374
    if (join->procedure)
 
12375
    {
 
12376
      if (join->procedure->send_row(join->procedure_fields_list))
 
12377
        DBUG_RETURN(NESTED_LOOP_ERROR);
 
12378
      DBUG_RETURN(NESTED_LOOP_OK);
 
12379
    }
12326
12380
    error=0;
12327
 
    if (join->procedure)
12328
 
      error=join->procedure->send_row(join->procedure_fields_list);
12329
 
    else if (join->do_send_rows)
 
12381
    if (join->do_send_rows)
12330
12382
      error=join->result->send_data(*join->fields);
12331
12383
    if (error)
12332
12384
      DBUG_RETURN(NESTED_LOOP_ERROR); /* purecov: inspected */
12813
12865
  return 0;                                     // keep test
12814
12866
}
12815
12867
 
 
12868
/**
 
12869
   Extract a condition that can be checked after reading given table
 
12870
 
 
12871
   @param cond       Condition to analyze
 
12872
   @param tables     Tables for which "current field values" are available
 
12873
   @param used_table Table that we're extracting the condition for (may
 
12874
                     also include PSEUDO_TABLE_BITS, and may be zero)
 
12875
   @param exclude_expensive_cond  Do not push expensive conditions
 
12876
 
 
12877
   @retval <>NULL Generated condition
 
12878
   @retval =NULL  Already checked, OR error
 
12879
 
 
12880
   @details
 
12881
     Extract the condition that can be checked after reading the table
 
12882
     specified in 'used_table', given that current-field values for tables
 
12883
     specified in 'tables' bitmap are available.
 
12884
     If 'used_table' is 0
 
12885
     - extract conditions for all tables in 'tables'.
 
12886
     - extract conditions are unrelated to any tables
 
12887
       in the same query block/level(i.e. conditions
 
12888
       which have used_tables == 0).
 
12889
 
 
12890
     The function assumes that
 
12891
     - Constant parts of the condition has already been checked.
 
12892
     - Condition that could be checked for tables in 'tables' has already
 
12893
     been checked.
 
12894
 
 
12895
     The function takes into account that some parts of the condition are
 
12896
     guaranteed to be true by employed 'ref' access methods (the code that
 
12897
     does this is located at the end, search down for "EQ_FUNC").
 
12898
 
 
12899
   @note
 
12900
     Make sure to keep the implementations of make_cond_for_table() and
 
12901
     make_cond_after_sjm() synchronized.
 
12902
     make_cond_for_info_schema() uses similar algorithm as well.
 
12903
*/ 
12816
12904
 
12817
12905
static COND *
12818
12906
make_cond_for_table(COND *cond, table_map tables, table_map used_table)
13337
13425
{
13338
13426
  int ref_key;
13339
13427
  uint ref_key_parts;
13340
 
  int order_direction;
 
13428
  int order_direction= 0;
13341
13429
  uint used_key_parts;
13342
13430
  TABLE *table=tab->table;
13343
13431
  SQL_SELECT *select=tab->select;
13344
13432
  key_map usable_keys;
13345
13433
  QUICK_SELECT_I *save_quick= 0;
 
13434
  int best_key= -1;
 
13435
 
13346
13436
  DBUG_ENTER("test_if_skip_sort_order");
13347
13437
  LINT_INIT(ref_key_parts);
13348
13438
 
13446
13536
          new_ref_key_map.clear_all();  // Force the creation of quick select
13447
13537
          new_ref_key_map.set_bit(new_ref_key); // only for new_ref_key.
13448
13538
 
 
13539
          select->quick= 0;
13449
13540
          if (select->test_quick_select(tab->join->thd, new_ref_key_map, 0,
13450
13541
                                        (tab->join->select_options &
13451
13542
                                         OPTION_FOUND_ROWS) ?
13452
13543
                                        HA_POS_ERROR :
13453
13544
                                        tab->join->unit->select_limit_cnt,0) <=
13454
13545
              0)
13455
 
            DBUG_RETURN(0);
 
13546
            goto use_filesort;
13456
13547
        }
13457
13548
        ref_key= new_ref_key;
13458
13549
      }
13477
13568
    int best_key_direction= 0;
13478
13569
    ha_rows best_records= 0;
13479
13570
    double read_time;
13480
 
    int best_key= -1;
13481
13571
    bool is_best_covering= FALSE;
13482
13572
    double fanout= 1;
13483
13573
    JOIN *join= tab->join;
13654
13744
         tab->join->tables > tab->join->const_tables + 1) &&
13655
13745
         ((unsigned) best_key != table->s->primary_key ||
13656
13746
          !table->file->primary_key_is_clustered()))
13657
 
      DBUG_RETURN(0);
 
13747
      goto use_filesort;
13658
13748
 
13659
13749
    if (best_key >= 0)
13660
13750
    {
13661
 
      bool quick_created= FALSE;
13662
13751
      if (table->quick_keys.is_set(best_key) && best_key != ref_key)
13663
13752
      {
13664
13753
        key_map map;
13665
13754
        map.clear_all();       // Force the creation of quick select
13666
13755
        map.set_bit(best_key); // only best_key.
13667
 
        quick_created=         
13668
 
          select->test_quick_select(join->thd, map, 0,
13669
 
                                    join->select_options & OPTION_FOUND_ROWS ?
13670
 
                                    HA_POS_ERROR :
13671
 
                                    join->unit->select_limit_cnt,
13672
 
                                    0) > 0;
13673
 
      }
13674
 
      if (!no_changes)
13675
 
      {
13676
 
        /* 
13677
 
           If ref_key used index tree reading only ('Using index' in EXPLAIN),
13678
 
           and best_key doesn't, then revert the decision.
13679
 
        */
13680
 
        if (!table->covering_keys.is_set(best_key))
13681
 
          table->set_keyread(FALSE);
13682
 
        if (!quick_created)
13683
 
        {
13684
 
          tab->index= best_key;
13685
 
          tab->read_first_record= best_key_direction > 0 ?
13686
 
                                  join_read_first:join_read_last;
13687
 
          tab->type=JT_NEXT;           // Read with index_first(), index_next()
13688
 
          if (select && select->quick)
13689
 
          {
13690
 
            delete select->quick;
13691
 
            select->quick= 0;
13692
 
          }
13693
 
          if (table->covering_keys.is_set(best_key))
13694
 
            table->set_keyread(TRUE);
13695
 
          table->file->ha_index_or_rnd_end();
13696
 
          if (join->select_options & SELECT_DESCRIBE)
13697
 
          {
13698
 
            tab->ref.key= -1;
13699
 
            tab->ref.key_parts= 0;
13700
 
            if (select_limit < table_records) 
13701
 
              tab->limit= select_limit;
13702
 
          }
13703
 
        }
13704
 
        else if (tab->type != JT_ALL)
13705
 
        {
13706
 
          /*
13707
 
            We're about to use a quick access to the table.
13708
 
            We need to change the access method so as the quick access
13709
 
            method is actually used.
13710
 
          */
13711
 
          DBUG_ASSERT(tab->select->quick);
13712
 
          tab->type=JT_ALL;
13713
 
          tab->use_quick=1;
13714
 
          tab->ref.key= -1;
13715
 
          tab->ref.key_parts=0;         // Don't use ref key.
13716
 
          tab->read_first_record= join_init_read_record;
13717
 
          if (tab->is_using_loose_index_scan())
13718
 
            join->tmp_table_param.precomputed_group_by= TRUE;
13719
 
          /*
13720
 
            TODO: update the number of records in join->best_positions[tablenr]
13721
 
          */
13722
 
        }
 
13756
        select->quick= 0;
 
13757
        select->test_quick_select(join->thd, map, 0,
 
13758
                                  join->select_options & OPTION_FOUND_ROWS ?
 
13759
                                  HA_POS_ERROR :
 
13760
                                  join->unit->select_limit_cnt,
 
13761
                                  0);
13723
13762
      }
13724
13763
      order_direction= best_key_direction;
13725
13764
      /*
13732
13771
        saved_best_key_parts :  best_key_parts;
13733
13772
    }
13734
13773
    else
13735
 
      DBUG_RETURN(0); 
 
13774
      goto use_filesort;
13736
13775
  } 
13737
13776
 
13738
13777
check_reverse_order:                  
 
13778
  DBUG_ASSERT(order_direction != 0);
 
13779
 
13739
13780
  if (order_direction == -1)            // If ORDER BY ... DESC
13740
13781
  {
13741
13782
    if (select && select->quick)
13744
13785
        Don't reverse the sort order, if it's already done.
13745
13786
        (In some cases test_if_order_by_key() can be called multiple times
13746
13787
      */
13747
 
      if (!select->quick->reverse_sorted())
 
13788
      if (select->quick->reverse_sorted())
 
13789
        goto skipped_filesort;
 
13790
      else
13748
13791
      {
13749
 
        QUICK_SELECT_DESC *tmp;
13750
13792
        int quick_type= select->quick->get_type();
13751
13793
        if (quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE ||
13752
13794
            quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT ||
13754
13796
            quick_type == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX)
13755
13797
        {
13756
13798
          tab->limit= 0;
13757
 
          select->quick= save_quick;
13758
 
          DBUG_RETURN(0);                   // Use filesort
13759
 
        }
13760
 
            
 
13799
          goto use_filesort;               // Use filesort
 
13800
        }
 
13801
      }
 
13802
    }
 
13803
  }
 
13804
 
 
13805
  /*
 
13806
    Update query plan with access pattern for doing 
 
13807
    ordered access according to what we have decided
 
13808
    above.
 
13809
  */
 
13810
  if (!no_changes) // We are allowed to update QEP
 
13811
  {
 
13812
    if (best_key >= 0)
 
13813
    {
 
13814
      bool quick_created= 
 
13815
        (select && select->quick && select->quick!=save_quick);
 
13816
 
 
13817
      /* 
 
13818
         If ref_key used index tree reading only ('Using index' in EXPLAIN),
 
13819
         and best_key doesn't, then revert the decision.
 
13820
      */
 
13821
      if (!table->covering_keys.is_set(best_key))
 
13822
        table->set_keyread(FALSE);
 
13823
      if (!quick_created)
 
13824
      {
 
13825
        if (select)                  // Throw any existing quick select
 
13826
          select->quick= 0;          // Cleanup either reset to save_quick,
 
13827
                                     // or 'delete save_quick'
 
13828
        tab->index= best_key;
 
13829
        tab->read_first_record= order_direction > 0 ?
 
13830
                                join_read_first:join_read_last;
 
13831
        tab->type=JT_NEXT;           // Read with index_first(), index_next()
 
13832
 
 
13833
        if (table->covering_keys.is_set(best_key))
 
13834
          table->set_keyread(TRUE);
 
13835
        table->file->ha_index_or_rnd_end();
 
13836
        if (tab->join->select_options & SELECT_DESCRIBE)
 
13837
        {
 
13838
          tab->ref.key= -1;
 
13839
          tab->ref.key_parts= 0;
 
13840
          if (select_limit < table->file->stats.records) 
 
13841
            tab->limit= select_limit;
 
13842
        }
 
13843
      }
 
13844
      else if (tab->type != JT_ALL)
 
13845
      {
 
13846
        /*
 
13847
          We're about to use a quick access to the table.
 
13848
          We need to change the access method so as the quick access
 
13849
          method is actually used.
 
13850
        */
 
13851
        DBUG_ASSERT(tab->select->quick);
 
13852
        tab->type=JT_ALL;
 
13853
        tab->use_quick=1;
 
13854
        tab->ref.key= -1;
 
13855
        tab->ref.key_parts=0;           // Don't use ref key.
 
13856
        tab->read_first_record= join_init_read_record;
 
13857
        if (tab->is_using_loose_index_scan())
 
13858
          tab->join->tmp_table_param.precomputed_group_by= TRUE;
 
13859
        /*
 
13860
          TODO: update the number of records in join->best_positions[tablenr]
 
13861
        */
 
13862
      }
 
13863
    } // best_key >= 0
 
13864
 
 
13865
    if (order_direction == -1)          // If ORDER BY ... DESC
 
13866
    {
 
13867
      if (select && select->quick)
 
13868
      {
 
13869
        QUICK_SELECT_DESC *tmp;
13761
13870
        /* ORDER BY range_key DESC */
13762
 
        tmp= new QUICK_SELECT_DESC((QUICK_RANGE_SELECT*)(select->quick),
 
13871
        tmp= new QUICK_SELECT_DESC((QUICK_RANGE_SELECT*)(select->quick),
13763
13872
                                    used_key_parts);
13764
 
        if (!tmp || tmp->error)
13765
 
        {
13766
 
          delete tmp;
13767
 
          select->quick= save_quick;
 
13873
        if (tmp && select->quick == save_quick)
 
13874
          save_quick= 0;    // ::QUICK_SELECT_DESC consumed it
 
13875
 
 
13876
        if (!tmp || tmp->error)
 
13877
        {
 
13878
          delete tmp;
13768
13879
          tab->limit= 0;
13769
 
          DBUG_RETURN(0);               // Reverse sort not supported
13770
 
        }
13771
 
        select->quick=tmp;
13772
 
      }
13773
 
    }
13774
 
    else if (tab->type != JT_NEXT && tab->type != JT_REF_OR_NULL &&
13775
 
             tab->ref.key >= 0 && tab->ref.key_parts <= used_key_parts)
13776
 
    {
13777
 
      /*
13778
 
        SELECT * FROM t1 WHERE a=1 ORDER BY a DESC,b DESC
13779
 
 
13780
 
        Use a traversal function that starts by reading the last row
13781
 
        with key part (A) and then traverse the index backwards.
13782
 
      */
13783
 
      tab->read_first_record= join_read_last_key;
13784
 
      tab->read_record.read_record= join_read_prev_same;
13785
 
    }
 
13880
          goto use_filesort;           // Reverse sort failed -> filesort
 
13881
        }
 
13882
        select->quick= tmp;
 
13883
      }
 
13884
      else if (tab->type != JT_NEXT && tab->type != JT_REF_OR_NULL &&
 
13885
               tab->ref.key >= 0 && tab->ref.key_parts <= used_key_parts)
 
13886
      {
 
13887
        /*
 
13888
          SELECT * FROM t1 WHERE a=1 ORDER BY a DESC,b DESC
 
13889
 
 
13890
          Use a traversal function that starts by reading the last row
 
13891
          with key part (A) and then traverse the index backwards.
 
13892
        */
 
13893
        tab->read_first_record= join_read_last_key;
 
13894
        tab->read_record.read_record= join_read_prev_same;
 
13895
      }
 
13896
    }
 
13897
    else if (select && select->quick)
 
13898
      select->quick->sorted= 1;
 
13899
 
 
13900
  } // QEP has been modified
 
13901
 
 
13902
  /*
 
13903
    Cleanup:
 
13904
    We may have both a 'select->quick' and 'save_quick' (original)
 
13905
    at this point. Delete the one that we wan't use.
 
13906
  */
 
13907
 
 
13908
skipped_filesort:
 
13909
  // Keep current (ordered) select->quick 
 
13910
  if (select && save_quick != select->quick)
 
13911
  {
 
13912
    delete save_quick;
 
13913
    save_quick= NULL;
13786
13914
  }
13787
 
  else if (select && select->quick)
13788
 
    select->quick->sorted= 1;
13789
13915
  DBUG_RETURN(1);
 
13916
 
 
13917
use_filesort:
 
13918
  // Restore original save_quick
 
13919
  if (select && select->quick != save_quick)
 
13920
  {
 
13921
    delete select->quick;
 
13922
    select->quick= save_quick;
 
13923
  }
 
13924
  DBUG_RETURN(0);
13790
13925
}
13791
13926
 
13792
13927
 
16827
16962
          need_order=0;
16828
16963
          extra.append(STRING_WITH_LEN("; Using filesort"));
16829
16964
        }
16830
 
        if (distinct & test_all_bits(used_tables,thd->used_tables))
 
16965
        if (distinct & test_all_bits(used_tables, thd->lex->used_tables))
16831
16966
          extra.append(STRING_WITH_LEN("; Distinct"));
16832
16967
 
16833
16968
        for (uint part= 0; part < tab->ref.key_parts; part++)