~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/opt_range.cc

  • Committer: Brian Aker
  • Date: 2008-10-29 13:46:43 UTC
  • Revision ID: brian@tangent.org-20081029134643-z6jcwjvyruhk2vlu
Updates for ignore file.

Show diffs side-by-side

added added

removed removed

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