~drizzle-trunk/drizzle/development

1 by brian
clean slate
1
/* Copyright (C) 2000 MySQL AB
2
3
   This program is free software; you can redistribute it and/or modify
4
   it under the terms of the GNU General Public License as published by
5
   the Free Software Foundation; version 2 of the License.
6
7
   This program is distributed in the hope that it will be useful,
8
   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
   GNU General Public License for more details.
11
12
   You should have received a copy of the GNU General Public License
13
   along with this program; if not, write to the Free Software
14
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
15
16
/**
17
  @file
18
19
  @brief
20
  subselect Item
21
22
  @todo
23
    - add function from mysql_select that use JOIN* as parameter to JOIN
24
    methods (sql_select.h/sql_select.cc)
25
*/
243.1.17 by Jay Pipes
FINAL PHASE removal of mysql_priv.h (Bye, bye my friend.)
26
#include <drizzled/server_includes.h>
27
#include <drizzled/sql_select.h>
549 by Monty Taylor
Took gettext.h out of header files.
28
#include <drizzled/error.h>
675 by Brian Aker
Cleanup around item includes.
29
#include <drizzled/item/cache.h>
584.4.7 by Monty Taylor
Removed a big bank of includes from item.h.
30
#include <drizzled/item/subselect.h>
31
#include <drizzled/item/cmpfunc.h>
642.1.18 by Lee
header file clean up
32
#include <drizzled/item/ref_null_helper.h>
584.4.10 by Monty Taylor
Broke out cached_item.
33
#include <drizzled/cached_item.h>
670.2.4 by Monty Taylor
Removed more stuff from the headers.
34
#include <drizzled/check_stack_overrun.h>
675 by Brian Aker
Cleanup around item includes.
35
#include <drizzled/item/ref_null_helper.h>
36
#include <drizzled/item/direct_ref.h>
1 by brian
clean slate
37
38
inline Item * and_items(Item* cond, Item *item)
39
{
40
  return (cond? (new Item_cond_and(cond, item)) : item);
41
}
42
43
Item_subselect::Item_subselect():
520.1.22 by Brian Aker
Second pass of thd cleanup
44
  Item_result_field(), value_assigned(0), session(0), substitution(0),
1 by brian
clean slate
45
  engine(0), old_engine(0), used_tables_cache(0), have_to_be_excluded(0),
46
  const_item_cache(1), engine_changed(0), changed(0),
55 by brian
Update for using real bool types.
47
  is_correlated(false)
1 by brian
clean slate
48
{
49
  with_subselect= 1;
50
  reset();
51
  /*
52
    Item value is NULL if select_result_interceptor didn't change this value
53
    (i.e. some rows will be found returned)
54
  */
55
  null_value= 1;
56
}
57
58
846 by Brian Aker
Removing on typedeffed class.
59
void Item_subselect::init(Select_Lex *select_lex,
1 by brian
clean slate
60
			  select_result_interceptor *result)
61
{
62
  /*
63
    Please see Item_singlerow_subselect::invalidate_and_restore_select_lex(),
64
    which depends on alterations to the parse tree implemented here.
65
  */
66
67
  unit= select_lex->master_unit();
68
69
  if (unit->item)
70
  {
71
    /*
72
      Item can be changed in JOIN::prepare while engine in JOIN::optimize
73
      => we do not copy old_engine here
74
    */
75
    engine= unit->item->engine;
76
    parsing_place= unit->item->parsing_place;
77
    unit->item->engine= 0;
78
    unit->item= this;
79
    engine->change_result(this, result);
80
  }
81
  else
82
  {
846 by Brian Aker
Removing on typedeffed class.
83
    Select_Lex *outer_select= unit->outer_select();
1 by brian
clean slate
84
    /*
85
      do not take into account expression inside aggregate functions because
86
      they can access original table fields
87
    */
88
    parsing_place= (outer_select->in_sum_expr ?
89
                    NO_MATTER :
90
                    outer_select->parsing_place);
91
    if (unit->is_union())
92
      engine= new subselect_union_engine(unit, result, this);
93
    else
94
      engine= new subselect_single_select_engine(select_lex, result, this);
95
  }
96
  {
846 by Brian Aker
Removing on typedeffed class.
97
    Select_Lex *upper= unit->outer_select();
1 by brian
clean slate
98
    if (upper->parsing_place == IN_HAVING)
99
      upper->subquery_in_having= 1;
100
  }
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
101
  return;
1 by brian
clean slate
102
}
103
846 by Brian Aker
Removing on typedeffed class.
104
Select_Lex *
1 by brian
clean slate
105
Item_subselect::get_select_lex()
106
{
107
  return unit->first_select();
108
}
109
110
void Item_subselect::cleanup()
111
{
112
  Item_result_field::cleanup();
113
  if (old_engine)
114
  {
115
    if (engine)
116
      engine->cleanup();
117
    engine= old_engine;
118
    old_engine= 0;
119
  }
120
  if (engine)
121
    engine->cleanup();
122
  reset();
123
  value_assigned= 0;
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
124
  return;
1 by brian
clean slate
125
}
126
127
void Item_singlerow_subselect::cleanup()
128
{
129
  value= 0; row= 0;
130
  Item_subselect::cleanup();
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
131
  return;
1 by brian
clean slate
132
}
133
134
135
void Item_in_subselect::cleanup()
136
{
1101.1.16 by Monty Taylor
Reverted 1103
137
  if (left_expr_cache)
1 by brian
clean slate
138
  {
1101.1.16 by Monty Taylor
Reverted 1103
139
    left_expr_cache->delete_elements();
140
    delete left_expr_cache;
141
    left_expr_cache= NULL;
1 by brian
clean slate
142
  }
55 by brian
Update for using real bool types.
143
  first_execution= true;
1 by brian
clean slate
144
  Item_subselect::cleanup();
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
145
  return;
1 by brian
clean slate
146
}
147
148
Item_subselect::~Item_subselect()
149
{
150
  delete engine;
151
}
152
153
Item_subselect::trans_res
779.1.27 by Monty Taylor
Got rid of __attribute__((unused)) and the like from the .cc files.
154
Item_subselect::select_transformer(JOIN *)
1 by brian
clean slate
155
{
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
156
  return(RES_OK);
1 by brian
clean slate
157
}
158
159
520.1.22 by Brian Aker
Second pass of thd cleanup
160
bool Item_subselect::fix_fields(Session *session_param, Item **ref)
1 by brian
clean slate
161
{
520.1.22 by Brian Aker
Second pass of thd cleanup
162
  char const *save_where= session_param->where;
206 by Brian Aker
Removed final uint dead types.
163
  uint8_t uncacheable;
1 by brian
clean slate
164
  bool res;
165
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
166
  assert(fixed == 0);
520.1.22 by Brian Aker
Second pass of thd cleanup
167
  engine->set_session((session= session_param));
1 by brian
clean slate
168
520.1.22 by Brian Aker
Second pass of thd cleanup
169
  if (check_stack_overrun(session, STACK_MIN_SIZE, (unsigned char*)&res))
55 by brian
Update for using real bool types.
170
    return true;
1 by brian
clean slate
171
172
  res= engine->prepare();
173
174
  // all transformation is done (used by prepared statements)
175
  changed= 1;
176
177
  if (!res)
178
  {
179
    /*
180
      Substitute the current item with an Item_in_optimizer that was
181
      created by Item_in_subselect::select_in_like_transformer and
182
      call fix_fields for the substituted item which in turn calls
183
      engine->prepare for the subquery predicate.
184
    */
185
    if (substitution)
186
    {
187
      int ret= 0;
188
189
      // did we changed top item of WHERE condition
190
      if (unit->outer_select()->where == (*ref))
191
	unit->outer_select()->where= substitution; // correct WHERE for PS
192
      else if (unit->outer_select()->having == (*ref))
193
	unit->outer_select()->having= substitution; // correct HAVING for PS
194
195
      (*ref)= substitution;
196
      substitution->name= name;
197
      if (have_to_be_excluded)
198
	engine->exclude();
199
      substitution= 0;
520.1.22 by Brian Aker
Second pass of thd cleanup
200
      session->where= "checking transformed subquery";
1 by brian
clean slate
201
      if (!(*ref)->fixed)
520.1.22 by Brian Aker
Second pass of thd cleanup
202
	ret= (*ref)->fix_fields(session, ref);
203
      session->where= save_where;
1 by brian
clean slate
204
      return ret;
205
    }
206
    // Is it one field subselect?
207
    if (engine->cols() > max_columns)
208
    {
209
      my_error(ER_OPERAND_COLUMNS, MYF(0), 1);
55 by brian
Update for using real bool types.
210
      return true;
1 by brian
clean slate
211
    }
212
    fix_length_and_dec();
213
  }
214
  else
215
    goto err;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
216
1 by brian
clean slate
217
  if ((uncacheable= engine->uncacheable()))
218
  {
219
    const_item_cache= 0;
220
    if (uncacheable & UNCACHEABLE_RAND)
221
      used_tables_cache|= RAND_TABLE_BIT;
222
  }
223
  fixed= 1;
224
225
err:
520.1.22 by Brian Aker
Second pass of thd cleanup
226
  session->where= save_where;
1 by brian
clean slate
227
  return res;
228
}
229
230
231
bool Item_subselect::walk(Item_processor processor, bool walk_subquery,
481 by Brian Aker
Remove all of uchar.
232
                          unsigned char *argument)
1 by brian
clean slate
233
{
234
235
  if (walk_subquery)
236
  {
846 by Brian Aker
Removing on typedeffed class.
237
    for (Select_Lex *lex= unit->first_select(); lex; lex= lex->next_select())
1 by brian
clean slate
238
    {
239
      List_iterator<Item> li(lex->item_list);
240
      Item *item;
327.2.3 by Brian Aker
Refactoring of class Table
241
      order_st *order;
1 by brian
clean slate
242
243
      if (lex->where && (lex->where)->walk(processor, walk_subquery, argument))
244
        return 1;
245
      if (lex->having && (lex->having)->walk(processor, walk_subquery,
246
                                             argument))
247
        return 1;
248
249
      while ((item=li++))
250
      {
251
        if (item->walk(processor, walk_subquery, argument))
252
          return 1;
253
      }
327.2.3 by Brian Aker
Refactoring of class Table
254
      for (order= (order_st*) lex->order_list.first ; order; order= order->next)
1 by brian
clean slate
255
      {
256
        if ((*order->item)->walk(processor, walk_subquery, argument))
257
          return 1;
258
      }
327.2.3 by Brian Aker
Refactoring of class Table
259
      for (order= (order_st*) lex->group_list.first ; order; order= order->next)
1 by brian
clean slate
260
      {
261
        if ((*order->item)->walk(processor, walk_subquery, argument))
262
          return 1;
263
      }
264
    }
265
  }
266
  return (this->*processor)(argument);
267
}
268
269
270
bool Item_subselect::exec()
271
{
272
  int res;
273
520.1.22 by Brian Aker
Second pass of thd cleanup
274
  if (session->is_error())
1 by brian
clean slate
275
  /* Do not execute subselect in case of a fatal error */
276
    return 1;
277
278
  res= engine->exec();
279
280
  if (engine_changed)
281
  {
282
    engine_changed= 0;
283
    return exec();
284
  }
285
  return (res);
286
}
287
288
289
/*
290
  Compute the IN predicate if the left operand's cache changed.
291
*/
292
293
bool Item_in_subselect::exec()
294
{
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
295
  assert(exec_method != MATERIALIZATION ||
1 by brian
clean slate
296
              (exec_method == MATERIALIZATION &&
297
               engine->engine_type() == subselect_engine::HASH_SJ_ENGINE));
298
  /*
299
    Initialize the cache of the left predicate operand. This has to be done as
300
    late as now, because Cached_item directly contains a resolved field (not
301
    an item, and in some cases (when temp tables are created), these fields
302
    end up pointing to the wrong field. One solution is to change Cached_item
303
    to not resolve its field upon creation, but to resolve it dynamically
304
    from a given Item_ref object.
305
    TODO: the cache should be applied conditionally based on:
306
    - rules - e.g. only if the left operand is known to be ordered, and/or
307
    - on a cost-based basis, that takes into account the cost of a cache
308
      lookup, the cache hit rate, and the savings per cache hit.
309
  */
1101.1.16 by Monty Taylor
Reverted 1103
310
  if (!left_expr_cache && exec_method == MATERIALIZATION)
1 by brian
clean slate
311
    init_left_expr_cache();
312
313
  /* If the new left operand is already in the cache, reuse the old result. */
1101.1.16 by Monty Taylor
Reverted 1103
314
  if (left_expr_cache && test_if_item_cache_changed(*left_expr_cache) < 0)
1 by brian
clean slate
315
  {
316
    /* Always compute IN for the first row as the cache is not valid for it. */
317
    if (!first_execution)
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
318
      return(false);
55 by brian
Update for using real bool types.
319
    first_execution= false;
1 by brian
clean slate
320
  }
321
322
  /*
323
    The exec() method below updates item::value, and item::null_value, thus if
324
    we don't call it, the next call to item::val_int() will return whatever
325
    result was computed by its previous call.
326
  */
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
327
  return(Item_subselect::exec());
1 by brian
clean slate
328
}
329
330
331
Item::Type Item_subselect::type() const
332
{
333
  return SUBSELECT_ITEM;
334
}
335
336
337
void Item_subselect::fix_length_and_dec()
338
{
339
  engine->fix_length_and_dec(0);
340
}
341
342
343
table_map Item_subselect::used_tables() const
344
{
345
  return (table_map) (engine->uncacheable() ? used_tables_cache : 0L);
346
}
347
348
349
bool Item_subselect::const_item() const
350
{
351
  return const_item_cache;
352
}
353
520.1.22 by Brian Aker
Second pass of thd cleanup
354
Item *Item_subselect::get_tmp_table_item(Session *session_arg)
1 by brian
clean slate
355
{
356
  if (!with_sum_func && !const_item())
357
    return new Item_field(result_field);
520.1.22 by Brian Aker
Second pass of thd cleanup
358
  return copy_or_same(session_arg);
1 by brian
clean slate
359
}
360
361
void Item_subselect::update_used_tables()
362
{
363
  if (!engine->uncacheable())
364
  {
365
    // did all used tables become static?
366
    if (!(used_tables_cache & ~engine->upper_select_const_tables()))
367
      const_item_cache= 1;
368
  }
369
}
370
371
372
void Item_subselect::print(String *str, enum_query_type query_type)
373
{
374
  str->append('(');
375
  engine->print(str, query_type);
376
  str->append(')');
377
}
378
379
846 by Brian Aker
Removing on typedeffed class.
380
Item_singlerow_subselect::Item_singlerow_subselect(Select_Lex *select_lex)
1 by brian
clean slate
381
  :Item_subselect(), value(0)
382
{
383
  init(select_lex, new select_singlerow_subselect(this));
384
  maybe_null= 1;
385
  max_columns= UINT_MAX;
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
386
  return;
1 by brian
clean slate
387
}
388
846 by Brian Aker
Removing on typedeffed class.
389
Select_Lex *
1 by brian
clean slate
390
Item_singlerow_subselect::invalidate_and_restore_select_lex()
391
{
846 by Brian Aker
Removing on typedeffed class.
392
  Select_Lex *result= get_select_lex();
1 by brian
clean slate
393
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
394
  assert(result);
1 by brian
clean slate
395
396
  /*
397
    This code restore the parse tree in it's state before the execution of
398
    Item_singlerow_subselect::Item_singlerow_subselect(),
846 by Brian Aker
Removing on typedeffed class.
399
    and in particular decouples this object from the Select_Lex,
400
    so that the Select_Lex can be used with a different flavor
1 by brian
clean slate
401
    or Item_subselect instead, as part of query rewriting.
402
  */
403
  unit->item= NULL;
404
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
405
  return(result);
1 by brian
clean slate
406
}
407
520.1.22 by Brian Aker
Second pass of thd cleanup
408
Item_maxmin_subselect::Item_maxmin_subselect(Session *session_param,
1 by brian
clean slate
409
                                             Item_subselect *parent,
846 by Brian Aker
Removing on typedeffed class.
410
					     Select_Lex *select_lex,
1 by brian
clean slate
411
					     bool max_arg)
55 by brian
Update for using real bool types.
412
  :Item_singlerow_subselect(), was_values(true)
1 by brian
clean slate
413
{
414
  max= max_arg;
415
  init(select_lex, new select_max_min_finder_subselect(this, max_arg));
416
  max_columns= 1;
417
  maybe_null= 1;
418
  max_columns= 1;
419
420
  /*
421
    Following information was collected during performing fix_fields()
422
    of Items belonged to subquery, which will be not repeated
423
  */
424
  used_tables_cache= parent->get_used_tables_cache();
425
  const_item_cache= parent->get_const_item_cache();
426
427
  /*
428
    this subquery always creates during preparation, so we can assign
520.1.22 by Brian Aker
Second pass of thd cleanup
429
    session here
1 by brian
clean slate
430
  */
520.1.22 by Brian Aker
Second pass of thd cleanup
431
  session= session_param;
1 by brian
clean slate
432
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
433
  return;
1 by brian
clean slate
434
}
435
436
void Item_maxmin_subselect::cleanup()
437
{
438
  Item_singlerow_subselect::cleanup();
439
440
  /*
55 by brian
Update for using real bool types.
441
    By default it is true to avoid true reporting by
1 by brian
clean slate
442
    Item_func_not_all/Item_func_nop_all if this item was never called.
443
55 by brian
Update for using real bool types.
444
    Engine exec() set it to false by reset_value_registration() call.
445
    select_max_min_finder_subselect::send_data() set it back to true if some
1 by brian
clean slate
446
    value will be found.
447
  */
55 by brian
Update for using real bool types.
448
  was_values= true;
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
449
  return;
1 by brian
clean slate
450
}
451
452
453
void Item_maxmin_subselect::print(String *str, enum_query_type query_type)
454
{
455
  str->append(max?"<max>":"<min>", 5);
456
  Item_singlerow_subselect::print(str, query_type);
457
}
458
459
460
void Item_singlerow_subselect::reset()
461
{
462
  null_value= 1;
463
  if (value)
464
    value->null_value= 1;
465
}
466
467
468
/**
469
  @todo
470
  - We cant change name of Item_field or Item_ref, because it will
471
  prevent it's correct resolving, but we should save name of
472
  removed item => we do not make optimization if top item of
473
  list is field or reference.
474
  - switch off this optimization for prepare statement,
475
  because we do not rollback this changes.
476
  Make rollback for it, or special name resolving mode in 5.0.
477
*/
478
Item_subselect::trans_res
479
Item_singlerow_subselect::select_transformer(JOIN *join)
480
{
481
  if (changed)
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
482
    return(RES_OK);
1 by brian
clean slate
483
846 by Brian Aker
Removing on typedeffed class.
484
  Select_Lex *select_lex= join->select_lex;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
485
1 by brian
clean slate
486
  if (!select_lex->master_unit()->is_union() &&
487
      !select_lex->table_list.elements &&
488
      select_lex->item_list.elements == 1 &&
489
      !select_lex->item_list.head()->with_sum_func &&
490
      /*
491
	We cant change name of Item_field or Item_ref, because it will
492
	prevent it's correct resolving, but we should save name of
493
	removed item => we do not make optimization if top item of
494
	list is field or reference.
495
	TODO: solve above problem
496
      */
497
      !(select_lex->item_list.head()->type() == FIELD_ITEM ||
498
	select_lex->item_list.head()->type() == REF_ITEM) &&
499
      !join->conds && !join->having
500
      )
501
  {
502
503
    have_to_be_excluded= 1;
520.1.22 by Brian Aker
Second pass of thd cleanup
504
    if (session->lex->describe)
1 by brian
clean slate
505
    {
261.4.1 by Felipe
- Renamed MYSQL_ERROR to DRIZZLE_ERROR.
506
      char warn_buff[DRIZZLE_ERRMSG_SIZE];
1 by brian
clean slate
507
      sprintf(warn_buff, ER(ER_SELECT_REDUCED), select_lex->select_number);
520.1.22 by Brian Aker
Second pass of thd cleanup
508
      push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
1 by brian
clean slate
509
		   ER_SELECT_REDUCED, warn_buff);
510
    }
511
    substitution= select_lex->item_list.head();
512
    /*
513
      as far as we moved content to upper level, field which depend of
514
      'upper' select is not really dependent => we remove this dependence
515
    */
516
    substitution->walk(&Item::remove_dependence_processor, 0,
481 by Brian Aker
Remove all of uchar.
517
		       (unsigned char *) select_lex->outer_select());
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
518
    return(RES_REDUCE);
1 by brian
clean slate
519
  }
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
520
  return(RES_OK);
1 by brian
clean slate
521
}
522
523
482 by Brian Aker
Remove uint.
524
void Item_singlerow_subselect::store(uint32_t i, Item *item)
1 by brian
clean slate
525
{
526
  row[i]->store(item);
527
}
528
529
enum Item_result Item_singlerow_subselect::result_type() const
530
{
531
  return engine->type();
532
}
533
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
534
/*
535
 Don't rely on the result type to calculate field type.
1 by brian
clean slate
536
 Ask the engine instead.
537
*/
538
enum_field_types Item_singlerow_subselect::field_type() const
539
{
540
  return engine->field_type();
541
}
542
543
void Item_singlerow_subselect::fix_length_and_dec()
544
{
545
  if ((max_columns= engine->cols()) == 1)
546
  {
547
    engine->fix_length_and_dec(row= &value);
548
  }
549
  else
550
  {
551
    if (!(row= (Item_cache**) sql_alloc(sizeof(Item_cache*)*max_columns)))
552
      return;
553
    engine->fix_length_and_dec(row);
554
    value= *row;
555
  }
556
  unsigned_flag= value->unsigned_flag;
557
  /*
558
    If there are not tables in subquery then ability to have NULL value
559
    depends on SELECT list (if single row subquery have tables then it
560
    always can be NULL if there are not records fetched).
561
  */
562
  if (engine->no_tables())
563
    maybe_null= engine->may_be_null();
564
}
565
482 by Brian Aker
Remove uint.
566
uint32_t Item_singlerow_subselect::cols()
1 by brian
clean slate
567
{
568
  return engine->cols();
569
}
570
482 by Brian Aker
Remove uint.
571
bool Item_singlerow_subselect::check_cols(uint32_t c)
1 by brian
clean slate
572
{
573
  if (c != engine->cols())
574
  {
575
    my_error(ER_OPERAND_COLUMNS, MYF(0), c);
576
    return 1;
577
  }
578
  return 0;
579
}
580
581
bool Item_singlerow_subselect::null_inside()
582
{
482 by Brian Aker
Remove uint.
583
  for (uint32_t i= 0; i < max_columns ; i++)
1 by brian
clean slate
584
  {
585
    if (row[i]->null_value)
586
      return 1;
587
  }
588
  return 0;
589
}
590
591
void Item_singlerow_subselect::bring_value()
592
{
593
  exec();
594
}
595
596
double Item_singlerow_subselect::val_real()
597
{
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
598
  assert(fixed == 1);
1 by brian
clean slate
599
  if (!exec() && !value->null_value)
600
  {
601
    null_value= 0;
602
    return value->val_real();
603
  }
604
  else
605
  {
606
    reset();
607
    return 0;
608
  }
609
}
610
152 by Brian Aker
longlong replacement
611
int64_t Item_singlerow_subselect::val_int()
1 by brian
clean slate
612
{
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
613
  assert(fixed == 1);
1 by brian
clean slate
614
  if (!exec() && !value->null_value)
615
  {
616
    null_value= 0;
617
    return value->val_int();
618
  }
619
  else
620
  {
621
    reset();
622
    return 0;
623
  }
624
}
625
626
String *Item_singlerow_subselect::val_str(String *str)
627
{
628
  if (!exec() && !value->null_value)
629
  {
630
    null_value= 0;
631
    return value->val_str(str);
632
  }
633
  else
634
  {
635
    reset();
636
    return 0;
637
  }
638
}
639
640
641
my_decimal *Item_singlerow_subselect::val_decimal(my_decimal *decimal_value)
642
{
643
  if (!exec() && !value->null_value)
644
  {
645
    null_value= 0;
646
    return value->val_decimal(decimal_value);
647
  }
648
  else
649
  {
650
    reset();
651
    return 0;
652
  }
653
}
654
655
656
bool Item_singlerow_subselect::val_bool()
657
{
658
  if (!exec() && !value->null_value)
659
  {
660
    null_value= 0;
661
    return value->val_bool();
662
  }
663
  else
664
  {
665
    reset();
666
    return 0;
667
  }
668
}
669
670
846 by Brian Aker
Removing on typedeffed class.
671
Item_exists_subselect::Item_exists_subselect(Select_Lex *select_lex):
1 by brian
clean slate
672
  Item_subselect()
673
{
674
  bool val_bool();
675
  init(select_lex, new select_exists_subselect(this));
676
  max_columns= UINT_MAX;
677
  null_value= 0; //can't be NULL
678
  maybe_null= 0; //can't be NULL
679
  value= 0;
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
680
  return;
1 by brian
clean slate
681
}
682
683
684
void Item_exists_subselect::print(String *str, enum_query_type query_type)
685
{
686
  str->append(STRING_WITH_LEN("exists"));
687
  Item_subselect::print(str, query_type);
688
}
689
690
848 by Brian Aker
typdef class removal (just... use the name of the class).
691
bool Item_in_subselect::test_limit(Select_Lex_Unit *unit_arg)
1 by brian
clean slate
692
{
693
  if (unit_arg->fake_select_lex &&
694
      unit_arg->fake_select_lex->test_limit())
695
    return(1);
696
846 by Brian Aker
Removing on typedeffed class.
697
  Select_Lex *sl= unit_arg->first_select();
1 by brian
clean slate
698
  for (; sl; sl= sl->next_select())
699
  {
700
    if (sl->test_limit())
701
      return(1);
702
  }
703
  return(0);
704
}
705
706
Item_in_subselect::Item_in_subselect(Item * left_exp,
846 by Brian Aker
Removing on typedeffed class.
707
				     Select_Lex *select_lex):
1101.1.16 by Monty Taylor
Reverted 1103
708
  Item_exists_subselect(), left_expr_cache(0), first_execution(true),
1 by brian
clean slate
709
  optimizer(0), pushed_cond_guards(NULL), exec_method(NOT_TRANSFORMED),
710
  upper_item(0)
711
{
712
  left_expr= left_exp;
713
  init(select_lex, new select_exists_subselect(this));
714
  max_columns= UINT_MAX;
715
  maybe_null= 1;
716
  abort_on_null= 0;
717
  reset();
718
  //if test_limit will fail then error will be reported to client
719
  test_limit(select_lex->master_unit());
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
720
  return;
1 by brian
clean slate
721
}
722
723
Item_allany_subselect::Item_allany_subselect(Item * left_exp,
724
                                             chooser_compare_func_creator fc,
846 by Brian Aker
Removing on typedeffed class.
725
					     Select_Lex *select_lex,
1 by brian
clean slate
726
					     bool all_arg)
727
  :Item_in_subselect(), func_creator(fc), all(all_arg)
728
{
729
  left_expr= left_exp;
730
  func= func_creator(all_arg);
731
  init(select_lex, new select_exists_subselect(this));
732
  max_columns= 1;
733
  abort_on_null= 0;
734
  reset();
735
  //if test_limit will fail then error will be reported to client
736
  test_limit(select_lex->master_unit());
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
737
  return;
1 by brian
clean slate
738
}
739
740
741
void Item_exists_subselect::fix_length_and_dec()
742
{
743
   decimals= 0;
744
   max_length= 1;
745
   max_columns= engine->cols();
746
  /* We need only 1 row to determine existence */
205 by Brian Aker
uint32 -> uin32_t
747
  unit->global_parameters->select_limit= new Item_int((int32_t) 1);
1 by brian
clean slate
748
}
749
750
double Item_exists_subselect::val_real()
751
{
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
752
  assert(fixed == 1);
1 by brian
clean slate
753
  if (exec())
754
  {
755
    reset();
756
    return 0;
757
  }
758
  return (double) value;
759
}
760
152 by Brian Aker
longlong replacement
761
int64_t Item_exists_subselect::val_int()
1 by brian
clean slate
762
{
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
763
  assert(fixed == 1);
1 by brian
clean slate
764
  if (exec())
765
  {
766
    reset();
767
    return 0;
768
  }
769
  return value;
770
}
771
772
String *Item_exists_subselect::val_str(String *str)
773
{
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
774
  assert(fixed == 1);
1 by brian
clean slate
775
  if (exec())
776
  {
777
    reset();
778
    return 0;
779
  }
151 by Brian Aker
Ulonglong to uint64_t
780
  str->set((uint64_t)value,&my_charset_bin);
1 by brian
clean slate
781
  return str;
782
}
783
784
785
my_decimal *Item_exists_subselect::val_decimal(my_decimal *decimal_value)
786
{
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
787
  assert(fixed == 1);
1 by brian
clean slate
788
  if (exec())
789
  {
790
    reset();
791
    return 0;
792
  }
793
  int2my_decimal(E_DEC_FATAL_ERROR, value, 0, decimal_value);
794
  return decimal_value;
795
}
796
797
798
bool Item_exists_subselect::val_bool()
799
{
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
800
  assert(fixed == 1);
1 by brian
clean slate
801
  if (exec())
802
  {
803
    reset();
804
    return 0;
805
  }
806
  return value != 0;
807
}
808
809
810
double Item_in_subselect::val_real()
811
{
812
  /*
813
    As far as Item_in_subselect called only from Item_in_optimizer this
814
    method should not be used
815
  */
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
816
  assert(0);
817
  assert(fixed == 1);
1 by brian
clean slate
818
  null_value= 0;
819
  if (exec())
820
  {
821
    reset();
822
    null_value= 1;
823
    return 0;
824
  }
825
  if (was_null && !value)
826
    null_value= 1;
827
  return (double) value;
828
}
829
830
152 by Brian Aker
longlong replacement
831
int64_t Item_in_subselect::val_int()
1 by brian
clean slate
832
{
833
  /*
834
    As far as Item_in_subselect called only from Item_in_optimizer this
835
    method should not be used
836
  */
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
837
  assert(fixed == 1);
1 by brian
clean slate
838
  null_value= 0;
839
  if (exec())
840
  {
841
    reset();
842
    null_value= 1;
843
    return 0;
844
  }
845
  if (was_null && !value)
846
    null_value= 1;
847
  return value;
848
}
849
850
851
String *Item_in_subselect::val_str(String *str)
852
{
853
  /*
854
    As far as Item_in_subselect called only from Item_in_optimizer this
855
    method should not be used
856
  */
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
857
  assert(0);
858
  assert(fixed == 1);
1 by brian
clean slate
859
  null_value= 0;
860
  if (exec())
861
  {
862
    reset();
863
    null_value= 1;
864
    return 0;
865
  }
866
  if (was_null && !value)
867
  {
868
    null_value= 1;
869
    return 0;
870
  }
151 by Brian Aker
Ulonglong to uint64_t
871
  str->set((uint64_t)value, &my_charset_bin);
1 by brian
clean slate
872
  return str;
873
}
874
875
876
bool Item_in_subselect::val_bool()
877
{
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
878
  assert(fixed == 1);
1 by brian
clean slate
879
  null_value= 0;
880
  if (exec())
881
  {
882
    reset();
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
883
    /*
1 by brian
clean slate
884
      Must mark the IN predicate as NULL so as to make sure an enclosing NOT
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
885
      predicate will return false. See the comments in
1 by brian
clean slate
886
      subselect_uniquesubquery_engine::copy_ref_key for further details.
887
    */
888
    null_value= 1;
889
    return 0;
890
  }
891
  if (was_null && !value)
892
    null_value= 1;
893
  return value;
894
}
895
896
my_decimal *Item_in_subselect::val_decimal(my_decimal *decimal_value)
897
{
898
  /*
899
    As far as Item_in_subselect called only from Item_in_optimizer this
900
    method should not be used
901
  */
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
902
  assert(0);
1 by brian
clean slate
903
  null_value= 0;
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
904
  assert(fixed == 1);
1 by brian
clean slate
905
  if (exec())
906
  {
907
    reset();
908
    null_value= 1;
909
    return 0;
910
  }
911
  if (was_null && !value)
912
    null_value= 1;
913
  int2my_decimal(E_DEC_FATAL_ERROR, value, 0, decimal_value);
914
  return decimal_value;
915
}
916
917
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
918
/*
1 by brian
clean slate
919
  Rewrite a single-column IN/ALL/ANY subselect
920
921
  SYNOPSIS
922
    Item_in_subselect::single_value_transformer()
923
      join  Join object of the subquery (i.e. 'child' join).
924
      func  Subquery comparison creator
925
926
  DESCRIPTION
927
    Rewrite a single-column subquery using rule-based approach. The subquery
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
928
1 by brian
clean slate
929
       oe $cmp$ (SELECT ie FROM ... WHERE subq_where ... HAVING subq_having)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
930
1 by brian
clean slate
931
    First, try to convert the subquery to scalar-result subquery in one of
932
    the forms:
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
933
1 by brian
clean slate
934
       - oe $cmp$ (SELECT MAX(...) )  // handled by Item_singlerow_subselect
935
       - oe $cmp$ <max>(SELECT ...)   // handled by Item_maxmin_subselect
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
936
1 by brian
clean slate
937
    If that fails, the subquery will be handled with class Item_in_optimizer.
938
    There are two possibilites:
939
    - If the subquery execution method is materialization, then the subquery is
940
      not transformed any further.
941
    - Otherwise the IN predicates is transformed into EXISTS by injecting
942
      equi-join predicates and possibly other helper predicates. For details
943
      see method single_value_in_like_transformer().
944
945
  RETURN
946
    RES_OK     Either subquery was transformed, or appopriate
947
                       predicates where injected into it.
948
    RES_REDUCE The subquery was reduced to non-subquery
949
    RES_ERROR  Error
950
*/
951
952
Item_subselect::trans_res
953
Item_in_subselect::single_value_transformer(JOIN *join,
584.4.7 by Monty Taylor
Removed a big bank of includes from item.h.
954
					    const Comp_creator *func)
1 by brian
clean slate
955
{
846 by Brian Aker
Removing on typedeffed class.
956
  Select_Lex *select_lex= join->select_lex;
1 by brian
clean slate
957
958
  /*
959
    Check that the right part of the subselect contains no more than one
960
    column. E.g. in SELECT 1 IN (SELECT * ..) the right part is (SELECT * ...)
961
  */
962
  if (select_lex->item_list.elements > 1)
963
  {
964
    my_error(ER_OPERAND_COLUMNS, MYF(0), 1);
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
965
    return(RES_ERROR);
1 by brian
clean slate
966
  }
967
968
  /*
969
    If this is an ALL/ANY single-value subselect, try to rewrite it with
970
    a MIN/MAX subselect. We can do that if a possible NULL result of the
971
    subselect can be ignored.
972
    E.g. SELECT * FROM t1 WHERE b > ANY (SELECT a FROM t2) can be rewritten
973
    with SELECT * FROM t1 WHERE b > (SELECT MAX(a) FROM t2).
974
    We can't check that this optimization is safe if it's not a top-level
975
    item of the WHERE clause (e.g. because the WHERE clause can contain IS
976
    NULL/IS NOT NULL functions). If so, we rewrite ALL/ANY with NOT EXISTS
977
    later in this method.
978
  */
979
  if ((abort_on_null || (upper_item && upper_item->top_level())) &&
980
      !select_lex->master_unit()->uncacheable && !func->eqne_op())
981
  {
982
    if (substitution)
983
    {
984
      // It is second (third, ...) SELECT of UNION => All is done
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
985
      return(RES_OK);
1 by brian
clean slate
986
    }
987
988
    Item *subs;
989
    if (!select_lex->group_list.elements &&
990
        !select_lex->having &&
991
	!select_lex->with_sum_func &&
992
	!(select_lex->next_select()) &&
993
        select_lex->table_list.elements)
994
    {
995
      Item_sum_hybrid *item;
996
      nesting_map save_allow_sum_func;
997
      if (func->l_op())
998
      {
999
	/*
1000
	  (ALL && (> || =>)) || (ANY && (< || =<))
1001
	  for ALL condition is inverted
1002
	*/
1003
	item= new Item_sum_max(*select_lex->ref_pointer_array);
1004
      }
1005
      else
1006
      {
1007
	/*
1008
	  (ALL && (< || =<)) || (ANY && (> || =>))
1009
	  for ALL condition is inverted
1010
	*/
1011
	item= new Item_sum_min(*select_lex->ref_pointer_array);
1012
      }
1013
      if (upper_item)
1014
        upper_item->set_sum_test(item);
1015
      *select_lex->ref_pointer_array= item;
1016
      {
1017
	List_iterator<Item> it(select_lex->item_list);
1018
	it++;
1019
	it.replace(item);
1020
      }
1021
520.1.22 by Brian Aker
Second pass of thd cleanup
1022
      save_allow_sum_func= session->lex->allow_sum_func;
1023
      session->lex->allow_sum_func|= 1 << session->lex->current_select->nest_level;
1 by brian
clean slate
1024
      /*
1025
	Item_sum_(max|min) can't substitute other item => we can use 0 as
1026
        reference, also Item_sum_(max|min) can't be fixed after creation, so
1027
        we do not check item->fixed
1028
      */
520.1.22 by Brian Aker
Second pass of thd cleanup
1029
      if (item->fix_fields(session, 0))
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1030
	return(RES_ERROR);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1031
      session->lex->allow_sum_func= save_allow_sum_func;
1 by brian
clean slate
1032
      /* we added aggregate function => we have to change statistic */
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1033
      count_field_types(select_lex, &join->tmp_table_param, join->all_fields,
1 by brian
clean slate
1034
                        0);
1035
1036
      subs= new Item_singlerow_subselect(select_lex);
1037
    }
1038
    else
1039
    {
1040
      Item_maxmin_subselect *item;
520.1.22 by Brian Aker
Second pass of thd cleanup
1041
      subs= item= new Item_maxmin_subselect(session, this, select_lex, func->l_op());
1 by brian
clean slate
1042
      if (upper_item)
1043
        upper_item->set_sub_test(item);
1044
    }
1045
    /* fix fields is already called for  left expression */
1046
    substitution= func->create(left_expr, subs);
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1047
    return(RES_OK);
1 by brian
clean slate
1048
  }
1049
1050
  if (!substitution)
1051
  {
1052
    /* We're invoked for the 1st (or the only) SELECT in the subquery UNION */
848 by Brian Aker
typdef class removal (just... use the name of the class).
1053
    Select_Lex_Unit *master_unit= select_lex->master_unit();
1 by brian
clean slate
1054
    substitution= optimizer;
1055
846 by Brian Aker
Removing on typedeffed class.
1056
    Select_Lex *current= session->lex->current_select, *up;
1 by brian
clean slate
1057
520.1.22 by Brian Aker
Second pass of thd cleanup
1058
    session->lex->current_select= up= current->return_after_parsing();
1 by brian
clean slate
1059
    //optimizer never use Item **ref => we can pass 0 as parameter
520.1.22 by Brian Aker
Second pass of thd cleanup
1060
    if (!optimizer || optimizer->fix_left(session, 0))
1 by brian
clean slate
1061
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
1062
      session->lex->current_select= current;
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1063
      return(RES_ERROR);
1 by brian
clean slate
1064
    }
520.1.22 by Brian Aker
Second pass of thd cleanup
1065
    session->lex->current_select= current;
1 by brian
clean slate
1066
1067
    /*
1068
      As far as  Item_ref_in_optimizer do not substitute itself on fix_fields
1069
      we can use same item for all selects.
1070
    */
1071
    expr= new Item_direct_ref(&select_lex->context,
1072
                              (Item**)optimizer->get_cache(),
1073
			      (char *)"<no matter>",
1074
			      (char *)in_left_expr_name);
1075
1076
    master_unit->uncacheable|= UNCACHEABLE_DEPENDENT;
1077
  }
1078
1079
  if (!abort_on_null && left_expr->maybe_null && !pushed_cond_guards)
1080
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
1081
    if (!(pushed_cond_guards= (bool*)join->session->alloc(sizeof(bool))))
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1082
      return(RES_ERROR);
55 by brian
Update for using real bool types.
1083
    pushed_cond_guards[0]= true;
1 by brian
clean slate
1084
  }
1085
1086
  /*
1087
    If this IN predicate can be computed via materialization, do not
1088
    perform the IN -> EXISTS transformation.
1089
  */
1090
  if (exec_method == MATERIALIZATION)
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1091
    return(RES_OK);
1 by brian
clean slate
1092
1093
  /* Perform the IN=>EXISTS transformation. */
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1094
  return(single_value_in_to_exists_transformer(join, func));
1 by brian
clean slate
1095
}
1096
1097
1098
/**
1099
  Transofrm an IN predicate into EXISTS via predicate injection.
1100
1101
  @details The transformation injects additional predicates into the subquery
1102
  (and makes the subquery correlated) as follows.
1103
1104
  - If the subquery has aggregates, GROUP BY, or HAVING, convert to
1105
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1106
    SELECT ie FROM ...  HAVING subq_having AND
1 by brian
clean slate
1107
                               trigcond(oe $cmp$ ref_or_null_helper<ie>)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1108
1 by brian
clean slate
1109
    the addition is wrapped into trigger only when we want to distinguish
55 by brian
Update for using real bool types.
1110
    between NULL and false results.
1 by brian
clean slate
1111
1112
  - Otherwise (no aggregates/GROUP BY/HAVING) convert it to one of the
1113
    following:
1114
55 by brian
Update for using real bool types.
1115
    = If we don't need to distinguish between NULL and false subquery:
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1116
1 by brian
clean slate
1117
      SELECT 1 FROM ... WHERE (oe $cmp$ ie) AND subq_where
1118
1119
    = If we need to distinguish between those:
1120
1121
      SELECT 1 FROM ...
1122
        WHERE  subq_where AND trigcond((oe $cmp$ ie) OR (ie IS NULL))
1123
        HAVING trigcond(<is_not_null_test>(ie))
1124
1125
    @param join  Join object of the subquery (i.e. 'child' join).
1126
    @param func  Subquery comparison creator
1127
1128
    @retval RES_OK     Either subquery was transformed, or appopriate
1129
                       predicates where injected into it.
1130
    @retval RES_REDUCE The subquery was reduced to non-subquery
1131
    @retval RES_ERROR  Error
1132
*/
1133
1134
Item_subselect::trans_res
584.4.7 by Monty Taylor
Removed a big bank of includes from item.h.
1135
Item_in_subselect::single_value_in_to_exists_transformer(JOIN * join, const Comp_creator *func)
1 by brian
clean slate
1136
{
846 by Brian Aker
Removing on typedeffed class.
1137
  Select_Lex *select_lex= join->select_lex;
1 by brian
clean slate
1138
1139
  select_lex->uncacheable|= UNCACHEABLE_DEPENDENT;
1140
  if (join->having || select_lex->with_sum_func ||
1141
      select_lex->group_list.elements)
1142
  {
1143
    bool tmp;
1144
    Item *item= func->create(expr,
1145
                             new Item_ref_null_helper(&select_lex->context,
1146
                                                      this,
1147
                                                      select_lex->
1148
                                                      ref_pointer_array,
1149
                                                      (char *)"<ref>",
1150
                                                      this->full_name()));
1151
    if (!abort_on_null && left_expr->maybe_null)
1152
    {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1153
      /*
1 by brian
clean slate
1154
        We can encounter "NULL IN (SELECT ...)". Wrap the added condition
1155
        within a trig_cond.
1156
      */
1157
      item= new Item_func_trig_cond(item, get_cond_guard(0));
1158
    }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1159
1 by brian
clean slate
1160
    /*
1161
      AND and comparison functions can't be changed during fix_fields()
1162
      we can assign select_lex->having here, and pass 0 as last
1163
      argument (reference) to fix_fields()
1164
    */
1165
    select_lex->having= join->having= and_items(join->having, item);
1166
    if (join->having == item)
1167
      item->name= (char*)in_having_cond;
1168
    select_lex->having_fix_field= 1;
1169
    /*
1170
      we do not check join->having->fixed, because Item_and (from and_items)
1171
      or comparison function (from func->create) can't be fixed after creation
1172
    */
520.1.22 by Brian Aker
Second pass of thd cleanup
1173
    tmp= join->having->fix_fields(session, 0);
1 by brian
clean slate
1174
    select_lex->having_fix_field= 0;
1175
    if (tmp)
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1176
      return(RES_ERROR);
1 by brian
clean slate
1177
  }
1178
  else
1179
  {
1180
    Item *item= (Item*) select_lex->item_list.head();
1181
1182
    if (select_lex->table_list.elements)
1183
    {
1184
      bool tmp;
1185
      Item *having= item, *orig_item= item;
1186
      select_lex->item_list.empty();
1187
      select_lex->item_list.push_back(new Item_int("Not_used",
152 by Brian Aker
longlong replacement
1188
                                                   (int64_t) 1,
1 by brian
clean slate
1189
                                                   MY_INT64_NUM_DECIMAL_DIGITS));
1190
      select_lex->ref_pointer_array[0]= select_lex->item_list.head();
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1191
1 by brian
clean slate
1192
      item= func->create(expr, item);
1193
      if (!abort_on_null && orig_item->maybe_null)
1194
      {
1195
	having= new Item_is_not_null_test(this, having);
1196
        if (left_expr->maybe_null)
1197
        {
1198
          if (!(having= new Item_func_trig_cond(having,
1199
                                                get_cond_guard(0))))
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1200
            return(RES_ERROR);
1 by brian
clean slate
1201
        }
1202
	/*
1203
	  Item_is_not_null_test can't be changed during fix_fields()
1204
	  we can assign select_lex->having here, and pass 0 as last
1205
	  argument (reference) to fix_fields()
1206
	*/
1207
        having->name= (char*)in_having_cond;
1208
	select_lex->having= join->having= having;
1209
	select_lex->having_fix_field= 1;
1210
        /*
1211
          we do not check join->having->fixed, because Item_and (from
1212
          and_items) or comparison function (from func->create) can't be
1213
          fixed after creation
1214
        */
520.1.22 by Brian Aker
Second pass of thd cleanup
1215
	tmp= join->having->fix_fields(session, 0);
1 by brian
clean slate
1216
        select_lex->having_fix_field= 0;
1217
        if (tmp)
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1218
	  return(RES_ERROR);
1 by brian
clean slate
1219
	item= new Item_cond_or(item,
1220
			       new Item_func_isnull(orig_item));
1221
      }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1222
      /*
1 by brian
clean slate
1223
        If we may encounter NULL IN (SELECT ...) and care whether subquery
55 by brian
Update for using real bool types.
1224
        result is NULL or false, wrap condition in a trig_cond.
1 by brian
clean slate
1225
      */
1226
      if (!abort_on_null && left_expr->maybe_null)
1227
      {
1228
        if (!(item= new Item_func_trig_cond(item, get_cond_guard(0))))
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1229
          return(RES_ERROR);
1 by brian
clean slate
1230
      }
1231
      /*
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1232
        TODO: figure out why the following is done here in
1 by brian
clean slate
1233
        single_value_transformer but there is no corresponding action in
1234
        row_value_transformer?
1235
      */
1236
      item->name= (char *)in_additional_cond;
1237
1238
      /*
1239
	AND can't be changed during fix_fields()
1240
	we can assign select_lex->having here, and pass 0 as last
1241
	argument (reference) to fix_fields()
1242
      */
1243
      select_lex->where= join->conds= and_items(join->conds, item);
1244
      select_lex->where->top_level_item();
1245
      /*
1246
        we do not check join->conds->fixed, because Item_and can't be fixed
1247
        after creation
1248
      */
520.1.22 by Brian Aker
Second pass of thd cleanup
1249
      if (join->conds->fix_fields(session, 0))
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1250
	return(RES_ERROR);
1 by brian
clean slate
1251
    }
1252
    else
1253
    {
1254
      bool tmp;
1255
      if (select_lex->master_unit()->is_union())
1256
      {
1257
	/*
1258
	  comparison functions can't be changed during fix_fields()
1259
	  we can assign select_lex->having here, and pass 0 as last
1260
	  argument (reference) to fix_fields()
1261
	*/
1262
        Item *new_having=
1263
          func->create(expr,
1264
                       new Item_ref_null_helper(&select_lex->context, this,
1265
                                            select_lex->ref_pointer_array,
1266
                                            (char *)"<no matter>",
1267
                                            (char *)"<result>"));
1268
        if (!abort_on_null && left_expr->maybe_null)
1269
        {
1270
          if (!(new_having= new Item_func_trig_cond(new_having,
1271
                                                    get_cond_guard(0))))
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1272
            return(RES_ERROR);
1 by brian
clean slate
1273
        }
1274
        new_having->name= (char*)in_having_cond;
1275
	select_lex->having= join->having= new_having;
1276
	select_lex->having_fix_field= 1;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1277
1 by brian
clean slate
1278
        /*
1279
          we do not check join->having->fixed, because comparison function
1280
          (from func->create) can't be fixed after creation
1281
        */
520.1.22 by Brian Aker
Second pass of thd cleanup
1282
	tmp= join->having->fix_fields(session, 0);
1 by brian
clean slate
1283
        select_lex->having_fix_field= 0;
1284
        if (tmp)
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1285
	  return(RES_ERROR);
1 by brian
clean slate
1286
      }
1287
      else
1288
      {
1289
	// it is single select without tables => possible optimization
1290
	item= func->create(left_expr, item);
1291
	// fix_field of item will be done in time of substituting
1292
	substitution= item;
1293
	have_to_be_excluded= 1;
520.1.22 by Brian Aker
Second pass of thd cleanup
1294
	if (session->lex->describe)
1 by brian
clean slate
1295
	{
261.4.1 by Felipe
- Renamed MYSQL_ERROR to DRIZZLE_ERROR.
1296
	  char warn_buff[DRIZZLE_ERRMSG_SIZE];
1 by brian
clean slate
1297
	  sprintf(warn_buff, ER(ER_SELECT_REDUCED), select_lex->select_number);
520.1.22 by Brian Aker
Second pass of thd cleanup
1298
	  push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
1 by brian
clean slate
1299
		       ER_SELECT_REDUCED, warn_buff);
1300
	}
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1301
	return(RES_REDUCE);
1 by brian
clean slate
1302
      }
1303
    }
1304
  }
1305
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1306
  return(RES_OK);
1 by brian
clean slate
1307
}
1308
1309
1310
Item_subselect::trans_res
1311
Item_in_subselect::row_value_transformer(JOIN *join)
1312
{
846 by Brian Aker
Removing on typedeffed class.
1313
  Select_Lex *select_lex= join->select_lex;
482 by Brian Aker
Remove uint.
1314
  uint32_t cols_num= left_expr->cols();
1 by brian
clean slate
1315
1316
  if (select_lex->item_list.elements != left_expr->cols())
1317
  {
1318
    my_error(ER_OPERAND_COLUMNS, MYF(0), left_expr->cols());
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1319
    return(RES_ERROR);
1 by brian
clean slate
1320
  }
1321
1322
  /*
1323
    Wrap the current IN predicate in an Item_in_optimizer. The actual
1324
    substitution in the Item tree takes place in Item_subselect::fix_fields.
1325
  */
1326
  if (!substitution)
1327
  {
1328
    //first call for this unit
848 by Brian Aker
typdef class removal (just... use the name of the class).
1329
    Select_Lex_Unit *master_unit= select_lex->master_unit();
1 by brian
clean slate
1330
    substitution= optimizer;
1331
846 by Brian Aker
Removing on typedeffed class.
1332
    Select_Lex *current= session->lex->current_select, *up;
520.1.22 by Brian Aker
Second pass of thd cleanup
1333
    session->lex->current_select= up= current->return_after_parsing();
1 by brian
clean slate
1334
    //optimizer never use Item **ref => we can pass 0 as parameter
520.1.22 by Brian Aker
Second pass of thd cleanup
1335
    if (!optimizer || optimizer->fix_left(session, 0))
1 by brian
clean slate
1336
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
1337
      session->lex->current_select= current;
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1338
      return(RES_ERROR);
1 by brian
clean slate
1339
    }
1340
1341
    // we will refer to upper level cache array => we have to save it in PS
1342
    optimizer->keep_top_level_cache();
1343
520.1.22 by Brian Aker
Second pass of thd cleanup
1344
    session->lex->current_select= current;
1 by brian
clean slate
1345
    master_unit->uncacheable|= UNCACHEABLE_DEPENDENT;
1346
1347
    if (!abort_on_null && left_expr->maybe_null && !pushed_cond_guards)
1348
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
1349
      if (!(pushed_cond_guards= (bool*)join->session->alloc(sizeof(bool) *
1 by brian
clean slate
1350
                                                        left_expr->cols())))
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1351
        return(RES_ERROR);
482 by Brian Aker
Remove uint.
1352
      for (uint32_t i= 0; i < cols_num; i++)
55 by brian
Update for using real bool types.
1353
        pushed_cond_guards[i]= true;
1 by brian
clean slate
1354
    }
1355
  }
1356
1357
  /*
1358
    If this IN predicate can be computed via materialization, do not
1359
    perform the IN -> EXISTS transformation.
1360
  */
1361
  if (exec_method == MATERIALIZATION)
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1362
    return(RES_OK);
1 by brian
clean slate
1363
1364
  /* Perform the IN=>EXISTS transformation. */
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1365
  return(row_value_in_to_exists_transformer(join));
1 by brian
clean slate
1366
}
1367
1368
1369
/**
1370
  Tranform a (possibly non-correlated) IN subquery into a correlated EXISTS.
1371
1372
  @todo
1373
  The IF-ELSE below can be refactored so that there is no duplication of the
1374
  statements that create the new conditions. For this we have to invert the IF
1375
  and the FOR statements as this:
1376
  for (each left operand)
1377
    create the equi-join condition
1378
    if (is_having_used || !abort_on_null)
1379
      create the "is null" and is_not_null_test items
1380
    if (is_having_used)
1381
      add the equi-join and the null tests to HAVING
1382
    else
1383
      add the equi-join and the "is null" to WHERE
1384
      add the is_not_null_test to HAVING
1385
*/
1386
1387
Item_subselect::trans_res
1388
Item_in_subselect::row_value_in_to_exists_transformer(JOIN * join)
1389
{
846 by Brian Aker
Removing on typedeffed class.
1390
  Select_Lex *select_lex= join->select_lex;
1 by brian
clean slate
1391
  Item *having_item= 0;
482 by Brian Aker
Remove uint.
1392
  uint32_t cols_num= left_expr->cols();
1 by brian
clean slate
1393
  bool is_having_used= (join->having || select_lex->with_sum_func ||
1394
                        select_lex->group_list.first ||
1395
                        !select_lex->table_list.elements);
1396
1397
  select_lex->uncacheable|= UNCACHEABLE_DEPENDENT;
1398
  if (is_having_used)
1399
  {
1400
    /*
1401
      (l1, l2, l3) IN (SELECT v1, v2, v3 ... HAVING having) =>
1402
      EXISTS (SELECT ... HAVING having and
1403
                                (l1 = v1 or is null v1) and
1404
                                (l2 = v2 or is null v2) and
1405
                                (l3 = v3 or is null v3) and
1406
                                is_not_null_test(v1) and
1407
                                is_not_null_test(v2) and
1408
                                is_not_null_test(v3))
1409
      where is_not_null_test used to register nulls in case if we have
1410
      not found matching to return correct NULL value
1411
      TODO: say here explicitly if the order of AND parts matters or not.
1412
    */
1413
    Item *item_having_part2= 0;
482 by Brian Aker
Remove uint.
1414
    for (uint32_t i= 0; i < cols_num; i++)
1 by brian
clean slate
1415
    {
133 by Brian Aker
Cleanup of warning/errors.
1416
      assert((left_expr->fixed && select_lex->ref_pointer_array[i]->fixed) ||
1 by brian
clean slate
1417
                  (select_lex->ref_pointer_array[i]->type() == REF_ITEM &&
1418
                   ((Item_ref*)(select_lex->ref_pointer_array[i]))->ref_type() ==
1419
                    Item_ref::OUTER_REF));
1420
      if (select_lex->ref_pointer_array[i]->
1421
          check_cols(left_expr->element_index(i)->cols()))
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1422
        return(RES_ERROR);
1 by brian
clean slate
1423
      Item *item_eq=
1424
        new Item_func_eq(new
1425
                         Item_ref(&select_lex->context,
1426
                                  (*optimizer->get_cache())->
1427
                                  addr(i),
1428
                                  (char *)"<no matter>",
1429
                                  (char *)in_left_expr_name),
1430
                         new
1431
                         Item_ref(&select_lex->context,
1432
                                  select_lex->ref_pointer_array + i,
1433
                                  (char *)"<no matter>",
1434
                                  (char *)"<list ref>")
1435
                        );
1436
      Item *item_isnull=
1437
        new Item_func_isnull(new
1438
                             Item_ref(&select_lex->context,
1439
                                      select_lex->ref_pointer_array+i,
1440
                                      (char *)"<no matter>",
1441
                                      (char *)"<list ref>")
1442
                            );
1443
      Item *col_item= new Item_cond_or(item_eq, item_isnull);
1444
      if (!abort_on_null && left_expr->element_index(i)->maybe_null)
1445
      {
1446
        if (!(col_item= new Item_func_trig_cond(col_item, get_cond_guard(i))))
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1447
          return(RES_ERROR);
1 by brian
clean slate
1448
      }
1449
      having_item= and_items(having_item, col_item);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1450
1451
      Item *item_nnull_test=
1 by brian
clean slate
1452
         new Item_is_not_null_test(this,
1453
                                   new Item_ref(&select_lex->context,
1454
                                                select_lex->
1455
                                                ref_pointer_array + i,
1456
                                                (char *)"<no matter>",
1457
                                                (char *)"<list ref>"));
1458
      if (!abort_on_null && left_expr->element_index(i)->maybe_null)
1459
      {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1460
        if (!(item_nnull_test=
1 by brian
clean slate
1461
              new Item_func_trig_cond(item_nnull_test, get_cond_guard(i))))
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1462
          return(RES_ERROR);
1 by brian
clean slate
1463
      }
1464
      item_having_part2= and_items(item_having_part2, item_nnull_test);
1465
      item_having_part2->top_level_item();
1466
    }
1467
    having_item= and_items(having_item, item_having_part2);
1468
    having_item->top_level_item();
1469
  }
1470
  else
1471
  {
1472
    /*
1473
      (l1, l2, l3) IN (SELECT v1, v2, v3 ... WHERE where) =>
1474
      EXISTS (SELECT ... WHERE where and
1475
                               (l1 = v1 or is null v1) and
1476
                               (l2 = v2 or is null v2) and
1477
                               (l3 = v3 or is null v3)
1478
                         HAVING is_not_null_test(v1) and
1479
                                is_not_null_test(v2) and
1480
                                is_not_null_test(v3))
1481
      where is_not_null_test register NULLs values but reject rows
1482
1483
      in case when we do not need correct NULL, we have simplier construction:
1484
      EXISTS (SELECT ... WHERE where and
1485
                               (l1 = v1) and
1486
                               (l2 = v2) and
1487
                               (l3 = v3)
1488
    */
1489
    Item *where_item= 0;
482 by Brian Aker
Remove uint.
1490
    for (uint32_t i= 0; i < cols_num; i++)
1 by brian
clean slate
1491
    {
1492
      Item *item, *item_isnull;
133 by Brian Aker
Cleanup of warning/errors.
1493
      assert((left_expr->fixed && select_lex->ref_pointer_array[i]->fixed) ||
1 by brian
clean slate
1494
                  (select_lex->ref_pointer_array[i]->type() == REF_ITEM &&
1495
                   ((Item_ref*)(select_lex->ref_pointer_array[i]))->ref_type() ==
1496
                    Item_ref::OUTER_REF));
1497
      if (select_lex->ref_pointer_array[i]->
1498
          check_cols(left_expr->element_index(i)->cols()))
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1499
        return(RES_ERROR);
1 by brian
clean slate
1500
      item=
1501
        new Item_func_eq(new
1502
                         Item_direct_ref(&select_lex->context,
1503
                                         (*optimizer->get_cache())->
1504
                                         addr(i),
1505
                                         (char *)"<no matter>",
1506
                                         (char *)in_left_expr_name),
1507
                         new
1508
                         Item_direct_ref(&select_lex->context,
1509
                                         select_lex->
1510
                                         ref_pointer_array+i,
1511
                                         (char *)"<no matter>",
1512
                                         (char *)"<list ref>")
1513
                        );
1514
      if (!abort_on_null)
1515
      {
1516
        Item *having_col_item=
1517
          new Item_is_not_null_test(this,
1518
                                    new
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1519
                                    Item_ref(&select_lex->context,
1 by brian
clean slate
1520
                                             select_lex->ref_pointer_array + i,
1521
                                             (char *)"<no matter>",
1522
                                             (char *)"<list ref>"));
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1523
1524
1 by brian
clean slate
1525
        item_isnull= new
1526
          Item_func_isnull(new
1527
                           Item_direct_ref(&select_lex->context,
1528
                                           select_lex->
1529
                                           ref_pointer_array+i,
1530
                                           (char *)"<no matter>",
1531
                                           (char *)"<list ref>")
1532
                          );
1533
        item= new Item_cond_or(item, item_isnull);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1534
        /*
1 by brian
clean slate
1535
          TODO: why we create the above for cases where the right part
1536
                cant be NULL?
1537
        */
1538
        if (left_expr->element_index(i)->maybe_null)
1539
        {
1540
          if (!(item= new Item_func_trig_cond(item, get_cond_guard(i))))
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1541
            return(RES_ERROR);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1542
          if (!(having_col_item=
1 by brian
clean slate
1543
                  new Item_func_trig_cond(having_col_item, get_cond_guard(i))))
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1544
            return(RES_ERROR);
1 by brian
clean slate
1545
        }
1546
        having_item= and_items(having_item, having_col_item);
1547
      }
1548
      where_item= and_items(where_item, item);
1549
    }
1550
    /*
1551
      AND can't be changed during fix_fields()
1552
      we can assign select_lex->where here, and pass 0 as last
1553
      argument (reference) to fix_fields()
1554
    */
1555
    select_lex->where= join->conds= and_items(join->conds, where_item);
1556
    select_lex->where->top_level_item();
520.1.22 by Brian Aker
Second pass of thd cleanup
1557
    if (join->conds->fix_fields(session, 0))
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1558
      return(RES_ERROR);
1 by brian
clean slate
1559
  }
1560
  if (having_item)
1561
  {
1562
    bool res;
1563
    select_lex->having= join->having= and_items(join->having, having_item);
1564
    if (having_item == select_lex->having)
1565
      having_item->name= (char*)in_having_cond;
1566
    select_lex->having->top_level_item();
1567
    /*
1568
      AND can't be changed during fix_fields()
1569
      we can assign select_lex->having here, and pass 0 as last
1570
      argument (reference) to fix_fields()
1571
    */
1572
    select_lex->having_fix_field= 1;
520.1.22 by Brian Aker
Second pass of thd cleanup
1573
    res= join->having->fix_fields(session, 0);
1 by brian
clean slate
1574
    select_lex->having_fix_field= 0;
1575
    if (res)
1576
    {
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1577
      return(RES_ERROR);
1 by brian
clean slate
1578
    }
1579
  }
1580
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1581
  return(RES_OK);
1 by brian
clean slate
1582
}
1583
1584
1585
Item_subselect::trans_res
1586
Item_in_subselect::select_transformer(JOIN *join)
1587
{
584.4.7 by Monty Taylor
Removed a big bank of includes from item.h.
1588
  return select_in_like_transformer(join, Eq_creator::instance());
1 by brian
clean slate
1589
}
1590
1591
1592
/**
1593
  Prepare IN/ALL/ANY/SOME subquery transformation and call appropriate
1594
  transformation function.
1595
1596
    To decide which transformation procedure (scalar or row) applicable here
1597
    we have to call fix_fields() for left expression to be able to call
1598
    cols() method on it. Also this method make arena management for
1599
    underlying transformation methods.
1600
1601
  @param join    JOIN object of transforming subquery
1602
  @param func    creator of condition function of subquery
1603
1604
  @retval
1605
    RES_OK      OK
1606
  @retval
1607
    RES_REDUCE  OK, and current subquery was reduced during
1608
    transformation
1609
  @retval
1610
    RES_ERROR   Error
1611
*/
1612
1613
Item_subselect::trans_res
584.4.7 by Monty Taylor
Removed a big bank of includes from item.h.
1614
Item_in_subselect::select_in_like_transformer(JOIN *join, const Comp_creator *func)
1 by brian
clean slate
1615
{
846 by Brian Aker
Removing on typedeffed class.
1616
  Select_Lex *current= session->lex->current_select, *up;
520.1.22 by Brian Aker
Second pass of thd cleanup
1617
  const char *save_where= session->where;
1 by brian
clean slate
1618
  Item_subselect::trans_res res= RES_ERROR;
1619
  bool result;
1620
1621
  {
1622
    /*
1623
      IN/SOME/ALL/ANY subqueries aren't support LIMIT clause. Without it
327.2.3 by Brian Aker
Refactoring of class Table
1624
      order_st BY clause becomes meaningless thus we drop it here.
1 by brian
clean slate
1625
    */
846 by Brian Aker
Removing on typedeffed class.
1626
    Select_Lex *sl= current->master_unit()->first_select();
1 by brian
clean slate
1627
    for (; sl; sl= sl->next_select())
1628
    {
1629
      if (sl->join)
1630
        sl->join->order= 0;
1631
    }
1632
  }
1633
1634
  if (changed)
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1635
    return(RES_OK);
1 by brian
clean slate
1636
520.1.22 by Brian Aker
Second pass of thd cleanup
1637
  session->where= "IN/ALL/ANY subquery";
1 by brian
clean slate
1638
1639
  /*
1640
    In some optimisation cases we will not need this Item_in_optimizer
1641
    object, but we can't know it here, but here we need address correct
1642
    reference on left expresion.
1643
  */
1644
  if (!optimizer)
1645
  {
1646
    result= (!(optimizer= new Item_in_optimizer(left_expr, this)));
1647
    if (result)
1648
      goto err;
1649
  }
1650
520.1.22 by Brian Aker
Second pass of thd cleanup
1651
  session->lex->current_select= up= current->return_after_parsing();
1 by brian
clean slate
1652
  result= (!left_expr->fixed &&
520.1.22 by Brian Aker
Second pass of thd cleanup
1653
           left_expr->fix_fields(session, optimizer->arguments()));
1 by brian
clean slate
1654
  /* fix_fields can change reference to left_expr, we need reassign it */
1655
  left_expr= optimizer->arguments()[0];
1656
520.1.22 by Brian Aker
Second pass of thd cleanup
1657
  session->lex->current_select= current;
1 by brian
clean slate
1658
  if (result)
1659
    goto err;
1660
1661
  /*
1662
    If we didn't choose an execution method up to this point, we choose
1663
    the IN=>EXISTS transformation.
1664
  */
1665
  if (exec_method == NOT_TRANSFORMED)
1666
    exec_method= IN_TO_EXISTS;
1667
1668
  /*
1669
    Both transformers call fix_fields() only for Items created inside them,
1670
    and all those items do not make permanent changes in the current item arena
1671
    which allows us to call them with changed arena (if we do not know the
1672
    nature of Item, we have to call fix_fields() for it only with the original
1673
    arena to avoid memory leak).
1674
  */
1675
  if (left_expr->cols() == 1)
1676
    res= single_value_transformer(join, func);
1677
  else
1678
  {
1679
    /* we do not support row operation for ALL/ANY/SOME */
584.4.7 by Monty Taylor
Removed a big bank of includes from item.h.
1680
    if (func != Eq_creator::instance())
1 by brian
clean slate
1681
    {
1682
      my_error(ER_OPERAND_COLUMNS, MYF(0), 1);
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1683
      return(RES_ERROR);
1 by brian
clean slate
1684
    }
1685
    res= row_value_transformer(join);
1686
  }
1687
err:
520.1.22 by Brian Aker
Second pass of thd cleanup
1688
  session->where= save_where;
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1689
  return(res);
1 by brian
clean slate
1690
}
1691
1692
1693
void Item_in_subselect::print(String *str, enum_query_type query_type)
1694
{
1695
  if (exec_method == IN_TO_EXISTS)
1696
    str->append(STRING_WITH_LEN("<exists>"));
1697
  else
1698
  {
1699
    left_expr->print(str, query_type);
1700
    str->append(STRING_WITH_LEN(" in "));
1701
  }
1702
  Item_subselect::print(str, query_type);
1703
}
1704
1705
520.1.22 by Brian Aker
Second pass of thd cleanup
1706
bool Item_in_subselect::fix_fields(Session *session_arg, Item **ref)
1 by brian
clean slate
1707
{
1708
  bool result = 0;
1709
1710
  if (exec_method == SEMI_JOIN)
1711
    return !( (*ref)= new Item_int(1));
1712
520.1.22 by Brian Aker
Second pass of thd cleanup
1713
  return result || Item_subselect::fix_fields(session_arg, ref);
1 by brian
clean slate
1714
}
1715
1716
1717
/**
1718
  Try to create an engine to compute the subselect via materialization,
1719
  and if this fails, revert to execution via the IN=>EXISTS transformation.
1720
1721
  @details
1722
    The purpose of this method is to hide the implementation details
1723
    of this Item's execution. The method creates a new engine for
1724
    materialized execution, and initializes the engine.
1725
1726
    If this initialization fails
1727
    - either because it wasn't possible to create the needed temporary table
1728
      and its index,
1729
    - or because of a memory allocation error,
1730
    then we revert back to execution via the IN=>EXISTS tranformation.
1731
1732
    The initialization of the new engine is divided in two parts - a permanent
1733
    one that lives across prepared statements, and one that is repeated for each
1734
    execution.
1735
1736
  @returns
55 by brian
Update for using real bool types.
1737
    @retval true  memory allocation error occurred
1738
    @retval false an execution method was chosen successfully
1 by brian
clean slate
1739
*/
1740
1741
bool Item_in_subselect::setup_engine()
1742
{
1743
  subselect_hash_sj_engine *new_engine= NULL;
55 by brian
Update for using real bool types.
1744
  bool res= false;
1 by brian
clean slate
1745
1746
  if (engine->engine_type() == subselect_engine::SINGLE_SELECT_ENGINE)
1747
  {
1748
    /* Create/initialize objects in permanent memory. */
779.3.10 by Monty Taylor
Turned on -Wshadow.
1749
    subselect_single_select_engine *old_engine_ptr;
1 by brian
clean slate
1750
779.3.10 by Monty Taylor
Turned on -Wshadow.
1751
    old_engine_ptr= static_cast<subselect_single_select_engine *>(engine);
1 by brian
clean slate
1752
520.1.22 by Brian Aker
Second pass of thd cleanup
1753
    if (!(new_engine= new subselect_hash_sj_engine(session, this,
779.3.10 by Monty Taylor
Turned on -Wshadow.
1754
                                                   old_engine_ptr)) ||
1 by brian
clean slate
1755
        new_engine->init_permanent(unit->get_unit_column_types()))
1756
    {
779.3.10 by Monty Taylor
Turned on -Wshadow.
1757
      Item_subselect::trans_res new_trans_res;
1 by brian
clean slate
1758
      /*
1759
        If for some reason we cannot use materialization for this IN predicate,
1760
        delete all materialization-related objects, and apply the IN=>EXISTS
1761
        transformation.
1762
      */
1763
      delete new_engine;
1764
      new_engine= NULL;
1765
      exec_method= NOT_TRANSFORMED;
1766
      if (left_expr->cols() == 1)
779.3.10 by Monty Taylor
Turned on -Wshadow.
1767
        new_trans_res= single_value_in_to_exists_transformer(
1768
                           old_engine_ptr->join,
1769
                           Eq_creator::instance());
1 by brian
clean slate
1770
      else
779.3.10 by Monty Taylor
Turned on -Wshadow.
1771
        new_trans_res= row_value_in_to_exists_transformer(old_engine_ptr->join);
1772
      res= (new_trans_res != Item_subselect::RES_OK);
1 by brian
clean slate
1773
    }
1774
    if (new_engine)
1775
      engine= new_engine;
1776
  }
1777
  else
1778
  {
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1779
    assert(engine->engine_type() == subselect_engine::HASH_SJ_ENGINE);
779.3.10 by Monty Taylor
Turned on -Wshadow.
1780
    new_engine= static_cast<subselect_hash_sj_engine *>(engine);
1 by brian
clean slate
1781
  }
1782
1783
  /* Initilizations done in runtime memory, repeated for each execution. */
1784
  if (new_engine)
1785
  {
1786
    /*
1787
      Reset the LIMIT 1 set in Item_exists_subselect::fix_length_and_dec.
1788
      TODO:
1789
      Currently we set the subquery LIMIT to infinity, and this is correct
1790
      because we forbid at parse time LIMIT inside IN subqueries (see
1791
      Item_in_subselect::test_limit). However, once we allow this, here
1792
      we should set the correct limit if given in the query.
1793
    */
1794
    unit->global_parameters->select_limit= NULL;
1795
    if ((res= new_engine->init_runtime()))
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1796
      return(res);
1 by brian
clean slate
1797
  }
1798
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1799
  return(res);
1 by brian
clean slate
1800
}
1801
1802
1803
/**
1804
  Initialize the cache of the left operand of the IN predicate.
1805
1806
  @note This method has the same purpose as alloc_group_fields(),
1807
  but it takes a different kind of collection of items, and the
1808
  list we push to is dynamically allocated.
1809
55 by brian
Update for using real bool types.
1810
  @retval true  if a memory allocation error occurred or the cache is
1 by brian
clean slate
1811
                not applicable to the current query
55 by brian
Update for using real bool types.
1812
  @retval false if success
1 by brian
clean slate
1813
*/
1814
1815
bool Item_in_subselect::init_left_expr_cache()
1816
{
1817
  JOIN *outer_join;
1818
  Next_select_func end_select;
55 by brian
Update for using real bool types.
1819
  bool use_result_field= false;
1 by brian
clean slate
1820
1821
  outer_join= unit->outer_select()->join;
1822
  if (!outer_join || !outer_join->tables)
55 by brian
Update for using real bool types.
1823
    return true;
1 by brian
clean slate
1824
  /*
1825
    If we use end_[send | write]_group to handle complete rows of the outer
1826
    query, make the cache of the left IN operand use Item_field::result_field
1827
    instead of Item_field::field.  We need this because normally
1828
    Cached_item_field uses Item::field to fetch field data, while
1829
    copy_ref_key() that copies the left IN operand into a lookup key uses
1830
    Item::result_field. In the case end_[send | write]_group result_field is
1831
    one row behind field.
1832
  */
1833
  end_select= outer_join->join_tab[outer_join->tables-1].next_select;
1834
  if (end_select == end_send_group || end_select == end_write_group)
55 by brian
Update for using real bool types.
1835
    use_result_field= true;
1 by brian
clean slate
1836
1101.1.16 by Monty Taylor
Reverted 1103
1837
  if (!(left_expr_cache= new List<Cached_item>))
1838
    return true;
1 by brian
clean slate
1839
482 by Brian Aker
Remove uint.
1840
  for (uint32_t i= 0; i < left_expr->cols(); i++)
1 by brian
clean slate
1841
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
1842
    Cached_item *cur_item_cache= new_Cached_item(session,
1 by brian
clean slate
1843
                                                 left_expr->element_index(i),
1844
                                                 use_result_field);
1101.1.16 by Monty Taylor
Reverted 1103
1845
    if (!cur_item_cache || left_expr_cache->push_front(cur_item_cache))
55 by brian
Update for using real bool types.
1846
      return true;
1 by brian
clean slate
1847
  }
55 by brian
Update for using real bool types.
1848
  return false;
1 by brian
clean slate
1849
}
1850
1851
1852
/*
1853
  Callback to test if an IN predicate is expensive.
1854
1855
  @details
1856
    IN predicates are considered expensive only if they will be executed via
1857
    materialization. The return value affects the behavior of
1858
    make_cond_for_table() in such a way that it is unchanged when we use
1859
    the IN=>EXISTS transformation to compute IN.
1860
55 by brian
Update for using real bool types.
1861
  @retval true  if the predicate is expensive
1862
  @retval false otherwise
1 by brian
clean slate
1863
*/
1864
779.1.27 by Monty Taylor
Got rid of __attribute__((unused)) and the like from the .cc files.
1865
bool Item_in_subselect::is_expensive_processor(unsigned char *)
1 by brian
clean slate
1866
{
1867
  return exec_method == MATERIALIZATION;
1868
}
1869
1870
1871
Item_subselect::trans_res
1872
Item_allany_subselect::select_transformer(JOIN *join)
1873
{
1874
  exec_method= IN_TO_EXISTS;
1875
  if (upper_item)
1876
    upper_item->show= 1;
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1877
  return(select_in_like_transformer(join, func));
1 by brian
clean slate
1878
}
1879
1880
1881
void Item_allany_subselect::print(String *str, enum_query_type query_type)
1882
{
1883
  if (exec_method == IN_TO_EXISTS)
1884
    str->append(STRING_WITH_LEN("<exists>"));
1885
  else
1886
  {
1887
    left_expr->print(str, query_type);
1888
    str->append(' ');
1889
    str->append(func->symbol(all));
1890
    str->append(all ? " all " : " any ", 5);
1891
  }
1892
  Item_subselect::print(str, query_type);
1893
}
1894
1895
520.1.22 by Brian Aker
Second pass of thd cleanup
1896
void subselect_engine::set_session(Session *session_arg)
1 by brian
clean slate
1897
{
520.1.22 by Brian Aker
Second pass of thd cleanup
1898
  session= session_arg;
1 by brian
clean slate
1899
  if (result)
520.1.22 by Brian Aker
Second pass of thd cleanup
1900
    result->set_session(session_arg);
1 by brian
clean slate
1901
}
1902
1903
1904
subselect_single_select_engine::
846 by Brian Aker
Removing on typedeffed class.
1905
subselect_single_select_engine(Select_Lex *select,
1 by brian
clean slate
1906
			       select_result_interceptor *result_arg,
1907
			       Item_subselect *item_arg)
1908
  :subselect_engine(item_arg, result_arg),
1909
   prepared(0), executed(0), select_lex(select), join(0)
1910
{
1911
  select_lex->master_unit()->item= item_arg;
1912
}
1913
1914
1915
void subselect_single_select_engine::cleanup()
1916
{
1917
  prepared= executed= 0;
1918
  join= 0;
1919
  result->cleanup();
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1920
  return;
1 by brian
clean slate
1921
}
1922
1923
1924
void subselect_union_engine::cleanup()
1925
{
1926
  unit->reinit_exec_mechanism();
1927
  result->cleanup();
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1928
  return;
1 by brian
clean slate
1929
}
1930
1931
1932
bool subselect_union_engine::is_executed() const
1933
{
1934
  return unit->executed;
1935
}
1936
1937
1938
/*
1939
  Check if last execution of the subquery engine produced any rows
1940
1941
  SYNOPSIS
1942
    subselect_union_engine::no_rows()
1943
1944
  DESCRIPTION
1945
    Check if last execution of the subquery engine produced any rows. The
1946
    return value is undefined if last execution ended in an error.
1947
1948
  RETURN
55 by brian
Update for using real bool types.
1949
    true  - Last subselect execution has produced no rows
1950
    false - Otherwise
1 by brian
clean slate
1951
*/
1952
1953
bool subselect_union_engine::no_rows()
1954
{
1955
  /* Check if we got any rows when reading UNION result from temp. table: */
1956
  return test(!unit->fake_select_lex->join->send_records);
1957
}
1958
1959
1960
void subselect_uniquesubquery_engine::cleanup()
1961
{
1962
  /* Tell handler we don't need the index anymore */
1963
  if (tab->table->file->inited)
1964
    tab->table->file->ha_index_end();
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
1965
  return;
1 by brian
clean slate
1966
}
1967
1968
848 by Brian Aker
typdef class removal (just... use the name of the class).
1969
subselect_union_engine::subselect_union_engine(Select_Lex_Unit *u,
1 by brian
clean slate
1970
					       select_result_interceptor *result_arg,
1971
					       Item_subselect *item_arg)
1972
  :subselect_engine(item_arg, result_arg)
1973
{
1974
  unit= u;
1975
  unit->item= item_arg;
1976
}
1977
1978
1979
/**
1980
  Create and prepare the JOIN object that represents the query execution
1981
  plan for the subquery.
1982
1983
  @detail
1984
  This method is called from Item_subselect::fix_fields. For prepared
1985
  statements it is called both during the PREPARE and EXECUTE phases in the
1986
  following ways:
1987
  - During PREPARE the optimizer needs some properties
1988
    (join->fields_list.elements) of the JOIN to proceed with preparation of
1989
    the remaining query (namely to complete ::fix_fields for the subselect
1990
    related classes. In the end of PREPARE the JOIN is deleted.
1991
  - When we EXECUTE the query, Item_subselect::fix_fields is called again, and
1992
    the JOIN object is re-created again, prepared and executed. In the end of
1993
    execution it is deleted.
1994
  In all cases the JOIN is created in runtime memory (not in the permanent
1995
  memory root).
1996
1997
  @todo
1998
  Re-check what properties of 'join' are needed during prepare, and see if
1999
  we can avoid creating a JOIN during JOIN::prepare of the outer join.
2000
2001
  @retval 0  if success
2002
  @retval 1  if error
2003
*/
2004
2005
int subselect_single_select_engine::prepare()
2006
{
2007
  if (prepared)
2008
    return 0;
520.1.22 by Brian Aker
Second pass of thd cleanup
2009
  join= new JOIN(session, select_lex->item_list,
1 by brian
clean slate
2010
		 select_lex->options | SELECT_NO_UNLOCK, result);
2011
  if (!join || !result)
2012
    return 1; /* Fatal error is set already. */
2013
  prepared= 1;
846 by Brian Aker
Removing on typedeffed class.
2014
  Select_Lex *save_select= session->lex->current_select;
520.1.22 by Brian Aker
Second pass of thd cleanup
2015
  session->lex->current_select= select_lex;
1 by brian
clean slate
2016
  if (join->prepare(&select_lex->ref_pointer_array,
327.2.4 by Brian Aker
Refactoring table.h
2017
		    (TableList*) select_lex->table_list.first,
1 by brian
clean slate
2018
		    select_lex->with_wild,
2019
		    select_lex->where,
2020
		    select_lex->order_list.elements +
2021
		    select_lex->group_list.elements,
327.2.3 by Brian Aker
Refactoring of class Table
2022
		    (order_st*) select_lex->order_list.first,
2023
		    (order_st*) select_lex->group_list.first,
1 by brian
clean slate
2024
		    select_lex->having,
923.1.10 by Brian Aker
Remove dead code around old procedures.
2025
		    select_lex, select_lex->master_unit()))
1 by brian
clean slate
2026
    return 1;
520.1.22 by Brian Aker
Second pass of thd cleanup
2027
  session->lex->current_select= save_select;
1 by brian
clean slate
2028
  return 0;
2029
}
2030
2031
int subselect_union_engine::prepare()
2032
{
779.3.18 by Monty Taylor
Cleaned up warnings up through innodb.
2033
  return unit->prepare(session, result, (uint32_t)SELECT_NO_UNLOCK);
1 by brian
clean slate
2034
}
2035
2036
int subselect_uniquesubquery_engine::prepare()
2037
{
2038
  /* Should never be called. */
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
2039
  assert(false);
1 by brian
clean slate
2040
  return 1;
2041
}
2042
2043
2044
/*
2045
  Check if last execution of the subquery engine produced any rows
2046
2047
  SYNOPSIS
2048
    subselect_single_select_engine::no_rows()
2049
2050
  DESCRIPTION
2051
    Check if last execution of the subquery engine produced any rows. The
2052
    return value is undefined if last execution ended in an error.
2053
2054
  RETURN
55 by brian
Update for using real bool types.
2055
    true  - Last subselect execution has produced no rows
2056
    false - Otherwise
1 by brian
clean slate
2057
*/
2058
2059
bool subselect_single_select_engine::no_rows()
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2060
{
1 by brian
clean slate
2061
  return !item->assigned();
2062
}
2063
2064
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2065
/*
2066
 makes storage for the output values for the subquery and calcuates
1 by brian
clean slate
2067
 their data and column types and their nullability.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2068
*/
1 by brian
clean slate
2069
void subselect_engine::set_row(List<Item> &item_list, Item_cache **row)
2070
{
2071
  Item *sel_item;
2072
  List_iterator_fast<Item> li(item_list);
2073
  res_type= STRING_RESULT;
241 by Brian Aker
First pass of CHAR removal.
2074
  res_field_type= DRIZZLE_TYPE_VARCHAR;
482 by Brian Aker
Remove uint.
2075
  for (uint32_t i= 0; (sel_item= li++); i++)
1 by brian
clean slate
2076
  {
2077
    item->max_length= sel_item->max_length;
2078
    res_type= sel_item->result_type();
2079
    res_field_type= sel_item->field_type();
2080
    item->decimals= sel_item->decimals;
2081
    item->unsigned_flag= sel_item->unsigned_flag;
2082
    maybe_null= sel_item->maybe_null;
2083
    if (!(row[i]= Item_cache::get_cache(sel_item)))
2084
      return;
2085
    row[i]->setup(sel_item);
2086
  }
2087
  if (item_list.elements > 1)
2088
    res_type= ROW_RESULT;
2089
}
2090
2091
void subselect_single_select_engine::fix_length_and_dec(Item_cache **row)
2092
{
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
2093
  assert(row || select_lex->item_list.elements==1);
1 by brian
clean slate
2094
  set_row(select_lex->item_list, row);
2095
  item->collation.set(row[0]->collation);
2096
  if (cols() != 1)
2097
    maybe_null= 0;
2098
}
2099
2100
void subselect_union_engine::fix_length_and_dec(Item_cache **row)
2101
{
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
2102
  assert(row || unit->first_select()->item_list.elements==1);
1 by brian
clean slate
2103
2104
  if (unit->first_select()->item_list.elements == 1)
2105
  {
2106
    set_row(unit->types, row);
2107
    item->collation.set(row[0]->collation);
2108
  }
2109
  else
2110
  {
2111
    bool maybe_null_saved= maybe_null;
2112
    set_row(unit->types, row);
2113
    maybe_null= maybe_null_saved;
2114
  }
2115
}
2116
779.1.27 by Monty Taylor
Got rid of __attribute__((unused)) and the like from the .cc files.
2117
void subselect_uniquesubquery_engine::fix_length_and_dec(Item_cache **)
1 by brian
clean slate
2118
{
2119
  //this never should be called
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
2120
  assert(0);
1 by brian
clean slate
2121
}
2122
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
2123
int  init_read_record_seq(JoinTable *tab);
2124
int join_read_always_key_or_null(JoinTable *tab);
1 by brian
clean slate
2125
int join_read_next_same_or_null(READ_RECORD *info);
2126
2127
int subselect_single_select_engine::exec()
2128
{
520.1.22 by Brian Aker
Second pass of thd cleanup
2129
  char const *save_where= session->where;
846 by Brian Aker
Removing on typedeffed class.
2130
  Select_Lex *save_select= session->lex->current_select;
520.1.22 by Brian Aker
Second pass of thd cleanup
2131
  session->lex->current_select= select_lex;
1 by brian
clean slate
2132
  if (!join->optimized)
2133
  {
848 by Brian Aker
typdef class removal (just... use the name of the class).
2134
    Select_Lex_Unit *unit= select_lex->master_unit();
1 by brian
clean slate
2135
2136
    unit->set_limit(unit->global_parameters);
2137
    if (join->optimize())
2138
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
2139
      session->where= save_where;
1 by brian
clean slate
2140
      executed= 1;
520.1.22 by Brian Aker
Second pass of thd cleanup
2141
      session->lex->current_select= save_select;
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
2142
      return(join->error ? join->error : 1);
1 by brian
clean slate
2143
    }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2144
    if (!select_lex->uncacheable && session->lex->describe &&
2145
        !(join->select_options & SELECT_DESCRIBE) &&
1 by brian
clean slate
2146
        join->need_tmp && item->const_item())
2147
    {
2148
      /*
2149
        Force join->join_tmp creation, because this subquery will be replaced
2150
        by a simple select from the materialization temp table by optimize()
2151
        called by EXPLAIN and we need to preserve the initial query structure
2152
        so we can display it.
2153
       */
2154
      select_lex->uncacheable|= UNCACHEABLE_EXPLAIN;
2155
      select_lex->master_unit()->uncacheable|= UNCACHEABLE_EXPLAIN;
2156
      if (join->init_save_join_tab())
971.6.11 by Eric Day
Removed purecov messages.
2157
        return(1);
1 by brian
clean slate
2158
    }
2159
    if (item->engine_changed)
2160
    {
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
2161
      return(1);
1 by brian
clean slate
2162
    }
2163
  }
2164
  if (select_lex->uncacheable &&
2165
      select_lex->uncacheable != UNCACHEABLE_EXPLAIN
2166
      && executed)
2167
  {
2168
    if (join->reinit())
2169
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
2170
      session->where= save_where;
2171
      session->lex->current_select= save_select;
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
2172
      return(1);
1 by brian
clean slate
2173
    }
2174
    item->reset();
2175
    item->assigned((executed= 0));
2176
  }
2177
  if (!executed)
2178
  {
2179
    item->reset_value_registration();
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
2180
    JoinTable *changed_tabs[MAX_TABLES];
2181
    JoinTable **last_changed_tab= changed_tabs;
1 by brian
clean slate
2182
    if (item->have_guarded_conds())
2183
    {
2184
      /*
2185
        For at least one of the pushed predicates the following is true:
2186
        We should not apply optimizations based on the condition that was
2187
        pushed down into the subquery. Those optimizations are ref[_or_null]
2188
        acceses. Change them to be full table scans.
2189
      */
482 by Brian Aker
Remove uint.
2190
      for (uint32_t i=join->const_tables ; i < join->tables ; i++)
1 by brian
clean slate
2191
      {
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
2192
        JoinTable *tab=join->join_tab+i;
1 by brian
clean slate
2193
        if (tab && tab->keyuse)
2194
        {
779.3.10 by Monty Taylor
Turned on -Wshadow.
2195
          for (uint32_t key_part= 0;
2196
               key_part < tab->ref.key_parts;
2197
               key_part++)
1 by brian
clean slate
2198
          {
779.3.10 by Monty Taylor
Turned on -Wshadow.
2199
            bool *cond_guard= tab->ref.cond_guards[key_part];
1 by brian
clean slate
2200
            if (cond_guard && !*cond_guard)
2201
            {
2202
              /* Change the access method to full table scan */
2203
              tab->save_read_first_record= tab->read_first_record;
2204
              tab->save_read_record= tab->read_record.read_record;
2205
              tab->read_first_record= init_read_record_seq;
2206
              tab->read_record.record= tab->table->record[0];
520.1.22 by Brian Aker
Second pass of thd cleanup
2207
              tab->read_record.session= join->session;
1 by brian
clean slate
2208
              tab->read_record.ref_length= tab->table->file->ref_length;
2209
              *(last_changed_tab++)= tab;
2210
              break;
2211
            }
2212
          }
2213
        }
2214
      }
2215
    }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2216
1 by brian
clean slate
2217
    join->exec();
2218
2219
    /* Enable the optimizations back */
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
2220
    for (JoinTable **ptab= changed_tabs; ptab != last_changed_tab; ptab++)
1 by brian
clean slate
2221
    {
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
2222
      JoinTable *tab= *ptab;
1 by brian
clean slate
2223
      tab->read_record.record= 0;
2224
      tab->read_record.ref_length= 0;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2225
      tab->read_first_record= tab->save_read_first_record;
1 by brian
clean slate
2226
      tab->read_record.read_record= tab->save_read_record;
2227
    }
2228
    executed= 1;
520.1.22 by Brian Aker
Second pass of thd cleanup
2229
    session->where= save_where;
2230
    session->lex->current_select= save_select;
2231
    return(join->error||session->is_fatal_error);
1 by brian
clean slate
2232
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
2233
  session->where= save_where;
2234
  session->lex->current_select= save_select;
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
2235
  return(0);
1 by brian
clean slate
2236
}
2237
2238
int subselect_union_engine::exec()
2239
{
520.1.22 by Brian Aker
Second pass of thd cleanup
2240
  char const *save_where= session->where;
1 by brian
clean slate
2241
  int res= unit->exec();
520.1.22 by Brian Aker
Second pass of thd cleanup
2242
  session->where= save_where;
1 by brian
clean slate
2243
  return res;
2244
}
2245
2246
2247
/*
2248
  Search for at least one row satisfying select condition
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2249
1 by brian
clean slate
2250
  SYNOPSIS
2251
    subselect_uniquesubquery_engine::scan_table()
2252
2253
  DESCRIPTION
2254
    Scan the table using sequential access until we find at least one row
2255
    satisfying select condition.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2256
55 by brian
Update for using real bool types.
2257
    The caller must set this->empty_result_set=false before calling this
2258
    function. This function will set it to true if it finds a matching row.
1 by brian
clean slate
2259
2260
  RETURN
55 by brian
Update for using real bool types.
2261
    false - OK
2262
    true  - Error
1 by brian
clean slate
2263
*/
2264
2265
int subselect_uniquesubquery_engine::scan_table()
2266
{
2267
  int error;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
2268
  Table *table= tab->table;
1 by brian
clean slate
2269
2270
  if (table->file->inited)
2271
    table->file->ha_index_end();
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2272
1 by brian
clean slate
2273
  table->file->ha_rnd_init(1);
2274
  table->file->extra_opt(HA_EXTRA_CACHE,
520.1.22 by Brian Aker
Second pass of thd cleanup
2275
                         current_session->variables.read_buff_size);
1 by brian
clean slate
2276
  table->null_row= 0;
2277
  for (;;)
2278
  {
2279
    error=table->file->rnd_next(table->record[0]);
2280
    if (error && error != HA_ERR_END_OF_FILE)
2281
    {
354 by Brian Aker
Refactor of Table methods.
2282
      error= table->report_error(error);
1 by brian
clean slate
2283
      break;
2284
    }
2285
    /* No more rows */
2286
    if (table->status)
2287
      break;
2288
2289
    if (!cond || cond->val_int())
2290
    {
55 by brian
Update for using real bool types.
2291
      empty_result_set= false;
1 by brian
clean slate
2292
      break;
2293
    }
2294
  }
2295
2296
  table->file->ha_rnd_end();
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
2297
  return(error != 0);
1 by brian
clean slate
2298
}
2299
2300
2301
/*
2302
  Copy ref key and check for null parts in it
2303
2304
  SYNOPSIS
2305
    subselect_uniquesubquery_engine::copy_ref_key()
2306
2307
  DESCRIPTION
2308
    Copy ref key and check for null parts in it.
2309
    Depending on the nullability and conversion problems this function
2310
    recognizes and processes the following states :
55 by brian
Update for using real bool types.
2311
      1. Partial match on top level. This means IN has a value of false
1 by brian
clean slate
2312
         regardless of the data in the subquery table.
2313
         Detected by finding a NULL in the left IN operand of a top level
2314
         expression.
55 by brian
Update for using real bool types.
2315
         We may actually skip reading the subquery, so return true to skip
1 by brian
clean slate
2316
         the table scan in subselect_uniquesubquery_engine::exec and make
55 by brian
Update for using real bool types.
2317
         the value of the IN predicate a NULL (that is equal to false on
1 by brian
clean slate
2318
         top level).
2319
      2. No exact match when IN is nested inside another predicate.
2320
         Detected by finding a NULL in the left IN operand when IN is not
2321
         a top level predicate.
2322
         We cannot have an exact match. But we must proceed further with a
2323
         table scan to find out if it's a partial match (and IN has a value
55 by brian
Update for using real bool types.
2324
         of NULL) or no match (and IN has a value of false).
2325
         So we return false to continue with the scan and see if there are
1 by brian
clean slate
2326
         any record that would constitute a partial match (as we cannot
2327
         determine that from the index).
2328
      3. Error converting the left IN operand to the column type of the
2329
         right IN operand. This counts as no match (and IN has the value of
55 by brian
Update for using real bool types.
2330
         false). We mark the subquery table cursor as having no more rows
1 by brian
clean slate
2331
         (to ensure that the processing that follows will not find a match)
55 by brian
Update for using real bool types.
2332
         and return false, so IN is not treated as returning NULL.
1 by brian
clean slate
2333
2334
2335
  RETURN
55 by brian
Update for using real bool types.
2336
    false - The value of the IN predicate is not known. Proceed to find the
1 by brian
clean slate
2337
            value of the IN predicate using the determined values of
2338
            null_keypart and table->status.
55 by brian
Update for using real bool types.
2339
    true  - IN predicate has a value of NULL. Stop the processing right there
1 by brian
clean slate
2340
            and return NULL to the outer predicates.
2341
*/
2342
2343
bool subselect_uniquesubquery_engine::copy_ref_key()
2344
{
1039.2.3 by Jay Pipes
Phase 3 of refactoring JOIN
2345
  for (StoredKey **copy= tab->ref.key_copy ; *copy ; copy++)
1 by brian
clean slate
2346
  {
1039.2.3 by Jay Pipes
Phase 3 of refactoring JOIN
2347
    enum StoredKey::store_key_result store_res;
1 by brian
clean slate
2348
    store_res= (*copy)->copy();
2349
    tab->ref.key_err= store_res;
2350
2351
    /*
2352
      When there is a NULL part in the key we don't need to make index
2353
      lookup for such key thus we don't need to copy whole key.
2354
      If we later should do a sequential scan return OK. Fail otherwise.
2355
2356
      See also the comment for the subselect_uniquesubquery_engine::exec()
2357
      function.
2358
    */
2359
    null_keypart= (*copy)->null_key;
2360
    if (null_keypart)
2361
    {
2362
      bool top_level= ((Item_in_subselect *) item)->is_top_level_item();
2363
      if (top_level)
2364
      {
2365
        /* Partial match on top level */
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
2366
        return(1);
1 by brian
clean slate
2367
      }
2368
      else
2369
      {
2370
        /* No exact match when IN is nested inside another predicate */
2371
        break;
2372
      }
2373
    }
2374
2375
    /*
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2376
      Check if the error is equal to STORE_KEY_FATAL. This is not expressed
1039.2.3 by Jay Pipes
Phase 3 of refactoring JOIN
2377
      using the StoredKey::store_key_result enum because ref.key_err is a
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2378
      boolean and we want to detect both true and STORE_KEY_FATAL from the
2379
      space of the union of the values of [true, false] and
1039.2.3 by Jay Pipes
Phase 3 of refactoring JOIN
2380
      StoredKey::store_key_result.
1 by brian
clean slate
2381
      TODO: fix the variable an return types.
2382
    */
1039.2.3 by Jay Pipes
Phase 3 of refactoring JOIN
2383
    if (store_res == StoredKey::STORE_KEY_FATAL)
1 by brian
clean slate
2384
    {
2385
      /*
2386
       Error converting the left IN operand to the column type of the right
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2387
       IN operand.
1 by brian
clean slate
2388
      */
2389
      tab->table->status= STATUS_NOT_FOUND;
2390
      break;
2391
    }
2392
  }
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
2393
  return(0);
1 by brian
clean slate
2394
}
2395
2396
2397
/*
2398
  Execute subselect
2399
2400
  SYNOPSIS
2401
    subselect_uniquesubquery_engine::exec()
2402
2403
  DESCRIPTION
2404
    Find rows corresponding to the ref key using index access.
2405
    If some part of the lookup key is NULL, then we're evaluating
2406
      NULL IN (SELECT ... )
2407
    This is a special case, we don't need to search for NULL in the table,
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2408
    instead, the result value is
1 by brian
clean slate
2409
      - NULL  if select produces empty row set
55 by brian
Update for using real bool types.
2410
      - false otherwise.
1 by brian
clean slate
2411
55 by brian
Update for using real bool types.
2412
    In some cases (IN subselect is a top level item, i.e. abort_on_null==true)
2413
    the caller doesn't distinguish between NULL and false result and we just
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2414
    return false.
2415
    Otherwise we make a full table scan to see if there is at least one
1 by brian
clean slate
2416
    matching row.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2417
1 by brian
clean slate
2418
    The result of this function (info about whether a row was found) is
2419
    stored in this->empty_result_set.
2420
  NOTE
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2421
1 by brian
clean slate
2422
  RETURN
55 by brian
Update for using real bool types.
2423
    false - ok
2424
    true  - an error occured while scanning
1 by brian
clean slate
2425
*/
2426
2427
int subselect_uniquesubquery_engine::exec()
2428
{
2429
  int error;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
2430
  Table *table= tab->table;
55 by brian
Update for using real bool types.
2431
  empty_result_set= true;
1 by brian
clean slate
2432
  table->status= 0;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2433
1 by brian
clean slate
2434
  /* TODO: change to use of 'full_scan' here? */
2435
  if (copy_ref_key())
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
2436
    return(1);
1 by brian
clean slate
2437
  if (table->status)
2438
  {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2439
    /*
2440
      We know that there will be no rows even if we scan.
1 by brian
clean slate
2441
      Can be set in copy_ref_key.
2442
    */
2443
    ((Item_in_subselect *) item)->value= 0;
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
2444
    return(0);
1 by brian
clean slate
2445
  }
2446
2447
  if (null_keypart)
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
2448
    return(scan_table());
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2449
1 by brian
clean slate
2450
  if (!table->file->inited)
2451
    table->file->ha_index_init(tab->ref.key, 0);
2452
  error= table->file->index_read_map(table->record[0],
2453
                                     tab->ref.key_buff,
2454
                                     make_prev_keypart_map(tab->ref.key_parts),
2455
                                     HA_READ_KEY_EXACT);
2456
  if (error &&
2457
      error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
354 by Brian Aker
Refactor of Table methods.
2458
    error= table->report_error(error);
1 by brian
clean slate
2459
  else
2460
  {
2461
    error= 0;
2462
    table->null_row= 0;
2463
    if (!table->status && (!cond || cond->val_int()))
2464
    {
2465
      ((Item_in_subselect *) item)->value= 1;
55 by brian
Update for using real bool types.
2466
      empty_result_set= false;
1 by brian
clean slate
2467
    }
2468
    else
2469
      ((Item_in_subselect *) item)->value= 0;
2470
  }
2471
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
2472
  return(error != 0);
1 by brian
clean slate
2473
}
2474
2475
2476
/*
2477
  Index-lookup subselect 'engine' - run the subquery
2478
2479
  SYNOPSIS
2480
    subselect_indexsubquery_engine:exec()
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2481
      full_scan
1 by brian
clean slate
2482
2483
  DESCRIPTION
2484
    The engine is used to resolve subqueries in form
2485
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2486
      oe IN (SELECT key FROM tbl WHERE subq_where)
1 by brian
clean slate
2487
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2488
    The value of the predicate is calculated as follows:
1 by brian
clean slate
2489
    1. If oe IS NULL, this is a special case, do a full table scan on
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2490
       table tbl and search for row that satisfies subq_where. If such
55 by brian
Update for using real bool types.
2491
       row is found, return NULL, otherwise return false.
1 by brian
clean slate
2492
    2. Make an index lookup via key=oe, search for a row that satisfies
55 by brian
Update for using real bool types.
2493
       subq_where. If found, return true.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2494
    3. If check_null==true, make another lookup via key=NULL, search for a
1 by brian
clean slate
2495
       row that satisfies subq_where. If found, return NULL, otherwise
55 by brian
Update for using real bool types.
2496
       return false.
1 by brian
clean slate
2497
2498
  TODO
2499
    The step #1 can be optimized further when the index has several key
2500
    parts. Consider a subquery:
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2501
1 by brian
clean slate
2502
      (oe1, oe2) IN (SELECT keypart1, keypart2 FROM tbl WHERE subq_where)
2503
2504
    and suppose we need to evaluate it for {oe1, oe2}=={const1, NULL}.
2505
    Current code will do a full table scan and obtain correct result. There
2506
    is a better option: instead of evaluating
2507
2508
      SELECT keypart1, keypart2 FROM tbl WHERE subq_where            (1)
2509
2510
    and checking if it has produced any matching rows, evaluate
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2511
1 by brian
clean slate
2512
      SELECT keypart2 FROM tbl WHERE subq_where AND keypart1=const1  (2)
2513
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2514
    If this query produces a row, the result is NULL (as we're evaluating
1 by brian
clean slate
2515
    "(const1, NULL) IN { (const1, X), ... }", which has a value of UNKNOWN,
55 by brian
Update for using real bool types.
2516
    i.e. NULL).  If the query produces no rows, the result is false.
1 by brian
clean slate
2517
2518
    We currently evaluate (1) by doing a full table scan. (2) can be
2519
    evaluated by doing a "ref" scan on "keypart1=const1", which can be much
2520
    cheaper. We can use index statistics to quickly check whether "ref" scan
2521
    will be cheaper than full table scan.
2522
2523
  RETURN
2524
    0
2525
    1
2526
*/
2527
2528
int subselect_indexsubquery_engine::exec()
2529
{
2530
  int error;
2531
  bool null_finding= 0;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
2532
  Table *table= tab->table;
1 by brian
clean slate
2533
2534
  ((Item_in_subselect *) item)->value= 0;
55 by brian
Update for using real bool types.
2535
  empty_result_set= true;
1 by brian
clean slate
2536
  null_keypart= 0;
2537
  table->status= 0;
2538
2539
  if (check_null)
2540
  {
2541
    /* We need to check for NULL if there wasn't a matching value */
2542
    *tab->ref.null_ref_key= 0;			// Search first for not null
2543
    ((Item_in_subselect *) item)->was_null= 0;
2544
  }
2545
2546
  /* Copy the ref key and check for nulls... */
2547
  if (copy_ref_key())
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
2548
    return(1);
1 by brian
clean slate
2549
2550
  if (table->status)
2551
  {
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2552
    /*
2553
      We know that there will be no rows even if we scan.
1 by brian
clean slate
2554
      Can be set in copy_ref_key.
2555
    */
2556
    ((Item_in_subselect *) item)->value= 0;
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
2557
    return(0);
1 by brian
clean slate
2558
  }
2559
2560
  if (null_keypart)
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
2561
    return(scan_table());
1 by brian
clean slate
2562
2563
  if (!table->file->inited)
2564
    table->file->ha_index_init(tab->ref.key, 1);
2565
  error= table->file->index_read_map(table->record[0],
2566
                                     tab->ref.key_buff,
2567
                                     make_prev_keypart_map(tab->ref.key_parts),
2568
                                     HA_READ_KEY_EXACT);
2569
  if (error &&
2570
      error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
354 by Brian Aker
Refactor of Table methods.
2571
    error= table->report_error(error);
1 by brian
clean slate
2572
  else
2573
  {
2574
    for (;;)
2575
    {
2576
      error= 0;
2577
      table->null_row= 0;
2578
      if (!table->status)
2579
      {
2580
        if ((!cond || cond->val_int()) && (!having || having->val_int()))
2581
        {
55 by brian
Update for using real bool types.
2582
          empty_result_set= false;
1 by brian
clean slate
2583
          if (null_finding)
2584
            ((Item_in_subselect *) item)->was_null= 1;
2585
          else
2586
            ((Item_in_subselect *) item)->value= 1;
2587
          break;
2588
        }
2589
        error= table->file->index_next_same(table->record[0],
2590
                                            tab->ref.key_buff,
2591
                                            tab->ref.key_length);
2592
        if (error && error != HA_ERR_END_OF_FILE)
2593
        {
354 by Brian Aker
Refactor of Table methods.
2594
          error= table->report_error(error);
1 by brian
clean slate
2595
          break;
2596
        }
2597
      }
2598
      else
2599
      {
2600
        if (!check_null || null_finding)
2601
          break;			/* We don't need to check nulls */
2602
        *tab->ref.null_ref_key= 1;
2603
        null_finding= 1;
2604
        /* Check if there exists a row with a null value in the index */
2605
        if ((error= (safe_index_read(tab) == 1)))
2606
          break;
2607
      }
2608
    }
2609
  }
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
2610
  return(error != 0);
1 by brian
clean slate
2611
}
2612
2613
482 by Brian Aker
Remove uint.
2614
uint32_t subselect_single_select_engine::cols()
1 by brian
clean slate
2615
{
2616
  return select_lex->item_list.elements;
2617
}
2618
2619
482 by Brian Aker
Remove uint.
2620
uint32_t subselect_union_engine::cols()
1 by brian
clean slate
2621
{
2622
  return unit->types.elements;
2623
}
2624
2625
206 by Brian Aker
Removed final uint dead types.
2626
uint8_t subselect_single_select_engine::uncacheable()
1 by brian
clean slate
2627
{
2628
  return select_lex->uncacheable;
2629
}
2630
2631
206 by Brian Aker
Removed final uint dead types.
2632
uint8_t subselect_union_engine::uncacheable()
1 by brian
clean slate
2633
{
2634
  return unit->uncacheable;
2635
}
2636
2637
2638
void subselect_single_select_engine::exclude()
2639
{
2640
  select_lex->master_unit()->exclude_level();
2641
}
2642
2643
void subselect_union_engine::exclude()
2644
{
2645
  unit->exclude_level();
2646
}
2647
2648
2649
void subselect_uniquesubquery_engine::exclude()
2650
{
2651
  //this never should be called
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
2652
  assert(0);
1 by brian
clean slate
2653
}
2654
2655
327.2.4 by Brian Aker
Refactoring table.h
2656
table_map subselect_engine::calc_const_tables(TableList *table)
1 by brian
clean slate
2657
{
2658
  table_map map= 0;
2659
  for (; table; table= table->next_leaf)
2660
  {
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
2661
    Table *tbl= table->table;
1 by brian
clean slate
2662
    if (tbl && tbl->const_table)
2663
      map|= tbl->map;
2664
  }
2665
  return map;
2666
}
2667
2668
2669
table_map subselect_single_select_engine::upper_select_const_tables()
2670
{
327.2.4 by Brian Aker
Refactoring table.h
2671
  return calc_const_tables((TableList *) select_lex->outer_select()->
1 by brian
clean slate
2672
			   leaf_tables);
2673
}
2674
2675
2676
table_map subselect_union_engine::upper_select_const_tables()
2677
{
327.2.4 by Brian Aker
Refactoring table.h
2678
  return calc_const_tables((TableList *) unit->outer_select()->leaf_tables);
1 by brian
clean slate
2679
}
2680
2681
2682
void subselect_single_select_engine::print(String *str,
2683
                                           enum_query_type query_type)
2684
{
520.1.22 by Brian Aker
Second pass of thd cleanup
2685
  select_lex->print(session, str, query_type);
1 by brian
clean slate
2686
}
2687
2688
2689
void subselect_union_engine::print(String *str, enum_query_type query_type)
2690
{
2691
  unit->print(str, query_type);
2692
}
2693
2694
2695
void subselect_uniquesubquery_engine::print(String *str,
2696
                                            enum_query_type query_type)
2697
{
2698
  char *table_name= tab->table->s->table_name.str;
2699
  str->append(STRING_WITH_LEN("<primary_index_lookup>("));
2700
  tab->ref.items[0]->print(str, query_type);
2701
  str->append(STRING_WITH_LEN(" in "));
2702
  if (tab->table->s->table_category == TABLE_CATEGORY_TEMPORARY)
2703
  {
2704
    /*
2705
      Temporary tables' names change across runs, so they can't be used for
2706
      EXPLAIN EXTENDED.
2707
    */
2708
    str->append(STRING_WITH_LEN("<temporary table>"));
2709
  }
2710
  else
2711
    str->append(table_name, tab->table->s->table_name.length);
2712
  KEY *key_info= tab->table->key_info+ tab->ref.key;
2713
  str->append(STRING_WITH_LEN(" on "));
2714
  str->append(key_info->name);
2715
  if (cond)
2716
  {
2717
    str->append(STRING_WITH_LEN(" where "));
2718
    cond->print(str, query_type);
2719
  }
2720
  str->append(')');
2721
}
2722
2723
/*
2724
TODO:
2725
The above ::print method should be changed as below. Do it after
2726
all other tests pass.
2727
2728
void subselect_uniquesubquery_engine::print(String *str)
2729
{
2730
  KEY *key_info= tab->table->key_info + tab->ref.key;
2731
  str->append(STRING_WITH_LEN("<primary_index_lookup>("));
482 by Brian Aker
Remove uint.
2732
  for (uint32_t i= 0; i < key_info->key_parts; i++)
1 by brian
clean slate
2733
    tab->ref.items[i]->print(str);
2734
  str->append(STRING_WITH_LEN(" in "));
2735
  str->append(tab->table->s->table_name.str, tab->table->s->table_name.length);
2736
  str->append(STRING_WITH_LEN(" on "));
2737
  str->append(key_info->name);
2738
  if (cond)
2739
  {
2740
    str->append(STRING_WITH_LEN(" where "));
2741
    cond->print(str);
2742
  }
2743
  str->append(')');
2744
}
2745
*/
2746
2747
void subselect_indexsubquery_engine::print(String *str,
2748
                                           enum_query_type query_type)
2749
{
2750
  str->append(STRING_WITH_LEN("<index_lookup>("));
2751
  tab->ref.items[0]->print(str, query_type);
2752
  str->append(STRING_WITH_LEN(" in "));
2753
  str->append(tab->table->s->table_name.str, tab->table->s->table_name.length);
2754
  KEY *key_info= tab->table->key_info+ tab->ref.key;
2755
  str->append(STRING_WITH_LEN(" on "));
2756
  str->append(key_info->name);
2757
  if (check_null)
2758
    str->append(STRING_WITH_LEN(" checking NULL"));
2759
  if (cond)
2760
  {
2761
    str->append(STRING_WITH_LEN(" where "));
2762
    cond->print(str, query_type);
2763
  }
2764
  if (having)
2765
  {
2766
    str->append(STRING_WITH_LEN(" having "));
2767
    having->print(str, query_type);
2768
  }
2769
  str->append(')');
2770
}
2771
2772
/**
2773
  change select_result object of engine.
2774
2775
  @param si		new subselect Item
2776
  @param res		new select_result object
2777
2778
  @retval
55 by brian
Update for using real bool types.
2779
    false OK
1 by brian
clean slate
2780
  @retval
55 by brian
Update for using real bool types.
2781
    true  error
1 by brian
clean slate
2782
*/
2783
2784
bool subselect_single_select_engine::change_result(Item_subselect *si,
2785
                                                 select_result_interceptor *res)
2786
{
2787
  item= si;
2788
  result= res;
2789
  return select_lex->join->change_result(result);
2790
}
2791
2792
2793
/**
2794
  change select_result object of engine.
2795
2796
  @param si		new subselect Item
2797
  @param res		new select_result object
2798
2799
  @retval
55 by brian
Update for using real bool types.
2800
    false OK
1 by brian
clean slate
2801
  @retval
55 by brian
Update for using real bool types.
2802
    true  error
1 by brian
clean slate
2803
*/
2804
2805
bool subselect_union_engine::change_result(Item_subselect *si,
2806
                                           select_result_interceptor *res)
2807
{
2808
  item= si;
2809
  int rc= unit->change_result(res, result);
2810
  result= res;
2811
  return rc;
2812
}
2813
2814
2815
/**
2816
  change select_result emulation, never should be called.
2817
2818
  @param si		new subselect Item
2819
  @param res		new select_result object
2820
2821
  @retval
55 by brian
Update for using real bool types.
2822
    false OK
1 by brian
clean slate
2823
  @retval
55 by brian
Update for using real bool types.
2824
    true  error
1 by brian
clean slate
2825
*/
2826
779.1.27 by Monty Taylor
Got rid of __attribute__((unused)) and the like from the .cc files.
2827
bool subselect_uniquesubquery_engine::change_result(Item_subselect *,
2828
                                                    select_result_interceptor *)
1 by brian
clean slate
2829
{
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
2830
  assert(0);
55 by brian
Update for using real bool types.
2831
  return true;
1 by brian
clean slate
2832
}
2833
2834
2835
/**
2836
  Report about presence of tables in subquery.
2837
2838
  @retval
55 by brian
Update for using real bool types.
2839
    true  there are not tables used in subquery
1 by brian
clean slate
2840
  @retval
55 by brian
Update for using real bool types.
2841
    false there are some tables in subquery
1 by brian
clean slate
2842
*/
2843
bool subselect_single_select_engine::no_tables()
2844
{
2845
  return(select_lex->table_list.elements == 0);
2846
}
2847
2848
2849
/*
2850
  Check statically whether the subquery can return NULL
2851
2852
  SINOPSYS
2853
    subselect_single_select_engine::may_be_null()
2854
2855
  RETURN
55 by brian
Update for using real bool types.
2856
    false  can guarantee that the subquery never return NULL
2857
    true   otherwise
1 by brian
clean slate
2858
*/
2859
bool subselect_single_select_engine::may_be_null()
2860
{
2861
  return ((no_tables() && !join->conds && !join->having) ? maybe_null : 1);
2862
}
2863
2864
2865
/**
2866
  Report about presence of tables in subquery.
2867
2868
  @retval
55 by brian
Update for using real bool types.
2869
    true  there are not tables used in subquery
1 by brian
clean slate
2870
  @retval
55 by brian
Update for using real bool types.
2871
    false there are some tables in subquery
1 by brian
clean slate
2872
*/
2873
bool subselect_union_engine::no_tables()
2874
{
846 by Brian Aker
Removing on typedeffed class.
2875
  for (Select_Lex *sl= unit->first_select(); sl; sl= sl->next_select())
1 by brian
clean slate
2876
  {
2877
    if (sl->table_list.elements)
55 by brian
Update for using real bool types.
2878
      return false;
1 by brian
clean slate
2879
  }
55 by brian
Update for using real bool types.
2880
  return true;
1 by brian
clean slate
2881
}
2882
2883
2884
/**
2885
  Report about presence of tables in subquery.
2886
2887
  @retval
55 by brian
Update for using real bool types.
2888
    true  there are not tables used in subquery
1 by brian
clean slate
2889
  @retval
55 by brian
Update for using real bool types.
2890
    false there are some tables in subquery
1 by brian
clean slate
2891
*/
2892
2893
bool subselect_uniquesubquery_engine::no_tables()
2894
{
2895
  /* returning value is correct, but this method should never be called */
2896
  return 0;
2897
}
2898
2899
2900
/******************************************************************************
2901
  WL#1110 - Implementation of class subselect_hash_sj_engine
2902
******************************************************************************/
2903
2904
2905
/**
2906
  Create all structures needed for IN execution that can live between PS
2907
  reexecution.
2908
2909
  @detail
2910
  - Create a temporary table to store the result of the IN subquery. The
2911
    temporary table has one hash index on all its columns.
2912
  - Create a new result sink that sends the result stream of the subquery to
2913
    the temporary table,
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
2914
  - Create and initialize a new JoinTable, and TABLE_REF objects to perform
1 by brian
clean slate
2915
    lookups into the indexed temporary table.
2916
2917
  @notice:
2918
    Currently Item_subselect::init() already chooses and creates at parse
2919
    time an engine with a corresponding JOIN to execute the subquery.
2920
55 by brian
Update for using real bool types.
2921
  @retval true  if error
2922
  @retval false otherwise
1 by brian
clean slate
2923
*/
2924
2925
bool subselect_hash_sj_engine::init_permanent(List<Item> *tmp_columns)
2926
{
2927
  /* The result sink where we will materialize the subquery result. */
2928
  select_union  *tmp_result_sink;
2929
  /* The table into which the subquery is materialized. */
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
2930
  Table         *tmp_table;
1 by brian
clean slate
2931
  KEY           *tmp_key; /* The only index on the temporary table. */
482 by Brian Aker
Remove uint.
2932
  uint32_t          tmp_key_parts; /* Number of keyparts in tmp_key. */
1 by brian
clean slate
2933
  Item_in_subselect *item_in= (Item_in_subselect *) item;
2934
2935
  /* 1. Create/initialize materialization related objects. */
2936
2937
  /*
2938
    Create and initialize a select result interceptor that stores the
2939
    result stream in a temporary table. The temporary table itself is
2940
    managed (created/filled/etc) internally by the interceptor.
2941
  */
2942
  if (!(tmp_result_sink= new select_union))
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
2943
    return(true);
1 by brian
clean slate
2944
  if (tmp_result_sink->create_result_table(
520.1.22 by Brian Aker
Second pass of thd cleanup
2945
                         session, tmp_columns, true,
2946
                         session->options | TMP_TABLE_ALL_COLUMNS,
55 by brian
Update for using real bool types.
2947
                         "materialized subselect", true))
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
2948
    return(true);
1 by brian
clean slate
2949
2950
  tmp_table= tmp_result_sink->table;
2951
  tmp_key= tmp_table->key_info;
2952
  tmp_key_parts= tmp_key->key_parts;
2953
2954
  /*
2955
     If the subquery has blobs, or the total key lenght is bigger than some
2956
     length, then the created index cannot be used for lookups and we
2957
     can't use hash semi join. If this is the case, delete the temporary
2958
     table since it will not be used, and tell the caller we failed to
2959
     initialize the engine.
2960
  */
2961
  if (tmp_table->s->keys == 0)
2962
  {
960.2.25 by Monty Taylor
First step of hton rename.
2963
    assert(tmp_table->s->db_type() == myisam_engine);
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
2964
    assert(
1 by brian
clean slate
2965
      tmp_table->s->uniques ||
2966
      tmp_table->key_info->key_length >= tmp_table->file->max_key_length() ||
2967
      tmp_table->key_info->key_parts > tmp_table->file->max_key_parts());
520.1.22 by Brian Aker
Second pass of thd cleanup
2968
    tmp_table->free_tmp_table(session);
1 by brian
clean slate
2969
    delete result;
2970
    result= NULL;
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
2971
    return(true);
1 by brian
clean slate
2972
  }
2973
  result= tmp_result_sink;
2974
2975
  /*
2976
    Make sure there is only one index on the temp table, and it doesn't have
2977
    the extra key part created when s->uniques > 0.
2978
  */
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
2979
  assert(tmp_table->s->keys == 1 && tmp_columns->elements == tmp_key_parts);
1 by brian
clean slate
2980
2981
2982
  /* 2. Create/initialize execution related objects. */
2983
2984
  /*
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
2985
    Create and initialize the JoinTable that represents an index lookup
1 by brian
clean slate
2986
    plan operator into the materialized subquery result. Notice that:
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
2987
    - this JoinTable has no corresponding JOIN (and doesn't need one), and
1 by brian
clean slate
2988
    - here we initialize only those members that are used by
2989
      subselect_uniquesubquery_engine, so these objects are incomplete.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
2990
  */
1089.1.1 by Brian Aker
Remove of JOIN_TAB to JoinTable
2991
  if (!(tab= (JoinTable*) session->alloc(sizeof(JoinTable))))
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
2992
    return(true);
1 by brian
clean slate
2993
  tab->table= tmp_table;
2994
  tab->ref.key= 0; /* The only temp table index. */
2995
  tab->ref.key_length= tmp_key->key_length;
2996
  if (!(tab->ref.key_buff=
520.1.22 by Brian Aker
Second pass of thd cleanup
2997
        (unsigned char*) session->calloc(ALIGN_SIZE(tmp_key->key_length) * 2)) ||
1 by brian
clean slate
2998
      !(tab->ref.key_copy=
1039.2.3 by Jay Pipes
Phase 3 of refactoring JOIN
2999
        (StoredKey**) session->alloc((sizeof(StoredKey*) *
1 by brian
clean slate
3000
                                  (tmp_key_parts + 1)))) ||
3001
      !(tab->ref.items=
520.1.22 by Brian Aker
Second pass of thd cleanup
3002
        (Item**) session->alloc(sizeof(Item*) * tmp_key_parts)))
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
3003
    return(true);
1 by brian
clean slate
3004
3005
  KEY_PART_INFO *cur_key_part= tmp_key->key_part;
1039.2.3 by Jay Pipes
Phase 3 of refactoring JOIN
3006
  StoredKey **ref_key= tab->ref.key_copy;
481 by Brian Aker
Remove all of uchar.
3007
  unsigned char *cur_ref_buff= tab->ref.key_buff;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
3008
482 by Brian Aker
Remove uint.
3009
  for (uint32_t i= 0; i < tmp_key_parts; i++, cur_key_part++, ref_key++)
1 by brian
clean slate
3010
  {
3011
    tab->ref.items[i]= item_in->left_expr->element_index(i);
3012
    int null_count= test(cur_key_part->field->real_maybe_null());
520.1.22 by Brian Aker
Second pass of thd cleanup
3013
    *ref_key= new store_key_item(session, cur_key_part->field,
1 by brian
clean slate
3014
                                 /* TODO:
3015
                                    the NULL byte is taken into account in
3016
                                    cur_key_part->store_length, so instead of
3017
                                    cur_ref_buff + test(maybe_null), we could
3018
                                    use that information instead.
3019
                                 */
3020
                                 cur_ref_buff + null_count,
3021
                                 null_count ? tab->ref.key_buff : 0,
3022
                                 cur_key_part->length, tab->ref.items[i]);
3023
    cur_ref_buff+= cur_key_part->store_length;
3024
  }
3025
  *ref_key= NULL; /* End marker. */
3026
  tab->ref.key_err= 1;
3027
  tab->ref.key_parts= tmp_key_parts;
3028
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
3029
  return(false);
1 by brian
clean slate
3030
}
3031
3032
3033
/**
3034
  Initialize members of the engine that need to be re-initilized at each
3035
  execution.
3036
55 by brian
Update for using real bool types.
3037
  @retval true  if a memory allocation error occurred
3038
  @retval false if success
1 by brian
clean slate
3039
*/
3040
3041
bool subselect_hash_sj_engine::init_runtime()
3042
{
3043
  /*
3044
    Create and optimize the JOIN that will be used to materialize
3045
    the subquery if not yet created.
3046
  */
3047
  materialize_engine->prepare();
3048
  /* Let our engine reuse this query plan for materialization. */
3049
  materialize_join= materialize_engine->join;
3050
  materialize_join->change_result(result);
55 by brian
Update for using real bool types.
3051
  return false;
1 by brian
clean slate
3052
}
3053
3054
3055
subselect_hash_sj_engine::~subselect_hash_sj_engine()
3056
{
3057
  delete result;
3058
  if (tab)
520.1.22 by Brian Aker
Second pass of thd cleanup
3059
    tab->table->free_tmp_table(session);
1 by brian
clean slate
3060
}
3061
3062
3063
/**
3064
  Cleanup performed after each PS execution.
3065
3066
  @detail
3067
  Called in the end of JOIN::prepare for PS from Item_subselect::cleanup.
3068
*/
3069
3070
void subselect_hash_sj_engine::cleanup()
3071
{
55 by brian
Update for using real bool types.
3072
  is_materialized= false;
1 by brian
clean slate
3073
  result->cleanup(); /* Resets the temp table as well. */
3074
  materialize_engine->cleanup();
3075
  subselect_uniquesubquery_engine::cleanup();
3076
}
3077
3078
3079
/**
3080
  Execute a subquery IN predicate via materialization.
3081
3082
  @detail
3083
  If needed materialize the subquery into a temporary table, then
3084
  copmpute the predicate via a lookup into this table.
3085
55 by brian
Update for using real bool types.
3086
  @retval true  if error
3087
  @retval false otherwise
1 by brian
clean slate
3088
*/
3089
3090
int subselect_hash_sj_engine::exec()
3091
{
3092
  Item_in_subselect *item_in= (Item_in_subselect *) item;
3093
3094
  /*
3095
    Optimize and materialize the subquery during the first execution of
3096
    the subquery predicate.
3097
  */
3098
  if (!is_materialized)
3099
  {
3100
    int res= 0;
846 by Brian Aker
Removing on typedeffed class.
3101
    Select_Lex *save_select= session->lex->current_select;
520.1.22 by Brian Aker
Second pass of thd cleanup
3102
    session->lex->current_select= materialize_engine->select_lex;
1 by brian
clean slate
3103
    if ((res= materialize_join->optimize()))
3104
      goto err;
3105
    materialize_join->exec();
520.1.22 by Brian Aker
Second pass of thd cleanup
3106
    if ((res= test(materialize_join->error || session->is_fatal_error)))
1 by brian
clean slate
3107
      goto err;
3108
3109
    /*
3110
      TODO:
3111
      - Unlock all subquery tables as we don't need them. To implement this
3112
        we need to add new functionality to JOIN::join_free that can unlock
3113
        all tables in a subquery (and all its subqueries).
3114
      - The temp table used for grouping in the subquery can be freed
3115
        immediately after materialization (yet it's done together with
3116
        unlocking).
3117
     */
55 by brian
Update for using real bool types.
3118
    is_materialized= true;
1 by brian
clean slate
3119
    /*
3120
      If the subquery returned no rows, the temporary table is empty, so we know
55 by brian
Update for using real bool types.
3121
      directly that the result of IN is false. We first update the table
1 by brian
clean slate
3122
      statistics, then we test if the temporary table for the query result is
3123
      empty.
3124
    */
3125
    tab->table->file->info(HA_STATUS_VARIABLE);
3126
    if (!tab->table->file->stats.records)
3127
    {
55 by brian
Update for using real bool types.
3128
      empty_result_set= true;
3129
      item_in->value= false;
3130
      /* TODO: check we need this: item_in->null_value= false; */
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
3131
      return(false);
1 by brian
clean slate
3132
    }
3133
    /* Set tmp_param only if its usable, i.e. tmp_param->copy_field != NULL. */
3134
    tmp_param= &(item_in->unit->outer_select()->join->tmp_table_param);
3135
    if (tmp_param && !tmp_param->copy_field)
3136
      tmp_param= NULL;
3137
3138
err:
520.1.22 by Brian Aker
Second pass of thd cleanup
3139
    session->lex->current_select= save_select;
1 by brian
clean slate
3140
    if (res)
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
3141
      return(res);
1 by brian
clean slate
3142
  }
3143
3144
  /*
3145
    Lookup the left IN operand in the hash index of the materialized subquery.
3146
  */
51.1.24 by Jay Pipes
Removed DBUG symbols and fixed TRUE/FALSE
3147
  return(subselect_uniquesubquery_engine::exec());
1 by brian
clean slate
3148
}
3149
3150
3151
/**
3152
  Print the state of this engine into a string for debugging and views.
3153
*/
3154
3155
void subselect_hash_sj_engine::print(String *str, enum_query_type query_type)
3156
{
3157
  str->append(STRING_WITH_LEN(" <materialize> ("));
3158
  materialize_engine->print(str, query_type);
3159
  str->append(STRING_WITH_LEN(" ), "));
3160
  if (tab)
3161
    subselect_uniquesubquery_engine::print(str, query_type);
3162
  else
3163
    str->append(STRING_WITH_LEN(
3164
           "<the access method for lookups is not yet created>"
3165
         ));
3166
}