1 /* Copyright (c) 2001, 2017, 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, version 2.0,
5    as published by the Free Software Foundation.
6 
7    This program is also distributed with certain software (including
8    but not limited to OpenSSL) that is licensed under separate terms,
9    as designated in a particular file or component or in included license
10    documentation.  The authors of MySQL hereby grant you an additional
11    permission to link the program and your derivative works with the
12    separately licensed software that they have included with MySQL.
13 
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License, version 2.0, for more details.
18 
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */
22 
23 /*
24   UNION  of select's
25   UNION's  were introduced by Monty and Sinisa <sinisa@mysql.com>
26 */
27 
28 
29 #include "sql_priv.h"
30 #include "unireg.h"
31 #include "sql_union.h"
32 #include "sql_select.h"
33 #include "sql_cursor.h"
34 #include "sql_base.h"                           // fill_record
35 #include "filesort.h"                           // filesort_free_buffers
36 #include "sql_tmp_table.h"                      // tmp tables
37 #include "sql_optimizer.h"                      // JOIN
38 #include "opt_explain_format.h"
39 
mysql_union(THD * thd,LEX * lex,select_result * result,SELECT_LEX_UNIT * unit,ulong setup_tables_done_option)40 bool mysql_union(THD *thd, LEX *lex, select_result *result,
41                  SELECT_LEX_UNIT *unit, ulong setup_tables_done_option)
42 {
43   bool res;
44   DBUG_ENTER("mysql_union");
45 
46   res= unit->prepare(thd, result,
47 		     SELECT_NO_UNLOCK | setup_tables_done_option);
48   if (res)
49     goto err;
50 
51 
52   /*
53     Tables are not locked at this point, it means that we have delayed
54     this step until after prepare stage (i.e. this moment). This allows to
55     do better partition pruning and avoid locking unused partitions.
56     As a consequence, in such a case, prepare stage can rely only on
57     metadata about tables used and not data from them.
58     We need to lock tables now in order to proceed with the remaning
59     stages of query optimization and execution.
60   */
61   DBUG_ASSERT(! thd->lex->is_query_tables_locked());
62   if (lock_tables(thd, lex->query_tables, lex->table_count, 0))
63     goto err;
64 
65   /*
66     Tables must be locked before storing the query in the query cache.
67     Transactional engines must been signalled that the statement started,
68     which external_lock signals.
69   */
70   query_cache_store_query(thd, thd->lex->query_tables);
71 
72   res= unit->optimize() || unit->exec();
73   res|= unit->cleanup();
74   DBUG_RETURN(res);
75 err:
76   (void) unit->cleanup();
77   DBUG_RETURN(true);
78 }
79 
80 
81 /***************************************************************************
82 ** store records in temporary table for UNION
83 ***************************************************************************/
84 
prepare(List<Item> & list,SELECT_LEX_UNIT * u)85 int select_union::prepare(List<Item> &list, SELECT_LEX_UNIT *u)
86 {
87   unit= u;
88   return 0;
89 }
90 
91 
send_data(List<Item> & values)92 bool select_union::send_data(List<Item> &values)
93 {
94   int error= 0;
95   if (unit->offset_limit_cnt)
96   {						// using limit offset,count
97     unit->offset_limit_cnt--;
98     return 0;
99   }
100   fill_record(thd, table->field, values, 1, NULL);
101   if (thd->is_error())
102     return 1;
103 
104   if ((error= table->file->ha_write_row(table->record[0])))
105   {
106     /* create_myisam_from_heap will generate error if needed */
107     if (table->file->is_fatal_error(error, HA_CHECK_DUP) &&
108         create_myisam_from_heap(thd, table, tmp_table_param.start_recinfo,
109                                 &tmp_table_param.recinfo, error, TRUE, NULL))
110       return 1;
111   }
112   return 0;
113 }
114 
115 
send_eof()116 bool select_union::send_eof()
117 {
118   return 0;
119 }
120 
121 
flush()122 bool select_union::flush()
123 {
124   int error;
125   if ((error=table->file->extra(HA_EXTRA_NO_CACHE)))
126   {
127     table->file->print_error(error, MYF(0));
128     return 1;
129   }
130   return 0;
131 }
132 
133 /*
134   Create a temporary table to store the result of select_union.
135 
136   SYNOPSIS
137     select_union::create_result_table()
138       thd                thread handle
139       column_types       a list of items used to define columns of the
140                          temporary table
141       is_union_distinct  if set, the temporary table will eliminate
142                          duplicates on insert
143       options            create options
144       table_alias        name of the temporary table
145       bit_fields_as_long convert bit fields to ulonglong
146 
147   DESCRIPTION
148     Create a temporary table that is used to store the result of a UNION,
149     derived table, or a materialized cursor.
150 
151   RETURN VALUE
152     0                    The table has been created successfully.
153     1                    create_tmp_table failed.
154 */
155 
156 bool
create_result_table(THD * thd_arg,List<Item> * column_types,bool is_union_distinct,ulonglong options,const char * table_alias,bool bit_fields_as_long,bool create_table)157 select_union::create_result_table(THD *thd_arg, List<Item> *column_types,
158                                   bool is_union_distinct, ulonglong options,
159                                   const char *table_alias,
160                                   bool bit_fields_as_long, bool create_table)
161 {
162   DBUG_ASSERT(table == 0);
163   tmp_table_param.init();
164   tmp_table_param.field_count= column_types->elements;
165   tmp_table_param.skip_create_table= !create_table;
166   tmp_table_param.bit_fields_as_long= bit_fields_as_long;
167 
168   if (! (table= create_tmp_table(thd_arg, &tmp_table_param, *column_types,
169                                  (ORDER*) 0, is_union_distinct, 1,
170                                  options, HA_POS_ERROR, (char*) table_alias)))
171     return TRUE;
172   if (create_table)
173   {
174     table->file->extra(HA_EXTRA_WRITE_CACHE);
175     table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
176   }
177   return FALSE;
178 }
179 
180 
181 /**
182   Reset and empty the temporary table that stores the materialized query result.
183 
184   @note The cleanup performed here is exactly the same as for the two temp
185   tables of JOIN - exec_tmp_table_[1 | 2].
186 */
187 
cleanup()188 void select_union::cleanup()
189 {
190   table->file->extra(HA_EXTRA_RESET_STATE);
191   table->file->ha_delete_all_rows();
192   free_io_cache(table);
193   filesort_free_buffers(table,0);
194 }
195 
196 
197 /**
198   Initialization procedures before fake_select_lex preparation()
199 
200   @param thd		 Thread handler
201   @param no_const_tables Skip reading const tables. TRUE for EXPLAIN.
202 
203   @returns
204     TRUE  OOM
205     FALSE Ok
206 */
207 
208 bool
init_prepare_fake_select_lex(THD * thd_arg,bool no_const_tables)209 st_select_lex_unit::init_prepare_fake_select_lex(THD *thd_arg,
210                                                  bool no_const_tables)
211 {
212   DBUG_ENTER("st_select_lex_unit::init_prepare_fake_select_lex");
213   thd_arg->lex->current_select= fake_select_lex;
214   fake_select_lex->table_list.link_in_list(&result_table_list,
215                                            &result_table_list.next_local);
216   fake_select_lex->context.table_list=
217     fake_select_lex->context.first_name_resolution_table=
218     fake_select_lex->get_table_list();
219   if (!fake_select_lex->first_execution)
220   {
221     for (ORDER *order= global_parameters->order_list.first;
222          order;
223          order= order->next)
224       order->item= &order->item_ptr;
225   }
226   for (ORDER *order= global_parameters->order_list.first;
227        order;
228        order=order->next)
229   {
230     (*order->item)->walk(&Item::change_context_processor, 0,
231                          (uchar*) &fake_select_lex->context);
232   }
233   if (!fake_select_lex->join)
234   {
235     /*
236       allocate JOIN for fake select only once (prevent
237       mysql_select automatic allocation)
238       TODO: The above is nonsense. mysql_select() will not allocate the
239       join if one already exists. There must be some other reason why we
240       don't let it allocate the join. Perhaps this is because we need
241       some special parameter values passed to join constructor?
242     */
243     if (!(fake_select_lex->join=
244         new JOIN(thd, item_list, fake_select_lex->options, result)))
245     {
246       fake_select_lex->table_list.empty();
247       DBUG_RETURN(true);
248     }
249     fake_select_lex->join->init(thd, item_list, fake_select_lex->options,
250                                 result);
251     fake_select_lex->join->no_const_tables= no_const_tables;
252 
253     /*
254       Fake st_select_lex should have item list for correct ref_array
255       allocation.
256     */
257     fake_select_lex->item_list= item_list;
258 
259     /*
260       We need to add up n_sum_items in order to make the correct
261       allocation in setup_ref_array().
262       Don't add more sum_items if we have already done JOIN::prepare
263       for this (with a different join object)
264     */
265     if (fake_select_lex->ref_pointer_array.is_null())
266       fake_select_lex->n_child_sum_items+= global_parameters->n_sum_items;
267   }
268   DBUG_RETURN(false);
269 }
270 
271 
prepare(THD * thd_arg,select_result * sel_result,ulong additional_options)272 bool st_select_lex_unit::prepare(THD *thd_arg, select_result *sel_result,
273                                  ulong additional_options)
274 {
275   SELECT_LEX *lex_select_save= thd_arg->lex->current_select;
276   SELECT_LEX *sl, *first_sl= first_select();
277   select_result *tmp_result;
278   bool is_union_select;
279   DBUG_ENTER("st_select_lex_unit::prepare");
280 
281   describe= MY_TEST(additional_options & SELECT_DESCRIBE);
282 
283   /*
284     result object should be reassigned even if preparing already done for
285     max/min subquery (ALL/ANY optimization)
286   */
287   result= sel_result;
288 
289   if (prepared)
290   {
291     if (describe)
292     {
293       /* fast reinit for EXPLAIN */
294       for (sl= first_sl; sl; sl= sl->next_select())
295       {
296         sl->join->result= result;
297         select_limit_cnt= HA_POS_ERROR;
298         offset_limit_cnt= 0;
299         if (result->prepare(sl->join->fields_list, this))
300         {
301           DBUG_RETURN(TRUE);
302         }
303         sl->join->select_options|= SELECT_DESCRIBE;
304         sl->join->reset();
305       }
306       if (fake_select_lex->join)
307         fake_select_lex->join->result= result;
308     }
309     DBUG_RETURN(FALSE);
310   }
311   prepared= 1;
312   saved_error= FALSE;
313 
314   thd_arg->lex->current_select= sl= first_sl;
315   found_rows_for_union= first_sl->options & OPTION_FOUND_ROWS;
316   is_union_select= is_union() || fake_select_lex;
317 
318   /* Global option */
319 
320   if (is_union_select)
321   {
322     if (!(tmp_result= union_result= new select_union))
323       goto err;
324     if (describe)
325       tmp_result= sel_result;
326   }
327   else
328     tmp_result= sel_result;
329 
330   sl->context.resolve_in_select_list= TRUE;
331 
332   for (;sl; sl= sl->next_select())
333   {
334     bool can_skip_order_by;
335     sl->options|=  SELECT_NO_UNLOCK;
336     JOIN *join= new JOIN(thd_arg, sl->item_list,
337 			 sl->options | thd_arg->variables.option_bits | additional_options,
338 			 tmp_result);
339     /*
340       setup_tables_done_option should be set only for very first SELECT,
341       because it protect from secont setup_tables call for select-like non
342       select commands (DELETE/INSERT/...) and they use only very first
343       SELECT (for union it can be only INSERT ... SELECT).
344     */
345     additional_options&= ~OPTION_SETUP_TABLES_DONE;
346     if (!join)
347       goto err;
348 
349     thd_arg->lex->current_select= sl;
350 
351     can_skip_order_by= is_union_select && !(sl->braces && sl->explicit_limit);
352 
353     saved_error= join->prepare(sl->table_list.first,
354                                sl->with_wild,
355                                sl->where,
356                                (can_skip_order_by ? 0 :
357                                 sl->order_list.elements) +
358                                sl->group_list.elements,
359                                can_skip_order_by ?
360                                NULL : sl->order_list.first,
361                                sl->group_list.first,
362                                sl->having,
363                                sl, this);
364     /* There are no * in the statement anymore (for PS) */
365     sl->with_wild= 0;
366 
367     if (saved_error || (saved_error= thd_arg->is_fatal_error))
368       goto err;
369     /*
370       Use items list of underlaid select for derived tables to preserve
371       information about fields lengths and exact types
372     */
373     if (!is_union_select)
374       types= first_sl->item_list;
375     else if (sl == first_sl)
376     {
377       types.empty();
378       List_iterator_fast<Item> it(sl->item_list);
379       Item *item_tmp;
380       while ((item_tmp= it++))
381       {
382         /*
383           If the outer query has a GROUP BY clause, an outer reference to this
384           query block may have been wrapped in a Item_outer_ref, which has not
385           been fixed yet. An Item_type_holder must be created based on a fixed
386           Item, so use the inner Item instead.
387         */
388         DBUG_ASSERT(item_tmp->fixed ||
389                     (item_tmp->type() == Item::REF_ITEM &&
390                      ((Item_ref *)(item_tmp))->ref_type() ==
391                      Item_ref::OUTER_REF));
392         if (!item_tmp->fixed)
393           item_tmp= item_tmp->real_item();
394 
395 	/* Error's in 'new' will be detected after loop */
396 	types.push_back(new Item_type_holder(thd_arg, item_tmp));
397       }
398 
399       if (thd_arg->is_fatal_error)
400 	goto err; // out of memory
401     }
402     else
403     {
404       if (types.elements != sl->item_list.elements)
405       {
406 	my_message(ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT,
407 		   ER(ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT),MYF(0));
408 	goto err;
409       }
410       List_iterator_fast<Item> it(sl->item_list);
411       List_iterator_fast<Item> tp(types);
412       Item *type, *item_tmp;
413       while ((type= tp++, item_tmp= it++))
414       {
415         if (((Item_type_holder*)type)->join_types(thd_arg, item_tmp))
416 	  DBUG_RETURN(TRUE);
417       }
418     }
419   }
420 
421   if (is_union_select)
422   {
423     /*
424       Check that it was possible to aggregate
425       all collations together for UNION.
426       We need this in case of UNION DISTINCT, to filter
427       out duplicates using the proper collation.
428 
429       TODO: consider removing this test in case of UNION ALL.
430     */
431     List_iterator_fast<Item> tp(types);
432     Item *type;
433     ulonglong create_options;
434 
435     while ((type= tp++))
436     {
437       if (type->result_type() == STRING_RESULT &&
438           type->collation.derivation == DERIVATION_NONE)
439       {
440         my_error(ER_CANT_AGGREGATE_NCOLLATIONS, MYF(0), "UNION");
441         goto err;
442       }
443     }
444 
445     /*
446       Disable the usage of fulltext searches in the last union branch.
447       This is a temporary 5.x limitation because of the way the fulltext
448       search functions are handled by the optimizer.
449       This is manifestation of the more general problems of "taking away"
450       parts of a SELECT statement post-fix_fields(). This is generally not
451       doable since various flags are collected in various places (e.g.
452       SELECT_LEX) that carry information about the presence of certain
453       expressions or constructs in the parts of the query.
454       When part of the query is taken away it's not clear how to "divide"
455       the meaning of these accumulated flags and what to carry over to the
456       recipient query (SELECT_LEX).
457     */
458     if (global_parameters->ftfunc_list->elements &&
459         global_parameters->order_list.elements &&
460         global_parameters != fake_select_lex)
461     {
462       ORDER *ord;
463       Item_func::Functype ft=  Item_func::FT_FUNC;
464       for (ord= global_parameters->order_list.first; ord; ord= ord->next)
465         if ((*ord->item)->walk (&Item::find_function_processor, FALSE,
466                                 (uchar *) &ft))
467         {
468           my_error (ER_CANT_USE_OPTION_HERE, MYF(0), "MATCH()");
469           goto err;
470         }
471     }
472 
473 
474     create_options= (first_sl->options | thd_arg->variables.option_bits |
475                      TMP_TABLE_ALL_COLUMNS);
476     /*
477       Force the temporary table to be a MyISAM table if we're going to use
478       fullext functions (MATCH ... AGAINST .. IN BOOLEAN MODE) when reading
479       from it (this should be removed in 5.2 when fulltext search is moved
480       out of MyISAM).
481     */
482     if (global_parameters->ftfunc_list->elements)
483       create_options= create_options | TMP_TABLE_FORCE_MYISAM;
484 
485     if (union_result->create_result_table(thd, &types, MY_TEST(union_distinct),
486                                           create_options, "", FALSE, TRUE))
487       goto err;
488     memset(&result_table_list, 0, sizeof(result_table_list));
489     result_table_list.db= (char*) "";
490     result_table_list.table_name= result_table_list.alias= (char*) "union";
491     result_table_list.table= table= union_result->table;
492 
493     thd_arg->lex->current_select= lex_select_save;
494     if (!item_list.elements)
495     {
496       {
497         Prepared_stmt_arena_holder ps_arena_holder(thd);
498 
499         saved_error= table->fill_item_list(&item_list);
500 
501         if (saved_error)
502           goto err;
503       }
504 
505       if (thd->stmt_arena->is_stmt_prepare())
506       {
507         /* Validate the global parameters of this union */
508         init_prepare_fake_select_lex(thd, false);
509 
510 	saved_error= fake_select_lex->join->
511 	  prepare(fake_select_lex->table_list.first, // tables_init
512                   0,                                 // wild_num
513                   0,                                 // conds_init
514                   global_parameters->order_list.elements, // og_num
515                   global_parameters->order_list.first,    // order
516                   NULL,                                // group_init
517                   NULL,                                // having_init
518                   fake_select_lex,                     // select_lex_arg
519                   this);                               // unit_arg
520 	fake_select_lex->table_list.empty();
521       }
522     }
523     else
524     {
525       /*
526         We're in execution of a prepared statement or stored procedure:
527         reset field items to point at fields from the created temporary table.
528       */
529       table->reset_item_list(&item_list);
530     }
531   }
532 
533   thd_arg->lex->current_select= lex_select_save;
534 
535   DBUG_RETURN(saved_error || thd_arg->is_fatal_error);
536 
537 err:
538   thd_arg->lex->current_select= lex_select_save;
539   (void) cleanup();
540   DBUG_RETURN(TRUE);
541 }
542 
543 
544 /**
545   Run optimization phase.
546 
547   @return FALSE unit successfully passed optimization phase.
548   @return TRUE an error occur.
549 */
550 
optimize()551 bool st_select_lex_unit::optimize()
552 {
553   DBUG_ENTER("st_select_lex_unit::optimize");
554 
555   if (optimized && item && item->assigned() && !uncacheable && !describe)
556     DBUG_RETURN(FALSE);
557 
558   for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
559   {
560     DBUG_ASSERT(sl->join);
561     if (optimized)
562     {
563       saved_error= false;
564       sl->join->reset();
565     }
566     else
567     {
568       SELECT_LEX *lex_select_save= thd->lex->current_select;
569       thd->lex->current_select= sl;
570       set_limit(sl);
571       if ((sl == global_parameters && is_union()) || describe)
572       {
573         offset_limit_cnt= 0;
574         /*
575           We can't use LIMIT at this stage if we are using ORDER BY for the
576           whole UNION.
577         */
578         if (sl->order_list.first || describe)
579           select_limit_cnt= HA_POS_ERROR;
580       }
581 
582       /*
583         When using braces, SQL_CALC_FOUND_ROWS affects the whole query:
584         we don't calculate found_rows() per union part.
585         Otherwise, SQL_CALC_FOUND_ROWS should be done on all sub parts.
586       */
587       sl->join->select_options=
588         (select_limit_cnt == HA_POS_ERROR || sl->braces) ?
589         sl->options & ~OPTION_FOUND_ROWS : sl->options | found_rows_for_union;
590 
591       saved_error= sl->join->optimize();
592       /*
593         Accumulate estimated number of rows.
594         1. Implicitly grouped query has one row (with HAVING it has zero or one
595            rows).
596         2. If GROUP BY clause is optimized away because it was a constant then
597            query produces at most one row.
598       */
599       result->estimated_rowcount+=
600         (sl->with_sum_func && sl->group_list.elements == 0) ||
601         sl->join->group_optimized_away ?
602           1 : sl->join->best_rowcount;
603 
604       thd->lex->current_select= lex_select_save;
605     }
606     if (saved_error)
607       break;
608   }
609   if (!saved_error)
610     optimized= 1;
611 
612   DBUG_RETURN(saved_error);
613 }
614 
615 
616 /**
617   Explain UNION.
618 */
619 
explain()620 bool st_select_lex_unit::explain()
621 {
622   SELECT_LEX *lex_select_save= thd->lex->current_select;
623   Explain_format *fmt= thd->lex->explain_format;
624   DBUG_ENTER("st_select_lex_unit::explain");
625   JOIN *join;
626   bool ret= false;
627 
628   DBUG_ASSERT((is_union() || fake_select_lex) && describe && optimized);
629   executed= true;
630 
631   if (fmt->begin_context(CTX_UNION))
632     DBUG_RETURN(true);
633 
634   for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
635   {
636     if (fmt->begin_context(CTX_QUERY_SPEC))
637       DBUG_RETURN(true);
638     DBUG_ASSERT(sl->join);
639     if (sl->join->explain() || thd->is_error())
640       DBUG_RETURN(true);
641     if (fmt->end_context(CTX_QUERY_SPEC))
642       DBUG_RETURN(true);
643   }
644 
645   if (init_prepare_fake_select_lex(thd, true))
646     DBUG_RETURN(true);
647 
648   if (thd->is_fatal_error)
649     DBUG_RETURN(true);
650   join= fake_select_lex->join;
651 
652   /*
653     In EXPLAIN command, constant subqueries that do not use any
654     tables are executed two times:
655      - 1st time is a real evaluation to get the subquery value
656      - 2nd time is to produce EXPLAIN output rows.
657     1st execution sets certain members (e.g. select_result) to perform
658     subquery execution rather than EXPLAIN line production. In order
659     to reset them back, we re-do all of the actions (yes it is ugly).
660   */
661   if (!join->optimized || !join->tables)
662   {
663     saved_error= mysql_select(thd,
664                           &result_table_list,
665                           0, item_list, NULL,
666                           &global_parameters->order_list,
667                           NULL, NULL,
668                           fake_select_lex->options | SELECT_NO_UNLOCK,
669                           result, this, fake_select_lex);
670   }
671   else
672     ret= join->explain();
673 
674   thd->lex->current_select= lex_select_save;
675 
676   if (saved_error || ret || thd->is_error())
677     DBUG_RETURN(true);
678   fmt->end_context(CTX_UNION);
679 
680   DBUG_RETURN(false);
681 }
682 
683 
684 /**
685   Execute UNION.
686 */
687 
exec()688 bool st_select_lex_unit::exec()
689 {
690   SELECT_LEX *lex_select_save= thd->lex->current_select;
691   ulonglong add_rows=0;
692   ha_rows examined_rows= 0;
693   DBUG_ENTER("st_select_lex_unit::exec");
694   DBUG_ASSERT((is_union() || fake_select_lex) && !describe && optimized);
695 
696   if (executed && !uncacheable)
697     DBUG_RETURN(false);
698   executed= true;
699 
700   if (uncacheable || !item || !item->assigned())
701   {
702     if (item)
703       item->reset_value_registration();
704     if (optimized && item)
705     {
706       if (item->assigned())
707       {
708         item->assigned(0); // We will reinit & rexecute unit
709         item->reset();
710         table->file->ha_delete_all_rows();
711       }
712       /* re-enabling indexes for next subselect iteration */
713       if (union_distinct && table->file->ha_enable_indexes(HA_KEY_SWITCH_ALL))
714       {
715         DBUG_ASSERT(0);
716       }
717     }
718 
719     for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
720     {
721       ha_rows records_at_start= 0;
722       DBUG_ASSERT(sl->join);
723       thd->lex->current_select= sl;
724 
725       set_limit(sl);
726       if (sl == global_parameters || describe)
727       {
728         offset_limit_cnt= 0;
729         /*
730           We can't use LIMIT at this stage if we are using ORDER BY for the
731           whole query
732         */
733         if (sl->order_list.first || describe)
734           select_limit_cnt= HA_POS_ERROR;
735       }
736       if (!saved_error)
737       {
738         records_at_start= table->file->stats.records;
739         sl->join->exec();
740         if (sl == union_distinct)
741         {
742           if (table->file->ha_disable_indexes(HA_KEY_SWITCH_ALL))
743             DBUG_RETURN(true);
744           table->no_keyread=1;
745         }
746         saved_error= sl->join->error;
747         offset_limit_cnt= (ha_rows)(sl->offset_limit ?
748                                     sl->offset_limit->val_uint() :
749                                     0);
750         if (!saved_error)
751         {
752           /*
753             Save the current examined row count locally and clear the global
754             counter, so that we can accumulate the number of evaluated rows for
755             the current query block.
756           */
757 	  examined_rows+= thd->get_examined_row_count();
758           thd->set_examined_row_count(0);
759 
760           if (union_result->flush())
761           {
762             thd->lex->current_select= lex_select_save;
763             DBUG_RETURN(true);
764           }
765         }
766       }
767       if (saved_error)
768       {
769         thd->lex->current_select= lex_select_save;
770         DBUG_RETURN(saved_error);
771       }
772       /* Needed for the following test and for records_at_start in next loop */
773       int error= table->file->info(HA_STATUS_VARIABLE);
774       if(error)
775       {
776         table->file->print_error(error, MYF(0));
777         DBUG_RETURN(true);
778       }
779       if (found_rows_for_union && !sl->braces &&
780           select_limit_cnt != HA_POS_ERROR)
781       {
782         /*
783           This is a union without braces. Remember the number of rows that
784           could also have been part of the result set.
785           We get this from the difference of between total number of possible
786           rows and actual rows added to the temporary table.
787         */
788         add_rows+= (ulonglong) (thd->limit_found_rows -
789                    (ulonglong)(table->file->stats.records - records_at_start));
790       }
791     }
792   }
793 
794   if (!saved_error && !thd->is_fatal_error)
795   {
796     /* Send result to 'result' */
797     saved_error= true;
798     List<Item_func_match> empty_list;
799     empty_list.empty();
800 
801     set_limit(global_parameters);
802     if (init_prepare_fake_select_lex(thd, true))
803       DBUG_RETURN(true);
804     JOIN *join= fake_select_lex->join;
805     if (!join->optimized)
806     {
807       saved_error=
808         mysql_select(thd,
809                      &result_table_list,      // tables
810                      0,                       // wild_num
811                      item_list,               // fields
812                      NULL,                    // conds
813                      &global_parameters->order_list,    // order
814                      NULL,                    // group
815                      NULL,                    // having
816                      fake_select_lex->options | SELECT_NO_UNLOCK,
817                      result,                  // result
818                      this,                    // unit
819                      fake_select_lex);        // select_lex
820     }
821     else
822     {
823       join->examined_rows= 0;
824       saved_error= false;
825       join->reset();
826       join->exec();
827     }
828 
829     fake_select_lex->table_list.empty();
830   }
831   if (!saved_error && !thd->is_fatal_error)
832   {
833 
834     thd->limit_found_rows = (ulonglong)table->file->stats.records + add_rows;
835     thd->inc_examined_row_count(examined_rows);
836   }
837   thd->lex->current_select= lex_select_save;
838   DBUG_RETURN(saved_error);
839 }
840 
841 
842 /**
843   Cleanup this query expression object after preparation or one round
844   of execution. After the cleanup, the object can be reused for a
845   new round of execution, but a new optimization will be needed before
846   the execution.
847 
848   @return false if previous execution was successful, and true otherwise
849 */
850 
cleanup()851 bool st_select_lex_unit::cleanup()
852 {
853   bool error= false;
854   DBUG_ENTER("st_select_lex_unit::cleanup");
855 
856   if (cleaned)
857   {
858     DBUG_RETURN(FALSE);
859   }
860   cleaned= true;
861 
862   for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
863     error|= sl->cleanup();
864 
865   cleanup_level();
866 
867   DBUG_RETURN(error);
868 }
869 
870 
871 /**
872   Cleanup only this select_lex_unit after preparation or one round of
873   execution.
874 
875   @return false if previous execution was successful, and true otherwise
876 */
cleanup_level()877 bool st_select_lex_unit::cleanup_level()
878 {
879   bool error= false;
880 
881   if (fake_select_lex)
882   {
883     error|= fake_select_lex->cleanup();
884     /*
885       There are two cases when we should clean order items:
886       1. UNION with SELECTs which all enclosed into braces
887         in this case global_parameters == fake_select_lex
888       2. UNION where last SELECT is not enclosed into braces
889         in this case global_parameters == 'last select'
890       So we should use global_parameters->order_list for
891       proper order list clean up.
892       Note: global_parameters and fake_select_lex are always
893             initialized for UNION
894     */
895     DBUG_ASSERT(global_parameters);
896     if (global_parameters->order_list.elements)
897     {
898       ORDER *ord;
899       for (ord= global_parameters->order_list.first; ord; ord= ord->next)
900         (*ord->item)->walk (&Item::cleanup_processor, 0, 0);
901     }
902   }
903 
904   if (union_result)
905   {
906     delete union_result;
907     union_result=0; // Safety
908     if (table)
909       free_tmp_table(thd, table);
910     table= 0; // Safety
911   }
912 
913   explain_marker= CTX_NONE;
914 
915   return error;
916 }
917 
918 
reinit_exec_mechanism()919 void st_select_lex_unit::reinit_exec_mechanism()
920 {
921   prepared= optimized= executed= 0;
922 #ifndef DBUG_OFF
923   if (is_union())
924   {
925     List_iterator_fast<Item> it(item_list);
926     Item *field;
927     while ((field= it++))
928     {
929       /*
930 	we can't cleanup here, because it broke link to temporary table field,
931 	but have to drop fixed flag to allow next fix_field of this field
932 	during re-executing
933       */
934       field->fixed= 0;
935     }
936   }
937 #endif
938 }
939 
940 
941 /*
942   change select_result object of unit
943 
944   SYNOPSIS
945     st_select_lex_unit::change_result()
946     result	new select_result object
947     old_result	old select_result object
948 
949   RETURN
950     FALSE - OK
951     TRUE  - error
952 */
953 
change_result(select_result_interceptor * new_result,select_result_interceptor * old_result)954 bool st_select_lex_unit::change_result(select_result_interceptor *new_result,
955                                        select_result_interceptor *old_result)
956 {
957   bool res= FALSE;
958   for (SELECT_LEX *sl= first_select(); sl; sl= sl->next_select())
959   {
960     if (sl->join && sl->join->result == old_result)
961       if (sl->join->change_result(new_result))
962 	return TRUE;
963   }
964   if (fake_select_lex && fake_select_lex->join)
965     res= fake_select_lex->join->change_result(new_result);
966   return (res);
967 }
968 
969 /*
970   Get column type information for this unit.
971 
972   SYNOPSIS
973     st_select_lex_unit::get_unit_column_types()
974 
975   DESCRIPTION
976     For a single-select the column types are taken
977     from the list of selected items. For a union this function
978     assumes that st_select_lex_unit::prepare has been called
979     and returns the type holders that were created for unioned
980     column types of all selects.
981 
982   NOTES
983     The implementation of this function should be in sync with
984     st_select_lex_unit::prepare()
985 */
986 
get_unit_column_types()987 List<Item> *st_select_lex_unit::get_unit_column_types()
988 {
989   if (is_union())
990   {
991     DBUG_ASSERT(prepared);
992     /* Types are generated during prepare */
993     return &types;
994   }
995 
996   return &first_select()->item_list;
997 }
998 
999 
1000 /**
1001   Get field list for this query expression.
1002 
1003   For a UNION of query blocks, return the field list generated
1004   during prepare.
1005   For a single query block, return the field list after all possible
1006   intermediate query processing steps are completed.
1007 
1008   @returns List containing fields of the query expression.
1009 */
1010 
get_field_list()1011 List<Item> *st_select_lex_unit::get_field_list()
1012 {
1013   if (is_union())
1014   {
1015     DBUG_ASSERT(prepared);
1016     /* Types are generated during prepare */
1017     return &types;
1018   }
1019 
1020   return first_select()->join->fields;
1021 }
1022 
1023 
1024 /**
1025   Cleanup after preparation or one round of execution.
1026 
1027   @return false if previous execution was successful, and true otherwise
1028 */
1029 
cleanup()1030 bool st_select_lex::cleanup()
1031 {
1032   bool error= FALSE;
1033   DBUG_ENTER("st_select_lex::cleanup()");
1034 
1035   error= cleanup_level();
1036   for (SELECT_LEX_UNIT *lex_unit= first_inner_unit(); lex_unit;
1037        lex_unit= lex_unit->next_unit())
1038   {
1039     error|= lex_unit->cleanup();
1040   }
1041 
1042   DBUG_RETURN(error);
1043 }
1044 
1045 
1046 /**
1047   Cleanup only this select_lex after preparation or one round of
1048   execution.
1049 
1050   @return false if previous execution was successful, and true otherwise
1051 */
cleanup_level()1052 bool st_select_lex::cleanup_level()
1053 {
1054   bool error= FALSE;
1055 
1056   if (join)
1057   {
1058     DBUG_ASSERT((st_select_lex*)join->select_lex == this);
1059     error= join->destroy();
1060     delete join;
1061     join= 0;
1062   }
1063 
1064   cur_pos_in_all_fields= ALL_FIELDS_UNDEF_POS;
1065   non_agg_fields.empty();
1066   inner_refs_list.empty();
1067 
1068   return error;
1069 }
1070 
1071 
cleanup_all_joins(bool full)1072 void st_select_lex::cleanup_all_joins(bool full)
1073 {
1074   SELECT_LEX_UNIT *unit;
1075   SELECT_LEX *sl;
1076 
1077   if (join)
1078     join->cleanup(full);
1079 
1080   for (unit= first_inner_unit(); unit; unit= unit->next_unit())
1081     for (sl= unit->first_select(); sl; sl= sl->next_select())
1082       sl->cleanup_all_joins(full);
1083 }
1084