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