~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/opt_range.cc

  • Committer: Jay Pipes
  • Date: 2008-09-11 16:03:22 UTC
  • mto: (383.5.1 trunk)
  • mto: This revision was merged to the branch mainline in revision 386.
  • Revision ID: jay@mysql.com-20080911160322-vrl0k1djo6q6ytv1
Removed SQL_MODE variances from comment_table.test and ensured correct error thrown when a comment that is too long was input.  After moving to proto buffer definition for table, the 2048 length will go away.

Show diffs side-by-side

added added

removed removed

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