~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/opt_range.cc

  • Committer: Brian Aker
  • Date: 2008-10-12 01:59:02 UTC
  • Revision ID: brian@tangent.org-20081012015902-prhy6wsimdqr28om
Dead code around unsigned (first pass)

Show diffs side-by-side

added added

removed removed

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