~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/opt_sum.cc

Merged vcol stuff.

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; either version 2 of the License, or
9
 
 *  (at your option) any later version.
10
 
 *
11
 
 *  This program is distributed in the hope that it will be useful,
12
 
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 
 *  GNU General Public License for more details.
15
 
 *
16
 
 *  You should have received a copy of the GNU General Public License
17
 
 *  along with this program; if not, write to the Free Software
18
 
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19
 
 */
 
1
/* Copyright (C) 2000-2003 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 */
 
15
 
20
16
 
21
17
/**
22
18
  @file
23
19
 
24
20
  Optimising of MIN(), MAX() and COUNT(*) queries without 'group by' clause
25
 
  by replacing the aggregate expression with a constant.
 
21
  by replacing the aggregate expression with a constant.  
26
22
 
27
23
  Given a table with a compound key on columns (a,b,c), the following
28
24
  types of queries are optimised (assuming the table handler supports
45
41
  involved tables and return the answer without any join. Thus, the
46
42
  following query will be replaced with a row of two constants:
47
43
  @verbatim
48
 
  SELECT MAX(b), MIN(d) FROM t1,t2
 
44
  SELECT MAX(b), MIN(d) FROM t1,t2 
49
45
    WHERE a=const AND b<const AND d>const
50
46
  @endverbatim
51
47
  (assuming a index for column d of table t2 is defined)
52
48
*/
53
49
 
54
 
#include "config.h"
55
 
#include "drizzled/sql_select.h"
56
 
#include "drizzled/item/sum.h"
57
 
#include "drizzled/item/cmpfunc.h"
58
 
#include "drizzled/optimizer/sum.h"
59
 
#include "drizzled/plugin/storage_engine.h"
60
 
 
61
 
namespace drizzled
62
 
{
63
 
 
64
 
static bool find_key_for_maxmin(bool max_fl,
65
 
                                table_reference_st *ref,
66
 
                                Field* field,
67
 
                                COND *cond,
68
 
                                uint32_t *range_fl,
 
50
#include <drizzled/server_includes.h>
 
51
#include <drizzled/sql_select.h>
 
52
 
 
53
static bool find_key_for_maxmin(bool max_fl, TABLE_REF *ref, Field* field,
 
54
                                COND *cond, uint32_t *range_fl,
69
55
                                uint32_t *key_prefix_length);
70
 
 
71
 
static int reckey_in_range(bool max_fl,
72
 
                           table_reference_st *ref,
73
 
                           Field* field,
74
 
                           COND *cond,
75
 
                           uint32_t range_fl,
76
 
                           uint32_t prefix_len);
77
 
 
78
 
static int maxmin_in_range(bool max_fl, Field *field, COND *cond);
 
56
static int reckey_in_range(bool max_fl, TABLE_REF *ref, Field* field,
 
57
                            COND *cond, uint32_t range_fl, uint32_t prefix_len);
 
58
static int maxmin_in_range(bool max_fl, Field* field, COND *cond);
79
59
 
80
60
 
81
61
/*
93
73
    UINT64_MAX  Error: Could not calculate number of rows
94
74
    #                   Multiplication of number of rows in all tables
95
75
*/
 
76
 
96
77
static uint64_t get_exact_record_count(TableList *tables)
97
78
{
98
79
  uint64_t count= 1;
99
80
  for (TableList *tl= tables; tl; tl= tl->next_leaf)
100
81
  {
101
 
    ha_rows tmp= tl->table->cursor->records();
 
82
    ha_rows tmp= tl->table->file->records();
102
83
    if ((tmp == HA_POS_ERROR))
103
 
    {
104
84
      return UINT64_MAX;
105
 
    }
106
85
    count*= tmp;
107
86
  }
108
87
  return count;
109
88
}
110
89
 
111
90
 
112
 
int optimizer::sum_query(TableList *tables, List<Item> &all_fields, COND *conds)
 
91
/**
 
92
  Substitutes constants for some COUNT(), MIN() and MAX() functions.
 
93
 
 
94
  @param tables                list of leaves of join table tree
 
95
  @param all_fields            All fields to be returned
 
96
  @param conds                 WHERE clause
 
97
 
 
98
  @note
 
99
    This function is only called for queries with sum functions and no
 
100
    GROUP BY part.
 
101
 
 
102
  @retval
 
103
    0                    no errors
 
104
  @retval
 
105
    1                    if all items were resolved
 
106
  @retval
 
107
    HA_ERR_KEY_NOT_FOUND on impossible conditions
 
108
  @retval
 
109
    HA_ERR_... if a deadlock or a lock wait timeout happens, for example
 
110
*/
 
111
 
 
112
int opt_sum_query(TableList *tables, List<Item> &all_fields,COND *conds)
113
113
{
114
114
  List_iterator_fast<Item> it(all_fields);
115
115
  int const_result= 1;
116
 
  bool recalc_const_item= false;
 
116
  bool recalc_const_item= 0;
117
117
  uint64_t count= 1;
118
 
  bool is_exact_count= true;
119
 
  bool maybe_exact_count= true;
120
 
  table_map removed_tables= 0;
121
 
  table_map outer_tables= 0;
122
 
  table_map used_tables= 0;
 
118
  bool is_exact_count= true, maybe_exact_count= true;
 
119
  table_map removed_tables= 0, outer_tables= 0, used_tables= 0;
123
120
  table_map where_tables= 0;
124
 
  Item *item= NULL;
 
121
  Item *item;
125
122
  int error;
126
123
 
127
124
  if (conds)
128
 
  {
129
125
    where_tables= conds->used_tables();
130
 
  }
131
126
 
132
127
  /*
133
 
     Analyze outer join dependencies, and, if possible, compute the number
134
 
     of returned rows.
135
 
   */
 
128
    Analyze outer join dependencies, and, if possible, compute the number
 
129
    of returned rows.
 
130
  */
136
131
  for (TableList *tl= tables; tl; tl= tl->next_leaf)
137
132
  {
138
 
    TableList *embedded= NULL;
139
 
    for (embedded= tl; embedded; embedded= embedded->getEmbedding())
 
133
    TableList *embedded;
 
134
    for (embedded= tl ; embedded; embedded= embedded->embedding)
140
135
    {
141
136
      if (embedded->on_expr)
142
137
        break;
143
138
    }
144
139
    if (embedded)
145
 
      /* Don't replace expression on a table that is part of an outer join */
 
140
    /* Don't replace expression on a table that is part of an outer join */
146
141
    {
147
142
      outer_tables|= tl->table->map;
148
143
 
149
144
      /*
150
 
         We can't optimise LEFT JOIN in cases where the WHERE condition
151
 
         restricts the table that is used, like in:
152
 
         SELECT MAX(t1.a) FROM t1 LEFT JOIN t2 join-condition
153
 
         WHERE t2.field IS NULL;
154
 
       */
 
145
        We can't optimise LEFT JOIN in cases where the WHERE condition
 
146
        restricts the table that is used, like in:
 
147
          SELECT MAX(t1.a) FROM t1 LEFT JOIN t2 join-condition
 
148
          WHERE t2.field IS NULL;
 
149
      */
155
150
      if (tl->table->map & where_tables)
156
151
        return 0;
157
152
    }
158
153
    else
159
 
    {
160
154
      used_tables|= tl->table->map;
161
 
    }
162
155
 
163
156
    /*
164
 
       If the storage manager of 'tl' gives exact row count as part of
165
 
       statistics (cheap), compute the total number of rows. If there are
166
 
       no outer table dependencies, this count may be used as the real count.
167
 
       Schema tables are filled after this function is invoked, so we can't
168
 
       get row count
169
 
     */
170
 
    if (! (tl->table->cursor->getEngine()->check_flag(HTON_BIT_STATS_RECORDS_IS_EXACT)))
 
157
      If the storage manager of 'tl' gives exact row count as part of
 
158
      statistics (cheap), compute the total number of rows. If there are
 
159
      no outer table dependencies, this count may be used as the real count.
 
160
      Schema tables are filled after this function is invoked, so we can't
 
161
      get row count 
 
162
    */
 
163
    if (!(tl->table->file->ha_table_flags() & HA_STATS_RECORDS_IS_EXACT) ||
 
164
        tl->schema_table)
171
165
    {
172
 
      maybe_exact_count&= test(tl->table->cursor->getEngine()->check_flag(HTON_BIT_HAS_RECORDS));
 
166
      maybe_exact_count&= test(!tl->schema_table &&
 
167
                               (tl->table->file->ha_table_flags() &
 
168
                                HA_HAS_RECORDS));
173
169
      is_exact_count= false;
174
 
      count= 1; // ensure count != 0
 
170
      count= 1;                                 // ensure count != 0
175
171
    }
176
172
    else
177
173
    {
178
 
      error= tl->table->cursor->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);
 
174
      error= tl->table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);
179
175
      if(error)
180
176
      {
181
 
        tl->table->print_error(error, MYF(ME_FATALERROR));
 
177
        tl->table->file->print_error(error, MYF(ME_FATALERROR));
182
178
        return error;
183
179
      }
184
 
      count*= tl->table->cursor->stats.records;
 
180
      count*= tl->table->file->stats.records;
185
181
    }
186
182
  }
187
183
 
188
184
  /*
189
 
     Iterate through all items in the SELECT clause and replace
190
 
     COUNT(), MIN() and MAX() with constants (if possible).
191
 
   */
 
185
    Iterate through all items in the SELECT clause and replace
 
186
    COUNT(), MIN() and MAX() with constants (if possible).
 
187
  */
192
188
 
193
189
  while ((item= it++))
194
190
  {
195
191
    if (item->type() == Item::SUM_FUNC_ITEM)
196
192
    {
197
193
      Item_sum *item_sum= (((Item_sum*) item));
198
 
      switch (item_sum->sum_func())
 
194
      switch (item_sum->sum_func()) {
 
195
      case Item_sum::COUNT_FUNC:
 
196
        /*
 
197
          If the expr in COUNT(expr) can never be null we can change this
 
198
          to the number of rows in the tables if this number is exact and
 
199
          there are no outer joins.
 
200
        */
 
201
        if (!conds && !((Item_sum_count*) item)->args[0]->maybe_null &&
 
202
            !outer_tables && maybe_exact_count)
 
203
        {
 
204
          if (!is_exact_count)
 
205
          {
 
206
            if ((count= get_exact_record_count(tables)) == UINT64_MAX)
 
207
            {
 
208
              /* Error from handler in counting rows. Don't optimize count() */
 
209
              const_result= 0;
 
210
              continue;
 
211
            }
 
212
            is_exact_count= 1;                  // count is now exact
 
213
          }
 
214
          ((Item_sum_count*) item)->make_const((int64_t) count);
 
215
          recalc_const_item= 1;
 
216
        }
 
217
        else
 
218
          const_result= 0;
 
219
        break;
 
220
      case Item_sum::MIN_FUNC:
199
221
      {
200
 
        case Item_sum::COUNT_FUNC:
201
 
          /*
202
 
             If the expr in COUNT(expr) can never be null we can change this
203
 
             to the number of rows in the tables if this number is exact and
204
 
             there are no outer joins.
205
 
           */
206
 
          if (! conds && ! ((Item_sum_count*) item)->args[0]->maybe_null &&
207
 
              ! outer_tables && maybe_exact_count)
208
 
          {
209
 
            if (! is_exact_count)
 
222
        /*
 
223
          If MIN(expr) is the first part of a key or if all previous
 
224
          parts of the key is found in the COND, then we can use
 
225
          indexes to find the key.
 
226
        */
 
227
        Item *expr=item_sum->args[0];
 
228
        if (expr->real_item()->type() == Item::FIELD_ITEM)
 
229
        {
 
230
          unsigned char key_buff[MAX_KEY_LENGTH];
 
231
          TABLE_REF ref;
 
232
          uint32_t range_fl, prefix_len;
 
233
 
 
234
          ref.key_buff= key_buff;
 
235
          Item_field *item_field= (Item_field*) (expr->real_item());
 
236
          Table *table= item_field->field->table;
 
237
 
 
238
          /* 
 
239
            Look for a partial key that can be used for optimization.
 
240
            If we succeed, ref.key_length will contain the length of
 
241
            this key, while prefix_len will contain the length of 
 
242
            the beginning of this key without field used in MIN(). 
 
243
            Type of range for the key part for this field will be
 
244
            returned in range_fl.
 
245
          */
 
246
          if (table->file->inited || (outer_tables & table->map) ||
 
247
              !find_key_for_maxmin(0, &ref, item_field->field, conds,
 
248
                                   &range_fl, &prefix_len))
 
249
          {
 
250
            const_result= 0;
 
251
            break;
 
252
          }
 
253
          error= table->file->ha_index_init((uint) ref.key, 1);
 
254
 
 
255
          if (!ref.key_length)
 
256
            error= table->file->index_first(table->record[0]);
 
257
          else 
 
258
          {
 
259
            /*
 
260
              Use index to replace MIN/MAX functions with their values
 
261
              according to the following rules:
 
262
           
 
263
              1) Insert the minimum non-null values where the WHERE clause still
 
264
                 matches, or
 
265
              2) a NULL value if there are only NULL values for key_part_k.
 
266
              3) Fail, producing a row of nulls
 
267
 
 
268
              Implementation: Read the smallest value using the search key. If
 
269
              the interval is open, read the next value after the search
 
270
              key. If read fails, and we're looking for a MIN() value for a
 
271
              nullable column, test if there is an exact match for the key.
 
272
            */
 
273
            if (!(range_fl & NEAR_MIN))
 
274
              /* 
 
275
                 Closed interval: Either The MIN argument is non-nullable, or
 
276
                 we have a >= predicate for the MIN argument.
 
277
              */
 
278
              error= table->file->index_read_map(table->record[0],
 
279
                                                 ref.key_buff,
 
280
                                                 make_prev_keypart_map(ref.key_parts),
 
281
                                                 HA_READ_KEY_OR_NEXT);
 
282
            else
210
283
            {
211
 
              if ((count= get_exact_record_count(tables)) == UINT64_MAX)
 
284
              /*
 
285
                Open interval: There are two cases:
 
286
                1) We have only MIN() and the argument column is nullable, or
 
287
                2) there is a > predicate on it, nullability is irrelevant.
 
288
                We need to scan the next bigger record first.
 
289
              */
 
290
              error= table->file->index_read_map(table->record[0],
 
291
                                                 ref.key_buff, 
 
292
                                                 make_prev_keypart_map(ref.key_parts),
 
293
                                                 HA_READ_AFTER_KEY);
 
294
              /* 
 
295
                 If the found record is outside the group formed by the search
 
296
                 prefix, or there is no such record at all, check if all
 
297
                 records in that group have NULL in the MIN argument
 
298
                 column. If that is the case return that NULL.
 
299
 
 
300
                 Check if case 1 from above holds. If it does, we should read
 
301
                 the skipped tuple.
 
302
              */
 
303
              if (item_field->field->real_maybe_null() &&
 
304
                  ref.key_buff[prefix_len] == 1 &&
 
305
                  /*
 
306
                     Last keypart (i.e. the argument to MIN) is set to NULL by
 
307
                     find_key_for_maxmin only if all other keyparts are bound
 
308
                     to constants in a conjunction of equalities. Hence, we
 
309
                     can detect this by checking only if the last keypart is
 
310
                     NULL.
 
311
                  */
 
312
                  (error == HA_ERR_KEY_NOT_FOUND ||
 
313
                   key_cmp_if_same(table, ref.key_buff, ref.key, prefix_len)))
212
314
              {
213
 
                /* Error from handler in counting rows. Don't optimize count() */
214
 
                const_result= 0;
215
 
                continue;
 
315
                assert(item_field->field->real_maybe_null());
 
316
                error= table->file->index_read_map(table->record[0],
 
317
                                                   ref.key_buff,
 
318
                                                   make_prev_keypart_map(ref.key_parts),
 
319
                                                   HA_READ_KEY_EXACT);
216
320
              }
217
 
              is_exact_count= 1;                  // count is now exact
218
321
            }
219
 
            ((Item_sum_count*) item)->make_const_count((int64_t) count);
220
 
            recalc_const_item= 1;
221
 
          }
 
322
          }
 
323
          /* Verify that the read tuple indeed matches the search key */
 
324
          if (!error && reckey_in_range(0, &ref, item_field->field, 
 
325
                                        conds, range_fl, prefix_len))
 
326
            error= HA_ERR_KEY_NOT_FOUND;
 
327
          if (table->key_read)
 
328
          {
 
329
            table->key_read= 0;
 
330
            table->file->extra(HA_EXTRA_NO_KEYREAD);
 
331
          }
 
332
          table->file->ha_index_end();
 
333
          if (error)
 
334
          {
 
335
            if (error == HA_ERR_KEY_NOT_FOUND || error == HA_ERR_END_OF_FILE)
 
336
              return HA_ERR_KEY_NOT_FOUND;            // No rows matching WHERE
 
337
            /* HA_ERR_LOCK_DEADLOCK or some other error */
 
338
            table->file->print_error(error, MYF(0));
 
339
            return(error);
 
340
          }
 
341
          removed_tables|= table->map;
 
342
        }
 
343
        else if (!expr->const_item() || !is_exact_count)
 
344
        {
 
345
          /*
 
346
            The optimization is not applicable in both cases:
 
347
            (a) 'expr' is a non-constant expression. Then we can't
 
348
            replace 'expr' by a constant.
 
349
            (b) 'expr' is a costant. According to ANSI, MIN/MAX must return
 
350
            NULL if the query does not return any rows. Thus, if we are not
 
351
            able to determine if the query returns any rows, we can't apply
 
352
            the optimization and replace MIN/MAX with a constant.
 
353
          */
 
354
          const_result= 0;
 
355
          break;
 
356
        }
 
357
        if (!count)
 
358
        {
 
359
          /* If count == 0, then we know that is_exact_count == true. */
 
360
          ((Item_sum_min*) item_sum)->clear(); /* Set to NULL. */
 
361
        }
 
362
        else
 
363
          ((Item_sum_min*) item_sum)->reset(); /* Set to the constant value. */
 
364
        ((Item_sum_min*) item_sum)->make_const();
 
365
        recalc_const_item= 1;
 
366
        break;
 
367
      }
 
368
      case Item_sum::MAX_FUNC:
 
369
      {
 
370
        /*
 
371
          If MAX(expr) is the first part of a key or if all previous
 
372
          parts of the key is found in the COND, then we can use
 
373
          indexes to find the key.
 
374
        */
 
375
        Item *expr=item_sum->args[0];
 
376
        if (expr->real_item()->type() == Item::FIELD_ITEM)
 
377
        {
 
378
          unsigned char key_buff[MAX_KEY_LENGTH];
 
379
          TABLE_REF ref;
 
380
          uint32_t range_fl, prefix_len;
 
381
 
 
382
          ref.key_buff= key_buff;
 
383
          Item_field *item_field= (Item_field*) (expr->real_item());
 
384
          Table *table= item_field->field->table;
 
385
 
 
386
          /* 
 
387
            Look for a partial key that can be used for optimization.
 
388
            If we succeed, ref.key_length will contain the length of
 
389
            this key, while prefix_len will contain the length of 
 
390
            the beginning of this key without field used in MAX().
 
391
            Type of range for the key part for this field will be
 
392
            returned in range_fl.
 
393
          */
 
394
          if (table->file->inited || (outer_tables & table->map) ||
 
395
                  !find_key_for_maxmin(1, &ref, item_field->field, conds,
 
396
                                                   &range_fl, &prefix_len))
 
397
          {
 
398
            const_result= 0;
 
399
            break;
 
400
          }
 
401
          error= table->file->ha_index_init((uint) ref.key, 1);
 
402
 
 
403
          if (!ref.key_length)
 
404
            error= table->file->index_last(table->record[0]);
222
405
          else
223
 
          {
224
 
            const_result= 0;
225
 
          }
226
 
          break;
227
 
        case Item_sum::MIN_FUNC:
228
 
          {
229
 
            /*
230
 
               If MIN(expr) is the first part of a key or if all previous
231
 
               parts of the key is found in the COND, then we can use
232
 
               indexes to find the key.
233
 
             */
234
 
            Item *expr=item_sum->args[0];
235
 
            if (expr->real_item()->type() == Item::FIELD_ITEM)
236
 
            {
237
 
              unsigned char key_buff[MAX_KEY_LENGTH];
238
 
              table_reference_st ref;
239
 
              uint32_t range_fl, prefix_len;
240
 
 
241
 
              ref.key_buff= key_buff;
242
 
              Item_field *item_field= (Item_field*) (expr->real_item());
243
 
              Table *table= item_field->field->getTable();
244
 
 
245
 
              /*
246
 
                 Look for a partial key that can be used for optimization.
247
 
                 If we succeed, ref.key_length will contain the length of
248
 
                 this key, while prefix_len will contain the length of
249
 
                 the beginning of this key without field used in MIN().
250
 
                 Type of range for the key part for this field will be
251
 
                 returned in range_fl.
252
 
               */
253
 
              if (table->cursor->inited ||
254
 
                  (outer_tables & table->map) ||
255
 
                  ! find_key_for_maxmin(0,
256
 
                                        &ref,
257
 
                                        item_field->field,
258
 
                                        conds,
259
 
                                        &range_fl,
260
 
                                        &prefix_len))
261
 
              {
262
 
                const_result= 0;
263
 
                break;
264
 
              }
265
 
              error= table->cursor->startIndexScan(static_cast<uint32_t>(ref.key), 1);
266
 
 
267
 
              if (! ref.key_length)
268
 
              {
269
 
                error= table->cursor->index_first(table->record[0]);
270
 
              }
271
 
              else
272
 
              {
273
 
                /*
274
 
                   Use index to replace MIN/MAX functions with their values
275
 
                   according to the following rules:
276
 
 
277
 
                   1) Insert the minimum non-null values where the WHERE clause still
278
 
                   matches, or
279
 
                   2) a NULL value if there are only NULL values for key_part_k.
280
 
                   3) Fail, producing a row of nulls
281
 
 
282
 
                   Implementation: Read the smallest value using the search key. If
283
 
                   the interval is open, read the next value after the search
284
 
                   key. If read fails, and we're looking for a MIN() value for a
285
 
                   nullable column, test if there is an exact match for the key.
286
 
                 */
287
 
                if (! (range_fl & NEAR_MIN))
288
 
                {
289
 
                  /*
290
 
                     Closed interval: Either The MIN argument is non-nullable, or
291
 
                     we have a >= predicate for the MIN argument.
292
 
                   */
293
 
                  error= table->cursor->index_read_map(table->record[0],
294
 
                                                       ref.key_buff,
295
 
                                                       make_prev_keypart_map(ref.key_parts),
296
 
                                                       HA_READ_KEY_OR_NEXT);
297
 
                }
298
 
                else
299
 
                {
300
 
                  /*
301
 
                     Open interval: There are two cases:
302
 
                     1) We have only MIN() and the argument column is nullable, or
303
 
                     2) there is a > predicate on it, nullability is irrelevant.
304
 
                     We need to scan the next bigger record first.
305
 
                   */
306
 
                  error= table->cursor->index_read_map(table->record[0],
307
 
                                                       ref.key_buff,
308
 
                                                       make_prev_keypart_map(ref.key_parts),
309
 
                                                       HA_READ_AFTER_KEY);
310
 
                  /*
311
 
                     If the found record is outside the group formed by the search
312
 
                     prefix, or there is no such record at all, check if all
313
 
                     records in that group have NULL in the MIN argument
314
 
                     column. If that is the case return that NULL.
315
 
 
316
 
                     Check if case 1 from above holds. If it does, we should read
317
 
                     the skipped tuple.
318
 
                   */
319
 
                  if (item_field->field->real_maybe_null() &&
320
 
                      ref.key_buff[prefix_len] == 1 &&
321
 
                      /*
322
 
                         Last keypart (i.e. the argument to MIN) is set to NULL by
323
 
                         find_key_for_maxmin only if all other keyparts are bound
324
 
                         to constants in a conjunction of equalities. Hence, we
325
 
                         can detect this by checking only if the last keypart is
326
 
                         NULL.
327
 
                       */
328
 
                      (error == HA_ERR_KEY_NOT_FOUND ||
329
 
                       key_cmp_if_same(table, ref.key_buff, ref.key, prefix_len)))
330
 
                  {
331
 
                    assert(item_field->field->real_maybe_null());
332
 
                    error= table->cursor->index_read_map(table->record[0],
333
 
                                                         ref.key_buff,
334
 
                                                         make_prev_keypart_map(ref.key_parts),
335
 
                                                         HA_READ_KEY_EXACT);
336
 
                  }
337
 
                }
338
 
              }
339
 
              /* Verify that the read tuple indeed matches the search key */
340
 
              if (! error &&
341
 
                  reckey_in_range(0,
342
 
                                  &ref,
343
 
                                  item_field->field,
344
 
                                  conds,
345
 
                                  range_fl,
346
 
                                  prefix_len))
347
 
              {
348
 
                error= HA_ERR_KEY_NOT_FOUND;
349
 
              }
350
 
              if (table->key_read)
351
 
              {
352
 
                table->key_read= 0;
353
 
                table->cursor->extra(HA_EXTRA_NO_KEYREAD);
354
 
              }
355
 
              table->cursor->endIndexScan();
356
 
              if (error)
357
 
              {
358
 
                if (error == HA_ERR_KEY_NOT_FOUND || error == HA_ERR_END_OF_FILE)
359
 
                {
360
 
                  return HA_ERR_KEY_NOT_FOUND;        // No rows matching WHERE
361
 
                }
362
 
                /* HA_ERR_LOCK_DEADLOCK or some other error */
363
 
                table->print_error(error, MYF(0));
364
 
                return error;
365
 
              }
366
 
              removed_tables|= table->map;
367
 
            }
368
 
            else if (! expr->const_item() || ! is_exact_count)
369
 
            {
370
 
              /*
371
 
                 The optimization is not applicable in both cases:
372
 
                 (a) 'expr' is a non-constant expression. Then we can't
373
 
                 replace 'expr' by a constant.
374
 
                 (b) 'expr' is a costant. According to ANSI, MIN/MAX must return
375
 
                 NULL if the query does not return any rows. Thus, if we are not
376
 
                 able to determine if the query returns any rows, we can't apply
377
 
                 the optimization and replace MIN/MAX with a constant.
378
 
               */
379
 
              const_result= 0;
380
 
              break;
381
 
            }
382
 
            if (! count)
383
 
            {
384
 
              /* If count == 0, then we know that is_exact_count == true. */
385
 
              ((Item_sum_min*) item_sum)->clear(); /* Set to NULL. */
386
 
            }
387
 
            else
388
 
            {
389
 
              ((Item_sum_min*) item_sum)->reset(); /* Set to the constant value. */
390
 
            }
391
 
            ((Item_sum_min*) item_sum)->make_const();
392
 
            recalc_const_item= 1;
393
 
            break;
394
 
          }
395
 
        case Item_sum::MAX_FUNC:
396
 
          {
397
 
            /*
398
 
               If MAX(expr) is the first part of a key or if all previous
399
 
               parts of the key is found in the COND, then we can use
400
 
               indexes to find the key.
401
 
             */
402
 
            Item *expr= item_sum->args[0];
403
 
            if (expr->real_item()->type() == Item::FIELD_ITEM)
404
 
            {
405
 
              unsigned char key_buff[MAX_KEY_LENGTH];
406
 
              table_reference_st ref;
407
 
              uint32_t range_fl, prefix_len;
408
 
 
409
 
              ref.key_buff= key_buff;
410
 
              Item_field *item_field= (Item_field*) (expr->real_item());
411
 
              Table *table= item_field->field->getTable();
412
 
 
413
 
              /*
414
 
                 Look for a partial key that can be used for optimization.
415
 
                 If we succeed, ref.key_length will contain the length of
416
 
                 this key, while prefix_len will contain the length of
417
 
                 the beginning of this key without field used in MAX().
418
 
                 Type of range for the key part for this field will be
419
 
                 returned in range_fl.
420
 
               */
421
 
              if (table->cursor->inited ||
422
 
                  (outer_tables & table->map) ||
423
 
                  ! find_key_for_maxmin(1,
424
 
                                        &ref,
425
 
                                        item_field->field,
426
 
                                        conds,
427
 
                                        &range_fl,
428
 
                                        &prefix_len))
429
 
              {
430
 
                const_result= 0;
431
 
                break;
432
 
              }
433
 
              error= table->cursor->startIndexScan(static_cast<uint32_t>(ref.key), 1);
434
 
 
435
 
              if (! ref.key_length)
436
 
              {
437
 
                error= table->cursor->index_last(table->record[0]);
438
 
              }
439
 
              else
440
 
              {
441
 
                error= table->cursor->index_read_map(table->record[0],
442
 
                                                     key_buff,
443
 
                                                     make_prev_keypart_map(ref.key_parts),
444
 
                                                     range_fl & NEAR_MAX ?
445
 
                                                     HA_READ_BEFORE_KEY :
446
 
                                                     HA_READ_PREFIX_LAST_OR_PREV);
447
 
              }
448
 
              if (! error &&
449
 
                  reckey_in_range(1,
450
 
                                  &ref,
451
 
                                  item_field->field,
452
 
                                  conds,
453
 
                                  range_fl,
454
 
                                  prefix_len))
455
 
              {
456
 
                error= HA_ERR_KEY_NOT_FOUND;
457
 
              }
458
 
              if (table->key_read)
459
 
              {
460
 
                table->key_read= 0;
461
 
                table->cursor->extra(HA_EXTRA_NO_KEYREAD);
462
 
              }
463
 
              table->cursor->endIndexScan();
464
 
              if (error)
465
 
              {
466
 
                if (error == HA_ERR_KEY_NOT_FOUND || error == HA_ERR_END_OF_FILE)
467
 
                {
468
 
                  return HA_ERR_KEY_NOT_FOUND;       // No rows matching WHERE
469
 
                }
470
 
                /* HA_ERR_LOCK_DEADLOCK or some other error */
471
 
                table->print_error(error, MYF(ME_FATALERROR));
472
 
                return error;
473
 
              }
474
 
              removed_tables|= table->map;
475
 
            }
476
 
            else if (! expr->const_item() || ! is_exact_count)
477
 
            {
478
 
              /*
479
 
                 The optimization is not applicable in both cases:
480
 
                 (a) 'expr' is a non-constant expression. Then we can't
481
 
                 replace 'expr' by a constant.
482
 
                 (b) 'expr' is a costant. According to ANSI, MIN/MAX must return
483
 
                 NULL if the query does not return any rows. Thus, if we are not
484
 
                 able to determine if the query returns any rows, we can't apply
485
 
                 the optimization and replace MIN/MAX with a constant.
486
 
               */
487
 
              const_result= 0;
488
 
              break;
489
 
            }
490
 
            if (! count)
491
 
            {
492
 
              /* If count != 1, then we know that is_exact_count == true. */
493
 
              ((Item_sum_max*) item_sum)->clear(); /* Set to NULL. */
494
 
            }
495
 
            else
496
 
            {
497
 
              ((Item_sum_max*) item_sum)->reset(); /* Set to the constant value. */
498
 
            }
499
 
            ((Item_sum_max*) item_sum)->make_const();
500
 
            recalc_const_item= 1;
501
 
            break;
502
 
          }
503
 
        default:
 
406
            error= table->file->index_read_map(table->record[0], key_buff,
 
407
                                               make_prev_keypart_map(ref.key_parts),
 
408
                                               range_fl & NEAR_MAX ?
 
409
                                               HA_READ_BEFORE_KEY :
 
410
                                               HA_READ_PREFIX_LAST_OR_PREV);
 
411
          if (!error && reckey_in_range(1, &ref, item_field->field,
 
412
                                        conds, range_fl, prefix_len))
 
413
            error= HA_ERR_KEY_NOT_FOUND;
 
414
          if (table->key_read)
 
415
          {
 
416
            table->key_read=0;
 
417
            table->file->extra(HA_EXTRA_NO_KEYREAD);
 
418
          }
 
419
          table->file->ha_index_end();
 
420
          if (error)
 
421
          {
 
422
            if (error == HA_ERR_KEY_NOT_FOUND || error == HA_ERR_END_OF_FILE)
 
423
              return HA_ERR_KEY_NOT_FOUND;           // No rows matching WHERE
 
424
            /* HA_ERR_LOCK_DEADLOCK or some other error */
 
425
            table->file->print_error(error, MYF(ME_FATALERROR));
 
426
            return(error);
 
427
          }
 
428
          removed_tables|= table->map;
 
429
        }
 
430
        else if (!expr->const_item() || !is_exact_count)
 
431
        {
 
432
          /*
 
433
            The optimization is not applicable in both cases:
 
434
            (a) 'expr' is a non-constant expression. Then we can't
 
435
            replace 'expr' by a constant.
 
436
            (b) 'expr' is a costant. According to ANSI, MIN/MAX must return
 
437
            NULL if the query does not return any rows. Thus, if we are not
 
438
            able to determine if the query returns any rows, we can't apply
 
439
            the optimization and replace MIN/MAX with a constant.
 
440
          */
504
441
          const_result= 0;
505
442
          break;
 
443
        }
 
444
        if (!count)
 
445
        {
 
446
          /* If count != 1, then we know that is_exact_count == true. */
 
447
          ((Item_sum_max*) item_sum)->clear(); /* Set to NULL. */
 
448
        }
 
449
        else
 
450
          ((Item_sum_max*) item_sum)->reset(); /* Set to the constant value. */
 
451
        ((Item_sum_max*) item_sum)->make_const();
 
452
        recalc_const_item= 1;
 
453
        break;
 
454
      }
 
455
      default:
 
456
        const_result= 0;
 
457
        break;
506
458
      }
507
459
    }
508
460
    else if (const_result)
509
461
    {
510
462
      if (recalc_const_item)
511
 
      {
512
463
        item->update_used_tables();
513
 
      }
514
 
      if (! item->const_item())
515
 
      {
 
464
      if (!item->const_item())
516
465
        const_result= 0;
517
 
      }
518
466
    }
519
467
  }
520
468
  /*
521
 
     If we have a where clause, we can only ignore searching in the
522
 
     tables if MIN/MAX optimisation replaced all used tables
523
 
     We do not use replaced values in case of:
524
 
     SELECT MIN(key) FROM table_1, empty_table
525
 
     removed_tables is != 0 if we have used MIN() or MAX().
526
 
   */
 
469
    If we have a where clause, we can only ignore searching in the
 
470
    tables if MIN/MAX optimisation replaced all used tables
 
471
    We do not use replaced values in case of:
 
472
    SELECT MIN(key) FROM table_1, empty_table
 
473
    removed_tables is != 0 if we have used MIN() or MAX().
 
474
  */
527
475
  if (removed_tables && used_tables != removed_tables)
528
 
  {
529
476
    const_result= 0;                            // We didn't remove all tables
530
 
  }
531
477
  return const_result;
532
478
}
533
479
 
534
480
 
535
 
bool optimizer::simple_pred(Item_func *func_item, Item **args, bool &inv_order)
 
481
/**
 
482
  Test if the predicate compares a field with constants.
 
483
 
 
484
  @param func_item        Predicate item
 
485
  @param[out] args        Here we store the field followed by constants
 
486
  @param[out] inv_order   Is set to 1 if the predicate is of the form
 
487
                          'const op field'
 
488
 
 
489
  @retval
 
490
    0        func_item is a simple predicate: a field is compared with
 
491
    constants
 
492
  @retval
 
493
    1        Otherwise
 
494
*/
 
495
 
 
496
bool simple_pred(Item_func *func_item, Item **args, bool *inv_order)
536
497
{
537
 
  Item *item= NULL;
538
 
  inv_order= false;
539
 
  switch (func_item->argument_count())
540
 
  {
 
498
  Item *item;
 
499
  *inv_order= 0;
 
500
  switch (func_item->argument_count()) {
541
501
  case 0:
542
502
    /* MULT_EQUAL_FUNC */
543
503
    {
545
505
      Item_equal_iterator it(*item_equal);
546
506
      args[0]= it++;
547
507
      if (it++)
548
 
      {
549
 
        return 0;
550
 
      }
551
 
      if (! (args[1]= item_equal->get_const()))
552
 
      {
553
 
        return 0;
554
 
      }
 
508
        return 0;
 
509
      if (!(args[1]= item_equal->get_const()))
 
510
        return 0;
555
511
    }
556
512
    break;
557
513
  case 1:
558
514
    /* field IS NULL */
559
515
    item= func_item->arguments()[0];
560
516
    if (item->type() != Item::FIELD_ITEM)
561
 
    {
562
517
      return 0;
563
 
    }
564
518
    args[0]= item;
565
519
    break;
566
520
  case 2:
570
524
    {
571
525
      args[0]= item;
572
526
      item= func_item->arguments()[1];
573
 
      if (! item->const_item())
574
 
      {
 
527
      if (!item->const_item())
575
528
        return 0;
576
 
      }
577
529
      args[1]= item;
578
530
    }
579
531
    else if (item->const_item())
581
533
      args[1]= item;
582
534
      item= func_item->arguments()[1];
583
535
      if (item->type() != Item::FIELD_ITEM)
584
 
      {
585
536
        return 0;
586
 
      }
587
537
      args[0]= item;
588
 
      inv_order= true;
 
538
      *inv_order= 1;
589
539
    }
590
540
    else
591
 
    {
592
541
      return 0;
593
 
    }
594
542
    break;
595
543
  case 3:
596
544
    /* field BETWEEN const AND const */
601
549
      for (int i= 1 ; i <= 2; i++)
602
550
      {
603
551
        item= func_item->arguments()[i];
604
 
        if (! item->const_item())
605
 
        {
 
552
        if (!item->const_item())
606
553
          return 0;
607
 
        }
608
554
        args[i]= item;
609
555
      }
610
556
    }
611
557
    else
612
 
    {
613
558
      return 0;
614
 
    }
615
559
  }
616
560
  return 1;
617
561
}
646
590
  @retval
647
591
    1        We can use index to get MIN/MAX value
648
592
*/
649
 
static bool matching_cond(bool max_fl,
650
 
                          table_reference_st *ref,
651
 
                          KeyInfo *keyinfo,
652
 
                          KeyPartInfo *field_part,
653
 
                          COND *cond,
654
 
                          key_part_map *key_part_used,
655
 
                          uint32_t *range_fl,
 
593
 
 
594
static bool matching_cond(bool max_fl, TABLE_REF *ref, KEY *keyinfo, 
 
595
                          KEY_PART_INFO *field_part, COND *cond,
 
596
                          key_part_map *key_part_used, uint32_t *range_fl,
656
597
                          uint32_t *prefix_len)
657
598
{
658
 
  if (! cond)
659
 
  {
 
599
  if (!cond)
660
600
    return 1;
661
 
  }
662
601
  Field *field= field_part->field;
663
 
 
664
 
  field->setWriteSet();
665
 
 
666
 
  if (! (cond->used_tables() & field->getTable()->map))
 
602
  if (!(cond->used_tables() & field->table->map))
667
603
  {
668
604
    /* Condition doesn't restrict the used table */
669
605
    return 1;
671
607
  if (cond->type() == Item::COND_ITEM)
672
608
  {
673
609
    if (((Item_cond*) cond)->functype() == Item_func::COND_OR_FUNC)
674
 
    {
675
610
      return 0;
676
 
    }
677
611
 
678
612
    /* AND */
679
613
    List_iterator_fast<Item> li(*((Item_cond*) cond)->argument_list());
680
614
    Item *item;
681
615
    while ((item= li++))
682
616
    {
683
 
      if (! matching_cond(max_fl,
684
 
                          ref,
685
 
                          keyinfo,
686
 
                          field_part,
687
 
                          item,
688
 
                          key_part_used,
689
 
                          range_fl,
690
 
                          prefix_len))
691
 
      {
 
617
      if (!matching_cond(max_fl, ref, keyinfo, field_part, item,
 
618
                         key_part_used, range_fl, prefix_len))
692
619
        return 0;
693
 
      }
694
620
    }
695
621
    return 1;
696
622
  }
697
623
 
698
624
  if (cond->type() != Item::FUNC_ITEM)
699
 
  {
700
 
    return 0; // Not operator, can't optimize
701
 
  }
702
 
 
703
 
  bool eq_type= false; // =, <=> or IS NULL
704
 
  bool noeq_type= false; // < or >
705
 
  bool less_fl= false; // < or <=
706
 
  bool is_null= false;
707
 
  bool between= false;
708
 
 
709
 
  switch (((Item_func*) cond)->functype())
710
 
  {
 
625
    return 0;                                 // Not operator, can't optimize
 
626
 
 
627
  bool eq_type= 0;                            // =, <=> or IS NULL
 
628
  bool noeq_type= 0;                          // < or >  
 
629
  bool less_fl= 0;                            // < or <= 
 
630
  bool is_null= 0;
 
631
  bool between= 0;
 
632
 
 
633
  switch (((Item_func*) cond)->functype()) {
711
634
  case Item_func::ISNULL_FUNC:
712
635
    is_null= 1;     /* fall through */
713
636
  case Item_func::EQ_FUNC:
717
640
  case Item_func::LT_FUNC:
718
641
    noeq_type= 1;   /* fall through */
719
642
  case Item_func::LE_FUNC:
720
 
    less_fl= 1;
 
643
    less_fl= 1;      
721
644
    break;
722
645
  case Item_func::GT_FUNC:
723
646
    noeq_type= 1;   /* fall through */
730
653
    eq_type= 1;
731
654
    break;
732
655
  default:
733
 
    return 0; // Can't optimize function
 
656
    return 0;                                        // Can't optimize function
734
657
  }
735
 
 
 
658
  
736
659
  Item *args[3];
737
660
  bool inv;
738
661
 
739
662
  /* Test if this is a comparison of a field and constant */
740
 
  if (! optimizer::simple_pred((Item_func*) cond, args, inv))
741
 
  {
 
663
  if (!simple_pred((Item_func*) cond, args, &inv))
742
664
    return 0;
743
 
  }
744
665
 
745
 
  if (inv && ! eq_type)
746
 
  {
747
 
    less_fl= 1 - less_fl; // Convert '<' -> '>' (etc)
748
 
  }
 
666
  if (inv && !eq_type)
 
667
    less_fl= 1-less_fl;                         // Convert '<' -> '>' (etc)
749
668
 
750
669
  /* Check if field is part of the tested partial key */
751
670
  unsigned char *key_ptr= ref->key_buff;
752
 
  KeyPartInfo *part= NULL;
 
671
  KEY_PART_INFO *part;
753
672
  for (part= keyinfo->key_part; ; key_ptr+= part++->store_length)
754
673
 
755
674
  {
756
675
    if (part > field_part)
757
 
    {
758
676
      return 0;                     // Field is beyond the tested parts
759
 
    }
760
677
    if (part->field->eq(((Item_field*) args[0])->field))
761
 
    {
762
678
      break;                        // Found a part of the key for the field
763
 
    }
764
679
  }
765
680
 
766
681
  bool is_field_part= part == field_part;
767
 
  if (! (is_field_part || eq_type))
768
 
  {
 
682
  if (!(is_field_part || eq_type))
769
683
    return 0;
770
 
  }
771
684
 
772
685
  key_part_map org_key_part_used= *key_part_used;
773
686
  if (eq_type || between || max_fl == less_fl)
776
689
    if (ref->key_length < length)
777
690
    {
778
691
    /* Ultimately ref->key_length will contain the length of the search key */
779
 
      ref->key_length= length;
 
692
      ref->key_length= length;      
780
693
      ref->key_parts= (part - keyinfo->key_part) + 1;
781
694
    }
782
 
    if (! *prefix_len && part + 1 == field_part)
783
 
    {
 
695
    if (!*prefix_len && part+1 == field_part)       
784
696
      *prefix_len= length;
785
 
    }
786
697
    if (is_field_part && eq_type)
787
 
    {
788
698
      *prefix_len= ref->key_length;
789
 
    }
790
 
 
 
699
  
791
700
    *key_part_used|= (key_part_map) 1 << (part - keyinfo->key_part);
792
701
  }
793
702
 
794
703
  if (org_key_part_used != *key_part_used ||
795
 
      (is_field_part &&
796
 
       (between || eq_type || max_fl == less_fl) && ! cond->val_int()))
 
704
      (is_field_part && 
 
705
       (between || eq_type || max_fl == less_fl) && !cond->val_int()))
797
706
  {
798
707
    /*
799
708
      It's the first predicate for this part or a predicate of the
800
709
      following form  that moves upper/lower bounds for max/min values:
801
710
      - field BETWEEN const AND const
802
 
      - field = const
 
711
      - field = const 
803
712
      - field {<|<=} const, when searching for MAX
804
713
      - field {>|>=} const, when searching for MIN
805
714
    */
813
722
    {
814
723
      store_val_in_field(part->field, args[between && max_fl ? 2 : 1],
815
724
                         CHECK_FIELD_IGNORE);
816
 
      if (part->null_bit)
817
 
      {
 
725
      if (part->null_bit) 
818
726
        *key_ptr++= (unsigned char) test(part->field->is_null());
819
 
      }
820
 
      part->field->get_key_image(key_ptr, part->length);
 
727
      part->field->get_key_image(key_ptr, part->length, Field::itRAW);
821
728
    }
822
729
    if (is_field_part)
823
730
    {
824
731
      if (between || eq_type)
825
 
      {
826
732
        *range_fl&= ~(NO_MAX_RANGE | NO_MIN_RANGE);
827
 
      }
828
733
      else
829
734
      {
830
735
        *range_fl&= ~(max_fl ? NO_MAX_RANGE : NO_MIN_RANGE);
831
736
        if (noeq_type)
832
 
        {
833
737
          *range_fl|=  (max_fl ? NEAR_MAX : NEAR_MIN);
834
 
        }
835
738
        else
836
 
        {
837
739
          *range_fl&= ~(max_fl ? NEAR_MAX : NEAR_MIN);
838
 
        }
839
740
      }
840
741
    }
841
742
  }
842
743
  else if (eq_type)
843
744
  {
844
 
    if ((! is_null && !cond->val_int()) ||
 
745
    if ((!is_null && !cond->val_int()) ||
845
746
        (is_null && !test(part->field->is_null())))
846
 
    {
847
747
     return 0;                       // Impossible test
848
 
    }
849
748
  }
850
749
  else if (is_field_part)
851
 
  {
852
750
    *range_fl&= ~(max_fl ? NO_MIN_RANGE : NO_MAX_RANGE);
853
 
  }
854
 
  return 1;
 
751
  return 1;  
855
752
}
856
753
 
857
754
 
865
762
     -# for each previous component f_i there is one and only one conjunct
866
763
        of the form: f_i= const_i or const_i= f_i or f_i is null
867
764
     -# references to field occur only in conjucts of the form:
868
 
        field {<|<=|>=|>|=} const or const {<|<=|>=|>|=} field or
 
765
        field {<|<=|>=|>|=} const or const {<|<=|>=|>|=} field or 
869
766
        field BETWEEN const1 AND const2
870
767
     -# all references to the columns from the same table as column field
871
768
        occur only in conjucts mentioned above.
896
793
    1   Can use key to optimize MIN()/MAX().
897
794
    In this case ref, range_fl and prefix_len are updated
898
795
*/
899
 
static bool find_key_for_maxmin(bool max_fl,
900
 
                                table_reference_st *ref,
901
 
                                Field* field,
902
 
                                COND *cond,
903
 
                                uint32_t *range_fl,
904
 
                                uint32_t *prefix_len)
 
796
 
 
797
      
 
798
static bool find_key_for_maxmin(bool max_fl, TABLE_REF *ref,
 
799
                                Field* field, COND *cond,
 
800
                                uint32_t *range_fl, uint32_t *prefix_len)
905
801
{
906
 
  if (! (field->flags & PART_KEY_FLAG))
907
 
  {
908
 
    return 0; // Not key field
909
 
  }
 
802
  if (!(field->flags & PART_KEY_FLAG))
 
803
    return 0;                                        // Not key field
910
804
 
911
 
  Table *table= field->getTable();
 
805
  Table *table= field->table;
912
806
  uint32_t idx= 0;
913
807
 
914
 
  KeyInfo *keyinfo,*keyinfo_end= NULL;
915
 
  for (keyinfo= table->key_info, keyinfo_end= keyinfo+table->getShare()->sizeKeys();
 
808
  KEY *keyinfo,*keyinfo_end;
 
809
  for (keyinfo= table->key_info, keyinfo_end= keyinfo+table->s->keys ;
916
810
       keyinfo != keyinfo_end;
917
811
       keyinfo++,idx++)
918
812
  {
919
 
    KeyPartInfo *part= NULL;
920
 
    KeyPartInfo *part_end= NULL;
 
813
    KEY_PART_INFO *part,*part_end;
921
814
    key_part_map key_part_to_use= 0;
922
815
    /*
923
816
      Perform a check if index is not disabled by ALTER Table
924
817
      or IGNORE INDEX.
925
818
    */
926
 
    if (! table->keys_in_use_for_query.test(idx))
927
 
    {
 
819
    if (!table->keys_in_use_for_query.is_set(idx))
928
820
      continue;
929
 
    }
930
821
    uint32_t jdx= 0;
931
822
    *prefix_len= 0;
932
 
    for (part= keyinfo->key_part, part_end= part+keyinfo->key_parts;
933
 
         part != part_end;
 
823
    for (part= keyinfo->key_part, part_end= part+keyinfo->key_parts ;
 
824
         part != part_end ;
934
825
         part++, jdx++, key_part_to_use= (key_part_to_use << 1) | 1)
935
826
    {
936
 
      if (! (table->index_flags(idx) & HA_READ_ORDER))
937
 
      {
 
827
      if (!(table->file->index_flags(idx, jdx, 0) & HA_READ_ORDER))
938
828
        return 0;
939
 
      }
940
829
 
941
830
      /* Check whether the index component is partial */
942
 
      Field *part_field= table->getField(part->fieldnr-1);
943
 
      part_field->setWriteSet();
944
 
 
 
831
      Field *part_field= table->field[part->fieldnr-1];
945
832
      if ((part_field->flags & BLOB_FLAG) ||
946
833
          part->length < part_field->key_length())
947
 
      {
948
834
        break;
949
 
      }
950
835
 
951
836
      if (field->eq(part->field))
952
837
      {
955
840
        ref->key_parts= 0;
956
841
        key_part_map key_part_used= 0;
957
842
        *range_fl= NO_MIN_RANGE | NO_MAX_RANGE;
958
 
        if (matching_cond(max_fl,
959
 
                          ref,
960
 
                          keyinfo,
961
 
                          part,
962
 
                          cond,
963
 
                          &key_part_used,
964
 
                          range_fl,
965
 
                          prefix_len) &&
966
 
            ! (key_part_to_use & ~key_part_used))
 
843
        if (matching_cond(max_fl, ref, keyinfo, part, cond,
 
844
                          &key_part_used, range_fl, prefix_len) &&
 
845
            !(key_part_to_use & ~key_part_used))
967
846
        {
968
 
          if (! max_fl && key_part_used == key_part_to_use && part->null_bit)
 
847
          if (!max_fl && key_part_used == key_part_to_use && part->null_bit)
969
848
          {
970
849
            /*
971
850
              The query is on this form:
972
851
 
973
 
              SELECT MIN(key_part_k)
974
 
              FROM t1
 
852
              SELECT MIN(key_part_k) 
 
853
              FROM t1 
975
854
              WHERE key_part_1 = const and ... and key_part_k-1 = const
976
855
 
977
856
              If key_part_k is nullable, we want to find the first matching row
993
872
            The following test is false when the key in the key tree is
994
873
            converted (for example to upper case)
995
874
          */
996
 
          if (field->part_of_key.test(idx))
 
875
          if (field->part_of_key.is_set(idx))
997
876
          {
998
877
            table->key_read= 1;
999
 
            table->cursor->extra(HA_EXTRA_KEYREAD);
 
878
            table->file->extra(HA_EXTRA_KEYREAD);
1000
879
          }
1001
880
          return 1;
1002
881
        }
1022
901
  @retval
1023
902
    1        WHERE was not true for the found row
1024
903
*/
1025
 
static int reckey_in_range(bool max_fl,
1026
 
                           table_reference_st *ref,
1027
 
                           Field* field,
1028
 
                           COND *cond,
1029
 
                           uint32_t range_fl,
1030
 
                           uint32_t prefix_len)
 
904
 
 
905
static int reckey_in_range(bool max_fl, TABLE_REF *ref, Field* field,
 
906
                            COND *cond, uint32_t range_fl, uint32_t prefix_len)
1031
907
{
1032
 
  if (key_cmp_if_same(field->getTable(), ref->key_buff, ref->key, prefix_len))
1033
 
  {
 
908
  if (key_cmp_if_same(field->table, ref->key_buff, ref->key, prefix_len))
1034
909
    return 1;
1035
 
  }
1036
 
  if (! cond || (range_fl & (max_fl ? NO_MIN_RANGE : NO_MAX_RANGE)))
1037
 
  {
 
910
  if (!cond || (range_fl & (max_fl ? NO_MIN_RANGE : NO_MAX_RANGE)))
1038
911
    return 0;
1039
 
  }
1040
912
  return maxmin_in_range(max_fl, field, cond);
1041
913
}
1042
914
 
1053
925
  @retval
1054
926
    1        WHERE was not true for the found row
1055
927
*/
 
928
 
1056
929
static int maxmin_in_range(bool max_fl, Field* field, COND *cond)
1057
930
{
1058
931
  /* If AND/OR condition */
1063
936
    while ((item= li++))
1064
937
    {
1065
938
      if (maxmin_in_range(max_fl, field, item))
1066
 
      {
1067
939
        return 1;
1068
 
      }
1069
940
    }
1070
941
    return 0;
1071
942
  }
1072
943
 
1073
 
  if (cond->used_tables() != field->getTable()->map)
1074
 
  {
 
944
  if (cond->used_tables() != field->table->map)
1075
945
    return 0;
1076
 
  }
1077
 
  bool less_fl= false;
1078
 
  switch (((Item_func*) cond)->functype())
1079
 
  {
 
946
  bool less_fl= 0;
 
947
  switch (((Item_func*) cond)->functype()) {
1080
948
  case Item_func::BETWEEN:
1081
949
    return cond->val_int() == 0;                // Return 1 if WHERE is false
1082
950
  case Item_func::LT_FUNC:
1087
955
  {
1088
956
    Item *item= ((Item_func*) cond)->arguments()[1];
1089
957
    /* In case of 'const op item' we have to swap the operator */
1090
 
    if (! item->const_item())
1091
 
    {
 
958
    if (!item->const_item())
1092
959
      less_fl= 1-less_fl;
1093
 
    }
1094
960
    /*
1095
961
      We only have to check the expression if we are using an expression like
1096
962
      SELECT MAX(b) FROM t1 WHERE a=const AND b>const
1098
964
      SELECT MAX(b) FROM t1 WHERE a=const AND b<const
1099
965
    */
1100
966
    if (max_fl != less_fl)
1101
 
    {
1102
967
      return cond->val_int() == 0;                // Return 1 if WHERE is false
1103
 
    }
1104
968
    return 0;
1105
969
  }
1106
970
  case Item_func::EQ_FUNC:
1113
977
  return 0;
1114
978
}
1115
979
 
1116
 
} /* namespace drizzled */
1117