~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/opt_range.cc

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

Show diffs side-by-side

added added

removed removed

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