MySQL 5.6.14 Source Code Document
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
opt_sum.cc
Go to the documentation of this file.
1 /* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
15 
16 
50 #include "sql_priv.h"
51 #include "key.h" // key_cmp_if_same
52 #include "sql_select.h"
53 
54 static bool find_key_for_maxmin(bool max_fl, TABLE_REF *ref, Field* field,
55  Item *cond, uint *range_fl,
56  uint *key_prefix_length);
57 static int reckey_in_range(bool max_fl, TABLE_REF *ref, Field* field,
58  Item *cond, uint range_fl, uint prefix_len);
59 static int maxmin_in_range(bool max_fl, Field* field, Item *cond);
60 
61 
62 /*
63  Get exact count of rows in all tables
64 
65  SYNOPSIS
66  get_exact_records()
67  tables List of tables
68 
69  NOTES
70  When this is called, we know all table handlers supports HA_HAS_RECORDS
71  or HA_STATS_RECORDS_IS_EXACT
72 
73  RETURN
74  ULONGLONG_MAX Error: Could not calculate number of rows
75  # Multiplication of number of rows in all tables
76 */
77 
78 static ulonglong get_exact_record_count(TABLE_LIST *tables)
79 {
80  ulonglong count= 1;
81  for (TABLE_LIST *tl= tables; tl; tl= tl->next_leaf)
82  {
83  ha_rows tmp= tl->table->file->records();
84  if (tmp == HA_POS_ERROR)
85  return ULONGLONG_MAX;
86  count*= tmp;
87  }
88  return count;
89 }
90 
91 
106 static int get_index_min_value(TABLE *table, TABLE_REF *ref,
107  Item_field *item_field, uint range_fl,
108  uint prefix_len)
109 {
110  int error;
111 
112  if (!ref->key_length)
113  error= table->file->ha_index_first(table->record[0]);
114  else
115  {
116  /*
117  Use index to replace MIN/MAX functions with their values
118  according to the following rules:
119 
120  1) Insert the minimum non-null values where the WHERE clause still
121  matches, or
122  2) a NULL value if there are only NULL values for key_part_k.
123  3) Fail, producing a row of nulls
124 
125  Implementation: Read the smallest value using the search key. If
126  the interval is open, read the next value after the search
127  key. If read fails, and we're looking for a MIN() value for a
128  nullable column, test if there is an exact match for the key.
129  */
130  if (!(range_fl & NEAR_MIN))
131  /*
132  Closed interval: Either The MIN argument is non-nullable, or
133  we have a >= predicate for the MIN argument.
134  */
135  error= table->file->ha_index_read_map(table->record[0],
136  ref->key_buff,
137  make_prev_keypart_map(ref->key_parts),
138  HA_READ_KEY_OR_NEXT);
139  else
140  {
141  /*
142  Open interval: There are two cases:
143  1) We have only MIN() and the argument column is nullable, or
144  2) there is a > predicate on it, nullability is irrelevant.
145  We need to scan the next bigger record first.
146  Open interval is not used if the search key involves the last keypart,
147  and it would not work.
148  */
149  DBUG_ASSERT(prefix_len < ref->key_length);
150  error= table->file->ha_index_read_map(table->record[0],
151  ref->key_buff,
152  make_prev_keypart_map(ref->key_parts),
153  HA_READ_AFTER_KEY);
154  /*
155  If the found record is outside the group formed by the search
156  prefix, or there is no such record at all, check if all
157  records in that group have NULL in the MIN argument
158  column. If that is the case return that NULL.
159 
160  Check if case 1 from above holds. If it does, we should read
161  the skipped tuple.
162  */
163  if (item_field->field->real_maybe_null() &&
164  ref->key_buff[prefix_len] == 1 &&
165  /*
166  Last keypart (i.e. the argument to MIN) is set to NULL by
167  find_key_for_maxmin only if all other keyparts are bound
168  to constants in a conjunction of equalities. Hence, we
169  can detect this by checking only if the last keypart is
170  NULL.
171  */
172  (error == HA_ERR_KEY_NOT_FOUND ||
173  key_cmp_if_same(table, ref->key_buff, ref->key, prefix_len)))
174  {
175  DBUG_ASSERT(item_field->field->real_maybe_null());
176  error= table->file->ha_index_read_map(table->record[0],
177  ref->key_buff,
178  make_prev_keypart_map(ref->key_parts),
179  HA_READ_KEY_EXACT);
180  }
181  }
182  }
183  return error;
184 }
185 
186 
199 static int get_index_max_value(TABLE *table, TABLE_REF *ref, uint range_fl)
200 {
201  return (ref->key_length ?
202  table->file->ha_index_read_map(table->record[0], ref->key_buff,
203  make_prev_keypart_map(ref->key_parts),
204  range_fl & NEAR_MAX ?
205  HA_READ_BEFORE_KEY :
206  HA_READ_PREFIX_LAST_OR_PREV) :
207  table->file->ha_index_last(table->record[0]));
208 }
209 
210 
211 
237 int opt_sum_query(THD *thd,
238  TABLE_LIST *tables, List<Item> &all_fields, Item *conds)
239 {
240  List_iterator_fast<Item> it(all_fields);
241  int const_result= 1;
242  bool recalc_const_item= false;
243  ulonglong count= 1;
244  bool is_exact_count= TRUE, maybe_exact_count= TRUE;
245  table_map removed_tables= 0, outer_tables= 0, used_tables= 0;
246  Item *item;
247  int error;
248 
249  DBUG_ENTER("opt_sum_query");
250 
251  const table_map where_tables= conds ? conds->used_tables() : 0;
252  /*
253  opt_sum_query() happens at optimization. A subquery is optimized once but
254  executed possibly multiple times.
255  If the value of the set function depends on the join's emptiness (like
256  MIN() does), and the join's emptiness depends on the outer row, we cannot
257  mark the set function as constant:
258  */
259  if (where_tables & OUTER_REF_TABLE_BIT)
260  DBUG_RETURN(0);
261 
262  /*
263  Analyze outer join dependencies, and, if possible, compute the number
264  of returned rows.
265  */
266  for (TABLE_LIST *tl= tables; tl; tl= tl->next_leaf)
267  {
268  if (tl->join_cond() || tl->outer_join_nest())
269  /* Don't replace expression on a table that is part of an outer join */
270  {
271  outer_tables|= tl->table->map;
272 
273  /*
274  We can't optimise LEFT JOIN in cases where the WHERE condition
275  restricts the table that is used, like in:
276  SELECT MAX(t1.a) FROM t1 LEFT JOIN t2 join-condition
277  WHERE t2.field IS NULL;
278  */
279  if (tl->table->map & where_tables)
280  DBUG_RETURN(0);
281  }
282  else
283  used_tables|= tl->table->map;
284 
285  /*
286  If the storage manager of 'tl' gives exact row count as part of
287  statistics (cheap), compute the total number of rows. If there are
288  no outer table dependencies, this count may be used as the real count.
289  Schema tables are filled after this function is invoked, so we can't
290  get row count.
291  Derived tables aren't filled yet, their number of rows are estimates.
292  */
293  bool table_filled= !(tl->schema_table || tl->uses_materialization());
294  if ((tl->table->file->ha_table_flags() & HA_STATS_RECORDS_IS_EXACT) &&
295  table_filled)
296  {
297  error= tl->fetch_number_of_rows();
298  if(error)
299  {
300  tl->table->file->print_error(error, MYF(ME_FATALERROR));
301  DBUG_RETURN(error);
302  }
303  count*= tl->table->file->stats.records;
304  }
305  else
306  {
307  maybe_exact_count&= test(table_filled &&
308  (tl->table->file->ha_table_flags() &
309  HA_HAS_RECORDS));
310  is_exact_count= FALSE;
311  count= 1; // ensure count != 0
312  }
313  }
314 
315  /*
316  Iterate through all items in the SELECT clause and replace
317  COUNT(), MIN() and MAX() with constants (if possible).
318  */
319 
320  while ((item= it++))
321  {
322  if (item->type() == Item::SUM_FUNC_ITEM)
323  {
324  Item_sum *item_sum= (((Item_sum*) item));
325  switch (item_sum->sum_func()) {
326  case Item_sum::COUNT_FUNC:
327  /*
328  If the expr in COUNT(expr) can never be null we can change this
329  to the number of rows in the tables if this number is exact and
330  there are no outer joins.
331  */
332  if (!conds && !((Item_sum_count*) item)->get_arg(0)->maybe_null &&
333  !outer_tables && maybe_exact_count)
334  {
335  if (!is_exact_count)
336  {
337  if ((count= get_exact_record_count(tables)) == ULONGLONG_MAX)
338  {
339  /* Error from handler in counting rows. Don't optimize count() */
340  const_result= 0;
341  continue;
342  }
343  is_exact_count= 1; // count is now exact
344  }
345  }
346  /* For result count of full-text search: If
347  1. it is a single table query,
348  2. the WHERE condition is a single MATCH expresssion,
349  3. the table engine can provide the row count from FTS result, and
350  4. the expr in COUNT(expr) can not be NULL,
351  we do the full-text search now, and replace with the actual count.
352 
353  Note: Item_func_match::init_search() will be called again
354  later in the optimization phase by init_fts_funcs(),
355  but search will still only be done once.
356  */
357  else if (tables->next_leaf == NULL && // 1
358  conds && conds->type() == Item::FUNC_ITEM &&
359  ((Item_func*)conds)->functype() == Item_func::FT_FUNC && // 2
360  (tables->table->file->ha_table_flags() &
361  HA_CAN_FULLTEXT_EXT) && // 3
362  !((Item_sum_count*) item)->get_arg(0)->maybe_null) // 4
363  {
364  Item_func_match* fts_item= static_cast<Item_func_match*>(conds);
365  fts_item->init_search(true);
366  if (thd->is_error())
367  break;
368  count= fts_item->get_count();
369  }
370  else
371  const_result= 0;
372 
373  if (const_result == 1) {
374  ((Item_sum_count*) item)->make_const((longlong) count);
375  recalc_const_item= true;
376  }
377 
378  break;
379  case Item_sum::MIN_FUNC:
380  case Item_sum::MAX_FUNC:
381  {
382  int is_max= test(item_sum->sum_func() == Item_sum::MAX_FUNC);
383  /*
384  If MIN/MAX(expr) is the first part of a key or if all previous
385  parts of the key is found in the COND, then we can use
386  indexes to find the key.
387  */
388  Item *expr=item_sum->get_arg(0);
389  if (expr->real_item()->type() == Item::FIELD_ITEM)
390  {
391  uchar key_buff[MAX_KEY_LENGTH];
392  TABLE_REF ref;
393  uint range_fl, prefix_len;
394 
395  ref.key_buff= key_buff;
396  Item_field *item_field= (Item_field*) (expr->real_item());
397  TABLE *table= item_field->field->table;
398 
399  /*
400  Look for a partial key that can be used for optimization.
401  If we succeed, ref.key_length will contain the length of
402  this key, while prefix_len will contain the length of
403  the beginning of this key without field used in MIN/MAX().
404  Type of range for the key part for this field will be
405  returned in range_fl.
406  */
407  if (table->file->inited || (outer_tables & table->map) ||
408  !find_key_for_maxmin(is_max, &ref, item_field->field, conds,
409  &range_fl, &prefix_len))
410  {
411  const_result= 0;
412  break;
413  }
414  if ((error= table->file->ha_index_init((uint) ref.key, 1)))
415  {
416  table->file->print_error(error, MYF(0));
417  table->set_keyread(FALSE);
418  DBUG_RETURN(error);
419  }
420 
421  error= is_max ?
422  get_index_max_value(table, &ref, range_fl) :
423  get_index_min_value(table, &ref, item_field, range_fl,
424  prefix_len);
425 
426  /* Verify that the read tuple indeed matches the search key */
427  if (!error && reckey_in_range(is_max, &ref, item_field->field,
428  conds, range_fl, prefix_len))
429  error= HA_ERR_KEY_NOT_FOUND;
430  table->set_keyread(FALSE);
431  table->file->ha_index_end();
432  if (error)
433  {
434  if (error == HA_ERR_KEY_NOT_FOUND || error == HA_ERR_END_OF_FILE)
435  DBUG_RETURN(HA_ERR_KEY_NOT_FOUND); // No rows matching WHERE
436  /* HA_ERR_LOCK_DEADLOCK or some other error */
437  table->file->print_error(error, MYF(0));
438  DBUG_RETURN(error);
439  }
440  removed_tables|= table->map;
441  }
442  else if (!expr->const_item() || conds || !is_exact_count)
443  {
444  /*
445  We get here if the aggregate function is not based on a field.
446  Example: "SELECT MAX(1) FROM table ..."
447 
448  This constant optimization is not applicable if
449  1. the expression is not constant, or
450  2. it is unknown if the query returns any rows. MIN/MAX must return
451  NULL if the query doesn't return any rows. We can't determine
452  this if:
453  - the query has a condition, because, in contrast to the
454  "MAX(field)" case above, the condition will not be evaluated
455  against an index for this case, or
456  - the storage engine does not provide exact count, which means
457  that it doesn't know whether there are any rows.
458  */
459  const_result= 0;
460  break;
461  }
462  item_sum->set_aggregator(item_sum->has_with_distinct() ?
463  Aggregator::DISTINCT_AGGREGATOR :
464  Aggregator::SIMPLE_AGGREGATOR);
465  /*
466  If count == 0 (so is_exact_count == TRUE) and
467  there're no outer joins, set to NULL,
468  otherwise set to the constant value.
469  */
470  if (!count && !outer_tables)
471  {
472  item_sum->aggregator_clear();
473  // Mark the aggregated value as based on no rows
474  item->no_rows_in_result();
475  }
476  else
477  item_sum->reset_and_add();
478  item_sum->make_const();
479  recalc_const_item= 1;
480  break;
481  }
482  default:
483  const_result= 0;
484  break;
485  }
486  }
487  else if (const_result)
488  {
489  if (recalc_const_item)
490  item->update_used_tables();
491  if (!item->const_item())
492  const_result= 0;
493  }
494  }
495 
496  if (thd->is_error())
497  DBUG_RETURN(thd->get_stmt_da()->sql_errno());
498 
499  /*
500  If we have a where clause, we can only ignore searching in the
501  tables if MIN/MAX optimisation replaced all used tables
502  We do not use replaced values in case of:
503  SELECT MIN(key) FROM table_1, empty_table
504  removed_tables is != 0 if we have used MIN() or MAX().
505  */
506  if (removed_tables && used_tables != removed_tables)
507  const_result= 0; // We didn't remove all tables
508  DBUG_RETURN(const_result);
509 }
510 
511 
527 bool simple_pred(Item_func *func_item, Item **args, bool *inv_order)
528 {
529  Item *item;
530  *inv_order= 0;
531  switch (func_item->argument_count()) {
532  case 0:
533  /* MULT_EQUAL_FUNC */
534  {
535  Item_equal *item_equal= (Item_equal *) func_item;
536  Item_equal_iterator it(*item_equal);
537  args[0]= it++;
538  if (it++)
539  return 0;
540  if (!(args[1]= item_equal->get_const()))
541  return 0;
542  }
543  break;
544  case 1:
545  /* field IS NULL */
546  item= func_item->arguments()[0];
547  if (item->type() != Item::FIELD_ITEM)
548  return 0;
549  args[0]= item;
550  break;
551  case 2:
552  /* 'field op const' or 'const op field' */
553  item= func_item->arguments()[0];
554  if (item->type() == Item::FIELD_ITEM)
555  {
556  args[0]= item;
557  item= func_item->arguments()[1];
558  if (!item->const_item())
559  return 0;
560  args[1]= item;
561  }
562  else if (item->const_item())
563  {
564  args[1]= item;
565  item= func_item->arguments()[1];
566  if (item->type() != Item::FIELD_ITEM)
567  return 0;
568  args[0]= item;
569  *inv_order= 1;
570  }
571  else
572  return 0;
573  break;
574  case 3:
575  /* field BETWEEN const AND const */
576  item= func_item->arguments()[0];
577  if (item->type() == Item::FIELD_ITEM)
578  {
579  args[0]= item;
580  for (int i= 1 ; i <= 2; i++)
581  {
582  item= func_item->arguments()[i];
583  if (!item->const_item())
584  return 0;
585  args[i]= item;
586  }
587  }
588  else
589  return 0;
590  }
591  return 1;
592 }
593 
594 
651 static bool matching_cond(bool max_fl, TABLE_REF *ref, KEY *keyinfo,
652  KEY_PART_INFO *field_part, Item *cond,
653  key_part_map *key_part_used, uint *range_fl,
654  uint *prefix_len)
655 {
656  DBUG_ENTER("matching_cond");
657  if (!cond)
658  DBUG_RETURN(TRUE);
659  Field *field= field_part->field;
660  if (!(cond->used_tables() & field->table->map))
661  {
662  /* Condition doesn't restrict the used table */
663  DBUG_RETURN(TRUE);
664  }
665  if (cond->type() == Item::COND_ITEM)
666  {
667  if (((Item_cond*) cond)->functype() == Item_func::COND_OR_FUNC)
668  DBUG_RETURN(FALSE);
669 
670  /* AND */
671  List_iterator_fast<Item> li(*((Item_cond*) cond)->argument_list());
672  Item *item;
673  while ((item= li++))
674  {
675  if (!matching_cond(max_fl, ref, keyinfo, field_part, item,
676  key_part_used, range_fl, prefix_len))
677  DBUG_RETURN(FALSE);
678  }
679  DBUG_RETURN(TRUE);
680  }
681 
682  if (cond->type() != Item::FUNC_ITEM)
683  DBUG_RETURN(FALSE); // Not operator, can't optimize
684 
685  bool eq_type= 0; // =, <=> or IS NULL
686  bool is_null_safe_eq= FALSE; // The operator is NULL safe, e.g. <=>
687  bool noeq_type= 0; // < or >
688  bool less_fl= 0; // < or <=
689  bool is_null= 0; // IS NULL
690  bool between= 0; // BETWEEN ... AND ...
691 
692  switch (((Item_func*) cond)->functype()) {
693  case Item_func::ISNULL_FUNC:
694  is_null= 1; /* fall through */
695  case Item_func::EQ_FUNC:
696  eq_type= TRUE;
697  break;
698  case Item_func::EQUAL_FUNC:
699  eq_type= is_null_safe_eq= TRUE;
700  break;
701  case Item_func::LT_FUNC:
702  noeq_type= 1; /* fall through */
703  case Item_func::LE_FUNC:
704  less_fl= 1;
705  break;
706  case Item_func::GT_FUNC:
707  noeq_type= 1; /* fall through */
708  case Item_func::GE_FUNC:
709  break;
710  case Item_func::BETWEEN:
711  between= 1;
712 
713  // NOT BETWEEN is equivalent to OR and is therefore not a conjunction
714  if (((Item_func_between*)cond)->negated)
715  DBUG_RETURN(false);
716 
717  break;
718  case Item_func::MULT_EQUAL_FUNC:
719  eq_type= 1;
720  break;
721  default:
722  DBUG_RETURN(FALSE); // Can't optimize function
723  }
724 
725  Item *args[3];
726  bool inv;
727 
728  /* Test if this is a comparison of a field and constant */
729  if (!simple_pred((Item_func*) cond, args, &inv))
730  DBUG_RETURN(FALSE);
731 
732  if (!is_null_safe_eq && !is_null &&
733  (args[1]->is_null() || (between && args[2]->is_null())))
734  DBUG_RETURN(FALSE);
735 
736  if (inv && !eq_type)
737  less_fl= 1-less_fl; // Convert '<' -> '>' (etc)
738 
739  /* Check if field is part of the tested partial key */
740  uchar *key_ptr= ref->key_buff;
741  KEY_PART_INFO *part;
742  for (part= keyinfo->key_part; ; key_ptr+= part++->store_length)
743 
744  {
745  if (part > field_part)
746  DBUG_RETURN(FALSE); // Field is beyond the tested parts
747  if (part->field->eq(((Item_field*) args[0])->field))
748  break; // Found a part of the key for the field
749  }
750 
751  bool is_field_part= part == field_part;
752  if (!(is_field_part || eq_type))
753  DBUG_RETURN(FALSE);
754 
755  key_part_map org_key_part_used= *key_part_used;
756  if (eq_type || between || max_fl == less_fl)
757  {
758  uint length= (key_ptr-ref->key_buff)+part->store_length;
759  if (ref->key_length < length)
760  {
761  /* Ultimately ref->key_length will contain the length of the search key */
762  ref->key_length= length;
763  ref->key_parts= (part - keyinfo->key_part) + 1;
764  }
765  if (!*prefix_len && part+1 == field_part)
766  *prefix_len= length;
767  if (is_field_part && eq_type)
768  *prefix_len= ref->key_length;
769 
770  *key_part_used|= (key_part_map) 1 << (part - keyinfo->key_part);
771  }
772 
773  if (org_key_part_used == *key_part_used &&
774  /*
775  The current search key is not being extended with a new key part. This
776  means that the a condition is added a key part for which there was a
777  previous condition. We can only overwrite such key parts in some special
778  cases, e.g. a > 2 AND a > 1 (here range_fl must be set to something). In
779  all other cases the WHERE condition is always false anyway.
780  */
781  (eq_type || *range_fl == 0))
782  DBUG_RETURN(FALSE);
783 
784  if (org_key_part_used != *key_part_used ||
785  (is_field_part &&
786  (between || eq_type || max_fl == less_fl) && !cond->val_int()))
787  {
788  /*
789  It's the first predicate for this part or a predicate of the
790  following form that moves upper/lower bounds for max/min values:
791  - field BETWEEN const AND const
792  - field = const
793  - field {<|<=} const, when searching for MAX
794  - field {>|>=} const, when searching for MIN
795  */
796 
797  if (is_null || (is_null_safe_eq && args[1]->is_null()))
798  {
799  /*
800  If we have a non-nullable index, we cannot use it,
801  since set_null will be ignored, and we will compare uninitialized data.
802  */
803  if (!part->field->real_maybe_null())
804  DBUG_RETURN(false);
805  part->field->set_null();
806  *key_ptr= (uchar) 1;
807  }
808  else
809  {
810  /* Update endpoints for MAX/MIN, see function comment. */
811  Item *value= args[between && max_fl ? 2 : 1];
812  value->save_in_field_no_warnings(part->field, true);
813  if (part->null_bit)
814  *key_ptr++= (uchar) test(part->field->is_null());
815  part->field->get_key_image(key_ptr, part->length, Field::itRAW);
816  }
817  if (is_field_part)
818  {
819  if (between || eq_type)
820  *range_fl&= ~(NO_MAX_RANGE | NO_MIN_RANGE);
821  else
822  {
823  *range_fl&= ~(max_fl ? NO_MAX_RANGE : NO_MIN_RANGE);
824  if (noeq_type)
825  *range_fl|= (max_fl ? NEAR_MAX : NEAR_MIN);
826  else
827  *range_fl&= ~(max_fl ? NEAR_MAX : NEAR_MIN);
828  }
829  }
830  }
831  else if (eq_type)
832  {
833  if ((!is_null && !cond->val_int()) ||
834  (is_null && !test(part->field->is_null())))
835  DBUG_RETURN(FALSE); // Impossible test
836  }
837  else if (is_field_part)
838  *range_fl&= ~(max_fl ? NO_MIN_RANGE : NO_MAX_RANGE);
839  DBUG_RETURN(TRUE);
840 }
841 
842 
887 static bool find_key_for_maxmin(bool max_fl, TABLE_REF *ref,
888  Field* field, Item *cond,
889  uint *range_fl, uint *prefix_len)
890 {
891  if (!(field->flags & PART_KEY_FLAG))
892  return false; // Not key field
893 
894  DBUG_ENTER("find_key_for_maxmin");
895 
896  TABLE *table= field->table;
897  uint idx= 0;
898 
899  KEY *keyinfo,*keyinfo_end;
900  for (keyinfo= table->key_info, keyinfo_end= keyinfo+table->s->keys ;
901  keyinfo != keyinfo_end;
902  keyinfo++,idx++)
903  {
904  KEY_PART_INFO *part,*part_end;
905  key_part_map key_part_to_use= 0;
906  /*
907  Perform a check if index is not disabled by ALTER TABLE
908  or IGNORE INDEX.
909  */
910  if (!table->keys_in_use_for_query.is_set(idx))
911  continue;
912  uint jdx= 0;
913  *prefix_len= 0;
914  for (part= keyinfo->key_part, part_end= part + actual_key_parts(keyinfo) ;
915  part != part_end ;
916  part++, jdx++, key_part_to_use= (key_part_to_use << 1) | 1)
917  {
918  if (!(table->file->index_flags(idx, jdx, 0) & HA_READ_ORDER))
919  DBUG_RETURN(false);
920 
921  /* Check whether the index component is partial */
922  Field *part_field= table->field[part->fieldnr-1];
923  if ((part_field->flags & BLOB_FLAG) ||
924  part->length < part_field->key_length())
925  break;
926 
927  if (field->eq(part->field))
928  {
929  ref->key= idx;
930  ref->key_length= 0;
931  ref->key_parts= 0;
932  key_part_map key_part_used= 0;
933  *range_fl= NO_MIN_RANGE | NO_MAX_RANGE;
934  if (matching_cond(max_fl, ref, keyinfo, part, cond,
935  &key_part_used, range_fl, prefix_len) &&
936  !(key_part_to_use & ~key_part_used))
937  {
938  if (!max_fl && key_part_used == key_part_to_use && part->null_bit)
939  {
940  /*
941  The query is on this form:
942 
943  SELECT MIN(key_part_k)
944  FROM t1
945  WHERE key_part_1 = const and ... and key_part_k-1 = const
946 
947  If key_part_k is nullable, we want to find the first matching row
948  where key_part_k is not null. The key buffer is now {const, ...,
949  NULL}. This will be passed to the handler along with a flag
950  indicating open interval. If a tuple is read that does not match
951  these search criteria, an attempt will be made to read an exact
952  match for the key buffer.
953  */
954  /* Set the first byte of key_part_k to 1, that means NULL */
955  ref->key_buff[ref->key_length]= 1;
956  ref->key_length+= part->store_length;
957  ref->key_parts++;
958  DBUG_ASSERT(ref->key_parts == jdx+1);
959  *range_fl&= ~NO_MIN_RANGE;
960  *range_fl|= NEAR_MIN; // Open interval
961  }
962  /*
963  The following test is false when the key in the key tree is
964  converted (for example to upper case)
965  */
966  if (field->part_of_key.is_set(idx))
967  table->set_keyread(TRUE);
968  DBUG_RETURN(true);
969  }
970  }
971  }
972  }
973  DBUG_RETURN(false);
974 }
975 
976 
993 static int reckey_in_range(bool max_fl, TABLE_REF *ref, Field* field,
994  Item *cond, uint range_fl, uint prefix_len)
995 {
996  if (key_cmp_if_same(field->table, ref->key_buff, ref->key, prefix_len))
997  return 1;
998  if (!cond || (range_fl & (max_fl ? NO_MIN_RANGE : NO_MAX_RANGE)))
999  return 0;
1000  return maxmin_in_range(max_fl, field, cond);
1001 }
1002 
1003 
1017 static int maxmin_in_range(bool max_fl, Field* field, Item *cond)
1018 {
1019  /* If AND/OR condition */
1020  if (cond->type() == Item::COND_ITEM)
1021  {
1022  List_iterator_fast<Item> li(*((Item_cond*) cond)->argument_list());
1023  Item *item;
1024  while ((item= li++))
1025  {
1026  if (maxmin_in_range(max_fl, field, item))
1027  return 1;
1028  }
1029  return 0;
1030  }
1031 
1032  if (cond->used_tables() != field->table->map)
1033  return 0;
1034  bool less_fl= 0;
1035  switch (((Item_func*) cond)->functype()) {
1036  case Item_func::BETWEEN:
1037  return cond->val_int() == 0; // Return 1 if WHERE is false
1038  case Item_func::LT_FUNC:
1039  case Item_func::LE_FUNC:
1040  less_fl= 1;
1041  case Item_func::GT_FUNC:
1042  case Item_func::GE_FUNC:
1043  {
1044  Item *item= ((Item_func*) cond)->arguments()[1];
1045  /* In case of 'const op item' we have to swap the operator */
1046  if (!item->const_item())
1047  less_fl= 1-less_fl;
1048  /*
1049  We only have to check the expression if we are using an expression like
1050  SELECT MAX(b) FROM t1 WHERE a=const AND b>const
1051  not for
1052  SELECT MAX(b) FROM t1 WHERE a=const AND b<const
1053  */
1054  if (max_fl != less_fl)
1055  return cond->val_int() == 0; // Return 1 if WHERE is false
1056  return 0;
1057  }
1058  case Item_func::EQ_FUNC:
1059  case Item_func::EQUAL_FUNC:
1060  break;
1061  default: // Keep compiler happy
1062  DBUG_ASSERT(1); // Impossible
1063  break;
1064  }
1065  return 0;
1066 }
1067