~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/opt_range.cc

  • Committer: Monty Taylor
  • Date: 2008-08-01 22:33:44 UTC
  • mto: (236.1.42 codestyle)
  • mto: This revision was merged to the branch mainline in revision 261.
  • Revision ID: monty@inaugust.com-20080801223344-vzhlflfmtijp1imv
First pass at gettexizing the error messages.

Show diffs side-by-side

added added

removed removed

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