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