~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/opt_range.cc

  • Committer: Monty Taylor
  • Date: 2008-11-16 05:36:13 UTC
  • mto: (584.1.9 devel)
  • mto: This revision was merged to the branch mainline in revision 589.
  • Revision ID: monty@inaugust.com-20081116053613-bld4rqxhlkb49c02
Split out cache_row and type_holder.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
2
 
 *  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
3
 
 *
4
 
 *  Copyright (C) 2008-2009 Sun Microsystems, Inc.
5
 
 *
6
 
 *  This program is free software; you can redistribute it and/or modify
7
 
 *  it under the terms of the GNU General Public License as published by
8
 
 *  the Free Software Foundation; version 2 of the License.
9
 
 *
10
 
 *  This program is distributed in the hope that it will be useful,
11
 
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 
 *  GNU General Public License for more details.
14
 
 *
15
 
 *  You should have received a copy of the GNU General Public License
16
 
 *  along with this program; if not, write to the Free Software
17
 
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
18
 
 */
 
1
/* Copyright (C) 2000-2006 MySQL AB
 
2
 
 
3
   This program is free software; you can redistribute it and/or modify
 
4
   it under the terms of the GNU General Public License as published by
 
5
   the Free Software Foundation; version 2 of the License.
 
6
 
 
7
   This program is distributed in the hope that it will be useful,
 
8
   but WITHOUT ANY WARRANTY; without even the implied warranty of
 
9
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
10
   GNU General Public License for more details.
 
11
 
 
12
   You should have received a copy of the GNU General Public License
 
13
   along with this program; if not, write to the Free Software
 
14
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
19
15
 
20
16
/*
21
17
  TODO:
27
23
*/
28
24
 
29
25
/*
30
 
  This cursor contains:
 
26
  This file contains:
31
27
 
32
 
  RangeAnalysisModule
33
 
    A module that accepts a condition, index (or partitioning) description,
34
 
    and builds lists of intervals (in index/partitioning space), such that
35
 
    all possible records that match the condition are contained within the
 
28
  RangeAnalysisModule  
 
29
    A module that accepts a condition, index (or partitioning) description, 
 
30
    and builds lists of intervals (in index/partitioning space), such that 
 
31
    all possible records that match the condition are contained within the 
36
32
    intervals.
37
33
    The entry point for the range analysis module is get_mm_tree() function.
38
 
 
 
34
    
39
35
    The lists are returned in form of complicated structure of interlinked
40
 
    optimizer::SEL_TREE/optimizer::SEL_IMERGE/SEL_ARG objects.
41
 
    See quick_range_seq_next, find_used_partitions for examples of how to walk
 
36
    SEL_TREE/SEL_IMERGE/SEL_ARG objects.
 
37
    See quick_range_seq_next, find_used_partitions for examples of how to walk 
42
38
    this structure.
43
 
    All direct "users" of this module are located within this cursor, too.
44
 
 
45
 
 
46
 
  Range/index_merge/groupby-minmax optimizer module
47
 
    A module that accepts a table, condition, and returns
 
39
    All direct "users" of this module are located within this file, too.
 
40
 
 
41
 
 
42
  PartitionPruningModule
 
43
    A module that accepts a partitioned table, condition, and finds which
 
44
    partitions we will need to use in query execution. Search down for
 
45
    "PartitionPruningModule" for description.
 
46
    The module has single entry point - prune_partitions() function.
 
47
 
 
48
 
 
49
  Range/index_merge/groupby-minmax optimizer module  
 
50
    A module that accepts a table, condition, and returns 
48
51
     - a QUICK_*_SELECT object that can be used to retrieve rows that match
49
 
       the specified condition, or a "no records will match the condition"
 
52
       the specified condition, or a "no records will match the condition" 
50
53
       statement.
51
54
 
52
55
    The module entry points are
59
62
 
60
63
  KeyTupleFormat
61
64
  ~~~~~~~~~~~~~~
62
 
  The code in this cursor (and elsewhere) makes operations on key value tuples.
 
65
  The code in this file (and elsewhere) makes operations on key value tuples.
63
66
  Those tuples are stored in the following format:
64
 
 
 
67
  
65
68
  The tuple is a sequence of key part values. The length of key part value
66
69
  depends only on its type (and not depends on the what value is stored)
67
 
 
 
70
  
68
71
    KeyTuple: keypart1-data, keypart2-data, ...
69
 
 
 
72
  
70
73
  The value of each keypart is stored in the following format:
71
 
 
 
74
  
72
75
    keypart_data: [isnull_byte] keypart-value-bytes
73
76
 
74
77
  If a keypart may have a NULL value (key_part->field->real_maybe_null() can
75
 
  be used to check this), then the first byte is a NULL indicator with the
 
78
  be used to check this), then the first byte is a NULL indicator with the 
76
79
  following valid values:
77
80
    1  - keypart has NULL value.
78
81
    0  - keypart has non-NULL value.
83
86
 
84
87
  keypart-value-bytes holds the value. Its format depends on the field type.
85
88
  The length of keypart-value-bytes may or may not depend on the value being
86
 
  stored. The default is that length is static and equal to
87
 
  KeyPartInfo::length.
88
 
 
89
 
  Key parts with (key_part_flag & HA_BLOB_PART) have length depending of the
 
89
  stored. The default is that length is static and equal to 
 
90
  KEY_PART_INFO::length.
 
91
  
 
92
  Key parts with (key_part_flag & HA_BLOB_PART) have length depending of the 
90
93
  value:
91
 
 
 
94
  
92
95
     keypart-value-bytes: value_length value_bytes
93
96
 
94
97
  The value_length part itself occupies HA_KEY_BLOB_LENGTH=2 bytes.
96
99
  See key_copy() and key_restore() for code to move data between index tuple
97
100
  and table record
98
101
 
99
 
  CAUTION: the above description is only sergefp's understanding of the
 
102
  CAUTION: the above description is only sergefp's understanding of the 
100
103
           subject and may omit some details.
101
104
*/
102
105
 
103
 
#include "config.h"
104
 
 
105
 
#include <math.h>
106
 
#include <float.h>
107
 
 
108
 
#include <string>
109
 
#include <vector>
110
 
#include <algorithm>
111
 
 
112
 
#include <boost/dynamic_bitset.hpp>
113
 
 
114
 
#include "drizzled/check_stack_overrun.h"
115
 
#include "drizzled/error.h"
116
 
#include "drizzled/field/num.h"
117
 
#include "drizzled/internal/iocache.h"
118
 
#include "drizzled/internal/my_sys.h"
119
 
#include "drizzled/item/cmpfunc.h"
120
 
#include "drizzled/optimizer/cost_vector.h"
121
 
#include "drizzled/optimizer/quick_group_min_max_select.h"
122
 
#include "drizzled/optimizer/quick_index_merge_select.h"
123
 
#include "drizzled/optimizer/quick_range.h"
124
 
#include "drizzled/optimizer/quick_range_select.h"
125
 
#include "drizzled/optimizer/quick_ror_intersect_select.h"
126
 
#include "drizzled/optimizer/quick_ror_union_select.h"
127
 
#include "drizzled/optimizer/range.h"
128
 
#include "drizzled/optimizer/range_param.h"
129
 
#include "drizzled/optimizer/sel_arg.h"
130
 
#include "drizzled/optimizer/sel_imerge.h"
131
 
#include "drizzled/optimizer/sel_tree.h"
132
 
#include "drizzled/optimizer/sum.h"
133
 
#include "drizzled/optimizer/table_read_plan.h"
134
 
#include "drizzled/plugin/storage_engine.h"
135
 
#include "drizzled/records.h"
136
 
#include "drizzled/sql_base.h"
137
 
#include "drizzled/sql_select.h"
138
 
#include "drizzled/table_reference.h"
139
 
 
140
 
#include "drizzled/temporal.h" /* Needed in get_mm_leaf() for timestamp -> datetime comparisons */
141
 
 
142
 
using namespace std;
143
 
namespace drizzled
144
 
{
145
 
 
146
 
#define HA_END_SPACE_KEY 0
 
106
#include <drizzled/server_includes.h>
 
107
#include <drizzled/sql_select.h>
 
108
#include <drizzled/error.h>
 
109
#include <drizzled/cost_vect.h>
 
110
 
 
111
#include CMATH_H
 
112
 
 
113
#if defined(CMATH_NAMESPACE)
 
114
using namespace CMATH_NAMESPACE;
 
115
#endif
147
116
 
148
117
/*
149
118
  Convert double value to #rows. Currently this does floor(), and we
150
119
  might consider using round() instead.
151
120
*/
152
 
static inline ha_rows double2rows(double x)
153
 
{
154
 
    return static_cast<ha_rows>(x);
155
 
}
 
121
#define double2rows(x) ((ha_rows)(x))
 
122
 
 
123
static int sel_cmp(Field *f,unsigned char *a,unsigned char *b,uint8_t a_flag,uint8_t b_flag);
156
124
 
157
125
static unsigned char is_null_string[2]= {1,0};
158
126
 
159
 
 
160
 
/**
161
 
  Get cost of reading nrows table records in a "disk sweep"
162
 
 
163
 
  A disk sweep read is a sequence of Cursor->rnd_pos(rowid) calls that made
164
 
  for an ordered sequence of rowids.
165
 
 
166
 
  We assume hard disk IO. The read is performed as follows:
167
 
 
168
 
   1. The disk head is moved to the needed cylinder
169
 
   2. The controller waits for the plate to rotate
170
 
   3. The data is transferred
171
 
 
172
 
  Time to do #3 is insignificant compared to #2+#1.
173
 
 
174
 
  Time to move the disk head is proportional to head travel distance.
175
 
 
176
 
  Time to wait for the plate to rotate depends on whether the disk head
177
 
  was moved or not.
178
 
 
179
 
  If disk head wasn't moved, the wait time is proportional to distance
180
 
  between the previous block and the block we're reading.
181
 
 
182
 
  If the head was moved, we don't know how much we'll need to wait for the
183
 
  plate to rotate. We assume the wait time to be a variate with a mean of
184
 
  0.5 of full rotation time.
185
 
 
186
 
  Our cost units are "random disk seeks". The cost of random disk seek is
187
 
  actually not a constant, it depends one range of cylinders we're going
188
 
  to access. We make it constant by introducing a fuzzy concept of "typical
189
 
  datafile length" (it's fuzzy as it's hard to tell whether it should
190
 
  include index cursor, temp.tables etc). Then random seek cost is:
191
 
 
192
 
    1 = half_rotation_cost + move_cost * 1/3 * typical_data_file_length
193
 
 
194
 
  We define half_rotation_cost as DISK_SEEK_BASE_COST=0.9.
195
 
 
196
 
  @param table             Table to be accessed
197
 
  @param nrows             Number of rows to retrieve
198
 
  @param interrupted       true <=> Assume that the disk sweep will be
199
 
                           interrupted by other disk IO. false - otherwise.
200
 
  @param cost         OUT  The cost.
201
 
*/
202
 
 
203
 
static void get_sweep_read_cost(Table *table,
204
 
                                ha_rows nrows,
205
 
                                bool interrupted,
206
 
                                optimizer::CostVector *cost)
207
 
{
208
 
  cost->zero();
209
 
  if (table->cursor->primary_key_is_clustered())
210
 
  {
211
 
    cost->setIOCount(table->cursor->read_time(table->getShare()->getPrimaryKey(),
212
 
                                             static_cast<uint32_t>(nrows),
213
 
                                             nrows));
214
 
  }
215
 
  else
216
 
  {
217
 
    double n_blocks=
218
 
      ceil(uint64_t2double(table->cursor->stats.data_file_length) / IO_SIZE);
219
 
    double busy_blocks=
220
 
      n_blocks * (1.0 - pow(1.0 - 1.0/n_blocks, rows2double(nrows)));
221
 
    if (busy_blocks < 1.0)
222
 
      busy_blocks= 1.0;
223
 
 
224
 
    cost->setIOCount(busy_blocks);
225
 
 
226
 
    if (! interrupted)
227
 
    {
228
 
      /* Assume reading is done in one 'sweep' */
229
 
      cost->setAvgIOCost((DISK_SEEK_BASE_COST +
230
 
                          DISK_SEEK_PROP_COST*n_blocks/busy_blocks));
231
 
    }
232
 
  }
233
 
}
234
 
 
235
 
static optimizer::SEL_TREE * get_mm_parts(optimizer::RangeParameter *param,
236
 
                               COND *cond_func,
237
 
                               Field *field,
238
 
                                                 Item_func::Functype type,
239
 
                               Item *value,
240
 
                                                 Item_result cmp_type);
241
 
 
242
 
static optimizer::SEL_ARG *get_mm_leaf(optimizer::RangeParameter *param,
243
 
                                       COND *cond_func,
244
 
                                       Field *field,
245
 
                                       KEY_PART *key_part,
246
 
                                                         Item_func::Functype type,
247
 
                                       Item *value);
248
 
 
249
 
static optimizer::SEL_TREE *get_mm_tree(optimizer::RangeParameter *param, COND *cond);
250
 
 
251
 
static bool is_key_scan_ror(optimizer::Parameter *param, uint32_t keynr, uint8_t nparts);
252
 
 
253
 
static ha_rows check_quick_select(Session *session,
254
 
                                  optimizer::Parameter *param,
255
 
                                  uint32_t idx,
256
 
                                  bool index_only,
257
 
                                  optimizer::SEL_ARG *tree,
258
 
                                  bool update_tbl_stats,
259
 
                                  uint32_t *mrr_flags,
260
 
                                  uint32_t *bufsize,
261
 
                                  optimizer::CostVector *cost);
262
 
 
263
 
static optimizer::RangeReadPlan *get_key_scans_params(Session *session,
264
 
                                                      optimizer::Parameter *param,
265
 
                                                      optimizer::SEL_TREE *tree,
266
 
                                                      bool index_read_must_be_used,
267
 
                                                      bool update_tbl_stats,
268
 
                                                      double read_time);
269
 
 
270
 
static
271
 
optimizer::RorIntersectReadPlan *get_best_ror_intersect(const optimizer::Parameter *param,
272
 
                                                        optimizer::SEL_TREE *tree,
273
 
                                                        double read_time,
274
 
                                                        bool *are_all_covering);
275
 
 
276
 
static
277
 
optimizer::RorIntersectReadPlan *get_best_covering_ror_intersect(optimizer::Parameter *param,
278
 
                                                                 optimizer::SEL_TREE *tree,
279
 
                                                                 double read_time);
280
 
 
281
 
static
282
 
optimizer::TableReadPlan *get_best_disjunct_quick(Session *session,
283
 
                                                  optimizer::Parameter *param,
284
 
                                                  optimizer::SEL_IMERGE *imerge,
285
 
                                                  double read_time);
286
 
 
287
 
static
288
 
optimizer::GroupMinMaxReadPlan *get_best_group_min_max(optimizer::Parameter *param, optimizer::SEL_TREE *tree);
289
 
 
290
 
static optimizer::SEL_TREE *tree_and(optimizer::RangeParameter *param, 
291
 
                                     optimizer::SEL_TREE *tree1, 
292
 
                                     optimizer::SEL_TREE *tree2);
293
 
 
294
 
static optimizer::SEL_ARG *sel_add(optimizer::SEL_ARG *key1, optimizer::SEL_ARG *key2);
295
 
 
296
 
static optimizer::SEL_ARG *key_and(optimizer::RangeParameter *param,
297
 
                                   optimizer::SEL_ARG *key1,
298
 
                                   optimizer::SEL_ARG *key2,
299
 
                                   uint32_t clone_flag);
300
 
 
301
 
static bool get_range(optimizer::SEL_ARG **e1, optimizer::SEL_ARG **e2, optimizer::SEL_ARG *root1);
302
 
 
303
 
optimizer::SEL_ARG optimizer::null_element(optimizer::SEL_ARG::IMPOSSIBLE);
304
 
 
305
 
static bool null_part_in_key(KEY_PART *key_part,
306
 
                             const unsigned char *key,
 
127
class RANGE_OPT_PARAM;
 
128
/*
 
129
  A construction block of the SEL_ARG-graph.
 
130
  
 
131
  The following description only covers graphs of SEL_ARG objects with 
 
132
  sel_arg->type==KEY_RANGE:
 
133
 
 
134
  One SEL_ARG object represents an "elementary interval" in form
 
135
  
 
136
      min_value <=?  table.keypartX  <=? max_value
 
137
  
 
138
  The interval is a non-empty interval of any kind: with[out] minimum/maximum
 
139
  bound, [half]open/closed, single-point interval, etc.
 
140
 
 
141
  1. SEL_ARG GRAPH STRUCTURE
 
142
  
 
143
  SEL_ARG objects are linked together in a graph. The meaning of the graph
 
144
  is better demostrated by an example:
 
145
  
 
146
     tree->keys[i]
 
147
      | 
 
148
      |             $              $
 
149
      |    part=1   $     part=2   $    part=3
 
150
      |             $              $
 
151
      |  +-------+  $   +-------+  $   +--------+
 
152
      |  | kp1<1 |--$-->| kp2=5 |--$-->| kp3=10 |
 
153
      |  +-------+  $   +-------+  $   +--------+
 
154
      |      |      $              $       |
 
155
      |      |      $              $   +--------+
 
156
      |      |      $              $   | kp3=12 | 
 
157
      |      |      $              $   +--------+ 
 
158
      |  +-------+  $              $   
 
159
      \->| kp1=2 |--$--------------$-+ 
 
160
         +-------+  $              $ |   +--------+
 
161
             |      $              $  ==>| kp3=11 |
 
162
         +-------+  $              $ |   +--------+
 
163
         | kp1=3 |--$--------------$-+       |
 
164
         +-------+  $              $     +--------+
 
165
             |      $              $     | kp3=14 |
 
166
            ...     $              $     +--------+
 
167
 
 
168
  The entire graph is partitioned into "interval lists".
 
169
 
 
170
  An interval list is a sequence of ordered disjoint intervals over the same
 
171
  key part. SEL_ARG are linked via "next" and "prev" pointers. Additionally,
 
172
  all intervals in the list form an RB-tree, linked via left/right/parent 
 
173
  pointers. The RB-tree root SEL_ARG object will be further called "root of the
 
174
  interval list".
 
175
  
 
176
    In the example pic, there are 4 interval lists: 
 
177
    "kp<1 OR kp1=2 OR kp1=3", "kp2=5", "kp3=10 OR kp3=12", "kp3=11 OR kp3=13".
 
178
    The vertical lines represent SEL_ARG::next/prev pointers.
 
179
    
 
180
  In an interval list, each member X may have SEL_ARG::next_key_part pointer
 
181
  pointing to the root of another interval list Y. The pointed interval list
 
182
  must cover a key part with greater number (i.e. Y->part > X->part).
 
183
    
 
184
    In the example pic, the next_key_part pointers are represented by
 
185
    horisontal lines.
 
186
 
 
187
  2. SEL_ARG GRAPH SEMANTICS
 
188
 
 
189
  It represents a condition in a special form (we don't have a name for it ATM)
 
190
  The SEL_ARG::next/prev is "OR", and next_key_part is "AND".
 
191
  
 
192
  For example, the picture represents the condition in form:
 
193
   (kp1 < 1 AND kp2=5 AND (kp3=10 OR kp3=12)) OR 
 
194
   (kp1=2 AND (kp3=11 OR kp3=14)) OR 
 
195
   (kp1=3 AND (kp3=11 OR kp3=14))
 
196
 
 
197
 
 
198
  3. SEL_ARG GRAPH USE
 
199
 
 
200
  Use get_mm_tree() to construct SEL_ARG graph from WHERE condition.
 
201
  Then walk the SEL_ARG graph and get a list of dijsoint ordered key
 
202
  intervals (i.e. intervals in form
 
203
  
 
204
   (constA1, .., const1_K) < (keypart1,.., keypartK) < (constB1, .., constB_K)
 
205
 
 
206
  Those intervals can be used to access the index. The uses are in:
 
207
   - check_quick_select() - Walk the SEL_ARG graph and find an estimate of
 
208
                            how many table records are contained within all
 
209
                            intervals.
 
210
   - get_quick_select()   - Walk the SEL_ARG, materialize the key intervals,
 
211
                            and create QUICK_RANGE_SELECT object that will
 
212
                            read records within these intervals.
 
213
 
 
214
  4. SPACE COMPLEXITY NOTES 
 
215
 
 
216
    SEL_ARG graph is a representation of an ordered disjoint sequence of
 
217
    intervals over the ordered set of index tuple values.
 
218
 
 
219
    For multi-part keys, one can construct a WHERE expression such that its
 
220
    list of intervals will be of combinatorial size. Here is an example:
 
221
     
 
222
      (keypart1 IN (1,2, ..., n1)) AND 
 
223
      (keypart2 IN (1,2, ..., n2)) AND 
 
224
      (keypart3 IN (1,2, ..., n3))
 
225
    
 
226
    For this WHERE clause the list of intervals will have n1*n2*n3 intervals
 
227
    of form
 
228
     
 
229
      (keypart1, keypart2, keypart3) = (k1, k2, k3), where 1 <= k{i} <= n{i}
 
230
    
 
231
    SEL_ARG graph structure aims to reduce the amount of required space by
 
232
    "sharing" the elementary intervals when possible (the pic at the
 
233
    beginning of this comment has examples of such sharing). The sharing may 
 
234
    prevent combinatorial blowup:
 
235
 
 
236
      There are WHERE clauses that have combinatorial-size interval lists but
 
237
      will be represented by a compact SEL_ARG graph.
 
238
      Example:
 
239
        (keypartN IN (1,2, ..., n1)) AND 
 
240
        ...
 
241
        (keypart2 IN (1,2, ..., n2)) AND 
 
242
        (keypart1 IN (1,2, ..., n3))
 
243
 
 
244
    but not in all cases:
 
245
 
 
246
    - There are WHERE clauses that do have a compact SEL_ARG-graph
 
247
      representation but get_mm_tree() and its callees will construct a
 
248
      graph of combinatorial size.
 
249
      Example:
 
250
        (keypart1 IN (1,2, ..., n1)) AND 
 
251
        (keypart2 IN (1,2, ..., n2)) AND 
 
252
        ...
 
253
        (keypartN IN (1,2, ..., n3))
 
254
 
 
255
    - There are WHERE clauses for which the minimal possible SEL_ARG graph
 
256
      representation will have combinatorial size.
 
257
      Example:
 
258
        By induction: Let's take any interval on some keypart in the middle:
 
259
 
 
260
           kp15=c0
 
261
        
 
262
        Then let's AND it with this interval 'structure' from preceding and
 
263
        following keyparts:
 
264
 
 
265
          (kp14=c1 AND kp16=c3) OR keypart14=c2) (*)
 
266
        
 
267
        We will obtain this SEL_ARG graph:
 
268
 
 
269
             kp14     $      kp15      $      kp16
 
270
                      $                $
 
271
         +---------+  $   +---------+  $   +---------+
 
272
         | kp14=c1 |--$-->| kp15=c0 |--$-->| kp16=c3 |
 
273
         +---------+  $   +---------+  $   +---------+
 
274
              |       $                $              
 
275
         +---------+  $   +---------+  $             
 
276
         | kp14=c2 |--$-->| kp15=c0 |  $             
 
277
         +---------+  $   +---------+  $             
 
278
                      $                $
 
279
                      
 
280
       Note that we had to duplicate "kp15=c0" and there was no way to avoid
 
281
       that. 
 
282
       The induction step: AND the obtained expression with another "wrapping"
 
283
       expression like (*).
 
284
       When the process ends because of the limit on max. number of keyparts 
 
285
       we'll have:
 
286
 
 
287
         WHERE clause length  is O(3*#max_keyparts)
 
288
         SEL_ARG graph size   is O(2^(#max_keyparts/2))
 
289
 
 
290
       (it is also possible to construct a case where instead of 2 in 2^n we
 
291
        have a bigger constant, e.g. 4, and get a graph with 4^(31/2)= 2^31
 
292
        nodes)
 
293
 
 
294
    We avoid consuming too much memory by setting a limit on the number of
 
295
    SEL_ARG object we can construct during one range analysis invocation.
 
296
*/
 
297
 
 
298
class SEL_ARG :public Sql_alloc
 
299
{
 
300
public:
 
301
  uint8_t min_flag,max_flag,maybe_flag;
 
302
  uint8_t part;                                 // Which key part
 
303
  uint8_t maybe_null;
 
304
  /* 
 
305
    Number of children of this element in the RB-tree, plus 1 for this
 
306
    element itself.
 
307
  */
 
308
  uint16_t elements;
 
309
  /*
 
310
    Valid only for elements which are RB-tree roots: Number of times this
 
311
    RB-tree is referred to (it is referred by SEL_ARG::next_key_part or by
 
312
    SEL_TREE::keys[i] or by a temporary SEL_ARG* variable)
 
313
  */
 
314
  ulong use_count;
 
315
 
 
316
  Field *field;
 
317
  unsigned char *min_value,*max_value;                  // Pointer to range
 
318
 
 
319
  /*
 
320
    eq_tree() requires that left == right == 0 if the type is MAYBE_KEY.
 
321
   */
 
322
  SEL_ARG *left,*right;   /* R-B tree children */
 
323
  SEL_ARG *next,*prev;    /* Links for bi-directional interval list */
 
324
  SEL_ARG *parent;        /* R-B tree parent */
 
325
  SEL_ARG *next_key_part; 
 
326
  enum leaf_color { BLACK,RED } color;
 
327
  enum Type { IMPOSSIBLE, MAYBE, MAYBE_KEY, KEY_RANGE } type;
 
328
 
 
329
  enum { MAX_SEL_ARGS = 16000 };
 
330
 
 
331
  SEL_ARG() {}
 
332
  SEL_ARG(SEL_ARG &);
 
333
  SEL_ARG(Field *,const unsigned char *, const unsigned char *);
 
334
  SEL_ARG(Field *field, uint8_t part, unsigned char *min_value, unsigned char *max_value,
 
335
          uint8_t min_flag, uint8_t max_flag, uint8_t maybe_flag);
 
336
  SEL_ARG(enum Type type_arg)
 
337
    :min_flag(0),elements(1),use_count(1),left(0),right(0),next_key_part(0),
 
338
    color(BLACK), type(type_arg)
 
339
  {}
 
340
  inline bool is_same(SEL_ARG *arg)
 
341
  {
 
342
    if (type != arg->type || part != arg->part)
 
343
      return 0;
 
344
    if (type != KEY_RANGE)
 
345
      return 1;
 
346
    return cmp_min_to_min(arg) == 0 && cmp_max_to_max(arg) == 0;
 
347
  }
 
348
  inline void merge_flags(SEL_ARG *arg) { maybe_flag|=arg->maybe_flag; }
 
349
  inline void maybe_smaller() { maybe_flag=1; }
 
350
  /* Return true iff it's a single-point null interval */
 
351
  inline bool is_null_interval() { return maybe_null && max_value[0] == 1; } 
 
352
  inline int cmp_min_to_min(SEL_ARG* arg)
 
353
  {
 
354
    return sel_cmp(field,min_value, arg->min_value, min_flag, arg->min_flag);
 
355
  }
 
356
  inline int cmp_min_to_max(SEL_ARG* arg)
 
357
  {
 
358
    return sel_cmp(field,min_value, arg->max_value, min_flag, arg->max_flag);
 
359
  }
 
360
  inline int cmp_max_to_max(SEL_ARG* arg)
 
361
  {
 
362
    return sel_cmp(field,max_value, arg->max_value, max_flag, arg->max_flag);
 
363
  }
 
364
  inline int cmp_max_to_min(SEL_ARG* arg)
 
365
  {
 
366
    return sel_cmp(field,max_value, arg->min_value, max_flag, arg->min_flag);
 
367
  }
 
368
  SEL_ARG *clone_and(SEL_ARG* arg)
 
369
  {                                             // Get overlapping range
 
370
    unsigned char *new_min,*new_max;
 
371
    uint8_t flag_min,flag_max;
 
372
    if (cmp_min_to_min(arg) >= 0)
 
373
    {
 
374
      new_min=min_value; flag_min=min_flag;
 
375
    }
 
376
    else
 
377
    {
 
378
      new_min=arg->min_value; flag_min=arg->min_flag; /* purecov: deadcode */
 
379
    }
 
380
    if (cmp_max_to_max(arg) <= 0)
 
381
    {
 
382
      new_max=max_value; flag_max=max_flag;
 
383
    }
 
384
    else
 
385
    {
 
386
      new_max=arg->max_value; flag_max=arg->max_flag;
 
387
    }
 
388
    return new SEL_ARG(field, part, new_min, new_max, flag_min, flag_max,
 
389
                       test(maybe_flag && arg->maybe_flag));
 
390
  }
 
391
  SEL_ARG *clone_first(SEL_ARG *arg)
 
392
  {                                             // min <= X < arg->min
 
393
    return new SEL_ARG(field,part, min_value, arg->min_value,
 
394
                       min_flag, arg->min_flag & NEAR_MIN ? 0 : NEAR_MAX,
 
395
                       maybe_flag | arg->maybe_flag);
 
396
  }
 
397
  SEL_ARG *clone_last(SEL_ARG *arg)
 
398
  {                                             // min <= X <= key_max
 
399
    return new SEL_ARG(field, part, min_value, arg->max_value,
 
400
                       min_flag, arg->max_flag, maybe_flag | arg->maybe_flag);
 
401
  }
 
402
  SEL_ARG *clone(RANGE_OPT_PARAM *param, SEL_ARG *new_parent, SEL_ARG **next);
 
403
 
 
404
  bool copy_min(SEL_ARG* arg)
 
405
  {                                             // Get overlapping range
 
406
    if (cmp_min_to_min(arg) > 0)
 
407
    {
 
408
      min_value=arg->min_value; min_flag=arg->min_flag;
 
409
      if ((max_flag & (NO_MAX_RANGE | NO_MIN_RANGE)) ==
 
410
          (NO_MAX_RANGE | NO_MIN_RANGE))
 
411
        return 1;                               // Full range
 
412
    }
 
413
    maybe_flag|=arg->maybe_flag;
 
414
    return 0;
 
415
  }
 
416
  bool copy_max(SEL_ARG* arg)
 
417
  {                                             // Get overlapping range
 
418
    if (cmp_max_to_max(arg) <= 0)
 
419
    {
 
420
      max_value=arg->max_value; max_flag=arg->max_flag;
 
421
      if ((max_flag & (NO_MAX_RANGE | NO_MIN_RANGE)) ==
 
422
          (NO_MAX_RANGE | NO_MIN_RANGE))
 
423
        return 1;                               // Full range
 
424
    }
 
425
    maybe_flag|=arg->maybe_flag;
 
426
    return 0;
 
427
  }
 
428
 
 
429
  void copy_min_to_min(SEL_ARG *arg)
 
430
  {
 
431
    min_value=arg->min_value; min_flag=arg->min_flag;
 
432
  }
 
433
  void copy_min_to_max(SEL_ARG *arg)
 
434
  {
 
435
    max_value=arg->min_value;
 
436
    max_flag=arg->min_flag & NEAR_MIN ? 0 : NEAR_MAX;
 
437
  }
 
438
  void copy_max_to_min(SEL_ARG *arg)
 
439
  {
 
440
    min_value=arg->max_value;
 
441
    min_flag=arg->max_flag & NEAR_MAX ? 0 : NEAR_MIN;
 
442
  }
 
443
  /* returns a number of keypart values (0 or 1) appended to the key buffer */
 
444
  int store_min(uint32_t length, unsigned char **min_key,uint32_t min_key_flag)
 
445
  {
 
446
    /* "(kp1 > c1) AND (kp2 OP c2) AND ..." -> (kp1 > c1) */
 
447
    if ((!(min_flag & NO_MIN_RANGE) &&
 
448
        !(min_key_flag & (NO_MIN_RANGE | NEAR_MIN))))
 
449
    {
 
450
      if (maybe_null && *min_value)
 
451
      {
 
452
        **min_key=1;
 
453
        memset(*min_key+1, 0, length-1);
 
454
      }
 
455
      else
 
456
        memcpy(*min_key,min_value,length);
 
457
      (*min_key)+= length;
 
458
      return 1;
 
459
    }
 
460
    return 0;
 
461
  }
 
462
  /* returns a number of keypart values (0 or 1) appended to the key buffer */
 
463
  int store_max(uint32_t length, unsigned char **max_key, uint32_t max_key_flag)
 
464
  {
 
465
    if (!(max_flag & NO_MAX_RANGE) &&
 
466
        !(max_key_flag & (NO_MAX_RANGE | NEAR_MAX)))
 
467
    {
 
468
      if (maybe_null && *max_value)
 
469
      {
 
470
        **max_key=1;
 
471
        memset(*max_key+1, 0, length-1);
 
472
      }
 
473
      else
 
474
        memcpy(*max_key,max_value,length);
 
475
      (*max_key)+= length;
 
476
      return 1;
 
477
    }
 
478
    return 0;
 
479
  }
 
480
 
 
481
  /* returns a number of keypart values appended to the key buffer */
 
482
  int store_min_key(KEY_PART *key, unsigned char **range_key, uint32_t *range_key_flag)
 
483
  {
 
484
    SEL_ARG *key_tree= first();
 
485
    uint32_t res= key_tree->store_min(key[key_tree->part].store_length,
 
486
                                  range_key, *range_key_flag);
 
487
    *range_key_flag|= key_tree->min_flag;
 
488
    
 
489
    if (key_tree->next_key_part &&
 
490
        key_tree->next_key_part->part == key_tree->part+1 &&
 
491
        !(*range_key_flag & (NO_MIN_RANGE | NEAR_MIN)) &&
 
492
        key_tree->next_key_part->type == SEL_ARG::KEY_RANGE)
 
493
      res+= key_tree->next_key_part->store_min_key(key, range_key,
 
494
                                                   range_key_flag);
 
495
    return res;
 
496
  }
 
497
 
 
498
  /* returns a number of keypart values appended to the key buffer */
 
499
  int store_max_key(KEY_PART *key, unsigned char **range_key, uint32_t *range_key_flag)
 
500
  {
 
501
    SEL_ARG *key_tree= last();
 
502
    uint32_t res=key_tree->store_max(key[key_tree->part].store_length,
 
503
                                 range_key, *range_key_flag);
 
504
    (*range_key_flag)|= key_tree->max_flag;
 
505
    if (key_tree->next_key_part &&
 
506
        key_tree->next_key_part->part == key_tree->part+1 &&
 
507
        !(*range_key_flag & (NO_MAX_RANGE | NEAR_MAX)) &&
 
508
        key_tree->next_key_part->type == SEL_ARG::KEY_RANGE)
 
509
      res+= key_tree->next_key_part->store_max_key(key, range_key,
 
510
                                                   range_key_flag);
 
511
    return res;
 
512
  }
 
513
 
 
514
  SEL_ARG *insert(SEL_ARG *key);
 
515
  SEL_ARG *tree_delete(SEL_ARG *key);
 
516
  SEL_ARG *find_range(SEL_ARG *key);
 
517
  SEL_ARG *rb_insert(SEL_ARG *leaf);
 
518
  friend SEL_ARG *rb_delete_fixup(SEL_ARG *root,SEL_ARG *key, SEL_ARG *par);
 
519
#ifdef EXTRA_DEBUG
 
520
  friend int test_rb_tree(SEL_ARG *element,SEL_ARG *parent);
 
521
  void test_use_count(SEL_ARG *root);
 
522
#endif
 
523
  SEL_ARG *first();
 
524
  SEL_ARG *last();
 
525
  void make_root();
 
526
  inline bool simple_key()
 
527
  {
 
528
    return !next_key_part && elements == 1;
 
529
  }
 
530
  void increment_use_count(long count)
 
531
  {
 
532
    if (next_key_part)
 
533
    {
 
534
      next_key_part->use_count+=count;
 
535
      count*= (next_key_part->use_count-count);
 
536
      for (SEL_ARG *pos=next_key_part->first(); pos ; pos=pos->next)
 
537
        if (pos->next_key_part)
 
538
          pos->increment_use_count(count);
 
539
    }
 
540
  }
 
541
  void free_tree()
 
542
  {
 
543
    for (SEL_ARG *pos=first(); pos ; pos=pos->next)
 
544
      if (pos->next_key_part)
 
545
      {
 
546
        pos->next_key_part->use_count--;
 
547
        pos->next_key_part->free_tree();
 
548
      }
 
549
  }
 
550
 
 
551
  inline SEL_ARG **parent_ptr()
 
552
  {
 
553
    return parent->left == this ? &parent->left : &parent->right;
 
554
  }
 
555
 
 
556
 
 
557
  /*
 
558
    Check if this SEL_ARG object represents a single-point interval
 
559
 
 
560
    SYNOPSIS
 
561
      is_singlepoint()
 
562
    
 
563
    DESCRIPTION
 
564
      Check if this SEL_ARG object (not tree) represents a single-point
 
565
      interval, i.e. if it represents a "keypart = const" or 
 
566
      "keypart IS NULL".
 
567
 
 
568
    RETURN
 
569
      true   This SEL_ARG object represents a singlepoint interval
 
570
      false  Otherwise
 
571
  */
 
572
 
 
573
  bool is_singlepoint()
 
574
  {
 
575
    /* 
 
576
      Check for NEAR_MIN ("strictly less") and NO_MIN_RANGE (-inf < field) 
 
577
      flags, and the same for right edge.
 
578
    */
 
579
    if (min_flag || max_flag)
 
580
      return false;
 
581
    unsigned char *min_val= min_value;
 
582
    unsigned char *max_val= max_value;
 
583
 
 
584
    if (maybe_null)
 
585
    {
 
586
      /* First byte is a NULL value indicator */
 
587
      if (*min_val != *max_val)
 
588
        return false;
 
589
 
 
590
      if (*min_val)
 
591
        return true; /* This "x IS NULL" */
 
592
      min_val++;
 
593
      max_val++;
 
594
    }
 
595
    return !field->key_cmp(min_val, max_val);
 
596
  }
 
597
  SEL_ARG *clone_tree(RANGE_OPT_PARAM *param);
 
598
};
 
599
 
 
600
class SEL_IMERGE;
 
601
 
 
602
 
 
603
class SEL_TREE :public Sql_alloc
 
604
{
 
605
public:
 
606
  /*
 
607
    Starting an effort to document this field:
 
608
    (for some i, keys[i]->type == SEL_ARG::IMPOSSIBLE) => 
 
609
       (type == SEL_TREE::IMPOSSIBLE)
 
610
  */
 
611
  enum Type { IMPOSSIBLE, ALWAYS, MAYBE, KEY, KEY_SMALLER } type;
 
612
  SEL_TREE(enum Type type_arg) :type(type_arg) {}
 
613
  SEL_TREE() :type(KEY)
 
614
  {
 
615
    keys_map.clear_all();
 
616
    memset(keys, 0, sizeof(keys));
 
617
  }
 
618
  /*
 
619
    Note: there may exist SEL_TREE objects with sel_tree->type=KEY and
 
620
    keys[i]=0 for all i. (SergeyP: it is not clear whether there is any
 
621
    merit in range analyzer functions (e.g. get_mm_parts) returning a
 
622
    pointer to such SEL_TREE instead of NULL)
 
623
  */
 
624
  SEL_ARG *keys[MAX_KEY];
 
625
  key_map keys_map;        /* bitmask of non-NULL elements in keys */
 
626
 
 
627
  /*
 
628
    Possible ways to read rows using index_merge. The list is non-empty only
 
629
    if type==KEY. Currently can be non empty only if keys_map.is_clear_all().
 
630
  */
 
631
  List<SEL_IMERGE> merges;
 
632
 
 
633
  /* The members below are filled/used only after get_mm_tree is done */
 
634
  key_map ror_scans_map;   /* bitmask of ROR scan-able elements in keys */
 
635
  uint32_t    n_ror_scans;     /* number of set bits in ror_scans_map */
 
636
 
 
637
  struct st_ror_scan_info **ror_scans;     /* list of ROR key scans */
 
638
  struct st_ror_scan_info **ror_scans_end; /* last ROR scan */
 
639
  /* Note that #records for each key scan is stored in table->quick_rows */
 
640
};
 
641
 
 
642
class RANGE_OPT_PARAM
 
643
{
 
644
public:
 
645
  Session       *session;   /* Current thread handle */
 
646
  Table *table; /* Table being analyzed */
 
647
  COND *cond;   /* Used inside get_mm_tree(). */
 
648
  table_map prev_tables;
 
649
  table_map read_tables;
 
650
  table_map current_table; /* Bit of the table being analyzed */
 
651
 
 
652
  /* Array of parts of all keys for which range analysis is performed */
 
653
  KEY_PART *key_parts;
 
654
  KEY_PART *key_parts_end;
 
655
  MEM_ROOT *mem_root; /* Memory that will be freed when range analysis completes */
 
656
  MEM_ROOT *old_root; /* Memory that will last until the query end */
 
657
  /*
 
658
    Number of indexes used in range analysis (In SEL_TREE::keys only first
 
659
    #keys elements are not empty)
 
660
  */
 
661
  uint32_t keys;
 
662
  
 
663
  /* 
 
664
    If true, the index descriptions describe real indexes (and it is ok to
 
665
    call field->optimize_range(real_keynr[...], ...).
 
666
    Otherwise index description describes fake indexes.
 
667
  */
 
668
  bool using_real_indexes;
 
669
  
 
670
  bool remove_jump_scans;
 
671
  
 
672
  /*
 
673
    used_key_no -> table_key_no translation table. Only makes sense if
 
674
    using_real_indexes==true
 
675
  */
 
676
  uint32_t real_keynr[MAX_KEY];
 
677
  /* Number of SEL_ARG objects allocated by SEL_ARG::clone_tree operations */
 
678
  uint32_t alloced_sel_args; 
 
679
  bool force_default_mrr;
 
680
};
 
681
 
 
682
class PARAM : public RANGE_OPT_PARAM
 
683
{
 
684
public:
 
685
  KEY_PART *key[MAX_KEY]; /* First key parts of keys used in the query */
 
686
  int64_t baseflag;
 
687
  uint32_t max_key_part;
 
688
  /* Number of ranges in the last checked tree->key */
 
689
  uint32_t range_count;
 
690
  unsigned char min_key[MAX_KEY_LENGTH+MAX_FIELD_WIDTH],
 
691
    max_key[MAX_KEY_LENGTH+MAX_FIELD_WIDTH];
 
692
  bool quick;                           // Don't calulate possible keys
 
693
 
 
694
  uint32_t fields_bitmap_size;
 
695
  MY_BITMAP needed_fields;    /* bitmask of fields needed by the query */
 
696
  MY_BITMAP tmp_covered_fields;
 
697
 
 
698
  key_map *needed_reg;        /* ptr to SQL_SELECT::needed_reg */
 
699
 
 
700
  uint32_t *imerge_cost_buff;     /* buffer for index_merge cost estimates */
 
701
  uint32_t imerge_cost_buff_size; /* size of the buffer */
 
702
 
 
703
  /* true if last checked tree->key can be used for ROR-scan */
 
704
  bool is_ror_scan;
 
705
  /* Number of ranges in the last checked tree->key */
 
706
  uint32_t n_ranges;
 
707
};
 
708
 
 
709
class TABLE_READ_PLAN;
 
710
  class TRP_RANGE;
 
711
  class TRP_ROR_INTERSECT;
 
712
  class TRP_ROR_UNION;
 
713
  class TRP_ROR_INDEX_MERGE;
 
714
  class TRP_GROUP_MIN_MAX;
 
715
 
 
716
struct st_ror_scan_info;
 
717
 
 
718
static SEL_TREE * get_mm_parts(RANGE_OPT_PARAM *param,COND *cond_func,Field *field,
 
719
                               Item_func::Functype type,Item *value,
 
720
                               Item_result cmp_type);
 
721
static SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *param,COND *cond_func,Field *field,
 
722
                            KEY_PART *key_part,
 
723
                            Item_func::Functype type,Item *value);
 
724
static SEL_TREE *get_mm_tree(RANGE_OPT_PARAM *param,COND *cond);
 
725
 
 
726
static bool is_key_scan_ror(PARAM *param, uint32_t keynr, uint8_t nparts);
 
727
static ha_rows check_quick_select(PARAM *param, uint32_t idx, bool index_only,
 
728
                                  SEL_ARG *tree, bool update_tbl_stats, 
 
729
                                  uint32_t *mrr_flags, uint32_t *bufsize,
 
730
                                  COST_VECT *cost);
 
731
                                  //bool update_tbl_stats);
 
732
/*static ha_rows check_quick_keys(PARAM *param,uint32_t index,SEL_ARG *key_tree,
 
733
                                unsigned char *min_key, uint32_t min_key_flag, int,
 
734
                                unsigned char *max_key, uint32_t max_key_flag, int);
 
735
*/
 
736
 
 
737
QUICK_RANGE_SELECT *get_quick_select(PARAM *param,uint32_t index,
 
738
                                     SEL_ARG *key_tree, uint32_t mrr_flags, 
 
739
                                     uint32_t mrr_buf_size, MEM_ROOT *alloc);
 
740
static TRP_RANGE *get_key_scans_params(PARAM *param, SEL_TREE *tree,
 
741
                                       bool index_read_must_be_used,
 
742
                                       bool update_tbl_stats,
 
743
                                       double read_time);
 
744
static
 
745
TRP_ROR_INTERSECT *get_best_ror_intersect(const PARAM *param, SEL_TREE *tree,
 
746
                                          double read_time,
 
747
                                          bool *are_all_covering);
 
748
static
 
749
TRP_ROR_INTERSECT *get_best_covering_ror_intersect(PARAM *param,
 
750
                                                   SEL_TREE *tree,
 
751
                                                   double read_time);
 
752
static
 
753
TABLE_READ_PLAN *get_best_disjunct_quick(PARAM *param, SEL_IMERGE *imerge,
 
754
                                         double read_time);
 
755
static
 
756
TRP_GROUP_MIN_MAX *get_best_group_min_max(PARAM *param, SEL_TREE *tree);
 
757
 
 
758
static void print_sel_tree(PARAM *param, SEL_TREE *tree, key_map *tree_map,
 
759
                           const char *msg);
 
760
static void print_ror_scans_arr(Table *table, const char *msg,
 
761
                                struct st_ror_scan_info **start,
 
762
                                struct st_ror_scan_info **end);
 
763
 
 
764
static SEL_TREE *tree_and(RANGE_OPT_PARAM *param,SEL_TREE *tree1,SEL_TREE *tree2);
 
765
static SEL_TREE *tree_or(RANGE_OPT_PARAM *param,SEL_TREE *tree1,SEL_TREE *tree2);
 
766
static SEL_ARG *sel_add(SEL_ARG *key1,SEL_ARG *key2);
 
767
static SEL_ARG *key_or(RANGE_OPT_PARAM *param, SEL_ARG *key1, SEL_ARG *key2);
 
768
static SEL_ARG *key_and(RANGE_OPT_PARAM *param, SEL_ARG *key1, SEL_ARG *key2,
 
769
                        uint32_t clone_flag);
 
770
static bool get_range(SEL_ARG **e1,SEL_ARG **e2,SEL_ARG *root1);
 
771
bool get_quick_keys(PARAM *param,QUICK_RANGE_SELECT *quick,KEY_PART *key,
 
772
                    SEL_ARG *key_tree, unsigned char *min_key,uint32_t min_key_flag,
 
773
                    unsigned char *max_key,uint32_t max_key_flag);
 
774
static bool eq_tree(SEL_ARG* a,SEL_ARG *b);
 
775
 
 
776
static SEL_ARG null_element(SEL_ARG::IMPOSSIBLE);
 
777
static bool null_part_in_key(KEY_PART *key_part, const unsigned char *key,
307
778
                             uint32_t length);
308
 
 
309
 
bool sel_trees_can_be_ored(optimizer::SEL_TREE *tree1, 
310
 
                           optimizer::SEL_TREE *tree2, 
311
 
                           optimizer::RangeParameter *param);
312
 
 
313
 
 
314
 
 
315
 
 
 
779
bool sel_trees_can_be_ored(SEL_TREE *tree1, SEL_TREE *tree2, RANGE_OPT_PARAM* param);
 
780
 
 
781
 
 
782
/*
 
783
  SEL_IMERGE is a list of possible ways to do index merge, i.e. it is
 
784
  a condition in the following form:
 
785
   (t_1||t_2||...||t_N) && (next)
 
786
 
 
787
  where all t_i are SEL_TREEs, next is another SEL_IMERGE and no pair
 
788
  (t_i,t_j) contains SEL_ARGS for the same index.
 
789
 
 
790
  SEL_TREE contained in SEL_IMERGE always has merges=NULL.
 
791
 
 
792
  This class relies on memory manager to do the cleanup.
 
793
*/
 
794
 
 
795
class SEL_IMERGE : public Sql_alloc
 
796
{
 
797
  enum { PREALLOCED_TREES= 10};
 
798
public:
 
799
  SEL_TREE *trees_prealloced[PREALLOCED_TREES];
 
800
  SEL_TREE **trees;             /* trees used to do index_merge   */
 
801
  SEL_TREE **trees_next;        /* last of these trees            */
 
802
  SEL_TREE **trees_end;         /* end of allocated space         */
 
803
 
 
804
  SEL_ARG  ***best_keys;        /* best keys to read in SEL_TREEs */
 
805
 
 
806
  SEL_IMERGE() :
 
807
    trees(&trees_prealloced[0]),
 
808
    trees_next(trees),
 
809
    trees_end(trees + PREALLOCED_TREES)
 
810
  {}
 
811
  int or_sel_tree(RANGE_OPT_PARAM *param, SEL_TREE *tree);
 
812
  int or_sel_tree_with_checks(RANGE_OPT_PARAM *param, SEL_TREE *new_tree);
 
813
  int or_sel_imerge_with_checks(RANGE_OPT_PARAM *param, SEL_IMERGE* imerge);
 
814
};
 
815
 
 
816
 
 
817
/*
 
818
  Add SEL_TREE to this index_merge without any checks,
 
819
 
 
820
  NOTES
 
821
    This function implements the following:
 
822
      (x_1||...||x_N) || t = (x_1||...||x_N||t), where x_i, t are SEL_TREEs
 
823
 
 
824
  RETURN
 
825
     0 - OK
 
826
    -1 - Out of memory.
 
827
*/
 
828
 
 
829
int SEL_IMERGE::or_sel_tree(RANGE_OPT_PARAM *param, SEL_TREE *tree)
 
830
{
 
831
  if (trees_next == trees_end)
 
832
  {
 
833
    const int realloc_ratio= 2;         /* Double size for next round */
 
834
    uint32_t old_elements= (trees_end - trees);
 
835
    uint32_t old_size= sizeof(SEL_TREE**) * old_elements;
 
836
    uint32_t new_size= old_size * realloc_ratio;
 
837
    SEL_TREE **new_trees;
 
838
    if (!(new_trees= (SEL_TREE**)alloc_root(param->mem_root, new_size)))
 
839
      return -1;
 
840
    memcpy(new_trees, trees, old_size);
 
841
    trees=      new_trees;
 
842
    trees_next= trees + old_elements;
 
843
    trees_end=  trees + old_elements * realloc_ratio;
 
844
  }
 
845
  *(trees_next++)= tree;
 
846
  return 0;
 
847
}
 
848
 
 
849
 
 
850
/*
 
851
  Perform OR operation on this SEL_IMERGE and supplied SEL_TREE new_tree,
 
852
  combining new_tree with one of the trees in this SEL_IMERGE if they both
 
853
  have SEL_ARGs for the same key.
 
854
 
 
855
  SYNOPSIS
 
856
    or_sel_tree_with_checks()
 
857
      param    PARAM from SQL_SELECT::test_quick_select
 
858
      new_tree SEL_TREE with type KEY or KEY_SMALLER.
 
859
 
 
860
  NOTES
 
861
    This does the following:
 
862
    (t_1||...||t_k)||new_tree =
 
863
     either
 
864
       = (t_1||...||t_k||new_tree)
 
865
     or
 
866
       = (t_1||....||(t_j|| new_tree)||...||t_k),
 
867
 
 
868
     where t_i, y are SEL_TREEs.
 
869
    new_tree is combined with the first t_j it has a SEL_ARG on common
 
870
    key with. As a consequence of this, choice of keys to do index_merge
 
871
    read may depend on the order of conditions in WHERE part of the query.
 
872
 
 
873
  RETURN
 
874
    0  OK
 
875
    1  One of the trees was combined with new_tree to SEL_TREE::ALWAYS,
 
876
       and (*this) should be discarded.
 
877
   -1  An error occurred.
 
878
*/
 
879
 
 
880
int SEL_IMERGE::or_sel_tree_with_checks(RANGE_OPT_PARAM *param, SEL_TREE *new_tree)
 
881
{
 
882
  for (SEL_TREE** tree = trees;
 
883
       tree != trees_next;
 
884
       tree++)
 
885
  {
 
886
    if (sel_trees_can_be_ored(*tree, new_tree, param))
 
887
    {
 
888
      *tree = tree_or(param, *tree, new_tree);
 
889
      if (!*tree)
 
890
        return 1;
 
891
      if (((*tree)->type == SEL_TREE::MAYBE) ||
 
892
          ((*tree)->type == SEL_TREE::ALWAYS))
 
893
        return 1;
 
894
      /* SEL_TREE::IMPOSSIBLE is impossible here */
 
895
      return 0;
 
896
    }
 
897
  }
 
898
 
 
899
  /* New tree cannot be combined with any of existing trees. */
 
900
  return or_sel_tree(param, new_tree);
 
901
}
 
902
 
 
903
 
 
904
/*
 
905
  Perform OR operation on this index_merge and supplied index_merge list.
 
906
 
 
907
  RETURN
 
908
    0 - OK
 
909
    1 - One of conditions in result is always true and this SEL_IMERGE
 
910
        should be discarded.
 
911
   -1 - An error occurred
 
912
*/
 
913
 
 
914
int SEL_IMERGE::or_sel_imerge_with_checks(RANGE_OPT_PARAM *param, SEL_IMERGE* imerge)
 
915
{
 
916
  for (SEL_TREE** tree= imerge->trees;
 
917
       tree != imerge->trees_next;
 
918
       tree++)
 
919
  {
 
920
    if (or_sel_tree_with_checks(param, *tree))
 
921
      return 1;
 
922
  }
 
923
  return 0;
 
924
}
316
925
 
317
926
 
318
927
/*
319
928
  Perform AND operation on two index_merge lists and store result in *im1.
320
929
*/
321
930
 
322
 
inline void imerge_list_and_list(List<optimizer::SEL_IMERGE> *im1, List<optimizer::SEL_IMERGE> *im2)
 
931
inline void imerge_list_and_list(List<SEL_IMERGE> *im1, List<SEL_IMERGE> *im2)
323
932
{
324
933
  im1->concat(im2);
325
934
}
326
935
 
327
936
 
 
937
/*
 
938
  Perform OR operation on 2 index_merge lists, storing result in first list.
 
939
 
 
940
  NOTES
 
941
    The following conversion is implemented:
 
942
     (a_1 &&...&& a_N)||(b_1 &&...&& b_K) = AND_i,j(a_i || b_j) =>
 
943
      => (a_1||b_1).
 
944
 
 
945
    i.e. all conjuncts except the first one are currently dropped.
 
946
    This is done to avoid producing N*K ways to do index_merge.
 
947
 
 
948
    If (a_1||b_1) produce a condition that is always true, NULL is returned
 
949
    and index_merge is discarded (while it is actually possible to try
 
950
    harder).
 
951
 
 
952
    As a consequence of this, choice of keys to do index_merge read may depend
 
953
    on the order of conditions in WHERE part of the query.
 
954
 
 
955
  RETURN
 
956
    0     OK, result is stored in *im1
 
957
    other Error, both passed lists are unusable
 
958
*/
 
959
 
 
960
int imerge_list_or_list(RANGE_OPT_PARAM *param,
 
961
                        List<SEL_IMERGE> *im1,
 
962
                        List<SEL_IMERGE> *im2)
 
963
{
 
964
  SEL_IMERGE *imerge= im1->head();
 
965
  im1->empty();
 
966
  im1->push_back(imerge);
 
967
 
 
968
  return imerge->or_sel_imerge_with_checks(param, im2->head());
 
969
}
 
970
 
 
971
 
 
972
/*
 
973
  Perform OR operation on index_merge list and key tree.
 
974
 
 
975
  RETURN
 
976
    0     OK, result is stored in *im1.
 
977
    other Error
 
978
*/
 
979
 
 
980
int imerge_list_or_tree(RANGE_OPT_PARAM *param,
 
981
                        List<SEL_IMERGE> *im1,
 
982
                        SEL_TREE *tree)
 
983
{
 
984
  SEL_IMERGE *imerge;
 
985
  List_iterator<SEL_IMERGE> it(*im1);
 
986
  while ((imerge= it++))
 
987
  {
 
988
    if (imerge->or_sel_tree_with_checks(param, tree))
 
989
      it.remove();
 
990
  }
 
991
  return im1->is_empty();
 
992
}
 
993
 
 
994
 
328
995
/***************************************************************************
329
 
** Basic functions for SqlSelect and QuickRangeSelect
 
996
** Basic functions for SQL_SELECT and QUICK_RANGE_SELECT
330
997
***************************************************************************/
331
998
 
332
999
        /* make a select from mysql info
335
1002
           1 = Got some error (out of memory?)
336
1003
           */
337
1004
 
338
 
optimizer::SqlSelect *optimizer::make_select(Table *head,
339
 
                                             table_map const_tables,
340
 
                                             table_map read_tables,
341
 
                                             COND *conds,
342
 
                                             bool allow_null_cond,
343
 
                                             int *error)
 
1005
SQL_SELECT *make_select(Table *head, table_map const_tables,
 
1006
                        table_map read_tables, COND *conds,
 
1007
                        bool allow_null_cond,
 
1008
                        int *error)
344
1009
{
345
 
  optimizer::SqlSelect *select= NULL;
346
 
 
347
 
  *error= 0;
348
 
 
349
 
  if (! conds && ! allow_null_cond)
350
 
  {
351
 
    return 0;
352
 
  }
353
 
  if (! (select= new optimizer::SqlSelect()))
 
1010
  SQL_SELECT *select;
 
1011
 
 
1012
  *error=0;
 
1013
 
 
1014
  if (!conds && !allow_null_cond)
 
1015
    return(0);
 
1016
  if (!(select= new SQL_SELECT))
354
1017
  {
355
1018
    *error= 1;                  // out of memory
356
 
    return 0;
 
1019
    return(0);          /* purecov: inspected */
357
1020
  }
358
1021
  select->read_tables=read_tables;
359
1022
  select->const_tables=const_tables;
362
1025
 
363
1026
  if (head->sort.io_cache)
364
1027
  {
365
 
    memcpy(select->file, head->sort.io_cache, sizeof(internal::IO_CACHE));
366
 
    select->records=(ha_rows) (select->file->end_of_file/
367
 
                               head->cursor->ref_length);
368
 
    delete head->sort.io_cache;
 
1028
    select->file= *head->sort.io_cache;
 
1029
    select->records=(ha_rows) (select->file.end_of_file/
 
1030
                               head->file->ref_length);
 
1031
    free(head->sort.io_cache);
369
1032
    head->sort.io_cache=0;
370
1033
  }
371
1034
  return(select);
372
1035
}
373
1036
 
374
1037
 
375
 
optimizer::SqlSelect::SqlSelect() 
376
 
  :
377
 
    quick(NULL),
378
 
    cond(NULL),
379
 
    file(static_cast<internal::IO_CACHE *>(memory::sql_calloc(sizeof(internal::IO_CACHE)))),
380
 
    free_cond(false)
 
1038
SQL_SELECT::SQL_SELECT() :quick(0),cond(0),free_cond(0)
381
1039
{
382
 
  quick_keys.reset();
383
 
  needed_reg.reset();
384
 
  my_b_clear(file);
 
1040
  quick_keys.clear_all(); needed_reg.clear_all();
 
1041
  my_b_clear(&file);
385
1042
}
386
1043
 
387
1044
 
388
 
void optimizer::SqlSelect::cleanup()
 
1045
void SQL_SELECT::cleanup()
389
1046
{
390
 
  if (quick)
391
 
  {
392
 
    delete quick;
393
 
    quick= NULL;
394
 
  }
395
 
 
 
1047
  delete quick;
 
1048
  quick= 0;
396
1049
  if (free_cond)
397
1050
  {
398
 
    free_cond= 0;
 
1051
    free_cond=0;
399
1052
    delete cond;
400
1053
    cond= 0;
401
1054
  }
402
 
  file->close_cached_file();
 
1055
  close_cached_file(&file);
403
1056
}
404
1057
 
405
1058
 
406
 
optimizer::SqlSelect::~SqlSelect()
 
1059
SQL_SELECT::~SQL_SELECT()
407
1060
{
408
1061
  cleanup();
409
1062
}
410
1063
 
411
 
 
412
 
bool optimizer::SqlSelect::check_quick(Session *session, 
413
 
                                       bool force_quick_range,
414
 
                                       ha_rows limit)
415
 
{
416
 
  key_map tmp;
417
 
  tmp.set();
418
 
  return (test_quick_select(session, 
419
 
                           tmp, 
420
 
                           0, 
421
 
                           limit,
422
 
                           force_quick_range, 
423
 
                           false) < 0);
424
 
}
425
 
 
426
 
 
427
 
bool optimizer::SqlSelect::skip_record()
428
 
{
429
 
  return (cond ? cond->val_int() == 0 : 0);
430
 
}
431
 
 
432
 
 
433
 
optimizer::QuickSelectInterface::QuickSelectInterface()
434
 
  :
435
 
    max_used_key_length(0),
436
 
    used_key_parts(0)
437
 
{}
 
1064
QUICK_SELECT_I::QUICK_SELECT_I()
 
1065
  :max_used_key_length(0),
 
1066
   used_key_parts(0)
 
1067
{}
 
1068
 
 
1069
QUICK_RANGE_SELECT::QUICK_RANGE_SELECT(Session *session, Table *table, uint32_t key_nr,
 
1070
                                       bool no_alloc, MEM_ROOT *parent_alloc,
 
1071
                                       bool *create_error)
 
1072
  :free_file(0),cur_range(NULL),last_range(0),dont_free(0)
 
1073
{
 
1074
  my_bitmap_map *bitmap;
 
1075
 
 
1076
  in_ror_merged_scan= 0;
 
1077
  sorted= 0;
 
1078
  index= key_nr;
 
1079
  head=  table;
 
1080
  key_part_info= head->key_info[index].key_part;
 
1081
  my_init_dynamic_array(&ranges, sizeof(QUICK_RANGE*), 16, 16);
 
1082
 
 
1083
  /* 'session' is not accessible in QUICK_RANGE_SELECT::reset(). */
 
1084
  mrr_buf_size= session->variables.read_rnd_buff_size;
 
1085
  mrr_buf_desc= NULL;
 
1086
 
 
1087
  if (!no_alloc && !parent_alloc)
 
1088
  {
 
1089
    // Allocates everything through the internal memroot
 
1090
    init_sql_alloc(&alloc, session->variables.range_alloc_block_size, 0);
 
1091
    session->mem_root= &alloc;
 
1092
  }
 
1093
  else
 
1094
    memset(&alloc, 0, sizeof(alloc));
 
1095
  file= head->file;
 
1096
  record= head->record[0];
 
1097
  save_read_set= head->read_set;
 
1098
  save_write_set= head->write_set;
 
1099
 
 
1100
  /* Allocate a bitmap for used columns (Q: why not on MEM_ROOT?) */
 
1101
  if (!(bitmap= (my_bitmap_map*) my_malloc(head->s->column_bitmap_size,
 
1102
                                           MYF(MY_WME))))
 
1103
  {
 
1104
    column_bitmap.bitmap= 0;
 
1105
    *create_error= 1;
 
1106
  }
 
1107
  else
 
1108
    bitmap_init(&column_bitmap, bitmap, head->s->fields, false);
 
1109
  return;
 
1110
}
 
1111
 
 
1112
 
 
1113
int QUICK_RANGE_SELECT::init()
 
1114
{
 
1115
  if (file->inited != handler::NONE)
 
1116
    file->ha_index_or_rnd_end();
 
1117
  return(file->ha_index_init(index, 1));
 
1118
}
 
1119
 
 
1120
 
 
1121
void QUICK_RANGE_SELECT::range_end()
 
1122
{
 
1123
  if (file->inited != handler::NONE)
 
1124
    file->ha_index_or_rnd_end();
 
1125
}
 
1126
 
 
1127
 
 
1128
QUICK_RANGE_SELECT::~QUICK_RANGE_SELECT()
 
1129
{
 
1130
  if (!dont_free)
 
1131
  {
 
1132
    /* file is NULL for CPK scan on covering ROR-intersection */
 
1133
    if (file) 
 
1134
    {
 
1135
      range_end();
 
1136
      if (head->key_read)
 
1137
      {
 
1138
        head->key_read= 0;
 
1139
        file->extra(HA_EXTRA_NO_KEYREAD);
 
1140
      }
 
1141
      if (free_file)
 
1142
      {
 
1143
        file->ha_external_lock(current_session, F_UNLCK);
 
1144
        file->close();
 
1145
        delete file;
 
1146
      }
 
1147
    }
 
1148
    delete_dynamic(&ranges); /* ranges are allocated in alloc */
 
1149
    free_root(&alloc,MYF(0));
 
1150
    free((char*) column_bitmap.bitmap);
 
1151
  }
 
1152
  head->column_bitmaps_set(save_read_set, save_write_set);
 
1153
  if (mrr_buf_desc)
 
1154
    free(mrr_buf_desc);
 
1155
  return;
 
1156
}
 
1157
 
 
1158
 
 
1159
QUICK_INDEX_MERGE_SELECT::QUICK_INDEX_MERGE_SELECT(Session *session_param,
 
1160
                                                   Table *table)
 
1161
  :pk_quick_select(NULL), session(session_param)
 
1162
{
 
1163
  index= MAX_KEY;
 
1164
  head= table;
 
1165
  memset(&read_record, 0, sizeof(read_record));
 
1166
  init_sql_alloc(&alloc, session->variables.range_alloc_block_size, 0);
 
1167
  return;
 
1168
}
 
1169
 
 
1170
int QUICK_INDEX_MERGE_SELECT::init()
 
1171
{
 
1172
  return(0);
 
1173
}
 
1174
 
 
1175
int QUICK_INDEX_MERGE_SELECT::reset()
 
1176
{
 
1177
  return(read_keys_and_merge());
 
1178
}
 
1179
 
 
1180
bool
 
1181
QUICK_INDEX_MERGE_SELECT::push_quick_back(QUICK_RANGE_SELECT *quick_sel_range)
 
1182
{
 
1183
  /*
 
1184
    Save quick_select that does scan on clustered primary key as it will be
 
1185
    processed separately.
 
1186
  */
 
1187
  if (head->file->primary_key_is_clustered() &&
 
1188
      quick_sel_range->index == head->s->primary_key)
 
1189
    pk_quick_select= quick_sel_range;
 
1190
  else
 
1191
    return quick_selects.push_back(quick_sel_range);
 
1192
  return 0;
 
1193
}
 
1194
 
 
1195
QUICK_INDEX_MERGE_SELECT::~QUICK_INDEX_MERGE_SELECT()
 
1196
{
 
1197
  List_iterator_fast<QUICK_RANGE_SELECT> quick_it(quick_selects);
 
1198
  QUICK_RANGE_SELECT* quick;
 
1199
  quick_it.rewind();
 
1200
  while ((quick= quick_it++))
 
1201
    quick->file= NULL;
 
1202
  quick_selects.delete_elements();
 
1203
  delete pk_quick_select;
 
1204
  free_root(&alloc,MYF(0));
 
1205
  return;
 
1206
}
 
1207
 
 
1208
 
 
1209
QUICK_ROR_INTERSECT_SELECT::QUICK_ROR_INTERSECT_SELECT(Session *session_param,
 
1210
                                                       Table *table,
 
1211
                                                       bool retrieve_full_rows,
 
1212
                                                       MEM_ROOT *parent_alloc)
 
1213
  : cpk_quick(NULL), session(session_param), need_to_fetch_row(retrieve_full_rows),
 
1214
    scans_inited(false)
 
1215
{
 
1216
  index= MAX_KEY;
 
1217
  head= table;
 
1218
  record= head->record[0];
 
1219
  if (!parent_alloc)
 
1220
    init_sql_alloc(&alloc, session->variables.range_alloc_block_size, 0);
 
1221
  else
 
1222
    memset(&alloc, 0, sizeof(MEM_ROOT));
 
1223
  last_rowid= (unsigned char*) alloc_root(parent_alloc? parent_alloc : &alloc,
 
1224
                                  head->file->ref_length);
 
1225
}
 
1226
 
 
1227
 
 
1228
/*
 
1229
  Do post-constructor initialization.
 
1230
  SYNOPSIS
 
1231
    QUICK_ROR_INTERSECT_SELECT::init()
 
1232
 
 
1233
  RETURN
 
1234
    0      OK
 
1235
    other  Error code
 
1236
*/
 
1237
 
 
1238
int QUICK_ROR_INTERSECT_SELECT::init()
 
1239
{
 
1240
 /* Check if last_rowid was successfully allocated in ctor */
 
1241
  return(!last_rowid);
 
1242
}
 
1243
 
 
1244
 
 
1245
/*
 
1246
  Initialize this quick select to be a ROR-merged scan.
 
1247
 
 
1248
  SYNOPSIS
 
1249
    QUICK_RANGE_SELECT::init_ror_merged_scan()
 
1250
      reuse_handler If true, use head->file, otherwise create a separate
 
1251
                    handler object
 
1252
 
 
1253
  NOTES
 
1254
    This function creates and prepares for subsequent use a separate handler
 
1255
    object if it can't reuse head->file. The reason for this is that during
 
1256
    ROR-merge several key scans are performed simultaneously, and a single
 
1257
    handler is only capable of preserving context of a single key scan.
 
1258
 
 
1259
    In ROR-merge the quick select doing merge does full records retrieval,
 
1260
    merged quick selects read only keys.
 
1261
 
 
1262
  RETURN
 
1263
    0  ROR child scan initialized, ok to use.
 
1264
    1  error
 
1265
*/
 
1266
 
 
1267
int QUICK_RANGE_SELECT::init_ror_merged_scan(bool reuse_handler)
 
1268
{
 
1269
  handler *save_file= file, *org_file;
 
1270
  Session *session;
 
1271
 
 
1272
  in_ror_merged_scan= 1;
 
1273
  if (reuse_handler)
 
1274
  {
 
1275
    if (init() || reset())
 
1276
    {
 
1277
      return(1);
 
1278
    }
 
1279
    head->column_bitmaps_set(&column_bitmap, &column_bitmap);
 
1280
    goto end;
 
1281
  }
 
1282
 
 
1283
  /* Create a separate handler object for this quick select */
 
1284
  if (free_file)
 
1285
  {
 
1286
    /* already have own 'handler' object. */
 
1287
    return(0);
 
1288
  }
 
1289
 
 
1290
  session= head->in_use;
 
1291
  if (!(file= head->file->clone(session->mem_root)))
 
1292
  {
 
1293
    /* 
 
1294
      Manually set the error flag. Note: there seems to be quite a few
 
1295
      places where a failure could cause the server to "hang" the client by
 
1296
      sending no response to a query. ATM those are not real errors because 
 
1297
      the storage engine calls in question happen to never fail with the 
 
1298
      existing storage engines. 
 
1299
    */
 
1300
    my_error(ER_OUT_OF_RESOURCES, MYF(0)); /* purecov: inspected */
 
1301
    /* Caller will free the memory */
 
1302
    goto failure;  /* purecov: inspected */
 
1303
  }
 
1304
 
 
1305
  head->column_bitmaps_set(&column_bitmap, &column_bitmap);
 
1306
 
 
1307
  if (file->ha_external_lock(session, F_RDLCK))
 
1308
    goto failure;
 
1309
 
 
1310
  if (init() || reset())
 
1311
  {
 
1312
    file->ha_external_lock(session, F_UNLCK);
 
1313
    file->close();
 
1314
    goto failure;
 
1315
  }
 
1316
  free_file= true;
 
1317
  last_rowid= file->ref;
 
1318
 
 
1319
end:
 
1320
  /*
 
1321
    We are only going to read key fields and call position() on 'file'
 
1322
    The following sets head->tmp_set to only use this key and then updates
 
1323
    head->read_set and head->write_set to use this bitmap.
 
1324
    The now bitmap is stored in 'column_bitmap' which is used in ::get_next()
 
1325
  */
 
1326
  org_file= head->file;
 
1327
  head->file= file;
 
1328
  /* We don't have to set 'head->keyread' here as the 'file' is unique */
 
1329
  if (!head->no_keyread)
 
1330
  {
 
1331
    head->key_read= 1;
 
1332
    head->mark_columns_used_by_index(index);
 
1333
  }
 
1334
  head->prepare_for_position();
 
1335
  head->file= org_file;
 
1336
  bitmap_copy(&column_bitmap, head->read_set);
 
1337
  head->column_bitmaps_set(&column_bitmap, &column_bitmap);
 
1338
 
 
1339
  return(0);
 
1340
 
 
1341
failure:
 
1342
  head->column_bitmaps_set(save_read_set, save_write_set);
 
1343
  delete file;
 
1344
  file= save_file;
 
1345
  return(1);
 
1346
}
 
1347
 
 
1348
 
 
1349
/*
 
1350
  Initialize this quick select to be a part of a ROR-merged scan.
 
1351
  SYNOPSIS
 
1352
    QUICK_ROR_INTERSECT_SELECT::init_ror_merged_scan()
 
1353
      reuse_handler If true, use head->file, otherwise create separate
 
1354
                    handler object.
 
1355
  RETURN
 
1356
    0     OK
 
1357
    other error code
 
1358
*/
 
1359
int QUICK_ROR_INTERSECT_SELECT::init_ror_merged_scan(bool reuse_handler)
 
1360
{
 
1361
  List_iterator_fast<QUICK_RANGE_SELECT> quick_it(quick_selects);
 
1362
  QUICK_RANGE_SELECT* quick;
 
1363
 
 
1364
  /* Initialize all merged "children" quick selects */
 
1365
  assert(!need_to_fetch_row || reuse_handler);
 
1366
  if (!need_to_fetch_row && reuse_handler)
 
1367
  {
 
1368
    quick= quick_it++;
 
1369
    /*
 
1370
      There is no use of this->file. Use it for the first of merged range
 
1371
      selects.
 
1372
    */
 
1373
    if (quick->init_ror_merged_scan(true))
 
1374
      return(1);
 
1375
    quick->file->extra(HA_EXTRA_KEYREAD_PRESERVE_FIELDS);
 
1376
  }
 
1377
  while ((quick= quick_it++))
 
1378
  {
 
1379
    if (quick->init_ror_merged_scan(false))
 
1380
      return(1);
 
1381
    quick->file->extra(HA_EXTRA_KEYREAD_PRESERVE_FIELDS);
 
1382
    /* All merged scans share the same record buffer in intersection. */
 
1383
    quick->record= head->record[0];
 
1384
  }
 
1385
 
 
1386
  if (need_to_fetch_row && head->file->ha_rnd_init(1))
 
1387
  {
 
1388
    return(1);
 
1389
  }
 
1390
  return(0);
 
1391
}
 
1392
 
 
1393
 
 
1394
/*
 
1395
  Initialize quick select for row retrieval.
 
1396
  SYNOPSIS
 
1397
    reset()
 
1398
  RETURN
 
1399
    0      OK
 
1400
    other  Error code
 
1401
*/
 
1402
 
 
1403
int QUICK_ROR_INTERSECT_SELECT::reset()
 
1404
{
 
1405
  if (!scans_inited && init_ror_merged_scan(true))
 
1406
    return(1);
 
1407
  scans_inited= true;
 
1408
  List_iterator_fast<QUICK_RANGE_SELECT> it(quick_selects);
 
1409
  QUICK_RANGE_SELECT *quick;
 
1410
  while ((quick= it++))
 
1411
    quick->reset();
 
1412
  return(0);
 
1413
}
 
1414
 
 
1415
 
 
1416
/*
 
1417
  Add a merged quick select to this ROR-intersection quick select.
 
1418
 
 
1419
  SYNOPSIS
 
1420
    QUICK_ROR_INTERSECT_SELECT::push_quick_back()
 
1421
      quick Quick select to be added. The quick select must return
 
1422
            rows in rowid order.
 
1423
  NOTES
 
1424
    This call can only be made before init() is called.
 
1425
 
 
1426
  RETURN
 
1427
    false OK
 
1428
    true  Out of memory.
 
1429
*/
 
1430
 
 
1431
bool
 
1432
QUICK_ROR_INTERSECT_SELECT::push_quick_back(QUICK_RANGE_SELECT *quick)
 
1433
{
 
1434
  return quick_selects.push_back(quick);
 
1435
}
 
1436
 
 
1437
QUICK_ROR_INTERSECT_SELECT::~QUICK_ROR_INTERSECT_SELECT()
 
1438
{
 
1439
  quick_selects.delete_elements();
 
1440
  delete cpk_quick;
 
1441
  free_root(&alloc,MYF(0));
 
1442
  if (need_to_fetch_row && head->file->inited != handler::NONE)
 
1443
    head->file->ha_rnd_end();
 
1444
  return;
 
1445
}
 
1446
 
 
1447
 
 
1448
QUICK_ROR_UNION_SELECT::QUICK_ROR_UNION_SELECT(Session *session_param,
 
1449
                                               Table *table)
 
1450
  : session(session_param), scans_inited(false)
 
1451
{
 
1452
  index= MAX_KEY;
 
1453
  head= table;
 
1454
  rowid_length= table->file->ref_length;
 
1455
  record= head->record[0];
 
1456
  init_sql_alloc(&alloc, session->variables.range_alloc_block_size, 0);
 
1457
  session_param->mem_root= &alloc;
 
1458
}
 
1459
 
 
1460
 
 
1461
/*
 
1462
  Do post-constructor initialization.
 
1463
  SYNOPSIS
 
1464
    QUICK_ROR_UNION_SELECT::init()
 
1465
 
 
1466
  RETURN
 
1467
    0      OK
 
1468
    other  Error code
 
1469
*/
 
1470
 
 
1471
int QUICK_ROR_UNION_SELECT::init()
 
1472
{
 
1473
  if (init_queue(&queue, quick_selects.elements, 0,
 
1474
                 false , QUICK_ROR_UNION_SELECT::queue_cmp,
 
1475
                 (void*) this))
 
1476
  {
 
1477
    memset(&queue, 0, sizeof(QUEUE));
 
1478
    return(1);
 
1479
  }
 
1480
 
 
1481
  if (!(cur_rowid= (unsigned char*) alloc_root(&alloc, 2*head->file->ref_length)))
 
1482
    return(1);
 
1483
  prev_rowid= cur_rowid + head->file->ref_length;
 
1484
  return(0);
 
1485
}
 
1486
 
 
1487
 
 
1488
/*
 
1489
  Comparison function to be used QUICK_ROR_UNION_SELECT::queue priority
 
1490
  queue.
 
1491
 
 
1492
  SYNPOSIS
 
1493
    QUICK_ROR_UNION_SELECT::queue_cmp()
 
1494
      arg   Pointer to QUICK_ROR_UNION_SELECT
 
1495
      val1  First merged select
 
1496
      val2  Second merged select
 
1497
*/
 
1498
 
 
1499
int QUICK_ROR_UNION_SELECT::queue_cmp(void *arg, unsigned char *val1, unsigned char *val2)
 
1500
{
 
1501
  QUICK_ROR_UNION_SELECT *self= (QUICK_ROR_UNION_SELECT*)arg;
 
1502
  return self->head->file->cmp_ref(((QUICK_SELECT_I*)val1)->last_rowid,
 
1503
                                   ((QUICK_SELECT_I*)val2)->last_rowid);
 
1504
}
 
1505
 
 
1506
 
 
1507
/*
 
1508
  Initialize quick select for row retrieval.
 
1509
  SYNOPSIS
 
1510
    reset()
 
1511
 
 
1512
  RETURN
 
1513
    0      OK
 
1514
    other  Error code
 
1515
*/
 
1516
 
 
1517
int QUICK_ROR_UNION_SELECT::reset()
 
1518
{
 
1519
  QUICK_SELECT_I *quick;
 
1520
  int error;
 
1521
  have_prev_rowid= false;
 
1522
  if (!scans_inited)
 
1523
  {
 
1524
    List_iterator_fast<QUICK_SELECT_I> it(quick_selects);
 
1525
    while ((quick= it++))
 
1526
    {
 
1527
      if (quick->init_ror_merged_scan(false))
 
1528
        return(1);
 
1529
    }
 
1530
    scans_inited= true;
 
1531
  }
 
1532
  queue_remove_all(&queue);
 
1533
  /*
 
1534
    Initialize scans for merged quick selects and put all merged quick
 
1535
    selects into the queue.
 
1536
  */
 
1537
  List_iterator_fast<QUICK_SELECT_I> it(quick_selects);
 
1538
  while ((quick= it++))
 
1539
  {
 
1540
    if (quick->reset())
 
1541
      return(1);
 
1542
    if ((error= quick->get_next()))
 
1543
    {
 
1544
      if (error == HA_ERR_END_OF_FILE)
 
1545
        continue;
 
1546
      return(error);
 
1547
    }
 
1548
    quick->save_last_pos();
 
1549
    queue_insert(&queue, (unsigned char*)quick);
 
1550
  }
 
1551
 
 
1552
  if (head->file->ha_rnd_init(1))
 
1553
  {
 
1554
    return(1);
 
1555
  }
 
1556
 
 
1557
  return(0);
 
1558
}
 
1559
 
 
1560
 
 
1561
bool
 
1562
QUICK_ROR_UNION_SELECT::push_quick_back(QUICK_SELECT_I *quick_sel_range)
 
1563
{
 
1564
  return quick_selects.push_back(quick_sel_range);
 
1565
}
 
1566
 
 
1567
QUICK_ROR_UNION_SELECT::~QUICK_ROR_UNION_SELECT()
 
1568
{
 
1569
  delete_queue(&queue);
 
1570
  quick_selects.delete_elements();
 
1571
  if (head->file->inited != handler::NONE)
 
1572
    head->file->ha_rnd_end();
 
1573
  free_root(&alloc,MYF(0));
 
1574
  return;
 
1575
}
 
1576
 
 
1577
 
 
1578
QUICK_RANGE::QUICK_RANGE()
 
1579
  :min_key(0),max_key(0),min_length(0),max_length(0),
 
1580
   flag(NO_MIN_RANGE | NO_MAX_RANGE),
 
1581
  min_keypart_map(0), max_keypart_map(0)
 
1582
{}
 
1583
 
 
1584
SEL_ARG::SEL_ARG(SEL_ARG &arg) :Sql_alloc()
 
1585
{
 
1586
  type=arg.type;
 
1587
  min_flag=arg.min_flag;
 
1588
  max_flag=arg.max_flag;
 
1589
  maybe_flag=arg.maybe_flag;
 
1590
  maybe_null=arg.maybe_null;
 
1591
  part=arg.part;
 
1592
  field=arg.field;
 
1593
  min_value=arg.min_value;
 
1594
  max_value=arg.max_value;
 
1595
  next_key_part=arg.next_key_part;
 
1596
  use_count=1; elements=1;
 
1597
}
 
1598
 
 
1599
 
 
1600
inline void SEL_ARG::make_root()
 
1601
{
 
1602
  left=right= &null_element;
 
1603
  color=BLACK;
 
1604
  next=prev=0;
 
1605
  use_count=0; elements=1;
 
1606
}
 
1607
 
 
1608
SEL_ARG::SEL_ARG(Field *f,const unsigned char *min_value_arg,
 
1609
                 const unsigned char *max_value_arg)
 
1610
  :min_flag(0), max_flag(0), maybe_flag(0), maybe_null(f->real_maybe_null()),
 
1611
   elements(1), use_count(1), field(f), min_value((unsigned char*) min_value_arg),
 
1612
   max_value((unsigned char*) max_value_arg), next(0),prev(0),
 
1613
   next_key_part(0),color(BLACK),type(KEY_RANGE)
 
1614
{
 
1615
  left=right= &null_element;
 
1616
}
 
1617
 
 
1618
SEL_ARG::SEL_ARG(Field *field_,uint8_t part_,
 
1619
                 unsigned char *min_value_, unsigned char *max_value_,
 
1620
                 uint8_t min_flag_,uint8_t max_flag_,uint8_t maybe_flag_)
 
1621
  :min_flag(min_flag_),max_flag(max_flag_),maybe_flag(maybe_flag_),
 
1622
   part(part_),maybe_null(field_->real_maybe_null()), elements(1),use_count(1),
 
1623
   field(field_), min_value(min_value_), max_value(max_value_),
 
1624
   next(0),prev(0),next_key_part(0),color(BLACK),type(KEY_RANGE)
 
1625
{
 
1626
  left=right= &null_element;
 
1627
}
 
1628
 
 
1629
SEL_ARG *SEL_ARG::clone(RANGE_OPT_PARAM *param, SEL_ARG *new_parent, 
 
1630
                        SEL_ARG **next_arg)
 
1631
{
 
1632
  SEL_ARG *tmp;
 
1633
 
 
1634
  /* Bail out if we have already generated too many SEL_ARGs */
 
1635
  if (++param->alloced_sel_args > MAX_SEL_ARGS)
 
1636
    return 0;
 
1637
 
 
1638
  if (type != KEY_RANGE)
 
1639
  {
 
1640
    if (!(tmp= new (param->mem_root) SEL_ARG(type)))
 
1641
      return 0;                                 // out of memory
 
1642
    tmp->prev= *next_arg;                       // Link into next/prev chain
 
1643
    (*next_arg)->next=tmp;
 
1644
    (*next_arg)= tmp;
 
1645
  }
 
1646
  else
 
1647
  {
 
1648
    if (!(tmp= new (param->mem_root) SEL_ARG(field,part, min_value,max_value,
 
1649
                                             min_flag, max_flag, maybe_flag)))
 
1650
      return 0;                                 // OOM
 
1651
    tmp->parent=new_parent;
 
1652
    tmp->next_key_part=next_key_part;
 
1653
    if (left != &null_element)
 
1654
      if (!(tmp->left=left->clone(param, tmp, next_arg)))
 
1655
        return 0;                               // OOM
 
1656
 
 
1657
    tmp->prev= *next_arg;                       // Link into next/prev chain
 
1658
    (*next_arg)->next=tmp;
 
1659
    (*next_arg)= tmp;
 
1660
 
 
1661
    if (right != &null_element)
 
1662
      if (!(tmp->right= right->clone(param, tmp, next_arg)))
 
1663
        return 0;                               // OOM
 
1664
  }
 
1665
  increment_use_count(1);
 
1666
  tmp->color= color;
 
1667
  tmp->elements= this->elements;
 
1668
  return tmp;
 
1669
}
 
1670
 
 
1671
SEL_ARG *SEL_ARG::first()
 
1672
{
 
1673
  SEL_ARG *next_arg=this;
 
1674
  if (!next_arg->left)
 
1675
    return 0;                                   // MAYBE_KEY
 
1676
  while (next_arg->left != &null_element)
 
1677
    next_arg=next_arg->left;
 
1678
  return next_arg;
 
1679
}
 
1680
 
 
1681
SEL_ARG *SEL_ARG::last()
 
1682
{
 
1683
  SEL_ARG *next_arg=this;
 
1684
  if (!next_arg->right)
 
1685
    return 0;                                   // MAYBE_KEY
 
1686
  while (next_arg->right != &null_element)
 
1687
    next_arg=next_arg->right;
 
1688
  return next_arg;
 
1689
}
 
1690
 
 
1691
 
 
1692
/*
 
1693
  Check if a compare is ok, when one takes ranges in account
 
1694
  Returns -2 or 2 if the ranges where 'joined' like  < 2 and >= 2
 
1695
*/
 
1696
 
 
1697
static int sel_cmp(Field *field, unsigned char *a, unsigned char *b, uint8_t a_flag,
 
1698
                   uint8_t b_flag)
 
1699
{
 
1700
  int cmp;
 
1701
  /* First check if there was a compare to a min or max element */
 
1702
  if (a_flag & (NO_MIN_RANGE | NO_MAX_RANGE))
 
1703
  {
 
1704
    if ((a_flag & (NO_MIN_RANGE | NO_MAX_RANGE)) ==
 
1705
        (b_flag & (NO_MIN_RANGE | NO_MAX_RANGE)))
 
1706
      return 0;
 
1707
    return (a_flag & NO_MIN_RANGE) ? -1 : 1;
 
1708
  }
 
1709
  if (b_flag & (NO_MIN_RANGE | NO_MAX_RANGE))
 
1710
    return (b_flag & NO_MIN_RANGE) ? 1 : -1;
 
1711
 
 
1712
  if (field->real_maybe_null())                 // If null is part of key
 
1713
  {
 
1714
    if (*a != *b)
 
1715
    {
 
1716
      return *a ? -1 : 1;
 
1717
    }
 
1718
    if (*a)
 
1719
      goto end;                                 // NULL where equal
 
1720
    a++; b++;                                   // Skip NULL marker
 
1721
  }
 
1722
  cmp=field->key_cmp(a , b);
 
1723
  if (cmp) return cmp < 0 ? -1 : 1;             // The values differed
 
1724
 
 
1725
  // Check if the compared equal arguments was defined with open/closed range
 
1726
 end:
 
1727
  if (a_flag & (NEAR_MIN | NEAR_MAX))
 
1728
  {
 
1729
    if ((a_flag & (NEAR_MIN | NEAR_MAX)) == (b_flag & (NEAR_MIN | NEAR_MAX)))
 
1730
      return 0;
 
1731
    if (!(b_flag & (NEAR_MIN | NEAR_MAX)))
 
1732
      return (a_flag & NEAR_MIN) ? 2 : -2;
 
1733
    return (a_flag & NEAR_MIN) ? 1 : -1;
 
1734
  }
 
1735
  if (b_flag & (NEAR_MIN | NEAR_MAX))
 
1736
    return (b_flag & NEAR_MIN) ? -2 : 2;
 
1737
  return 0;                                     // The elements where equal
 
1738
}
 
1739
 
 
1740
 
 
1741
SEL_ARG *SEL_ARG::clone_tree(RANGE_OPT_PARAM *param)
 
1742
{
 
1743
  SEL_ARG tmp_link,*next_arg,*root;
 
1744
  next_arg= &tmp_link;
 
1745
  if (!(root= clone(param, (SEL_ARG *) 0, &next_arg)))
 
1746
    return 0;
 
1747
  next_arg->next=0;                             // Fix last link
 
1748
  tmp_link.next->prev=0;                        // Fix first link
 
1749
  if (root)                                     // If not OOM
 
1750
    root->use_count= 0;
 
1751
  return root;
 
1752
}
438
1753
 
439
1754
 
440
1755
/*
447
1762
      limit  Number of records that will be retrieved
448
1763
 
449
1764
  DESCRIPTION
450
 
    Find the best index that allows to retrieve first #limit records in the
 
1765
    Find the best index that allows to retrieve first #limit records in the 
451
1766
    given order cheaper then one would retrieve them using full table scan.
452
1767
 
453
1768
  IMPLEMENTATION
466
1781
    MAX_KEY if no such index was found.
467
1782
*/
468
1783
 
469
 
uint32_t optimizer::get_index_for_order(Table *table, Order *order, ha_rows limit)
 
1784
uint32_t get_index_for_order(Table *table, order_st *order, ha_rows limit)
470
1785
{
471
1786
  uint32_t idx;
472
1787
  uint32_t match_key= MAX_KEY, match_key_len= MAX_KEY_LENGTH + 1;
473
 
  Order *ord;
474
 
 
 
1788
  order_st *ord;
 
1789
  
475
1790
  for (ord= order; ord; ord= ord->next)
476
1791
    if (!ord->asc)
477
1792
      return MAX_KEY;
478
1793
 
479
 
  for (idx= 0; idx < table->getShare()->sizeKeys(); idx++)
 
1794
  for (idx= 0; idx < table->s->keys; idx++)
480
1795
  {
481
 
    if (!(table->keys_in_use_for_query.test(idx)))
 
1796
    if (!(table->keys_in_use_for_query.is_set(idx)))
482
1797
      continue;
483
 
    KeyPartInfo *keyinfo= table->key_info[idx].key_part;
 
1798
    KEY_PART_INFO *keyinfo= table->key_info[idx].key_part;
484
1799
    uint32_t n_parts=  table->key_info[idx].key_parts;
485
1800
    uint32_t partno= 0;
486
 
 
487
 
    /*
488
 
      The below check is sufficient considering we now have either BTREE
489
 
      indexes (records are returned in order for any index prefix) or HASH
 
1801
    
 
1802
    /* 
 
1803
      The below check is sufficient considering we now have either BTREE 
 
1804
      indexes (records are returned in order for any index prefix) or HASH 
490
1805
      indexes (records are not returned in order for any index prefix).
491
1806
    */
492
 
    if (! (table->index_flags(idx) & HA_READ_ORDER))
 
1807
    if (!(table->file->index_flags(idx, 0, 1) & HA_READ_ORDER))
493
1808
      continue;
494
1809
    for (ord= order; ord && partno < n_parts; ord= ord->next, partno++)
495
1810
    {
496
1811
      Item *item= order->item[0];
497
 
      if (! (item->type() == Item::FIELD_ITEM &&
 
1812
      if (!(item->type() == Item::FIELD_ITEM &&
498
1813
           ((Item_field*)item)->field->eq(keyinfo[partno].field)))
499
1814
        break;
500
1815
    }
501
 
 
502
 
    if (! ord && table->key_info[idx].key_length < match_key_len)
 
1816
    
 
1817
    if (!ord && table->key_info[idx].key_length < match_key_len)
503
1818
    {
504
 
      /*
 
1819
      /* 
505
1820
        Ok, the ordering is compatible and this key is shorter then
506
1821
        previous match (we want shorter keys as we'll have to read fewer
507
1822
        index pages for the same number of records)
513
1828
 
514
1829
  if (match_key != MAX_KEY)
515
1830
  {
516
 
    /*
517
 
      Found an index that allows records to be retrieved in the requested
 
1831
    /* 
 
1832
      Found an index that allows records to be retrieved in the requested 
518
1833
      order. Now we'll check if using the index is cheaper then doing a table
519
1834
      scan.
520
1835
    */
521
 
    double full_scan_time= table->cursor->scan_time();
522
 
    double index_scan_time= table->cursor->read_time(match_key, 1, limit);
 
1836
    double full_scan_time= table->file->scan_time();
 
1837
    double index_scan_time= table->file->read_time(match_key, 1, limit);
523
1838
    if (index_scan_time > full_scan_time)
524
1839
      match_key= MAX_KEY;
525
1840
  }
527
1842
}
528
1843
 
529
1844
 
 
1845
/*
 
1846
  Table rows retrieval plan. Range optimizer creates QUICK_SELECT_I-derived
 
1847
  objects from table read plans.
 
1848
*/
 
1849
class TABLE_READ_PLAN
 
1850
{
 
1851
public:
 
1852
  /*
 
1853
    Plan read cost, with or without cost of full row retrieval, depending
 
1854
    on plan creation parameters.
 
1855
  */
 
1856
  double read_cost;
 
1857
  ha_rows records; /* estimate of #rows to be examined */
 
1858
 
 
1859
  /*
 
1860
    If true, the scan returns rows in rowid order. This is used only for
 
1861
    scans that can be both ROR and non-ROR.
 
1862
  */
 
1863
  bool is_ror;
 
1864
 
 
1865
  /*
 
1866
    Create quick select for this plan.
 
1867
    SYNOPSIS
 
1868
     make_quick()
 
1869
       param               Parameter from test_quick_select
 
1870
       retrieve_full_rows  If true, created quick select will do full record
 
1871
                           retrieval.
 
1872
       parent_alloc        Memory pool to use, if any.
 
1873
 
 
1874
    NOTES
 
1875
      retrieve_full_rows is ignored by some implementations.
 
1876
 
 
1877
    RETURN
 
1878
      created quick select
 
1879
      NULL on any error.
 
1880
  */
 
1881
  virtual QUICK_SELECT_I *make_quick(PARAM *param,
 
1882
                                     bool retrieve_full_rows,
 
1883
                                     MEM_ROOT *parent_alloc=NULL) = 0;
 
1884
 
 
1885
  /* Table read plans are allocated on MEM_ROOT and are never deleted */
 
1886
  static void *operator new(size_t size, MEM_ROOT *mem_root)
 
1887
  { return (void*) alloc_root(mem_root, (uint) size); }
 
1888
  static void operator delete(void *ptr __attribute__((unused)),
 
1889
                              size_t size __attribute__((unused)))
 
1890
    { TRASH(ptr, size); }
 
1891
  static void operator delete(void *ptr __attribute__((unused)),
 
1892
                              MEM_ROOT *mem_root __attribute__((unused)))
 
1893
    { /* Never called */ }
 
1894
  virtual ~TABLE_READ_PLAN() {}               /* Remove gcc warning */
 
1895
 
 
1896
};
 
1897
 
 
1898
class TRP_ROR_INTERSECT;
 
1899
class TRP_ROR_UNION;
 
1900
class TRP_INDEX_MERGE;
 
1901
 
 
1902
 
 
1903
/*
 
1904
  Plan for a QUICK_RANGE_SELECT scan.
 
1905
  TRP_RANGE::make_quick ignores retrieve_full_rows parameter because
 
1906
  QUICK_RANGE_SELECT doesn't distinguish between 'index only' scans and full
 
1907
  record retrieval scans.
 
1908
*/
 
1909
 
 
1910
class TRP_RANGE : public TABLE_READ_PLAN
 
1911
{
 
1912
public:
 
1913
  SEL_ARG *key; /* set of intervals to be used in "range" method retrieval */
 
1914
  uint32_t     key_idx; /* key number in PARAM::key */
 
1915
  uint32_t     mrr_flags; 
 
1916
  uint32_t     mrr_buf_size;
 
1917
 
 
1918
  TRP_RANGE(SEL_ARG *key_arg, uint32_t idx_arg, uint32_t mrr_flags_arg)
 
1919
   : key(key_arg), key_idx(idx_arg), mrr_flags(mrr_flags_arg)
 
1920
  {}
 
1921
  virtual ~TRP_RANGE() {}                     /* Remove gcc warning */
 
1922
 
 
1923
  QUICK_SELECT_I *make_quick(PARAM *param,
 
1924
                             bool retrieve_full_rows __attribute__((unused)),
 
1925
                             MEM_ROOT *parent_alloc)
 
1926
  {
 
1927
    QUICK_RANGE_SELECT *quick;
 
1928
    if ((quick= get_quick_select(param, key_idx, key, mrr_flags, mrr_buf_size,
 
1929
                                 parent_alloc)))
 
1930
    {
 
1931
      quick->records= records;
 
1932
      quick->read_time= read_cost;
 
1933
    }
 
1934
    return(quick);
 
1935
  }
 
1936
};
 
1937
 
 
1938
 
 
1939
/* Plan for QUICK_ROR_INTERSECT_SELECT scan. */
 
1940
 
 
1941
class TRP_ROR_INTERSECT : public TABLE_READ_PLAN
 
1942
{
 
1943
public:
 
1944
  TRP_ROR_INTERSECT() {}                      /* Remove gcc warning */
 
1945
  virtual ~TRP_ROR_INTERSECT() {}             /* Remove gcc warning */
 
1946
  QUICK_SELECT_I *make_quick(PARAM *param, bool retrieve_full_rows,
 
1947
                             MEM_ROOT *parent_alloc);
 
1948
 
 
1949
  /* Array of pointers to ROR range scans used in this intersection */
 
1950
  struct st_ror_scan_info **first_scan;
 
1951
  struct st_ror_scan_info **last_scan; /* End of the above array */
 
1952
  struct st_ror_scan_info *cpk_scan;  /* Clustered PK scan, if there is one */
 
1953
  bool is_covering; /* true if no row retrieval phase is necessary */
 
1954
  double index_scan_costs; /* SUM(cost(index_scan)) */
 
1955
};
 
1956
 
 
1957
 
 
1958
/*
 
1959
  Plan for QUICK_ROR_UNION_SELECT scan.
 
1960
  QUICK_ROR_UNION_SELECT always retrieves full rows, so retrieve_full_rows
 
1961
  is ignored by make_quick.
 
1962
*/
 
1963
 
 
1964
class TRP_ROR_UNION : public TABLE_READ_PLAN
 
1965
{
 
1966
public:
 
1967
  TRP_ROR_UNION() {}                          /* Remove gcc warning */
 
1968
  virtual ~TRP_ROR_UNION() {}                 /* Remove gcc warning */
 
1969
  QUICK_SELECT_I *make_quick(PARAM *param, bool retrieve_full_rows,
 
1970
                             MEM_ROOT *parent_alloc);
 
1971
  TABLE_READ_PLAN **first_ror; /* array of ptrs to plans for merged scans */
 
1972
  TABLE_READ_PLAN **last_ror;  /* end of the above array */
 
1973
};
 
1974
 
 
1975
 
 
1976
/*
 
1977
  Plan for QUICK_INDEX_MERGE_SELECT scan.
 
1978
  QUICK_ROR_INTERSECT_SELECT always retrieves full rows, so retrieve_full_rows
 
1979
  is ignored by make_quick.
 
1980
*/
 
1981
 
 
1982
class TRP_INDEX_MERGE : public TABLE_READ_PLAN
 
1983
{
 
1984
public:
 
1985
  TRP_INDEX_MERGE() {}                        /* Remove gcc warning */
 
1986
  virtual ~TRP_INDEX_MERGE() {}               /* Remove gcc warning */
 
1987
  QUICK_SELECT_I *make_quick(PARAM *param, bool retrieve_full_rows,
 
1988
                             MEM_ROOT *parent_alloc);
 
1989
  TRP_RANGE **range_scans; /* array of ptrs to plans of merged scans */
 
1990
  TRP_RANGE **range_scans_end; /* end of the array */
 
1991
};
 
1992
 
 
1993
 
 
1994
/*
 
1995
  Plan for a QUICK_GROUP_MIN_MAX_SELECT scan. 
 
1996
*/
 
1997
 
 
1998
class TRP_GROUP_MIN_MAX : public TABLE_READ_PLAN
 
1999
{
 
2000
private:
 
2001
  bool have_min, have_max;
 
2002
  KEY_PART_INFO *min_max_arg_part;
 
2003
  uint32_t group_prefix_len;
 
2004
  uint32_t used_key_parts;
 
2005
  uint32_t group_key_parts;
 
2006
  KEY *index_info;
 
2007
  uint32_t index;
 
2008
  uint32_t key_infix_len;
 
2009
  unsigned char key_infix[MAX_KEY_LENGTH];
 
2010
  SEL_TREE *range_tree; /* Represents all range predicates in the query. */
 
2011
  SEL_ARG  *index_tree; /* The SEL_ARG sub-tree corresponding to index_info. */
 
2012
  uint32_t param_idx; /* Index of used key in param->key. */
 
2013
  /* Number of records selected by the ranges in index_tree. */
 
2014
public:
 
2015
  ha_rows quick_prefix_records;
 
2016
public:
 
2017
  TRP_GROUP_MIN_MAX(bool have_min_arg, bool have_max_arg,
 
2018
                    KEY_PART_INFO *min_max_arg_part_arg,
 
2019
                    uint32_t group_prefix_len_arg, uint32_t used_key_parts_arg,
 
2020
                    uint32_t group_key_parts_arg, KEY *index_info_arg,
 
2021
                    uint32_t index_arg, uint32_t key_infix_len_arg,
 
2022
                    unsigned char *key_infix_arg,
 
2023
                    SEL_TREE *tree_arg, SEL_ARG *index_tree_arg,
 
2024
                    uint32_t param_idx_arg, ha_rows quick_prefix_records_arg)
 
2025
  : have_min(have_min_arg), have_max(have_max_arg),
 
2026
    min_max_arg_part(min_max_arg_part_arg),
 
2027
    group_prefix_len(group_prefix_len_arg), used_key_parts(used_key_parts_arg),
 
2028
    group_key_parts(group_key_parts_arg), index_info(index_info_arg),
 
2029
    index(index_arg), key_infix_len(key_infix_len_arg), range_tree(tree_arg),
 
2030
    index_tree(index_tree_arg), param_idx(param_idx_arg),
 
2031
    quick_prefix_records(quick_prefix_records_arg)
 
2032
    {
 
2033
      if (key_infix_len)
 
2034
        memcpy(this->key_infix, key_infix_arg, key_infix_len);
 
2035
    }
 
2036
  virtual ~TRP_GROUP_MIN_MAX() {}             /* Remove gcc warning */
 
2037
 
 
2038
  QUICK_SELECT_I *make_quick(PARAM *param, bool retrieve_full_rows,
 
2039
                             MEM_ROOT *parent_alloc);
 
2040
};
 
2041
 
530
2042
 
531
2043
/*
532
2044
  Fill param->needed_fields with bitmap of fields used in the query.
542
2054
    1  Out of memory.
543
2055
*/
544
2056
 
545
 
static int fill_used_fields_bitmap(optimizer::Parameter *param)
 
2057
static int fill_used_fields_bitmap(PARAM *param)
546
2058
{
547
2059
  Table *table= param->table;
 
2060
  my_bitmap_map *tmp;
548
2061
  uint32_t pk;
549
 
  param->tmp_covered_fields.clear();
550
 
  param->needed_fields.resize(table->getShare()->sizeFields());
551
 
  param->needed_fields.reset();
552
 
 
553
 
  param->needed_fields|= *table->read_set;
554
 
  param->needed_fields|= *table->write_set;
555
 
 
556
 
  pk= param->table->getShare()->getPrimaryKey();
557
 
  if (pk != MAX_KEY && param->table->cursor->primary_key_is_clustered())
 
2062
  param->tmp_covered_fields.bitmap= 0;
 
2063
  param->fields_bitmap_size= table->s->column_bitmap_size;
 
2064
  if (!(tmp= (my_bitmap_map*) alloc_root(param->mem_root,
 
2065
                                  param->fields_bitmap_size)) ||
 
2066
      bitmap_init(&param->needed_fields, tmp, table->s->fields, false))
 
2067
    return 1;
 
2068
 
 
2069
  bitmap_copy(&param->needed_fields, table->read_set);
 
2070
  bitmap_union(&param->needed_fields, table->write_set);
 
2071
 
 
2072
  pk= param->table->s->primary_key;
 
2073
  if (pk != MAX_KEY && param->table->file->primary_key_is_clustered())
558
2074
  {
559
2075
    /* The table uses clustered PK and it is not internally generated */
560
 
    KeyPartInfo *key_part= param->table->key_info[pk].key_part;
561
 
    KeyPartInfo *key_part_end= key_part +
 
2076
    KEY_PART_INFO *key_part= param->table->key_info[pk].key_part;
 
2077
    KEY_PART_INFO *key_part_end= key_part +
562
2078
                                 param->table->key_info[pk].key_parts;
563
2079
    for (;key_part != key_part_end; ++key_part)
564
 
      param->needed_fields.reset(key_part->fieldnr-1);
 
2080
      bitmap_clear_bit(&param->needed_fields, key_part->fieldnr-1);
565
2081
  }
566
2082
  return 0;
567
2083
}
571
2087
  Test if a key can be used in different ranges
572
2088
 
573
2089
  SYNOPSIS
574
 
    SqlSelect::test_quick_select()
 
2090
    SQL_SELECT::test_quick_select()
575
2091
      session               Current thread
576
2092
      keys_to_use       Keys to use for range retrieval
577
2093
      prev_tables       Tables assumed to be already read when the scan is
592
2108
 
593
2109
  IMPLEMENTATION
594
2110
    quick_condition_rows value is obtained as follows:
595
 
 
 
2111
      
596
2112
      It is a minimum of E(#output rows) for all considered table access
597
2113
      methods (range and index_merge accesses over various indexes).
598
 
 
 
2114
    
599
2115
    The obtained value is not a true E(#rows that satisfy table condition)
600
2116
    but rather a pessimistic estimate. To obtain a true E(#...) one would
601
2117
    need to combine estimates of various access methods, taking into account
602
2118
    correlations between sets of rows they will return.
603
 
 
 
2119
    
604
2120
    For example, if values of tbl.key1 and tbl.key2 are independent (a right
605
2121
    assumption if we have no information about their correlation) then the
606
2122
    correct estimate will be:
607
 
 
608
 
      E(#rows("tbl.key1 < c1 AND tbl.key2 < c2")) =
 
2123
    
 
2124
      E(#rows("tbl.key1 < c1 AND tbl.key2 < c2")) = 
609
2125
      = E(#rows(tbl.key1 < c1)) / total_rows(tbl) * E(#rows(tbl.key2 < c2)
610
2126
 
611
 
    which is smaller than
612
 
 
 
2127
    which is smaller than 
 
2128
      
613
2129
       MIN(E(#rows(tbl.key1 < c1), E(#rows(tbl.key2 < c2)))
614
2130
 
615
2131
    which is currently produced.
616
2132
 
617
2133
  TODO
618
2134
   * Change the value returned in quick_condition_rows from a pessimistic
619
 
     estimate to true E(#rows that satisfy table condition).
620
 
     (we can re-use some of E(#rows) calcuation code from index_merge/intersection
 
2135
     estimate to true E(#rows that satisfy table condition). 
 
2136
     (we can re-use some of E(#rows) calcuation code from index_merge/intersection 
621
2137
      for this)
622
 
 
 
2138
   
623
2139
   * Check if this function really needs to modify keys_to_use, and change the
624
2140
     code to pass it by reference if it doesn't.
625
2141
 
633
2149
    1 if found usable ranges and quick select has been successfully created.
634
2150
*/
635
2151
 
636
 
int optimizer::SqlSelect::test_quick_select(Session *session,
637
 
                                            key_map keys_to_use,
638
 
                                                                    table_map prev_tables,
639
 
                                                                    ha_rows limit,
640
 
                                            bool force_quick_range,
641
 
                                            bool ordered_output)
 
2152
int SQL_SELECT::test_quick_select(Session *session, key_map keys_to_use,
 
2153
                                  table_map prev_tables,
 
2154
                                  ha_rows limit, bool force_quick_range, 
 
2155
                                  bool ordered_output)
642
2156
{
643
2157
  uint32_t idx;
644
2158
  double scan_time;
645
 
  if (quick)
646
 
  {
647
 
    delete quick;
648
 
    quick= NULL;
649
 
  }
650
 
  needed_reg.reset();
651
 
  quick_keys.reset();
652
 
  if (keys_to_use.none())
653
 
    return 0;
654
 
  records= head->cursor->stats.records;
 
2159
  delete quick;
 
2160
  quick=0;
 
2161
  needed_reg.clear_all();
 
2162
  quick_keys.clear_all();
 
2163
  if (keys_to_use.is_clear_all())
 
2164
    return(0);
 
2165
  records= head->file->stats.records;
655
2166
  if (!records)
656
 
    records++;
 
2167
    records++;                                  /* purecov: inspected */
657
2168
  scan_time= (double) records / TIME_FOR_COMPARE + 1;
658
 
  read_time= (double) head->cursor->scan_time() + scan_time + 1.1;
 
2169
  read_time= (double) head->file->scan_time() + scan_time + 1.1;
659
2170
  if (head->force_index)
660
2171
    scan_time= read_time= DBL_MAX;
661
2172
  if (limit < records)
662
2173
    read_time= (double) records + scan_time + 1; // Force to use index
663
2174
  else if (read_time <= 2.0 && !force_quick_range)
664
 
    return 0;                           /* No need for quick select */
 
2175
    return(0);                          /* No need for quick select */
665
2176
 
666
 
  keys_to_use&= head->keys_in_use_for_query;
667
 
  if (keys_to_use.any())
 
2177
  keys_to_use.intersect(head->keys_in_use_for_query);
 
2178
  if (!keys_to_use.is_clear_all())
668
2179
  {
669
 
    memory::Root alloc;
670
 
    optimizer::SEL_TREE *tree= NULL;
 
2180
    MEM_ROOT alloc;
 
2181
    SEL_TREE *tree= NULL;
671
2182
    KEY_PART *key_parts;
672
 
    KeyInfo *key_info;
673
 
    optimizer::Parameter param;
 
2183
    KEY *key_info;
 
2184
    PARAM param;
674
2185
 
675
2186
    if (check_stack_overrun(session, 2*STACK_MIN_SIZE, NULL))
676
 
      return 0;                           // Fatal error flag is set
 
2187
      return(0);                           // Fatal error flag is set
677
2188
 
678
2189
    /* set up parameter that is passed to all functions */
679
2190
    param.session= session;
680
 
    param.prev_tables= prev_tables | const_tables;
681
 
    param.read_tables= read_tables;
 
2191
    param.baseflag= head->file->ha_table_flags();
 
2192
    param.prev_tables=prev_tables | const_tables;
 
2193
    param.read_tables=read_tables;
682
2194
    param.current_table= head->map;
683
2195
    param.table=head;
684
2196
    param.keys=0;
691
2203
    param.force_default_mrr= ordered_output;
692
2204
 
693
2205
    session->no_errors=1;                               // Don't warn about NULL
694
 
    memory::init_sql_alloc(&alloc, session->variables.range_alloc_block_size, 0);
695
 
    if (!(param.key_parts= (KEY_PART*) alloc.alloc_root( sizeof(KEY_PART) * head->getShare()->key_parts)) ||
 
2206
    init_sql_alloc(&alloc, session->variables.range_alloc_block_size, 0);
 
2207
    if (!(param.key_parts= (KEY_PART*) alloc_root(&alloc,
 
2208
                                                  sizeof(KEY_PART)*
 
2209
                                                  head->s->key_parts)) ||
696
2210
        fill_used_fields_bitmap(&param))
697
2211
    {
698
2212
      session->no_errors=0;
699
 
      alloc.free_root(MYF(0));                  // Return memory & allocator
700
 
 
701
 
      return 0;                         // Can't use range
 
2213
      free_root(&alloc,MYF(0));                 // Return memory & allocator
 
2214
      return(0);                                // Can't use range
702
2215
    }
703
2216
    key_parts= param.key_parts;
704
2217
    session->mem_root= &alloc;
708
2221
      This is used in get_mm_parts function.
709
2222
    */
710
2223
    key_info= head->key_info;
711
 
    for (idx=0 ; idx < head->getShare()->sizeKeys() ; idx++, key_info++)
 
2224
    for (idx=0 ; idx < head->s->keys ; idx++, key_info++)
712
2225
    {
713
 
      KeyPartInfo *key_part_info;
714
 
      if (! keys_to_use.test(idx))
 
2226
      KEY_PART_INFO *key_part_info;
 
2227
      if (!keys_to_use.is_set(idx))
715
2228
        continue;
716
2229
 
717
2230
      param.key[param.keys]=key_parts;
718
2231
      key_part_info= key_info->key_part;
719
 
      for (uint32_t part=0;
720
 
           part < key_info->key_parts;
721
 
           part++, key_parts++, key_part_info++)
 
2232
      for (uint32_t part=0 ; part < key_info->key_parts ;
 
2233
           part++, key_parts++, key_part_info++)
722
2234
      {
723
 
        key_parts->key= param.keys;
724
 
        key_parts->part= part;
725
 
        key_parts->length= key_part_info->length;
726
 
        key_parts->store_length= key_part_info->store_length;
727
 
        key_parts->field= key_part_info->field;
728
 
        key_parts->null_bit= key_part_info->null_bit;
 
2235
        key_parts->key=          param.keys;
 
2236
        key_parts->part=         part;
 
2237
        key_parts->length=       key_part_info->length;
 
2238
        key_parts->store_length= key_part_info->store_length;
 
2239
        key_parts->field=        key_part_info->field;
 
2240
        key_parts->null_bit=     key_part_info->null_bit;
 
2241
        key_parts->image_type =  Field::itRAW;
729
2242
        /* Only HA_PART_KEY_SEG is used */
730
 
        key_parts->flag= (uint8_t) key_part_info->key_part_flag;
 
2243
        key_parts->flag=         (uint8_t) key_part_info->key_part_flag;
731
2244
      }
732
2245
      param.real_keynr[param.keys++]=idx;
733
2246
    }
735
2248
    param.alloced_sel_args= 0;
736
2249
 
737
2250
    /* Calculate cost of full index read for the shortest covering index */
738
 
    if (!head->covering_keys.none())
 
2251
    if (!head->covering_keys.is_clear_all())
739
2252
    {
740
2253
      int key_for_use= head->find_shortest_key(&head->covering_keys);
741
 
      double key_read_time=
742
 
        param.table->cursor->index_only_read_time(key_for_use,
 
2254
      double key_read_time= 
 
2255
        param.table->file->index_only_read_time(key_for_use, 
743
2256
                                                rows2double(records)) +
744
2257
        (double) records / TIME_FOR_COMPARE;
745
2258
      if (key_read_time < read_time)
746
2259
        read_time= key_read_time;
747
2260
    }
748
2261
 
749
 
    optimizer::TableReadPlan *best_trp= NULL;
750
 
    optimizer::GroupMinMaxReadPlan *group_trp= NULL;
 
2262
    TABLE_READ_PLAN *best_trp= NULL;
 
2263
    TRP_GROUP_MIN_MAX *group_trp;
751
2264
    double best_read_time= read_time;
752
2265
 
753
2266
    if (cond)
754
2267
    {
755
2268
      if ((tree= get_mm_tree(&param,cond)))
756
2269
      {
757
 
        if (tree->type == optimizer::SEL_TREE::IMPOSSIBLE)
 
2270
        if (tree->type == SEL_TREE::IMPOSSIBLE)
758
2271
        {
759
2272
          records=0L;                      /* Return -1 from this function. */
760
2273
          read_time= (double) HA_POS_ERROR;
764
2277
          If the tree can't be used for range scans, proceed anyway, as we
765
2278
          can construct a group-min-max quick select
766
2279
        */
767
 
        if (tree->type != optimizer::SEL_TREE::KEY && tree->type != optimizer::SEL_TREE::KEY_SMALLER)
 
2280
        if (tree->type != SEL_TREE::KEY && tree->type != SEL_TREE::KEY_SMALLER)
768
2281
          tree= NULL;
769
2282
      }
770
2283
    }
771
2284
 
772
2285
    /*
773
 
      Try to construct a QuickGroupMinMaxSelect.
 
2286
      Try to construct a QUICK_GROUP_MIN_MAX_SELECT.
774
2287
      Notice that it can be constructed no matter if there is a range tree.
775
2288
    */
776
2289
    group_trp= get_best_group_min_max(&param, tree);
777
2290
    if (group_trp)
778
2291
    {
779
 
      param.table->quick_condition_rows= min(group_trp->records,
780
 
                                             head->cursor->stats.records);
 
2292
      param.table->quick_condition_rows= cmin(group_trp->records,
 
2293
                                             head->file->stats.records);
781
2294
      if (group_trp->read_cost < best_read_time)
782
2295
      {
783
2296
        best_trp= group_trp;
793
2306
      */
794
2307
      if (tree->merges.is_empty())
795
2308
      {
796
 
        optimizer::RangeReadPlan *range_trp= NULL;
797
 
        optimizer::RorIntersectReadPlan *rori_trp= NULL;
 
2309
        TRP_RANGE         *range_trp;
 
2310
        TRP_ROR_INTERSECT *rori_trp;
798
2311
        bool can_build_covering= false;
799
2312
 
800
2313
        /* Get best 'range' plan and prepare data for making other plans */
801
 
        if ((range_trp= get_key_scans_params(session, &param, tree, false, true,
 
2314
        if ((range_trp= get_key_scans_params(&param, tree, false, true,
802
2315
                                             best_read_time)))
803
2316
        {
804
2317
          best_trp= range_trp;
806
2319
        }
807
2320
 
808
2321
        /*
809
 
          Simultaneous key scans and row deletes on several Cursor
 
2322
          Simultaneous key scans and row deletes on several handler
810
2323
          objects are not allowed so don't use ROR-intersection for
811
2324
          table deletes.
812
2325
        */
835
2348
      else
836
2349
      {
837
2350
        /* Try creating index_merge/ROR-union scan. */
838
 
        optimizer::SEL_IMERGE *imerge= NULL;
839
 
        optimizer::TableReadPlan *best_conj_trp= NULL;
840
 
        optimizer::TableReadPlan *new_conj_trp= NULL;
841
 
        List_iterator_fast<optimizer::SEL_IMERGE> it(tree->merges);
 
2351
        SEL_IMERGE *imerge;
 
2352
        TABLE_READ_PLAN *best_conj_trp= NULL, *new_conj_trp;
 
2353
        List_iterator_fast<SEL_IMERGE> it(tree->merges);
842
2354
        while ((imerge= it++))
843
2355
        {
844
 
          new_conj_trp= get_best_disjunct_quick(session, &param, imerge, best_read_time);
 
2356
          new_conj_trp= get_best_disjunct_quick(&param, imerge, best_read_time);
845
2357
          if (new_conj_trp)
846
 
            set_if_smaller(param.table->quick_condition_rows,
 
2358
            set_if_smaller(param.table->quick_condition_rows, 
847
2359
                           new_conj_trp->records);
848
2360
          if (!best_conj_trp || (new_conj_trp && new_conj_trp->read_cost <
849
2361
                                 best_conj_trp->read_cost))
860
2372
    if (best_trp)
861
2373
    {
862
2374
      records= best_trp->records;
863
 
      if (! (quick= best_trp->make_quick(&param, true)) || quick->init())
 
2375
      if (!(quick= best_trp->make_quick(&param, true)) || quick->init())
864
2376
      {
865
 
        /* quick can already be free here */
866
 
        if (quick)
867
 
        {
868
 
          delete quick;
869
 
          quick= NULL;
870
 
        }
 
2377
        delete quick;
 
2378
        quick= NULL;
871
2379
      }
872
2380
    }
873
2381
 
874
2382
  free_mem:
875
 
    alloc.free_root(MYF(0));                    // Return memory & allocator
 
2383
    free_root(&alloc,MYF(0));                   // Return memory & allocator
876
2384
    session->mem_root= param.old_root;
877
2385
    session->no_errors=0;
878
2386
  }
885
2393
}
886
2394
 
887
2395
/*
888
 
  Get best plan for a optimizer::SEL_IMERGE disjunctive expression.
 
2396
  Get best plan for a SEL_IMERGE disjunctive expression.
889
2397
  SYNOPSIS
890
2398
    get_best_disjunct_quick()
891
 
      session
892
2399
      param     Parameter from check_quick_select function
893
2400
      imerge    Expression to use
894
2401
      read_time Don't create scans with cost > read_time
912
2419
          {cost of ordinary clustered PK scan with n_ranges=n_rows}
913
2420
 
914
2421
      Otherwise, we use the following model to calculate costs:
915
 
      We need to retrieve n_rows rows from cursor that occupies n_blocks blocks.
 
2422
      We need to retrieve n_rows rows from file that occupies n_blocks blocks.
916
2423
      We assume that offsets of rows we need are independent variates with
917
2424
      uniform distribution in [0..max_file_offset] range.
918
2425
 
920
2427
      and "empty" if doesn't contain rows we need.
921
2428
 
922
2429
      Probability that a block is empty is (1 - 1/n_blocks)^n_rows (this
923
 
      applies to any block in cursor). Let x_i be a variate taking value 1 if
 
2430
      applies to any block in file). Let x_i be a variate taking value 1 if
924
2431
      block #i is empty and 0 otherwise.
925
2432
 
926
2433
      Then E(x_i) = (1 - 1/n_blocks)^n_rows;
951
2458
*/
952
2459
 
953
2460
static
954
 
optimizer::TableReadPlan *get_best_disjunct_quick(Session *session,
955
 
                                                  optimizer::Parameter *param,
956
 
                                                  optimizer::SEL_IMERGE *imerge,
957
 
                                                  double read_time)
 
2461
TABLE_READ_PLAN *get_best_disjunct_quick(PARAM *param, SEL_IMERGE *imerge,
 
2462
                                         double read_time)
958
2463
{
959
 
  optimizer::SEL_TREE **ptree= NULL;
960
 
  optimizer::IndexMergeReadPlan *imerge_trp= NULL;
 
2464
  SEL_TREE **ptree;
 
2465
  TRP_INDEX_MERGE *imerge_trp= NULL;
961
2466
  uint32_t n_child_scans= imerge->trees_next - imerge->trees;
962
 
  optimizer::RangeReadPlan **range_scans= NULL;
963
 
  optimizer::RangeReadPlan **cur_child= NULL;
964
 
  optimizer::RangeReadPlan **cpk_scan= NULL;
 
2467
  TRP_RANGE **range_scans;
 
2468
  TRP_RANGE **cur_child;
 
2469
  TRP_RANGE **cpk_scan= NULL;
965
2470
  bool imerge_too_expensive= false;
966
2471
  double imerge_cost= 0.0;
967
2472
  ha_rows cpk_scan_records= 0;
968
2473
  ha_rows non_cpk_scan_records= 0;
969
 
  bool pk_is_clustered= param->table->cursor->primary_key_is_clustered();
 
2474
  bool pk_is_clustered= param->table->file->primary_key_is_clustered();
970
2475
  bool all_scans_ror_able= true;
971
2476
  bool all_scans_rors= true;
972
2477
  uint32_t unique_calc_buff_size;
973
 
  optimizer::TableReadPlan **roru_read_plans= NULL;
974
 
  optimizer::TableReadPlan **cur_roru_plan= NULL;
 
2478
  TABLE_READ_PLAN **roru_read_plans;
 
2479
  TABLE_READ_PLAN **cur_roru_plan;
975
2480
  double roru_index_costs;
976
2481
  ha_rows roru_total_records;
977
2482
  double roru_intersect_part= 1.0;
978
2483
 
979
 
  if (! (range_scans= (optimizer::RangeReadPlan**)param->mem_root->alloc_root(sizeof(optimizer::RangeReadPlan*)* n_child_scans)))
980
 
  {
981
 
    return NULL;
982
 
  }
983
 
 
 
2484
  if (!(range_scans= (TRP_RANGE**)alloc_root(param->mem_root,
 
2485
                                             sizeof(TRP_RANGE*)*
 
2486
                                             n_child_scans)))
 
2487
    return(NULL);
984
2488
  /*
985
2489
    Collect best 'range' scan for each of disjuncts, and, while doing so,
986
2490
    analyze possibility of ROR scans. Also calculate some values needed by
990
2494
       ptree != imerge->trees_next;
991
2495
       ptree++, cur_child++)
992
2496
  {
993
 
    if (!(*cur_child= get_key_scans_params(session, param, *ptree, true, false, read_time)))
 
2497
    print_sel_tree(param, *ptree, &(*ptree)->keys_map, "tree in SEL_IMERGE");
 
2498
    if (!(*cur_child= get_key_scans_params(param, *ptree, true, false, read_time)))
994
2499
    {
995
2500
      /*
996
2501
        One of index scans in this index_merge is more expensive than entire
997
2502
        table read for another available option. The entire index_merge (and
998
2503
        any possible ROR-union) will be more expensive then, too. We continue
999
 
        here only to update SqlSelect members.
 
2504
        here only to update SQL_SELECT members.
1000
2505
      */
1001
2506
      imerge_too_expensive= true;
1002
2507
    }
1008
2513
    all_scans_rors &= (*cur_child)->is_ror;
1009
2514
    if (pk_is_clustered &&
1010
2515
        param->real_keynr[(*cur_child)->key_idx] ==
1011
 
        param->table->getShare()->getPrimaryKey())
 
2516
        param->table->s->primary_key)
1012
2517
    {
1013
2518
      cpk_scan= cur_child;
1014
2519
      cpk_scan_records= (*cur_child)->records;
1018
2523
  }
1019
2524
 
1020
2525
  if (imerge_too_expensive || (imerge_cost > read_time) ||
1021
 
      ((non_cpk_scan_records+cpk_scan_records >= param->table->cursor->stats.records) && read_time != DBL_MAX))
 
2526
      ((non_cpk_scan_records+cpk_scan_records >= param->table->file->stats.records) && read_time != DBL_MAX))
1022
2527
  {
1023
2528
    /*
1024
2529
      Bail out if it is obvious that both index_merge and ROR-union will be
1025
2530
      more expensive
1026
2531
    */
1027
 
    return NULL;
 
2532
    return(NULL);
1028
2533
  }
1029
2534
  if (all_scans_rors)
1030
2535
  {
1031
 
    roru_read_plans= (optimizer::TableReadPlan **) range_scans;
 
2536
    roru_read_plans= (TABLE_READ_PLAN**)range_scans;
1032
2537
    goto skip_to_ror_scan;
1033
2538
  }
1034
2539
  if (cpk_scan)
1035
2540
  {
1036
2541
    /*
1037
2542
      Add one ROWID comparison for each row retrieved on non-CPK scan.  (it
1038
 
      is done in QuickRangeSelect::row_in_ranges)
 
2543
      is done in QUICK_RANGE_SELECT::row_in_ranges)
1039
2544
     */
1040
2545
    imerge_cost += non_cpk_scan_records / TIME_FOR_COMPARE_ROWID;
1041
2546
  }
1042
2547
 
1043
2548
  /* Calculate cost(rowid_to_row_scan) */
1044
2549
  {
1045
 
    optimizer::CostVector sweep_cost;
1046
 
    Join *join= param->session->lex->select_lex.join;
 
2550
    COST_VECT sweep_cost;
 
2551
    JOIN *join= param->session->lex->select_lex.join;
1047
2552
    bool is_interrupted= test(join && join->tables == 1);
1048
2553
    get_sweep_read_cost(param->table, non_cpk_scan_records, is_interrupted,
1049
2554
                        &sweep_cost);
1055
2560
  /* Add Unique operations cost */
1056
2561
  unique_calc_buff_size=
1057
2562
    Unique::get_cost_calc_buff_size((ulong)non_cpk_scan_records,
1058
 
                                    param->table->cursor->ref_length,
 
2563
                                    param->table->file->ref_length,
1059
2564
                                    param->session->variables.sortbuff_size);
1060
2565
  if (param->imerge_cost_buff_size < unique_calc_buff_size)
1061
2566
  {
1062
 
    if (!(param->imerge_cost_buff= (uint*)param->mem_root->alloc_root(unique_calc_buff_size)))
1063
 
    {
1064
 
      return NULL;
1065
 
    }
1066
 
 
 
2567
    if (!(param->imerge_cost_buff= (uint*)alloc_root(param->mem_root,
 
2568
                                                     unique_calc_buff_size)))
 
2569
      return(NULL);
1067
2570
    param->imerge_cost_buff_size= unique_calc_buff_size;
1068
2571
  }
1069
2572
 
1070
2573
  imerge_cost +=
1071
 
    Unique::get_use_cost(param->imerge_cost_buff, (uint32_t)non_cpk_scan_records,
1072
 
                         param->table->cursor->ref_length,
 
2574
    Unique::get_use_cost(param->imerge_cost_buff, (uint)non_cpk_scan_records,
 
2575
                         param->table->file->ref_length,
1073
2576
                         param->session->variables.sortbuff_size);
1074
2577
  if (imerge_cost < read_time)
1075
2578
  {
1076
 
    if ((imerge_trp= new (param->mem_root) optimizer::IndexMergeReadPlan))
 
2579
    if ((imerge_trp= new (param->mem_root)TRP_INDEX_MERGE))
1077
2580
    {
1078
2581
      imerge_trp->read_cost= imerge_cost;
1079
2582
      imerge_trp->records= non_cpk_scan_records + cpk_scan_records;
1080
 
      imerge_trp->records= min(imerge_trp->records,
1081
 
                               param->table->cursor->stats.records);
 
2583
      imerge_trp->records= cmin(imerge_trp->records,
 
2584
                               param->table->file->stats.records);
1082
2585
      imerge_trp->range_scans= range_scans;
1083
2586
      imerge_trp->range_scans_end= range_scans + n_child_scans;
1084
2587
      read_time= imerge_cost;
1091
2594
 
1092
2595
  /* Ok, it is possible to build a ROR-union, try it. */
1093
2596
  bool dummy;
1094
 
  if (! (roru_read_plans=
1095
 
          (optimizer::TableReadPlan **) param->mem_root->alloc_root(sizeof(optimizer::TableReadPlan*) * n_child_scans)))
1096
 
  {
1097
 
    return imerge_trp;
1098
 
  }
 
2597
  if (!(roru_read_plans=
 
2598
          (TABLE_READ_PLAN**)alloc_root(param->mem_root,
 
2599
                                        sizeof(TABLE_READ_PLAN*)*
 
2600
                                        n_child_scans)))
 
2601
    return(imerge_trp);
1099
2602
skip_to_ror_scan:
1100
2603
  roru_index_costs= 0.0;
1101
2604
  roru_total_records= 0;
1116
2619
    if ((*cur_child)->is_ror)
1117
2620
    {
1118
2621
      /* Ok, we have index_only cost, now get full rows scan cost */
1119
 
      cost= param->table->cursor->
 
2622
      cost= param->table->file->
1120
2623
              read_time(param->real_keynr[(*cur_child)->key_idx], 1,
1121
2624
                        (*cur_child)->records) +
1122
2625
              rows2double((*cur_child)->records) / TIME_FOR_COMPARE;
1124
2627
    else
1125
2628
      cost= read_time;
1126
2629
 
1127
 
    optimizer::TableReadPlan *prev_plan= *cur_child;
 
2630
    TABLE_READ_PLAN *prev_plan= *cur_child;
1128
2631
    if (!(*cur_roru_plan= get_best_ror_intersect(param, *ptree, cost,
1129
2632
                                                 &dummy)))
1130
2633
    {
1136
2639
    }
1137
2640
    else
1138
2641
      roru_index_costs +=
1139
 
        ((optimizer::RorIntersectReadPlan*)(*cur_roru_plan))->index_scan_costs;
 
2642
        ((TRP_ROR_INTERSECT*)(*cur_roru_plan))->index_scan_costs;
1140
2643
    roru_total_records += (*cur_roru_plan)->records;
1141
2644
    roru_intersect_part *= (*cur_roru_plan)->records /
1142
 
                           param->table->cursor->stats.records;
 
2645
                           param->table->file->stats.records;
1143
2646
  }
1144
2647
 
1145
2648
  /*
1149
2652
    in disjunction do not share key parts.
1150
2653
  */
1151
2654
  roru_total_records -= (ha_rows)(roru_intersect_part*
1152
 
                                  param->table->cursor->stats.records);
 
2655
                                  param->table->file->stats.records);
1153
2656
  /* ok, got a ROR read plan for each of the disjuncts
1154
2657
    Calculate cost:
1155
2658
    cost(index_union_scan(scan_1, ... scan_n)) =
1160
2663
  */
1161
2664
  double roru_total_cost;
1162
2665
  {
1163
 
    optimizer::CostVector sweep_cost;
1164
 
    Join *join= param->session->lex->select_lex.join;
 
2666
    COST_VECT sweep_cost;
 
2667
    JOIN *join= param->session->lex->select_lex.join;
1165
2668
    bool is_interrupted= test(join && join->tables == 1);
1166
2669
    get_sweep_read_cost(param->table, roru_total_records, is_interrupted,
1167
2670
                        &sweep_cost);
1171
2674
                     sweep_cost.total_cost();
1172
2675
  }
1173
2676
 
1174
 
  optimizer::RorUnionReadPlan *roru= NULL;
 
2677
  TRP_ROR_UNION* roru;
1175
2678
  if (roru_total_cost < read_time)
1176
2679
  {
1177
 
    if ((roru= new (param->mem_root) optimizer::RorUnionReadPlan))
 
2680
    if ((roru= new (param->mem_root) TRP_ROR_UNION))
1178
2681
    {
1179
2682
      roru->first_ror= roru_read_plans;
1180
2683
      roru->last_ror= roru_read_plans + n_child_scans;
1181
2684
      roru->read_cost= roru_total_cost;
1182
2685
      roru->records= roru_total_records;
1183
 
      return roru;
 
2686
      return(roru);
1184
2687
    }
1185
2688
  }
1186
2689
  return(imerge_trp);
1187
2690
}
1188
2691
 
1189
2692
 
 
2693
typedef struct st_ror_scan_info
 
2694
{
 
2695
  uint32_t      idx;      /* # of used key in param->keys */
 
2696
  uint32_t      keynr;    /* # of used key in table */
 
2697
  ha_rows   records;  /* estimate of # records this scan will return */
 
2698
 
 
2699
  /* Set of intervals over key fields that will be used for row retrieval. */
 
2700
  SEL_ARG   *sel_arg;
 
2701
 
 
2702
  /* Fields used in the query and covered by this ROR scan. */
 
2703
  MY_BITMAP covered_fields;
 
2704
  uint32_t      used_fields_covered; /* # of set bits in covered_fields */
 
2705
  int       key_rec_length; /* length of key record (including rowid) */
 
2706
 
 
2707
  /*
 
2708
    Cost of reading all index records with values in sel_arg intervals set
 
2709
    (assuming there is no need to access full table records)
 
2710
  */
 
2711
  double    index_read_cost;
 
2712
  uint32_t      first_uncovered_field; /* first unused bit in covered_fields */
 
2713
  uint32_t      key_components; /* # of parts in the key */
 
2714
} ROR_SCAN_INFO;
 
2715
 
1190
2716
 
1191
2717
/*
1192
 
  Create optimizer::RorScanInfo* structure with a single ROR scan on index idx using
 
2718
  Create ROR_SCAN_INFO* structure with a single ROR scan on index idx using
1193
2719
  sel_arg set of intervals.
1194
2720
 
1195
2721
  SYNOPSIS
1204
2730
*/
1205
2731
 
1206
2732
static
1207
 
optimizer::RorScanInfo *make_ror_scan(const optimizer::Parameter *param, int idx, optimizer::SEL_ARG *sel_arg)
 
2733
ROR_SCAN_INFO *make_ror_scan(const PARAM *param, int idx, SEL_ARG *sel_arg)
1208
2734
{
1209
 
  optimizer::RorScanInfo *ror_scan= NULL;
1210
 
 
 
2735
  ROR_SCAN_INFO *ror_scan;
 
2736
  my_bitmap_map *bitmap_buf;
1211
2737
  uint32_t keynr;
1212
2738
 
1213
 
  if (!(ror_scan= (optimizer::RorScanInfo*)param->mem_root->alloc_root(sizeof(optimizer::RorScanInfo))))
1214
 
    return NULL;
 
2739
  if (!(ror_scan= (ROR_SCAN_INFO*)alloc_root(param->mem_root,
 
2740
                                             sizeof(ROR_SCAN_INFO))))
 
2741
    return(NULL);
1215
2742
 
1216
2743
  ror_scan->idx= idx;
1217
2744
  ror_scan->keynr= keynr= param->real_keynr[idx];
1218
2745
  ror_scan->key_rec_length= (param->table->key_info[keynr].key_length +
1219
 
                             param->table->cursor->ref_length);
 
2746
                             param->table->file->ref_length);
1220
2747
  ror_scan->sel_arg= sel_arg;
1221
2748
  ror_scan->records= param->table->quick_rows[keynr];
1222
2749
 
1223
 
  ror_scan->covered_fields_size= param->table->getShare()->sizeFields();
1224
 
  boost::dynamic_bitset<> tmp_bitset(param->table->getShare()->sizeFields());
1225
 
  tmp_bitset.reset();
1226
 
 
1227
 
  KeyPartInfo *key_part= param->table->key_info[keynr].key_part;
1228
 
  KeyPartInfo *key_part_end= key_part +
 
2750
  if (!(bitmap_buf= (my_bitmap_map*) alloc_root(param->mem_root,
 
2751
                                                param->fields_bitmap_size)))
 
2752
    return(NULL);
 
2753
 
 
2754
  if (bitmap_init(&ror_scan->covered_fields, bitmap_buf,
 
2755
                  param->table->s->fields, false))
 
2756
    return(NULL);
 
2757
  bitmap_clear_all(&ror_scan->covered_fields);
 
2758
 
 
2759
  KEY_PART_INFO *key_part= param->table->key_info[keynr].key_part;
 
2760
  KEY_PART_INFO *key_part_end= key_part +
1229
2761
                               param->table->key_info[keynr].key_parts;
1230
 
  for (; key_part != key_part_end; ++key_part)
 
2762
  for (;key_part != key_part_end; ++key_part)
1231
2763
  {
1232
 
    if (param->needed_fields.test(key_part->fieldnr-1))
1233
 
      tmp_bitset.set(key_part->fieldnr-1);
 
2764
    if (bitmap_is_set(&param->needed_fields, key_part->fieldnr-1))
 
2765
      bitmap_set_bit(&ror_scan->covered_fields, key_part->fieldnr-1);
1234
2766
  }
1235
2767
  double rows= rows2double(param->table->quick_rows[ror_scan->keynr]);
1236
2768
  ror_scan->index_read_cost=
1237
 
    param->table->cursor->index_only_read_time(ror_scan->keynr, rows);
1238
 
  ror_scan->covered_fields= tmp_bitset.to_ulong();
1239
 
  return ror_scan;
 
2769
    param->table->file->index_only_read_time(ror_scan->keynr, rows);
 
2770
  return(ror_scan);
1240
2771
}
1241
2772
 
1242
2773
 
1243
2774
/*
1244
 
  Compare two optimizer::RorScanInfo** by  E(#records_matched) * key_record_length.
 
2775
  Compare two ROR_SCAN_INFO** by  E(#records_matched) * key_record_length.
1245
2776
  SYNOPSIS
1246
2777
    cmp_ror_scan_info()
1247
2778
      a ptr to first compared value
1253
2784
    1 a > b
1254
2785
*/
1255
2786
 
1256
 
static int cmp_ror_scan_info(optimizer::RorScanInfo** a, optimizer::RorScanInfo** b)
 
2787
static int cmp_ror_scan_info(ROR_SCAN_INFO** a, ROR_SCAN_INFO** b)
1257
2788
{
1258
2789
  double val1= rows2double((*a)->records) * (*a)->key_rec_length;
1259
2790
  double val2= rows2double((*b)->records) * (*b)->key_rec_length;
1260
2791
  return (val1 < val2)? -1: (val1 == val2)? 0 : 1;
1261
2792
}
1262
2793
 
1263
 
 
1264
2794
/*
1265
 
  Compare two optimizer::RorScanInfo** by
 
2795
  Compare two ROR_SCAN_INFO** by
1266
2796
   (#covered fields in F desc,
1267
2797
    #components asc,
1268
2798
    number of first not covered component asc)
1278
2808
    1 a > b
1279
2809
*/
1280
2810
 
1281
 
static int cmp_ror_scan_info_covering(optimizer::RorScanInfo** a, optimizer::RorScanInfo** b)
 
2811
static int cmp_ror_scan_info_covering(ROR_SCAN_INFO** a, ROR_SCAN_INFO** b)
1282
2812
{
1283
2813
  if ((*a)->used_fields_covered > (*b)->used_fields_covered)
1284
2814
    return -1;
1295
2825
  return 0;
1296
2826
}
1297
2827
 
 
2828
 
1298
2829
/* Auxiliary structure for incremental ROR-intersection creation */
1299
 
typedef struct st_ror_intersect_info
 
2830
typedef struct
1300
2831
{
1301
 
  st_ror_intersect_info()
1302
 
    :
1303
 
      param(NULL),
1304
 
      covered_fields(),
1305
 
      out_rows(0.0),
1306
 
      is_covering(false),
1307
 
      index_records(0),
1308
 
      index_scan_costs(0.0),
1309
 
      total_cost(0.0)
1310
 
  {}
1311
 
 
1312
 
  st_ror_intersect_info(const optimizer::Parameter *in_param)
1313
 
    :
1314
 
      param(in_param),
1315
 
      covered_fields(in_param->table->getShare()->sizeFields()),
1316
 
      out_rows(in_param->table->cursor->stats.records),
1317
 
      is_covering(false),
1318
 
      index_records(0),
1319
 
      index_scan_costs(0.0),
1320
 
      total_cost(0.0)
1321
 
  {
1322
 
    covered_fields.reset();
1323
 
  }
1324
 
 
1325
 
  const optimizer::Parameter *param;
1326
 
  boost::dynamic_bitset<> covered_fields; /* union of fields covered by all scans */
 
2832
  const PARAM *param;
 
2833
  MY_BITMAP covered_fields; /* union of fields covered by all scans */
1327
2834
  /*
1328
2835
    Fraction of table records that satisfies conditions of all scans.
1329
2836
    This is the number of full records that will be retrieved if a
1339
2846
} ROR_INTERSECT_INFO;
1340
2847
 
1341
2848
 
1342
 
static void ror_intersect_cpy(ROR_INTERSECT_INFO *dst,
1343
 
                              const ROR_INTERSECT_INFO *src)
 
2849
/*
 
2850
  Allocate a ROR_INTERSECT_INFO and initialize it to contain zero scans.
 
2851
 
 
2852
  SYNOPSIS
 
2853
    ror_intersect_init()
 
2854
      param         Parameter from test_quick_select
 
2855
 
 
2856
  RETURN
 
2857
    allocated structure
 
2858
    NULL on error
 
2859
*/
 
2860
 
 
2861
static
 
2862
ROR_INTERSECT_INFO* ror_intersect_init(const PARAM *param)
 
2863
{
 
2864
  ROR_INTERSECT_INFO *info;
 
2865
  my_bitmap_map* buf;
 
2866
  if (!(info= (ROR_INTERSECT_INFO*)alloc_root(param->mem_root,
 
2867
                                              sizeof(ROR_INTERSECT_INFO))))
 
2868
    return NULL;
 
2869
  info->param= param;
 
2870
  if (!(buf= (my_bitmap_map*) alloc_root(param->mem_root,
 
2871
                                         param->fields_bitmap_size)))
 
2872
    return NULL;
 
2873
  if (bitmap_init(&info->covered_fields, buf, param->table->s->fields,
 
2874
                  false))
 
2875
    return NULL;
 
2876
  info->is_covering= false;
 
2877
  info->index_scan_costs= 0.0;
 
2878
  info->index_records= 0;
 
2879
  info->out_rows= (double) param->table->file->stats.records;
 
2880
  bitmap_clear_all(&info->covered_fields);
 
2881
  return info;
 
2882
}
 
2883
 
 
2884
void ror_intersect_cpy(ROR_INTERSECT_INFO *dst, const ROR_INTERSECT_INFO *src)
1344
2885
{
1345
2886
  dst->param= src->param;
1346
 
  dst->covered_fields= src->covered_fields;
 
2887
  memcpy(dst->covered_fields.bitmap, src->covered_fields.bitmap, 
 
2888
         no_bytes_in_map(&src->covered_fields));
1347
2889
  dst->out_rows= src->out_rows;
1348
2890
  dst->is_covering= src->is_covering;
1349
2891
  dst->index_records= src->index_records;
1357
2899
 
1358
2900
  SYNOPSIS
1359
2901
    ror_scan_selectivity()
1360
 
      info  ROR-interection
 
2902
      info  ROR-interection 
1361
2903
      scan  ROR scan
1362
 
 
 
2904
      
1363
2905
  NOTES
1364
2906
    Suppose we have a condition on several keys
1365
2907
    cond=k_11=c_11 AND k_12=c_12 AND ...  // parts of first key
1442
2984
    Selectivity of given ROR scan.
1443
2985
*/
1444
2986
 
1445
 
static double ror_scan_selectivity(const ROR_INTERSECT_INFO *info,
1446
 
                                   const optimizer::RorScanInfo *scan)
 
2987
static double ror_scan_selectivity(const ROR_INTERSECT_INFO *info, 
 
2988
                                   const ROR_SCAN_INFO *scan)
1447
2989
{
1448
2990
  double selectivity_mult= 1.0;
1449
 
  KeyPartInfo *key_part= info->param->table->key_info[scan->keynr].key_part;
 
2991
  KEY_PART_INFO *key_part= info->param->table->key_info[scan->keynr].key_part;
1450
2992
  unsigned char key_val[MAX_KEY_LENGTH+MAX_FIELD_WIDTH]; /* key values tuple */
1451
2993
  unsigned char *key_ptr= key_val;
1452
 
  optimizer::SEL_ARG *sel_arg= NULL;
1453
 
  optimizer::SEL_ARG *tuple_arg= NULL;
 
2994
  SEL_ARG *sel_arg, *tuple_arg= NULL;
1454
2995
  key_part_map keypart_map= 0;
1455
2996
  bool cur_covered;
1456
 
  bool prev_covered= test(info->covered_fields.test(key_part->fieldnr-1));
 
2997
  bool prev_covered= test(bitmap_is_set(&info->covered_fields,
 
2998
                                        key_part->fieldnr-1));
1457
2999
  key_range min_range;
1458
3000
  key_range max_range;
1459
3001
  min_range.key= key_val;
1460
3002
  min_range.flag= HA_READ_KEY_EXACT;
1461
3003
  max_range.key= key_val;
1462
3004
  max_range.flag= HA_READ_AFTER_KEY;
1463
 
  ha_rows prev_records= info->param->table->cursor->stats.records;
 
3005
  ha_rows prev_records= info->param->table->file->stats.records;
1464
3006
 
1465
3007
  for (sel_arg= scan->sel_arg; sel_arg;
1466
3008
       sel_arg= sel_arg->next_key_part)
1467
3009
  {
1468
 
    cur_covered=
1469
 
      test(info->covered_fields.test(key_part[sel_arg->part].fieldnr-1));
 
3010
    cur_covered= test(bitmap_is_set(&info->covered_fields,
 
3011
                                    key_part[sel_arg->part].fieldnr-1));
1470
3012
    if (cur_covered != prev_covered)
1471
3013
    {
1472
3014
      /* create (part1val, ..., part{n-1}val) tuple. */
1487
3029
      }
1488
3030
      min_range.length= max_range.length= (size_t) (key_ptr - key_val);
1489
3031
      min_range.keypart_map= max_range.keypart_map= keypart_map;
1490
 
      records= (info->param->table->cursor->
 
3032
      records= (info->param->table->file->
1491
3033
                records_in_range(scan->keynr, &min_range, &max_range));
1492
3034
      if (cur_covered)
1493
3035
      {
1544
3086
 
1545
3087
    E(rows_to_retrieve) = #rows_in_table * ror_scan_selectivity(null, scan1) *
1546
3088
                           ror_scan_selectivity({scan1}, scan2) * ... *
1547
 
                           ror_scan_selectivity({scan1,...}, scanN).
 
3089
                           ror_scan_selectivity({scan1,...}, scanN). 
1548
3090
  RETURN
1549
3091
    true   ROR scan added to ROR-intersection, cost updated.
1550
3092
    false  It doesn't make sense to add this ROR scan to this ROR-intersection.
1551
3093
*/
1552
3094
 
1553
3095
static bool ror_intersect_add(ROR_INTERSECT_INFO *info,
1554
 
                              optimizer::RorScanInfo* ror_scan, bool is_cpk_scan)
 
3096
                              ROR_SCAN_INFO* ror_scan, bool is_cpk_scan)
1555
3097
{
1556
3098
  double selectivity_mult= 1.0;
1557
3099
 
1559
3101
  if (selectivity_mult == 1.0)
1560
3102
  {
1561
3103
    /* Don't add this scan if it doesn't improve selectivity. */
1562
 
    return false;
 
3104
    return(false);
1563
3105
  }
1564
 
 
 
3106
  
1565
3107
  info->out_rows *= selectivity_mult;
1566
 
 
 
3108
  
1567
3109
  if (is_cpk_scan)
1568
3110
  {
1569
3111
    /*
1570
 
      CPK scan is used to filter out rows. We apply filtering for
 
3112
      CPK scan is used to filter out rows. We apply filtering for 
1571
3113
      each record of every scan. Assuming 1/TIME_FOR_COMPARE_ROWID
1572
3114
      per check this gives us:
1573
3115
    */
1574
 
    info->index_scan_costs += rows2double(info->index_records) /
 
3116
    info->index_scan_costs += rows2double(info->index_records) / 
1575
3117
                              TIME_FOR_COMPARE_ROWID;
1576
3118
  }
1577
3119
  else
1578
3120
  {
1579
3121
    info->index_records += info->param->table->quick_rows[ror_scan->keynr];
1580
3122
    info->index_scan_costs += ror_scan->index_read_cost;
1581
 
    boost::dynamic_bitset<> tmp_bitset= ror_scan->bitsToBitset();
1582
 
    info->covered_fields|= tmp_bitset;
1583
 
    if (! info->is_covering && info->param->needed_fields.is_subset_of(info->covered_fields))
 
3123
    bitmap_union(&info->covered_fields, &ror_scan->covered_fields);
 
3124
    if (!info->is_covering && bitmap_is_subset(&info->param->needed_fields,
 
3125
                                               &info->covered_fields))
1584
3126
    {
1585
3127
      info->is_covering= true;
1586
3128
    }
1587
3129
  }
1588
3130
 
1589
3131
  info->total_cost= info->index_scan_costs;
1590
 
  if (! info->is_covering)
 
3132
  if (!info->is_covering)
1591
3133
  {
1592
 
    optimizer::CostVector sweep_cost;
1593
 
    Join *join= info->param->session->lex->select_lex.join;
 
3134
    COST_VECT sweep_cost;
 
3135
    JOIN *join= info->param->session->lex->select_lex.join;
1594
3136
    bool is_interrupted= test(join && join->tables == 1);
1595
3137
    get_sweep_read_cost(info->param->table, double2rows(info->out_rows),
1596
3138
                        is_interrupted, &sweep_cost);
1597
3139
    info->total_cost += sweep_cost.total_cost();
1598
3140
  }
1599
 
  return true;
1600
 
}
1601
 
 
1602
 
 
1603
 
/*
1604
 
  Get best covering ROR-intersection.
1605
 
  SYNOPSIS
1606
 
    get_best_covering_ror_intersect()
1607
 
      param     Parameter from test_quick_select function.
1608
 
      tree      optimizer::SEL_TREE with sets of intervals for different keys.
1609
 
      read_time Don't return table read plans with cost > read_time.
1610
 
 
1611
 
  RETURN
1612
 
    Best covering ROR-intersection plan
1613
 
    NULL if no plan found.
1614
 
 
1615
 
  NOTES
1616
 
    get_best_ror_intersect must be called for a tree before calling this
1617
 
    function for it.
1618
 
    This function invalidates tree->ror_scans member values.
1619
 
 
1620
 
  The following approximate algorithm is used:
1621
 
    I=set of all covering indexes
1622
 
    F=set of all fields to cover
1623
 
    S={}
1624
 
 
1625
 
    do
1626
 
    {
1627
 
      Order I by (#covered fields in F desc,
1628
 
                  #components asc,
1629
 
                  number of first not covered component asc);
1630
 
      F=F-covered by first(I);
1631
 
      S=S+first(I);
1632
 
      I=I-first(I);
1633
 
    } while F is not empty.
1634
 
*/
1635
 
 
1636
 
static
1637
 
optimizer::RorIntersectReadPlan *get_best_covering_ror_intersect(optimizer::Parameter *param,
1638
 
                                                            optimizer::SEL_TREE *tree,
1639
 
                                                            double read_time)
1640
 
{
1641
 
  optimizer::RorScanInfo **ror_scan_mark;
1642
 
  optimizer::RorScanInfo **ror_scans_end= tree->ror_scans_end;
1643
 
 
1644
 
  for (optimizer::RorScanInfo **scan= tree->ror_scans; scan != ror_scans_end; ++scan)
1645
 
    (*scan)->key_components=
1646
 
      param->table->key_info[(*scan)->keynr].key_parts;
1647
 
 
1648
 
  /*
1649
 
    Run covering-ROR-search algorithm.
1650
 
    Assume set I is [ror_scan .. ror_scans_end)
1651
 
  */
1652
 
 
1653
 
  /*I=set of all covering indexes */
1654
 
  ror_scan_mark= tree->ror_scans;
1655
 
 
1656
 
  boost::dynamic_bitset<> *covered_fields= &param->tmp_covered_fields;
1657
 
  if (covered_fields->empty())
1658
 
  {
1659
 
    covered_fields->resize(param->table->getShare()->sizeFields());
1660
 
  }
1661
 
  covered_fields->reset();
1662
 
 
1663
 
  double total_cost= 0.0f;
1664
 
  ha_rows records=0;
1665
 
  bool all_covered;
1666
 
 
1667
 
  do
1668
 
  {
1669
 
    /*
1670
 
      Update changed sorting info:
1671
 
        #covered fields,
1672
 
        number of first not covered component
1673
 
      Calculate and save these values for each of remaining scans.
1674
 
    */
1675
 
    for (optimizer::RorScanInfo **scan= ror_scan_mark; scan != ror_scans_end; ++scan)
1676
 
    {
1677
 
      /* subtract one bitset from the other */
1678
 
      (*scan)->subtractBitset(*covered_fields);
1679
 
      (*scan)->used_fields_covered=
1680
 
        (*scan)->getBitCount();
1681
 
      (*scan)->first_uncovered_field= (*scan)->findFirstNotSet();
1682
 
    }
1683
 
 
1684
 
    internal::my_qsort(ror_scan_mark, ror_scans_end-ror_scan_mark,
1685
 
                       sizeof(optimizer::RorScanInfo*),
1686
 
                       (qsort_cmp)cmp_ror_scan_info_covering);
1687
 
 
1688
 
    /* I=I-first(I) */
1689
 
    total_cost += (*ror_scan_mark)->index_read_cost;
1690
 
    records += (*ror_scan_mark)->records;
1691
 
    if (total_cost > read_time)
1692
 
      return NULL;
1693
 
    /* F=F-covered by first(I) */
1694
 
    boost::dynamic_bitset<> tmp_bitset= (*ror_scan_mark)->bitsToBitset();
1695
 
    *covered_fields|= tmp_bitset;
1696
 
    all_covered= param->needed_fields.is_subset_of(*covered_fields);
1697
 
  } while ((++ror_scan_mark < ror_scans_end) && ! all_covered);
1698
 
 
1699
 
  if (!all_covered || (ror_scan_mark - tree->ror_scans) == 1)
1700
 
    return NULL;
1701
 
 
1702
 
  /*
1703
 
    Ok, [tree->ror_scans .. ror_scan) holds covering index_intersection with
1704
 
    cost total_cost.
1705
 
  */
1706
 
  /* Add priority queue use cost. */
1707
 
  total_cost += rows2double(records)*
1708
 
                log((double)(ror_scan_mark - tree->ror_scans)) /
1709
 
                (TIME_FOR_COMPARE_ROWID * M_LN2);
1710
 
 
1711
 
  if (total_cost > read_time)
1712
 
    return NULL;
1713
 
 
1714
 
  optimizer::RorIntersectReadPlan *trp= NULL;
1715
 
  if (! (trp= new (param->mem_root) optimizer::RorIntersectReadPlan))
1716
 
  {
1717
 
    return trp;
1718
 
  }
1719
 
 
1720
 
  uint32_t best_num= (ror_scan_mark - tree->ror_scans);
1721
 
  if (!(trp->first_scan= (optimizer::RorScanInfo**)param->mem_root->alloc_root(sizeof(optimizer::RorScanInfo*)* best_num)))
1722
 
    return NULL;
1723
 
  memcpy(trp->first_scan, tree->ror_scans, best_num*sizeof(optimizer::RorScanInfo*));
1724
 
  trp->last_scan=  trp->first_scan + best_num;
1725
 
  trp->is_covering= true;
1726
 
  trp->read_cost= total_cost;
1727
 
  trp->records= records;
1728
 
  trp->cpk_scan= NULL;
1729
 
  set_if_smaller(param->table->quick_condition_rows, records);
1730
 
 
1731
 
  return(trp);
 
3141
  return(true);
1732
3142
}
1733
3143
 
1734
3144
 
1748
3158
 
1749
3159
  NOTES
1750
3160
    get_key_scans_params must be called before this function can be called.
1751
 
 
 
3161
    
1752
3162
    When this function is called by ROR-union construction algorithm it
1753
3163
    assumes it is building an uncovered ROR-intersection (and thus # of full
1754
3164
    records to be retrieved is wrong here). This is a hack.
1770
3180
        firstR= R - first(R);
1771
3181
        if (!selectivity(S + firstR < selectivity(S)))
1772
3182
          continue;
1773
 
 
 
3183
          
1774
3184
        S= S + first(R);
1775
3185
        if (cost(S) < min_cost)
1776
3186
        {
1797
3207
*/
1798
3208
 
1799
3209
static
1800
 
optimizer::RorIntersectReadPlan *get_best_ror_intersect(const optimizer::Parameter *param,
1801
 
                                                   optimizer::SEL_TREE *tree,
1802
 
                                                   double read_time,
1803
 
                                                   bool *are_all_covering)
 
3210
TRP_ROR_INTERSECT *get_best_ror_intersect(const PARAM *param, SEL_TREE *tree,
 
3211
                                          double read_time,
 
3212
                                          bool *are_all_covering)
1804
3213
{
1805
 
  uint32_t idx= 0;
 
3214
  uint32_t idx;
1806
3215
  double min_cost= DBL_MAX;
1807
3216
 
1808
 
  if ((tree->n_ror_scans < 2) || ! param->table->cursor->stats.records)
1809
 
    return NULL;
 
3217
  if ((tree->n_ror_scans < 2) || !param->table->file->stats.records)
 
3218
    return(NULL);
1810
3219
 
1811
3220
  /*
1812
 
    Step1: Collect ROR-able SEL_ARGs and create optimizer::RorScanInfo for each of
 
3221
    Step1: Collect ROR-able SEL_ARGs and create ROR_SCAN_INFO for each of 
1813
3222
    them. Also find and save clustered PK scan if there is one.
1814
3223
  */
1815
 
  optimizer::RorScanInfo **cur_ror_scan= NULL;
1816
 
  optimizer::RorScanInfo *cpk_scan= NULL;
1817
 
  uint32_t cpk_no= 0;
 
3224
  ROR_SCAN_INFO **cur_ror_scan;
 
3225
  ROR_SCAN_INFO *cpk_scan= NULL;
 
3226
  uint32_t cpk_no;
1818
3227
  bool cpk_scan_used= false;
1819
3228
 
1820
 
  if (! (tree->ror_scans= (optimizer::RorScanInfo**)param->mem_root->alloc_root(sizeof(optimizer::RorScanInfo*)* param->keys)))
1821
 
  {
 
3229
  if (!(tree->ror_scans= (ROR_SCAN_INFO**)alloc_root(param->mem_root,
 
3230
                                                     sizeof(ROR_SCAN_INFO*)*
 
3231
                                                     param->keys)))
1822
3232
    return NULL;
1823
 
  }
1824
 
  cpk_no= ((param->table->cursor->primary_key_is_clustered()) ?
1825
 
           param->table->getShare()->getPrimaryKey() : MAX_KEY);
 
3233
  cpk_no= ((param->table->file->primary_key_is_clustered()) ?
 
3234
           param->table->s->primary_key : MAX_KEY);
1826
3235
 
1827
3236
  for (idx= 0, cur_ror_scan= tree->ror_scans; idx < param->keys; idx++)
1828
3237
  {
1829
 
    optimizer::RorScanInfo *scan;
1830
 
    if (! tree->ror_scans_map.test(idx))
 
3238
    ROR_SCAN_INFO *scan;
 
3239
    if (!tree->ror_scans_map.is_set(idx))
1831
3240
      continue;
1832
 
    if (! (scan= make_ror_scan(param, idx, tree->keys[idx])))
 
3241
    if (!(scan= make_ror_scan(param, idx, tree->keys[idx])))
1833
3242
      return NULL;
1834
3243
    if (param->real_keynr[idx] == cpk_no)
1835
3244
    {
1841
3250
  }
1842
3251
 
1843
3252
  tree->ror_scans_end= cur_ror_scan;
 
3253
  print_ror_scans_arr(param->table, "original",
 
3254
                                          tree->ror_scans,
 
3255
                                          tree->ror_scans_end);
1844
3256
  /*
1845
3257
    Ok, [ror_scans, ror_scans_end) is array of ptrs to initialized
1846
 
    optimizer::RorScanInfo's.
 
3258
    ROR_SCAN_INFO's.
1847
3259
    Step 2: Get best ROR-intersection using an approximate algorithm.
1848
3260
  */
1849
 
  internal::my_qsort(tree->ror_scans, tree->n_ror_scans, sizeof(optimizer::RorScanInfo*),
1850
 
                     (qsort_cmp)cmp_ror_scan_info);
 
3261
  my_qsort(tree->ror_scans, tree->n_ror_scans, sizeof(ROR_SCAN_INFO*),
 
3262
           (qsort_cmp)cmp_ror_scan_info);
 
3263
  print_ror_scans_arr(param->table, "ordered",
 
3264
                                          tree->ror_scans,
 
3265
                                          tree->ror_scans_end);
1851
3266
 
1852
 
  optimizer::RorScanInfo **intersect_scans= NULL; /* ROR scans used in index intersection */
1853
 
  optimizer::RorScanInfo **intersect_scans_end= NULL;
1854
 
  if (! (intersect_scans= (optimizer::RorScanInfo**)param->mem_root->alloc_root(sizeof(optimizer::RorScanInfo*) * tree->n_ror_scans)))
 
3267
  ROR_SCAN_INFO **intersect_scans; /* ROR scans used in index intersection */
 
3268
  ROR_SCAN_INFO **intersect_scans_end;
 
3269
  if (!(intersect_scans= (ROR_SCAN_INFO**)alloc_root(param->mem_root,
 
3270
                                                     sizeof(ROR_SCAN_INFO*)*
 
3271
                                                     tree->n_ror_scans)))
1855
3272
    return NULL;
1856
3273
  intersect_scans_end= intersect_scans;
1857
3274
 
1858
3275
  /* Create and incrementally update ROR intersection. */
1859
 
  ROR_INTERSECT_INFO intersect(param);
1860
 
  ROR_INTERSECT_INFO intersect_best(param);
 
3276
  ROR_INTERSECT_INFO *intersect, *intersect_best;
 
3277
  if (!(intersect= ror_intersect_init(param)) || 
 
3278
      !(intersect_best= ror_intersect_init(param)))
 
3279
    return NULL;
1861
3280
 
1862
3281
  /* [intersect_scans,intersect_scans_best) will hold the best intersection */
1863
 
  optimizer::RorScanInfo **intersect_scans_best= NULL;
 
3282
  ROR_SCAN_INFO **intersect_scans_best;
1864
3283
  cur_ror_scan= tree->ror_scans;
1865
3284
  intersect_scans_best= intersect_scans;
1866
 
  while (cur_ror_scan != tree->ror_scans_end && ! intersect.is_covering)
 
3285
  while (cur_ror_scan != tree->ror_scans_end && !intersect->is_covering)
1867
3286
  {
1868
3287
    /* S= S + first(R);  R= R - first(R); */
1869
 
    if (! ror_intersect_add(&intersect, *cur_ror_scan, false))
 
3288
    if (!ror_intersect_add(intersect, *cur_ror_scan, false))
1870
3289
    {
1871
3290
      cur_ror_scan++;
1872
3291
      continue;
1873
3292
    }
1874
 
 
 
3293
    
1875
3294
    *(intersect_scans_end++)= *(cur_ror_scan++);
1876
3295
 
1877
 
    if (intersect.total_cost < min_cost)
 
3296
    if (intersect->total_cost < min_cost)
1878
3297
    {
1879
3298
      /* Local minimum found, save it */
1880
 
      ror_intersect_cpy(&intersect_best, &intersect);
 
3299
      ror_intersect_cpy(intersect_best, intersect);
1881
3300
      intersect_scans_best= intersect_scans_end;
1882
 
      min_cost = intersect.total_cost;
 
3301
      min_cost = intersect->total_cost;
1883
3302
    }
1884
3303
  }
1885
3304
 
1886
3305
  if (intersect_scans_best == intersect_scans)
1887
3306
  {
1888
 
    return NULL;
 
3307
    return(NULL);
1889
3308
  }
 
3309
    
 
3310
  print_ror_scans_arr(param->table,
 
3311
                                          "best ROR-intersection",
 
3312
                                          intersect_scans,
 
3313
                                          intersect_scans_best);
1890
3314
 
1891
 
  *are_all_covering= intersect.is_covering;
 
3315
  *are_all_covering= intersect->is_covering;
1892
3316
  uint32_t best_num= intersect_scans_best - intersect_scans;
1893
 
  ror_intersect_cpy(&intersect, &intersect_best);
 
3317
  ror_intersect_cpy(intersect, intersect_best);
1894
3318
 
1895
3319
  /*
1896
3320
    Ok, found the best ROR-intersection of non-CPK key scans.
1897
 
    Check if we should add a CPK scan. If the obtained ROR-intersection is
 
3321
    Check if we should add a CPK scan. If the obtained ROR-intersection is 
1898
3322
    covering, it doesn't make sense to add CPK scan.
1899
3323
  */
1900
 
  if (cpk_scan && ! intersect.is_covering)
 
3324
  if (cpk_scan && !intersect->is_covering)
1901
3325
  {
1902
 
    if (ror_intersect_add(&intersect, cpk_scan, true) &&
1903
 
        (intersect.total_cost < min_cost))
 
3326
    if (ror_intersect_add(intersect, cpk_scan, true) && 
 
3327
        (intersect->total_cost < min_cost))
1904
3328
    {
1905
3329
      cpk_scan_used= true;
1906
3330
      intersect_best= intersect; //just set pointer here
1908
3332
  }
1909
3333
 
1910
3334
  /* Ok, return ROR-intersect plan if we have found one */
1911
 
  optimizer::RorIntersectReadPlan *trp= NULL;
 
3335
  TRP_ROR_INTERSECT *trp= NULL;
1912
3336
  if (min_cost < read_time && (cpk_scan_used || best_num > 1))
1913
3337
  {
1914
 
    if (! (trp= new (param->mem_root) optimizer::RorIntersectReadPlan))
1915
 
      return trp;
1916
 
 
1917
 
    if (! (trp->first_scan=
1918
 
           (optimizer::RorScanInfo**)param->mem_root->alloc_root(sizeof(optimizer::RorScanInfo*)*best_num)))
1919
 
      return NULL;
1920
 
    memcpy(trp->first_scan, intersect_scans, best_num*sizeof(optimizer::RorScanInfo*));
 
3338
    if (!(trp= new (param->mem_root) TRP_ROR_INTERSECT))
 
3339
      return(trp);
 
3340
    if (!(trp->first_scan=
 
3341
           (ROR_SCAN_INFO**)alloc_root(param->mem_root,
 
3342
                                       sizeof(ROR_SCAN_INFO*)*best_num)))
 
3343
      return(NULL);
 
3344
    memcpy(trp->first_scan, intersect_scans, best_num*sizeof(ROR_SCAN_INFO*));
1921
3345
    trp->last_scan=  trp->first_scan + best_num;
1922
 
    trp->is_covering= intersect_best.is_covering;
1923
 
    trp->read_cost= intersect_best.total_cost;
 
3346
    trp->is_covering= intersect_best->is_covering;
 
3347
    trp->read_cost= intersect_best->total_cost;
1924
3348
    /* Prevent divisons by zero */
1925
 
    ha_rows best_rows = double2rows(intersect_best.out_rows);
1926
 
    if (! best_rows)
 
3349
    ha_rows best_rows = double2rows(intersect_best->out_rows);
 
3350
    if (!best_rows)
1927
3351
      best_rows= 1;
1928
3352
    set_if_smaller(param->table->quick_condition_rows, best_rows);
1929
3353
    trp->records= best_rows;
1930
 
    trp->index_scan_costs= intersect_best.index_scan_costs;
 
3354
    trp->index_scan_costs= intersect_best->index_scan_costs;
1931
3355
    trp->cpk_scan= cpk_scan_used? cpk_scan: NULL;
1932
3356
  }
1933
 
  return trp;
1934
 
}
1935
 
 
1936
 
 
1937
 
/*
1938
 
  Get best "range" table read plan for given optimizer::SEL_TREE, also update some info
 
3357
  return(trp);
 
3358
}
 
3359
 
 
3360
 
 
3361
/*
 
3362
  Get best covering ROR-intersection.
 
3363
  SYNOPSIS
 
3364
    get_best_covering_ror_intersect()
 
3365
      param     Parameter from test_quick_select function.
 
3366
      tree      SEL_TREE with sets of intervals for different keys.
 
3367
      read_time Don't return table read plans with cost > read_time.
 
3368
 
 
3369
  RETURN
 
3370
    Best covering ROR-intersection plan
 
3371
    NULL if no plan found.
 
3372
 
 
3373
  NOTES
 
3374
    get_best_ror_intersect must be called for a tree before calling this
 
3375
    function for it.
 
3376
    This function invalidates tree->ror_scans member values.
 
3377
 
 
3378
  The following approximate algorithm is used:
 
3379
    I=set of all covering indexes
 
3380
    F=set of all fields to cover
 
3381
    S={}
 
3382
 
 
3383
    do
 
3384
    {
 
3385
      Order I by (#covered fields in F desc,
 
3386
                  #components asc,
 
3387
                  number of first not covered component asc);
 
3388
      F=F-covered by first(I);
 
3389
      S=S+first(I);
 
3390
      I=I-first(I);
 
3391
    } while F is not empty.
 
3392
*/
 
3393
 
 
3394
static
 
3395
TRP_ROR_INTERSECT *get_best_covering_ror_intersect(PARAM *param,
 
3396
                                                   SEL_TREE *tree,
 
3397
                                                   double read_time)
 
3398
{
 
3399
  ROR_SCAN_INFO **ror_scan_mark;
 
3400
  ROR_SCAN_INFO **ror_scans_end= tree->ror_scans_end;
 
3401
 
 
3402
  for (ROR_SCAN_INFO **scan= tree->ror_scans; scan != ror_scans_end; ++scan)
 
3403
    (*scan)->key_components=
 
3404
      param->table->key_info[(*scan)->keynr].key_parts;
 
3405
 
 
3406
  /*
 
3407
    Run covering-ROR-search algorithm.
 
3408
    Assume set I is [ror_scan .. ror_scans_end)
 
3409
  */
 
3410
 
 
3411
  /*I=set of all covering indexes */
 
3412
  ror_scan_mark= tree->ror_scans;
 
3413
 
 
3414
  MY_BITMAP *covered_fields= &param->tmp_covered_fields;
 
3415
  if (!covered_fields->bitmap) 
 
3416
    covered_fields->bitmap= (my_bitmap_map*)alloc_root(param->mem_root,
 
3417
                                               param->fields_bitmap_size);
 
3418
  if (!covered_fields->bitmap ||
 
3419
      bitmap_init(covered_fields, covered_fields->bitmap,
 
3420
                  param->table->s->fields, false))
 
3421
    return(0);
 
3422
  bitmap_clear_all(covered_fields);
 
3423
 
 
3424
  double total_cost= 0.0f;
 
3425
  ha_rows records=0;
 
3426
  bool all_covered;
 
3427
 
 
3428
  print_ror_scans_arr(param->table,
 
3429
                                           "building covering ROR-I",
 
3430
                                           ror_scan_mark, ror_scans_end);
 
3431
  do
 
3432
  {
 
3433
    /*
 
3434
      Update changed sorting info:
 
3435
        #covered fields,
 
3436
        number of first not covered component
 
3437
      Calculate and save these values for each of remaining scans.
 
3438
    */
 
3439
    for (ROR_SCAN_INFO **scan= ror_scan_mark; scan != ror_scans_end; ++scan)
 
3440
    {
 
3441
      bitmap_subtract(&(*scan)->covered_fields, covered_fields);
 
3442
      (*scan)->used_fields_covered=
 
3443
        bitmap_bits_set(&(*scan)->covered_fields);
 
3444
      (*scan)->first_uncovered_field=
 
3445
        bitmap_get_first(&(*scan)->covered_fields);
 
3446
    }
 
3447
 
 
3448
    my_qsort(ror_scan_mark, ror_scans_end-ror_scan_mark, sizeof(ROR_SCAN_INFO*),
 
3449
             (qsort_cmp)cmp_ror_scan_info_covering);
 
3450
 
 
3451
    print_ror_scans_arr(param->table,
 
3452
                                             "remaining scans",
 
3453
                                             ror_scan_mark, ror_scans_end);
 
3454
 
 
3455
    /* I=I-first(I) */
 
3456
    total_cost += (*ror_scan_mark)->index_read_cost;
 
3457
    records += (*ror_scan_mark)->records;
 
3458
    if (total_cost > read_time)
 
3459
      return(NULL);
 
3460
    /* F=F-covered by first(I) */
 
3461
    bitmap_union(covered_fields, &(*ror_scan_mark)->covered_fields);
 
3462
    all_covered= bitmap_is_subset(&param->needed_fields, covered_fields);
 
3463
  } while ((++ror_scan_mark < ror_scans_end) && !all_covered);
 
3464
  
 
3465
  if (!all_covered || (ror_scan_mark - tree->ror_scans) == 1)
 
3466
    return(NULL);
 
3467
 
 
3468
  /*
 
3469
    Ok, [tree->ror_scans .. ror_scan) holds covering index_intersection with
 
3470
    cost total_cost.
 
3471
  */
 
3472
  print_ror_scans_arr(param->table,
 
3473
                                           "creating covering ROR-intersect",
 
3474
                                           tree->ror_scans, ror_scan_mark);
 
3475
 
 
3476
  /* Add priority queue use cost. */
 
3477
  total_cost += rows2double(records)*
 
3478
                log((double)(ror_scan_mark - tree->ror_scans)) /
 
3479
                (TIME_FOR_COMPARE_ROWID * M_LN2);
 
3480
 
 
3481
  if (total_cost > read_time)
 
3482
    return(NULL);
 
3483
 
 
3484
  TRP_ROR_INTERSECT *trp;
 
3485
  if (!(trp= new (param->mem_root) TRP_ROR_INTERSECT))
 
3486
    return(trp);
 
3487
  uint32_t best_num= (ror_scan_mark - tree->ror_scans);
 
3488
  if (!(trp->first_scan= (ROR_SCAN_INFO**)alloc_root(param->mem_root,
 
3489
                                                     sizeof(ROR_SCAN_INFO*)*
 
3490
                                                     best_num)))
 
3491
    return(NULL);
 
3492
  memcpy(trp->first_scan, tree->ror_scans, best_num*sizeof(ROR_SCAN_INFO*));
 
3493
  trp->last_scan=  trp->first_scan + best_num;
 
3494
  trp->is_covering= true;
 
3495
  trp->read_cost= total_cost;
 
3496
  trp->records= records;
 
3497
  trp->cpk_scan= NULL;
 
3498
  set_if_smaller(param->table->quick_condition_rows, records); 
 
3499
 
 
3500
  return(trp);
 
3501
}
 
3502
 
 
3503
 
 
3504
/*
 
3505
  Get best "range" table read plan for given SEL_TREE, also update some info
1939
3506
 
1940
3507
  SYNOPSIS
1941
3508
    get_key_scans_params()
1942
 
      session
1943
3509
      param                    Parameters from test_quick_select
1944
 
      tree                     Make range select for this optimizer::SEL_TREE
 
3510
      tree                     Make range select for this SEL_TREE
1945
3511
      index_read_must_be_used  true <=> assume 'index only' option will be set
1946
3512
                               (except for clustered PK indexes)
1947
3513
      update_tbl_stats         true <=> update table->quick_* with information
1948
3514
                               about range scans we've evaluated.
1949
 
      read_time                Maximum cost. i.e. don't create read plans with
 
3515
      read_time                Maximum cost. i.e. don't create read plans with 
1950
3516
                               cost > read_time.
1951
3517
 
1952
3518
  DESCRIPTION
1953
 
    Find the best "range" table read plan for given optimizer::SEL_TREE.
1954
 
    The side effects are
 
3519
    Find the best "range" table read plan for given SEL_TREE. 
 
3520
    The side effects are 
1955
3521
     - tree->ror_scans is updated to indicate which scans are ROR scans.
1956
3522
     - if update_tbl_stats=true then table->quick_* is updated with info
1957
3523
       about every possible range scan.
1961
3527
    NULL if no plan found or error occurred
1962
3528
*/
1963
3529
 
1964
 
static optimizer::RangeReadPlan *get_key_scans_params(Session *session,
1965
 
                                                      optimizer::Parameter *param,
1966
 
                                                      optimizer::SEL_TREE *tree,
1967
 
                                                      bool index_read_must_be_used,
1968
 
                                                      bool update_tbl_stats,
1969
 
                                                      double read_time)
 
3530
static TRP_RANGE *get_key_scans_params(PARAM *param, SEL_TREE *tree,
 
3531
                                       bool index_read_must_be_used, 
 
3532
                                       bool update_tbl_stats,
 
3533
                                       double read_time)
1970
3534
{
1971
3535
  uint32_t idx;
1972
 
  optimizer::SEL_ARG **key= NULL;
1973
 
  optimizer::SEL_ARG **end= NULL;
1974
 
  optimizer::SEL_ARG **key_to_read= NULL;
 
3536
  SEL_ARG **key,**end, **key_to_read= NULL;
1975
3537
  ha_rows best_records= 0;
1976
 
  uint32_t best_mrr_flags= 0;
1977
 
  uint32_t best_buf_size= 0;
1978
 
  optimizer::RangeReadPlan *read_plan= NULL;
 
3538
  uint32_t    best_mrr_flags= 0, best_buf_size= 0;
 
3539
  TRP_RANGE* read_plan= NULL;
1979
3540
  /*
1980
 
    Note that there may be trees that have type optimizer::SEL_TREE::KEY but contain no
 
3541
    Note that there may be trees that have type SEL_TREE::KEY but contain no
1981
3542
    key reads at all, e.g. tree for expression "key1 is not null" where key1
1982
3543
    is defined as "not null".
1983
3544
  */
1984
 
  tree->ror_scans_map.reset();
 
3545
  print_sel_tree(param, tree, &tree->keys_map, "tree scans");
 
3546
  tree->ror_scans_map.clear_all();
1985
3547
  tree->n_ror_scans= 0;
1986
3548
  for (idx= 0,key=tree->keys, end=key+param->keys; key != end; key++,idx++)
1987
3549
  {
1988
3550
    if (*key)
1989
3551
    {
1990
3552
      ha_rows found_records;
1991
 
      optimizer::CostVector cost;
1992
 
      double found_read_time= 0.0;
 
3553
      COST_VECT cost;
 
3554
      double found_read_time;
1993
3555
      uint32_t mrr_flags, buf_size;
1994
3556
      uint32_t keynr= param->real_keynr[idx];
1995
 
      if ((*key)->type == optimizer::SEL_ARG::MAYBE_KEY ||
 
3557
      if ((*key)->type == SEL_ARG::MAYBE_KEY ||
1996
3558
          (*key)->maybe_flag)
1997
 
        param->needed_reg->set(keynr);
1998
 
 
1999
 
      bool read_index_only= index_read_must_be_used ||
2000
 
                            param->table->covering_keys.test(keynr);
2001
 
 
2002
 
      found_records= check_quick_select(session, param, idx, read_index_only, *key,
 
3559
        param->needed_reg->set_bit(keynr);
 
3560
 
 
3561
      bool read_index_only= index_read_must_be_used || 
 
3562
                            param->table->covering_keys.is_set(keynr);
 
3563
 
 
3564
      found_records= check_quick_select(param, idx, read_index_only, *key,
2003
3565
                                        update_tbl_stats, &mrr_flags,
2004
3566
                                        &buf_size, &cost);
2005
3567
      found_read_time= cost.total_cost();
2006
3568
      if ((found_records != HA_POS_ERROR) && param->is_ror_scan)
2007
3569
      {
2008
3570
        tree->n_ror_scans++;
2009
 
        tree->ror_scans_map.set(idx);
 
3571
        tree->ror_scans_map.set_bit(idx);
2010
3572
      }
2011
3573
      if (read_time > found_read_time && found_records != HA_POS_ERROR)
2012
3574
      {
2019
3581
    }
2020
3582
  }
2021
3583
 
 
3584
  print_sel_tree(param, tree, &tree->ror_scans_map, "ROR scans");
2022
3585
  if (key_to_read)
2023
3586
  {
2024
3587
    idx= key_to_read - tree->keys;
2025
 
    if ((read_plan= new (param->mem_root) optimizer::RangeReadPlan(*key_to_read, idx,
2026
 
                                                                   best_mrr_flags)))
 
3588
    if ((read_plan= new (param->mem_root) TRP_RANGE(*key_to_read, idx,
 
3589
                                                    best_mrr_flags)))
2027
3590
    {
2028
3591
      read_plan->records= best_records;
2029
 
      read_plan->is_ror= tree->ror_scans_map.test(idx);
 
3592
      read_plan->is_ror= tree->ror_scans_map.is_set(idx);
2030
3593
      read_plan->read_cost= read_time;
2031
3594
      read_plan->mrr_buf_size= best_buf_size;
2032
3595
    }
2036
3599
}
2037
3600
 
2038
3601
 
2039
 
optimizer::QuickSelectInterface *optimizer::IndexMergeReadPlan::make_quick(optimizer::Parameter *param, bool, memory::Root *)
 
3602
QUICK_SELECT_I *TRP_INDEX_MERGE::make_quick(PARAM *param,
 
3603
                                            bool retrieve_full_rows __attribute__((unused)),
 
3604
                                            MEM_ROOT *parent_alloc __attribute__((unused)))
2040
3605
{
2041
 
  optimizer::QuickIndexMergeSelect *quick_imerge;
2042
 
  optimizer::QuickRangeSelect *quick= NULL;
 
3606
  QUICK_INDEX_MERGE_SELECT *quick_imerge;
 
3607
  QUICK_RANGE_SELECT *quick;
2043
3608
  /* index_merge always retrieves full rows, ignore retrieve_full_rows */
2044
 
  if (! (quick_imerge= new optimizer::QuickIndexMergeSelect(param->session, param->table)))
2045
 
  {
 
3609
  if (!(quick_imerge= new QUICK_INDEX_MERGE_SELECT(param->session, param->table)))
2046
3610
    return NULL;
2047
 
  }
2048
3611
 
2049
3612
  quick_imerge->records= records;
2050
3613
  quick_imerge->read_time= read_cost;
2051
 
  for (optimizer::RangeReadPlan **range_scan= range_scans; 
2052
 
       range_scan != range_scans_end;
 
3614
  for (TRP_RANGE **range_scan= range_scans; range_scan != range_scans_end;
2053
3615
       range_scan++)
2054
3616
  {
2055
 
    if (! (quick= (optimizer::QuickRangeSelect*)
2056
 
          ((*range_scan)->make_quick(param, false, &quick_imerge->alloc))) ||
 
3617
    if (!(quick= (QUICK_RANGE_SELECT*)
 
3618
          ((*range_scan)->make_quick(param, false, &quick_imerge->alloc)))||
2057
3619
        quick_imerge->push_quick_back(quick))
2058
3620
    {
2059
3621
      delete quick;
2064
3626
  return quick_imerge;
2065
3627
}
2066
3628
 
2067
 
optimizer::QuickSelectInterface *optimizer::RorIntersectReadPlan::make_quick(optimizer::Parameter *param,
2068
 
                                                                             bool retrieve_full_rows,
2069
 
                                                                             memory::Root *parent_alloc)
 
3629
QUICK_SELECT_I *TRP_ROR_INTERSECT::make_quick(PARAM *param,
 
3630
                                              bool retrieve_full_rows,
 
3631
                                              MEM_ROOT *parent_alloc)
2070
3632
{
2071
 
  optimizer::QuickRorIntersectSelect *quick_intersect= NULL;
2072
 
  optimizer::QuickRangeSelect *quick= NULL;
2073
 
  memory::Root *alloc= NULL;
 
3633
  QUICK_ROR_INTERSECT_SELECT *quick_intrsect;
 
3634
  QUICK_RANGE_SELECT *quick;
 
3635
  MEM_ROOT *alloc;
2074
3636
 
2075
 
  if ((quick_intersect=
2076
 
         new optimizer::QuickRorIntersectSelect(param->session,
2077
 
                                                param->table,
2078
 
                                                (retrieve_full_rows? (! is_covering) : false),
2079
 
                                                parent_alloc)))
 
3637
  if ((quick_intrsect=
 
3638
         new QUICK_ROR_INTERSECT_SELECT(param->session, param->table,
 
3639
                                        (retrieve_full_rows? (!is_covering) :
 
3640
                                         false),
 
3641
                                        parent_alloc)))
2080
3642
  {
2081
 
    alloc= parent_alloc ? parent_alloc : &quick_intersect->alloc;
2082
 
    for (; first_scan != last_scan; ++first_scan)
 
3643
    print_ror_scans_arr(param->table,
 
3644
                                             "creating ROR-intersect",
 
3645
                                             first_scan, last_scan);
 
3646
    alloc= parent_alloc? parent_alloc: &quick_intrsect->alloc;
 
3647
    for (; first_scan != last_scan;++first_scan)
2083
3648
    {
2084
 
      if (! (quick= optimizer::get_quick_select(param,
2085
 
                                                (*first_scan)->idx,
2086
 
                                                (*first_scan)->sel_arg,
2087
 
                                                HA_MRR_USE_DEFAULT_IMPL | HA_MRR_SORTED,
2088
 
                                                0,
2089
 
                                                alloc)) ||
2090
 
          quick_intersect->push_quick_back(quick))
 
3649
      if (!(quick= get_quick_select(param, (*first_scan)->idx,
 
3650
                                    (*first_scan)->sel_arg,
 
3651
                                    HA_MRR_USE_DEFAULT_IMPL | HA_MRR_SORTED,
 
3652
                                    0, alloc)) ||
 
3653
          quick_intrsect->push_quick_back(quick))
2091
3654
      {
2092
 
        delete quick_intersect;
2093
 
        return NULL;
 
3655
        delete quick_intrsect;
 
3656
        return(NULL);
2094
3657
      }
2095
3658
    }
2096
3659
    if (cpk_scan)
2097
3660
    {
2098
 
      if (! (quick= optimizer::get_quick_select(param,
2099
 
                                                cpk_scan->idx,
2100
 
                                                cpk_scan->sel_arg,
2101
 
                                                HA_MRR_USE_DEFAULT_IMPL | HA_MRR_SORTED,
2102
 
                                                0,
2103
 
                                                alloc)))
 
3661
      if (!(quick= get_quick_select(param, cpk_scan->idx,
 
3662
                                    cpk_scan->sel_arg,
 
3663
                                    HA_MRR_USE_DEFAULT_IMPL | HA_MRR_SORTED,
 
3664
                                    0, alloc)))
2104
3665
      {
2105
 
        delete quick_intersect;
2106
 
        return NULL;
 
3666
        delete quick_intrsect;
 
3667
        return(NULL);
2107
3668
      }
2108
 
      quick->resetCursor();
2109
 
      quick_intersect->cpk_quick= quick;
 
3669
      quick->file= NULL; 
 
3670
      quick_intrsect->cpk_quick= quick;
2110
3671
    }
2111
 
    quick_intersect->records= records;
2112
 
    quick_intersect->read_time= read_cost;
 
3672
    quick_intrsect->records= records;
 
3673
    quick_intrsect->read_time= read_cost;
2113
3674
  }
2114
 
  return quick_intersect;
 
3675
  return(quick_intrsect);
2115
3676
}
2116
3677
 
2117
3678
 
2118
 
optimizer::QuickSelectInterface *optimizer::RorUnionReadPlan::make_quick(optimizer::Parameter *param, bool, memory::Root *)
 
3679
QUICK_SELECT_I *TRP_ROR_UNION::make_quick(PARAM *param,
 
3680
                                          bool retrieve_full_rows __attribute__((unused)),
 
3681
                                          MEM_ROOT *parent_alloc __attribute__((unused)))
2119
3682
{
2120
 
  optimizer::QuickRorUnionSelect *quick_roru= NULL;
2121
 
  optimizer::TableReadPlan **scan= NULL;
2122
 
  optimizer::QuickSelectInterface *quick= NULL;
 
3683
  QUICK_ROR_UNION_SELECT *quick_roru;
 
3684
  TABLE_READ_PLAN **scan;
 
3685
  QUICK_SELECT_I *quick;
2123
3686
  /*
2124
3687
    It is impossible to construct a ROR-union that will not retrieve full
2125
3688
    rows, ignore retrieve_full_rows parameter.
2126
3689
  */
2127
 
  if ((quick_roru= new optimizer::QuickRorUnionSelect(param->session, param->table)))
 
3690
  if ((quick_roru= new QUICK_ROR_UNION_SELECT(param->session, param->table)))
2128
3691
  {
2129
3692
    for (scan= first_ror; scan != last_ror; scan++)
2130
3693
    {
2131
 
      if (! (quick= (*scan)->make_quick(param, false, &quick_roru->alloc)) ||
 
3694
      if (!(quick= (*scan)->make_quick(param, false, &quick_roru->alloc)) ||
2132
3695
          quick_roru->push_quick_back(quick))
2133
 
      {
2134
 
        return NULL;
2135
 
      }
 
3696
        return(NULL);
2136
3697
    }
2137
3698
    quick_roru->records= records;
2138
3699
    quick_roru->read_time= read_cost;
2139
3700
  }
2140
 
  return quick_roru;
 
3701
  return(quick_roru);
2141
3702
}
2142
3703
 
2143
3704
 
2144
3705
/*
2145
 
  Build a optimizer::SEL_TREE for <> or NOT BETWEEN predicate
2146
 
 
 
3706
  Build a SEL_TREE for <> or NOT BETWEEN predicate
 
3707
 
2147
3708
  SYNOPSIS
2148
3709
    get_ne_mm_tree()
2149
 
      param       Parameter from SqlSelect::test_quick_select
 
3710
      param       PARAM from SQL_SELECT::test_quick_select
2150
3711
      cond_func   item for the predicate
2151
3712
      field       field in the predicate
2152
3713
      lt_value    constant that field should be smaller
2153
3714
      gt_value    constant that field should be greaterr
2154
3715
      cmp_type    compare type for the field
2155
3716
 
2156
 
  RETURN
 
3717
  RETURN 
2157
3718
    #  Pointer to tree built tree
2158
3719
    0  on error
2159
3720
*/
2160
 
static optimizer::SEL_TREE *get_ne_mm_tree(optimizer::RangeParameter *param,
2161
 
                                Item_func *cond_func,
 
3721
 
 
3722
static SEL_TREE *get_ne_mm_tree(RANGE_OPT_PARAM *param, Item_func *cond_func, 
2162
3723
                                Field *field,
2163
3724
                                Item *lt_value, Item *gt_value,
2164
3725
                                Item_result cmp_type)
2165
3726
{
2166
 
  optimizer::SEL_TREE *tree= NULL;
 
3727
  SEL_TREE *tree;
2167
3728
  tree= get_mm_parts(param, cond_func, field, Item_func::LT_FUNC,
2168
3729
                     lt_value, cmp_type);
2169
3730
  if (tree)
2170
3731
  {
2171
 
    tree= tree_or(param,
2172
 
                  tree,
2173
 
                  get_mm_parts(param, cond_func, field,
2174
 
                                                Item_func::GT_FUNC,
2175
 
                                                gt_value,
2176
 
                  cmp_type));
 
3732
    tree= tree_or(param, tree, get_mm_parts(param, cond_func, field,
 
3733
                                            Item_func::GT_FUNC,
 
3734
                                            gt_value, cmp_type));
2177
3735
  }
2178
3736
  return tree;
2179
3737
}
2180
 
 
 
3738
   
2181
3739
 
2182
3740
/*
2183
 
  Build a optimizer::SEL_TREE for a simple predicate
2184
 
 
 
3741
  Build a SEL_TREE for a simple predicate
 
3742
 
2185
3743
  SYNOPSIS
2186
3744
    get_func_mm_tree()
2187
 
      param       Parameter from SqlSelect::test_quick_select
 
3745
      param       PARAM from SQL_SELECT::test_quick_select
2188
3746
      cond_func   item for the predicate
2189
3747
      field       field in the predicate
2190
3748
      value       constant in the predicate
2191
3749
      cmp_type    compare type for the field
2192
3750
      inv         true <> NOT cond_func is considered
2193
 
                  (makes sense only when cond_func is BETWEEN or IN)
 
3751
                  (makes sense only when cond_func is BETWEEN or IN) 
2194
3752
 
2195
 
  RETURN
 
3753
  RETURN 
2196
3754
    Pointer to the tree built tree
2197
3755
*/
2198
 
static optimizer::SEL_TREE *get_func_mm_tree(optimizer::RangeParameter *param,
2199
 
                                  Item_func *cond_func,
2200
 
                                  Field *field, 
2201
 
                                  Item *value,
2202
 
                                  Item_result cmp_type, 
2203
 
                                  bool inv)
 
3756
 
 
3757
static SEL_TREE *get_func_mm_tree(RANGE_OPT_PARAM *param, Item_func *cond_func, 
 
3758
                                  Field *field, Item *value,
 
3759
                                  Item_result cmp_type, bool inv)
2204
3760
{
2205
 
  optimizer::SEL_TREE *tree= NULL;
 
3761
  SEL_TREE *tree= 0;
2206
3762
 
2207
 
  switch (cond_func->functype()) 
2208
 
  {
 
3763
  switch (cond_func->functype()) {
2209
3764
 
2210
3765
  case Item_func::NE_FUNC:
2211
3766
    tree= get_ne_mm_tree(param, cond_func, field, value, value, cmp_type);
2213
3768
 
2214
3769
  case Item_func::BETWEEN:
2215
3770
  {
2216
 
    if (! value)
 
3771
    if (!value)
2217
3772
    {
2218
3773
      if (inv)
2219
3774
      {
2220
 
        tree= get_ne_mm_tree(param, 
2221
 
                             cond_func, 
2222
 
                             field, 
2223
 
                             cond_func->arguments()[1],
2224
 
                             cond_func->arguments()[2], 
2225
 
                             cmp_type);
 
3775
        tree= get_ne_mm_tree(param, cond_func, field, cond_func->arguments()[1],
 
3776
                             cond_func->arguments()[2], cmp_type);
2226
3777
      }
2227
3778
      else
2228
3779
      {
2229
 
        tree= get_mm_parts(param, 
2230
 
                           cond_func, 
2231
 
                           field, 
2232
 
                           Item_func::GE_FUNC,
2233
 
                                       cond_func->arguments()[1],
2234
 
                           cmp_type);
 
3780
        tree= get_mm_parts(param, cond_func, field, Item_func::GE_FUNC,
 
3781
                           cond_func->arguments()[1],cmp_type);
2235
3782
        if (tree)
2236
3783
        {
2237
 
          tree= tree_and(param, 
2238
 
                         tree, 
2239
 
                         get_mm_parts(param, cond_func, field,
2240
 
                                                       Item_func::LE_FUNC,
2241
 
                                                       cond_func->arguments()[2],
2242
 
                         cmp_type));
 
3784
          tree= tree_and(param, tree, get_mm_parts(param, cond_func, field,
 
3785
                                                   Item_func::LE_FUNC,
 
3786
                                                   cond_func->arguments()[2],
 
3787
                                                   cmp_type));
2243
3788
        }
2244
3789
      }
2245
3790
    }
2246
3791
    else
2247
 
      tree= get_mm_parts(param, 
2248
 
                         cond_func, 
2249
 
                         field,
 
3792
      tree= get_mm_parts(param, cond_func, field,
2250
3793
                         (inv ?
2251
3794
                          (value == (Item*)1 ? Item_func::GT_FUNC :
2252
3795
                                               Item_func::LT_FUNC):
2253
3796
                          (value == (Item*)1 ? Item_func::LE_FUNC :
2254
3797
                                               Item_func::GE_FUNC)),
2255
 
                         cond_func->arguments()[0], 
2256
 
                         cmp_type);
 
3798
                         cond_func->arguments()[0], cmp_type);
2257
3799
    break;
2258
3800
  }
2259
3801
  case Item_func::IN_FUNC:
2260
3802
  {
2261
 
    Item_func_in *func= (Item_func_in*) cond_func;
 
3803
    Item_func_in *func=(Item_func_in*) cond_func;
2262
3804
 
2263
3805
    /*
2264
3806
      Array for IN() is constructed when all values have the same result
2265
3807
      type. Tree won't be built for values with different result types,
2266
3808
      so we check it here to avoid unnecessary work.
2267
3809
    */
2268
 
    if (! func->arg_types_compatible)
2269
 
      break;
 
3810
    if (!func->arg_types_compatible)
 
3811
      break;     
2270
3812
 
2271
3813
    if (inv)
2272
3814
    {
2274
3816
      {
2275
3817
        /*
2276
3818
          We get here for conditions in form "t.key NOT IN (c1, c2, ...)",
2277
 
          where c{i} are constants. Our goal is to produce a optimizer::SEL_TREE that
 
3819
          where c{i} are constants. Our goal is to produce a SEL_TREE that 
2278
3820
          represents intervals:
2279
 
 
 
3821
          
2280
3822
          ($MIN<t.key<c1) OR (c1<t.key<c2) OR (c2<t.key<c3) OR ...    (*)
2281
 
 
 
3823
          
2282
3824
          where $MIN is either "-inf" or NULL.
2283
 
 
 
3825
          
2284
3826
          The most straightforward way to produce it is to convert NOT IN
2285
3827
          into "(t.key != c1) AND (t.key != c2) AND ... " and let the range
2286
 
          analyzer to build optimizer::SEL_TREE from that. The problem is that the
 
3828
          analyzer to build SEL_TREE from that. The problem is that the
2287
3829
          range analyzer will use O(N^2) memory (which is probably a bug),
2288
3830
          and people do use big NOT IN lists (e.g. see BUG#15872, BUG#21282),
2289
3831
          will run out of memory.
2290
3832
 
2291
3833
          Another problem with big lists like (*) is that a big list is
2292
3834
          unlikely to produce a good "range" access, while considering that
2293
 
          range access will require expensive CPU calculations (and for
 
3835
          range access will require expensive CPU calculations (and for 
2294
3836
          MyISAM even index accesses). In short, big NOT IN lists are rarely
2295
3837
          worth analyzing.
2296
3838
 
2297
3839
          Considering the above, we'll handle NOT IN as follows:
2298
3840
          * if the number of entries in the NOT IN list is less than
2299
 
            NOT_IN_IGNORE_THRESHOLD, construct the optimizer::SEL_TREE (*) manually.
2300
 
          * Otherwise, don't produce a optimizer::SEL_TREE.
 
3841
            NOT_IN_IGNORE_THRESHOLD, construct the SEL_TREE (*) manually.
 
3842
          * Otherwise, don't produce a SEL_TREE.
2301
3843
        */
2302
3844
#define NOT_IN_IGNORE_THRESHOLD 1000
2303
 
        memory::Root *tmp_root= param->mem_root;
 
3845
        MEM_ROOT *tmp_root= param->mem_root;
2304
3846
        param->session->mem_root= param->old_root;
2305
 
        /*
 
3847
        /* 
2306
3848
          Create one Item_type constant object. We'll need it as
2307
3849
          get_mm_parts only accepts constant values wrapped in Item_Type
2308
3850
          objects.
2313
3855
        Item *value_item= func->array->create_item();
2314
3856
        param->session->mem_root= tmp_root;
2315
3857
 
2316
 
        if (func->array->count > NOT_IN_IGNORE_THRESHOLD || ! value_item)
 
3858
        if (func->array->count > NOT_IN_IGNORE_THRESHOLD || !value_item)
2317
3859
          break;
2318
3860
 
2319
 
        /* Get a optimizer::SEL_TREE for "(-inf|NULL) < X < c_0" interval.  */
 
3861
        /* Get a SEL_TREE for "(-inf|NULL) < X < c_0" interval.  */
2320
3862
        uint32_t i=0;
2321
 
        do
 
3863
        do 
2322
3864
        {
2323
3865
          func->array->value_to_item(i, value_item);
2324
 
          tree= get_mm_parts(param, 
2325
 
                             cond_func, 
2326
 
                             field, Item_func::LT_FUNC,
2327
 
                             value_item, 
2328
 
                             cmp_type);
2329
 
          if (! tree)
 
3866
          tree= get_mm_parts(param, cond_func, field, Item_func::LT_FUNC,
 
3867
                             value_item, cmp_type);
 
3868
          if (!tree)
2330
3869
            break;
2331
3870
          i++;
2332
 
        } while (i < func->array->count && tree->type == optimizer::SEL_TREE::IMPOSSIBLE);
 
3871
        } while (i < func->array->count && tree->type == SEL_TREE::IMPOSSIBLE);
2333
3872
 
2334
 
        if (!tree || tree->type == optimizer::SEL_TREE::IMPOSSIBLE)
 
3873
        if (!tree || tree->type == SEL_TREE::IMPOSSIBLE)
2335
3874
        {
2336
3875
          /* We get here in cases like "t.unsigned NOT IN (-1,-2,-3) */
2337
3876
          tree= NULL;
2338
3877
          break;
2339
3878
        }
2340
 
        optimizer::SEL_TREE *tree2= NULL;
 
3879
        SEL_TREE *tree2;
2341
3880
        for (; i < func->array->count; i++)
2342
3881
        {
2343
3882
          if (func->array->compare_elems(i, i-1))
2344
3883
          {
2345
 
            /* Get a optimizer::SEL_TREE for "-inf < X < c_i" interval */
 
3884
            /* Get a SEL_TREE for "-inf < X < c_i" interval */
2346
3885
            func->array->value_to_item(i, value_item);
2347
3886
            tree2= get_mm_parts(param, cond_func, field, Item_func::LT_FUNC,
2348
3887
                                value_item, cmp_type);
2355
3894
            /* Change all intervals to be "c_{i-1} < X < c_i" */
2356
3895
            for (uint32_t idx= 0; idx < param->keys; idx++)
2357
3896
            {
2358
 
              optimizer::SEL_ARG *new_interval, *last_val;
 
3897
              SEL_ARG *new_interval, *last_val;
2359
3898
              if (((new_interval= tree2->keys[idx])) &&
2360
3899
                  (tree->keys[idx]) &&
2361
3900
                  ((last_val= tree->keys[idx]->last())))
2364
3903
                new_interval->min_flag= NEAR_MIN;
2365
3904
              }
2366
3905
            }
2367
 
            /*
 
3906
            /* 
2368
3907
              The following doesn't try to allocate memory so no need to
2369
3908
              check for NULL.
2370
3909
            */
2371
3910
            tree= tree_or(param, tree, tree2);
2372
3911
          }
2373
3912
        }
2374
 
 
2375
 
        if (tree && tree->type != optimizer::SEL_TREE::IMPOSSIBLE)
 
3913
        
 
3914
        if (tree && tree->type != SEL_TREE::IMPOSSIBLE)
2376
3915
        {
2377
 
          /*
2378
 
            Get the optimizer::SEL_TREE for the last "c_last < X < +inf" interval
 
3916
          /* 
 
3917
            Get the SEL_TREE for the last "c_last < X < +inf" interval 
2379
3918
            (value_item cotains c_last already)
2380
3919
          */
2381
3920
          tree2= get_mm_parts(param, cond_func, field, Item_func::GT_FUNC,
2394
3933
          for (arg= func->arguments()+2, end= arg+func->argument_count()-2;
2395
3934
               arg < end ; arg++)
2396
3935
          {
2397
 
            tree=  tree_and(param, tree, get_ne_mm_tree(param, cond_func, field,
 
3936
            tree=  tree_and(param, tree, get_ne_mm_tree(param, cond_func, field, 
2398
3937
                                                        *arg, *arg, cmp_type));
2399
3938
          }
2400
3939
        }
2401
3940
      }
2402
3941
    }
2403
3942
    else
2404
 
    {
 
3943
    {    
2405
3944
      tree= get_mm_parts(param, cond_func, field, Item_func::EQ_FUNC,
2406
3945
                         func->arguments()[1], cmp_type);
2407
3946
      if (tree)
2410
3949
        for (arg= func->arguments()+2, end= arg+func->argument_count()-2;
2411
3950
             arg < end ; arg++)
2412
3951
        {
2413
 
          tree= tree_or(param, tree, get_mm_parts(param, cond_func, field,
 
3952
          tree= tree_or(param, tree, get_mm_parts(param, cond_func, field, 
2414
3953
                                                  Item_func::EQ_FUNC,
2415
3954
                                                  *arg, cmp_type));
2416
3955
        }
2418
3957
    }
2419
3958
    break;
2420
3959
  }
2421
 
  default:
 
3960
  default: 
2422
3961
  {
2423
 
    /*
 
3962
    /* 
2424
3963
       Here the function for the following predicates are processed:
2425
3964
       <, <=, =, >=, >, LIKE, IS NULL, IS NOT NULL.
2426
3965
       If the predicate is of the form (value op field) it is handled
2439
3978
 
2440
3979
 
2441
3980
/*
2442
 
  Build conjunction of all optimizer::SEL_TREEs for a simple predicate applying equalities
2443
 
 
 
3981
  Build conjunction of all SEL_TREEs for a simple predicate applying equalities
 
3982
 
2444
3983
  SYNOPSIS
2445
3984
    get_full_func_mm_tree()
2446
 
      param       Parameter from SqlSelect::test_quick_select
 
3985
      param       PARAM from SQL_SELECT::test_quick_select
2447
3986
      cond_func   item for the predicate
2448
3987
      field_item  field in the predicate
2449
3988
      value       constant in the predicate
2450
3989
                  (for BETWEEN it contains the number of the field argument,
2451
 
                   for IN it's always 0)
 
3990
                   for IN it's always 0) 
2452
3991
      inv         true <> NOT cond_func is considered
2453
3992
                  (makes sense only when cond_func is BETWEEN or IN)
2454
3993
 
2455
3994
  DESCRIPTION
2456
3995
    For a simple SARGable predicate of the form (f op c), where f is a field and
2457
 
    c is a constant, the function builds a conjunction of all optimizer::SEL_TREES that can
 
3996
    c is a constant, the function builds a conjunction of all SEL_TREES that can
2458
3997
    be obtained by the substitution of f for all different fields equal to f.
2459
3998
 
2460
 
  NOTES
 
3999
  NOTES  
2461
4000
    If the WHERE condition contains a predicate (fi op c),
2462
4001
    then not only SELL_TREE for this predicate is built, but
2463
4002
    the trees for the results of substitution of fi for
2464
4003
    each fj belonging to the same multiple equality as fi
2465
4004
    are built as well.
2466
 
    E.g. for WHERE t1.a=t2.a AND t2.a > 10
2467
 
    a optimizer::SEL_TREE for t2.a > 10 will be built for quick select from t2
2468
 
    and
2469
 
    a optimizer::SEL_TREE for t1.a > 10 will be built for quick select from t1.
 
4005
    E.g. for WHERE t1.a=t2.a AND t2.a > 10 
 
4006
    a SEL_TREE for t2.a > 10 will be built for quick select from t2
 
4007
    and   
 
4008
    a SEL_TREE for t1.a > 10 will be built for quick select from t1.
2470
4009
 
2471
4010
    A BETWEEN predicate of the form (fi [NOT] BETWEEN c1 AND c2) is treated
2472
4011
    in a similar way: we build a conjuction of trees for the results
2474
4013
    Yet a predicate of the form (c BETWEEN f1i AND f2i) is processed
2475
4014
    differently. It is considered as a conjuction of two SARGable
2476
4015
    predicates (f1i <= c) and (f2i <=c) and the function get_full_func_mm_tree
2477
 
    is called for each of them separately producing trees for
2478
 
       AND j (f1j <=c ) and AND j (f2j <= c)
 
4016
    is called for each of them separately producing trees for 
 
4017
       AND j (f1j <=c ) and AND j (f2j <= c) 
2479
4018
    After this these two trees are united in one conjunctive tree.
2480
4019
    It's easy to see that the same tree is obtained for
2481
4020
       AND j,k (f1j <=c AND f2k<=c)
2482
 
    which is equivalent to
 
4021
    which is equivalent to 
2483
4022
       AND j,k (c BETWEEN f1j AND f2k).
2484
4023
    The validity of the processing of the predicate (c NOT BETWEEN f1i AND f2i)
2485
4024
    which equivalent to (f1i > c OR f2i < c) is not so obvious. Here the
2486
4025
    function get_full_func_mm_tree is called for (f1i > c) and (f2i < c)
2487
4026
    producing trees for AND j (f1j > c) and AND j (f2j < c). Then this two
2488
 
    trees are united in one OR-tree. The expression
 
4027
    trees are united in one OR-tree. The expression 
2489
4028
      (AND j (f1j > c) OR AND j (f2j < c)
2490
4029
    is equivalent to the expression
2491
 
      AND j,k (f1j > c OR f2k < c)
2492
 
    which is just a translation of
 
4030
      AND j,k (f1j > c OR f2k < c) 
 
4031
    which is just a translation of 
2493
4032
      AND j,k (c NOT BETWEEN f1j AND f2k)
2494
4033
 
2495
4034
    In the cases when one of the items f1, f2 is a constant c1 we do not create
2502
4041
    As to IN predicates only ones of the form (f IN (c1,...,cn)),
2503
4042
    where f1 is a field and c1,...,cn are constant, are considered as
2504
4043
    SARGable. We never try to narrow the index scan using predicates of
2505
 
    the form (c IN (c1,...,f,...,cn)).
2506
 
 
2507
 
  RETURN
2508
 
    Pointer to the tree representing the built conjunction of optimizer::SEL_TREEs
 
4044
    the form (c IN (c1,...,f,...,cn)). 
 
4045
      
 
4046
  RETURN 
 
4047
    Pointer to the tree representing the built conjunction of SEL_TREEs
2509
4048
*/
2510
4049
 
2511
 
static optimizer::SEL_TREE *get_full_func_mm_tree(optimizer::RangeParameter *param,
 
4050
static SEL_TREE *get_full_func_mm_tree(RANGE_OPT_PARAM *param,
2512
4051
                                       Item_func *cond_func,
2513
 
                                       Item_field *field_item, Item *value,
 
4052
                                       Item_field *field_item, Item *value, 
2514
4053
                                       bool inv)
2515
4054
{
2516
 
  optimizer::SEL_TREE *tree= 0;
2517
 
  optimizer::SEL_TREE *ftree= 0;
 
4055
  SEL_TREE *tree= 0;
 
4056
  SEL_TREE *ftree= 0;
2518
4057
  table_map ref_tables= 0;
2519
4058
  table_map param_comp= ~(param->prev_tables | param->read_tables |
2520
4059
                          param->current_table);
2525
4064
    if (arg != field_item)
2526
4065
      ref_tables|= arg->used_tables();
2527
4066
  }
2528
 
 
2529
4067
  Field *field= field_item->field;
2530
 
  field->setWriteSet();
2531
 
 
2532
4068
  Item_result cmp_type= field->cmp_type();
2533
 
  if (!((ref_tables | field->getTable()->map) & param_comp))
 
4069
  if (!((ref_tables | field->table->map) & param_comp))
2534
4070
    ftree= get_func_mm_tree(param, cond_func, field, value, cmp_type, inv);
2535
4071
  Item_equal *item_equal= field_item->item_equal;
2536
4072
  if (item_equal)
2540
4076
    while ((item= it++))
2541
4077
    {
2542
4078
      Field *f= item->field;
2543
 
      f->setWriteSet();
2544
 
 
2545
4079
      if (field->eq(f))
2546
4080
        continue;
2547
 
      if (!((ref_tables | f->getTable()->map) & param_comp))
 
4081
      if (!((ref_tables | f->table->map) & param_comp))
2548
4082
      {
2549
4083
        tree= get_func_mm_tree(param, cond_func, f, value, cmp_type, inv);
2550
4084
        ftree= !ftree ? tree : tree_and(param, ftree, tree);
2556
4090
 
2557
4091
        /* make a select tree of all keys in condition */
2558
4092
 
2559
 
static optimizer::SEL_TREE *get_mm_tree(optimizer::RangeParameter *param, COND *cond)
 
4093
static SEL_TREE *get_mm_tree(RANGE_OPT_PARAM *param,COND *cond)
2560
4094
{
2561
 
  optimizer::SEL_TREE *tree=0;
2562
 
  optimizer::SEL_TREE *ftree= 0;
 
4095
  SEL_TREE *tree=0;
 
4096
  SEL_TREE *ftree= 0;
2563
4097
  Item_field *field_item= 0;
2564
4098
  bool inv= false;
2565
4099
  Item *value= 0;
2574
4108
      Item *item;
2575
4109
      while ((item=li++))
2576
4110
      {
2577
 
        optimizer::SEL_TREE *new_tree= get_mm_tree(param,item);
2578
 
        if (param->session->is_fatal_error ||
2579
 
            param->alloced_sel_args > optimizer::SEL_ARG::MAX_SEL_ARGS)
2580
 
          return 0;     // out of memory
 
4111
        SEL_TREE *new_tree=get_mm_tree(param,item);
 
4112
        if (param->session->is_fatal_error || 
 
4113
            param->alloced_sel_args > SEL_ARG::MAX_SEL_ARGS)
 
4114
          return(0);    // out of memory
2581
4115
        tree=tree_and(param,tree,new_tree);
2582
 
        if (tree && tree->type == optimizer::SEL_TREE::IMPOSSIBLE)
 
4116
        if (tree && tree->type == SEL_TREE::IMPOSSIBLE)
2583
4117
          break;
2584
4118
      }
2585
4119
    }
2586
4120
    else
2587
4121
    {                                           // COND OR
2588
 
      tree= get_mm_tree(param,li++);
 
4122
      tree=get_mm_tree(param,li++);
2589
4123
      if (tree)
2590
4124
      {
2591
4125
        Item *item;
2592
4126
        while ((item=li++))
2593
4127
        {
2594
 
          optimizer::SEL_TREE *new_tree= get_mm_tree(param,item);
 
4128
          SEL_TREE *new_tree=get_mm_tree(param,item);
2595
4129
          if (!new_tree)
2596
 
            return 0;   // out of memory
 
4130
            return(0);  // out of memory
2597
4131
          tree=tree_or(param,tree,new_tree);
2598
 
          if (!tree || tree->type == optimizer::SEL_TREE::ALWAYS)
 
4132
          if (!tree || tree->type == SEL_TREE::ALWAYS)
2599
4133
            break;
2600
4134
        }
2601
4135
      }
2602
4136
    }
2603
4137
    return(tree);
2604
4138
  }
2605
 
  /* Here when simple cond
2606
 
     There are limits on what kinds of const items we can evaluate, grep for
2607
 
     DontEvaluateMaterializedSubqueryTooEarly.
2608
 
  */
2609
 
  if (cond->const_item()  && !cond->is_expensive())
 
4139
  /* Here when simple cond */
 
4140
  if (cond->const_item())
2610
4141
  {
2611
4142
    /*
2612
 
      During the cond->val_int() evaluation we can come across a subselect
2613
 
      item which may allocate memory on the session->mem_root and assumes
2614
 
      all the memory allocated has the same life span as the subselect
 
4143
      During the cond->val_int() evaluation we can come across a subselect 
 
4144
      item which may allocate memory on the session->mem_root and assumes 
 
4145
      all the memory allocated has the same life span as the subselect 
2615
4146
      item itself. So we have to restore the thread's mem_root here.
2616
4147
    */
2617
 
    memory::Root *tmp_root= param->mem_root;
 
4148
    MEM_ROOT *tmp_root= param->mem_root;
2618
4149
    param->session->mem_root= param->old_root;
2619
 
    tree= cond->val_int() ? new(tmp_root) optimizer::SEL_TREE(optimizer::SEL_TREE::ALWAYS) :
2620
 
                            new(tmp_root) optimizer::SEL_TREE(optimizer::SEL_TREE::IMPOSSIBLE);
 
4150
    tree= cond->val_int() ? new(tmp_root) SEL_TREE(SEL_TREE::ALWAYS) :
 
4151
                            new(tmp_root) SEL_TREE(SEL_TREE::IMPOSSIBLE);
2621
4152
    param->session->mem_root= tmp_root;
2622
4153
    return(tree);
2623
4154
  }
2630
4161
    ref_tables= cond->used_tables();
2631
4162
    if ((ref_tables & param->current_table) ||
2632
4163
        (ref_tables & ~(param->prev_tables | param->read_tables)))
2633
 
      return 0;
2634
 
    return(new optimizer::SEL_TREE(optimizer::SEL_TREE::MAYBE));
 
4164
      return(0);
 
4165
    return(new SEL_TREE(SEL_TREE::MAYBE));
2635
4166
  }
2636
4167
 
2637
4168
  Item_func *cond_func= (Item_func*) cond;
2639
4170
      cond_func->functype() == Item_func::IN_FUNC)
2640
4171
    inv= ((Item_func_opt_neg *) cond_func)->negated;
2641
4172
  else if (cond_func->select_optimize() == Item_func::OPTIMIZE_NONE)
2642
 
    return 0;
 
4173
    return(0);                         
2643
4174
 
2644
4175
  param->cond= cond;
2645
4176
 
2660
4191
      if (cond_func->arguments()[i]->real_item()->type() == Item::FIELD_ITEM)
2661
4192
      {
2662
4193
        field_item= (Item_field*) (cond_func->arguments()[i]->real_item());
2663
 
        optimizer::SEL_TREE *tmp= get_full_func_mm_tree(param, cond_func,
 
4194
        SEL_TREE *tmp= get_full_func_mm_tree(param, cond_func, 
2664
4195
                                    field_item, (Item*)(intptr_t)i, inv);
2665
4196
        if (inv)
2666
4197
          tree= !tree ? tmp : tree_or(param, tree, tmp);
2667
 
        else
 
4198
        else 
2668
4199
          tree= tree_and(param, tree, tmp);
2669
4200
      }
2670
4201
      else if (inv)
2671
 
      {
 
4202
      { 
2672
4203
        tree= 0;
2673
4204
        break;
2674
4205
      }
2680
4211
  {
2681
4212
    Item_func_in *func=(Item_func_in*) cond_func;
2682
4213
    if (func->key_item()->real_item()->type() != Item::FIELD_ITEM)
2683
 
      return 0;
 
4214
      return(0);
2684
4215
    field_item= (Item_field*) (func->key_item()->real_item());
2685
4216
    ftree= get_full_func_mm_tree(param, cond_func, field_item, NULL, inv);
2686
4217
    break;
2687
4218
  }
2688
4219
  case Item_func::MULT_EQUAL_FUNC:
2689
4220
  {
2690
 
    Item_equal *item_equal= (Item_equal *) cond;
 
4221
    Item_equal *item_equal= (Item_equal *) cond;    
2691
4222
    if (!(value= item_equal->get_const()))
2692
 
      return 0;
 
4223
      return(0);
2693
4224
    Item_equal_iterator it(*item_equal);
2694
4225
    ref_tables= value->used_tables();
2695
4226
    while ((field_item= it++))
2696
4227
    {
2697
4228
      Field *field= field_item->field;
2698
 
      field->setWriteSet();
2699
 
 
2700
4229
      Item_result cmp_type= field->cmp_type();
2701
 
      if (!((ref_tables | field->getTable()->map) & param_comp))
 
4230
      if (!((ref_tables | field->table->map) & param_comp))
2702
4231
      {
2703
4232
        tree= get_mm_parts(param, cond, field, Item_func::EQ_FUNC,
2704
4233
                           value,cmp_type);
2705
4234
        ftree= !ftree ? tree : tree_and(param, ftree, tree);
2706
4235
      }
2707
4236
    }
2708
 
 
 
4237
    
2709
4238
    return(ftree);
2710
4239
  }
2711
4240
  default:
2722
4251
      value= cond_func->arguments()[0];
2723
4252
    }
2724
4253
    else
2725
 
      return 0;
 
4254
      return(0);
2726
4255
    ftree= get_full_func_mm_tree(param, cond_func, field_item, value, inv);
2727
4256
  }
2728
4257
 
2730
4259
}
2731
4260
 
2732
4261
 
2733
 
static optimizer::SEL_TREE *
2734
 
get_mm_parts(optimizer::RangeParameter *param,
2735
 
             COND *cond_func,
2736
 
             Field *field,
2737
 
                   Item_func::Functype type,
2738
 
                   Item *value, Item_result)
 
4262
static SEL_TREE *
 
4263
get_mm_parts(RANGE_OPT_PARAM *param, COND *cond_func, Field *field,
 
4264
             Item_func::Functype type,
 
4265
             Item *value,
 
4266
             Item_result cmp_type __attribute__((unused)))
2739
4267
{
2740
 
  if (field->getTable() != param->table)
2741
 
    return 0;
 
4268
  if (field->table != param->table)
 
4269
    return(0);
2742
4270
 
2743
4271
  KEY_PART *key_part = param->key_parts;
2744
4272
  KEY_PART *end = param->key_parts_end;
2745
 
  optimizer::SEL_TREE *tree=0;
 
4273
  SEL_TREE *tree=0;
2746
4274
  if (value &&
2747
4275
      value->used_tables() & ~(param->prev_tables | param->read_tables))
2748
 
    return 0;
2749
 
  for (; key_part != end; key_part++)
 
4276
    return(0);
 
4277
  for (; key_part != end ; key_part++)
2750
4278
  {
2751
4279
    if (field->eq(key_part->field))
2752
4280
    {
2753
 
      optimizer::SEL_ARG *sel_arg=0;
2754
 
      if (!tree && !(tree=new optimizer::SEL_TREE()))
2755
 
        return 0;                               // OOM
 
4281
      SEL_ARG *sel_arg=0;
 
4282
      if (!tree && !(tree=new SEL_TREE()))
 
4283
        return(0);                              // OOM
2756
4284
      if (!value || !(value->used_tables() & ~param->read_tables))
2757
4285
      {
2758
 
        sel_arg= get_mm_leaf(param,cond_func,
2759
 
            key_part->field,key_part,type,value);
2760
 
        if (! sel_arg)
2761
 
          continue;
2762
 
        if (sel_arg->type == optimizer::SEL_ARG::IMPOSSIBLE)
2763
 
        {
2764
 
          tree->type=optimizer::SEL_TREE::IMPOSSIBLE;
2765
 
          return(tree);
2766
 
        }
 
4286
        sel_arg=get_mm_leaf(param,cond_func,
 
4287
                            key_part->field,key_part,type,value);
 
4288
        if (!sel_arg)
 
4289
          continue;
 
4290
        if (sel_arg->type == SEL_ARG::IMPOSSIBLE)
 
4291
        {
 
4292
          tree->type=SEL_TREE::IMPOSSIBLE;
 
4293
          return(tree);
 
4294
        }
2767
4295
      }
2768
4296
      else
2769
4297
      {
2770
 
        // This key may be used later
2771
 
        if (! (sel_arg= new optimizer::SEL_ARG(optimizer::SEL_ARG::MAYBE_KEY)))
2772
 
          return 0;                     // OOM
 
4298
        // This key may be used later
 
4299
        if (!(sel_arg= new SEL_ARG(SEL_ARG::MAYBE_KEY)))
 
4300
          return(0);                    // OOM
2773
4301
      }
2774
4302
      sel_arg->part=(unsigned char) key_part->part;
2775
4303
      tree->keys[key_part->key]=sel_add(tree->keys[key_part->key],sel_arg);
2776
 
      tree->keys_map.set(key_part->key);
 
4304
      tree->keys_map.set_bit(key_part->key);
2777
4305
    }
2778
4306
  }
2779
 
 
2780
 
  return tree;
 
4307
  
 
4308
  return(tree);
2781
4309
}
2782
4310
 
2783
4311
 
2784
 
static optimizer::SEL_ARG *
2785
 
get_mm_leaf(optimizer::RangeParameter *param,
2786
 
            COND *conf_func,
2787
 
            Field *field,
2788
 
            KEY_PART *key_part,
2789
 
            Item_func::Functype type,
2790
 
            Item *value)
 
4312
static SEL_ARG *
 
4313
get_mm_leaf(RANGE_OPT_PARAM *param, COND *conf_func, Field *field,
 
4314
            KEY_PART *key_part, Item_func::Functype type,Item *value)
2791
4315
{
2792
 
  uint32_t maybe_null=(uint32_t) field->real_maybe_null();
 
4316
  uint32_t maybe_null=(uint) field->real_maybe_null();
2793
4317
  bool optimize_range;
2794
 
  optimizer::SEL_ARG *tree= NULL;
2795
 
  memory::Root *alloc= param->mem_root;
 
4318
  SEL_ARG *tree= 0;
 
4319
  MEM_ROOT *alloc= param->mem_root;
2796
4320
  unsigned char *str;
2797
 
  int err= 0;
 
4321
  ulong orig_sql_mode;
 
4322
  int err;
2798
4323
 
2799
4324
  /*
2800
4325
    We need to restore the runtime mem_root of the thread in this
2802
4327
    the argument can be any, e.g. a subselect. The subselect
2803
4328
    items, in turn, assume that all the memory allocated during
2804
4329
    the evaluation has the same life span as the item itself.
2805
 
    TODO: opitimizer/range.cc should not reset session->mem_root at all.
 
4330
    TODO: opt_range.cc should not reset session->mem_root at all.
2806
4331
  */
2807
4332
  param->session->mem_root= param->old_root;
2808
4333
  if (!value)                                   // IS NULL or IS NOT NULL
2809
4334
  {
2810
 
    if (field->getTable()->maybe_null)          // Can't use a key on this
 
4335
    if (field->table->maybe_null)               // Can't use a key on this
2811
4336
      goto end;
2812
4337
    if (!maybe_null)                            // Not null field
2813
4338
    {
2814
4339
      if (type == Item_func::ISNULL_FUNC)
2815
 
        tree= &optimizer::null_element;
 
4340
        tree= &null_element;
2816
4341
      goto end;
2817
4342
    }
2818
 
    if (!(tree= new (alloc) optimizer::SEL_ARG(field,is_null_string,is_null_string)))
 
4343
    if (!(tree= new (alloc) SEL_ARG(field,is_null_string,is_null_string)))
2819
4344
      goto end;                                 // out of memory
2820
4345
    if (type == Item_func::ISNOTNULL_FUNC)
2821
4346
    {
2839
4364
  */
2840
4365
  if (field->result_type() == STRING_RESULT &&
2841
4366
      value->result_type() == STRING_RESULT &&
 
4367
      key_part->image_type == Field::itRAW &&
2842
4368
      ((Field_str*)field)->charset() != conf_func->compare_collation() &&
2843
4369
      !(conf_func->compare_collation()->state & MY_CS_BINSORT))
2844
4370
    goto end;
2862
4388
      goto end;
2863
4389
    if (!(res= value->val_str(&tmp)))
2864
4390
    {
2865
 
      tree= &optimizer::null_element;
 
4391
      tree= &null_element;
2866
4392
      goto end;
2867
4393
    }
2868
4394
 
2892
4418
    {
2893
4419
      if (unlikely(length < field_length))
2894
4420
      {
2895
 
        /*
2896
 
          This can only happen in a table created with UNIREG where one key
2897
 
          overlaps many fields
2898
 
        */
2899
 
        length= field_length;
 
4421
        /*
 
4422
          This can only happen in a table created with UNIREG where one key
 
4423
          overlaps many fields
 
4424
        */
 
4425
        length= field_length;
2900
4426
      }
2901
4427
      else
2902
 
        field_length= length;
 
4428
        field_length= length;
2903
4429
    }
2904
4430
    length+=offset;
2905
 
    if (!(min_str= (unsigned char*) alloc->alloc_root(length*2)))
2906
 
    {
 
4431
    if (!(min_str= (unsigned char*) alloc_root(alloc, length*2)))
2907
4432
      goto end;
2908
 
    }
2909
4433
 
2910
4434
    max_str=min_str+length;
2911
4435
    if (maybe_null)
2912
4436
      max_str[0]= min_str[0]=0;
2913
4437
 
2914
4438
    field_length-= maybe_null;
2915
 
    int escape_code= make_escape_code(field->charset(),
2916
 
                                      ((Item_func_like*)(param->cond))->escape);
2917
4439
    like_error= my_like_range(field->charset(),
2918
 
                              res->ptr(), res->length(),
2919
 
                              escape_code,
2920
 
                              internal::wild_one, internal::wild_many,
2921
 
                              field_length,
2922
 
                              (char*) min_str+offset, (char*) max_str+offset,
2923
 
                              &min_length, &max_length);
 
4440
                              res->ptr(), res->length(),
 
4441
                              ((Item_func_like*)(param->cond))->escape,
 
4442
                              wild_one, wild_many,
 
4443
                              field_length,
 
4444
                              (char*) min_str+offset, (char*) max_str+offset,
 
4445
                              &min_length, &max_length);
2924
4446
    if (like_error)                             // Can't optimize with LIKE
2925
4447
      goto end;
2926
4448
 
2929
4451
      int2store(min_str+maybe_null,min_length);
2930
4452
      int2store(max_str+maybe_null,max_length);
2931
4453
    }
2932
 
    tree= new (alloc) optimizer::SEL_ARG(field, min_str, max_str);
 
4454
    tree= new (alloc) SEL_ARG(field, min_str, max_str);
2933
4455
    goto end;
2934
4456
  }
2935
4457
 
2936
 
  if (! optimize_range &&
 
4458
  if (!optimize_range &&
2937
4459
      type != Item_func::EQ_FUNC &&
2938
4460
      type != Item_func::EQUAL_FUNC)
2939
4461
    goto end;                                   // Can't optimize this
2946
4468
      value->result_type() != STRING_RESULT &&
2947
4469
      field->cmp_type() != value->result_type())
2948
4470
    goto end;
2949
 
 
2950
 
  /*
2951
 
   * Some notes from Jay...
2952
 
   *
2953
 
   * OK, so previously, and in MySQL, what the optimizer does here is
2954
 
   * override the sql_mode variable to ignore out-of-range or bad date-
2955
 
   * time values.  It does this because the optimizer is populating the
2956
 
   * field variable with the incoming value from the comparison field,
2957
 
   * and the value may exceed the bounds of a proper column type.
2958
 
   *
2959
 
   * For instance, assume the following:
2960
 
   *
2961
 
   * CREATE TABLE t1 (ts TIMESTAMP);
2962
 
   * INSERT INTO t1 ('2009-03-04 00:00:00');
2963
 
   * CREATE TABLE t2 (dt1 DATETIME, dt2 DATETIME);
2964
 
   * INSERT INT t2 ('2003-12-31 00:00:00','2999-12-31 00:00:00');
2965
 
   *
2966
 
   * If we issue this query:
2967
 
   *
2968
 
   * SELECT * FROM t1, t2 WHERE t1.ts BETWEEN t2.dt1 AND t2.dt2;
2969
 
   *
2970
 
   * We will come into bounds issues.  Field_timestamp::store() will be
2971
 
   * called with a datetime value of "2999-12-31 00:00:00" and will throw
2972
 
   * an error for out-of-bounds.  MySQL solves this via a hack with sql_mode
2973
 
   * but Drizzle always throws errors on bad data storage in a Field class.
2974
 
   *
2975
 
   * Therefore, to get around the problem of the Field class being used for
2976
 
   * "storage" here without actually storing anything...we must check to see
2977
 
   * if the value being stored in a Field_timestamp here is out of range.  If
2978
 
   * it is, then we must convert to the highest Timestamp value (or lowest,
2979
 
   * depending on whether the datetime is before or after the epoch.
2980
 
   */
2981
 
  if (field->type() == DRIZZLE_TYPE_TIMESTAMP)
2982
 
  {
2983
 
    /*
2984
 
     * The left-side of the range comparison is a timestamp field.  Therefore,
2985
 
     * we must check to see if the value in the right-hand side is outside the
2986
 
     * range of the UNIX epoch, and cut to the epoch bounds if it is.
2987
 
     */
2988
 
    /* Datetime and date columns are Item::FIELD_ITEM ... and have a result type of STRING_RESULT */
2989
 
    if (value->real_item()->type() == Item::FIELD_ITEM
2990
 
        && value->result_type() == STRING_RESULT)
2991
 
    {
2992
 
      char buff[DateTime::MAX_STRING_LENGTH];
2993
 
      String tmp(buff, sizeof(buff), &my_charset_bin);
2994
 
      String *res= value->val_str(&tmp);
2995
 
 
2996
 
      if (!res)
2997
 
        goto end;
2998
 
      else
2999
 
      {
3000
 
        /*
3001
 
         * Create a datetime from the string and compare to fixed timestamp
3002
 
         * instances representing the epoch boundaries.
3003
 
         */
3004
 
        DateTime value_datetime;
3005
 
 
3006
 
        if (! value_datetime.from_string(res->c_ptr(), (size_t) res->length()))
3007
 
          goto end;
3008
 
 
3009
 
        Timestamp max_timestamp;
3010
 
        Timestamp min_timestamp;
3011
 
 
3012
 
        (void) max_timestamp.from_time_t((time_t) INT32_MAX);
3013
 
        (void) min_timestamp.from_time_t((time_t) 0);
3014
 
 
3015
 
        /* We rely on Temporal class operator overloads to do our comparisons. */
3016
 
        if (value_datetime < min_timestamp)
3017
 
        {
3018
 
          /*
3019
 
           * Datetime in right-hand side column is before UNIX epoch, so adjust to
3020
 
           * lower bound.
3021
 
           */
3022
 
          char new_value_buff[DateTime::MAX_STRING_LENGTH];
3023
 
          int new_value_length;
3024
 
          String new_value_string(new_value_buff, sizeof(new_value_buff), &my_charset_bin);
3025
 
 
3026
 
          new_value_length= min_timestamp.to_string(new_value_string.c_ptr(),
3027
 
                                    DateTime::MAX_STRING_LENGTH);
3028
 
          assert((new_value_length+1) < DateTime::MAX_STRING_LENGTH);
3029
 
          new_value_string.length(new_value_length);
3030
 
          err= value->save_str_value_in_field(field, &new_value_string);
3031
 
        }
3032
 
        else if (value_datetime > max_timestamp)
3033
 
        {
3034
 
          /*
3035
 
           * Datetime in right hand side column is after UNIX epoch, so adjust
3036
 
           * to the higher bound of the epoch.
3037
 
           */
3038
 
          char new_value_buff[DateTime::MAX_STRING_LENGTH];
3039
 
          int new_value_length;
3040
 
          String new_value_string(new_value_buff, sizeof(new_value_buff), &my_charset_bin);
3041
 
 
3042
 
          new_value_length= max_timestamp.to_string(new_value_string.c_ptr(),
3043
 
                                        DateTime::MAX_STRING_LENGTH);
3044
 
          assert((new_value_length+1) < DateTime::MAX_STRING_LENGTH);
3045
 
          new_value_string.length(new_value_length);
3046
 
          err= value->save_str_value_in_field(field, &new_value_string);
3047
 
        }
3048
 
        else
3049
 
          err= value->save_in_field(field, 1);
3050
 
      }
3051
 
    }
3052
 
    else /* Not a datetime -> timestamp comparison */
3053
 
      err= value->save_in_field(field, 1);
3054
 
  }
3055
 
  else /* Not a timestamp comparison */
3056
 
    err= value->save_in_field(field, 1);
3057
 
 
 
4471
  /* For comparison purposes allow invalid dates like 2000-01-32 */
 
4472
  orig_sql_mode= field->table->in_use->variables.sql_mode;
 
4473
  if (value->real_item()->type() == Item::STRING_ITEM &&
 
4474
      (field->type() == DRIZZLE_TYPE_NEWDATE ||
 
4475
       field->type() == DRIZZLE_TYPE_DATETIME))
 
4476
    field->table->in_use->variables.sql_mode|= MODE_INVALID_DATES;
 
4477
  err= value->save_in_field_no_warnings(field, 1);
3058
4478
  if (err > 0)
3059
4479
  {
3060
4480
    if (field->cmp_type() != value->result_type())
3063
4483
          value->result_type() == item_cmp_type(field->result_type(),
3064
4484
                                                value->result_type()))
3065
4485
      {
3066
 
        tree= new (alloc) optimizer::SEL_ARG(field, 0, 0);
3067
 
        tree->type= optimizer::SEL_ARG::IMPOSSIBLE;
 
4486
        tree= new (alloc) SEL_ARG(field, 0, 0);
 
4487
        tree->type= SEL_ARG::IMPOSSIBLE;
3068
4488
        goto end;
3069
4489
      }
3070
4490
      else
3074
4494
          for the cases like int_field > 999999999999999999999999 as well.
3075
4495
        */
3076
4496
        tree= 0;
3077
 
        if (err == 3 && field->type() == DRIZZLE_TYPE_DATE &&
 
4497
        if (err == 3 && field->type() == DRIZZLE_TYPE_NEWDATE &&
3078
4498
            (type == Item_func::GT_FUNC || type == Item_func::GE_FUNC ||
3079
4499
             type == Item_func::LT_FUNC || type == Item_func::LE_FUNC) )
3080
4500
        {
3083
4503
            but a non-zero time part was cut off.
3084
4504
 
3085
4505
            In MySQL's SQL dialect, DATE and DATETIME are compared as datetime
3086
 
            values. Index over a DATE column uses DATE comparison. Changing
 
4506
            values. Index over a DATE column uses DATE comparison. Changing 
3087
4507
            from one comparison to the other is possible:
3088
4508
 
3089
4509
            datetime(date_col)< '2007-12-10 12:34:55' -> date_col<='2007-12-10'
3120
4540
  }
3121
4541
  else if (err < 0)
3122
4542
  {
 
4543
    field->table->in_use->variables.sql_mode= orig_sql_mode;
3123
4544
    /* This happens when we try to insert a NULL field in a not null column */
3124
 
    tree= &optimizer::null_element;                        // cmp with NULL is never true
3125
 
    goto end;
3126
 
  }
3127
 
 
3128
 
  /*
3129
 
    Any predicate except "<=>"(null-safe equality operator) involving NULL as a
3130
 
    constant is always FALSE
3131
 
    Put IMPOSSIBLE Tree(null_element) here.
3132
 
  */  
3133
 
  if (type != Item_func::EQUAL_FUNC && field->is_real_null())
3134
 
  {
3135
 
    tree= &optimizer::null_element;
3136
 
    goto end;
3137
 
  }
3138
 
 
3139
 
  str= (unsigned char*) alloc->alloc_root(key_part->store_length+1);
 
4545
    tree= &null_element;                        // cmp with NULL is never true
 
4546
    goto end;
 
4547
  }
 
4548
  field->table->in_use->variables.sql_mode= orig_sql_mode;
 
4549
  str= (unsigned char*) alloc_root(alloc, key_part->store_length+1);
3140
4550
  if (!str)
3141
4551
    goto end;
3142
4552
  if (maybe_null)
3143
4553
    *str= (unsigned char) field->is_real_null();        // Set to 1 if null
3144
 
  field->get_key_image(str+maybe_null, key_part->length);
3145
 
  if (! (tree= new (alloc) optimizer::SEL_ARG(field, str, str)))
3146
 
    goto end; // out of memory
 
4554
  field->get_key_image(str+maybe_null, key_part->length,
 
4555
                       key_part->image_type);
 
4556
  if (!(tree= new (alloc) SEL_ARG(field, str, str)))
 
4557
    goto end;                                   // out of memory
3147
4558
 
3148
4559
  /*
3149
4560
    Check if we are comparing an UNSIGNED integer with a negative constant.
3165
4576
    {
3166
4577
      if (type == Item_func::LT_FUNC || type == Item_func::LE_FUNC)
3167
4578
      {
3168
 
        tree->type= optimizer::SEL_ARG::IMPOSSIBLE;
 
4579
        tree->type= SEL_ARG::IMPOSSIBLE;
3169
4580
        goto end;
3170
4581
      }
3171
4582
      if (type == Item_func::GT_FUNC || type == Item_func::GE_FUNC)
3226
4637
  This will never be called for same key parts.
3227
4638
*/
3228
4639
 
3229
 
static optimizer::SEL_ARG *
3230
 
sel_add(optimizer::SEL_ARG *key1, optimizer::SEL_ARG *key2)
 
4640
static SEL_ARG *
 
4641
sel_add(SEL_ARG *key1,SEL_ARG *key2)
3231
4642
{
3232
 
  optimizer::SEL_ARG *root= NULL;
3233
 
  optimizer::SEL_ARG **key_link= NULL;
 
4643
  SEL_ARG *root,**key_link;
3234
4644
 
3235
4645
  if (!key1)
3236
4646
    return key2;
3259
4669
 
3260
4670
#define CLONE_KEY1_MAYBE 1
3261
4671
#define CLONE_KEY2_MAYBE 2
3262
 
 
3263
 
static uint32_t swap_clone_flag(uint32_t a)
3264
 
{
3265
 
  return ((a & 1) << 1) | ((a & 2) >> 1);
3266
 
}
3267
 
 
3268
 
static optimizer::SEL_TREE *
3269
 
tree_and(optimizer::RangeParameter *param, optimizer::SEL_TREE *tree1, optimizer::SEL_TREE *tree2)
 
4672
#define swap_clone_flag(A) ((A & 1) << 1) | ((A & 2) >> 1)
 
4673
 
 
4674
 
 
4675
static SEL_TREE *
 
4676
tree_and(RANGE_OPT_PARAM *param,SEL_TREE *tree1,SEL_TREE *tree2)
3270
4677
{
3271
4678
  if (!tree1)
3272
4679
    return(tree2);
3273
4680
  if (!tree2)
3274
4681
    return(tree1);
3275
 
  if (tree1->type == optimizer::SEL_TREE::IMPOSSIBLE || tree2->type == optimizer::SEL_TREE::ALWAYS)
 
4682
  if (tree1->type == SEL_TREE::IMPOSSIBLE || tree2->type == SEL_TREE::ALWAYS)
3276
4683
    return(tree1);
3277
 
  if (tree2->type == optimizer::SEL_TREE::IMPOSSIBLE || tree1->type == optimizer::SEL_TREE::ALWAYS)
 
4684
  if (tree2->type == SEL_TREE::IMPOSSIBLE || tree1->type == SEL_TREE::ALWAYS)
3278
4685
    return(tree2);
3279
 
  if (tree1->type == optimizer::SEL_TREE::MAYBE)
 
4686
  if (tree1->type == SEL_TREE::MAYBE)
3280
4687
  {
3281
 
    if (tree2->type == optimizer::SEL_TREE::KEY)
3282
 
      tree2->type=optimizer::SEL_TREE::KEY_SMALLER;
 
4688
    if (tree2->type == SEL_TREE::KEY)
 
4689
      tree2->type=SEL_TREE::KEY_SMALLER;
3283
4690
    return(tree2);
3284
4691
  }
3285
 
  if (tree2->type == optimizer::SEL_TREE::MAYBE)
 
4692
  if (tree2->type == SEL_TREE::MAYBE)
3286
4693
  {
3287
 
    tree1->type=optimizer::SEL_TREE::KEY_SMALLER;
 
4694
    tree1->type=SEL_TREE::KEY_SMALLER;
3288
4695
    return(tree1);
3289
4696
  }
3290
4697
  key_map  result_keys;
3291
 
  result_keys.reset();
3292
 
 
 
4698
  result_keys.clear_all();
 
4699
  
3293
4700
  /* Join the trees key per key */
3294
 
  optimizer::SEL_ARG **key1,**key2,**end;
 
4701
  SEL_ARG **key1,**key2,**end;
3295
4702
  for (key1= tree1->keys,key2= tree2->keys,end=key1+param->keys ;
3296
4703
       key1 != end ; key1++,key2++)
3297
4704
  {
3299
4706
    if (*key1 || *key2)
3300
4707
    {
3301
4708
      if (*key1 && !(*key1)->simple_key())
3302
 
        flag|=CLONE_KEY1_MAYBE;
 
4709
        flag|=CLONE_KEY1_MAYBE;
3303
4710
      if (*key2 && !(*key2)->simple_key())
3304
 
        flag|=CLONE_KEY2_MAYBE;
 
4711
        flag|=CLONE_KEY2_MAYBE;
3305
4712
      *key1=key_and(param, *key1, *key2, flag);
3306
 
      if (*key1 && (*key1)->type == optimizer::SEL_ARG::IMPOSSIBLE)
 
4713
      if (*key1 && (*key1)->type == SEL_ARG::IMPOSSIBLE)
3307
4714
      {
3308
 
        tree1->type= optimizer::SEL_TREE::IMPOSSIBLE;
 
4715
        tree1->type= SEL_TREE::IMPOSSIBLE;
3309
4716
        return(tree1);
3310
4717
      }
3311
 
      result_keys.set(key1 - tree1->keys);
 
4718
      result_keys.set_bit(key1 - tree1->keys);
 
4719
#ifdef EXTRA_DEBUG
 
4720
        if (*key1 && param->alloced_sel_args < SEL_ARG::MAX_SEL_ARGS) 
 
4721
          (*key1)->test_use_count(*key1);
 
4722
#endif
3312
4723
    }
3313
4724
  }
3314
4725
  tree1->keys_map= result_keys;
3315
4726
  /* dispose index_merge if there is a "range" option */
3316
 
  if (result_keys.any())
 
4727
  if (!result_keys.is_clear_all())
3317
4728
  {
3318
4729
    tree1->merges.empty();
3319
4730
    return(tree1);
3325
4736
}
3326
4737
 
3327
4738
 
 
4739
/*
 
4740
  Check if two SEL_TREES can be combined into one (i.e. a single key range
 
4741
  read can be constructed for "cond_of_tree1 OR cond_of_tree2" ) without
 
4742
  using index_merge.
 
4743
*/
 
4744
 
 
4745
bool sel_trees_can_be_ored(SEL_TREE *tree1, SEL_TREE *tree2, 
 
4746
                           RANGE_OPT_PARAM* param)
 
4747
{
 
4748
  key_map common_keys= tree1->keys_map;
 
4749
  common_keys.intersect(tree2->keys_map);
 
4750
 
 
4751
  if (common_keys.is_clear_all())
 
4752
    return(false);
 
4753
 
 
4754
  /* trees have a common key, check if they refer to same key part */
 
4755
  SEL_ARG **key1,**key2;
 
4756
  for (uint32_t key_no=0; key_no < param->keys; key_no++)
 
4757
  {
 
4758
    if (common_keys.is_set(key_no))
 
4759
    {
 
4760
      key1= tree1->keys + key_no;
 
4761
      key2= tree2->keys + key_no;
 
4762
      if ((*key1)->part == (*key2)->part)
 
4763
      {
 
4764
        return(true);
 
4765
      }
 
4766
    }
 
4767
  }
 
4768
  return(false);
 
4769
}
 
4770
 
 
4771
 
 
4772
/*
 
4773
  Remove the trees that are not suitable for record retrieval.
 
4774
  SYNOPSIS
 
4775
    param  Range analysis parameter
 
4776
    tree   Tree to be processed, tree->type is KEY or KEY_SMALLER
 
4777
 
 
4778
  DESCRIPTION
 
4779
    This function walks through tree->keys[] and removes the SEL_ARG* trees
 
4780
    that are not "maybe" trees (*) and cannot be used to construct quick range
 
4781
    selects.
 
4782
    (*) - have type MAYBE or MAYBE_KEY. Perhaps we should remove trees of
 
4783
          these types here as well.
 
4784
 
 
4785
    A SEL_ARG* tree cannot be used to construct quick select if it has
 
4786
    tree->part != 0. (e.g. it could represent "keypart2 < const").
 
4787
 
 
4788
    WHY THIS FUNCTION IS NEEDED
 
4789
    
 
4790
    Normally we allow construction of SEL_TREE objects that have SEL_ARG
 
4791
    trees that do not allow quick range select construction. For example for
 
4792
    " keypart1=1 AND keypart2=2 " the execution will proceed as follows:
 
4793
    tree1= SEL_TREE { SEL_ARG{keypart1=1} }
 
4794
    tree2= SEL_TREE { SEL_ARG{keypart2=2} } -- can't make quick range select
 
4795
                                               from this
 
4796
    call tree_and(tree1, tree2) -- this joins SEL_ARGs into a usable SEL_ARG
 
4797
                                   tree.
 
4798
    
 
4799
    There is an exception though: when we construct index_merge SEL_TREE,
 
4800
    any SEL_ARG* tree that cannot be used to construct quick range select can
 
4801
    be removed, because current range analysis code doesn't provide any way
 
4802
    that tree could be later combined with another tree.
 
4803
    Consider an example: we should not construct
 
4804
    st1 = SEL_TREE { 
 
4805
      merges = SEL_IMERGE { 
 
4806
                            SEL_TREE(t.key1part1 = 1), 
 
4807
                            SEL_TREE(t.key2part2 = 2)   -- (*)
 
4808
                          } 
 
4809
                   };
 
4810
    because 
 
4811
     - (*) cannot be used to construct quick range select, 
 
4812
     - There is no execution path that would cause (*) to be converted to 
 
4813
       a tree that could be used.
 
4814
 
 
4815
    The latter is easy to verify: first, notice that the only way to convert
 
4816
    (*) into a usable tree is to call tree_and(something, (*)).
 
4817
 
 
4818
    Second look at what tree_and/tree_or function would do when passed a
 
4819
    SEL_TREE that has the structure like st1 tree has, and conlcude that 
 
4820
    tree_and(something, (*)) will not be called.
 
4821
 
 
4822
  RETURN
 
4823
    0  Ok, some suitable trees left
 
4824
    1  No tree->keys[] left.
 
4825
*/
 
4826
 
 
4827
static bool remove_nonrange_trees(RANGE_OPT_PARAM *param, SEL_TREE *tree)
 
4828
{
 
4829
  bool res= false;
 
4830
  for (uint32_t i=0; i < param->keys; i++)
 
4831
  {
 
4832
    if (tree->keys[i])
 
4833
    {
 
4834
      if (tree->keys[i]->part)
 
4835
      {
 
4836
        tree->keys[i]= NULL;
 
4837
        tree->keys_map.clear_bit(i);
 
4838
      }
 
4839
      else
 
4840
        res= true;
 
4841
    }
 
4842
  }
 
4843
  return !res;
 
4844
}
 
4845
 
 
4846
 
 
4847
static SEL_TREE *
 
4848
tree_or(RANGE_OPT_PARAM *param,SEL_TREE *tree1,SEL_TREE *tree2)
 
4849
{
 
4850
  if (!tree1 || !tree2)
 
4851
    return(0);
 
4852
  if (tree1->type == SEL_TREE::IMPOSSIBLE || tree2->type == SEL_TREE::ALWAYS)
 
4853
    return(tree2);
 
4854
  if (tree2->type == SEL_TREE::IMPOSSIBLE || tree1->type == SEL_TREE::ALWAYS)
 
4855
    return(tree1);
 
4856
  if (tree1->type == SEL_TREE::MAYBE)
 
4857
    return(tree1);                              // Can't use this
 
4858
  if (tree2->type == SEL_TREE::MAYBE)
 
4859
    return(tree2);
 
4860
 
 
4861
  SEL_TREE *result= 0;
 
4862
  key_map  result_keys;
 
4863
  result_keys.clear_all();
 
4864
  if (sel_trees_can_be_ored(tree1, tree2, param))
 
4865
  {
 
4866
    /* Join the trees key per key */
 
4867
    SEL_ARG **key1,**key2,**end;
 
4868
    for (key1= tree1->keys,key2= tree2->keys,end= key1+param->keys ;
 
4869
         key1 != end ; key1++,key2++)
 
4870
    {
 
4871
      *key1=key_or(param, *key1, *key2);
 
4872
      if (*key1)
 
4873
      {
 
4874
        result=tree1;                           // Added to tree1
 
4875
        result_keys.set_bit(key1 - tree1->keys);
 
4876
#ifdef EXTRA_DEBUG
 
4877
        if (param->alloced_sel_args < SEL_ARG::MAX_SEL_ARGS) 
 
4878
          (*key1)->test_use_count(*key1);
 
4879
#endif
 
4880
      }
 
4881
    }
 
4882
    if (result)
 
4883
      result->keys_map= result_keys;
 
4884
  }
 
4885
  else
 
4886
  {
 
4887
    /* ok, two trees have KEY type but cannot be used without index merge */
 
4888
    if (tree1->merges.is_empty() && tree2->merges.is_empty())
 
4889
    {
 
4890
      if (param->remove_jump_scans)
 
4891
      {
 
4892
        bool no_trees= remove_nonrange_trees(param, tree1);
 
4893
        no_trees= no_trees || remove_nonrange_trees(param, tree2);
 
4894
        if (no_trees)
 
4895
          return(new SEL_TREE(SEL_TREE::ALWAYS));
 
4896
      }
 
4897
      SEL_IMERGE *merge;
 
4898
      /* both trees are "range" trees, produce new index merge structure */
 
4899
      if (!(result= new SEL_TREE()) || !(merge= new SEL_IMERGE()) ||
 
4900
          (result->merges.push_back(merge)) ||
 
4901
          (merge->or_sel_tree(param, tree1)) ||
 
4902
          (merge->or_sel_tree(param, tree2)))
 
4903
        result= NULL;
 
4904
      else
 
4905
        result->type= tree1->type;
 
4906
    }
 
4907
    else if (!tree1->merges.is_empty() && !tree2->merges.is_empty())
 
4908
    {
 
4909
      if (imerge_list_or_list(param, &tree1->merges, &tree2->merges))
 
4910
        result= new SEL_TREE(SEL_TREE::ALWAYS);
 
4911
      else
 
4912
        result= tree1;
 
4913
    }
 
4914
    else
 
4915
    {
 
4916
      /* one tree is index merge tree and another is range tree */
 
4917
      if (tree1->merges.is_empty())
 
4918
        std::swap(tree1, tree2);
 
4919
      
 
4920
      if (param->remove_jump_scans && remove_nonrange_trees(param, tree2))
 
4921
         return(new SEL_TREE(SEL_TREE::ALWAYS));
 
4922
      /* add tree2 to tree1->merges, checking if it collapses to ALWAYS */
 
4923
      if (imerge_list_or_tree(param, &tree1->merges, tree2))
 
4924
        result= new SEL_TREE(SEL_TREE::ALWAYS);
 
4925
      else
 
4926
        result= tree1;
 
4927
    }
 
4928
  }
 
4929
  return(result);
 
4930
}
 
4931
 
3328
4932
 
3329
4933
/* And key trees where key1->part < key2 -> part */
3330
4934
 
3331
 
static optimizer::SEL_ARG *
3332
 
and_all_keys(optimizer::RangeParameter *param,
3333
 
             optimizer::SEL_ARG *key1,
3334
 
             optimizer::SEL_ARG *key2,
 
4935
static SEL_ARG *
 
4936
and_all_keys(RANGE_OPT_PARAM *param, SEL_ARG *key1, SEL_ARG *key2, 
3335
4937
             uint32_t clone_flag)
3336
4938
{
3337
 
  optimizer::SEL_ARG *next= NULL;
 
4939
  SEL_ARG *next;
3338
4940
  ulong use_count=key1->use_count;
3339
4941
 
3340
4942
  if (key1->elements != 1)
3342
4944
    key2->use_count+=key1->elements-1; //psergey: why we don't count that key1 has n-k-p?
3343
4945
    key2->increment_use_count((int) key1->elements-1);
3344
4946
  }
3345
 
  if (key1->type == optimizer::SEL_ARG::MAYBE_KEY)
 
4947
  if (key1->type == SEL_ARG::MAYBE_KEY)
3346
4948
  {
3347
 
    key1->right= key1->left= &optimizer::null_element;
 
4949
    key1->right= key1->left= &null_element;
3348
4950
    key1->next= key1->prev= 0;
3349
4951
  }
3350
 
  for (next= key1->first(); next ; next=next->next)
 
4952
  for (next=key1->first(); next ; next=next->next)
3351
4953
  {
3352
4954
    if (next->next_key_part)
3353
4955
    {
3354
 
      optimizer::SEL_ARG *tmp= key_and(param, next->next_key_part, key2, clone_flag);
3355
 
      if (tmp && tmp->type == optimizer::SEL_ARG::IMPOSSIBLE)
 
4956
      SEL_ARG *tmp= key_and(param, next->next_key_part, key2, clone_flag);
 
4957
      if (tmp && tmp->type == SEL_ARG::IMPOSSIBLE)
3356
4958
      {
3357
 
        key1=key1->tree_delete(next);
3358
 
        continue;
 
4959
        key1=key1->tree_delete(next);
 
4960
        continue;
3359
4961
      }
3360
4962
      next->next_key_part=tmp;
3361
4963
      if (use_count)
3362
 
        next->increment_use_count(use_count);
3363
 
      if (param->alloced_sel_args > optimizer::SEL_ARG::MAX_SEL_ARGS)
 
4964
        next->increment_use_count(use_count);
 
4965
      if (param->alloced_sel_args > SEL_ARG::MAX_SEL_ARGS)
3364
4966
        break;
3365
4967
    }
3366
4968
    else
3367
4969
      next->next_key_part=key2;
3368
4970
  }
3369
 
  if (! key1)
3370
 
    return &optimizer::null_element;                    // Impossible ranges
 
4971
  if (!key1)
 
4972
    return &null_element;                       // Impossible ranges
3371
4973
  key1->use_count++;
3372
4974
  return key1;
3373
4975
}
3388
4990
    NULL if the result of AND operation is an empty interval {0}.
3389
4991
*/
3390
4992
 
3391
 
static optimizer::SEL_ARG *
3392
 
key_and(optimizer::RangeParameter *param,
3393
 
        optimizer::SEL_ARG *key1,
3394
 
        optimizer::SEL_ARG *key2,
3395
 
        uint32_t clone_flag)
 
4993
static SEL_ARG *
 
4994
key_and(RANGE_OPT_PARAM *param, SEL_ARG *key1, SEL_ARG *key2, uint32_t clone_flag)
3396
4995
{
3397
 
  if (! key1)
 
4996
  if (!key1)
3398
4997
    return key2;
3399
 
  if (! key2)
 
4998
  if (!key2)
3400
4999
    return key1;
3401
5000
  if (key1->part != key2->part)
3402
5001
  {
3408
5007
    // key1->part < key2->part
3409
5008
    key1->use_count--;
3410
5009
    if (key1->use_count > 0)
3411
 
      if (! (key1= key1->clone_tree(param)))
3412
 
        return 0;                               // OOM
 
5010
      if (!(key1= key1->clone_tree(param)))
 
5011
        return 0;                               // OOM
3413
5012
    return and_all_keys(param, key1, key2, clone_flag);
3414
5013
  }
3415
5014
 
3416
5015
  if (((clone_flag & CLONE_KEY2_MAYBE) &&
3417
 
       ! (clone_flag & CLONE_KEY1_MAYBE) &&
3418
 
       key2->type != optimizer::SEL_ARG::MAYBE_KEY) ||
3419
 
      key1->type == optimizer::SEL_ARG::MAYBE_KEY)
 
5016
       !(clone_flag & CLONE_KEY1_MAYBE) &&
 
5017
       key2->type != SEL_ARG::MAYBE_KEY) ||
 
5018
      key1->type == SEL_ARG::MAYBE_KEY)
3420
5019
  {                                             // Put simple key in key2
3421
5020
    std::swap(key1, key2);
3422
 
    clone_flag= swap_clone_flag(clone_flag);
 
5021
    clone_flag=swap_clone_flag(clone_flag);
3423
5022
  }
3424
5023
 
3425
5024
  /* If one of the key is MAYBE_KEY then the found region may be smaller */
3426
 
  if (key2->type == optimizer::SEL_ARG::MAYBE_KEY)
 
5025
  if (key2->type == SEL_ARG::MAYBE_KEY)
3427
5026
  {
3428
5027
    if (key1->use_count > 1)
3429
5028
    {
3430
5029
      key1->use_count--;
3431
 
      if (! (key1=key1->clone_tree(param)))
3432
 
        return 0;                               // OOM
 
5030
      if (!(key1=key1->clone_tree(param)))
 
5031
        return 0;                               // OOM
3433
5032
      key1->use_count++;
3434
5033
    }
3435
 
    if (key1->type == optimizer::SEL_ARG::MAYBE_KEY)
 
5034
    if (key1->type == SEL_ARG::MAYBE_KEY)
3436
5035
    {                                           // Both are maybe key
3437
 
      key1->next_key_part= key_and(param,
3438
 
                                   key1->next_key_part,
3439
 
                                   key2->next_key_part,
3440
 
                                   clone_flag);
 
5036
      key1->next_key_part=key_and(param, key1->next_key_part, 
 
5037
                                  key2->next_key_part, clone_flag);
3441
5038
      if (key1->next_key_part &&
3442
 
          key1->next_key_part->type == optimizer::SEL_ARG::IMPOSSIBLE)
3443
 
        return key1;
 
5039
          key1->next_key_part->type == SEL_ARG::IMPOSSIBLE)
 
5040
        return key1;
3444
5041
    }
3445
5042
    else
3446
5043
    {
3447
5044
      key1->maybe_smaller();
3448
5045
      if (key2->next_key_part)
3449
5046
      {
3450
 
        key1->use_count--;                      // Incremented in and_all_keys
3451
 
        return and_all_keys(param, key1, key2, clone_flag);
 
5047
        key1->use_count--;                      // Incremented in and_all_keys
 
5048
        return and_all_keys(param, key1, key2, clone_flag);
3452
5049
      }
3453
5050
      key2->use_count--;                        // Key2 doesn't have a tree
3454
5051
    }
3457
5054
 
3458
5055
  key1->use_count--;
3459
5056
  key2->use_count--;
3460
 
  optimizer::SEL_ARG *e1= key1->first();
3461
 
  optimizer::SEL_ARG *e2= key2->first();
3462
 
  optimizer::SEL_ARG *new_tree= NULL;
 
5057
  SEL_ARG *e1=key1->first(), *e2=key2->first(), *new_tree=0;
3463
5058
 
3464
5059
  while (e1 && e2)
3465
5060
  {
3466
 
    int cmp= e1->cmp_min_to_min(e2);
 
5061
    int cmp=e1->cmp_min_to_min(e2);
3467
5062
    if (cmp < 0)
3468
5063
    {
3469
 
      if (get_range(&e1, &e2, key1))
3470
 
        continue;
 
5064
      if (get_range(&e1,&e2,key1))
 
5065
        continue;
3471
5066
    }
3472
 
    else if (get_range(&e2, &e1, key2))
 
5067
    else if (get_range(&e2,&e1,key2))
3473
5068
      continue;
3474
 
    optimizer::SEL_ARG *next= key_and(param,
3475
 
                                      e1->next_key_part,
3476
 
                                      e2->next_key_part,
3477
 
                                      clone_flag);
 
5069
    SEL_ARG *next=key_and(param, e1->next_key_part, e2->next_key_part,
 
5070
                          clone_flag);
3478
5071
    e1->increment_use_count(1);
3479
5072
    e2->increment_use_count(1);
3480
 
    if (! next || next->type != optimizer::SEL_ARG::IMPOSSIBLE)
 
5073
    if (!next || next->type != SEL_ARG::IMPOSSIBLE)
3481
5074
    {
3482
 
      optimizer::SEL_ARG *new_arg= e1->clone_and(e2);
3483
 
      if (! new_arg)
3484
 
        return &optimizer::null_element;                        // End of memory
 
5075
      SEL_ARG *new_arg= e1->clone_and(e2);
 
5076
      if (!new_arg)
 
5077
        return &null_element;                   // End of memory
3485
5078
      new_arg->next_key_part=next;
3486
 
      if (! new_tree)
 
5079
      if (!new_tree)
3487
5080
      {
3488
 
        new_tree=new_arg;
 
5081
        new_tree=new_arg;
3489
5082
      }
3490
5083
      else
3491
 
        new_tree=new_tree->insert(new_arg);
 
5084
        new_tree=new_tree->insert(new_arg);
3492
5085
    }
3493
5086
    if (e1->cmp_max_to_max(e2) < 0)
3494
5087
      e1=e1->next;                              // e1 can't overlapp next e2
3497
5090
  }
3498
5091
  key1->free_tree();
3499
5092
  key2->free_tree();
3500
 
  if (! new_tree)
3501
 
    return &optimizer::null_element;                    // Impossible range
 
5093
  if (!new_tree)
 
5094
    return &null_element;                       // Impossible range
3502
5095
  return new_tree;
3503
5096
}
3504
5097
 
3505
5098
 
3506
5099
static bool
3507
 
get_range(optimizer::SEL_ARG **e1, optimizer::SEL_ARG **e2, optimizer::SEL_ARG *root1)
 
5100
get_range(SEL_ARG **e1,SEL_ARG **e2,SEL_ARG *root1)
3508
5101
{
3509
 
  (*e1)= root1->find_range(*e2);                        // first e1->min < e2->min
 
5102
  (*e1)=root1->find_range(*e2);                 // first e1->min < e2->min
3510
5103
  if ((*e1)->cmp_max_to_min(*e2) < 0)
3511
5104
  {
3512
 
    if (! ((*e1)=(*e1)->next))
 
5105
    if (!((*e1)=(*e1)->next))
3513
5106
      return 1;
3514
5107
    if ((*e1)->cmp_min_to_max(*e2) > 0)
3515
5108
    {
3521
5114
}
3522
5115
 
3523
5116
 
 
5117
static SEL_ARG *
 
5118
key_or(RANGE_OPT_PARAM *param, SEL_ARG *key1,SEL_ARG *key2)
 
5119
{
 
5120
  if (!key1)
 
5121
  {
 
5122
    if (key2)
 
5123
    {
 
5124
      key2->use_count--;
 
5125
      key2->free_tree();
 
5126
    }
 
5127
    return 0;
 
5128
  }
 
5129
  if (!key2)
 
5130
  {
 
5131
    key1->use_count--;
 
5132
    key1->free_tree();
 
5133
    return 0;
 
5134
  }
 
5135
  key1->use_count--;
 
5136
  key2->use_count--;
 
5137
 
 
5138
  if (key1->part != key2->part)
 
5139
  {
 
5140
    key1->free_tree();
 
5141
    key2->free_tree();
 
5142
    return 0;                                   // Can't optimize this
 
5143
  }
 
5144
 
 
5145
  // If one of the key is MAYBE_KEY then the found region may be bigger
 
5146
  if (key1->type == SEL_ARG::MAYBE_KEY)
 
5147
  {
 
5148
    key2->free_tree();
 
5149
    key1->use_count++;
 
5150
    return key1;
 
5151
  }
 
5152
  if (key2->type == SEL_ARG::MAYBE_KEY)
 
5153
  {
 
5154
    key1->free_tree();
 
5155
    key2->use_count++;
 
5156
    return key2;
 
5157
  }
 
5158
 
 
5159
  if (key1->use_count > 0)
 
5160
  {
 
5161
    if (key2->use_count == 0 || key1->elements > key2->elements)
 
5162
    {
 
5163
      std::swap(key1,key2);
 
5164
    }
 
5165
    if (key1->use_count > 0 || !(key1=key1->clone_tree(param)))
 
5166
      return 0;                                 // OOM
 
5167
  }
 
5168
 
 
5169
  // Add tree at key2 to tree at key1
 
5170
  bool key2_shared=key2->use_count != 0;
 
5171
  key1->maybe_flag|=key2->maybe_flag;
 
5172
 
 
5173
  for (key2=key2->first(); key2; )
 
5174
  {
 
5175
    SEL_ARG *tmp=key1->find_range(key2);        // Find key1.min <= key2.min
 
5176
    int cmp;
 
5177
 
 
5178
    if (!tmp)
 
5179
    {
 
5180
      tmp=key1->first();                        // tmp.min > key2.min
 
5181
      cmp= -1;
 
5182
    }
 
5183
    else if ((cmp=tmp->cmp_max_to_min(key2)) < 0)
 
5184
    {                                           // Found tmp.max < key2.min
 
5185
      SEL_ARG *next=tmp->next;
 
5186
      if (cmp == -2 && eq_tree(tmp->next_key_part,key2->next_key_part))
 
5187
      {
 
5188
        // Join near ranges like tmp.max < 0 and key2.min >= 0
 
5189
        SEL_ARG *key2_next=key2->next;
 
5190
        if (key2_shared)
 
5191
        {
 
5192
          if (!(key2=new SEL_ARG(*key2)))
 
5193
            return 0;           // out of memory
 
5194
          key2->increment_use_count(key1->use_count+1);
 
5195
          key2->next=key2_next;                 // New copy of key2
 
5196
        }
 
5197
        key2->copy_min(tmp);
 
5198
        if (!(key1=key1->tree_delete(tmp)))
 
5199
        {                                       // Only one key in tree
 
5200
          key1=key2;
 
5201
          key1->make_root();
 
5202
          key2=key2_next;
 
5203
          break;
 
5204
        }
 
5205
      }
 
5206
      if (!(tmp=next))                          // tmp.min > key2.min
 
5207
        break;                                  // Copy rest of key2
 
5208
    }
 
5209
    if (cmp < 0)
 
5210
    {                                           // tmp.min > key2.min
 
5211
      int tmp_cmp;
 
5212
      if ((tmp_cmp=tmp->cmp_min_to_max(key2)) > 0) // if tmp.min > key2.max
 
5213
      {
 
5214
        if (tmp_cmp == 2 && eq_tree(tmp->next_key_part,key2->next_key_part))
 
5215
        {                                       // ranges are connected
 
5216
          tmp->copy_min_to_min(key2);
 
5217
          key1->merge_flags(key2);
 
5218
          if (tmp->min_flag & NO_MIN_RANGE &&
 
5219
              tmp->max_flag & NO_MAX_RANGE)
 
5220
          {
 
5221
            if (key1->maybe_flag)
 
5222
              return new SEL_ARG(SEL_ARG::MAYBE_KEY);
 
5223
            return 0;
 
5224
          }
 
5225
          key2->increment_use_count(-1);        // Free not used tree
 
5226
          key2=key2->next;
 
5227
          continue;
 
5228
        }
 
5229
        else
 
5230
        {
 
5231
          SEL_ARG *next=key2->next;             // Keys are not overlapping
 
5232
          if (key2_shared)
 
5233
          {
 
5234
            SEL_ARG *cpy= new SEL_ARG(*key2);   // Must make copy
 
5235
            if (!cpy)
 
5236
              return 0;                         // OOM
 
5237
            key1=key1->insert(cpy);
 
5238
            key2->increment_use_count(key1->use_count+1);
 
5239
          }
 
5240
          else
 
5241
            key1=key1->insert(key2);            // Will destroy key2_root
 
5242
          key2=next;
 
5243
          continue;
 
5244
        }
 
5245
      }
 
5246
    }
 
5247
 
 
5248
    // tmp.max >= key2.min && tmp.min <= key.cmax(overlapping ranges)
 
5249
    if (eq_tree(tmp->next_key_part,key2->next_key_part))
 
5250
    {
 
5251
      if (tmp->is_same(key2))
 
5252
      {
 
5253
        tmp->merge_flags(key2);                 // Copy maybe flags
 
5254
        key2->increment_use_count(-1);          // Free not used tree
 
5255
      }
 
5256
      else
 
5257
      {
 
5258
        SEL_ARG *last=tmp;
 
5259
        while (last->next && last->next->cmp_min_to_max(key2) <= 0 &&
 
5260
               eq_tree(last->next->next_key_part,key2->next_key_part))
 
5261
        {
 
5262
          SEL_ARG *save=last;
 
5263
          last=last->next;
 
5264
          key1=key1->tree_delete(save);
 
5265
        }
 
5266
        last->copy_min(tmp);
 
5267
        if (last->copy_min(key2) || last->copy_max(key2))
 
5268
        {                                       // Full range
 
5269
          key1->free_tree();
 
5270
          for (; key2 ; key2=key2->next)
 
5271
            key2->increment_use_count(-1);      // Free not used tree
 
5272
          if (key1->maybe_flag)
 
5273
            return new SEL_ARG(SEL_ARG::MAYBE_KEY);
 
5274
          return 0;
 
5275
        }
 
5276
      }
 
5277
      key2=key2->next;
 
5278
      continue;
 
5279
    }
 
5280
 
 
5281
    if (cmp >= 0 && tmp->cmp_min_to_min(key2) < 0)
 
5282
    {                                           // tmp.min <= x < key2.min
 
5283
      SEL_ARG *new_arg=tmp->clone_first(key2);
 
5284
      if (!new_arg)
 
5285
        return 0;                               // OOM
 
5286
      if ((new_arg->next_key_part= key1->next_key_part))
 
5287
        new_arg->increment_use_count(key1->use_count+1);
 
5288
      tmp->copy_min_to_min(key2);
 
5289
      key1=key1->insert(new_arg);
 
5290
    }
 
5291
 
 
5292
    // tmp.min >= key2.min && tmp.min <= key2.max
 
5293
    SEL_ARG key(*key2);                         // Get copy we can modify
 
5294
    for (;;)
 
5295
    {
 
5296
      if (tmp->cmp_min_to_min(&key) > 0)
 
5297
      {                                         // key.min <= x < tmp.min
 
5298
        SEL_ARG *new_arg=key.clone_first(tmp);
 
5299
        if (!new_arg)
 
5300
          return 0;                             // OOM
 
5301
        if ((new_arg->next_key_part=key.next_key_part))
 
5302
          new_arg->increment_use_count(key1->use_count+1);
 
5303
        key1=key1->insert(new_arg);
 
5304
      }
 
5305
      if ((cmp=tmp->cmp_max_to_max(&key)) <= 0)
 
5306
      {                                         // tmp.min. <= x <= tmp.max
 
5307
        tmp->maybe_flag|= key.maybe_flag;
 
5308
        key.increment_use_count(key1->use_count+1);
 
5309
        tmp->next_key_part= key_or(param, tmp->next_key_part, key.next_key_part);
 
5310
        if (!cmp)                               // Key2 is ready
 
5311
          break;
 
5312
        key.copy_max_to_min(tmp);
 
5313
        if (!(tmp=tmp->next))
 
5314
        {
 
5315
          SEL_ARG *tmp2= new SEL_ARG(key);
 
5316
          if (!tmp2)
 
5317
            return 0;                           // OOM
 
5318
          key1=key1->insert(tmp2);
 
5319
          key2=key2->next;
 
5320
          goto end;
 
5321
        }
 
5322
        if (tmp->cmp_min_to_max(&key) > 0)
 
5323
        {
 
5324
          SEL_ARG *tmp2= new SEL_ARG(key);
 
5325
          if (!tmp2)
 
5326
            return 0;                           // OOM
 
5327
          key1=key1->insert(tmp2);
 
5328
          break;
 
5329
        }
 
5330
      }
 
5331
      else
 
5332
      {
 
5333
        SEL_ARG *new_arg=tmp->clone_last(&key); // tmp.min <= x <= key.max
 
5334
        if (!new_arg)
 
5335
          return 0;                             // OOM
 
5336
        tmp->copy_max_to_min(&key);
 
5337
        tmp->increment_use_count(key1->use_count+1);
 
5338
        /* Increment key count as it may be used for next loop */
 
5339
        key.increment_use_count(1);
 
5340
        new_arg->next_key_part= key_or(param, tmp->next_key_part, key.next_key_part);
 
5341
        key1=key1->insert(new_arg);
 
5342
        break;
 
5343
      }
 
5344
    }
 
5345
    key2=key2->next;
 
5346
  }
 
5347
 
 
5348
end:
 
5349
  while (key2)
 
5350
  {
 
5351
    SEL_ARG *next=key2->next;
 
5352
    if (key2_shared)
 
5353
    {
 
5354
      SEL_ARG *tmp=new SEL_ARG(*key2);          // Must make copy
 
5355
      if (!tmp)
 
5356
        return 0;
 
5357
      key2->increment_use_count(key1->use_count+1);
 
5358
      key1=key1->insert(tmp);
 
5359
    }
 
5360
    else
 
5361
      key1=key1->insert(key2);                  // Will destroy key2_root
 
5362
    key2=next;
 
5363
  }
 
5364
  key1->use_count++;
 
5365
  return key1;
 
5366
}
 
5367
 
 
5368
 
 
5369
/* Compare if two trees are equal */
 
5370
 
 
5371
static bool eq_tree(SEL_ARG* a,SEL_ARG *b)
 
5372
{
 
5373
  if (a == b)
 
5374
    return 1;
 
5375
  if (!a || !b || !a->is_same(b))
 
5376
    return 0;
 
5377
  if (a->left != &null_element && b->left != &null_element)
 
5378
  {
 
5379
    if (!eq_tree(a->left,b->left))
 
5380
      return 0;
 
5381
  }
 
5382
  else if (a->left != &null_element || b->left != &null_element)
 
5383
    return 0;
 
5384
  if (a->right != &null_element && b->right != &null_element)
 
5385
  {
 
5386
    if (!eq_tree(a->right,b->right))
 
5387
      return 0;
 
5388
  }
 
5389
  else if (a->right != &null_element || b->right != &null_element)
 
5390
    return 0;
 
5391
  if (a->next_key_part != b->next_key_part)
 
5392
  {                                             // Sub range
 
5393
    if (!a->next_key_part != !b->next_key_part ||
 
5394
        !eq_tree(a->next_key_part, b->next_key_part))
 
5395
      return 0;
 
5396
  }
 
5397
  return 1;
 
5398
}
 
5399
 
 
5400
 
 
5401
SEL_ARG *
 
5402
SEL_ARG::insert(SEL_ARG *key)
 
5403
{
 
5404
  SEL_ARG *element, **par= NULL, *last_element= NULL;
 
5405
 
 
5406
  for (element= this; element != &null_element ; )
 
5407
  {
 
5408
    last_element=element;
 
5409
    if (key->cmp_min_to_min(element) > 0)
 
5410
    {
 
5411
      par= &element->right; element= element->right;
 
5412
    }
 
5413
    else
 
5414
    {
 
5415
      par = &element->left; element= element->left;
 
5416
    }
 
5417
  }
 
5418
  *par=key;
 
5419
  key->parent=last_element;
 
5420
        /* Link in list */
 
5421
  if (par == &last_element->left)
 
5422
  {
 
5423
    key->next=last_element;
 
5424
    if ((key->prev=last_element->prev))
 
5425
      key->prev->next=key;
 
5426
    last_element->prev=key;
 
5427
  }
 
5428
  else
 
5429
  {
 
5430
    if ((key->next=last_element->next))
 
5431
      key->next->prev=key;
 
5432
    key->prev=last_element;
 
5433
    last_element->next=key;
 
5434
  }
 
5435
  key->left=key->right= &null_element;
 
5436
  SEL_ARG *root=rb_insert(key);                 // rebalance tree
 
5437
  root->use_count=this->use_count;              // copy root info
 
5438
  root->elements= this->elements+1;
 
5439
  root->maybe_flag=this->maybe_flag;
 
5440
  return root;
 
5441
}
 
5442
 
 
5443
 
 
5444
/*
 
5445
** Find best key with min <= given key
 
5446
** Because the call context this should never return 0 to get_range
 
5447
*/
 
5448
 
 
5449
SEL_ARG *
 
5450
SEL_ARG::find_range(SEL_ARG *key)
 
5451
{
 
5452
  SEL_ARG *element=this,*found=0;
 
5453
 
 
5454
  for (;;)
 
5455
  {
 
5456
    if (element == &null_element)
 
5457
      return found;
 
5458
    int cmp=element->cmp_min_to_min(key);
 
5459
    if (cmp == 0)
 
5460
      return element;
 
5461
    if (cmp < 0)
 
5462
    {
 
5463
      found=element;
 
5464
      element=element->right;
 
5465
    }
 
5466
    else
 
5467
      element=element->left;
 
5468
  }
 
5469
}
 
5470
 
 
5471
 
 
5472
/*
 
5473
  Remove a element from the tree
 
5474
 
 
5475
  SYNOPSIS
 
5476
    tree_delete()
 
5477
    key         Key that is to be deleted from tree (this)
 
5478
 
 
5479
  NOTE
 
5480
    This also frees all sub trees that is used by the element
 
5481
 
 
5482
  RETURN
 
5483
    root of new tree (with key deleted)
 
5484
*/
 
5485
 
 
5486
SEL_ARG *
 
5487
SEL_ARG::tree_delete(SEL_ARG *key)
 
5488
{
 
5489
  enum leaf_color remove_color;
 
5490
  SEL_ARG *root,*nod,**par,*fix_par;
 
5491
 
 
5492
  root=this;
 
5493
  this->parent= 0;
 
5494
 
 
5495
  /* Unlink from list */
 
5496
  if (key->prev)
 
5497
    key->prev->next=key->next;
 
5498
  if (key->next)
 
5499
    key->next->prev=key->prev;
 
5500
  key->increment_use_count(-1);
 
5501
  if (!key->parent)
 
5502
    par= &root;
 
5503
  else
 
5504
    par=key->parent_ptr();
 
5505
 
 
5506
  if (key->left == &null_element)
 
5507
  {
 
5508
    *par=nod=key->right;
 
5509
    fix_par=key->parent;
 
5510
    if (nod != &null_element)
 
5511
      nod->parent=fix_par;
 
5512
    remove_color= key->color;
 
5513
  }
 
5514
  else if (key->right == &null_element)
 
5515
  {
 
5516
    *par= nod=key->left;
 
5517
    nod->parent=fix_par=key->parent;
 
5518
    remove_color= key->color;
 
5519
  }
 
5520
  else
 
5521
  {
 
5522
    SEL_ARG *tmp=key->next;                     // next bigger key (exist!)
 
5523
    nod= *tmp->parent_ptr()= tmp->right;        // unlink tmp from tree
 
5524
    fix_par=tmp->parent;
 
5525
    if (nod != &null_element)
 
5526
      nod->parent=fix_par;
 
5527
    remove_color= tmp->color;
 
5528
 
 
5529
    tmp->parent=key->parent;                    // Move node in place of key
 
5530
    (tmp->left=key->left)->parent=tmp;
 
5531
    if ((tmp->right=key->right) != &null_element)
 
5532
      tmp->right->parent=tmp;
 
5533
    tmp->color=key->color;
 
5534
    *par=tmp;
 
5535
    if (fix_par == key)                         // key->right == key->next
 
5536
      fix_par=tmp;                              // new parent of nod
 
5537
  }
 
5538
 
 
5539
  if (root == &null_element)
 
5540
    return(0);                          // Maybe root later
 
5541
  if (remove_color == BLACK)
 
5542
    root=rb_delete_fixup(root,nod,fix_par);
 
5543
#ifdef EXTRA_DEBUG
 
5544
  test_rb_tree(root,root->parent);
 
5545
#endif /* EXTRA_DEBUG */
 
5546
 
 
5547
  root->use_count=this->use_count;              // Fix root counters
 
5548
  root->elements=this->elements-1;
 
5549
  root->maybe_flag=this->maybe_flag;
 
5550
  return(root);
 
5551
}
 
5552
 
 
5553
 
 
5554
        /* Functions to fix up the tree after insert and delete */
 
5555
 
 
5556
static void left_rotate(SEL_ARG **root,SEL_ARG *leaf)
 
5557
{
 
5558
  SEL_ARG *y=leaf->right;
 
5559
  leaf->right=y->left;
 
5560
  if (y->left != &null_element)
 
5561
    y->left->parent=leaf;
 
5562
  if (!(y->parent=leaf->parent))
 
5563
    *root=y;
 
5564
  else
 
5565
    *leaf->parent_ptr()=y;
 
5566
  y->left=leaf;
 
5567
  leaf->parent=y;
 
5568
}
 
5569
 
 
5570
static void right_rotate(SEL_ARG **root,SEL_ARG *leaf)
 
5571
{
 
5572
  SEL_ARG *y=leaf->left;
 
5573
  leaf->left=y->right;
 
5574
  if (y->right != &null_element)
 
5575
    y->right->parent=leaf;
 
5576
  if (!(y->parent=leaf->parent))
 
5577
    *root=y;
 
5578
  else
 
5579
    *leaf->parent_ptr()=y;
 
5580
  y->right=leaf;
 
5581
  leaf->parent=y;
 
5582
}
 
5583
 
 
5584
 
 
5585
SEL_ARG *
 
5586
SEL_ARG::rb_insert(SEL_ARG *leaf)
 
5587
{
 
5588
  SEL_ARG *y,*par,*par2,*root;
 
5589
  root= this; root->parent= 0;
 
5590
 
 
5591
  leaf->color=RED;
 
5592
  while (leaf != root && (par= leaf->parent)->color == RED)
 
5593
  {                                     // This can't be root or 1 level under
 
5594
    if (par == (par2= leaf->parent->parent)->left)
 
5595
    {
 
5596
      y= par2->right;
 
5597
      if (y->color == RED)
 
5598
      {
 
5599
        par->color=BLACK;
 
5600
        y->color=BLACK;
 
5601
        leaf=par2;
 
5602
        leaf->color=RED;                /* And the loop continues */
 
5603
      }
 
5604
      else
 
5605
      {
 
5606
        if (leaf == par->right)
 
5607
        {
 
5608
          left_rotate(&root,leaf->parent);
 
5609
          par=leaf;                     /* leaf is now parent to old leaf */
 
5610
        }
 
5611
        par->color=BLACK;
 
5612
        par2->color=RED;
 
5613
        right_rotate(&root,par2);
 
5614
        break;
 
5615
      }
 
5616
    }
 
5617
    else
 
5618
    {
 
5619
      y= par2->left;
 
5620
      if (y->color == RED)
 
5621
      {
 
5622
        par->color=BLACK;
 
5623
        y->color=BLACK;
 
5624
        leaf=par2;
 
5625
        leaf->color=RED;                /* And the loop continues */
 
5626
      }
 
5627
      else
 
5628
      {
 
5629
        if (leaf == par->left)
 
5630
        {
 
5631
          right_rotate(&root,par);
 
5632
          par=leaf;
 
5633
        }
 
5634
        par->color=BLACK;
 
5635
        par2->color=RED;
 
5636
        left_rotate(&root,par2);
 
5637
        break;
 
5638
      }
 
5639
    }
 
5640
  }
 
5641
  root->color=BLACK;
 
5642
#ifdef EXTRA_DEBUG
 
5643
  test_rb_tree(root,root->parent);
 
5644
#endif /* EXTRA_DEBUG */
 
5645
 
 
5646
  return root;
 
5647
}
 
5648
 
 
5649
 
 
5650
SEL_ARG *rb_delete_fixup(SEL_ARG *root,SEL_ARG *key,SEL_ARG *par)
 
5651
{
 
5652
  SEL_ARG *x,*w;
 
5653
  root->parent=0;
 
5654
 
 
5655
  x= key;
 
5656
  while (x != root && x->color == SEL_ARG::BLACK)
 
5657
  {
 
5658
    if (x == par->left)
 
5659
    {
 
5660
      w=par->right;
 
5661
      if (w->color == SEL_ARG::RED)
 
5662
      {
 
5663
        w->color=SEL_ARG::BLACK;
 
5664
        par->color=SEL_ARG::RED;
 
5665
        left_rotate(&root,par);
 
5666
        w=par->right;
 
5667
      }
 
5668
      if (w->left->color == SEL_ARG::BLACK && w->right->color == SEL_ARG::BLACK)
 
5669
      {
 
5670
        w->color=SEL_ARG::RED;
 
5671
        x=par;
 
5672
      }
 
5673
      else
 
5674
      {
 
5675
        if (w->right->color == SEL_ARG::BLACK)
 
5676
        {
 
5677
          w->left->color=SEL_ARG::BLACK;
 
5678
          w->color=SEL_ARG::RED;
 
5679
          right_rotate(&root,w);
 
5680
          w=par->right;
 
5681
        }
 
5682
        w->color=par->color;
 
5683
        par->color=SEL_ARG::BLACK;
 
5684
        w->right->color=SEL_ARG::BLACK;
 
5685
        left_rotate(&root,par);
 
5686
        x=root;
 
5687
        break;
 
5688
      }
 
5689
    }
 
5690
    else
 
5691
    {
 
5692
      w=par->left;
 
5693
      if (w->color == SEL_ARG::RED)
 
5694
      {
 
5695
        w->color=SEL_ARG::BLACK;
 
5696
        par->color=SEL_ARG::RED;
 
5697
        right_rotate(&root,par);
 
5698
        w=par->left;
 
5699
      }
 
5700
      if (w->right->color == SEL_ARG::BLACK && w->left->color == SEL_ARG::BLACK)
 
5701
      {
 
5702
        w->color=SEL_ARG::RED;
 
5703
        x=par;
 
5704
      }
 
5705
      else
 
5706
      {
 
5707
        if (w->left->color == SEL_ARG::BLACK)
 
5708
        {
 
5709
          w->right->color=SEL_ARG::BLACK;
 
5710
          w->color=SEL_ARG::RED;
 
5711
          left_rotate(&root,w);
 
5712
          w=par->left;
 
5713
        }
 
5714
        w->color=par->color;
 
5715
        par->color=SEL_ARG::BLACK;
 
5716
        w->left->color=SEL_ARG::BLACK;
 
5717
        right_rotate(&root,par);
 
5718
        x=root;
 
5719
        break;
 
5720
      }
 
5721
    }
 
5722
    par=x->parent;
 
5723
  }
 
5724
  x->color=SEL_ARG::BLACK;
 
5725
  return root;
 
5726
}
 
5727
 
 
5728
 
 
5729
        /* Test that the properties for a red-black tree hold */
 
5730
 
 
5731
#ifdef EXTRA_DEBUG
 
5732
int test_rb_tree(SEL_ARG *element,SEL_ARG *parent)
 
5733
{
 
5734
  int count_l,count_r;
 
5735
 
 
5736
  if (element == &null_element)
 
5737
    return 0;                                   // Found end of tree
 
5738
  if (element->parent != parent)
 
5739
  {
 
5740
    sql_print_error("Wrong tree: Parent doesn't point at parent");
 
5741
    return -1;
 
5742
  }
 
5743
  if (element->color == SEL_ARG::RED &&
 
5744
      (element->left->color == SEL_ARG::RED ||
 
5745
       element->right->color == SEL_ARG::RED))
 
5746
  {
 
5747
    sql_print_error("Wrong tree: Found two red in a row");
 
5748
    return -1;
 
5749
  }
 
5750
  if (element->left == element->right && element->left != &null_element)
 
5751
  {                                             // Dummy test
 
5752
    sql_print_error("Wrong tree: Found right == left");
 
5753
    return -1;
 
5754
  }
 
5755
  count_l=test_rb_tree(element->left,element);
 
5756
  count_r=test_rb_tree(element->right,element);
 
5757
  if (count_l >= 0 && count_r >= 0)
 
5758
  {
 
5759
    if (count_l == count_r)
 
5760
      return count_l+(element->color == SEL_ARG::BLACK);
 
5761
    sql_print_error("Wrong tree: Incorrect black-count: %d - %d",
 
5762
            count_l,count_r);
 
5763
  }
 
5764
  return -1;                                    // Error, no more warnings
 
5765
}
 
5766
 
 
5767
 
 
5768
/*
 
5769
  Count how many times SEL_ARG graph "root" refers to its part "key"
 
5770
  
 
5771
  SYNOPSIS
 
5772
    count_key_part_usage()
 
5773
      root  An RB-Root node in a SEL_ARG graph.
 
5774
      key   Another RB-Root node in that SEL_ARG graph.
 
5775
 
 
5776
  DESCRIPTION
 
5777
    The passed "root" node may refer to "key" node via root->next_key_part,
 
5778
    root->next->n
 
5779
 
 
5780
    This function counts how many times the node "key" is referred (via
 
5781
    SEL_ARG::next_key_part) by 
 
5782
     - intervals of RB-tree pointed by "root", 
 
5783
     - intervals of RB-trees that are pointed by SEL_ARG::next_key_part from 
 
5784
       intervals of RB-tree pointed by "root",
 
5785
     - and so on.
 
5786
    
 
5787
    Here is an example (horizontal links represent next_key_part pointers, 
 
5788
    vertical links - next/prev prev pointers):  
 
5789
    
 
5790
         +----+               $
 
5791
         |root|-----------------+
 
5792
         +----+               $ |
 
5793
           |                  $ |
 
5794
           |                  $ |
 
5795
         +----+       +---+   $ |     +---+    Here the return value
 
5796
         |    |- ... -|   |---$-+--+->|key|    will be 4.
 
5797
         +----+       +---+   $ |  |  +---+
 
5798
           |                  $ |  |
 
5799
          ...                 $ |  |
 
5800
           |                  $ |  |
 
5801
         +----+   +---+       $ |  |
 
5802
         |    |---|   |---------+  |
 
5803
         +----+   +---+       $    |
 
5804
           |        |         $    |
 
5805
          ...     +---+       $    |
 
5806
                  |   |------------+
 
5807
                  +---+       $
 
5808
  RETURN 
 
5809
    Number of links to "key" from nodes reachable from "root".
 
5810
*/
 
5811
 
 
5812
static ulong count_key_part_usage(SEL_ARG *root, SEL_ARG *key)
 
5813
{
 
5814
  ulong count= 0;
 
5815
  for (root=root->first(); root ; root=root->next)
 
5816
  {
 
5817
    if (root->next_key_part)
 
5818
    {
 
5819
      if (root->next_key_part == key)
 
5820
        count++;
 
5821
      if (root->next_key_part->part < key->part)
 
5822
        count+=count_key_part_usage(root->next_key_part,key);
 
5823
    }
 
5824
  }
 
5825
  return count;
 
5826
}
 
5827
 
 
5828
 
 
5829
/*
 
5830
  Check if SEL_ARG::use_count value is correct
 
5831
 
 
5832
  SYNOPSIS
 
5833
    SEL_ARG::test_use_count()
 
5834
      root  The root node of the SEL_ARG graph (an RB-tree root node that
 
5835
            has the least value of sel_arg->part in the entire graph, and
 
5836
            thus is the "origin" of the graph)
 
5837
 
 
5838
  DESCRIPTION
 
5839
    Check if SEL_ARG::use_count value is correct. See the definition of
 
5840
    use_count for what is "correct".
 
5841
*/
 
5842
 
 
5843
void SEL_ARG::test_use_count(SEL_ARG *root)
 
5844
{
 
5845
  uint32_t e_count=0;
 
5846
  if (this == root && use_count != 1)
 
5847
  {
 
5848
    sql_print_information("Use_count: Wrong count %lu for root",use_count);
 
5849
    return;
 
5850
  }
 
5851
  if (this->type != SEL_ARG::KEY_RANGE)
 
5852
    return;
 
5853
  for (SEL_ARG *pos=first(); pos ; pos=pos->next)
 
5854
  {
 
5855
    e_count++;
 
5856
    if (pos->next_key_part)
 
5857
    {
 
5858
      ulong count=count_key_part_usage(root,pos->next_key_part);
 
5859
      if (count > pos->next_key_part->use_count)
 
5860
      {
 
5861
        sql_print_information("Use_count: Wrong count for key at 0x%lx, %lu "
 
5862
                              "should be %lu", (long unsigned int)pos,
 
5863
                              pos->next_key_part->use_count, count);
 
5864
        return;
 
5865
      }
 
5866
      pos->next_key_part->test_use_count(root);
 
5867
    }
 
5868
  }
 
5869
  if (e_count != elements)
 
5870
    sql_print_warning("Wrong use count: %u (should be %u) for tree at 0x%lx",
 
5871
                      e_count, elements, (long unsigned int) this);
 
5872
}
 
5873
 
 
5874
#endif
 
5875
 
3524
5876
/****************************************************************************
3525
5877
  MRR Range Sequence Interface implementation that walks a SEL_ARG* tree.
3526
5878
 ****************************************************************************/
3527
5879
 
3528
5880
/* MRR range sequence, SEL_ARG* implementation: stack entry */
3529
 
typedef struct st_range_seq_entry
 
5881
typedef struct st_range_seq_entry 
3530
5882
{
3531
 
  /*
 
5883
  /* 
3532
5884
    Pointers in min and max keys. They point to right-after-end of key
3533
5885
    images. The 0-th entry has these pointing to key tuple start.
3534
5886
  */
3535
5887
  unsigned char *min_key, *max_key;
3536
 
 
3537
 
  /*
 
5888
  
 
5889
  /* 
3538
5890
    Flags, for {keypart0, keypart1, ... this_keypart} subtuple.
3539
5891
    min_key_flag may have NULL_RANGE set.
3540
5892
  */
3541
5893
  uint32_t min_key_flag, max_key_flag;
3542
 
 
 
5894
  
3543
5895
  /* Number of key parts */
3544
5896
  uint32_t min_key_parts, max_key_parts;
3545
 
  optimizer::SEL_ARG *key_tree;
 
5897
  SEL_ARG *key_tree;
3546
5898
} RANGE_SEQ_ENTRY;
3547
5899
 
3548
5900
 
3551
5903
*/
3552
5904
typedef struct st_sel_arg_range_seq
3553
5905
{
3554
 
  uint32_t keyno;      /* index of used tree in optimizer::SEL_TREE structure */
 
5906
  uint32_t keyno;      /* index of used tree in SEL_TREE structure */
3555
5907
  uint32_t real_keyno; /* Number of the index in tables */
3556
 
  optimizer::Parameter *param;
3557
 
  optimizer::SEL_ARG *start; /* Root node of the traversed SEL_ARG* graph */
3558
 
 
 
5908
  PARAM *param;
 
5909
  SEL_ARG *start; /* Root node of the traversed SEL_ARG* graph */
 
5910
  
3559
5911
  RANGE_SEQ_ENTRY stack[MAX_REF_PARTS];
3560
5912
  int i; /* Index of last used element in the above array */
3561
 
 
 
5913
  
3562
5914
  bool at_start; /* true <=> The traversal has just started */
3563
5915
} SEL_ARG_RANGE_SEQ;
3564
5916
 
3569
5921
  SYNOPSIS
3570
5922
    init()
3571
5923
      init_params  SEL_ARG tree traversal context
3572
 
      n_ranges     [ignored] The number of ranges obtained
 
5924
      n_ranges     [ignored] The number of ranges obtained 
3573
5925
      flags        [ignored] HA_MRR_SINGLE_POINT, HA_MRR_FIXED_KEY
3574
5926
 
3575
5927
  RETURN
3576
5928
    Value of init_param
3577
5929
*/
3578
5930
 
3579
 
static range_seq_t sel_arg_range_seq_init(void *init_param, uint32_t, uint32_t)
 
5931
range_seq_t sel_arg_range_seq_init(void *init_param,
 
5932
                                   uint32_t n_ranges __attribute__((unused)),
 
5933
                                   uint32_t flags __attribute__((unused)))
3580
5934
{
3581
5935
  SEL_ARG_RANGE_SEQ *seq= (SEL_ARG_RANGE_SEQ*)init_param;
3582
5936
  seq->at_start= true;
3593
5947
}
3594
5948
 
3595
5949
 
3596
 
static void step_down_to(SEL_ARG_RANGE_SEQ *arg, optimizer::SEL_ARG *key_tree)
 
5950
static void step_down_to(SEL_ARG_RANGE_SEQ *arg, SEL_ARG *key_tree)
3597
5951
{
3598
5952
  RANGE_SEQ_ENTRY *cur= &arg->stack[arg->i+1];
3599
5953
  RANGE_SEQ_ENTRY *prev= &arg->stack[arg->i];
3600
 
 
 
5954
  
3601
5955
  cur->key_tree= key_tree;
3602
5956
  cur->min_key= prev->min_key;
3603
5957
  cur->max_key= prev->max_key;
3621
5975
 
3622
5976
/*
3623
5977
  Range sequence interface, SEL_ARG* implementation: get the next interval
3624
 
 
 
5978
  
3625
5979
  SYNOPSIS
3626
5980
    sel_arg_range_seq_next()
3627
5981
      rseq        Value returned from sel_arg_range_seq_init
3643
5997
*/
3644
5998
 
3645
5999
//psergey-merge-todo: support check_quick_keys:max_keypart
3646
 
static uint32_t sel_arg_range_seq_next(range_seq_t rseq, KEY_MULTI_RANGE *range)
 
6000
uint32_t sel_arg_range_seq_next(range_seq_t rseq, KEY_MULTI_RANGE *range)
3647
6001
{
3648
 
  optimizer::SEL_ARG *key_tree;
 
6002
  SEL_ARG *key_tree;
3649
6003
  SEL_ARG_RANGE_SEQ *seq= (SEL_ARG_RANGE_SEQ*)rseq;
3650
6004
  if (seq->at_start)
3651
6005
  {
3656
6010
 
3657
6011
  key_tree= seq->stack[seq->i].key_tree;
3658
6012
  /* Ok, we're at some "full tuple" position in the tree */
3659
 
 
 
6013
 
3660
6014
  /* Step down if we can */
3661
 
  if (key_tree->next && key_tree->next != &optimizer::null_element)
 
6015
  if (key_tree->next && key_tree->next != &null_element)
3662
6016
  {
3663
6017
    //step down; (update the tuple, we'll step right and stay there)
3664
6018
    seq->i--;
3678
6032
    key_tree= seq->stack[seq->i].key_tree;
3679
6033
 
3680
6034
    /* Step down if we can */
3681
 
    if (key_tree->next && key_tree->next != &optimizer::null_element)
 
6035
    if (key_tree->next && key_tree->next != &null_element)
3682
6036
    {
3683
6037
      // Step down; update the tuple
3684
6038
      seq->i--;
3693
6047
    Walk right-up while we can
3694
6048
  */
3695
6049
walk_right_n_up:
3696
 
  while (key_tree->next_key_part && key_tree->next_key_part != &optimizer::null_element &&
 
6050
  while (key_tree->next_key_part && key_tree->next_key_part != &null_element && 
3697
6051
         key_tree->next_key_part->part == key_tree->part + 1 &&
3698
 
         key_tree->next_key_part->type == optimizer::SEL_ARG::KEY_RANGE)
 
6052
         key_tree->next_key_part->type == SEL_ARG::KEY_RANGE)
3699
6053
  {
3700
6054
    {
3701
6055
      RANGE_SEQ_ENTRY *cur= &seq->stack[seq->i];
3702
6056
      uint32_t min_key_length= cur->min_key - seq->param->min_key;
3703
6057
      uint32_t max_key_length= cur->max_key - seq->param->max_key;
3704
6058
      uint32_t len= cur->min_key - cur[-1].min_key;
3705
 
      if (! (min_key_length == max_key_length &&
3706
 
          ! memcmp(cur[-1].min_key, cur[-1].max_key, len) &&
3707
 
          ! key_tree->min_flag && !key_tree->max_flag))
 
6059
      if (!(min_key_length == max_key_length &&
 
6060
            !memcmp(cur[-1].min_key, cur[-1].max_key, len) &&
 
6061
            !key_tree->min_flag && !key_tree->max_flag))
3708
6062
      {
3709
6063
        seq->param->is_ror_scan= false;
3710
 
        if (! key_tree->min_flag)
3711
 
          cur->min_key_parts +=
 
6064
        if (!key_tree->min_flag)
 
6065
          cur->min_key_parts += 
3712
6066
            key_tree->next_key_part->store_min_key(seq->param->key[seq->keyno],
3713
6067
                                                   &cur->min_key,
3714
6068
                                                   &cur->min_key_flag);
3715
 
        if (! key_tree->max_flag)
3716
 
          cur->max_key_parts +=
 
6069
        if (!key_tree->max_flag)
 
6070
          cur->max_key_parts += 
3717
6071
            key_tree->next_key_part->store_max_key(seq->param->key[seq->keyno],
3718
6072
                                                   &cur->max_key,
3719
6073
                                                   &cur->max_key_flag);
3720
6074
        break;
3721
6075
      }
3722
6076
    }
3723
 
 
 
6077
  
3724
6078
    /*
3725
6079
      Ok, current atomic interval is in form "t.field=const" and there is
3726
6080
      next_key_part interval. Step right, and walk up from there.
3728
6082
    key_tree= key_tree->next_key_part;
3729
6083
 
3730
6084
walk_up_n_right:
3731
 
    while (key_tree->prev && key_tree->prev != &optimizer::null_element)
 
6085
    while (key_tree->prev && key_tree->prev != &null_element)
3732
6086
    {
3733
6087
      /* Step up */
3734
6088
      key_tree= key_tree->prev;
3738
6092
 
3739
6093
  /* Ok got a tuple */
3740
6094
  RANGE_SEQ_ENTRY *cur= &seq->stack[seq->i];
3741
 
 
3742
 
  range->ptr= (char*)(size_t)(key_tree->part);
 
6095
  
 
6096
  range->ptr= (char*)(int)(key_tree->part);
3743
6097
  {
3744
6098
    range->range_flag= cur->min_key_flag | cur->max_key_flag;
3745
 
 
 
6099
    
3746
6100
    range->start_key.key=    seq->param->min_key;
3747
6101
    range->start_key.length= cur->min_key - seq->param->min_key;
3748
6102
    range->start_key.keypart_map= make_prev_keypart_map(cur->min_key_parts);
3749
 
    range->start_key.flag= (cur->min_key_flag & NEAR_MIN ? HA_READ_AFTER_KEY :
 
6103
    range->start_key.flag= (cur->min_key_flag & NEAR_MIN ? HA_READ_AFTER_KEY : 
3750
6104
                                                           HA_READ_KEY_EXACT);
3751
6105
 
3752
6106
    range->end_key.key=    seq->param->max_key;
3753
6107
    range->end_key.length= cur->max_key - seq->param->max_key;
3754
 
    range->end_key.flag= (cur->max_key_flag & NEAR_MAX ? HA_READ_BEFORE_KEY :
 
6108
    range->end_key.flag= (cur->max_key_flag & NEAR_MAX ? HA_READ_BEFORE_KEY : 
3755
6109
                                                         HA_READ_AFTER_KEY);
3756
6110
    range->end_key.keypart_map= make_prev_keypart_map(cur->max_key_parts);
3757
6111
 
3758
6112
    if (!(cur->min_key_flag & ~NULL_RANGE) && !cur->max_key_flag &&
3759
 
        (uint32_t)key_tree->part+1 == seq->param->table->key_info[seq->real_keyno].key_parts &&
 
6113
        (uint)key_tree->part+1 == seq->param->table->key_info[seq->real_keyno].key_parts &&
3760
6114
        (seq->param->table->key_info[seq->real_keyno].flags & (HA_NOSAME)) ==
3761
6115
        HA_NOSAME &&
3762
6116
        range->start_key.length == range->end_key.length &&
3763
6117
        !memcmp(seq->param->min_key,seq->param->max_key,range->start_key.length))
3764
6118
      range->range_flag= UNIQUE_RANGE | (cur->min_key_flag & NULL_RANGE);
3765
 
 
 
6119
      
3766
6120
    if (seq->param->is_ror_scan)
3767
6121
    {
3768
6122
      /*
3782
6136
    }
3783
6137
  }
3784
6138
  seq->param->range_count++;
3785
 
  seq->param->max_key_part= max(seq->param->max_key_part,(uint32_t)key_tree->part);
 
6139
  seq->param->max_key_part=cmax(seq->param->max_key_part,(uint)key_tree->part);
3786
6140
  return 0;
3787
6141
}
3788
6142
 
3789
6143
 
3790
6144
/*
3791
 
  Calculate cost and E(#rows) for a given index and intervals tree
 
6145
  Calculate cost and E(#rows) for a given index and intervals tree 
3792
6146
 
3793
6147
  SYNOPSIS
3794
6148
    check_quick_select()
3795
6149
      param             Parameter from test_quick_select
3796
 
      idx               Number of index to use in Parameter::key optimizer::SEL_TREE::key
 
6150
      idx               Number of index to use in PARAM::key SEL_TREE::key
3797
6151
      index_only        true  - assume only index tuples will be accessed
3798
6152
                        false - assume full table rows will be read
3799
6153
      tree              Transformed selection condition, tree->key[idx] holds
3811
6165
 
3812
6166
  RETURN
3813
6167
    Estimate # of records to be retrieved.
3814
 
    HA_POS_ERROR if estimate calculation failed due to table Cursor problems.
 
6168
    HA_POS_ERROR if estimate calculation failed due to table handler problems.
3815
6169
*/
3816
6170
 
3817
6171
static
3818
 
ha_rows check_quick_select(Session *session,
3819
 
                           optimizer::Parameter *param,
3820
 
                           uint32_t idx,
3821
 
                           bool index_only,
3822
 
                           optimizer::SEL_ARG *tree,
3823
 
                           bool update_tbl_stats,
3824
 
                           uint32_t *mrr_flags,
3825
 
                           uint32_t *bufsize,
3826
 
                           optimizer::CostVector *cost)
 
6172
ha_rows check_quick_select(PARAM *param, uint32_t idx, bool index_only,
 
6173
                           SEL_ARG *tree, bool update_tbl_stats, 
 
6174
                           uint32_t *mrr_flags, uint32_t *bufsize, COST_VECT *cost)
3827
6175
{
3828
6176
  SEL_ARG_RANGE_SEQ seq;
3829
6177
  RANGE_SEQ_IF seq_if = {sel_arg_range_seq_init, sel_arg_range_seq_next};
3830
 
  Cursor *cursor= param->table->cursor;
 
6178
  handler *file= param->table->file;
3831
6179
  ha_rows rows;
3832
6180
  uint32_t keynr= param->real_keynr[idx];
3833
 
 
 
6181
  
3834
6182
  /* Handle cases when we don't have a valid non-empty list of range */
3835
 
  if (! tree)
 
6183
  if (!tree)
3836
6184
    return(HA_POS_ERROR);
3837
 
  if (tree->type == optimizer::SEL_ARG::IMPOSSIBLE)
 
6185
  if (tree->type == SEL_ARG::IMPOSSIBLE)
3838
6186
    return(0L);
3839
 
  if (tree->type != optimizer::SEL_ARG::KEY_RANGE || tree->part != 0)
 
6187
  if (tree->type != SEL_ARG::KEY_RANGE || tree->part != 0)
3840
6188
    return(HA_POS_ERROR);
3841
6189
 
3842
6190
  seq.keyno= idx;
3848
6196
  param->max_key_part=0;
3849
6197
 
3850
6198
  param->is_ror_scan= true;
3851
 
  if (param->table->index_flags(keynr) & HA_KEY_SCAN_NOT_ROR)
 
6199
  if (file->index_flags(keynr, 0, true) & HA_KEY_SCAN_NOT_ROR)
3852
6200
    param->is_ror_scan= false;
3853
 
 
 
6201
  
3854
6202
  *mrr_flags= param->force_default_mrr? HA_MRR_USE_DEFAULT_IMPL: 0;
3855
6203
  *mrr_flags|= HA_MRR_NO_ASSOCIATION;
3856
6204
 
3857
 
  bool pk_is_clustered= cursor->primary_key_is_clustered();
3858
 
  if (index_only &&
3859
 
      (param->table->index_flags(keynr) & HA_KEYREAD_ONLY) &&
3860
 
      !(pk_is_clustered && keynr == param->table->getShare()->getPrimaryKey()))
 
6205
  bool pk_is_clustered= file->primary_key_is_clustered();
 
6206
  if (index_only && 
 
6207
      (file->index_flags(keynr, param->max_key_part, 1) & HA_KEYREAD_ONLY) &&
 
6208
      !(pk_is_clustered && keynr == param->table->s->primary_key))
3861
6209
     *mrr_flags |= HA_MRR_INDEX_ONLY;
3862
 
 
3863
 
  if (session->lex->sql_command != SQLCOM_SELECT)
 
6210
  
 
6211
  if (current_session->lex->sql_command != SQLCOM_SELECT)
3864
6212
    *mrr_flags |= HA_MRR_USE_DEFAULT_IMPL;
3865
6213
 
3866
6214
  *bufsize= param->session->variables.read_rnd_buff_size;
3867
 
  rows= cursor->multi_range_read_info_const(keynr, &seq_if, (void*)&seq, 0,
 
6215
  rows= file->multi_range_read_info_const(keynr, &seq_if, (void*)&seq, 0,
3868
6216
                                          bufsize, mrr_flags, cost);
3869
6217
  if (rows != HA_POS_ERROR)
3870
6218
  {
3871
6219
    param->table->quick_rows[keynr]=rows;
3872
6220
    if (update_tbl_stats)
3873
6221
    {
3874
 
      param->table->quick_keys.set(keynr);
 
6222
      param->table->quick_keys.set_bit(keynr);
3875
6223
      param->table->quick_key_parts[keynr]=param->max_key_part+1;
3876
6224
      param->table->quick_n_ranges[keynr]= param->range_count;
3877
6225
      param->table->quick_condition_rows=
3878
 
        min(param->table->quick_condition_rows, rows);
 
6226
        cmin(param->table->quick_condition_rows, rows);
3879
6227
    }
3880
6228
  }
3881
6229
  /* Figure out if the key scan is ROR (returns rows in ROWID order) or not */
3882
6230
  enum ha_key_alg key_alg= param->table->key_info[seq.real_keyno].algorithm;
3883
6231
  if ((key_alg != HA_KEY_ALG_BTREE) && (key_alg!= HA_KEY_ALG_UNDEF))
3884
6232
  {
3885
 
    /*
 
6233
    /* 
3886
6234
      All scans are non-ROR scans for those index types.
3887
 
      TODO: Don't have this logic here, make table engines return
 
6235
      TODO: Don't have this logic here, make table engines return 
3888
6236
      appropriate flags instead.
3889
6237
    */
3890
6238
    param->is_ror_scan= false;
3892
6240
  else
3893
6241
  {
3894
6242
    /* Clustered PK scan is always a ROR scan (TODO: same as above) */
3895
 
    if (param->table->getShare()->getPrimaryKey() == keynr && pk_is_clustered)
 
6243
    if (param->table->s->primary_key == keynr && pk_is_clustered)
3896
6244
      param->is_ror_scan= true;
3897
6245
  }
3898
6246
 
3923
6271
 
3924
6272
    where the index is defined on (key1_1, ..., key1_N [,a_1, ..., a_n])
3925
6273
 
3926
 
    and the table has a clustered Primary Key defined as
3927
 
      PRIMARY KEY(a_1, ..., a_n, b1, ..., b_k)
3928
 
 
3929
 
    i.e. the first key parts of it are identical to uncovered parts ot the
 
6274
    and the table has a clustered Primary Key defined as 
 
6275
      PRIMARY KEY(a_1, ..., a_n, b1, ..., b_k) 
 
6276
    
 
6277
    i.e. the first key parts of it are identical to uncovered parts ot the 
3930
6278
    key being scanned. This function assumes that the index flags do not
3931
6279
    include HA_KEY_SCAN_NOT_ROR flag (that is checked elsewhere).
3932
6280
 
3937
6285
    false  Otherwise
3938
6286
*/
3939
6287
 
3940
 
static bool is_key_scan_ror(optimizer::Parameter *param, uint32_t keynr, uint8_t nparts)
 
6288
static bool is_key_scan_ror(PARAM *param, uint32_t keynr, uint8_t nparts)
3941
6289
{
3942
 
  KeyInfo *table_key= param->table->key_info + keynr;
3943
 
  KeyPartInfo *key_part= table_key->key_part + nparts;
3944
 
  KeyPartInfo *key_part_end= (table_key->key_part +
 
6290
  KEY *table_key= param->table->key_info + keynr;
 
6291
  KEY_PART_INFO *key_part= table_key->key_part + nparts;
 
6292
  KEY_PART_INFO *key_part_end= (table_key->key_part +
3945
6293
                                table_key->key_parts);
3946
6294
  uint32_t pk_number;
3947
 
 
3948
 
  for (KeyPartInfo *kp= table_key->key_part; kp < key_part; kp++)
 
6295
  
 
6296
  for (KEY_PART_INFO *kp= table_key->key_part; kp < key_part; kp++)
3949
6297
  {
3950
6298
    uint16_t fieldnr= param->table->key_info[keynr].
3951
6299
                    key_part[kp - table_key->key_part].fieldnr - 1;
3952
 
    if (param->table->getField(fieldnr)->key_length() != kp->length)
 
6300
    if (param->table->field[fieldnr]->key_length() != kp->length)
3953
6301
      return false;
3954
6302
  }
3955
6303
 
3957
6305
    return true;
3958
6306
 
3959
6307
  key_part= table_key->key_part + nparts;
3960
 
  pk_number= param->table->getShare()->getPrimaryKey();
3961
 
  if (!param->table->cursor->primary_key_is_clustered() || pk_number == MAX_KEY)
 
6308
  pk_number= param->table->s->primary_key;
 
6309
  if (!param->table->file->primary_key_is_clustered() || pk_number == MAX_KEY)
3962
6310
    return false;
3963
6311
 
3964
 
  KeyPartInfo *pk_part= param->table->key_info[pk_number].key_part;
3965
 
  KeyPartInfo *pk_part_end= pk_part +
 
6312
  KEY_PART_INFO *pk_part= param->table->key_info[pk_number].key_part;
 
6313
  KEY_PART_INFO *pk_part_end= pk_part +
3966
6314
                              param->table->key_info[pk_number].key_parts;
3967
6315
  for (;(key_part!=key_part_end) && (pk_part != pk_part_end);
3968
6316
       ++key_part, ++pk_part)
3975
6323
}
3976
6324
 
3977
6325
 
3978
 
optimizer::QuickRangeSelect *
3979
 
optimizer::get_quick_select(Parameter *param,
3980
 
                            uint32_t idx,
3981
 
                            optimizer::SEL_ARG *key_tree,
3982
 
                            uint32_t mrr_flags,
3983
 
                            uint32_t mrr_buf_size,
3984
 
                            memory::Root *parent_alloc)
 
6326
/*
 
6327
  Create a QUICK_RANGE_SELECT from given key and SEL_ARG tree for that key.
 
6328
 
 
6329
  SYNOPSIS
 
6330
    get_quick_select()
 
6331
      param
 
6332
      idx            Index of used key in param->key.
 
6333
      key_tree       SEL_ARG tree for the used key
 
6334
      mrr_flags      MRR parameter for quick select
 
6335
      mrr_buf_size   MRR parameter for quick select
 
6336
      parent_alloc   If not NULL, use it to allocate memory for
 
6337
                     quick select data. Otherwise use quick->alloc.
 
6338
  NOTES
 
6339
    The caller must call QUICK_SELECT::init for returned quick select.
 
6340
 
 
6341
    CAUTION! This function may change session->mem_root to a MEM_ROOT which will be
 
6342
    deallocated when the returned quick select is deleted.
 
6343
 
 
6344
  RETURN
 
6345
    NULL on error
 
6346
    otherwise created quick select
 
6347
*/
 
6348
 
 
6349
QUICK_RANGE_SELECT *
 
6350
get_quick_select(PARAM *param,uint32_t idx,SEL_ARG *key_tree, uint32_t mrr_flags,
 
6351
                 uint32_t mrr_buf_size, MEM_ROOT *parent_alloc)
3985
6352
{
3986
 
  optimizer::QuickRangeSelect *quick= new optimizer::QuickRangeSelect(param->session,
3987
 
                                                                      param->table,
3988
 
                                                                      param->real_keynr[idx],
3989
 
                                                                      test(parent_alloc),
3990
 
                                                                      NULL);
 
6353
  QUICK_RANGE_SELECT *quick;
 
6354
  bool create_err= false;
 
6355
 
 
6356
  quick=new QUICK_RANGE_SELECT(param->session, param->table,
 
6357
                               param->real_keynr[idx],
 
6358
                               test(parent_alloc), NULL, &create_err);
3991
6359
 
3992
6360
  if (quick)
3993
6361
  {
3994
 
          if (get_quick_keys(param,
3995
 
                       quick,
3996
 
                       param->key[idx],
3997
 
                       key_tree,
3998
 
                       param->min_key,
3999
 
                       0,
4000
 
                                   param->max_key,
4001
 
                       0))
 
6362
    if (create_err ||
 
6363
        get_quick_keys(param,quick,param->key[idx],key_tree,param->min_key,0,
 
6364
                       param->max_key,0))
4002
6365
    {
4003
6366
      delete quick;
4004
 
      quick= NULL;
 
6367
      quick=0;
4005
6368
    }
4006
6369
    else
4007
6370
    {
4008
6371
      quick->mrr_flags= mrr_flags;
4009
6372
      quick->mrr_buf_size= mrr_buf_size;
4010
 
      if (parent_alloc)
4011
 
      {
4012
 
        quick->key_parts=(KEY_PART*)
4013
 
          parent_alloc->memdup_root( (char*) param->key[idx], sizeof(KEY_PART)* param->table->key_info[param->real_keynr[idx]].key_parts);
4014
 
      }
4015
 
      else
4016
 
      {
4017
 
        quick->key_parts=(KEY_PART*)
4018
 
          quick->alloc.memdup_root((char*) param->key[idx], sizeof(KEY_PART)* param->table->key_info[param->real_keynr[idx]].key_parts);
4019
 
      }
 
6373
      quick->key_parts=(KEY_PART*)
 
6374
        memdup_root(parent_alloc? parent_alloc : &quick->alloc,
 
6375
                    (char*) param->key[idx],
 
6376
                    sizeof(KEY_PART)*
 
6377
                    param->table->key_info[param->real_keynr[idx]].key_parts);
4020
6378
    }
4021
6379
  }
4022
 
  return quick;
 
6380
  return(quick);
4023
6381
}
4024
6382
 
4025
6383
 
4027
6385
** Fix this to get all possible sub_ranges
4028
6386
*/
4029
6387
bool
4030
 
optimizer::get_quick_keys(optimizer::Parameter *param,
4031
 
                          optimizer::QuickRangeSelect *quick,
4032
 
                          KEY_PART *key,
4033
 
                                optimizer::SEL_ARG *key_tree,
4034
 
                          unsigned char *min_key,
4035
 
                          uint32_t min_key_flag,
4036
 
                                unsigned char *max_key,
4037
 
                          uint32_t max_key_flag)
 
6388
get_quick_keys(PARAM *param,QUICK_RANGE_SELECT *quick,KEY_PART *key,
 
6389
               SEL_ARG *key_tree, unsigned char *min_key,uint32_t min_key_flag,
 
6390
               unsigned char *max_key, uint32_t max_key_flag)
4038
6391
{
4039
 
  optimizer::QuickRange *range= NULL;
 
6392
  QUICK_RANGE *range;
4040
6393
  uint32_t flag;
4041
 
  int min_part= key_tree->part - 1; // # of keypart values in min_key buffer
4042
 
  int max_part= key_tree->part - 1; // # of keypart values in max_key buffer
 
6394
  int min_part= key_tree->part-1, // # of keypart values in min_key buffer
 
6395
      max_part= key_tree->part-1; // # of keypart values in max_key buffer
4043
6396
 
4044
 
  if (key_tree->left != &optimizer::null_element)
 
6397
  if (key_tree->left != &null_element)
4045
6398
  {
4046
 
    if (get_quick_keys(param,
4047
 
                       quick,
4048
 
                       key,
4049
 
                       key_tree->left,
4050
 
                                   min_key,
4051
 
                       min_key_flag,
4052
 
                       max_key,
4053
 
                       max_key_flag))
4054
 
    {
 
6399
    if (get_quick_keys(param,quick,key,key_tree->left,
 
6400
                       min_key,min_key_flag, max_key, max_key_flag))
4055
6401
      return 1;
4056
 
    }
4057
6402
  }
4058
 
  unsigned char *tmp_min_key= min_key,*tmp_max_key= max_key;
 
6403
  unsigned char *tmp_min_key=min_key,*tmp_max_key=max_key;
4059
6404
  min_part+= key_tree->store_min(key[key_tree->part].store_length,
4060
6405
                                 &tmp_min_key,min_key_flag);
4061
6406
  max_part+= key_tree->store_max(key[key_tree->part].store_length,
4063
6408
 
4064
6409
  if (key_tree->next_key_part &&
4065
6410
      key_tree->next_key_part->part == key_tree->part+1 &&
4066
 
      key_tree->next_key_part->type == optimizer::SEL_ARG::KEY_RANGE)
 
6411
      key_tree->next_key_part->type == SEL_ARG::KEY_RANGE)
4067
6412
  {                                               // const key as prefix
4068
6413
    if ((tmp_min_key - min_key) == (tmp_max_key - max_key) &&
4069
 
        memcmp(min_key, max_key, (uint32_t)(tmp_max_key - max_key))==0 &&
4070
 
        key_tree->min_flag==0 && key_tree->max_flag==0)
 
6414
         memcmp(min_key, max_key, (uint)(tmp_max_key - max_key))==0 &&
 
6415
         key_tree->min_flag==0 && key_tree->max_flag==0)
4071
6416
    {
4072
 
      if (get_quick_keys(param,
4073
 
                         quick,
4074
 
                         key,
4075
 
                         key_tree->next_key_part,
4076
 
                         tmp_min_key,
4077
 
                         min_key_flag | key_tree->min_flag,
4078
 
                         tmp_max_key,
4079
 
                         max_key_flag | key_tree->max_flag))
4080
 
      {
4081
 
        return 1;
4082
 
      }
 
6417
      if (get_quick_keys(param,quick,key,key_tree->next_key_part,
 
6418
                         tmp_min_key, min_key_flag | key_tree->min_flag,
 
6419
                         tmp_max_key, max_key_flag | key_tree->max_flag))
 
6420
        return 1;
4083
6421
      goto end;                                 // Ugly, but efficient
4084
6422
    }
4085
6423
    {
4086
6424
      uint32_t tmp_min_flag=key_tree->min_flag,tmp_max_flag=key_tree->max_flag;
4087
 
      if (! tmp_min_flag)
4088
 
      {
4089
 
        min_part+= key_tree->next_key_part->store_min_key(key,
4090
 
                                                          &tmp_min_key,
 
6425
      if (!tmp_min_flag)
 
6426
        min_part+= key_tree->next_key_part->store_min_key(key, &tmp_min_key,
4091
6427
                                                          &tmp_min_flag);
4092
 
      }
4093
 
      if (! tmp_max_flag)
4094
 
      {
4095
 
        max_part+= key_tree->next_key_part->store_max_key(key,
4096
 
                                                          &tmp_max_key,
 
6428
      if (!tmp_max_flag)
 
6429
        max_part+= key_tree->next_key_part->store_max_key(key, &tmp_max_key,
4097
6430
                                                          &tmp_max_flag);
4098
 
      }
4099
6431
      flag=tmp_min_flag | tmp_max_flag;
4100
6432
    }
4101
6433
  }
4108
6440
    Ensure that some part of min_key and max_key are used.  If not,
4109
6441
    regard this as no lower/upper range
4110
6442
  */
4111
 
  if (tmp_min_key != param->min_key)
4112
 
  {
4113
 
    flag&= ~NO_MIN_RANGE;
4114
 
  }
4115
 
  else
4116
 
  {
4117
 
    flag|= NO_MIN_RANGE;
4118
 
  }
4119
 
  if (tmp_max_key != param->max_key)
4120
 
  {
4121
 
    flag&= ~NO_MAX_RANGE;
4122
 
  }
4123
 
  else
4124
 
  {
4125
 
    flag|= NO_MAX_RANGE;
 
6443
  {
 
6444
    if (tmp_min_key != param->min_key)
 
6445
      flag&= ~NO_MIN_RANGE;
 
6446
    else
 
6447
      flag|= NO_MIN_RANGE;
 
6448
    if (tmp_max_key != param->max_key)
 
6449
      flag&= ~NO_MAX_RANGE;
 
6450
    else
 
6451
      flag|= NO_MAX_RANGE;
4126
6452
  }
4127
6453
  if (flag == 0)
4128
6454
  {
4129
 
    uint32_t length= (uint32_t) (tmp_min_key - param->min_key);
4130
 
    if (length == (uint32_t) (tmp_max_key - param->max_key) &&
4131
 
              ! memcmp(param->min_key,param->max_key,length))
 
6455
    uint32_t length= (uint) (tmp_min_key - param->min_key);
 
6456
    if (length == (uint) (tmp_max_key - param->max_key) &&
 
6457
        !memcmp(param->min_key,param->max_key,length))
4132
6458
    {
4133
 
      KeyInfo *table_key= quick->head->key_info+quick->index;
4134
 
      flag= EQ_RANGE;
 
6459
      KEY *table_key=quick->head->key_info+quick->index;
 
6460
      flag=EQ_RANGE;
4135
6461
      if ((table_key->flags & (HA_NOSAME)) == HA_NOSAME &&
4136
 
                key->part == table_key->key_parts-1)
 
6462
          key->part == table_key->key_parts-1)
4137
6463
      {
4138
 
        if (! (table_key->flags & HA_NULL_PART_KEY) ||
4139
 
            ! null_part_in_key(key,
4140
 
                               param->min_key,
4141
 
                               (uint32_t) (tmp_min_key - param->min_key)))
4142
 
        {
4143
 
          flag|= UNIQUE_RANGE;
4144
 
        }
4145
 
        else
4146
 
        {
4147
 
          flag|= NULL_RANGE;
4148
 
        }
 
6464
        if (!(table_key->flags & HA_NULL_PART_KEY) ||
 
6465
            !null_part_in_key(key,
 
6466
                              param->min_key,
 
6467
                              (uint) (tmp_min_key - param->min_key)))
 
6468
          flag|= UNIQUE_RANGE;
 
6469
        else
 
6470
          flag|= NULL_RANGE;
4149
6471
      }
4150
6472
    }
4151
6473
  }
4152
6474
 
4153
6475
  /* Get range for retrieving rows in QUICK_SELECT::get_next */
4154
 
  if (! (range= new optimizer::QuickRange(param->min_key,
4155
 
                                                             (uint32_t) (tmp_min_key - param->min_key),
4156
 
                                           min_part >=0 ? make_keypart_map(min_part) : 0,
4157
 
                                                             param->max_key,
4158
 
                                                             (uint32_t) (tmp_max_key - param->max_key),
4159
 
                                           max_part >=0 ? make_keypart_map(max_part) : 0,
4160
 
                                                             flag)))
4161
 
  {
 
6476
  if (!(range= new QUICK_RANGE(param->min_key,
 
6477
                               (uint) (tmp_min_key - param->min_key),
 
6478
                               min_part >=0 ? make_keypart_map(min_part) : 0,
 
6479
                               param->max_key,
 
6480
                               (uint) (tmp_max_key - param->max_key),
 
6481
                               max_part >=0 ? make_keypart_map(max_part) : 0,
 
6482
                               flag)))
4162
6483
    return 1;                   // out of memory
4163
 
  }
4164
6484
 
4165
 
  set_if_bigger(quick->max_used_key_length, (uint32_t)range->min_length);
4166
 
  set_if_bigger(quick->max_used_key_length, (uint32_t)range->max_length);
4167
 
  set_if_bigger(quick->used_key_parts, (uint32_t) key_tree->part+1);
 
6485
  set_if_bigger(quick->max_used_key_length, range->min_length);
 
6486
  set_if_bigger(quick->max_used_key_length, range->max_length);
 
6487
  set_if_bigger(quick->used_key_parts, (uint) key_tree->part+1);
4168
6488
  if (insert_dynamic(&quick->ranges, (unsigned char*) &range))
4169
 
  {
4170
6489
    return 1;
4171
 
  }
4172
6490
 
4173
6491
 end:
4174
 
  if (key_tree->right != &optimizer::null_element)
 
6492
  if (key_tree->right != &null_element)
 
6493
    return get_quick_keys(param,quick,key,key_tree->right,
 
6494
                          min_key,min_key_flag,
 
6495
                          max_key,max_key_flag);
 
6496
  return 0;
 
6497
}
 
6498
 
 
6499
/*
 
6500
  Return 1 if there is only one range and this uses the whole primary key
 
6501
*/
 
6502
 
 
6503
bool QUICK_RANGE_SELECT::unique_key_range()
 
6504
{
 
6505
  if (ranges.elements == 1)
4175
6506
  {
4176
 
    return get_quick_keys(param,
4177
 
                          quick,
4178
 
                          key,
4179
 
                          key_tree->right,
4180
 
                                            min_key,
4181
 
                          min_key_flag,
4182
 
                                            max_key,
4183
 
                          max_key_flag);
 
6507
    QUICK_RANGE *tmp= *((QUICK_RANGE**)ranges.buffer);
 
6508
    if ((tmp->flag & (EQ_RANGE | NULL_RANGE)) == EQ_RANGE)
 
6509
    {
 
6510
      KEY *key=head->key_info+index;
 
6511
      return ((key->flags & (HA_NOSAME)) == HA_NOSAME &&
 
6512
              key->key_length == tmp->min_length);
 
6513
    }
4184
6514
  }
4185
6515
  return 0;
4186
6516
}
4187
6517
 
 
6518
 
 
6519
 
4188
6520
/*
4189
6521
  Return true if any part of the key is NULL
4190
6522
 
4191
6523
  SYNOPSIS
4192
 
    null_part_in_key()
 
6524
    null_part_in_key()    
4193
6525
      key_part  Array of key parts (index description)
4194
6526
      key       Key values tuple
4195
6527
      length    Length of key values tuple in bytes.
4212
6544
}
4213
6545
 
4214
6546
 
4215
 
bool optimizer::QuickSelectInterface::is_keys_used(const boost::dynamic_bitset<>& fields)
 
6547
bool QUICK_SELECT_I::is_keys_used(const MY_BITMAP *fields)
4216
6548
{
4217
6549
  return is_key_used(head, index, fields);
4218
6550
}
4219
6551
 
 
6552
bool QUICK_INDEX_MERGE_SELECT::is_keys_used(const MY_BITMAP *fields)
 
6553
{
 
6554
  QUICK_RANGE_SELECT *quick;
 
6555
  List_iterator_fast<QUICK_RANGE_SELECT> it(quick_selects);
 
6556
  while ((quick= it++))
 
6557
  {
 
6558
    if (is_key_used(head, quick->index, fields))
 
6559
      return 1;
 
6560
  }
 
6561
  return 0;
 
6562
}
 
6563
 
 
6564
bool QUICK_ROR_INTERSECT_SELECT::is_keys_used(const MY_BITMAP *fields)
 
6565
{
 
6566
  QUICK_RANGE_SELECT *quick;
 
6567
  List_iterator_fast<QUICK_RANGE_SELECT> it(quick_selects);
 
6568
  while ((quick= it++))
 
6569
  {
 
6570
    if (is_key_used(head, quick->index, fields))
 
6571
      return 1;
 
6572
  }
 
6573
  return 0;
 
6574
}
 
6575
 
 
6576
bool QUICK_ROR_UNION_SELECT::is_keys_used(const MY_BITMAP *fields)
 
6577
{
 
6578
  QUICK_SELECT_I *quick;
 
6579
  List_iterator_fast<QUICK_SELECT_I> it(quick_selects);
 
6580
  while ((quick= it++))
 
6581
  {
 
6582
    if (quick->is_keys_used(fields))
 
6583
      return 1;
 
6584
  }
 
6585
  return 0;
 
6586
}
 
6587
 
4220
6588
 
4221
6589
/*
4222
6590
  Create quick select from ref/ref_or_null scan.
4237
6605
    NULL on error.
4238
6606
*/
4239
6607
 
4240
 
optimizer::QuickRangeSelect *optimizer::get_quick_select_for_ref(Session *session,
4241
 
                                                                 Table *table,
4242
 
                                                                 table_reference_st *ref,
4243
 
                                                                 ha_rows records)
 
6608
QUICK_RANGE_SELECT *get_quick_select_for_ref(Session *session, Table *table,
 
6609
                                             TABLE_REF *ref, ha_rows records)
4244
6610
{
4245
 
  memory::Root *old_root= NULL;
4246
 
  memory::Root *alloc= NULL;
4247
 
  KeyInfo *key_info = &table->key_info[ref->key];
 
6611
  MEM_ROOT *old_root, *alloc;
 
6612
  QUICK_RANGE_SELECT *quick;
 
6613
  KEY *key_info = &table->key_info[ref->key];
4248
6614
  KEY_PART *key_part;
4249
 
  optimizer::QuickRange *range= NULL;
 
6615
  QUICK_RANGE *range;
4250
6616
  uint32_t part;
4251
 
  optimizer::CostVector cost;
 
6617
  bool create_err= false;
 
6618
  COST_VECT cost;
4252
6619
 
4253
6620
  old_root= session->mem_root;
4254
6621
  /* The following call may change session->mem_root */
4255
 
  optimizer::QuickRangeSelect *quick= new optimizer::QuickRangeSelect(session, table, ref->key, 0, 0);
4256
 
  /* save mem_root set by QuickRangeSelect constructor */
 
6622
  quick= new QUICK_RANGE_SELECT(session, table, ref->key, 0, 0, &create_err);
 
6623
  /* save mem_root set by QUICK_RANGE_SELECT constructor */
4257
6624
  alloc= session->mem_root;
4258
6625
  /*
4259
6626
    return back default mem_root (session->mem_root) changed by
4260
 
    QuickRangeSelect constructor
 
6627
    QUICK_RANGE_SELECT constructor
4261
6628
  */
4262
6629
  session->mem_root= old_root;
4263
6630
 
4264
 
  if (! quick)
 
6631
  if (!quick || create_err)
4265
6632
    return 0;                   /* no ranges found */
4266
6633
  if (quick->init())
4267
6634
    goto err;
4268
6635
  quick->records= records;
4269
6636
 
4270
6637
  if ((cp_buffer_from_ref(session, ref) && session->is_fatal_error) ||
4271
 
      !(range= new(alloc) optimizer::QuickRange()))
 
6638
      !(range= new(alloc) QUICK_RANGE()))
4272
6639
    goto err;                                   // out of memory
4273
6640
 
4274
6641
  range->min_key= range->max_key= ref->key_buff;
4276
6643
  range->min_keypart_map= range->max_keypart_map=
4277
6644
    make_prev_keypart_map(ref->key_parts);
4278
6645
  range->flag= ((ref->key_length == key_info->key_length &&
4279
 
                 (key_info->flags & HA_END_SPACE_KEY) == 0) ? EQ_RANGE : 0);
4280
 
 
 
6646
                 key_info->flags == 0) ? EQ_RANGE : 0);
4281
6647
 
4282
6648
  if (!(quick->key_parts=key_part=(KEY_PART *)
4283
 
        quick->alloc.alloc_root(sizeof(KEY_PART)*ref->key_parts)))
 
6649
        alloc_root(&quick->alloc,sizeof(KEY_PART)*ref->key_parts)))
4284
6650
    goto err;
4285
6651
 
4286
6652
  for (part=0 ; part < ref->key_parts ;part++,key_part++)
4303
6669
  */
4304
6670
  if (ref->null_ref_key)
4305
6671
  {
4306
 
    optimizer::QuickRange *null_range= NULL;
 
6672
    QUICK_RANGE *null_range;
4307
6673
 
4308
6674
    *ref->null_ref_key= 1;              // Set null byte then create a range
4309
6675
    if (!(null_range= new (alloc)
4310
 
          optimizer::QuickRange(ref->key_buff, ref->key_length,
4311
 
                                 make_prev_keypart_map(ref->key_parts),
4312
 
                                 ref->key_buff, ref->key_length,
4313
 
                                 make_prev_keypart_map(ref->key_parts), EQ_RANGE)))
 
6676
          QUICK_RANGE(ref->key_buff, ref->key_length,
 
6677
                      make_prev_keypart_map(ref->key_parts),
 
6678
                      ref->key_buff, ref->key_length,
 
6679
                      make_prev_keypart_map(ref->key_parts), EQ_RANGE)))
4314
6680
      goto err;
4315
6681
    *ref->null_ref_key= 0;              // Clear null byte
4316
6682
    if (insert_dynamic(&quick->ranges,(unsigned char*)&null_range))
4318
6684
  }
4319
6685
 
4320
6686
  /* Call multi_range_read_info() to get the MRR flags and buffer size */
4321
 
  quick->mrr_flags= HA_MRR_NO_ASSOCIATION |
 
6687
  quick->mrr_flags= HA_MRR_NO_ASSOCIATION | 
4322
6688
                    (table->key_read ? HA_MRR_INDEX_ONLY : 0);
4323
6689
  if (session->lex->sql_command != SQLCOM_SELECT)
4324
6690
    quick->mrr_flags |= HA_MRR_USE_DEFAULT_IMPL;
4325
6691
 
4326
6692
  quick->mrr_buf_size= session->variables.read_rnd_buff_size;
4327
 
  if (table->cursor->multi_range_read_info(quick->index, 1, (uint32_t)records,
4328
 
                                           &quick->mrr_buf_size,
4329
 
                                           &quick->mrr_flags, &cost))
 
6693
  if (table->file->multi_range_read_info(quick->index, 1, (uint)records,
 
6694
                                         &quick->mrr_buf_size,
 
6695
                                         &quick->mrr_flags, &cost))
4330
6696
    goto err;
4331
6697
 
4332
6698
  return quick;
4337
6703
 
4338
6704
 
4339
6705
/*
4340
 
  Range sequence interface implementation for array<QuickRange>: initialize
4341
 
 
 
6706
  Perform key scans for all used indexes (except CPK), get rowids and merge 
 
6707
  them into an ordered non-recurrent sequence of rowids.
 
6708
  
 
6709
  The merge/duplicate removal is performed using Unique class. We put all
 
6710
  rowids into Unique, get the sorted sequence and destroy the Unique.
 
6711
  
 
6712
  If table has a clustered primary key that covers all rows (true for bdb
 
6713
  and innodb currently) and one of the index_merge scans is a scan on PK,
 
6714
  then rows that will be retrieved by PK scan are not put into Unique and 
 
6715
  primary key scan is not performed here, it is performed later separately.
 
6716
 
 
6717
  RETURN
 
6718
    0     OK
 
6719
    other error
 
6720
*/
 
6721
 
 
6722
int QUICK_INDEX_MERGE_SELECT::read_keys_and_merge()
 
6723
{
 
6724
  List_iterator_fast<QUICK_RANGE_SELECT> cur_quick_it(quick_selects);
 
6725
  QUICK_RANGE_SELECT* cur_quick;
 
6726
  int result;
 
6727
  Unique *unique;
 
6728
  handler *file= head->file;
 
6729
 
 
6730
  file->extra(HA_EXTRA_KEYREAD);
 
6731
  head->prepare_for_position();
 
6732
 
 
6733
  cur_quick_it.rewind();
 
6734
  cur_quick= cur_quick_it++;
 
6735
  assert(cur_quick != 0);
 
6736
  
 
6737
  /*
 
6738
    We reuse the same instance of handler so we need to call both init and 
 
6739
    reset here.
 
6740
  */
 
6741
  if (cur_quick->init() || cur_quick->reset())
 
6742
    return(1);
 
6743
 
 
6744
  unique= new Unique(refpos_order_cmp, (void *)file,
 
6745
                     file->ref_length,
 
6746
                     session->variables.sortbuff_size);
 
6747
  if (!unique)
 
6748
    return(1);
 
6749
  for (;;)
 
6750
  {
 
6751
    while ((result= cur_quick->get_next()) == HA_ERR_END_OF_FILE)
 
6752
    {
 
6753
      cur_quick->range_end();
 
6754
      cur_quick= cur_quick_it++;
 
6755
      if (!cur_quick)
 
6756
        break;
 
6757
 
 
6758
      if (cur_quick->file->inited != handler::NONE) 
 
6759
        cur_quick->file->ha_index_end();
 
6760
      if (cur_quick->init() || cur_quick->reset())
 
6761
        return(1);
 
6762
    }
 
6763
 
 
6764
    if (result)
 
6765
    {
 
6766
      if (result != HA_ERR_END_OF_FILE)
 
6767
      {
 
6768
        cur_quick->range_end();
 
6769
        return(result);
 
6770
      }
 
6771
      break;
 
6772
    }
 
6773
 
 
6774
    if (session->killed)
 
6775
      return(1);
 
6776
 
 
6777
    /* skip row if it will be retrieved by clustered PK scan */
 
6778
    if (pk_quick_select && pk_quick_select->row_in_ranges())
 
6779
      continue;
 
6780
 
 
6781
    cur_quick->file->position(cur_quick->record);
 
6782
    result= unique->unique_add((char*)cur_quick->file->ref);
 
6783
    if (result)
 
6784
      return(1);
 
6785
 
 
6786
  }
 
6787
 
 
6788
  /* ok, all row ids are in Unique */
 
6789
  result= unique->get(head);
 
6790
  delete unique;
 
6791
  doing_pk_scan= false;
 
6792
  /* index_merge currently doesn't support "using index" at all */
 
6793
  file->extra(HA_EXTRA_NO_KEYREAD);
 
6794
  /* start table scan */
 
6795
  init_read_record(&read_record, session, head, (SQL_SELECT*) 0, 1, 1);
 
6796
  return(result);
 
6797
}
 
6798
 
 
6799
 
 
6800
/*
 
6801
  Get next row for index_merge.
 
6802
  NOTES
 
6803
    The rows are read from
 
6804
      1. rowids stored in Unique.
 
6805
      2. QUICK_RANGE_SELECT with clustered primary key (if any).
 
6806
    The sets of rows retrieved in 1) and 2) are guaranteed to be disjoint.
 
6807
*/
 
6808
 
 
6809
int QUICK_INDEX_MERGE_SELECT::get_next()
 
6810
{
 
6811
  int result;
 
6812
 
 
6813
  if (doing_pk_scan)
 
6814
    return(pk_quick_select->get_next());
 
6815
 
 
6816
  if ((result= read_record.read_record(&read_record)) == -1)
 
6817
  {
 
6818
    result= HA_ERR_END_OF_FILE;
 
6819
    end_read_record(&read_record);
 
6820
    /* All rows from Unique have been retrieved, do a clustered PK scan */
 
6821
    if (pk_quick_select)
 
6822
    {
 
6823
      doing_pk_scan= true;
 
6824
      if ((result= pk_quick_select->init()) ||
 
6825
          (result= pk_quick_select->reset()))
 
6826
        return(result);
 
6827
      return(pk_quick_select->get_next());
 
6828
    }
 
6829
  }
 
6830
 
 
6831
  return(result);
 
6832
}
 
6833
 
 
6834
 
 
6835
/*
 
6836
  Retrieve next record.
 
6837
  SYNOPSIS
 
6838
     QUICK_ROR_INTERSECT_SELECT::get_next()
 
6839
 
 
6840
  NOTES
 
6841
    Invariant on enter/exit: all intersected selects have retrieved all index
 
6842
    records with rowid <= some_rowid_val and no intersected select has
 
6843
    retrieved any index records with rowid > some_rowid_val.
 
6844
    We start fresh and loop until we have retrieved the same rowid in each of
 
6845
    the key scans or we got an error.
 
6846
 
 
6847
    If a Clustered PK scan is present, it is used only to check if row
 
6848
    satisfies its condition (and never used for row retrieval).
 
6849
 
 
6850
  RETURN
 
6851
   0     - Ok
 
6852
   other - Error code if any error occurred.
 
6853
*/
 
6854
 
 
6855
int QUICK_ROR_INTERSECT_SELECT::get_next()
 
6856
{
 
6857
  List_iterator_fast<QUICK_RANGE_SELECT> quick_it(quick_selects);
 
6858
  QUICK_RANGE_SELECT* quick;
 
6859
  int error, cmp;
 
6860
  uint32_t last_rowid_count=0;
 
6861
 
 
6862
  do
 
6863
  {
 
6864
    /* Get a rowid for first quick and save it as a 'candidate' */
 
6865
    quick= quick_it++;
 
6866
    error= quick->get_next();
 
6867
    if (cpk_quick)
 
6868
    {
 
6869
      while (!error && !cpk_quick->row_in_ranges())
 
6870
        error= quick->get_next();
 
6871
    }
 
6872
    if (error)
 
6873
      return(error);
 
6874
 
 
6875
    quick->file->position(quick->record);
 
6876
    memcpy(last_rowid, quick->file->ref, head->file->ref_length);
 
6877
    last_rowid_count= 1;
 
6878
 
 
6879
    while (last_rowid_count < quick_selects.elements)
 
6880
    {
 
6881
      if (!(quick= quick_it++))
 
6882
      {
 
6883
        quick_it.rewind();
 
6884
        quick= quick_it++;
 
6885
      }
 
6886
 
 
6887
      do
 
6888
      {
 
6889
        if ((error= quick->get_next()))
 
6890
          return(error);
 
6891
        quick->file->position(quick->record);
 
6892
        cmp= head->file->cmp_ref(quick->file->ref, last_rowid);
 
6893
      } while (cmp < 0);
 
6894
 
 
6895
      /* Ok, current select 'caught up' and returned ref >= cur_ref */
 
6896
      if (cmp > 0)
 
6897
      {
 
6898
        /* Found a row with ref > cur_ref. Make it a new 'candidate' */
 
6899
        if (cpk_quick)
 
6900
        {
 
6901
          while (!cpk_quick->row_in_ranges())
 
6902
          {
 
6903
            if ((error= quick->get_next()))
 
6904
              return(error);
 
6905
          }
 
6906
        }
 
6907
        memcpy(last_rowid, quick->file->ref, head->file->ref_length);
 
6908
        last_rowid_count= 1;
 
6909
      }
 
6910
      else
 
6911
      {
 
6912
        /* current 'candidate' row confirmed by this select */
 
6913
        last_rowid_count++;
 
6914
      }
 
6915
    }
 
6916
 
 
6917
    /* We get here if we got the same row ref in all scans. */
 
6918
    if (need_to_fetch_row)
 
6919
      error= head->file->rnd_pos(head->record[0], last_rowid);
 
6920
  } while (error == HA_ERR_RECORD_DELETED);
 
6921
  return(error);
 
6922
}
 
6923
 
 
6924
 
 
6925
/*
 
6926
  Retrieve next record.
 
6927
  SYNOPSIS
 
6928
    QUICK_ROR_UNION_SELECT::get_next()
 
6929
 
 
6930
  NOTES
 
6931
    Enter/exit invariant:
 
6932
    For each quick select in the queue a {key,rowid} tuple has been
 
6933
    retrieved but the corresponding row hasn't been passed to output.
 
6934
 
 
6935
  RETURN
 
6936
   0     - Ok
 
6937
   other - Error code if any error occurred.
 
6938
*/
 
6939
 
 
6940
int QUICK_ROR_UNION_SELECT::get_next()
 
6941
{
 
6942
  int error, dup_row;
 
6943
  QUICK_SELECT_I *quick;
 
6944
  unsigned char *tmp;
 
6945
 
 
6946
  do
 
6947
  {
 
6948
    do
 
6949
    {
 
6950
      if (!queue.elements)
 
6951
        return(HA_ERR_END_OF_FILE);
 
6952
      /* Ok, we have a queue with >= 1 scans */
 
6953
 
 
6954
      quick= (QUICK_SELECT_I*)queue_top(&queue);
 
6955
      memcpy(cur_rowid, quick->last_rowid, rowid_length);
 
6956
 
 
6957
      /* put into queue rowid from the same stream as top element */
 
6958
      if ((error= quick->get_next()))
 
6959
      {
 
6960
        if (error != HA_ERR_END_OF_FILE)
 
6961
          return(error);
 
6962
        queue_remove(&queue, 0);
 
6963
      }
 
6964
      else
 
6965
      {
 
6966
        quick->save_last_pos();
 
6967
        queue_replaced(&queue);
 
6968
      }
 
6969
 
 
6970
      if (!have_prev_rowid)
 
6971
      {
 
6972
        /* No rows have been returned yet */
 
6973
        dup_row= false;
 
6974
        have_prev_rowid= true;
 
6975
      }
 
6976
      else
 
6977
        dup_row= !head->file->cmp_ref(cur_rowid, prev_rowid);
 
6978
    } while (dup_row);
 
6979
 
 
6980
    tmp= cur_rowid;
 
6981
    cur_rowid= prev_rowid;
 
6982
    prev_rowid= tmp;
 
6983
 
 
6984
    error= head->file->rnd_pos(quick->record, prev_rowid);
 
6985
  } while (error == HA_ERR_RECORD_DELETED);
 
6986
  return(error);
 
6987
}
 
6988
 
 
6989
 
 
6990
int QUICK_RANGE_SELECT::reset()
 
6991
{
 
6992
  uint32_t  buf_size;
 
6993
  unsigned char *mrange_buff;
 
6994
  int   error;
 
6995
  HANDLER_BUFFER empty_buf;
 
6996
  last_range= NULL;
 
6997
  cur_range= (QUICK_RANGE**) ranges.buffer;
 
6998
 
 
6999
  if (file->inited == handler::NONE && (error= file->ha_index_init(index,1)))
 
7000
    return(error);
 
7001
 
 
7002
  /* Allocate buffer if we need one but haven't allocated it yet */
 
7003
  if (mrr_buf_size && !mrr_buf_desc)
 
7004
  {
 
7005
    buf_size= mrr_buf_size;
 
7006
    while (buf_size && !my_multi_malloc(MYF(MY_WME),
 
7007
                                        &mrr_buf_desc, sizeof(*mrr_buf_desc),
 
7008
                                        &mrange_buff, buf_size,
 
7009
                                        NULL))
 
7010
    {
 
7011
      /* Try to shrink the buffers until both are 0. */
 
7012
      buf_size/= 2;
 
7013
    }
 
7014
    if (!mrr_buf_desc)
 
7015
      return(HA_ERR_OUT_OF_MEM);
 
7016
 
 
7017
    /* Initialize the handler buffer. */
 
7018
    mrr_buf_desc->buffer= mrange_buff;
 
7019
    mrr_buf_desc->buffer_end= mrange_buff + buf_size;
 
7020
    mrr_buf_desc->end_of_used_area= mrange_buff;
 
7021
  }
 
7022
 
 
7023
  if (!mrr_buf_desc)
 
7024
    empty_buf.buffer= empty_buf.buffer_end= empty_buf.end_of_used_area= NULL;
 
7025
 
 
7026
  if (sorted)
 
7027
     mrr_flags |= HA_MRR_SORTED;
 
7028
  RANGE_SEQ_IF seq_funcs= {quick_range_seq_init, quick_range_seq_next};
 
7029
  error= file->multi_range_read_init(&seq_funcs, (void*)this, ranges.elements,
 
7030
                                     mrr_flags, mrr_buf_desc? mrr_buf_desc: 
 
7031
                                                              &empty_buf);
 
7032
  return(error);
 
7033
}
 
7034
 
 
7035
 
 
7036
/*
 
7037
  Range sequence interface implementation for array<QUICK_RANGE>: initialize
 
7038
  
4342
7039
  SYNOPSIS
4343
7040
    quick_range_seq_init()
4344
 
      init_param  Caller-opaque paramenter: QuickRangeSelect* pointer
 
7041
      init_param  Caller-opaque paramenter: QUICK_RANGE_SELECT* pointer
4345
7042
      n_ranges    Number of ranges in the sequence (ignored)
4346
 
      flags       MRR flags (currently not used)
 
7043
      flags       MRR flags (currently not used) 
4347
7044
 
4348
7045
  RETURN
4349
7046
    Opaque value to be passed to quick_range_seq_next
4350
7047
*/
4351
7048
 
4352
 
range_seq_t optimizer::quick_range_seq_init(void *init_param, uint32_t, uint32_t)
 
7049
range_seq_t quick_range_seq_init(void *init_param,
 
7050
                                 uint32_t n_ranges __attribute__((unused)),
 
7051
                                 uint32_t flags __attribute__((unused)))
4353
7052
{
4354
 
  optimizer::QuickRangeSelect *quick= (optimizer::QuickRangeSelect*)init_param;
4355
 
  quick->qr_traversal_ctx.first=  (optimizer::QuickRange**)quick->ranges.buffer;
4356
 
  quick->qr_traversal_ctx.cur=    (optimizer::QuickRange**)quick->ranges.buffer;
 
7053
  QUICK_RANGE_SELECT *quick= (QUICK_RANGE_SELECT*)init_param;
 
7054
  quick->qr_traversal_ctx.first=  (QUICK_RANGE**)quick->ranges.buffer;
 
7055
  quick->qr_traversal_ctx.cur=    (QUICK_RANGE**)quick->ranges.buffer;
4357
7056
  quick->qr_traversal_ctx.last=   quick->qr_traversal_ctx.cur +
4358
7057
                                  quick->ranges.elements;
4359
7058
  return &quick->qr_traversal_ctx;
4361
7060
 
4362
7061
 
4363
7062
/*
4364
 
  Range sequence interface implementation for array<QuickRange>: get next
4365
 
 
 
7063
  Range sequence interface implementation for array<QUICK_RANGE>: get next
 
7064
  
4366
7065
  SYNOPSIS
4367
7066
    quick_range_seq_next()
4368
7067
      rseq        Value returned from quick_range_seq_init
4372
7071
    0  Ok
4373
7072
    1  No more ranges in the sequence
4374
7073
*/
4375
 
uint32_t optimizer::quick_range_seq_next(range_seq_t rseq, KEY_MULTI_RANGE *range)
 
7074
 
 
7075
uint32_t quick_range_seq_next(range_seq_t rseq, KEY_MULTI_RANGE *range)
4376
7076
{
4377
 
  QuickRangeSequenceContext *ctx= (QuickRangeSequenceContext*) rseq;
 
7077
  QUICK_RANGE_SEQ_CTX *ctx= (QUICK_RANGE_SEQ_CTX*)rseq;
4378
7078
 
4379
7079
  if (ctx->cur == ctx->last)
4380
7080
    return 1; /* no more ranges */
4381
7081
 
4382
 
  optimizer::QuickRange *cur= *(ctx->cur);
 
7082
  QUICK_RANGE *cur= *(ctx->cur);
4383
7083
  key_range *start_key= &range->start_key;
4384
 
  key_range *end_key= &range->end_key;
 
7084
  key_range *end_key=   &range->end_key;
4385
7085
 
4386
 
  start_key->key= cur->min_key;
 
7086
  start_key->key=    cur->min_key;
4387
7087
  start_key->length= cur->min_length;
4388
7088
  start_key->keypart_map= cur->min_keypart_map;
4389
 
  start_key->flag= ((cur->flag & NEAR_MIN) ? HA_READ_AFTER_KEY :
4390
 
                                             (cur->flag & EQ_RANGE) ?
4391
 
                                             HA_READ_KEY_EXACT : HA_READ_KEY_OR_NEXT);
4392
 
  end_key->key= cur->max_key;
4393
 
  end_key->length= cur->max_length;
 
7089
  start_key->flag=   ((cur->flag & NEAR_MIN) ? HA_READ_AFTER_KEY :
 
7090
                      (cur->flag & EQ_RANGE) ?
 
7091
                      HA_READ_KEY_EXACT : HA_READ_KEY_OR_NEXT);
 
7092
  end_key->key=      cur->max_key;
 
7093
  end_key->length=   cur->max_length;
4394
7094
  end_key->keypart_map= cur->max_keypart_map;
4395
7095
  /*
4396
7096
    We use HA_READ_AFTER_KEY here because if we are reading on a key
4397
7097
    prefix. We want to find all keys with this prefix.
4398
7098
  */
4399
 
  end_key->flag= (cur->flag & NEAR_MAX ? HA_READ_BEFORE_KEY :
4400
 
                                         HA_READ_AFTER_KEY);
 
7099
  end_key->flag=     (cur->flag & NEAR_MAX ? HA_READ_BEFORE_KEY :
 
7100
                      HA_READ_AFTER_KEY);
4401
7101
  range->range_flag= cur->flag;
4402
7102
  ctx->cur++;
4403
7103
  return 0;
4404
7104
}
4405
7105
 
4406
7106
 
4407
 
static inline uint32_t get_field_keypart(KeyInfo *index, Field *field);
4408
 
 
4409
 
static inline optimizer::SEL_ARG * get_index_range_tree(uint32_t index,
4410
 
                                                        optimizer::SEL_TREE *range_tree,
4411
 
                                                        optimizer::Parameter *param,
4412
 
                                                        uint32_t *param_idx);
4413
 
 
4414
 
static bool get_constant_key_infix(KeyInfo *index_info,
4415
 
                                   optimizer::SEL_ARG *index_range_tree,
4416
 
                                   KeyPartInfo *first_non_group_part,
4417
 
                                   KeyPartInfo *min_max_arg_part,
4418
 
                                   KeyPartInfo *last_part,
4419
 
                                   Session *session,
4420
 
                                   unsigned char *key_infix,
4421
 
                                   uint32_t *key_infix_len,
4422
 
                                   KeyPartInfo **first_non_infix_part);
4423
 
 
4424
 
static bool check_group_min_max_predicates(COND *cond, Item_field *min_max_arg_item);
 
7107
/*
 
7108
  MRR range sequence interface: array<QUICK_RANGE> impl: utility func for NDB
 
7109
 
 
7110
  SYNOPSIS
 
7111
    mrr_persistent_flag_storage()
 
7112
      seq  Range sequence being traversed
 
7113
      idx  Number of range
 
7114
 
 
7115
  DESCRIPTION
 
7116
    MRR/NDB implementation needs to store some bits for each range. This
 
7117
    function returns a reference to the "range_flag" associated with the
 
7118
    range number idx.
 
7119
 
 
7120
    This function should be removed when we get a proper MRR/NDB 
 
7121
    implementation.
 
7122
 
 
7123
  RETURN
 
7124
    Reference to range_flag associated with range number #idx
 
7125
*/
 
7126
 
 
7127
uint16_t &mrr_persistent_flag_storage(range_seq_t seq, uint32_t idx)
 
7128
{
 
7129
  QUICK_RANGE_SEQ_CTX *ctx= (QUICK_RANGE_SEQ_CTX*)seq;
 
7130
  return ctx->first[idx]->flag;
 
7131
}
 
7132
 
 
7133
 
 
7134
/*
 
7135
  MRR range sequence interface: array<QUICK_RANGE> impl: utility func for NDB
 
7136
 
 
7137
  SYNOPSIS
 
7138
    mrr_get_ptr_by_idx()
 
7139
      seq  Range sequence bening traversed
 
7140
      idx  Number of the range
 
7141
 
 
7142
  DESCRIPTION
 
7143
    An extension of MRR range sequence interface needed by NDB: return the
 
7144
    data associated with the given range.
 
7145
 
 
7146
    A proper MRR interface implementer is supposed to store and return
 
7147
    range-associated data. NDB stores number of the range instead. So this
 
7148
    is a helper function that translates range number to range associated
 
7149
    data.
 
7150
 
 
7151
    This function does nothing, as currrently there is only one user of the
 
7152
    MRR interface - the quick range select code, and this user doesn't need
 
7153
    to use range-associated data.
 
7154
 
 
7155
  RETURN
 
7156
    Reference to range-associated data
 
7157
*/
 
7158
 
 
7159
char* &mrr_get_ptr_by_idx(range_seq_t seq __attribute__((unused)),
 
7160
                          uint32_t idx __attribute__((unused)))
 
7161
{
 
7162
  static char *dummy;
 
7163
  return dummy;
 
7164
}
 
7165
 
 
7166
 
 
7167
/*
 
7168
  Get next possible record using quick-struct.
 
7169
 
 
7170
  SYNOPSIS
 
7171
    QUICK_RANGE_SELECT::get_next()
 
7172
 
 
7173
  NOTES
 
7174
    Record is read into table->record[0]
 
7175
 
 
7176
  RETURN
 
7177
    0                   Found row
 
7178
    HA_ERR_END_OF_FILE  No (more) rows in range
 
7179
    #                   Error code
 
7180
*/
 
7181
 
 
7182
int QUICK_RANGE_SELECT::get_next()
 
7183
{
 
7184
  char *dummy;
 
7185
  if (in_ror_merged_scan)
 
7186
  {
 
7187
    /*
 
7188
      We don't need to signal the bitmap change as the bitmap is always the
 
7189
      same for this head->file
 
7190
    */
 
7191
    head->column_bitmaps_set_no_signal(&column_bitmap, &column_bitmap);
 
7192
  }
 
7193
 
 
7194
  int result= file->multi_range_read_next(&dummy);
 
7195
 
 
7196
  if (in_ror_merged_scan)
 
7197
  {
 
7198
    /* Restore bitmaps set on entry */
 
7199
    head->column_bitmaps_set_no_signal(save_read_set, save_write_set);
 
7200
  }
 
7201
  return(result);
 
7202
}
 
7203
 
 
7204
 
 
7205
/*
 
7206
  Get the next record with a different prefix.
 
7207
 
 
7208
  SYNOPSIS
 
7209
    QUICK_RANGE_SELECT::get_next_prefix()
 
7210
    prefix_length  length of cur_prefix
 
7211
    cur_prefix     prefix of a key to be searched for
 
7212
 
 
7213
  DESCRIPTION
 
7214
    Each subsequent call to the method retrieves the first record that has a
 
7215
    prefix with length prefix_length different from cur_prefix, such that the
 
7216
    record with the new prefix is within the ranges described by
 
7217
    this->ranges. The record found is stored into the buffer pointed by
 
7218
    this->record.
 
7219
    The method is useful for GROUP-BY queries with range conditions to
 
7220
    discover the prefix of the next group that satisfies the range conditions.
 
7221
 
 
7222
  TODO
 
7223
    This method is a modified copy of QUICK_RANGE_SELECT::get_next(), so both
 
7224
    methods should be unified into a more general one to reduce code
 
7225
    duplication.
 
7226
 
 
7227
  RETURN
 
7228
    0                  on success
 
7229
    HA_ERR_END_OF_FILE if returned all keys
 
7230
    other              if some error occurred
 
7231
*/
 
7232
 
 
7233
int QUICK_RANGE_SELECT::get_next_prefix(uint32_t prefix_length,
 
7234
                                        key_part_map keypart_map,
 
7235
                                        unsigned char *cur_prefix)
 
7236
{
 
7237
  for (;;)
 
7238
  {
 
7239
    int result;
 
7240
    key_range start_key, end_key;
 
7241
    if (last_range)
 
7242
    {
 
7243
      /* Read the next record in the same range with prefix after cur_prefix. */
 
7244
      assert(cur_prefix != 0);
 
7245
      result= file->index_read_map(record, cur_prefix, keypart_map,
 
7246
                                   HA_READ_AFTER_KEY);
 
7247
      if (result || (file->compare_key(file->end_range) <= 0))
 
7248
        return(result);
 
7249
    }
 
7250
 
 
7251
    uint32_t count= ranges.elements - (cur_range - (QUICK_RANGE**) ranges.buffer);
 
7252
    if (count == 0)
 
7253
    {
 
7254
      /* Ranges have already been used up before. None is left for read. */
 
7255
      last_range= 0;
 
7256
      return(HA_ERR_END_OF_FILE);
 
7257
    }
 
7258
    last_range= *(cur_range++);
 
7259
 
 
7260
    start_key.key=    (const unsigned char*) last_range->min_key;
 
7261
    start_key.length= cmin(last_range->min_length, (uint16_t)prefix_length);
 
7262
    start_key.keypart_map= last_range->min_keypart_map & keypart_map;
 
7263
    start_key.flag=   ((last_range->flag & NEAR_MIN) ? HA_READ_AFTER_KEY :
 
7264
                       (last_range->flag & EQ_RANGE) ?
 
7265
                       HA_READ_KEY_EXACT : HA_READ_KEY_OR_NEXT);
 
7266
    end_key.key=      (const unsigned char*) last_range->max_key;
 
7267
    end_key.length=   cmin(last_range->max_length, (uint16_t)prefix_length);
 
7268
    end_key.keypart_map= last_range->max_keypart_map & keypart_map;
 
7269
    /*
 
7270
      We use READ_AFTER_KEY here because if we are reading on a key
 
7271
      prefix we want to find all keys with this prefix
 
7272
    */
 
7273
    end_key.flag=     (last_range->flag & NEAR_MAX ? HA_READ_BEFORE_KEY :
 
7274
                       HA_READ_AFTER_KEY);
 
7275
 
 
7276
    result= file->read_range_first(last_range->min_keypart_map ? &start_key : 0,
 
7277
                                   last_range->max_keypart_map ? &end_key : 0,
 
7278
                                   test(last_range->flag & EQ_RANGE),
 
7279
                                   sorted);
 
7280
    if (last_range->flag == (UNIQUE_RANGE | EQ_RANGE))
 
7281
      last_range= 0;                    // Stop searching
 
7282
 
 
7283
    if (result != HA_ERR_END_OF_FILE)
 
7284
      return(result);
 
7285
    last_range= 0;                      // No matching rows; go to next range
 
7286
  }
 
7287
}
 
7288
 
 
7289
 
 
7290
/*
 
7291
  Check if current row will be retrieved by this QUICK_RANGE_SELECT
 
7292
 
 
7293
  NOTES
 
7294
    It is assumed that currently a scan is being done on another index
 
7295
    which reads all necessary parts of the index that is scanned by this
 
7296
    quick select.
 
7297
    The implementation does a binary search on sorted array of disjoint
 
7298
    ranges, without taking size of range into account.
 
7299
 
 
7300
    This function is used to filter out clustered PK scan rows in
 
7301
    index_merge quick select.
 
7302
 
 
7303
  RETURN
 
7304
    true  if current row will be retrieved by this quick select
 
7305
    false if not
 
7306
*/
 
7307
 
 
7308
bool QUICK_RANGE_SELECT::row_in_ranges()
 
7309
{
 
7310
  QUICK_RANGE *res;
 
7311
  uint32_t min= 0;
 
7312
  uint32_t max= ranges.elements - 1;
 
7313
  uint32_t mid= (max + min)/2;
 
7314
 
 
7315
  while (min != max)
 
7316
  {
 
7317
    if (cmp_next(*(QUICK_RANGE**)dynamic_array_ptr(&ranges, mid)))
 
7318
    {
 
7319
      /* current row value > mid->max */
 
7320
      min= mid + 1;
 
7321
    }
 
7322
    else
 
7323
      max= mid;
 
7324
    mid= (min + max) / 2;
 
7325
  }
 
7326
  res= *(QUICK_RANGE**)dynamic_array_ptr(&ranges, mid);
 
7327
  return (!cmp_next(res) && !cmp_prev(res));
 
7328
}
 
7329
 
 
7330
/*
 
7331
  This is a hack: we inherit from QUICK_SELECT so that we can use the
 
7332
  get_next() interface, but we have to hold a pointer to the original
 
7333
  QUICK_SELECT because its data are used all over the place.  What
 
7334
  should be done is to factor out the data that is needed into a base
 
7335
  class (QUICK_SELECT), and then have two subclasses (_ASC and _DESC)
 
7336
  which handle the ranges and implement the get_next() function.  But
 
7337
  for now, this seems to work right at least.
 
7338
 */
 
7339
 
 
7340
QUICK_SELECT_DESC::QUICK_SELECT_DESC(QUICK_RANGE_SELECT *q,
 
7341
                                     uint32_t used_key_parts_arg __attribute__((unused)),
 
7342
                                     bool *create_err __attribute__((unused)))
 
7343
 :QUICK_RANGE_SELECT(*q), rev_it(rev_ranges)
 
7344
{
 
7345
  QUICK_RANGE *r;
 
7346
 
 
7347
  QUICK_RANGE **pr= (QUICK_RANGE**)ranges.buffer;
 
7348
  QUICK_RANGE **end_range= pr + ranges.elements;
 
7349
  for (; pr!=end_range; pr++)
 
7350
    rev_ranges.push_front(*pr);
 
7351
 
 
7352
  /* Remove EQ_RANGE flag for keys that are not using the full key */
 
7353
  for (r = rev_it++; r; r = rev_it++)
 
7354
  {
 
7355
    if ((r->flag & EQ_RANGE) &&
 
7356
        head->key_info[index].key_length != r->max_length)
 
7357
      r->flag&= ~EQ_RANGE;
 
7358
  }
 
7359
  rev_it.rewind();
 
7360
  q->dont_free=1;                               // Don't free shared mem
 
7361
  delete q;
 
7362
}
 
7363
 
 
7364
 
 
7365
int QUICK_SELECT_DESC::get_next()
 
7366
{
 
7367
  /* The max key is handled as follows:
 
7368
   *   - if there is NO_MAX_RANGE, start at the end and move backwards
 
7369
   *   - if it is an EQ_RANGE, which means that max key covers the entire
 
7370
   *     key, go directly to the key and read through it (sorting backwards is
 
7371
   *     same as sorting forwards)
 
7372
   *   - if it is NEAR_MAX, go to the key or next, step back once, and
 
7373
   *     move backwards
 
7374
   *   - otherwise (not NEAR_MAX == include the key), go after the key,
 
7375
   *     step back once, and move backwards
 
7376
   */
 
7377
 
 
7378
  for (;;)
 
7379
  {
 
7380
    int result;
 
7381
    if (last_range)
 
7382
    {                                           // Already read through key
 
7383
      result = ((last_range->flag & EQ_RANGE)
 
7384
                ? file->index_next_same(record, last_range->min_key,
 
7385
                                        last_range->min_length) :
 
7386
                file->index_prev(record));
 
7387
      if (!result)
 
7388
      {
 
7389
        if (cmp_prev(*rev_it.ref()) == 0)
 
7390
          return(0);
 
7391
      }
 
7392
      else if (result != HA_ERR_END_OF_FILE)
 
7393
        return(result);
 
7394
    }
 
7395
 
 
7396
    if (!(last_range= rev_it++))
 
7397
      return(HA_ERR_END_OF_FILE);               // All ranges used
 
7398
 
 
7399
    if (last_range->flag & NO_MAX_RANGE)        // Read last record
 
7400
    {
 
7401
      int local_error;
 
7402
      if ((local_error=file->index_last(record)))
 
7403
        return(local_error);            // Empty table
 
7404
      if (cmp_prev(last_range) == 0)
 
7405
        return(0);
 
7406
      last_range= 0;                            // No match; go to next range
 
7407
      continue;
 
7408
    }
 
7409
 
 
7410
    if (last_range->flag & EQ_RANGE)
 
7411
    {
 
7412
      result = file->index_read_map(record, last_range->max_key,
 
7413
                                    last_range->max_keypart_map,
 
7414
                                    HA_READ_KEY_EXACT);
 
7415
    }
 
7416
    else
 
7417
    {
 
7418
      assert(last_range->flag & NEAR_MAX ||
 
7419
                  range_reads_after_key(last_range));
 
7420
      result=file->index_read_map(record, last_range->max_key,
 
7421
                                  last_range->max_keypart_map,
 
7422
                                  ((last_range->flag & NEAR_MAX) ?
 
7423
                                   HA_READ_BEFORE_KEY :
 
7424
                                   HA_READ_PREFIX_LAST_OR_PREV));
 
7425
    }
 
7426
    if (result)
 
7427
    {
 
7428
      if (result != HA_ERR_KEY_NOT_FOUND && result != HA_ERR_END_OF_FILE)
 
7429
        return(result);
 
7430
      last_range= 0;                            // Not found, to next range
 
7431
      continue;
 
7432
    }
 
7433
    if (cmp_prev(last_range) == 0)
 
7434
    {
 
7435
      if (last_range->flag == (UNIQUE_RANGE | EQ_RANGE))
 
7436
        last_range= 0;                          // Stop searching
 
7437
      return(0);                                // Found key is in range
 
7438
    }
 
7439
    last_range= 0;                              // To next range
 
7440
  }
 
7441
}
 
7442
 
 
7443
 
 
7444
/*
 
7445
  Compare if found key is over max-value
 
7446
  Returns 0 if key <= range->max_key
 
7447
  TODO: Figure out why can't this function be as simple as cmp_prev(). 
 
7448
*/
 
7449
 
 
7450
int QUICK_RANGE_SELECT::cmp_next(QUICK_RANGE *range_arg)
 
7451
{
 
7452
  if (range_arg->flag & NO_MAX_RANGE)
 
7453
    return 0;                                   /* key can't be to large */
 
7454
 
 
7455
  KEY_PART *key_part=key_parts;
 
7456
  uint32_t store_length;
 
7457
 
 
7458
  for (unsigned char *key=range_arg->max_key, *end=key+range_arg->max_length;
 
7459
       key < end;
 
7460
       key+= store_length, key_part++)
 
7461
  {
 
7462
    int cmp;
 
7463
    store_length= key_part->store_length;
 
7464
    if (key_part->null_bit)
 
7465
    {
 
7466
      if (*key)
 
7467
      {
 
7468
        if (!key_part->field->is_null())
 
7469
          return 1;
 
7470
        continue;
 
7471
      }
 
7472
      else if (key_part->field->is_null())
 
7473
        return 0;
 
7474
      key++;                                    // Skip null byte
 
7475
      store_length--;
 
7476
    }
 
7477
    if ((cmp=key_part->field->key_cmp(key, key_part->length)) < 0)
 
7478
      return 0;
 
7479
    if (cmp > 0)
 
7480
      return 1;
 
7481
  }
 
7482
  return (range_arg->flag & NEAR_MAX) ? 1 : 0;          // Exact match
 
7483
}
 
7484
 
 
7485
 
 
7486
/*
 
7487
  Returns 0 if found key is inside range (found key >= range->min_key).
 
7488
*/
 
7489
 
 
7490
int QUICK_RANGE_SELECT::cmp_prev(QUICK_RANGE *range_arg)
 
7491
{
 
7492
  int cmp;
 
7493
  if (range_arg->flag & NO_MIN_RANGE)
 
7494
    return 0;                                   /* key can't be to small */
 
7495
 
 
7496
  cmp= key_cmp(key_part_info, range_arg->min_key,
 
7497
               range_arg->min_length);
 
7498
  if (cmp > 0 || (cmp == 0 && (range_arg->flag & NEAR_MIN) == false))
 
7499
    return 0;
 
7500
  return 1;                                     // outside of range
 
7501
}
 
7502
 
 
7503
 
 
7504
/*
 
7505
 * true if this range will require using HA_READ_AFTER_KEY
 
7506
   See comment in get_next() about this
 
7507
 */
 
7508
 
 
7509
bool QUICK_SELECT_DESC::range_reads_after_key(QUICK_RANGE *range_arg)
 
7510
{
 
7511
  return ((range_arg->flag & (NO_MAX_RANGE | NEAR_MAX)) ||
 
7512
          !(range_arg->flag & EQ_RANGE) ||
 
7513
          head->key_info[index].key_length != range_arg->max_length) ? 1 : 0;
 
7514
}
 
7515
 
 
7516
 
 
7517
void QUICK_RANGE_SELECT::add_info_string(String *str)
 
7518
{
 
7519
  KEY *key_info= head->key_info + index;
 
7520
  str->append(key_info->name);
 
7521
}
 
7522
 
 
7523
void QUICK_INDEX_MERGE_SELECT::add_info_string(String *str)
 
7524
{
 
7525
  QUICK_RANGE_SELECT *quick;
 
7526
  bool first= true;
 
7527
  List_iterator_fast<QUICK_RANGE_SELECT> it(quick_selects);
 
7528
  str->append(STRING_WITH_LEN("sort_union("));
 
7529
  while ((quick= it++))
 
7530
  {
 
7531
    if (!first)
 
7532
      str->append(',');
 
7533
    else
 
7534
      first= false;
 
7535
    quick->add_info_string(str);
 
7536
  }
 
7537
  if (pk_quick_select)
 
7538
  {
 
7539
    str->append(',');
 
7540
    pk_quick_select->add_info_string(str);
 
7541
  }
 
7542
  str->append(')');
 
7543
}
 
7544
 
 
7545
void QUICK_ROR_INTERSECT_SELECT::add_info_string(String *str)
 
7546
{
 
7547
  bool first= true;
 
7548
  QUICK_RANGE_SELECT *quick;
 
7549
  List_iterator_fast<QUICK_RANGE_SELECT> it(quick_selects);
 
7550
  str->append(STRING_WITH_LEN("intersect("));
 
7551
  while ((quick= it++))
 
7552
  {
 
7553
    KEY *key_info= head->key_info + quick->index;
 
7554
    if (!first)
 
7555
      str->append(',');
 
7556
    else
 
7557
      first= false;
 
7558
    str->append(key_info->name);
 
7559
  }
 
7560
  if (cpk_quick)
 
7561
  {
 
7562
    KEY *key_info= head->key_info + cpk_quick->index;
 
7563
    str->append(',');
 
7564
    str->append(key_info->name);
 
7565
  }
 
7566
  str->append(')');
 
7567
}
 
7568
 
 
7569
void QUICK_ROR_UNION_SELECT::add_info_string(String *str)
 
7570
{
 
7571
  bool first= true;
 
7572
  QUICK_SELECT_I *quick;
 
7573
  List_iterator_fast<QUICK_SELECT_I> it(quick_selects);
 
7574
  str->append(STRING_WITH_LEN("union("));
 
7575
  while ((quick= it++))
 
7576
  {
 
7577
    if (!first)
 
7578
      str->append(',');
 
7579
    else
 
7580
      first= false;
 
7581
    quick->add_info_string(str);
 
7582
  }
 
7583
  str->append(')');
 
7584
}
 
7585
 
 
7586
 
 
7587
void QUICK_RANGE_SELECT::add_keys_and_lengths(String *key_names,
 
7588
                                              String *used_lengths)
 
7589
{
 
7590
  char buf[64];
 
7591
  uint32_t length;
 
7592
  KEY *key_info= head->key_info + index;
 
7593
  key_names->append(key_info->name);
 
7594
  length= int64_t2str(max_used_key_length, buf, 10) - buf;
 
7595
  used_lengths->append(buf, length);
 
7596
}
 
7597
 
 
7598
void QUICK_INDEX_MERGE_SELECT::add_keys_and_lengths(String *key_names,
 
7599
                                                    String *used_lengths)
 
7600
{
 
7601
  char buf[64];
 
7602
  uint32_t length;
 
7603
  bool first= true;
 
7604
  QUICK_RANGE_SELECT *quick;
 
7605
 
 
7606
  List_iterator_fast<QUICK_RANGE_SELECT> it(quick_selects);
 
7607
  while ((quick= it++))
 
7608
  {
 
7609
    if (first)
 
7610
      first= false;
 
7611
    else
 
7612
    {
 
7613
      key_names->append(',');
 
7614
      used_lengths->append(',');
 
7615
    }
 
7616
 
 
7617
    KEY *key_info= head->key_info + quick->index;
 
7618
    key_names->append(key_info->name);
 
7619
    length= int64_t2str(quick->max_used_key_length, buf, 10) - buf;
 
7620
    used_lengths->append(buf, length);
 
7621
  }
 
7622
  if (pk_quick_select)
 
7623
  {
 
7624
    KEY *key_info= head->key_info + pk_quick_select->index;
 
7625
    key_names->append(',');
 
7626
    key_names->append(key_info->name);
 
7627
    length= int64_t2str(pk_quick_select->max_used_key_length, buf, 10) - buf;
 
7628
    used_lengths->append(',');
 
7629
    used_lengths->append(buf, length);
 
7630
  }
 
7631
}
 
7632
 
 
7633
void QUICK_ROR_INTERSECT_SELECT::add_keys_and_lengths(String *key_names,
 
7634
                                                      String *used_lengths)
 
7635
{
 
7636
  char buf[64];
 
7637
  uint32_t length;
 
7638
  bool first= true;
 
7639
  QUICK_RANGE_SELECT *quick;
 
7640
  List_iterator_fast<QUICK_RANGE_SELECT> it(quick_selects);
 
7641
  while ((quick= it++))
 
7642
  {
 
7643
    KEY *key_info= head->key_info + quick->index;
 
7644
    if (first)
 
7645
      first= false;
 
7646
    else
 
7647
    {
 
7648
      key_names->append(',');
 
7649
      used_lengths->append(',');
 
7650
    }
 
7651
    key_names->append(key_info->name);
 
7652
    length= int64_t2str(quick->max_used_key_length, buf, 10) - buf;
 
7653
    used_lengths->append(buf, length);
 
7654
  }
 
7655
 
 
7656
  if (cpk_quick)
 
7657
  {
 
7658
    KEY *key_info= head->key_info + cpk_quick->index;
 
7659
    key_names->append(',');
 
7660
    key_names->append(key_info->name);
 
7661
    length= int64_t2str(cpk_quick->max_used_key_length, buf, 10) - buf;
 
7662
    used_lengths->append(',');
 
7663
    used_lengths->append(buf, length);
 
7664
  }
 
7665
}
 
7666
 
 
7667
void QUICK_ROR_UNION_SELECT::add_keys_and_lengths(String *key_names,
 
7668
                                                  String *used_lengths)
 
7669
{
 
7670
  bool first= true;
 
7671
  QUICK_SELECT_I *quick;
 
7672
  List_iterator_fast<QUICK_SELECT_I> it(quick_selects);
 
7673
  while ((quick= it++))
 
7674
  {
 
7675
    if (first)
 
7676
      first= false;
 
7677
    else
 
7678
    {
 
7679
      used_lengths->append(',');
 
7680
      key_names->append(',');
 
7681
    }
 
7682
    quick->add_keys_and_lengths(key_names, used_lengths);
 
7683
  }
 
7684
}
 
7685
 
 
7686
 
 
7687
/*******************************************************************************
 
7688
* Implementation of QUICK_GROUP_MIN_MAX_SELECT
 
7689
*******************************************************************************/
 
7690
 
 
7691
static inline uint32_t get_field_keypart(KEY *index, Field *field);
 
7692
static inline SEL_ARG * get_index_range_tree(uint32_t index, SEL_TREE* range_tree,
 
7693
                                             PARAM *param, uint32_t *param_idx);
 
7694
static bool get_constant_key_infix(KEY *index_info, SEL_ARG *index_range_tree,
 
7695
                       KEY_PART_INFO *first_non_group_part,
 
7696
                       KEY_PART_INFO *min_max_arg_part,
 
7697
                       KEY_PART_INFO *last_part, Session *session,
 
7698
                       unsigned char *key_infix, uint32_t *key_infix_len,
 
7699
                       KEY_PART_INFO **first_non_infix_part);
 
7700
static bool
 
7701
check_group_min_max_predicates(COND *cond, Item_field *min_max_arg_item,
 
7702
                               Field::imagetype image_type);
4425
7703
 
4426
7704
static void
4427
 
cost_group_min_max(Table* table,
4428
 
                   KeyInfo *index_info,
4429
 
                   uint32_t used_key_parts,
4430
 
                   uint32_t group_key_parts,
4431
 
                   optimizer::SEL_TREE *range_tree,
4432
 
                   optimizer::SEL_ARG *index_tree,
4433
 
                   ha_rows quick_prefix_records,
4434
 
                   bool have_min,
4435
 
                   bool have_max,
4436
 
                   double *read_cost,
4437
 
                   ha_rows *records);
 
7705
cost_group_min_max(Table* table, KEY *index_info, uint32_t used_key_parts,
 
7706
                   uint32_t group_key_parts, SEL_TREE *range_tree,
 
7707
                   SEL_ARG *index_tree, ha_rows quick_prefix_records,
 
7708
                   bool have_min, bool have_max,
 
7709
                   double *read_cost, ha_rows *records);
4438
7710
 
4439
7711
 
4440
7712
/*
4447
7719
    sel_tree Range tree generated by get_mm_tree
4448
7720
 
4449
7721
  DESCRIPTION
4450
 
    Test whether a query can be computed via a QuickGroupMinMaxSelect.
4451
 
    Queries computable via a QuickGroupMinMaxSelect must satisfy the
 
7722
    Test whether a query can be computed via a QUICK_GROUP_MIN_MAX_SELECT.
 
7723
    Queries computable via a QUICK_GROUP_MIN_MAX_SELECT must satisfy the
4452
7724
    following conditions:
4453
7725
    A) Table T has at least one compound index I of the form:
4454
7726
       I = <A_1, ...,A_k, [B_1,..., B_m], C, [D_1,...,D_n]>
4465
7737
        - NGA = QA - (GA union C) = {NG_1, ..., NG_m} - the ones not in
4466
7738
          GROUP BY and not referenced by MIN/MAX functions.
4467
7739
        with the following properties specified below.
4468
 
    B3. If Q has a GROUP BY WITH ROLLUP clause the access method is not
 
7740
    B3. If Q has a GROUP BY WITH ROLLUP clause the access method is not 
4469
7741
        applicable.
4470
7742
 
4471
7743
    SA1. There is at most one attribute in SA referenced by any number of
4532
7804
  NOTES
4533
7805
    If the current query satisfies the conditions above, and if
4534
7806
    (mem_root! = NULL), then the function constructs and returns a new TRP
4535
 
    object, that is later used to construct a new QuickGroupMinMaxSelect.
 
7807
    object, that is later used to construct a new QUICK_GROUP_MIN_MAX_SELECT.
4536
7808
    If (mem_root == NULL), then the function only tests whether the current
4537
7809
    query satisfies the conditions above, and, if so, sets
4538
7810
    is_applicable = true.
4553
7825
    other field as in: "select min(a) from t1 group by a" ?
4554
7826
  - We assume that the general correctness of the GROUP-BY query was checked
4555
7827
    before this point. Is this correct, or do we have to check it completely?
4556
 
  - Lift the limitation in condition (B3), that is, make this access method
 
7828
  - Lift the limitation in condition (B3), that is, make this access method 
4557
7829
    applicable to ROLLUP queries.
4558
7830
 
4559
7831
  RETURN
4560
7832
    If mem_root != NULL
4561
 
    - valid GroupMinMaxReadPlan object if this QUICK class can be used for
 
7833
    - valid TRP_GROUP_MIN_MAX object if this QUICK class can be used for
4562
7834
      the query
4563
7835
    -  NULL o/w.
4564
7836
    If mem_root == NULL
4565
7837
    - NULL
4566
7838
*/
4567
 
static optimizer::GroupMinMaxReadPlan *
4568
 
get_best_group_min_max(optimizer::Parameter *param, optimizer::SEL_TREE *tree)
 
7839
 
 
7840
static TRP_GROUP_MIN_MAX *
 
7841
get_best_group_min_max(PARAM *param, SEL_TREE *tree)
4569
7842
{
4570
7843
  Session *session= param->session;
4571
 
  Join *join= session->lex->current_select->join;
 
7844
  JOIN *join= session->lex->current_select->join;
4572
7845
  Table *table= param->table;
4573
7846
  bool have_min= false;              /* true if there is a MIN function. */
4574
7847
  bool have_max= false;              /* true if there is a MAX function. */
4575
7848
  Item_field *min_max_arg_item= NULL; // The argument of all MIN/MAX functions
4576
 
  KeyPartInfo *min_max_arg_part= NULL; /* The corresponding keypart. */
 
7849
  KEY_PART_INFO *min_max_arg_part= NULL; /* The corresponding keypart. */
4577
7850
  uint32_t group_prefix_len= 0; /* Length (in bytes) of the key prefix. */
4578
 
  KeyInfo *index_info= NULL;    /* The index chosen for data access. */
 
7851
  KEY *index_info= NULL;    /* The index chosen for data access. */
4579
7852
  uint32_t index= 0;            /* The id of the chosen index. */
4580
7853
  uint32_t group_key_parts= 0;  // Number of index key parts in the group prefix.
4581
7854
  uint32_t used_key_parts= 0;   /* Number of index key parts used for access. */
4582
7855
  unsigned char key_infix[MAX_KEY_LENGTH]; /* Constants from equality predicates.*/
4583
7856
  uint32_t key_infix_len= 0;          /* Length of key_infix. */
4584
 
  optimizer::GroupMinMaxReadPlan *read_plan= NULL; /* The eventually constructed TRP. */
 
7857
  TRP_GROUP_MIN_MAX *read_plan= NULL; /* The eventually constructed TRP. */
4585
7858
  uint32_t key_part_nr;
4586
 
  Order *tmp_group= NULL;
4587
 
  Item *item= NULL;
4588
 
  Item_field *item_field= NULL;
 
7859
  order_st *tmp_group;
 
7860
  Item *item;
 
7861
  Item_field *item_field;
4589
7862
 
4590
7863
  /* Perform few 'cheap' tests whether this access method is applicable. */
4591
 
  if (! join)
4592
 
    return NULL;        /* This is not a select statement. */
4593
 
 
 
7864
  if (!join)
 
7865
    return(NULL);        /* This is not a select statement. */
4594
7866
  if ((join->tables != 1) ||  /* The query must reference one table. */
4595
 
      ((! join->group_list) && /* Neither GROUP BY nor a DISTINCT query. */
4596
 
       (! join->select_distinct)) ||
 
7867
      ((!join->group_list) && /* Neither GROUP BY nor a DISTINCT query. */
 
7868
       (!join->select_distinct)) ||
4597
7869
      (join->select_lex->olap == ROLLUP_TYPE)) /* Check (B3) for ROLLUP */
4598
 
    return NULL;
4599
 
  if (table->getShare()->sizeKeys() == 0)        /* There are no indexes to use. */
4600
 
    return NULL;
 
7870
    return(NULL);
 
7871
  if (table->s->keys == 0)        /* There are no indexes to use. */
 
7872
    return(NULL);
4601
7873
 
4602
7874
  /* Analyze the query in more detail. */
4603
7875
  List_iterator<Item> select_items_it(join->fields_list);
4604
7876
 
4605
7877
  /* Check (SA1,SA4) and store the only MIN/MAX argument - the C attribute.*/
4606
7878
  if (join->make_sum_func_list(join->all_fields, join->fields_list, 1))
4607
 
    return NULL;
4608
 
 
 
7879
    return(NULL);
4609
7880
  if (join->sum_funcs[0])
4610
7881
  {
4611
 
    Item_sum *min_max_item= NULL;
 
7882
    Item_sum *min_max_item;
4612
7883
    Item_sum **func_ptr= join->sum_funcs;
4613
7884
    while ((min_max_item= *(func_ptr++)))
4614
7885
    {
4617
7888
      else if (min_max_item->sum_func() == Item_sum::MAX_FUNC)
4618
7889
        have_max= true;
4619
7890
      else
4620
 
        return NULL;
 
7891
        return(NULL);
4621
7892
 
4622
7893
      /* The argument of MIN/MAX. */
4623
 
      Item *expr= min_max_item->args[0]->real_item();
 
7894
      Item *expr= min_max_item->args[0]->real_item();    
4624
7895
      if (expr->type() == Item::FIELD_ITEM) /* Is it an attribute? */
4625
7896
      {
4626
7897
        if (! min_max_arg_item)
4627
7898
          min_max_arg_item= (Item_field*) expr;
4628
7899
        else if (! min_max_arg_item->eq(expr, 1))
4629
 
          return NULL;
 
7900
          return(NULL);
4630
7901
      }
4631
7902
      else
4632
 
        return NULL;
 
7903
        return(NULL);
4633
7904
    }
4634
7905
  }
4635
7906
 
4639
7910
    while ((item= select_items_it++))
4640
7911
    {
4641
7912
      if (item->type() != Item::FIELD_ITEM)
4642
 
        return NULL;
 
7913
        return(NULL);
4643
7914
    }
4644
7915
  }
4645
7916
 
4647
7918
  for (tmp_group= join->group_list; tmp_group; tmp_group= tmp_group->next)
4648
7919
  {
4649
7920
    if ((*tmp_group->item)->type() != Item::FIELD_ITEM)
4650
 
      return NULL;
 
7921
      return(NULL);
4651
7922
  }
4652
7923
 
4653
7924
  /*
4655
7926
    (GA1,GA2) are all true. If there is more than one such index, select the
4656
7927
    first one. Here we set the variables: group_prefix_len and index_info.
4657
7928
  */
4658
 
  KeyInfo *cur_index_info= table->key_info;
4659
 
  KeyInfo *cur_index_info_end= cur_index_info + table->getShare()->sizeKeys();
4660
 
  KeyPartInfo *cur_part= NULL;
4661
 
  KeyPartInfo *end_part= NULL; /* Last part for loops. */
 
7929
  KEY *cur_index_info= table->key_info;
 
7930
  KEY *cur_index_info_end= cur_index_info + table->s->keys;
 
7931
  KEY_PART_INFO *cur_part= NULL;
 
7932
  KEY_PART_INFO *end_part; /* Last part for loops. */
4662
7933
  /* Last index part. */
4663
 
  KeyPartInfo *last_part= NULL;
4664
 
  KeyPartInfo *first_non_group_part= NULL;
4665
 
  KeyPartInfo *first_non_infix_part= NULL;
 
7934
  KEY_PART_INFO *last_part= NULL;
 
7935
  KEY_PART_INFO *first_non_group_part= NULL;
 
7936
  KEY_PART_INFO *first_non_infix_part= NULL;
4666
7937
  uint32_t key_infix_parts= 0;
4667
7938
  uint32_t cur_group_key_parts= 0;
4668
7939
  uint32_t cur_group_prefix_len= 0;
4669
7940
  /* Cost-related variables for the best index so far. */
4670
7941
  double best_read_cost= DBL_MAX;
4671
7942
  ha_rows best_records= 0;
4672
 
  optimizer::SEL_ARG *best_index_tree= NULL;
 
7943
  SEL_ARG *best_index_tree= NULL;
4673
7944
  ha_rows best_quick_prefix_records= 0;
4674
7945
  uint32_t best_param_idx= 0;
4675
7946
  double cur_read_cost= DBL_MAX;
4676
7947
  ha_rows cur_records;
4677
 
  optimizer::SEL_ARG *cur_index_tree= NULL;
 
7948
  SEL_ARG *cur_index_tree= NULL;
4678
7949
  ha_rows cur_quick_prefix_records= 0;
4679
 
  uint32_t cur_param_idx= MAX_KEY;
4680
 
  key_map used_key_parts_map;
4681
 
  uint32_t cur_key_infix_len= 0;
4682
 
  unsigned char cur_key_infix[MAX_KEY_LENGTH];
4683
 
  uint32_t cur_used_key_parts= 0;
4684
 
  uint32_t pk= param->table->getShare()->getPrimaryKey();
 
7950
  uint32_t cur_param_idx=MAX_KEY;
 
7951
  key_map cur_used_key_parts;
 
7952
  uint32_t pk= param->table->s->primary_key;
4685
7953
 
4686
 
  for (uint32_t cur_index= 0;
4687
 
       cur_index_info != cur_index_info_end;
 
7954
  for (uint32_t cur_index= 0 ; cur_index_info != cur_index_info_end ;
4688
7955
       cur_index_info++, cur_index++)
4689
7956
  {
4690
7957
    /* Check (B1) - if current index is covering. */
4691
 
    if (! table->covering_keys.test(cur_index))
 
7958
    if (!table->covering_keys.is_set(cur_index))
4692
7959
      goto next_index;
4693
7960
 
4694
7961
    /*
4701
7968
      we check that all query fields are indeed covered by 'cur_index'.
4702
7969
    */
4703
7970
    if (pk < MAX_KEY && cur_index != pk &&
4704
 
        (table->cursor->getEngine()->check_flag(HTON_BIT_PRIMARY_KEY_IN_READ_INDEX)))
 
7971
        (table->file->ha_table_flags() & HA_PRIMARY_KEY_IN_READ_INDEX))
4705
7972
    {
4706
7973
      /* For each table field */
4707
 
      for (uint32_t i= 0; i < table->getShare()->sizeFields(); i++)
 
7974
      for (uint32_t i= 0; i < table->s->fields; i++)
4708
7975
      {
4709
 
        Field *cur_field= table->getField(i);
 
7976
        Field *cur_field= table->field[i];
4710
7977
        /*
4711
7978
          If the field is used in the current query ensure that it's
4712
7979
          part of 'cur_index'
4713
7980
        */
4714
 
        if ((cur_field->isReadSet()) &&
4715
 
            ! cur_field->part_of_key_not_clustered.test(cur_index))
 
7981
        if (bitmap_is_set(table->read_set, cur_field->field_index) &&
 
7982
            !cur_field->part_of_key_not_clustered.is_set(cur_index))
4716
7983
          goto next_index;                  // Field was not part of key
4717
7984
      }
4718
7985
    }
4725
7992
      cur_part= cur_index_info->key_part;
4726
7993
      end_part= cur_part + cur_index_info->key_parts;
4727
7994
      /* Iterate in parallel over the GROUP list and the index parts. */
4728
 
      for (tmp_group= join->group_list;
4729
 
           tmp_group && (cur_part != end_part);
 
7995
      for (tmp_group= join->group_list; tmp_group && (cur_part != end_part);
4730
7996
           tmp_group= tmp_group->next, cur_part++)
4731
7997
      {
4732
7998
        /*
4757
8023
    else if (join->select_distinct)
4758
8024
    {
4759
8025
      select_items_it.rewind();
4760
 
      used_key_parts_map.reset();
 
8026
      cur_used_key_parts.clear_all();
4761
8027
      uint32_t max_key_part= 0;
4762
8028
      while ((item= select_items_it++))
4763
8029
      {
4768
8034
          Check if this attribute was already present in the select list.
4769
8035
          If it was present, then its corresponding key part was alredy used.
4770
8036
        */
4771
 
        if (used_key_parts_map.test(key_part_nr))
 
8037
        if (cur_used_key_parts.is_set(key_part_nr))
4772
8038
          continue;
4773
8039
        if (key_part_nr < 1 || key_part_nr > join->fields_list.elements)
4774
8040
          goto next_index;
4775
8041
        cur_part= cur_index_info->key_part + key_part_nr - 1;
4776
8042
        cur_group_prefix_len+= cur_part->store_length;
4777
 
        used_key_parts_map.set(key_part_nr);
 
8043
        cur_used_key_parts.set_bit(key_part_nr);
4778
8044
        ++cur_group_key_parts;
4779
 
        max_key_part= max(max_key_part,key_part_nr);
 
8045
        max_key_part= cmax(max_key_part,key_part_nr);
4780
8046
      }
4781
8047
      /*
4782
8048
        Check that used key parts forms a prefix of the index.
4784
8050
        all_parts have all bits set from 0 to (max_key_part-1).
4785
8051
        cur_parts have bits set for only used keyparts.
4786
8052
      */
4787
 
      key_map all_parts;
4788
 
      key_map cur_parts;
4789
 
      for (uint32_t pos= 0; pos < max_key_part; pos++)
4790
 
        all_parts.set(pos);
4791
 
      cur_parts= used_key_parts_map >> 1;
 
8053
      uint64_t all_parts, cur_parts;
 
8054
      all_parts= (1<<max_key_part) - 1;
 
8055
      cur_parts= cur_used_key_parts.to_uint64_t() >> 1;
4792
8056
      if (all_parts != cur_parts)
4793
8057
        goto next_index;
4794
8058
    }
4829
8093
                             NULL :
4830
8094
                           NULL;
4831
8095
    if (first_non_group_part &&
4832
 
        (! min_max_arg_part || (min_max_arg_part - first_non_group_part > 0)))
 
8096
        (!min_max_arg_part || (min_max_arg_part - first_non_group_part > 0)))
4833
8097
    {
4834
8098
      if (tree)
4835
8099
      {
4836
8100
        uint32_t dummy;
4837
 
        optimizer::SEL_ARG *index_range_tree= get_index_range_tree(cur_index,
4838
 
                                                                   tree,
4839
 
                                                                   param,
4840
 
                                                                   &dummy);
4841
 
        if (! get_constant_key_infix(cur_index_info,
4842
 
                                     index_range_tree,
4843
 
                                     first_non_group_part,
4844
 
                                     min_max_arg_part,
4845
 
                                     last_part,
4846
 
                                     session,
4847
 
                                     cur_key_infix,
4848
 
                                     &cur_key_infix_len,
4849
 
                                     &first_non_infix_part))
4850
 
        {
 
8101
        SEL_ARG *index_range_tree= get_index_range_tree(cur_index, tree, param,
 
8102
                                                        &dummy);
 
8103
        if (!get_constant_key_infix(cur_index_info, index_range_tree,
 
8104
                                    first_non_group_part, min_max_arg_part,
 
8105
                                    last_part, session, key_infix, &key_infix_len,
 
8106
                                    &first_non_infix_part))
4851
8107
          goto next_index;
4852
 
        }
4853
8108
      }
4854
8109
      else if (min_max_arg_part &&
4855
8110
               (min_max_arg_part - first_non_group_part > 0))
4874
8129
          Store the first and last keyparts that need to be analyzed
4875
8130
          into one array that can be passed as parameter.
4876
8131
        */
4877
 
        KeyPartInfo *key_part_range[2];
 
8132
        KEY_PART_INFO *key_part_range[2];
4878
8133
        key_part_range[0]= first_non_group_part;
4879
8134
        key_part_range[1]= last_part;
4880
8135
 
4881
8136
        /* Check if cur_part is referenced in the WHERE clause. */
4882
 
        if (join->conds->walk(&Item::find_item_in_field_list_processor,
4883
 
                              0,
 
8137
        if (join->conds->walk(&Item::find_item_in_field_list_processor, 0,
4884
8138
                              (unsigned char*) key_part_range))
4885
8139
          goto next_index;
4886
8140
      }
4896
8150
                (min_max_arg_part && (min_max_arg_part < last_part));
4897
8151
      for (; cur_part != last_part; cur_part++)
4898
8152
      {
4899
 
        if (cur_part->field->isReadSet())
 
8153
        if (bitmap_is_set(table->read_set, cur_part->field->field_index))
4900
8154
          goto next_index;
4901
8155
      }
4902
8156
    }
4903
8157
 
4904
8158
    /* If we got to this point, cur_index_info passes the test. */
4905
 
    key_infix_parts= cur_key_infix_len ?
 
8159
    key_infix_parts= key_infix_len ?
4906
8160
                     (first_non_infix_part - first_non_group_part) : 0;
4907
 
    cur_used_key_parts= cur_group_key_parts + key_infix_parts;
 
8161
    used_key_parts= cur_group_key_parts + key_infix_parts;
4908
8162
 
4909
8163
    /* Compute the cost of using this index. */
4910
8164
    if (tree)
4911
8165
    {
4912
8166
      /* Find the SEL_ARG sub-tree that corresponds to the chosen index. */
4913
 
      cur_index_tree= get_index_range_tree(cur_index,
4914
 
                                           tree,
4915
 
                                           param,
 
8167
      cur_index_tree= get_index_range_tree(cur_index, tree, param,
4916
8168
                                           &cur_param_idx);
4917
8169
      /* Check if this range tree can be used for prefix retrieval. */
4918
 
      optimizer::CostVector dummy_cost;
 
8170
      COST_VECT dummy_cost;
4919
8171
      uint32_t mrr_flags= HA_MRR_USE_DEFAULT_IMPL;
4920
 
      uint32_t mrr_bufsize= 0;
4921
 
      cur_quick_prefix_records= check_quick_select(session,
4922
 
                                                   param,
4923
 
                                                   cur_param_idx,
4924
 
                                                   false /*don't care*/,
4925
 
                                                   cur_index_tree,
4926
 
                                                   true,
4927
 
                                                   &mrr_flags,
4928
 
                                                   &mrr_bufsize,
 
8172
      uint32_t mrr_bufsize=0;
 
8173
      cur_quick_prefix_records= check_quick_select(param, cur_param_idx, 
 
8174
                                                   false /*don't care*/, 
 
8175
                                                   cur_index_tree, true,
 
8176
                                                   &mrr_flags, &mrr_bufsize,
4929
8177
                                                   &dummy_cost);
4930
8178
    }
4931
 
    cost_group_min_max(table,
4932
 
                       cur_index_info,
4933
 
                       cur_used_key_parts,
4934
 
                       cur_group_key_parts,
4935
 
                       tree,
4936
 
                       cur_index_tree,
4937
 
                       cur_quick_prefix_records,
4938
 
                       have_min,
4939
 
                       have_max,
4940
 
                       &cur_read_cost,
4941
 
                       &cur_records);
 
8179
    cost_group_min_max(table, cur_index_info, used_key_parts,
 
8180
                       cur_group_key_parts, tree, cur_index_tree,
 
8181
                       cur_quick_prefix_records, have_min, have_max,
 
8182
                       &cur_read_cost, &cur_records);
4942
8183
    /*
4943
8184
      If cur_read_cost is lower than best_read_cost use cur_index.
4944
8185
      Do not compare doubles directly because they may have different
4956
8197
      best_param_idx= cur_param_idx;
4957
8198
      group_key_parts= cur_group_key_parts;
4958
8199
      group_prefix_len= cur_group_prefix_len;
4959
 
      key_infix_len= cur_key_infix_len;
4960
 
 
4961
 
      if (key_infix_len)
4962
 
      {
4963
 
        memcpy(key_infix, cur_key_infix, sizeof (key_infix));
4964
 
      }
4965
 
 
4966
 
      used_key_parts= cur_used_key_parts;
4967
8200
    }
4968
8201
 
4969
8202
  next_index:
4970
8203
    cur_group_key_parts= 0;
4971
8204
    cur_group_prefix_len= 0;
4972
 
    cur_key_infix_len= 0;
4973
8205
  }
4974
 
  if (! index_info) /* No usable index found. */
4975
 
    return NULL;
 
8206
  if (!index_info) /* No usable index found. */
 
8207
    return(NULL);
4976
8208
 
4977
8209
  /* Check (SA3) for the where clause. */
4978
8210
  if (join->conds && min_max_arg_item &&
4979
 
      ! check_group_min_max_predicates(join->conds, min_max_arg_item))
4980
 
    return NULL;
 
8211
      !check_group_min_max_predicates(join->conds, min_max_arg_item, Field::itRAW))
 
8212
    return(NULL);
4981
8213
 
4982
8214
  /* The query passes all tests, so construct a new TRP object. */
4983
 
  read_plan=
4984
 
    new(param->mem_root) optimizer::GroupMinMaxReadPlan(have_min,
4985
 
                                                        have_max,
4986
 
                                                        min_max_arg_part,
4987
 
                                                        group_prefix_len,
4988
 
                                                        used_key_parts,
4989
 
                                                        group_key_parts,
4990
 
                                                        index_info,
4991
 
                                                        index,
4992
 
                                                        key_infix_len,
4993
 
                                                        (key_infix_len > 0) ? key_infix : NULL,
4994
 
                                                        tree,
4995
 
                                                        best_index_tree,
4996
 
                                                        best_param_idx,
4997
 
                                                        best_quick_prefix_records);
 
8215
  read_plan= new (param->mem_root)
 
8216
                 TRP_GROUP_MIN_MAX(have_min, have_max, min_max_arg_part,
 
8217
                                   group_prefix_len, used_key_parts,
 
8218
                                   group_key_parts, index_info, index,
 
8219
                                   key_infix_len,
 
8220
                                   (key_infix_len > 0) ? key_infix : NULL,
 
8221
                                   tree, best_index_tree, best_param_idx,
 
8222
                                   best_quick_prefix_records);
4998
8223
  if (read_plan)
4999
8224
  {
5000
8225
    if (tree && read_plan->quick_prefix_records == 0)
5001
 
      return NULL;
 
8226
      return(NULL);
5002
8227
 
5003
8228
    read_plan->read_cost= best_read_cost;
5004
 
    read_plan->records= best_records;
 
8229
    read_plan->records=   best_records;
5005
8230
  }
5006
8231
 
5007
 
  return read_plan;
 
8232
  return(read_plan);
5008
8233
}
5009
8234
 
5010
8235
 
5029
8254
    true  if cond passes the test
5030
8255
    false o/w
5031
8256
*/
5032
 
static bool check_group_min_max_predicates(COND *cond, Item_field *min_max_arg_item)
 
8257
 
 
8258
static bool
 
8259
check_group_min_max_predicates(COND *cond, Item_field *min_max_arg_item,
 
8260
                               Field::imagetype image_type)
5033
8261
{
5034
8262
  assert(cond && min_max_arg_item);
5035
8263
 
5038
8266
  if (cond_type == Item::COND_ITEM) /* 'AND' or 'OR' */
5039
8267
  {
5040
8268
    List_iterator_fast<Item> li(*((Item_cond*) cond)->argument_list());
5041
 
    Item *and_or_arg= NULL;
 
8269
    Item *and_or_arg;
5042
8270
    while ((and_or_arg= li++))
5043
8271
    {
5044
 
      if (! check_group_min_max_predicates(and_or_arg, min_max_arg_item))
5045
 
        return false;
 
8272
      if (!check_group_min_max_predicates(and_or_arg, min_max_arg_item,
 
8273
                                         image_type))
 
8274
        return(false);
5046
8275
    }
5047
 
    return true;
 
8276
    return(true);
5048
8277
  }
5049
8278
 
5050
8279
  /*
5057
8286
    so.
5058
8287
  */
5059
8288
  if (cond_type == Item::SUBSELECT_ITEM)
5060
 
    return false;
5061
 
 
 
8289
    return(false);
 
8290
  
5062
8291
  /* We presume that at this point there are no other Items than functions. */
5063
8292
  assert(cond_type == Item::FUNC_ITEM);
5064
8293
 
5065
8294
  /* Test if cond references only group-by or non-group fields. */
5066
8295
  Item_func *pred= (Item_func*) cond;
5067
8296
  Item **arguments= pred->arguments();
5068
 
  Item *cur_arg= NULL;
 
8297
  Item *cur_arg;
5069
8298
  for (uint32_t arg_idx= 0; arg_idx < pred->argument_count (); arg_idx++)
5070
8299
  {
5071
8300
    cur_arg= arguments[arg_idx]->real_item();
5072
8301
    if (cur_arg->type() == Item::FIELD_ITEM)
5073
8302
    {
5074
 
      if (min_max_arg_item->eq(cur_arg, 1))
 
8303
      if (min_max_arg_item->eq(cur_arg, 1)) 
5075
8304
      {
5076
8305
       /*
5077
8306
         If pred references the MIN/MAX argument, check whether pred is a range
5088
8317
            pred_type != Item_func::ISNOTNULL_FUNC &&
5089
8318
            pred_type != Item_func::EQ_FUNC        &&
5090
8319
            pred_type != Item_func::NE_FUNC)
5091
 
          return false;
 
8320
          return(false);
5092
8321
 
5093
8322
        /* Check that pred compares min_max_arg_item with a constant. */
5094
8323
        Item *args[3];
5095
8324
        memset(args, 0, 3 * sizeof(Item*));
5096
 
        bool inv= false;
 
8325
        bool inv;
5097
8326
        /* Test if this is a comparison of a field and a constant. */
5098
 
        if (! optimizer::simple_pred(pred, args, inv))
5099
 
          return false;
 
8327
        if (!simple_pred(pred, args, &inv))
 
8328
          return(false);
5100
8329
 
5101
8330
        /* Check for compatible string comparisons - similar to get_mm_leaf. */
5102
8331
        if (args[0] && args[1] && !args[2] && // this is a binary function
5105
8334
              Don't use an index when comparing strings of different collations.
5106
8335
            */
5107
8336
            ((args[1]->result_type() == STRING_RESULT &&
 
8337
              image_type == Field::itRAW &&
5108
8338
              ((Field_str*) min_max_arg_item->field)->charset() !=
5109
8339
              pred->compare_collation())
5110
8340
             ||
5114
8344
             */
5115
8345
             (args[1]->result_type() != STRING_RESULT &&
5116
8346
              min_max_arg_item->field->cmp_type() != args[1]->result_type())))
5117
 
        {
5118
 
          return false;
5119
 
        }
 
8347
          return(false);
5120
8348
      }
5121
8349
    }
5122
8350
    else if (cur_arg->type() == Item::FUNC_ITEM)
5123
8351
    {
5124
 
      if (! check_group_min_max_predicates(cur_arg, min_max_arg_item))
5125
 
        return false;
 
8352
      if (!check_group_min_max_predicates(cur_arg, min_max_arg_item,
 
8353
                                         image_type))
 
8354
        return(false);
5126
8355
    }
5127
8356
    else if (cur_arg->const_item())
5128
8357
    {
5129
 
      return true;
 
8358
      return(true);
5130
8359
    }
5131
8360
    else
5132
 
      return false;
 
8361
      return(false);
5133
8362
  }
5134
8363
 
5135
 
  return true;
 
8364
  return(true);
5136
8365
}
5137
8366
 
5138
8367
 
5150
8379
    key_infix              [out] Infix of constants to be used for index lookup
5151
8380
    key_infix_len          [out] Lenghth of the infix
5152
8381
    first_non_infix_part   [out] The first keypart after the infix (if any)
5153
 
 
 
8382
    
5154
8383
  DESCRIPTION
5155
8384
    Test conditions (NGA1, NGA2) from get_best_group_min_max(). Namely,
5156
8385
    for each keypart field NGF_i not in GROUP-BY, check that there is a
5166
8395
    true  if the index passes the test
5167
8396
    false o/w
5168
8397
*/
 
8398
 
5169
8399
static bool
5170
 
get_constant_key_infix(KeyInfo *,
5171
 
                       optimizer::SEL_ARG *index_range_tree,
5172
 
                       KeyPartInfo *first_non_group_part,
5173
 
                       KeyPartInfo *min_max_arg_part,
5174
 
                       KeyPartInfo *last_part,
5175
 
                       Session *,
5176
 
                       unsigned char *key_infix,
5177
 
                       uint32_t *key_infix_len,
5178
 
                       KeyPartInfo **first_non_infix_part)
 
8400
get_constant_key_infix(KEY *index_info __attribute__((unused)),
 
8401
                       SEL_ARG *index_range_tree,
 
8402
                       KEY_PART_INFO *first_non_group_part,
 
8403
                       KEY_PART_INFO *min_max_arg_part,
 
8404
                       KEY_PART_INFO *last_part,
 
8405
                       Session *session __attribute__((unused)),
 
8406
                       unsigned char *key_infix, uint32_t *key_infix_len,
 
8407
                       KEY_PART_INFO **first_non_infix_part)
5179
8408
{
5180
 
  optimizer::SEL_ARG *cur_range= NULL;
5181
 
  KeyPartInfo *cur_part= NULL;
 
8409
  SEL_ARG       *cur_range;
 
8410
  KEY_PART_INFO *cur_part;
5182
8411
  /* End part for the first loop below. */
5183
 
  KeyPartInfo *end_part= min_max_arg_part ? min_max_arg_part : last_part;
 
8412
  KEY_PART_INFO *end_part= min_max_arg_part ? min_max_arg_part : last_part;
5184
8413
 
5185
8414
  *key_infix_len= 0;
5186
8415
  unsigned char *key_ptr= key_infix;
5196
8425
      if (cur_range->field->eq(cur_part->field))
5197
8426
        break;
5198
8427
    }
5199
 
    if (! cur_range)
 
8428
    if (!cur_range)
5200
8429
    {
5201
8430
      if (min_max_arg_part)
5202
8431
        return false; /* The current keypart has no range predicates at all. */
5212
8441
      return false; /* This is not the only range predicate for the field. */
5213
8442
    if ((cur_range->min_flag & NO_MIN_RANGE) ||
5214
8443
        (cur_range->max_flag & NO_MAX_RANGE) ||
5215
 
        (cur_range->min_flag & NEAR_MIN) ||
5216
 
        (cur_range->max_flag & NEAR_MAX))
 
8444
        (cur_range->min_flag & NEAR_MIN) || (cur_range->max_flag & NEAR_MAX))
5217
8445
      return false;
5218
8446
 
5219
8447
    uint32_t field_length= cur_part->store_length;
5246
8474
    field  field that possibly references some key part in index
5247
8475
 
5248
8476
  NOTES
5249
 
    The return value can be used to get a KeyPartInfo pointer by
 
8477
    The return value can be used to get a KEY_PART_INFO pointer by
5250
8478
    part= index->key_part + get_field_keypart(...) - 1;
5251
8479
 
5252
8480
  RETURN
5253
8481
    Positive number which is the consecutive number of the key part, or
5254
8482
    0 if field does not reference any index field.
5255
8483
*/
 
8484
 
5256
8485
static inline uint
5257
 
get_field_keypart(KeyInfo *index, Field *field)
 
8486
get_field_keypart(KEY *index, Field *field)
5258
8487
{
5259
 
  KeyPartInfo *part= NULL;
5260
 
  KeyPartInfo *end= NULL;
 
8488
  KEY_PART_INFO *part, *end;
5261
8489
 
5262
8490
  for (part= index->key_part, end= part + index->key_parts; part < end; part++)
5263
8491
  {
5275
8503
    get_index_range_tree()
5276
8504
    index     [in]  The ID of the index being looked for
5277
8505
    range_tree[in]  Tree of ranges being searched
5278
 
    param     [in]  Parameter from SqlSelect::test_quick_select
5279
 
    param_idx [out] Index in the array Parameter::key that corresponds to 'index'
 
8506
    param     [in]  PARAM from SQL_SELECT::test_quick_select
 
8507
    param_idx [out] Index in the array PARAM::key that corresponds to 'index'
5280
8508
 
5281
8509
  DESCRIPTION
5282
8510
 
5283
 
    A optimizer::SEL_TREE contains range trees for all usable indexes. This procedure
5284
 
    finds the SEL_ARG sub-tree for 'index'. The members of a optimizer::SEL_TREE are
5285
 
    ordered in the same way as the members of Parameter::key, thus we first find
5286
 
    the corresponding index in the array Parameter::key. This index is returned
 
8511
    A SEL_TREE contains range trees for all usable indexes. This procedure
 
8512
    finds the SEL_ARG sub-tree for 'index'. The members of a SEL_TREE are
 
8513
    ordered in the same way as the members of PARAM::key, thus we first find
 
8514
    the corresponding index in the array PARAM::key. This index is returned
5287
8515
    through the variable param_idx, to be used later as argument of
5288
8516
    check_quick_select().
5289
8517
 
5290
8518
  RETURN
5291
8519
    Pointer to the SEL_ARG subtree that corresponds to index.
5292
8520
*/
5293
 
optimizer::SEL_ARG *get_index_range_tree(uint32_t index,
5294
 
                                         optimizer::SEL_TREE* range_tree,
5295
 
                                         optimizer::Parameter *param,
5296
 
                                         uint32_t *param_idx)
 
8521
 
 
8522
SEL_ARG * get_index_range_tree(uint32_t index, SEL_TREE* range_tree, PARAM *param,
 
8523
                               uint32_t *param_idx)
5297
8524
{
5298
8525
  uint32_t idx= 0; /* Index nr in param->key_parts */
5299
8526
  while (idx < param->keys)
5303
8530
    idx++;
5304
8531
  }
5305
8532
  *param_idx= idx;
5306
 
  return range_tree->keys[idx];
 
8533
  return(range_tree->keys[idx]);
5307
8534
}
5308
8535
 
5309
8536
 
5326
8553
    records             [out] The number of rows retrieved
5327
8554
 
5328
8555
  DESCRIPTION
5329
 
    This method computes the access cost of a GroupMinMaxReadPlan instance and
 
8556
    This method computes the access cost of a TRP_GROUP_MIN_MAX instance and
5330
8557
    the number of rows returned. It updates this->read_cost and this->records.
5331
8558
 
5332
8559
  NOTES
5366
8593
  RETURN
5367
8594
    None
5368
8595
*/
5369
 
void cost_group_min_max(Table* table,
5370
 
                        KeyInfo *index_info,
5371
 
                        uint32_t used_key_parts,
5372
 
                        uint32_t group_key_parts,
5373
 
                        optimizer::SEL_TREE *range_tree,
5374
 
                        optimizer::SEL_ARG *,
 
8596
 
 
8597
void cost_group_min_max(Table* table, KEY *index_info, uint32_t used_key_parts,
 
8598
                        uint32_t group_key_parts, SEL_TREE *range_tree,
 
8599
                        SEL_ARG *index_tree __attribute__((unused)),
5375
8600
                        ha_rows quick_prefix_records,
5376
 
                        bool have_min,
5377
 
                        bool have_max,
5378
 
                        double *read_cost,
5379
 
                        ha_rows *records)
 
8601
                        bool have_min, bool have_max,
 
8602
                        double *read_cost, ha_rows *records)
5380
8603
{
5381
8604
  ha_rows table_records;
5382
8605
  uint32_t num_groups;
5390
8613
  double io_cost;
5391
8614
  double cpu_cost= 0; /* TODO: CPU cost of index_read calls? */
5392
8615
 
5393
 
  table_records= table->cursor->stats.records;
5394
 
  keys_per_block= (table->cursor->stats.block_size / 2 /
5395
 
                   (index_info->key_length + table->cursor->ref_length)
 
8616
  table_records= table->file->stats.records;
 
8617
  keys_per_block= (table->file->stats.block_size / 2 /
 
8618
                   (index_info->key_length + table->file->ref_length)
5396
8619
                        + 1);
5397
 
  num_blocks= (uint32_t) (table_records / keys_per_block) + 1;
 
8620
  num_blocks= (uint)(table_records / keys_per_block) + 1;
5398
8621
 
5399
8622
  /* Compute the number of keys in a group. */
5400
8623
  keys_per_group= index_info->rec_per_key[group_key_parts - 1];
5401
8624
  if (keys_per_group == 0) /* If there is no statistics try to guess */
5402
8625
    /* each group contains 10% of all records */
5403
 
    keys_per_group= (uint32_t)(table_records / 10) + 1;
5404
 
  num_groups= (uint32_t)(table_records / keys_per_group) + 1;
 
8626
    keys_per_group= (uint)(table_records / 10) + 1;
 
8627
  num_groups= (uint)(table_records / keys_per_group) + 1;
5405
8628
 
5406
8629
  /* Apply the selectivity of the quick select for group prefixes. */
5407
8630
  if (range_tree && (quick_prefix_records != HA_POS_ERROR))
5408
8631
  {
5409
8632
    quick_prefix_selectivity= (double) quick_prefix_records /
5410
8633
                              (double) table_records;
5411
 
    num_groups= (uint32_t) rint(num_groups * quick_prefix_selectivity);
5412
 
    set_if_bigger(num_groups, 1U);
 
8634
    num_groups= (uint) rint(num_groups * quick_prefix_selectivity);
 
8635
    set_if_bigger(num_groups, 1);
5413
8636
  }
5414
8637
 
5415
8638
  if (used_key_parts > group_key_parts)
5424
8647
    {
5425
8648
      double blocks_per_group= (double) num_blocks / (double) num_groups;
5426
8649
      p_overlap= (blocks_per_group * (keys_per_subgroup - 1)) / keys_per_group;
5427
 
      p_overlap= min(p_overlap, 1.0);
 
8650
      p_overlap= cmin(p_overlap, 1.0);
5428
8651
    }
5429
 
    io_cost= (double) min(num_groups * (1 + p_overlap), (double)num_blocks);
 
8652
    io_cost= (double) cmin(num_groups * (1 + p_overlap), (double)num_blocks);
5430
8653
  }
5431
8654
  else
5432
8655
    io_cost= (keys_per_group > keys_per_block) ?
5437
8660
  /*
5438
8661
    TODO: If there is no WHERE clause and no other expressions, there should be
5439
8662
    no CPU cost. We leave it here to make this cost comparable to that of index
5440
 
    scan as computed in SqlSelect::test_quick_select().
 
8663
    scan as computed in SQL_SELECT::test_quick_select().
5441
8664
  */
5442
8665
  cpu_cost= (double) num_groups / TIME_FOR_COMPARE;
5443
8666
 
5444
8667
  *read_cost= io_cost + cpu_cost;
5445
8668
  *records= num_groups;
 
8669
  return;
5446
8670
}
5447
8671
 
5448
8672
 
5450
8674
  Construct a new quick select object for queries with group by with min/max.
5451
8675
 
5452
8676
  SYNOPSIS
5453
 
    GroupMinMaxReadPlan::make_quick()
 
8677
    TRP_GROUP_MIN_MAX::make_quick()
5454
8678
    param              Parameter from test_quick_select
5455
8679
    retrieve_full_rows ignored
5456
8680
    parent_alloc       Memory pool to use, if any.
5457
8681
 
5458
8682
  NOTES
5459
8683
    Make_quick ignores the retrieve_full_rows parameter because
5460
 
    QuickGroupMinMaxSelect always performs 'index only' scans.
 
8684
    QUICK_GROUP_MIN_MAX_SELECT always performs 'index only' scans.
5461
8685
    The other parameter are ignored as well because all necessary
5462
8686
    data to create the QUICK object is computed at this TRP creation
5463
8687
    time.
5464
8688
 
5465
8689
  RETURN
5466
 
    New QuickGroupMinMaxSelect object if successfully created,
 
8690
    New QUICK_GROUP_MIN_MAX_SELECT object if successfully created,
5467
8691
    NULL otherwise.
5468
8692
*/
5469
 
optimizer::QuickSelectInterface *
5470
 
optimizer::GroupMinMaxReadPlan::make_quick(optimizer::Parameter *param, bool, memory::Root *parent_alloc)
 
8693
 
 
8694
QUICK_SELECT_I *
 
8695
TRP_GROUP_MIN_MAX::make_quick(PARAM *param,
 
8696
                              bool retrieve_full_rows __attribute__((unused)),
 
8697
                              MEM_ROOT *parent_alloc)
5471
8698
{
5472
 
  optimizer::QuickGroupMinMaxSelect *quick= NULL;
 
8699
  QUICK_GROUP_MIN_MAX_SELECT *quick;
5473
8700
 
5474
 
  quick= new optimizer::QuickGroupMinMaxSelect(param->table,
5475
 
                                               param->session->lex->current_select->join,
5476
 
                                               have_min,
5477
 
                                               have_max,
5478
 
                                               min_max_arg_part,
5479
 
                                               group_prefix_len,
5480
 
                                               group_key_parts,
5481
 
                                               used_key_parts,
5482
 
                                               index_info,
5483
 
                                               index,
5484
 
                                               read_cost,
5485
 
                                               records,
5486
 
                                               key_infix_len,
5487
 
                                               key_infix,
5488
 
                                               parent_alloc);
5489
 
  if (! quick)
5490
 
  {
5491
 
    return NULL;
5492
 
  }
 
8701
  quick= new QUICK_GROUP_MIN_MAX_SELECT(param->table,
 
8702
                                        param->session->lex->current_select->join,
 
8703
                                        have_min, have_max, min_max_arg_part,
 
8704
                                        group_prefix_len, group_key_parts,
 
8705
                                        used_key_parts, index_info, index,
 
8706
                                        read_cost, records, key_infix_len,
 
8707
                                        key_infix, parent_alloc);
 
8708
  if (!quick)
 
8709
    return(NULL);
5493
8710
 
5494
8711
  if (quick->init())
5495
8712
  {
5496
8713
    delete quick;
5497
 
    return NULL;
 
8714
    return(NULL);
5498
8715
  }
5499
8716
 
5500
8717
  if (range_tree)
5501
8718
  {
5502
8719
    assert(quick_prefix_records > 0);
5503
8720
    if (quick_prefix_records == HA_POS_ERROR)
5504
 
    {
5505
8721
      quick->quick_prefix_select= NULL; /* Can't construct a quick select. */
5506
 
    }
5507
8722
    else
5508
 
    {
5509
 
      /* Make a QuickRangeSelect to be used for group prefix retrieval. */
5510
 
      quick->quick_prefix_select= optimizer::get_quick_select(param,
5511
 
                                                              param_idx,
5512
 
                                                              index_tree,
5513
 
                                                              HA_MRR_USE_DEFAULT_IMPL,
5514
 
                                                              0,
5515
 
                                                              &quick->alloc);
5516
 
    }
 
8723
      /* Make a QUICK_RANGE_SELECT to be used for group prefix retrieval. */
 
8724
      quick->quick_prefix_select= get_quick_select(param, param_idx,
 
8725
                                                   index_tree,
 
8726
                                                   HA_MRR_USE_DEFAULT_IMPL, 0,
 
8727
                                                   &quick->alloc);
5517
8728
 
5518
8729
    /*
5519
8730
      Extract the SEL_ARG subtree that contains only ranges for the MIN/MAX
5520
 
      attribute, and create an array of QuickRanges to be used by the
 
8731
      attribute, and create an array of QUICK_RANGES to be used by the
5521
8732
      new quick select.
5522
8733
    */
5523
8734
    if (min_max_arg_part)
5524
8735
    {
5525
 
      optimizer::SEL_ARG *min_max_range= index_tree;
 
8736
      SEL_ARG *min_max_range= index_tree;
5526
8737
      while (min_max_range) /* Find the tree for the MIN/MAX key part. */
5527
8738
      {
5528
8739
        if (min_max_range->field->eq(min_max_arg_part->field))
5532
8743
      /* Scroll to the leftmost interval for the MIN/MAX argument. */
5533
8744
      while (min_max_range && min_max_range->prev)
5534
8745
        min_max_range= min_max_range->prev;
5535
 
      /* Create an array of QuickRanges for the MIN/MAX argument. */
 
8746
      /* Create an array of QUICK_RANGEs for the MIN/MAX argument. */
5536
8747
      while (min_max_range)
5537
8748
      {
5538
8749
        if (quick->add_range(min_max_range))
5539
8750
        {
5540
8751
          delete quick;
5541
8752
          quick= NULL;
5542
 
          return NULL;
 
8753
          return(NULL);
5543
8754
        }
5544
8755
        min_max_range= min_max_range->next;
5545
8756
      }
5551
8762
  quick->update_key_stat();
5552
8763
  quick->adjust_prefix_ranges();
5553
8764
 
5554
 
  return quick;
5555
 
}
5556
 
 
5557
 
 
5558
 
optimizer::QuickSelectInterface *optimizer::RangeReadPlan::make_quick(optimizer::Parameter *param, bool, memory::Root *parent_alloc)
5559
 
{
5560
 
  optimizer::QuickRangeSelect *quick= NULL;
5561
 
  if ((quick= optimizer::get_quick_select(param,
5562
 
                                          key_idx,
5563
 
                                          key,
5564
 
                                          mrr_flags,
5565
 
                                          mrr_buf_size,
5566
 
                                          parent_alloc)))
5567
 
  {
5568
 
    quick->records= records;
5569
 
    quick->read_time= read_cost;
5570
 
  }
5571
 
  return quick;
5572
 
}
5573
 
 
5574
 
 
5575
 
uint32_t optimizer::RorScanInfo::findFirstNotSet() const
5576
 
{
5577
 
  boost::dynamic_bitset<> map= bitsToBitset();
5578
 
  for (boost::dynamic_bitset<>::size_type i= 0; i < map.size(); i++)
5579
 
  {
5580
 
    if (! map.test(i))
5581
 
    {
5582
 
      return i;
5583
 
    }
5584
 
  }
5585
 
  return map.size();
5586
 
}
5587
 
 
5588
 
 
5589
 
size_t optimizer::RorScanInfo::getBitCount() const
5590
 
{
5591
 
  boost::dynamic_bitset<> tmp_bitset= bitsToBitset();
5592
 
  return tmp_bitset.count();
5593
 
}
5594
 
 
5595
 
 
5596
 
void optimizer::RorScanInfo::subtractBitset(const boost::dynamic_bitset<>& in_bitset)
5597
 
{
5598
 
  boost::dynamic_bitset<> tmp_bitset= bitsToBitset();
5599
 
  tmp_bitset-= in_bitset;
5600
 
  covered_fields= tmp_bitset.to_ulong();
5601
 
}
5602
 
 
5603
 
 
5604
 
boost::dynamic_bitset<> optimizer::RorScanInfo::bitsToBitset() const
5605
 
{
5606
 
  string res;
5607
 
  uint64_t conv= covered_fields;
5608
 
  while (conv)
5609
 
  {
5610
 
    res.push_back((conv & 1) + '0');
5611
 
    conv>>= 1;
5612
 
  }
5613
 
  if (! res.empty())
5614
 
  {
5615
 
    std::reverse(res.begin(), res.end());
5616
 
  }
5617
 
  string final(covered_fields_size - res.length(), '0');
5618
 
  final.append(res);
5619
 
  return (boost::dynamic_bitset<>(final));
5620
 
}
5621
 
 
5622
 
 
5623
 
} /* namespace drizzled */
 
8765
  return(quick);
 
8766
}
 
8767
 
 
8768
 
 
8769
/*
 
8770
  Construct new quick select for group queries with min/max.
 
8771
 
 
8772
  SYNOPSIS
 
8773
    QUICK_GROUP_MIN_MAX_SELECT::QUICK_GROUP_MIN_MAX_SELECT()
 
8774
    table             The table being accessed
 
8775
    join              Descriptor of the current query
 
8776
    have_min          true if the query selects a MIN function
 
8777
    have_max          true if the query selects a MAX function
 
8778
    min_max_arg_part  The only argument field of all MIN/MAX functions
 
8779
    group_prefix_len  Length of all key parts in the group prefix
 
8780
    prefix_key_parts  All key parts in the group prefix
 
8781
    index_info        The index chosen for data access
 
8782
    use_index         The id of index_info
 
8783
    read_cost         Cost of this access method
 
8784
    records           Number of records returned
 
8785
    key_infix_len     Length of the key infix appended to the group prefix
 
8786
    key_infix         Infix of constants from equality predicates
 
8787
    parent_alloc      Memory pool for this and quick_prefix_select data
 
8788
 
 
8789
  RETURN
 
8790
    None
 
8791
*/
 
8792
 
 
8793
QUICK_GROUP_MIN_MAX_SELECT::
 
8794
QUICK_GROUP_MIN_MAX_SELECT(Table *table, JOIN *join_arg, bool have_min_arg,
 
8795
                           bool have_max_arg,
 
8796
                           KEY_PART_INFO *min_max_arg_part_arg,
 
8797
                           uint32_t group_prefix_len_arg, uint32_t group_key_parts_arg,
 
8798
                           uint32_t used_key_parts_arg, KEY *index_info_arg,
 
8799
                           uint32_t use_index, double read_cost_arg,
 
8800
                           ha_rows records_arg, uint32_t key_infix_len_arg,
 
8801
                           unsigned char *key_infix_arg, MEM_ROOT *parent_alloc)
 
8802
  :join(join_arg), index_info(index_info_arg),
 
8803
   group_prefix_len(group_prefix_len_arg),
 
8804
   group_key_parts(group_key_parts_arg), have_min(have_min_arg),
 
8805
   have_max(have_max_arg), seen_first_key(false),
 
8806
   min_max_arg_part(min_max_arg_part_arg), key_infix(key_infix_arg),
 
8807
   key_infix_len(key_infix_len_arg), min_functions_it(NULL),
 
8808
   max_functions_it(NULL)
 
8809
{
 
8810
  head=       table;
 
8811
  file=       head->file;
 
8812
  index=      use_index;
 
8813
  record=     head->record[0];
 
8814
  tmp_record= head->record[1];
 
8815
  read_time= read_cost_arg;
 
8816
  records= records_arg;
 
8817
  used_key_parts= used_key_parts_arg;
 
8818
  real_key_parts= used_key_parts_arg;
 
8819
  real_prefix_len= group_prefix_len + key_infix_len;
 
8820
  group_prefix= NULL;
 
8821
  min_max_arg_len= min_max_arg_part ? min_max_arg_part->store_length : 0;
 
8822
 
 
8823
  /*
 
8824
    We can't have parent_alloc set as the init function can't handle this case
 
8825
    yet.
 
8826
  */
 
8827
  assert(!parent_alloc);
 
8828
  if (!parent_alloc)
 
8829
  {
 
8830
    init_sql_alloc(&alloc, join->session->variables.range_alloc_block_size, 0);
 
8831
    join->session->mem_root= &alloc;
 
8832
  }
 
8833
  else
 
8834
    memset(&alloc, 0, sizeof(MEM_ROOT));  // ensure that it's not used
 
8835
}
 
8836
 
 
8837
 
 
8838
/*
 
8839
  Do post-constructor initialization.
 
8840
 
 
8841
  SYNOPSIS
 
8842
    QUICK_GROUP_MIN_MAX_SELECT::init()
 
8843
  
 
8844
  DESCRIPTION
 
8845
    The method performs initialization that cannot be done in the constructor
 
8846
    such as memory allocations that may fail. It allocates memory for the
 
8847
    group prefix and inifix buffers, and for the lists of MIN/MAX item to be
 
8848
    updated during execution.
 
8849
 
 
8850
  RETURN
 
8851
    0      OK
 
8852
    other  Error code
 
8853
*/
 
8854
 
 
8855
int QUICK_GROUP_MIN_MAX_SELECT::init()
 
8856
{
 
8857
  if (group_prefix) /* Already initialized. */
 
8858
    return 0;
 
8859
 
 
8860
  if (!(last_prefix= (unsigned char*) alloc_root(&alloc, group_prefix_len)))
 
8861
      return 1;
 
8862
  /*
 
8863
    We may use group_prefix to store keys with all select fields, so allocate
 
8864
    enough space for it.
 
8865
  */
 
8866
  if (!(group_prefix= (unsigned char*) alloc_root(&alloc,
 
8867
                                         real_prefix_len + min_max_arg_len)))
 
8868
    return 1;
 
8869
 
 
8870
  if (key_infix_len > 0)
 
8871
  {
 
8872
    /*
 
8873
      The memory location pointed to by key_infix will be deleted soon, so
 
8874
      allocate a new buffer and copy the key_infix into it.
 
8875
    */
 
8876
    unsigned char *tmp_key_infix= (unsigned char*) alloc_root(&alloc, key_infix_len);
 
8877
    if (!tmp_key_infix)
 
8878
      return 1;
 
8879
    memcpy(tmp_key_infix, this->key_infix, key_infix_len);
 
8880
    this->key_infix= tmp_key_infix;
 
8881
  }
 
8882
 
 
8883
  if (min_max_arg_part)
 
8884
  {
 
8885
    if (my_init_dynamic_array(&min_max_ranges, sizeof(QUICK_RANGE*), 16, 16))
 
8886
      return 1;
 
8887
 
 
8888
    if (have_min)
 
8889
    {
 
8890
      if (!(min_functions= new List<Item_sum>))
 
8891
        return 1;
 
8892
    }
 
8893
    else
 
8894
      min_functions= NULL;
 
8895
    if (have_max)
 
8896
    {
 
8897
      if (!(max_functions= new List<Item_sum>))
 
8898
        return 1;
 
8899
    }
 
8900
    else
 
8901
      max_functions= NULL;
 
8902
 
 
8903
    Item_sum *min_max_item;
 
8904
    Item_sum **func_ptr= join->sum_funcs;
 
8905
    while ((min_max_item= *(func_ptr++)))
 
8906
    {
 
8907
      if (have_min && (min_max_item->sum_func() == Item_sum::MIN_FUNC))
 
8908
        min_functions->push_back(min_max_item);
 
8909
      else if (have_max && (min_max_item->sum_func() == Item_sum::MAX_FUNC))
 
8910
        max_functions->push_back(min_max_item);
 
8911
    }
 
8912
 
 
8913
    if (have_min)
 
8914
    {
 
8915
      if (!(min_functions_it= new List_iterator<Item_sum>(*min_functions)))
 
8916
        return 1;
 
8917
    }
 
8918
 
 
8919
    if (have_max)
 
8920
    {
 
8921
      if (!(max_functions_it= new List_iterator<Item_sum>(*max_functions)))
 
8922
        return 1;
 
8923
    }
 
8924
  }
 
8925
  else
 
8926
    min_max_ranges.elements= 0;
 
8927
 
 
8928
  return 0;
 
8929
}
 
8930
 
 
8931
 
 
8932
QUICK_GROUP_MIN_MAX_SELECT::~QUICK_GROUP_MIN_MAX_SELECT()
 
8933
{
 
8934
  if (file->inited != handler::NONE) 
 
8935
    file->ha_index_end();
 
8936
  if (min_max_arg_part)
 
8937
    delete_dynamic(&min_max_ranges);
 
8938
  free_root(&alloc,MYF(0));
 
8939
  delete min_functions_it;
 
8940
  delete max_functions_it;
 
8941
  delete quick_prefix_select;
 
8942
  return; 
 
8943
}
 
8944
 
 
8945
 
 
8946
/*
 
8947
  Eventually create and add a new quick range object.
 
8948
 
 
8949
  SYNOPSIS
 
8950
    QUICK_GROUP_MIN_MAX_SELECT::add_range()
 
8951
    sel_range  Range object from which a 
 
8952
 
 
8953
  NOTES
 
8954
    Construct a new QUICK_RANGE object from a SEL_ARG object, and
 
8955
    add it to the array min_max_ranges. If sel_arg is an infinite
 
8956
    range, e.g. (x < 5 or x > 4), then skip it and do not construct
 
8957
    a quick range.
 
8958
 
 
8959
  RETURN
 
8960
    false on success
 
8961
    true  otherwise
 
8962
*/
 
8963
 
 
8964
bool QUICK_GROUP_MIN_MAX_SELECT::add_range(SEL_ARG *sel_range)
 
8965
{
 
8966
  QUICK_RANGE *range;
 
8967
  uint32_t range_flag= sel_range->min_flag | sel_range->max_flag;
 
8968
 
 
8969
  /* Skip (-inf,+inf) ranges, e.g. (x < 5 or x > 4). */
 
8970
  if ((range_flag & NO_MIN_RANGE) && (range_flag & NO_MAX_RANGE))
 
8971
    return false;
 
8972
 
 
8973
  if (!(sel_range->min_flag & NO_MIN_RANGE) &&
 
8974
      !(sel_range->max_flag & NO_MAX_RANGE))
 
8975
  {
 
8976
    if (sel_range->maybe_null &&
 
8977
        sel_range->min_value[0] && sel_range->max_value[0])
 
8978
      range_flag|= NULL_RANGE; /* IS NULL condition */
 
8979
    else if (memcmp(sel_range->min_value, sel_range->max_value,
 
8980
                    min_max_arg_len) == 0)
 
8981
      range_flag|= EQ_RANGE;  /* equality condition */
 
8982
  }
 
8983
  range= new QUICK_RANGE(sel_range->min_value, min_max_arg_len,
 
8984
                         make_keypart_map(sel_range->part),
 
8985
                         sel_range->max_value, min_max_arg_len,
 
8986
                         make_keypart_map(sel_range->part),
 
8987
                         range_flag);
 
8988
  if (!range)
 
8989
    return true;
 
8990
  if (insert_dynamic(&min_max_ranges, (unsigned char*)&range))
 
8991
    return true;
 
8992
  return false;
 
8993
}
 
8994
 
 
8995
 
 
8996
/*
 
8997
  Opens the ranges if there are more conditions in quick_prefix_select than
 
8998
  the ones used for jumping through the prefixes.
 
8999
 
 
9000
  SYNOPSIS
 
9001
    QUICK_GROUP_MIN_MAX_SELECT::adjust_prefix_ranges()
 
9002
 
 
9003
  NOTES
 
9004
    quick_prefix_select is made over the conditions on the whole key.
 
9005
    It defines a number of ranges of length x. 
 
9006
    However when jumping through the prefixes we use only the the first 
 
9007
    few most significant keyparts in the range key. However if there
 
9008
    are more keyparts to follow the ones we are using we must make the 
 
9009
    condition on the key inclusive (because x < "ab" means 
 
9010
    x[0] < 'a' OR (x[0] == 'a' AND x[1] < 'b').
 
9011
    To achive the above we must turn off the NEAR_MIN/NEAR_MAX
 
9012
*/
 
9013
void QUICK_GROUP_MIN_MAX_SELECT::adjust_prefix_ranges ()
 
9014
{
 
9015
  if (quick_prefix_select &&
 
9016
      group_prefix_len < quick_prefix_select->max_used_key_length)
 
9017
  {
 
9018
    DYNAMIC_ARRAY *arr;
 
9019
    uint32_t inx;
 
9020
 
 
9021
    for (inx= 0, arr= &quick_prefix_select->ranges; inx < arr->elements; inx++)
 
9022
    {
 
9023
      QUICK_RANGE *range;
 
9024
 
 
9025
      get_dynamic(arr, (unsigned char*)&range, inx);
 
9026
      range->flag &= ~(NEAR_MIN | NEAR_MAX);
 
9027
    }
 
9028
  }
 
9029
}
 
9030
 
 
9031
 
 
9032
/*
 
9033
  Determine the total number and length of the keys that will be used for
 
9034
  index lookup.
 
9035
 
 
9036
  SYNOPSIS
 
9037
    QUICK_GROUP_MIN_MAX_SELECT::update_key_stat()
 
9038
 
 
9039
  DESCRIPTION
 
9040
    The total length of the keys used for index lookup depends on whether
 
9041
    there are any predicates referencing the min/max argument, and/or if
 
9042
    the min/max argument field can be NULL.
 
9043
    This function does an optimistic analysis whether the search key might
 
9044
    be extended by a constant for the min/max keypart. It is 'optimistic'
 
9045
    because during actual execution it may happen that a particular range
 
9046
    is skipped, and then a shorter key will be used. However this is data
 
9047
    dependent and can't be easily estimated here.
 
9048
 
 
9049
  RETURN
 
9050
    None
 
9051
*/
 
9052
 
 
9053
void QUICK_GROUP_MIN_MAX_SELECT::update_key_stat()
 
9054
{
 
9055
  max_used_key_length= real_prefix_len;
 
9056
  if (min_max_ranges.elements > 0)
 
9057
  {
 
9058
    QUICK_RANGE *cur_range;
 
9059
    if (have_min)
 
9060
    { /* Check if the right-most range has a lower boundary. */
 
9061
      get_dynamic(&min_max_ranges, (unsigned char*)&cur_range,
 
9062
                  min_max_ranges.elements - 1);
 
9063
      if (!(cur_range->flag & NO_MIN_RANGE))
 
9064
      {
 
9065
        max_used_key_length+= min_max_arg_len;
 
9066
        used_key_parts++;
 
9067
        return;
 
9068
      }
 
9069
    }
 
9070
    if (have_max)
 
9071
    { /* Check if the left-most range has an upper boundary. */
 
9072
      get_dynamic(&min_max_ranges, (unsigned char*)&cur_range, 0);
 
9073
      if (!(cur_range->flag & NO_MAX_RANGE))
 
9074
      {
 
9075
        max_used_key_length+= min_max_arg_len;
 
9076
        used_key_parts++;
 
9077
        return;
 
9078
      }
 
9079
    }
 
9080
  }
 
9081
  else if (have_min && min_max_arg_part &&
 
9082
           min_max_arg_part->field->real_maybe_null())
 
9083
  {
 
9084
    /*
 
9085
      If a MIN/MAX argument value is NULL, we can quickly determine
 
9086
      that we're in the beginning of the next group, because NULLs
 
9087
      are always < any other value. This allows us to quickly
 
9088
      determine the end of the current group and jump to the next
 
9089
      group (see next_min()) and thus effectively increases the
 
9090
      usable key length.
 
9091
    */
 
9092
    max_used_key_length+= min_max_arg_len;
 
9093
    used_key_parts++;
 
9094
  }
 
9095
}
 
9096
 
 
9097
 
 
9098
/*
 
9099
  Initialize a quick group min/max select for key retrieval.
 
9100
 
 
9101
  SYNOPSIS
 
9102
    QUICK_GROUP_MIN_MAX_SELECT::reset()
 
9103
 
 
9104
  DESCRIPTION
 
9105
    Initialize the index chosen for access and find and store the prefix
 
9106
    of the last group. The method is expensive since it performs disk access.
 
9107
 
 
9108
  RETURN
 
9109
    0      OK
 
9110
    other  Error code
 
9111
*/
 
9112
 
 
9113
int QUICK_GROUP_MIN_MAX_SELECT::reset(void)
 
9114
{
 
9115
  int result;
 
9116
 
 
9117
  file->extra(HA_EXTRA_KEYREAD); /* We need only the key attributes */
 
9118
  if ((result= file->ha_index_init(index,1)))
 
9119
    return(result);
 
9120
  if (quick_prefix_select && quick_prefix_select->reset())
 
9121
    return(1);
 
9122
  result= file->index_last(record);
 
9123
  if (result == HA_ERR_END_OF_FILE)
 
9124
    return(0);
 
9125
  /* Save the prefix of the last group. */
 
9126
  key_copy(last_prefix, record, index_info, group_prefix_len);
 
9127
 
 
9128
  return(0);
 
9129
}
 
9130
 
 
9131
 
 
9132
 
 
9133
/* 
 
9134
  Get the next key containing the MIN and/or MAX key for the next group.
 
9135
 
 
9136
  SYNOPSIS
 
9137
    QUICK_GROUP_MIN_MAX_SELECT::get_next()
 
9138
 
 
9139
  DESCRIPTION
 
9140
    The method finds the next subsequent group of records that satisfies the
 
9141
    query conditions and finds the keys that contain the MIN/MAX values for
 
9142
    the key part referenced by the MIN/MAX function(s). Once a group and its
 
9143
    MIN/MAX values are found, store these values in the Item_sum objects for
 
9144
    the MIN/MAX functions. The rest of the values in the result row are stored
 
9145
    in the Item_field::result_field of each select field. If the query does
 
9146
    not contain MIN and/or MAX functions, then the function only finds the
 
9147
    group prefix, which is a query answer itself.
 
9148
 
 
9149
  NOTES
 
9150
    If both MIN and MAX are computed, then we use the fact that if there is
 
9151
    no MIN key, there can't be a MAX key as well, so we can skip looking
 
9152
    for a MAX key in this case.
 
9153
 
 
9154
  RETURN
 
9155
    0                  on success
 
9156
    HA_ERR_END_OF_FILE if returned all keys
 
9157
    other              if some error occurred
 
9158
*/
 
9159
 
 
9160
int QUICK_GROUP_MIN_MAX_SELECT::get_next()
 
9161
{
 
9162
  int min_res= 0;
 
9163
  int max_res= 0;
 
9164
  int result;
 
9165
  int is_last_prefix= 0;
 
9166
 
 
9167
  /*
 
9168
    Loop until a group is found that satisfies all query conditions or the last
 
9169
    group is reached.
 
9170
  */
 
9171
  do
 
9172
  {
 
9173
    result= next_prefix();
 
9174
    /*
 
9175
      Check if this is the last group prefix. Notice that at this point
 
9176
      this->record contains the current prefix in record format.
 
9177
    */
 
9178
    if (!result)
 
9179
    {
 
9180
      is_last_prefix= key_cmp(index_info->key_part, last_prefix,
 
9181
                              group_prefix_len);
 
9182
      assert(is_last_prefix <= 0);
 
9183
    }
 
9184
    else 
 
9185
    {
 
9186
      if (result == HA_ERR_KEY_NOT_FOUND)
 
9187
        continue;
 
9188
      break;
 
9189
    }
 
9190
 
 
9191
    if (have_min)
 
9192
    {
 
9193
      min_res= next_min();
 
9194
      if (min_res == 0)
 
9195
        update_min_result();
 
9196
    }
 
9197
    /* If there is no MIN in the group, there is no MAX either. */
 
9198
    if ((have_max && !have_min) ||
 
9199
        (have_max && have_min && (min_res == 0)))
 
9200
    {
 
9201
      max_res= next_max();
 
9202
      if (max_res == 0)
 
9203
        update_max_result();
 
9204
      /* If a MIN was found, a MAX must have been found as well. */
 
9205
      assert((have_max && !have_min) ||
 
9206
                  (have_max && have_min && (max_res == 0)));
 
9207
    }
 
9208
    /*
 
9209
      If this is just a GROUP BY or DISTINCT without MIN or MAX and there
 
9210
      are equality predicates for the key parts after the group, find the
 
9211
      first sub-group with the extended prefix.
 
9212
    */
 
9213
    if (!have_min && !have_max && key_infix_len > 0)
 
9214
      result= file->index_read_map(record, group_prefix,
 
9215
                                   make_prev_keypart_map(real_key_parts),
 
9216
                                   HA_READ_KEY_EXACT);
 
9217
 
 
9218
    result= have_min ? min_res : have_max ? max_res : result;
 
9219
  } while ((result == HA_ERR_KEY_NOT_FOUND || result == HA_ERR_END_OF_FILE) &&
 
9220
           is_last_prefix != 0);
 
9221
 
 
9222
  if (result == 0)
 
9223
  {
 
9224
    /*
 
9225
      Partially mimic the behavior of end_select_send. Copy the
 
9226
      field data from Item_field::field into Item_field::result_field
 
9227
      of each non-aggregated field (the group fields, and optionally
 
9228
      other fields in non-ANSI SQL mode).
 
9229
    */
 
9230
    copy_fields(&join->tmp_table_param);
 
9231
  }
 
9232
  else if (result == HA_ERR_KEY_NOT_FOUND)
 
9233
    result= HA_ERR_END_OF_FILE;
 
9234
 
 
9235
  return(result);
 
9236
}
 
9237
 
 
9238
 
 
9239
/*
 
9240
  Retrieve the minimal key in the next group.
 
9241
 
 
9242
  SYNOPSIS
 
9243
    QUICK_GROUP_MIN_MAX_SELECT::next_min()
 
9244
 
 
9245
  DESCRIPTION
 
9246
    Find the minimal key within this group such that the key satisfies the query
 
9247
    conditions and NULL semantics. The found key is loaded into this->record.
 
9248
 
 
9249
  IMPLEMENTATION
 
9250
    Depending on the values of min_max_ranges.elements, key_infix_len, and
 
9251
    whether there is a  NULL in the MIN field, this function may directly
 
9252
    return without any data access. In this case we use the key loaded into
 
9253
    this->record by the call to this->next_prefix() just before this call.
 
9254
 
 
9255
  RETURN
 
9256
    0                    on success
 
9257
    HA_ERR_KEY_NOT_FOUND if no MIN key was found that fulfills all conditions.
 
9258
    HA_ERR_END_OF_FILE   - "" -
 
9259
    other                if some error occurred
 
9260
*/
 
9261
 
 
9262
int QUICK_GROUP_MIN_MAX_SELECT::next_min()
 
9263
{
 
9264
  int result= 0;
 
9265
 
 
9266
  /* Find the MIN key using the eventually extended group prefix. */
 
9267
  if (min_max_ranges.elements > 0)
 
9268
  {
 
9269
    if ((result= next_min_in_range()))
 
9270
      return(result);
 
9271
  }
 
9272
  else
 
9273
  {
 
9274
    /* Apply the constant equality conditions to the non-group select fields */
 
9275
    if (key_infix_len > 0)
 
9276
    {
 
9277
      if ((result= file->index_read_map(record, group_prefix,
 
9278
                                        make_prev_keypart_map(real_key_parts),
 
9279
                                        HA_READ_KEY_EXACT)))
 
9280
        return(result);
 
9281
    }
 
9282
 
 
9283
    /*
 
9284
      If the min/max argument field is NULL, skip subsequent rows in the same
 
9285
      group with NULL in it. Notice that:
 
9286
      - if the first row in a group doesn't have a NULL in the field, no row
 
9287
      in the same group has (because NULL < any other value),
 
9288
      - min_max_arg_part->field->ptr points to some place in 'record'.
 
9289
    */
 
9290
    if (min_max_arg_part && min_max_arg_part->field->is_null())
 
9291
    {
 
9292
      /* Find the first subsequent record without NULL in the MIN/MAX field. */
 
9293
      key_copy(tmp_record, record, index_info, 0);
 
9294
      result= file->index_read_map(record, tmp_record,
 
9295
                                   make_keypart_map(real_key_parts),
 
9296
                                   HA_READ_AFTER_KEY);
 
9297
      /*
 
9298
        Check if the new record belongs to the current group by comparing its
 
9299
        prefix with the group's prefix. If it is from the next group, then the
 
9300
        whole group has NULLs in the MIN/MAX field, so use the first record in
 
9301
        the group as a result.
 
9302
        TODO:
 
9303
        It is possible to reuse this new record as the result candidate for the
 
9304
        next call to next_min(), and to save one lookup in the next call. For
 
9305
        this add a new member 'this->next_group_prefix'.
 
9306
      */
 
9307
      if (!result)
 
9308
      {
 
9309
        if (key_cmp(index_info->key_part, group_prefix, real_prefix_len))
 
9310
          key_restore(record, tmp_record, index_info, 0);
 
9311
      }
 
9312
      else if (result == HA_ERR_KEY_NOT_FOUND || result == HA_ERR_END_OF_FILE)
 
9313
        result= 0; /* There is a result in any case. */
 
9314
    }
 
9315
  }
 
9316
 
 
9317
  /*
 
9318
    If the MIN attribute is non-nullable, this->record already contains the
 
9319
    MIN key in the group, so just return.
 
9320
  */
 
9321
  return(result);
 
9322
}
 
9323
 
 
9324
 
 
9325
/* 
 
9326
  Retrieve the maximal key in the next group.
 
9327
 
 
9328
  SYNOPSIS
 
9329
    QUICK_GROUP_MIN_MAX_SELECT::next_max()
 
9330
 
 
9331
  DESCRIPTION
 
9332
    Lookup the maximal key of the group, and store it into this->record.
 
9333
 
 
9334
  RETURN
 
9335
    0                    on success
 
9336
    HA_ERR_KEY_NOT_FOUND if no MAX key was found that fulfills all conditions.
 
9337
    HA_ERR_END_OF_FILE   - "" -
 
9338
    other                if some error occurred
 
9339
*/
 
9340
 
 
9341
int QUICK_GROUP_MIN_MAX_SELECT::next_max()
 
9342
{
 
9343
  int result;
 
9344
 
 
9345
  /* Get the last key in the (possibly extended) group. */
 
9346
  if (min_max_ranges.elements > 0)
 
9347
    result= next_max_in_range();
 
9348
  else
 
9349
    result= file->index_read_map(record, group_prefix,
 
9350
                                 make_prev_keypart_map(real_key_parts),
 
9351
                                 HA_READ_PREFIX_LAST);
 
9352
  return(result);
 
9353
}
 
9354
 
 
9355
 
 
9356
/*
 
9357
  Determine the prefix of the next group.
 
9358
 
 
9359
  SYNOPSIS
 
9360
    QUICK_GROUP_MIN_MAX_SELECT::next_prefix()
 
9361
 
 
9362
  DESCRIPTION
 
9363
    Determine the prefix of the next group that satisfies the query conditions.
 
9364
    If there is a range condition referencing the group attributes, use a
 
9365
    QUICK_RANGE_SELECT object to retrieve the *first* key that satisfies the
 
9366
    condition. If there is a key infix of constants, append this infix
 
9367
    immediately after the group attributes. The possibly extended prefix is
 
9368
    stored in this->group_prefix. The first key of the found group is stored in
 
9369
    this->record, on which relies this->next_min().
 
9370
 
 
9371
  RETURN
 
9372
    0                    on success
 
9373
    HA_ERR_KEY_NOT_FOUND if there is no key with the formed prefix
 
9374
    HA_ERR_END_OF_FILE   if there are no more keys
 
9375
    other                if some error occurred
 
9376
*/
 
9377
int QUICK_GROUP_MIN_MAX_SELECT::next_prefix()
 
9378
{
 
9379
  int result;
 
9380
 
 
9381
  if (quick_prefix_select)
 
9382
  {
 
9383
    unsigned char *cur_prefix= seen_first_key ? group_prefix : NULL;
 
9384
    if ((result= quick_prefix_select->get_next_prefix(group_prefix_len,
 
9385
                         make_prev_keypart_map(group_key_parts), cur_prefix)))
 
9386
      return(result);
 
9387
    seen_first_key= true;
 
9388
  }
 
9389
  else
 
9390
  {
 
9391
    if (!seen_first_key)
 
9392
    {
 
9393
      result= file->index_first(record);
 
9394
      if (result)
 
9395
        return(result);
 
9396
      seen_first_key= true;
 
9397
    }
 
9398
    else
 
9399
    {
 
9400
      /* Load the first key in this group into record. */
 
9401
      result= file->index_read_map(record, group_prefix,
 
9402
                                   make_prev_keypart_map(group_key_parts),
 
9403
                                   HA_READ_AFTER_KEY);
 
9404
      if (result)
 
9405
        return(result);
 
9406
    }
 
9407
  }
 
9408
 
 
9409
  /* Save the prefix of this group for subsequent calls. */
 
9410
  key_copy(group_prefix, record, index_info, group_prefix_len);
 
9411
  /* Append key_infix to group_prefix. */
 
9412
  if (key_infix_len > 0)
 
9413
    memcpy(group_prefix + group_prefix_len,
 
9414
           key_infix, key_infix_len);
 
9415
 
 
9416
  return(0);
 
9417
}
 
9418
 
 
9419
 
 
9420
/*
 
9421
  Find the minimal key in a group that satisfies some range conditions for the
 
9422
  min/max argument field.
 
9423
 
 
9424
  SYNOPSIS
 
9425
    QUICK_GROUP_MIN_MAX_SELECT::next_min_in_range()
 
9426
 
 
9427
  DESCRIPTION
 
9428
    Given the sequence of ranges min_max_ranges, find the minimal key that is
 
9429
    in the left-most possible range. If there is no such key, then the current
 
9430
    group does not have a MIN key that satisfies the WHERE clause. If a key is
 
9431
    found, its value is stored in this->record.
 
9432
 
 
9433
  RETURN
 
9434
    0                    on success
 
9435
    HA_ERR_KEY_NOT_FOUND if there is no key with the given prefix in any of
 
9436
                         the ranges
 
9437
    HA_ERR_END_OF_FILE   - "" -
 
9438
    other                if some error
 
9439
*/
 
9440
 
 
9441
int QUICK_GROUP_MIN_MAX_SELECT::next_min_in_range()
 
9442
{
 
9443
  ha_rkey_function find_flag;
 
9444
  key_part_map keypart_map;
 
9445
  QUICK_RANGE *cur_range;
 
9446
  bool found_null= false;
 
9447
  int result= HA_ERR_KEY_NOT_FOUND;
 
9448
 
 
9449
  assert(min_max_ranges.elements > 0);
 
9450
 
 
9451
  for (uint32_t range_idx= 0; range_idx < min_max_ranges.elements; range_idx++)
 
9452
  { /* Search from the left-most range to the right. */
 
9453
    get_dynamic(&min_max_ranges, (unsigned char*)&cur_range, range_idx);
 
9454
 
 
9455
    /*
 
9456
      If the current value for the min/max argument is bigger than the right
 
9457
      boundary of cur_range, there is no need to check this range.
 
9458
    */
 
9459
    if (range_idx != 0 && !(cur_range->flag & NO_MAX_RANGE) &&
 
9460
        (key_cmp(min_max_arg_part, (const unsigned char*) cur_range->max_key,
 
9461
                 min_max_arg_len) == 1))
 
9462
      continue;
 
9463
 
 
9464
    if (cur_range->flag & NO_MIN_RANGE)
 
9465
    {
 
9466
      keypart_map= make_prev_keypart_map(real_key_parts);
 
9467
      find_flag= HA_READ_KEY_EXACT;
 
9468
    }
 
9469
    else
 
9470
    {
 
9471
      /* Extend the search key with the lower boundary for this range. */
 
9472
      memcpy(group_prefix + real_prefix_len, cur_range->min_key,
 
9473
             cur_range->min_length);
 
9474
      keypart_map= make_keypart_map(real_key_parts);
 
9475
      find_flag= (cur_range->flag & (EQ_RANGE | NULL_RANGE)) ?
 
9476
                 HA_READ_KEY_EXACT : (cur_range->flag & NEAR_MIN) ?
 
9477
                 HA_READ_AFTER_KEY : HA_READ_KEY_OR_NEXT;
 
9478
    }
 
9479
 
 
9480
    result= file->index_read_map(record, group_prefix, keypart_map, find_flag);
 
9481
    if (result)
 
9482
    {
 
9483
      if ((result == HA_ERR_KEY_NOT_FOUND || result == HA_ERR_END_OF_FILE) &&
 
9484
          (cur_range->flag & (EQ_RANGE | NULL_RANGE)))
 
9485
        continue; /* Check the next range. */
 
9486
 
 
9487
      /*
 
9488
        In all other cases (HA_ERR_*, HA_READ_KEY_EXACT with NO_MIN_RANGE,
 
9489
        HA_READ_AFTER_KEY, HA_READ_KEY_OR_NEXT) if the lookup failed for this
 
9490
        range, it can't succeed for any other subsequent range.
 
9491
      */
 
9492
      break;
 
9493
    }
 
9494
 
 
9495
    /* A key was found. */
 
9496
    if (cur_range->flag & EQ_RANGE)
 
9497
      break; /* No need to perform the checks below for equal keys. */
 
9498
 
 
9499
    if (cur_range->flag & NULL_RANGE)
 
9500
    {
 
9501
      /*
 
9502
        Remember this key, and continue looking for a non-NULL key that
 
9503
        satisfies some other condition.
 
9504
      */
 
9505
      memcpy(tmp_record, record, head->s->rec_buff_length);
 
9506
      found_null= true;
 
9507
      continue;
 
9508
    }
 
9509
 
 
9510
    /* Check if record belongs to the current group. */
 
9511
    if (key_cmp(index_info->key_part, group_prefix, real_prefix_len))
 
9512
    {
 
9513
      result= HA_ERR_KEY_NOT_FOUND;
 
9514
      continue;
 
9515
    }
 
9516
 
 
9517
    /* If there is an upper limit, check if the found key is in the range. */
 
9518
    if ( !(cur_range->flag & NO_MAX_RANGE) )
 
9519
    {
 
9520
      /* Compose the MAX key for the range. */
 
9521
      unsigned char *max_key= (unsigned char*) my_alloca(real_prefix_len + min_max_arg_len);
 
9522
      memcpy(max_key, group_prefix, real_prefix_len);
 
9523
      memcpy(max_key + real_prefix_len, cur_range->max_key,
 
9524
             cur_range->max_length);
 
9525
      /* Compare the found key with max_key. */
 
9526
      int cmp_res= key_cmp(index_info->key_part, max_key,
 
9527
                           real_prefix_len + min_max_arg_len);
 
9528
      if ((!((cur_range->flag & NEAR_MAX) && (cmp_res == -1)) || (cmp_res <= 0)))
 
9529
      {
 
9530
        result= HA_ERR_KEY_NOT_FOUND;
 
9531
        continue;
 
9532
      }
 
9533
    }
 
9534
    /* If we got to this point, the current key qualifies as MIN. */
 
9535
    assert(result == 0);
 
9536
    break;
 
9537
  }
 
9538
  /*
 
9539
    If there was a key with NULL in the MIN/MAX field, and there was no other
 
9540
    key without NULL from the same group that satisfies some other condition,
 
9541
    then use the key with the NULL.
 
9542
  */
 
9543
  if (found_null && result)
 
9544
  {
 
9545
    memcpy(record, tmp_record, head->s->rec_buff_length);
 
9546
    result= 0;
 
9547
  }
 
9548
  return result;
 
9549
}
 
9550
 
 
9551
 
 
9552
/*
 
9553
  Find the maximal key in a group that satisfies some range conditions for the
 
9554
  min/max argument field.
 
9555
 
 
9556
  SYNOPSIS
 
9557
    QUICK_GROUP_MIN_MAX_SELECT::next_max_in_range()
 
9558
 
 
9559
  DESCRIPTION
 
9560
    Given the sequence of ranges min_max_ranges, find the maximal key that is
 
9561
    in the right-most possible range. If there is no such key, then the current
 
9562
    group does not have a MAX key that satisfies the WHERE clause. If a key is
 
9563
    found, its value is stored in this->record.
 
9564
 
 
9565
  RETURN
 
9566
    0                    on success
 
9567
    HA_ERR_KEY_NOT_FOUND if there is no key with the given prefix in any of
 
9568
                         the ranges
 
9569
    HA_ERR_END_OF_FILE   - "" -
 
9570
    other                if some error
 
9571
*/
 
9572
 
 
9573
int QUICK_GROUP_MIN_MAX_SELECT::next_max_in_range()
 
9574
{
 
9575
  ha_rkey_function find_flag;
 
9576
  key_part_map keypart_map;
 
9577
  QUICK_RANGE *cur_range;
 
9578
  int result;
 
9579
 
 
9580
  assert(min_max_ranges.elements > 0);
 
9581
 
 
9582
  for (uint32_t range_idx= min_max_ranges.elements; range_idx > 0; range_idx--)
 
9583
  { /* Search from the right-most range to the left. */
 
9584
    get_dynamic(&min_max_ranges, (unsigned char*)&cur_range, range_idx - 1);
 
9585
 
 
9586
    /*
 
9587
      If the current value for the min/max argument is smaller than the left
 
9588
      boundary of cur_range, there is no need to check this range.
 
9589
    */
 
9590
    if (range_idx != min_max_ranges.elements &&
 
9591
        !(cur_range->flag & NO_MIN_RANGE) &&
 
9592
        (key_cmp(min_max_arg_part, (const unsigned char*) cur_range->min_key,
 
9593
                 min_max_arg_len) == -1))
 
9594
      continue;
 
9595
 
 
9596
    if (cur_range->flag & NO_MAX_RANGE)
 
9597
    {
 
9598
      keypart_map= make_prev_keypart_map(real_key_parts);
 
9599
      find_flag= HA_READ_PREFIX_LAST;
 
9600
    }
 
9601
    else
 
9602
    {
 
9603
      /* Extend the search key with the upper boundary for this range. */
 
9604
      memcpy(group_prefix + real_prefix_len, cur_range->max_key,
 
9605
             cur_range->max_length);
 
9606
      keypart_map= make_keypart_map(real_key_parts);
 
9607
      find_flag= (cur_range->flag & EQ_RANGE) ?
 
9608
                 HA_READ_KEY_EXACT : (cur_range->flag & NEAR_MAX) ?
 
9609
                 HA_READ_BEFORE_KEY : HA_READ_PREFIX_LAST_OR_PREV;
 
9610
    }
 
9611
 
 
9612
    result= file->index_read_map(record, group_prefix, keypart_map, find_flag);
 
9613
 
 
9614
    if (result)
 
9615
    {
 
9616
      if ((result == HA_ERR_KEY_NOT_FOUND || result == HA_ERR_END_OF_FILE) &&
 
9617
          (cur_range->flag & EQ_RANGE))
 
9618
        continue; /* Check the next range. */
 
9619
 
 
9620
      /*
 
9621
        In no key was found with this upper bound, there certainly are no keys
 
9622
        in the ranges to the left.
 
9623
      */
 
9624
      return result;
 
9625
    }
 
9626
    /* A key was found. */
 
9627
    if (cur_range->flag & EQ_RANGE)
 
9628
      return 0; /* No need to perform the checks below for equal keys. */
 
9629
 
 
9630
    /* Check if record belongs to the current group. */
 
9631
    if (key_cmp(index_info->key_part, group_prefix, real_prefix_len))
 
9632
      continue;                                 // Row not found
 
9633
 
 
9634
    /* If there is a lower limit, check if the found key is in the range. */
 
9635
    if ( !(cur_range->flag & NO_MIN_RANGE) )
 
9636
    {
 
9637
      /* Compose the MIN key for the range. */
 
9638
      unsigned char *min_key= (unsigned char*) my_alloca(real_prefix_len + min_max_arg_len);
 
9639
      memcpy(min_key, group_prefix, real_prefix_len);
 
9640
      memcpy(min_key + real_prefix_len, cur_range->min_key,
 
9641
             cur_range->min_length);
 
9642
      /* Compare the found key with min_key. */
 
9643
      int cmp_res= key_cmp(index_info->key_part, min_key,
 
9644
                           real_prefix_len + min_max_arg_len);
 
9645
      if ((!((cur_range->flag & NEAR_MIN) && (cmp_res == 1)) ||
 
9646
            (cmp_res >= 0)))
 
9647
        continue;
 
9648
    }
 
9649
    /* If we got to this point, the current key qualifies as MAX. */
 
9650
    return result;
 
9651
  }
 
9652
  return HA_ERR_KEY_NOT_FOUND;
 
9653
}
 
9654
 
 
9655
 
 
9656
/*
 
9657
  Update all MIN function results with the newly found value.
 
9658
 
 
9659
  SYNOPSIS
 
9660
    QUICK_GROUP_MIN_MAX_SELECT::update_min_result()
 
9661
 
 
9662
  DESCRIPTION
 
9663
    The method iterates through all MIN functions and updates the result value
 
9664
    of each function by calling Item_sum::reset(), which in turn picks the new
 
9665
    result value from this->head->record[0], previously updated by
 
9666
    next_min(). The updated value is stored in a member variable of each of the
 
9667
    Item_sum objects, depending on the value type.
 
9668
 
 
9669
  IMPLEMENTATION
 
9670
    The update must be done separately for MIN and MAX, immediately after
 
9671
    next_min() was called and before next_max() is called, because both MIN and
 
9672
    MAX take their result value from the same buffer this->head->record[0]
 
9673
    (i.e.  this->record).
 
9674
 
 
9675
  RETURN
 
9676
    None
 
9677
*/
 
9678
 
 
9679
void QUICK_GROUP_MIN_MAX_SELECT::update_min_result()
 
9680
{
 
9681
  Item_sum *min_func;
 
9682
 
 
9683
  min_functions_it->rewind();
 
9684
  while ((min_func= (*min_functions_it)++))
 
9685
    min_func->reset();
 
9686
}
 
9687
 
 
9688
 
 
9689
/*
 
9690
  Update all MAX function results with the newly found value.
 
9691
 
 
9692
  SYNOPSIS
 
9693
    QUICK_GROUP_MIN_MAX_SELECT::update_max_result()
 
9694
 
 
9695
  DESCRIPTION
 
9696
    The method iterates through all MAX functions and updates the result value
 
9697
    of each function by calling Item_sum::reset(), which in turn picks the new
 
9698
    result value from this->head->record[0], previously updated by
 
9699
    next_max(). The updated value is stored in a member variable of each of the
 
9700
    Item_sum objects, depending on the value type.
 
9701
 
 
9702
  IMPLEMENTATION
 
9703
    The update must be done separately for MIN and MAX, immediately after
 
9704
    next_max() was called, because both MIN and MAX take their result value
 
9705
    from the same buffer this->head->record[0] (i.e.  this->record).
 
9706
 
 
9707
  RETURN
 
9708
    None
 
9709
*/
 
9710
 
 
9711
void QUICK_GROUP_MIN_MAX_SELECT::update_max_result()
 
9712
{
 
9713
  Item_sum *max_func;
 
9714
 
 
9715
  max_functions_it->rewind();
 
9716
  while ((max_func= (*max_functions_it)++))
 
9717
    max_func->reset();
 
9718
}
 
9719
 
 
9720
 
 
9721
/*
 
9722
  Append comma-separated list of keys this quick select uses to key_names;
 
9723
  append comma-separated list of corresponding used lengths to used_lengths.
 
9724
 
 
9725
  SYNOPSIS
 
9726
    QUICK_GROUP_MIN_MAX_SELECT::add_keys_and_lengths()
 
9727
    key_names    [out] Names of used indexes
 
9728
    used_lengths [out] Corresponding lengths of the index names
 
9729
 
 
9730
  DESCRIPTION
 
9731
    This method is used by select_describe to extract the names of the
 
9732
    indexes used by a quick select.
 
9733
 
 
9734
*/
 
9735
 
 
9736
void QUICK_GROUP_MIN_MAX_SELECT::add_keys_and_lengths(String *key_names,
 
9737
                                                      String *used_lengths)
 
9738
{
 
9739
  char buf[64];
 
9740
  uint32_t length;
 
9741
  key_names->append(index_info->name);
 
9742
  length= int64_t2str(max_used_key_length, buf, 10) - buf;
 
9743
  used_lengths->append(buf, length);
 
9744
}
 
9745
 
 
9746
static void print_sel_tree(PARAM *param, SEL_TREE *tree, key_map *tree_map,
 
9747
                           const char *msg __attribute__((unused)))
 
9748
{
 
9749
  SEL_ARG **key,**end;
 
9750
  int idx;
 
9751
  char buff[1024];
 
9752
 
 
9753
  String tmp(buff,sizeof(buff),&my_charset_bin);
 
9754
  tmp.length(0);
 
9755
  for (idx= 0,key=tree->keys, end=key+param->keys ;
 
9756
       key != end ;
 
9757
       key++,idx++)
 
9758
  {
 
9759
    if (tree_map->is_set(idx))
 
9760
    {
 
9761
      uint32_t keynr= param->real_keynr[idx];
 
9762
      if (tmp.length())
 
9763
        tmp.append(',');
 
9764
      tmp.append(param->table->key_info[keynr].name);
 
9765
    }
 
9766
  }
 
9767
  if (!tmp.length())
 
9768
    tmp.append(STRING_WITH_LEN("(empty)"));
 
9769
 
 
9770
  return;
 
9771
}
 
9772
 
 
9773
 
 
9774
static void print_ror_scans_arr(Table *table,
 
9775
                                const char *msg __attribute__((unused)),
 
9776
                                struct st_ror_scan_info **start,
 
9777
                                struct st_ror_scan_info **end)
 
9778
{
 
9779
  char buff[1024];
 
9780
  String tmp(buff,sizeof(buff),&my_charset_bin);
 
9781
  tmp.length(0);
 
9782
  for (;start != end; start++)
 
9783
  {
 
9784
    if (tmp.length())
 
9785
      tmp.append(',');
 
9786
    tmp.append(table->key_info[(*start)->keynr].name);
 
9787
  }
 
9788
  if (!tmp.length())
 
9789
    tmp.append(STRING_WITH_LEN("(empty)"));
 
9790
  return;
 
9791
}
 
9792
 
 
9793
/*****************************************************************************
 
9794
** Instantiate templates 
 
9795
*****************************************************************************/
 
9796
 
 
9797
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
 
9798
template class List<QUICK_RANGE>;
 
9799
template class List_iterator<QUICK_RANGE>;
 
9800
#endif