~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/opt_range.cc

  • Committer: Brian Aker
  • Date: 2008-07-28 18:01:38 UTC
  • Revision ID: brian@tangent.org-20080728180138-q2pxlq0qiapvqsdn
Remove YEAR field type

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