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