~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/opt_range.cc

  • Committer: Monty Taylor
  • Date: 2009-04-25 20:45:19 UTC
  • mto: (997.2.5 mordred)
  • mto: This revision was merged to the branch mainline in revision 1003.
  • Revision ID: mordred@inaugust.com-20090425204519-lgrl7mz2r66v0jby
Blackhole.

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