mySQL 5.0.11 sources for tomato
[tomato.git] / release / src / router / mysql / sql / opt_sum.cc
blob5747ea550878863aa0b067350e736858def52ce1
1 /* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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.
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.
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
18 /**
19 @file
21 Optimising of MIN(), MAX() and COUNT(*) queries without 'group by' clause
22 by replacing the aggregate expression with a constant.
24 Given a table with a compound key on columns (a,b,c), the following
25 types of queries are optimised (assuming the table handler supports
26 the required methods)
28 @verbatim
29 SELECT COUNT(*) FROM t1[,t2,t3,...]
30 SELECT MIN(b) FROM t1 WHERE a=const
31 SELECT MAX(c) FROM t1 WHERE a=const AND b=const
32 SELECT MAX(b) FROM t1 WHERE a=const AND b<const
33 SELECT MIN(b) FROM t1 WHERE a=const AND b>const
34 SELECT MIN(b) FROM t1 WHERE a=const AND b BETWEEN const AND const
35 SELECT MAX(b) FROM t1 WHERE a=const AND b BETWEEN const AND const
36 @endverbatim
38 Instead of '<' one can use '<=', '>', '>=' and '=' as well.
39 Instead of 'a=const' the condition 'a IS NULL' can be used.
41 If all selected fields are replaced then we will also remove all
42 involved tables and return the answer without any join. Thus, the
43 following query will be replaced with a row of two constants:
44 @verbatim
45 SELECT MAX(b), MIN(d) FROM t1,t2
46 WHERE a=const AND b<const AND d>const
47 @endverbatim
48 (assuming a index for column d of table t2 is defined)
51 #include "mysql_priv.h"
52 #include "sql_select.h"
54 static bool find_key_for_maxmin(bool max_fl, TABLE_REF *ref, Field* field,
55 COND *cond, uint *range_fl,
56 uint *key_prefix_length);
57 static int reckey_in_range(bool max_fl, TABLE_REF *ref, Field* field,
58 COND *cond, uint range_fl, uint prefix_len);
59 static int maxmin_in_range(bool max_fl, Field* field, COND *cond);
63 Get exact count of rows in all tables
65 SYNOPSIS
66 get_exact_records()
67 tables List of tables
69 NOTES
70 When this is called, we know all table handlers supports HA_HAS_RECORDS
71 or HA_STATS_RECORDS_IS_EXACT
73 RETURN
74 ULONGLONG_MAX Error: Could not calculate number of rows
75 # Multiplication of number of rows in all tables
78 static ulonglong get_exact_record_count(TABLE_LIST *tables)
80 ulonglong count= 1;
81 for (TABLE_LIST *tl= tables; tl; tl= tl->next_leaf)
83 ha_rows tmp= tl->table->file->records();
84 if ((tmp == HA_POS_ERROR))
85 return ULONGLONG_MAX;
86 count*= tmp;
88 return count;
92 /**
93 Use index to read MIN(field) value.
95 @param table Table object
96 @param ref Reference to the structure where we store the key value
97 @item_field Field used in MIN()
98 @range_fl Whether range endpoint is strict less than
99 @prefix_len Length of common key part for the range
101 @retval
102 0 No errors
103 HA_ERR_... Otherwise
106 static int get_index_min_value(TABLE *table, TABLE_REF *ref,
107 Item_field *item_field, uint range_fl,
108 uint prefix_len)
110 int error;
112 if (!ref->key_length)
113 error= table->file->index_first(table->record[0]);
114 else
117 Use index to replace MIN/MAX functions with their values
118 according to the following rules:
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
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.
130 if (!(range_fl & NEAR_MIN))
132 Closed interval: Either The MIN argument is non-nullable, or
133 we have a >= predicate for the MIN argument.
135 error= table->file->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
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.
149 DBUG_ASSERT(prefix_len < ref->key_length);
150 error= table->file->index_read_map(table->record[0],
151 ref->key_buff,
152 make_prev_keypart_map(ref->key_parts),
153 HA_READ_AFTER_KEY);
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.
160 Check if case 1 from above holds. If it does, we should read
161 the skipped tuple.
163 if (item_field->field->real_maybe_null() &&
164 ref->key_buff[prefix_len] == 1 &&
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.
172 (error == HA_ERR_KEY_NOT_FOUND ||
173 key_cmp_if_same(table, ref->key_buff, ref->key, prefix_len)))
175 DBUG_ASSERT(item_field->field->real_maybe_null());
176 error= table->file->index_read_map(table->record[0],
177 ref->key_buff,
178 make_prev_keypart_map(ref->key_parts),
179 HA_READ_KEY_EXACT);
183 return error;
188 Use index to read MAX(field) value.
190 @param table Table object
191 @param ref Reference to the structure where we store the key value
192 @range_fl Whether range endpoint is strict greater than
194 @retval
195 0 No errors
196 HA_ERR_... Otherwise
199 static int get_index_max_value(TABLE *table, TABLE_REF *ref, uint range_fl)
201 return (ref->key_length ?
202 table->file->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->index_last(table->record[0]));
213 Substitutes constants for some COUNT(), MIN() and MAX() functions.
215 @param thd thread handler
216 @param tables list of leaves of join table tree
217 @param all_fields All fields to be returned
218 @param conds WHERE clause
220 @note
221 This function is only called for queries with aggregate functions and no
222 GROUP BY part. This means that the result set shall contain a single
223 row only
225 @retval
226 0 no errors
227 @retval
228 1 if all items were resolved
229 @retval
230 HA_ERR_KEY_NOT_FOUND on impossible conditions
231 @retval
232 HA_ERR_... if a deadlock or a lock wait timeout happens, for example
233 @retval
234 ER_... e.g. ER_SUBQUERY_NO_1_ROW
237 int opt_sum_query(THD *thd,
238 TABLE_LIST *tables, List<Item> &all_fields, COND *conds)
240 List_iterator_fast<Item> it(all_fields);
241 int const_result= 1;
242 bool recalc_const_item= 0;
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 table_map where_tables= 0;
247 Item *item;
248 int error;
250 DBUG_ENTER("opt_sum_query");
252 if (conds)
253 where_tables= conds->used_tables();
256 Analyze outer join dependencies, and, if possible, compute the number
257 of returned rows.
259 for (TABLE_LIST *tl= tables; tl; tl= tl->next_leaf)
261 TABLE_LIST *embedded;
262 for (embedded= tl ; embedded; embedded= embedded->embedding)
264 if (embedded->on_expr)
265 break;
267 if (embedded)
268 /* Don't replace expression on a table that is part of an outer join */
270 outer_tables|= tl->table->map;
273 We can't optimise LEFT JOIN in cases where the WHERE condition
274 restricts the table that is used, like in:
275 SELECT MAX(t1.a) FROM t1 LEFT JOIN t2 join-condition
276 WHERE t2.field IS NULL;
278 if (tl->table->map & where_tables)
279 DBUG_RETURN(0);
281 else
282 used_tables|= tl->table->map;
285 If the storage manager of 'tl' gives exact row count as part of
286 statistics (cheap), compute the total number of rows. If there are
287 no outer table dependencies, this count may be used as the real count.
288 Schema tables are filled after this function is invoked, so we can't
289 get row count
291 if (!(tl->table->file->ha_table_flags() & HA_STATS_RECORDS_IS_EXACT) ||
292 tl->schema_table)
294 maybe_exact_count&= test(!tl->schema_table &&
295 (tl->table->file->ha_table_flags() &
296 HA_HAS_RECORDS));
297 is_exact_count= FALSE;
298 count= 1; // ensure count != 0
300 else
302 error= tl->table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);
303 if(error)
305 tl->table->file->print_error(error, MYF(0));
306 tl->table->in_use->fatal_error();
307 DBUG_RETURN(error);
309 count*= tl->table->file->stats.records;
314 Iterate through all items in the SELECT clause and replace
315 COUNT(), MIN() and MAX() with constants (if possible).
318 while ((item= it++))
320 if (item->type() == Item::SUM_FUNC_ITEM)
322 Item_sum *item_sum= (((Item_sum*) item));
323 switch (item_sum->sum_func()) {
324 case Item_sum::COUNT_FUNC:
326 If the expr in COUNT(expr) can never be null we can change this
327 to the number of rows in the tables if this number is exact and
328 there are no outer joins.
330 if (!conds && !((Item_sum_count*) item)->get_arg(0)->maybe_null &&
331 !outer_tables && maybe_exact_count)
333 if (!is_exact_count)
335 if ((count= get_exact_record_count(tables)) == ULONGLONG_MAX)
337 /* Error from handler in counting rows. Don't optimize count() */
338 const_result= 0;
339 continue;
341 is_exact_count= 1; // count is now exact
343 ((Item_sum_count*) item)->make_const((longlong) count);
344 recalc_const_item= 1;
346 else
347 const_result= 0;
348 break;
349 case Item_sum::MIN_FUNC:
350 case Item_sum::MAX_FUNC:
352 int is_max= test(item_sum->sum_func() == Item_sum::MAX_FUNC);
354 If MIN/MAX(expr) is the first part of a key or if all previous
355 parts of the key is found in the COND, then we can use
356 indexes to find the key.
358 Item *expr=item_sum->get_arg(0);
359 if (expr->real_item()->type() == Item::FIELD_ITEM)
361 uchar key_buff[MAX_KEY_LENGTH];
362 TABLE_REF ref;
363 uint range_fl, prefix_len;
365 ref.key_buff= key_buff;
366 Item_field *item_field= (Item_field*) (expr->real_item());
367 TABLE *table= item_field->field->table;
370 Look for a partial key that can be used for optimization.
371 If we succeed, ref.key_length will contain the length of
372 this key, while prefix_len will contain the length of
373 the beginning of this key without field used in MIN/MAX().
374 Type of range for the key part for this field will be
375 returned in range_fl.
377 if (table->file->inited || (outer_tables & table->map) ||
378 !find_key_for_maxmin(is_max, &ref, item_field->field, conds,
379 &range_fl, &prefix_len))
381 const_result= 0;
382 break;
384 table->file->ha_index_init((uint) ref.key, 1);
386 error= is_max ?
387 get_index_max_value(table, &ref, range_fl) :
388 get_index_min_value(table, &ref, item_field, range_fl,
389 prefix_len);
391 /* Verify that the read tuple indeed matches the search key */
392 if (!error && reckey_in_range(is_max, &ref, item_field->field,
393 conds, range_fl, prefix_len))
394 error= HA_ERR_KEY_NOT_FOUND;
395 table->set_keyread(FALSE);
396 table->file->ha_index_end();
397 if (error)
399 if (error == HA_ERR_KEY_NOT_FOUND || error == HA_ERR_END_OF_FILE)
400 DBUG_RETURN(HA_ERR_KEY_NOT_FOUND); // No rows matching WHERE
401 /* HA_ERR_LOCK_DEADLOCK or some other error */
402 table->file->print_error(error, MYF(0));
403 DBUG_RETURN(error);
405 removed_tables|= table->map;
407 else if (!expr->const_item() || !is_exact_count)
410 The optimization is not applicable in both cases:
411 (a) 'expr' is a non-constant expression. Then we can't
412 replace 'expr' by a constant.
413 (b) 'expr' is a costant. According to ANSI, MIN/MAX must return
414 NULL if the query does not return any rows. Thus, if we are not
415 able to determine if the query returns any rows, we can't apply
416 the optimization and replace MIN/MAX with a constant.
418 const_result= 0;
419 break;
422 If count == 0 (so is_exact_count == TRUE) and
423 there're no outer joins, set to NULL,
424 otherwise set to the constant value.
426 if (!count && !outer_tables)
427 item_sum->clear();
428 else
429 item_sum->reset();
430 item_sum->make_const();
431 recalc_const_item= 1;
432 break;
434 default:
435 const_result= 0;
436 break;
439 else if (const_result)
441 if (recalc_const_item)
442 item->update_used_tables();
443 if (!item->const_item())
444 const_result= 0;
448 if (thd->is_error())
449 DBUG_RETURN(thd->main_da.sql_errno());
452 If we have a where clause, we can only ignore searching in the
453 tables if MIN/MAX optimisation replaced all used tables
454 We do not use replaced values in case of:
455 SELECT MIN(key) FROM table_1, empty_table
456 removed_tables is != 0 if we have used MIN() or MAX().
458 if (removed_tables && used_tables != removed_tables)
459 const_result= 0; // We didn't remove all tables
460 DBUG_RETURN(const_result);
465 Test if the predicate compares a field with constants.
467 @param func_item Predicate item
468 @param[out] args Here we store the field followed by constants
469 @param[out] inv_order Is set to 1 if the predicate is of the form
470 'const op field'
472 @retval
473 0 func_item is a simple predicate: a field is compared with
474 constants
475 @retval
476 1 Otherwise
479 bool simple_pred(Item_func *func_item, Item **args, bool *inv_order)
481 Item *item;
482 *inv_order= 0;
483 switch (func_item->argument_count()) {
484 case 0:
485 /* MULT_EQUAL_FUNC */
487 Item_equal *item_equal= (Item_equal *) func_item;
488 Item_equal_iterator it(*item_equal);
489 args[0]= it++;
490 if (it++)
491 return 0;
492 if (!(args[1]= item_equal->get_const()))
493 return 0;
495 break;
496 case 1:
497 /* field IS NULL */
498 item= func_item->arguments()[0];
499 if (item->type() != Item::FIELD_ITEM)
500 return 0;
501 args[0]= item;
502 break;
503 case 2:
504 /* 'field op const' or 'const op field' */
505 item= func_item->arguments()[0];
506 if (item->type() == Item::FIELD_ITEM)
508 args[0]= item;
509 item= func_item->arguments()[1];
510 if (!item->const_item())
511 return 0;
512 args[1]= item;
514 else if (item->const_item())
516 args[1]= item;
517 item= func_item->arguments()[1];
518 if (item->type() != Item::FIELD_ITEM)
519 return 0;
520 args[0]= item;
521 *inv_order= 1;
523 else
524 return 0;
525 break;
526 case 3:
527 /* field BETWEEN const AND const */
528 item= func_item->arguments()[0];
529 if (item->type() == Item::FIELD_ITEM)
531 args[0]= item;
532 for (int i= 1 ; i <= 2; i++)
534 item= func_item->arguments()[i];
535 if (!item->const_item())
536 return 0;
537 args[i]= item;
540 else
541 return 0;
543 return 1;
548 Check whether a condition matches a key to get {MAX|MIN}(field):.
550 For the index specified by the keyinfo parameter and an index that
551 contains the field as its component (field_part), the function
552 checks whether
554 - the condition cond is a conjunction,
555 - all of its conjuncts refer to columns of the same table, and
556 - each conjunct is on one of the following forms:
557 - f_i = const_i or const_i = f_i or f_i IS NULL,
558 where f_i is part of the index
559 - field {<|<=|>=|>|=} const
560 - const {<|<=|>=|>|=} field
561 - field BETWEEN const_1 AND const_2
563 As a side-effect, the key value to be used for looking up the MIN/MAX value
564 is actually stored inside the Field object. An interesting feature is that
565 the function will find the most restrictive endpoint by over-eager
566 evaluation of the @c WHERE condition. It continually stores the current
567 endpoint inside the Field object. For a query such as
569 @code
570 SELECT MIN(a) FROM t1 WHERE a > 3 AND a > 5;
571 @endcode
573 the algorithm will recurse over the conjuction, storing first a 3 in the
574 field. In the next recursive invocation the expression a > 5 is evaluated
575 as 3 > 5 (Due to the dual nature of Field objects as value carriers and
576 field identifiers), which will obviously fail, leading to 5 being stored in
577 the Field object.
579 @param[in] max_fl Set to true if we are optimizing MAX(),
580 false means we are optimizing %MIN()
581 @param[in, out] ref Reference to the structure where the function
582 stores the key value
583 @param[in] keyinfo Reference to the key info
584 @param[in] field_part Pointer to the key part for the field
585 @param[in] cond WHERE condition
586 @param[in,out] key_part_used Map of matchings parts. The function will output
587 the set of key parts actually being matched in
588 this set, yet it relies on the caller to
589 initialize the value to zero. This is due
590 to the fact that this value is passed
591 recursively.
592 @param[in,out] range_fl Says whether endpoints use strict greater/less
593 than.
594 @param[out] prefix_len Length of common key part for the range
595 where MAX/MIN is searched for
597 @retval
598 false Index can't be used.
599 @retval
600 true We can use the index to get MIN/MAX value
603 static bool matching_cond(bool max_fl, TABLE_REF *ref, KEY *keyinfo,
604 KEY_PART_INFO *field_part, COND *cond,
605 key_part_map *key_part_used, uint *range_fl,
606 uint *prefix_len)
608 DBUG_ENTER("matching_cond");
609 if (!cond)
610 DBUG_RETURN(TRUE);
611 Field *field= field_part->field;
612 if (!(cond->used_tables() & field->table->map))
614 /* Condition doesn't restrict the used table */
615 DBUG_RETURN(TRUE);
617 if (cond->type() == Item::COND_ITEM)
619 if (((Item_cond*) cond)->functype() == Item_func::COND_OR_FUNC)
620 DBUG_RETURN(FALSE);
622 /* AND */
623 List_iterator_fast<Item> li(*((Item_cond*) cond)->argument_list());
624 Item *item;
625 while ((item= li++))
627 if (!matching_cond(max_fl, ref, keyinfo, field_part, item,
628 key_part_used, range_fl, prefix_len))
629 DBUG_RETURN(FALSE);
631 DBUG_RETURN(TRUE);
634 if (cond->type() != Item::FUNC_ITEM)
635 DBUG_RETURN(FALSE); // Not operator, can't optimize
637 bool eq_type= 0; // =, <=> or IS NULL
638 bool is_null_safe_eq= FALSE; // The operator is NULL safe, e.g. <=>
639 bool noeq_type= 0; // < or >
640 bool less_fl= 0; // < or <=
641 bool is_null= 0; // IS NULL
642 bool between= 0; // BETWEEN ... AND ...
644 switch (((Item_func*) cond)->functype()) {
645 case Item_func::ISNULL_FUNC:
646 is_null= 1; /* fall through */
647 case Item_func::EQ_FUNC:
648 eq_type= TRUE;
649 break;
650 case Item_func::EQUAL_FUNC:
651 eq_type= is_null_safe_eq= TRUE;
652 break;
653 case Item_func::LT_FUNC:
654 noeq_type= 1; /* fall through */
655 case Item_func::LE_FUNC:
656 less_fl= 1;
657 break;
658 case Item_func::GT_FUNC:
659 noeq_type= 1; /* fall through */
660 case Item_func::GE_FUNC:
661 break;
662 case Item_func::BETWEEN:
663 between= 1;
664 break;
665 case Item_func::MULT_EQUAL_FUNC:
666 eq_type= 1;
667 break;
668 default:
669 DBUG_RETURN(FALSE); // Can't optimize function
672 Item *args[3];
673 bool inv;
675 /* Test if this is a comparison of a field and constant */
676 if (!simple_pred((Item_func*) cond, args, &inv))
677 DBUG_RETURN(FALSE);
679 if (!is_null_safe_eq && !is_null &&
680 (args[1]->is_null() || (between && args[2]->is_null())))
681 DBUG_RETURN(FALSE);
683 if (inv && !eq_type)
684 less_fl= 1-less_fl; // Convert '<' -> '>' (etc)
686 /* Check if field is part of the tested partial key */
687 uchar *key_ptr= ref->key_buff;
688 KEY_PART_INFO *part;
689 for (part= keyinfo->key_part; ; key_ptr+= part++->store_length)
692 if (part > field_part)
693 DBUG_RETURN(FALSE); // Field is beyond the tested parts
694 if (part->field->eq(((Item_field*) args[0])->field))
695 break; // Found a part of the key for the field
698 bool is_field_part= part == field_part;
699 if (!(is_field_part || eq_type))
700 DBUG_RETURN(FALSE);
702 key_part_map org_key_part_used= *key_part_used;
703 if (eq_type || between || max_fl == less_fl)
705 uint length= (key_ptr-ref->key_buff)+part->store_length;
706 if (ref->key_length < length)
708 /* Ultimately ref->key_length will contain the length of the search key */
709 ref->key_length= length;
710 ref->key_parts= (part - keyinfo->key_part) + 1;
712 if (!*prefix_len && part+1 == field_part)
713 *prefix_len= length;
714 if (is_field_part && eq_type)
715 *prefix_len= ref->key_length;
717 *key_part_used|= (key_part_map) 1 << (part - keyinfo->key_part);
720 if (org_key_part_used == *key_part_used &&
722 The current search key is not being extended with a new key part. This
723 means that the a condition is added a key part for which there was a
724 previous condition. We can only overwrite such key parts in some special
725 cases, e.g. a > 2 AND a > 1 (here range_fl must be set to something). In
726 all other cases the WHERE condition is always false anyway.
728 (eq_type || *range_fl == 0))
729 DBUG_RETURN(FALSE);
731 if (org_key_part_used != *key_part_used ||
732 (is_field_part &&
733 (between || eq_type || max_fl == less_fl) && !cond->val_int()))
736 It's the first predicate for this part or a predicate of the
737 following form that moves upper/lower bounds for max/min values:
738 - field BETWEEN const AND const
739 - field = const
740 - field {<|<=} const, when searching for MAX
741 - field {>|>=} const, when searching for MIN
744 if (is_null || (is_null_safe_eq && args[1]->is_null()))
747 If we have a non-nullable index, we cannot use it,
748 since set_null will be ignored, and we will compare uninitialized data.
750 if (!part->field->real_maybe_null())
751 DBUG_RETURN(false);
752 part->field->set_null();
753 *key_ptr= (uchar) 1;
755 else
757 /* Update endpoints for MAX/MIN, see function comment. */
758 Item *value= args[between && max_fl ? 2 : 1];
759 store_val_in_field(part->field, value, CHECK_FIELD_IGNORE);
760 if (part->null_bit)
761 *key_ptr++= (uchar) test(part->field->is_null());
762 part->field->get_key_image(key_ptr, part->length, Field::itRAW);
764 if (is_field_part)
766 if (between || eq_type)
767 *range_fl&= ~(NO_MAX_RANGE | NO_MIN_RANGE);
768 else
770 *range_fl&= ~(max_fl ? NO_MAX_RANGE : NO_MIN_RANGE);
771 if (noeq_type)
772 *range_fl|= (max_fl ? NEAR_MAX : NEAR_MIN);
773 else
774 *range_fl&= ~(max_fl ? NEAR_MAX : NEAR_MIN);
778 else if (eq_type)
780 if ((!is_null && !cond->val_int()) ||
781 (is_null && !test(part->field->is_null())))
782 DBUG_RETURN(FALSE); // Impossible test
784 else if (is_field_part)
785 *range_fl&= ~(max_fl ? NO_MIN_RANGE : NO_MAX_RANGE);
786 DBUG_RETURN(TRUE);
791 Check whether we can get value for {max|min}(field) by using a key.
793 If where-condition is not a conjunction of 0 or more conjuct the
794 function returns false, otherwise it checks whether there is an
795 index including field as its k-th component/part such that:
797 -# for each previous component f_i there is one and only one conjunct
798 of the form: f_i= const_i or const_i= f_i or f_i is null
799 -# references to field occur only in conjucts of the form:
800 field {<|<=|>=|>|=} const or const {<|<=|>=|>|=} field or
801 field BETWEEN const1 AND const2
802 -# all references to the columns from the same table as column field
803 occur only in conjucts mentioned above.
804 -# each of k first components the index is not partial, i.e. is not
805 defined on a fixed length proper prefix of the field.
807 If such an index exists the function through the ref parameter
808 returns the key value to find max/min for the field using the index,
809 the length of first (k-1) components of the key and flags saying
810 how to apply the key for the search max/min value.
811 (if we have a condition field = const, prefix_len contains the length
812 of the whole search key)
814 @param[in] max_fl 0 for MIN(field) / 1 for MAX(field)
815 @param[in,out] ref Reference to the structure we store the key value
816 @param[in] field Field used inside MIN() / MAX()
817 @param[in] cond WHERE condition
818 @param[out] range_fl Bit flags for how to search if key is ok
819 @param[out] prefix_len Length of prefix for the search range
821 @note
822 This function may set field->table->key_read to true,
823 which must be reset after index is used!
824 (This can only happen when function returns 1)
826 @retval
827 0 Index can not be used to optimize MIN(field)/MAX(field)
828 @retval
829 1 Can use key to optimize MIN()/MAX().
830 In this case ref, range_fl and prefix_len are updated
834 static bool find_key_for_maxmin(bool max_fl, TABLE_REF *ref,
835 Field* field, COND *cond,
836 uint *range_fl, uint *prefix_len)
838 if (!(field->flags & PART_KEY_FLAG))
839 return false; // Not key field
841 DBUG_ENTER("find_key_for_maxmin");
843 TABLE *table= field->table;
844 uint idx= 0;
846 KEY *keyinfo,*keyinfo_end;
847 for (keyinfo= table->key_info, keyinfo_end= keyinfo+table->s->keys ;
848 keyinfo != keyinfo_end;
849 keyinfo++,idx++)
851 KEY_PART_INFO *part,*part_end;
852 key_part_map key_part_to_use= 0;
854 Perform a check if index is not disabled by ALTER TABLE
855 or IGNORE INDEX.
857 if (!table->keys_in_use_for_query.is_set(idx))
858 continue;
859 uint jdx= 0;
860 *prefix_len= 0;
861 for (part= keyinfo->key_part, part_end= part+keyinfo->key_parts ;
862 part != part_end ;
863 part++, jdx++, key_part_to_use= (key_part_to_use << 1) | 1)
865 if (!(table->file->index_flags(idx, jdx, 0) & HA_READ_ORDER))
866 DBUG_RETURN(false);
868 /* Check whether the index component is partial */
869 Field *part_field= table->field[part->fieldnr-1];
870 if ((part_field->flags & BLOB_FLAG) ||
871 part->length < part_field->key_length())
872 break;
874 if (field->eq(part->field))
876 ref->key= idx;
877 ref->key_length= 0;
878 ref->key_parts= 0;
879 key_part_map key_part_used= 0;
880 *range_fl= NO_MIN_RANGE | NO_MAX_RANGE;
881 if (matching_cond(max_fl, ref, keyinfo, part, cond,
882 &key_part_used, range_fl, prefix_len) &&
883 !(key_part_to_use & ~key_part_used))
885 if (!max_fl && key_part_used == key_part_to_use && part->null_bit)
888 The query is on this form:
890 SELECT MIN(key_part_k)
891 FROM t1
892 WHERE key_part_1 = const and ... and key_part_k-1 = const
894 If key_part_k is nullable, we want to find the first matching row
895 where key_part_k is not null. The key buffer is now {const, ...,
896 NULL}. This will be passed to the handler along with a flag
897 indicating open interval. If a tuple is read that does not match
898 these search criteria, an attempt will be made to read an exact
899 match for the key buffer.
901 /* Set the first byte of key_part_k to 1, that means NULL */
902 ref->key_buff[ref->key_length]= 1;
903 ref->key_length+= part->store_length;
904 ref->key_parts++;
905 DBUG_ASSERT(ref->key_parts == jdx+1);
906 *range_fl&= ~NO_MIN_RANGE;
907 *range_fl|= NEAR_MIN; // Open interval
910 The following test is false when the key in the key tree is
911 converted (for example to upper case)
913 if (field->part_of_key.is_set(idx))
914 table->set_keyread(TRUE);
915 DBUG_RETURN(true);
920 DBUG_RETURN(false);
925 Check whether found key is in range specified by conditions.
927 @param[in] max_fl 0 for MIN(field) / 1 for MAX(field)
928 @param[in] ref Reference to the key value and info
929 @param[in] field Field used the MIN/MAX expression
930 @param[in] cond WHERE condition
931 @param[in] range_fl Says whether there is a condition to to be checked
932 @param[in] prefix_len Length of the constant part of the key
934 @retval
935 0 ok
936 @retval
937 1 WHERE was not true for the found row
940 static int reckey_in_range(bool max_fl, TABLE_REF *ref, Field* field,
941 COND *cond, uint range_fl, uint prefix_len)
943 if (key_cmp_if_same(field->table, ref->key_buff, ref->key, prefix_len))
944 return 1;
945 if (!cond || (range_fl & (max_fl ? NO_MIN_RANGE : NO_MAX_RANGE)))
946 return 0;
947 return maxmin_in_range(max_fl, field, cond);
952 Check whether {MAX|MIN}(field) is in range specified by conditions.
954 @param[in] max_fl 0 for MIN(field) / 1 for MAX(field)
955 @param[in] field Field used the MIN/MAX expression
956 @param[in] cond WHERE condition
958 @retval
959 0 ok
960 @retval
961 1 WHERE was not true for the found row
964 static int maxmin_in_range(bool max_fl, Field* field, COND *cond)
966 /* If AND/OR condition */
967 if (cond->type() == Item::COND_ITEM)
969 List_iterator_fast<Item> li(*((Item_cond*) cond)->argument_list());
970 Item *item;
971 while ((item= li++))
973 if (maxmin_in_range(max_fl, field, item))
974 return 1;
976 return 0;
979 if (cond->used_tables() != field->table->map)
980 return 0;
981 bool less_fl= 0;
982 switch (((Item_func*) cond)->functype()) {
983 case Item_func::BETWEEN:
984 return cond->val_int() == 0; // Return 1 if WHERE is false
985 case Item_func::LT_FUNC:
986 case Item_func::LE_FUNC:
987 less_fl= 1;
988 case Item_func::GT_FUNC:
989 case Item_func::GE_FUNC:
991 Item *item= ((Item_func*) cond)->arguments()[1];
992 /* In case of 'const op item' we have to swap the operator */
993 if (!item->const_item())
994 less_fl= 1-less_fl;
996 We only have to check the expression if we are using an expression like
997 SELECT MAX(b) FROM t1 WHERE a=const AND b>const
998 not for
999 SELECT MAX(b) FROM t1 WHERE a=const AND b<const
1001 if (max_fl != less_fl)
1002 return cond->val_int() == 0; // Return 1 if WHERE is false
1003 return 0;
1005 case Item_func::EQ_FUNC:
1006 case Item_func::EQUAL_FUNC:
1007 break;
1008 default: // Keep compiler happy
1009 DBUG_ASSERT(1); // Impossible
1010 break;
1012 return 0;