sp_head.cc 83.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* Copyright (C) 2002 MySQL AB

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

17
#include "mysql_priv.h"
18
#ifdef USE_PRAGMA_IMPLEMENTATION
19 20 21
#pragma implementation
#endif
#include "sp_head.h"
22
#include "sp.h"
23 24
#include "sp_pcontext.h"
#include "sp_rcontext.h"
25
#include "sp_cache.h"
26

27 28 29 30 31 32 33 34 35 36 37 38
Item_result
sp_map_result_type(enum enum_field_types type)
{
  switch (type)
  {
  case MYSQL_TYPE_TINY:
  case MYSQL_TYPE_SHORT:
  case MYSQL_TYPE_LONG:
  case MYSQL_TYPE_LONGLONG:
  case MYSQL_TYPE_INT24:
    return INT_RESULT;
  case MYSQL_TYPE_DECIMAL:
unknown's avatar
unknown committed
39 40
  case MYSQL_TYPE_NEWDECIMAL:
    return DECIMAL_RESULT;
41 42 43 44 45 46 47 48
  case MYSQL_TYPE_FLOAT:
  case MYSQL_TYPE_DOUBLE:
    return REAL_RESULT;
  default:
    return STRING_RESULT;
  }
}

49
/*
50 51 52 53 54 55 56 57 58 59 60 61 62
  SYNOPSIS
    sp_get_flags_for_command()

  DESCRIPTION
    Returns a combination of:
    * sp_head::MULTI_RESULTS: added if the 'cmd' is a command that might
      result in multiple result sets being sent back.
    * sp_head::CONTAINS_DYNAMIC_SQL: added if 'cmd' is one of PREPARE,
      EXECUTE, DEALLOCATE.
*/

uint
sp_get_flags_for_command(LEX *lex)
63
{
64 65 66 67 68 69 70 71 72 73
  uint flags;

  switch (lex->sql_command) {
  case SQLCOM_SELECT:
    if (lex->result)
    {
      flags= 0;                      /* This is a SELECT with INTO clause */
      break;
    }
    /* fallthrough */
74
  case SQLCOM_ANALYZE:
75 76 77
  case SQLCOM_OPTIMIZE:
  case SQLCOM_PRELOAD_KEYS:
  case SQLCOM_ASSIGN_TO_KEYCACHE:
78
  case SQLCOM_CHECKSUM:
79
  case SQLCOM_CHECK:
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
  case SQLCOM_HA_READ:
  case SQLCOM_SHOW_BINLOGS:
  case SQLCOM_SHOW_BINLOG_EVENTS:
  case SQLCOM_SHOW_CHARSETS:
  case SQLCOM_SHOW_COLLATIONS:
  case SQLCOM_SHOW_COLUMN_TYPES:
  case SQLCOM_SHOW_CREATE:
  case SQLCOM_SHOW_CREATE_DB:
  case SQLCOM_SHOW_CREATE_FUNC:
  case SQLCOM_SHOW_CREATE_PROC:
  case SQLCOM_SHOW_DATABASES:
  case SQLCOM_SHOW_ERRORS:
  case SQLCOM_SHOW_FIELDS:
  case SQLCOM_SHOW_GRANTS:
  case SQLCOM_SHOW_INNODB_STATUS:
  case SQLCOM_SHOW_KEYS:
  case SQLCOM_SHOW_LOGS:
  case SQLCOM_SHOW_MASTER_STAT:
98
  case SQLCOM_SHOW_MUTEX_STATUS:
99 100 101 102 103 104 105 106 107 108 109 110 111
  case SQLCOM_SHOW_NEW_MASTER:
  case SQLCOM_SHOW_OPEN_TABLES:
  case SQLCOM_SHOW_PRIVILEGES:
  case SQLCOM_SHOW_PROCESSLIST:
  case SQLCOM_SHOW_SLAVE_HOSTS:
  case SQLCOM_SHOW_SLAVE_STAT:
  case SQLCOM_SHOW_STATUS:
  case SQLCOM_SHOW_STATUS_FUNC:
  case SQLCOM_SHOW_STATUS_PROC:
  case SQLCOM_SHOW_STORAGE_ENGINES:
  case SQLCOM_SHOW_TABLES:
  case SQLCOM_SHOW_VARIABLES:
  case SQLCOM_SHOW_WARNS:
unknown's avatar
unknown committed
112 113
  case SQLCOM_SHOW_PROC_CODE:
  case SQLCOM_SHOW_FUNC_CODE:
114 115 116
  case SQLCOM_REPAIR:
  case SQLCOM_BACKUP_TABLE:
  case SQLCOM_RESTORE_TABLE:
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
    flags= sp_head::MULTI_RESULTS;
    break;
  /*
    EXECUTE statement may return a result set, but doesn't have to.
    We can't, however, know it in advance, and therefore must add
    this statement here. This is ok, as is equivalent to a result-set
    statement within an IF condition.
  */
  case SQLCOM_EXECUTE:
    flags= sp_head::MULTI_RESULTS | sp_head::CONTAINS_DYNAMIC_SQL;
    break;
  case SQLCOM_PREPARE:
  case SQLCOM_DEALLOCATE_PREPARE:
    flags= sp_head::CONTAINS_DYNAMIC_SQL;
    break;
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
  case SQLCOM_CREATE_TABLE:
    if (lex->create_info.options & HA_LEX_CREATE_TMP_TABLE)
      flags= 0;
    else
      flags= sp_head::HAS_COMMIT_OR_ROLLBACK;
    break;
  case SQLCOM_DROP_TABLE:
    if (lex->drop_temporary)
      flags= 0;
    else
      flags= sp_head::HAS_COMMIT_OR_ROLLBACK;
    break;
  case SQLCOM_CREATE_INDEX:
  case SQLCOM_CREATE_DB:
  case SQLCOM_CREATE_VIEW:
  case SQLCOM_CREATE_TRIGGER:
  case SQLCOM_CREATE_USER:
  case SQLCOM_ALTER_TABLE:
  case SQLCOM_BEGIN:
  case SQLCOM_RENAME_TABLE:
  case SQLCOM_RENAME_USER:
  case SQLCOM_DROP_INDEX:
  case SQLCOM_DROP_DB:
  case SQLCOM_DROP_USER:
  case SQLCOM_DROP_VIEW:
  case SQLCOM_DROP_TRIGGER:
  case SQLCOM_TRUNCATE:
  case SQLCOM_COMMIT:
  case SQLCOM_ROLLBACK:
  case SQLCOM_LOAD_MASTER_DATA:
  case SQLCOM_LOCK_TABLES:
  case SQLCOM_CREATE_PROCEDURE:
  case SQLCOM_CREATE_SPFUNCTION:
  case SQLCOM_ALTER_PROCEDURE:
  case SQLCOM_ALTER_FUNCTION:
  case SQLCOM_DROP_PROCEDURE:
  case SQLCOM_DROP_FUNCTION:
    flags= sp_head::HAS_COMMIT_OR_ROLLBACK;
    break;
171
  default:
172 173
    flags= 0;
    break;
174
  }
175
  return flags;
176 177
}

178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198

/*
  Prepare Item for execution (call of fix_fields)

  SYNOPSIS
    sp_prepare_func_item()
    thd       thread handler
    it_addr   pointer on item refernce

  RETURN
    NULL  error
    prepared item
*/

static Item *
sp_prepare_func_item(THD* thd, Item **it_addr)
{
  Item *it= *it_addr;
  DBUG_ENTER("sp_prepare_func_item");
  it_addr= it->this_item_addr(thd, it_addr);

199
  if (!it->fixed && (*it_addr)->fix_fields(thd, it_addr))
200 201 202 203 204 205 206 207
  {
    DBUG_PRINT("info", ("fix_fields() failed"));
    DBUG_RETURN(NULL);
  }
  DBUG_RETURN(*it_addr);
}


208
/* Macro to switch arena in sp_eval_func_item */
209 210 211 212
#define CREATE_ON_CALLERS_ARENA(new_command, condition, backup_arena)   \
  do                                                                    \
  {                                                                     \
    if (condition)                                                      \
unknown's avatar
unknown committed
213 214
      thd->set_n_backup_active_arena(thd->spcont->callers_arena,        \
                                     backup_arena);                     \
215 216
    new_command;                                                        \
    if (condition)                                                      \
unknown's avatar
unknown committed
217 218
      thd->restore_active_arena(thd->spcont->callers_arena,             \
                                backup_arena);                          \
219
  } while(0)
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239

/*
  Evaluate an item and store it in the returned item

  SYNOPSIS
    sp_eval_func_item()
      name                  - current thread object
      it_addr               - pointer to the item to evaluate
      type                  - type of the item we evaluating
      reuse                 - used if we would like to reuse existing item
                              instead of allocation of the new one
      use_callers_arena     - TRUE if we want to use caller's arena
                              rather then current one.
  DESCRIPTION
   We use this function to evaluate result for stored functions
   and stored procedure parameters. It is also used to evaluate and
   (re) allocate variables.

  RETURN VALUES
    Evaluated item is returned
240
*/
241

242
Item *
243
sp_eval_func_item(THD *thd, Item **it_addr, enum enum_field_types type,
244
		  Item *reuse, bool use_callers_arena)
245
{
246
  DBUG_ENTER("sp_eval_func_item");
247
  Item *it= sp_prepare_func_item(thd, it_addr);
248
  uint rsize;
unknown's avatar
unknown committed
249
  Query_arena backup_arena;
250
  Item *old_item_next, *old_free_list, **p_free_list;
251
  DBUG_PRINT("info", ("type: %d", type));
252

253
  if (!it)
254
    DBUG_RETURN(NULL);
255 256 257 258 259 260 261

  if (reuse)
  {
    old_item_next= reuse->next;
    p_free_list= use_callers_arena ? &thd->spcont->callers_arena->free_list :
                                     &thd->free_list;
    old_free_list= *p_free_list;
262
  }
263

264 265
  switch (sp_map_result_type(type)) {
  case INT_RESULT:
266 267
  {
    longlong i= it->val_int();
268

269 270 271 272
    if (it->null_value)
    {
      DBUG_PRINT("info", ("INT_RESULT: null"));
      goto return_null_item;
273
    }
274 275
    DBUG_PRINT("info", ("INT_RESULT: %d", i));
    CREATE_ON_CALLERS_ARENA(it= new(reuse, &rsize) Item_int(i),
unknown's avatar
unknown committed
276
                            use_callers_arena, &backup_arena);
277 278
    break;
  }
279
  case REAL_RESULT:
280 281 282 283
  {
    double d= it->val_real();
    uint8 decimals;
    uint32 max_length;
284

285 286 287 288
    if (it->null_value)
    {
      DBUG_PRINT("info", ("REAL_RESULT: null"));
      goto return_null_item;
289
    }
290 291 292 293 294 295 296 297 298

    /*
      There's some difference between Item::new_item() and the
      constructor; the former crashes, the latter works... weird.
    */
    decimals= it->decimals;
    max_length= it->max_length;
    DBUG_PRINT("info", ("REAL_RESULT: %g", d));
    CREATE_ON_CALLERS_ARENA(it= new(reuse, &rsize) Item_float(d),
unknown's avatar
unknown committed
299
                            use_callers_arena, &backup_arena);
300 301 302 303
    it->decimals= decimals;
    it->max_length= max_length;
    break;
  }
304
  case DECIMAL_RESULT:
305 306 307 308 309
  {
    my_decimal value, *val= it->val_decimal(&value);
    if (it->null_value)
      goto return_null_item;
    CREATE_ON_CALLERS_ARENA(it= new(reuse, &rsize) Item_decimal(val),
unknown's avatar
unknown committed
310
                            use_callers_arena, &backup_arena);
unknown's avatar
unknown committed
311
#ifndef DBUG_OFF
312
    {
313
      char dbug_buff[DECIMAL_MAX_STR_LENGTH+1];
314 315
      DBUG_PRINT("info", ("DECIMAL_RESULT: %s",
                          dbug_decimal_as_string(dbug_buff, val)));
316
    }
317
#endif
318 319
    break;
  }
320
  case STRING_RESULT:
321 322 323 324
  {
    char buffer[MAX_FIELD_WIDTH];
    String tmp(buffer, sizeof(buffer), it->collation.collation);
    String *s= it->val_str(&tmp);
325

326 327 328 329
    if (type == MYSQL_TYPE_NULL || it->null_value)
    {
      DBUG_PRINT("info", ("STRING_RESULT: null"));
      goto return_null_item;
330
    }
331
    DBUG_PRINT("info",("STRING_RESULT: %.*s",
332
                       s->length(), s->c_ptr_quick()));
333 334 335 336 337 338 339 340 341 342 343
    /*
      Reuse mechanism in sp_eval_func_item() is only employed for assignments
      to local variables and OUT/INOUT SP parameters repsesented by
      Item_splocal. Usually we have some expression, which needs
      to be calculated and stored into the local variable. However in the
      case if "it" equals to "reuse", there is no "calculation" step. So,
      no reason to employ reuse mechanism to save variable into itself.
    */
    if (it == reuse)
      DBUG_RETURN(it);

344 345
    /*
      For some functions, 's' is now pointing to an argument of the
unknown's avatar
unknown committed
346
      function, which might be a local variable that is to be reused.
347 348 349 350 351 352 353 354
      In this case, new(reuse, &rsize) below will call the destructor
      and 's' ends up pointing to freed memory.
      A somewhat ugly fix is to simply copy the string to our local one
      (which is unused by most functions anyway), but only if 's' is
      pointing somewhere else than to 'tmp' or 'it->str_value'.
     */
    if (reuse && s != &tmp && s != &it->str_value)
    {
unknown's avatar
unknown committed
355 356
      if (tmp.copy((const String)(*s)))
        DBUG_RETURN(NULL);
357 358 359
      s= &tmp;
    }

360 361
    CREATE_ON_CALLERS_ARENA(it= new(reuse, &rsize)
                            Item_string(it->collation.collation),
unknown's avatar
unknown committed
362
                            use_callers_arena, &backup_arena);
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
    /*
      We have to use special constructor and allocate string
      on system heap here. This is because usual Item_string
      constructor would allocate memory in the callers arena.
      This would lead to the memory leak in SP loops.
      See Bug #11333 "Stored Procedure: Memory blow up on
      repeated SELECT ... INTO query" for sample of such SP.
      TODO: Usage of the system heap gives significant overhead,
      however usual "reuse" mechanism does not work here, as
      Item_string has no max size. That is, if we have a loop, which
      has string variable with constantly increasing size, we would have
      to allocate new pieces of memory again and again on each iteration.
      In future we should probably reserve some area of memory for
      not-very-large strings and reuse it. But for large strings
      we would have to use system heap anyway.
    */
    ((Item_string*) it)->set_str_with_copy(s->ptr(), s->length());
380 381
    break;
  }
382 383 384
  case ROW_RESULT:
  default:
    DBUG_ASSERT(0);
385
  }
386
  goto end;
387 388 389

return_null_item:
  CREATE_ON_CALLERS_ARENA(it= new(reuse, &rsize) Item_null(),
unknown's avatar
unknown committed
390
                          use_callers_arena, &backup_arena);
391
end:
392 393
  it->rsize= rsize;

394 395 396 397 398 399 400 401 402
  if (reuse && it == reuse)
  {
    /*
      The Item constructor registered itself in the arena free list,
      while the item slot is reused, so we have to restore the list.
    */
    it->next= old_item_next;
    *p_free_list= old_free_list;
  }
403
  DBUG_RETURN(it);
404 405
}

406 407 408 409 410 411 412 413 414 415

/*
 *
 *  sp_name
 *
 */

void
sp_name::init_qname(THD *thd)
{
416 417 418 419 420
  m_sroutines_key.length=  m_db.length + m_name.length + 2;
  if (!(m_sroutines_key.str= thd->alloc(m_sroutines_key.length + 1)))
    return;
  m_qname.length= m_sroutines_key.length - 1;
  m_qname.str= m_sroutines_key.str + 1;
421
  sprintf(m_qname.str, "%.*s.%.*s",
422 423 424 425
	  m_db.length, (m_db.length ? m_db.str : ""),
	  m_name.length, m_name.str);
}

426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
sp_name *
sp_name_current_db_new(THD *thd, LEX_STRING name)
{
  sp_name *qname;

  if (! thd->db)
    qname= new sp_name(name);
  else
  {
    LEX_STRING db;

    db.length= strlen(thd->db);
    db.str= thd->strmake(thd->db, db.length);
    qname= new sp_name(db, name);
  }
  qname->init_qname(thd);
  return qname;
}


446 447 448 449 450 451 452 453 454
/* ------------------------------------------------------------------ */


/*
 *
 *  sp_head
 *
 */

455 456 457 458 459 460 461 462
void *
sp_head::operator new(size_t size)
{
  DBUG_ENTER("sp_head::operator new");
  MEM_ROOT own_root;
  sp_head *sp;

  init_alloc_root(&own_root, MEM_ROOT_BLOCK_SIZE, MEM_ROOT_PREALLOC);
unknown's avatar
unknown committed
463 464
  sp= (sp_head *) alloc_root(&own_root, size);
  sp->main_mem_root= own_root;
465
  DBUG_PRINT("info", ("mem_root 0x%lx", (ulong) &sp->mem_root));
466 467 468 469 470 471 472 473
  DBUG_RETURN(sp);
}

void 
sp_head::operator delete(void *ptr, size_t size)
{
  DBUG_ENTER("sp_head::operator delete");
  MEM_ROOT own_root;
unknown's avatar
unknown committed
474
  sp_head *sp= (sp_head *) ptr;
475

unknown's avatar
unknown committed
476 477
  /* Make a copy of main_mem_root as free_root will free the sp */
  own_root= sp->main_mem_root;
478 479
  DBUG_PRINT("info", ("mem_root 0x%lx moved to 0x%lx",
                      (ulong) &sp->mem_root, (ulong) &own_root));
480 481 482 483 484
  free_root(&own_root, MYF(0));

  DBUG_VOID_RETURN;
}

485

486
sp_head::sp_head()
487
  :Query_arena(&main_mem_root, INITIALIZED_FOR_SP),
488 489
   m_flags(0), m_returns_cs(NULL), m_recursion_level(0), m_next_cached_sp(0),
   m_first_instance(this), m_first_free_instance(this), m_last_cached_sp(this)
490
{
491 492
  extern byte *
    sp_table_key(const byte *ptr, uint *plen, my_bool first);
493
  DBUG_ENTER("sp_head::sp_head");
494 495 496

  m_backpatch.empty();
  m_lex.empty();
497
  hash_init(&m_sptabs, system_charset_info, 0, 0, 0, sp_table_key, 0, 0);
498
  hash_init(&m_sroutines, system_charset_info, 0, 0, 0, sp_sroutine_key, 0, 0);
499 500 501
  DBUG_VOID_RETURN;
}

502

503
void
504
sp_head::init(LEX *lex)
505 506
{
  DBUG_ENTER("sp_head::init");
507

508
  lex->spcont= m_pcont= new sp_pcontext(NULL);
509 510 511 512 513
  /*
    Altough trg_table_fields list is used only in triggers we init for all
    types of stored procedures to simplify reset_lex()/restore_lex() code.
  */
  lex->trg_table_fields.empty();
514
  my_init_dynamic_array(&m_instr, sizeof(sp_instr *), 16, 8);
unknown's avatar
unknown committed
515 516
  m_param_begin= m_param_end= m_body_begin= 0;
  m_qname.str= m_db.str= m_name.str= m_params.str= 
517 518
    m_body.str= m_defstr.str= 0;
  m_qname.length= m_db.length= m_name.length= m_params.length=
unknown's avatar
unknown committed
519
    m_body.length= m_defstr.length= 0;
520
  m_returns_cs= NULL;
521 522 523 524
  DBUG_VOID_RETURN;
}

void
525
sp_head::init_strings(THD *thd, LEX *lex, sp_name *name)
526 527
{
  DBUG_ENTER("sp_head::init_strings");
528
  uchar *endp;                  /* Used to trim the end */
unknown's avatar
unknown committed
529
  /* During parsing, we must use thd->mem_root */
unknown's avatar
unknown committed
530
  MEM_ROOT *root= thd->mem_root;
531

532
  /* We have to copy strings to get them into the right memroot */
533 534
  if (name)
  {
535
    m_db.length= name->m_db.length;
536
    if (name->m_db.length == 0)
537
      m_db.str= NULL;
538 539 540 541 542 543 544 545 546 547
    else
      m_db.str= strmake_root(root, name->m_db.str, name->m_db.length);
    m_name.length= name->m_name.length;
    m_name.str= strmake_root(root, name->m_name.str, name->m_name.length);

    if (name->m_qname.length == 0)
      name->init_qname(thd);
    m_qname.length= name->m_qname.length;
    m_qname.str= strmake_root(root, name->m_qname.str, m_qname.length);
  }
548
  else if (thd->db)
549
  {
550
    m_db.length= thd->db_length;
551
    m_db.str= strmake_root(root, thd->db, m_db.length);
552
  }
553

554
  if (m_param_begin && m_param_end)
555
  {
556 557 558
    m_params.length= m_param_end - m_param_begin;
    m_params.str= strmake_root(root,
                               (char *)m_param_begin, m_params.length);
559
  }
560

561 562 563 564 565 566 567 568 569 570 571 572
  /* If ptr has overrun end_of_query then end_of_query is the end */
  endp= (lex->ptr > lex->end_of_query ? lex->end_of_query : lex->ptr);
  /*
    Trim "garbage" at the end. This is sometimes needed with the
    "/ * ! VERSION... * /" wrapper in dump files.
  */
  while (m_body_begin < endp &&
         (endp[-1] <= ' ' || endp[-1] == '*' ||
          endp[-1] == '/' || endp[-1] == ';'))
    endp-= 1;

  m_body.length= endp - m_body_begin;
unknown's avatar
unknown committed
573
  m_body.str= strmake_root(root, (char *)m_body_begin, m_body.length);
574
  m_defstr.length= endp - lex->buf;
unknown's avatar
unknown committed
575
  m_defstr.str= strmake_root(root, (char *)lex->buf, m_defstr.length);
576
  DBUG_VOID_RETURN;
577 578
}

unknown's avatar
unknown committed
579 580 581 582
TYPELIB *
sp_head::create_typelib(List<String> *src)
{
  TYPELIB *result= NULL;
583
  CHARSET_INFO *cs= m_returns_cs;
unknown's avatar
unknown committed
584 585 586 587 588 589 590
  DBUG_ENTER("sp_head::clone_typelib");
  if (src->elements)
  {
    result= (TYPELIB*) alloc_root(mem_root, sizeof(TYPELIB));
    result->count= src->elements;
    result->name= "";
    if (!(result->type_names=(const char **)
591
          alloc_root(mem_root,(sizeof(char *)+sizeof(int))*(result->count+1))))
unknown's avatar
unknown committed
592
      return 0;
593
    result->type_lengths= (unsigned int *)(result->type_names + result->count+1);
unknown's avatar
unknown committed
594
    List_iterator<String> it(*src);
unknown's avatar
unknown committed
595 596
    String conv;
    for (uint i=0; i < result->count; i++)
597
    {
unknown's avatar
unknown committed
598 599 600 601
      uint32 dummy;
      uint length;
      String *tmp= it++;

602 603 604 605 606
      if (String::needs_conversion(tmp->length(), tmp->charset(),
      				   cs, &dummy))
      {
        uint cnv_errs;
        conv.copy(tmp->ptr(), tmp->length(), tmp->charset(), cs, &cnv_errs);
unknown's avatar
unknown committed
607 608 609 610

        length= conv.length();
        result->type_names[i]= (char*) strmake_root(mem_root, conv.ptr(),
                                                    length);
611
      }
unknown's avatar
unknown committed
612 613 614 615
      else
      {
        length= tmp->length();
        result->type_names[i]= strmake_root(mem_root, tmp->ptr(), length);
616
      }
617 618

      // Strip trailing spaces.
unknown's avatar
unknown committed
619 620 621
      length= cs->cset->lengthsp(cs, result->type_names[i], length);
      result->type_lengths[i]= length;
      ((uchar *)result->type_names[i])[length]= '\0';
622
    }
unknown's avatar
unknown committed
623
    result->type_names[result->count]= 0;
624
    result->type_lengths[result->count]= 0;
unknown's avatar
unknown committed
625 626 627 628
  }
  return result;
}

629 630 631
int
sp_head::create(THD *thd)
{
632
  DBUG_ENTER("sp_head::create");
633 634
  int ret;

635 636
  DBUG_PRINT("info", ("type: %d name: %s params: %s body: %s",
		      m_type, m_name.str, m_params.str, m_body.str));
637

638
#ifndef DBUG_OFF
639
  optimize();
640
  {
641 642 643 644 645 646
    String s;
    sp_instr *i;
    uint ip= 0;
    while ((i = get_instr(ip)))
    {
      char buf[8];
647

648 649 650 651 652 653 654 655
      sprintf(buf, "%4u: ", ip);
      s.append(buf);
      i->print(&s);
      s.append('\n');
      ip+= 1;
    }
    s.append('\0');
    DBUG_PRINT("info", ("Code %s\n%s", m_qname.str, s.ptr()));
656 657 658
  }
#endif

659
  if (m_type == TYPE_ENUM_FUNCTION)
660
    ret= sp_create_function(thd, this);
661
  else
662
    ret= sp_create_procedure(thd, this);
663

664
  DBUG_RETURN(ret);
665 666
}

667 668 669
sp_head::~sp_head()
{
  destroy();
670
  delete m_next_cached_sp;
671 672 673 674
  if (m_thd)
    restore_thd_mem_root(m_thd);
}

675 676 677
void
sp_head::destroy()
{
678 679
  sp_instr *i;
  LEX *lex;
unknown's avatar
unknown committed
680 681
  DBUG_ENTER("sp_head::destroy");
  DBUG_PRINT("info", ("name: %s", m_name.str));
682 683 684

  for (uint ip = 0 ; (i = get_instr(ip)) ; ip++)
    delete i;
685 686
  delete_dynamic(&m_instr);
  m_pcont->destroy();
687
  free_items();
688 689 690 691 692 693 694 695 696 697

  /*
    If we have non-empty LEX stack then we just came out of parser with
    error. Now we should delete all auxilary LEXes and restore original
    THD::lex (In this case sp_head::restore_thd_mem_root() was not called
    too, so m_thd points to the current thread context).
    It is safe to not update LEX::ptr because further query string parsing
    and execution will be stopped anyway.
  */
  DBUG_ASSERT(m_lex.is_empty() || m_thd);
698 699
  while ((lex= (LEX *)m_lex.pop()))
  {
700 701
    delete m_thd->lex;
    m_thd->lex= lex;
702
  }
703

704
  hash_free(&m_sptabs);
705
  hash_free(&m_sroutines);
706
  DBUG_VOID_RETURN;
707
}
708

unknown's avatar
unknown committed
709

710
/*
711 712 713 714
  This is only used for result fields from functions (both during
  fix_length_and_dec() and evaluation).
*/

unknown's avatar
unknown committed
715 716 717 718 719
Field *
sp_head::make_field(uint max_length, const char *name, TABLE *dummy)
{
  Field *field;
  DBUG_ENTER("sp_head::make_field");
720

unknown's avatar
unknown committed
721 722 723
  field= ::make_field((char *)0,
		!m_returns_len ? max_length : m_returns_len, 
		(uchar *)"", 0, m_returns_pack, m_returns, m_returns_cs,
724
		m_geom_returns, Field::NONE, 
unknown's avatar
unknown committed
725 726 727 728 729
		m_returns_typelib,
		name ? name : (const char *)m_name.str, dummy);
  DBUG_RETURN(field);
}

730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775

int cmp_splocal_locations(Item_splocal * const *a, Item_splocal * const *b)
{
  return (int)((*a)->pos_in_query - (*b)->pos_in_query);
}


/*
  StoredRoutinesBinlogging
  Top-down overview:

  1. Statements

  Statements that have is_update_query(stmt) == TRUE are written into the
  binary log verbatim.
  Examples:
    UPDATE tbl SET tbl.x = spfunc_w_side_effects()
    UPDATE tbl SET tbl.x=1 WHERE spfunc_w_side_effect_that_returns_false(tbl.y)

  Statements that have is_update_query(stmt) == FALSE (e.g. SELECTs) are not
  written into binary log. Instead we catch function calls the statement
  makes and write it into binary log separately (see #3).
  
  We actually can easily write SELECT statements into the binary log in the 
  right order (we don't have issues with const tables being unlocked early
  because SELECTs that use FUNCTIONs unlock all tables at once) We don't do 
  it because replication slave thread currently can't execute SELECT
  statements. Fixing this is on the TODO.
  
  2. PROCEDURE calls

  CALL statements are not written into binary log. Instead
  * Any FUNCTION invocation (in SET, IF, WHILE, OPEN CURSOR and other SP
    instructions) is written into binlog separately.

  * Each statement executed in SP is binlogged separately, according to rules
    in #1, with the exception that we modify query string: we replace uses
    of SP local variables with NAME_CONST('spvar_name', <spvar-value>) calls.
    This substitution is done in subst_spvars().

  3. FUNCTION calls
  
  In sp_head::execute_function(), we check 
   * If this function invocation is done from a statement that is written
     into the binary log.
   * If there were any attempts to write events to the binary log during
776 777
     function execution (grep for start_union_events and stop_union_events)

778 779
   If the answers are No and Yes, we write the function call into the binary
   log as "DO spfunc(<param1value>, <param2value>, ...)"
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
  
  
  4. Miscellaneous issues.
  
  4.1 User variables. 

  When we call mysql_bin_log.write() for an SP statement, thd->user_var_events
  must hold set<{var_name, value}> pairs for all user variables used during 
  the statement execution.
  This set is produced by tracking user variable reads during statement
  execution. 

  Fo SPs, this has the following implications:
  1) thd->user_var_events may contain events from several SP statements and 
     needs to be valid after exection of these statements was finished. In 
     order to achieve that, we
     * Allocate user_var_events array elements on appropriate mem_root (grep
       for user_var_events_alloc).
     * Use is_query_in_union() to determine if user_var_event is created.
     
  2) We need to empty thd->user_var_events after we have wrote a function
     call. This is currently done by making 
     reset_dynamic(&thd->user_var_events);
     calls in several different places. (TODO cosider moving this into
     mysql_bin_log.write() function)
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
*/


/*
  Replace thd->query{_length} with a string that one can write to the binlog.
 
  SYNOPSIS
    subst_spvars()
      thd        Current thread. 
      instr      Instruction (we look for Item_splocal instances in
                 instr->free_list)
      query_str  Original query string
     
  DESCRIPTION

  The binlog-suitable string is produced by replacing references to SP local 
  variables with NAME_CONST('sp_var_name', value) calls.
 
  RETURN
824
    0  Ok, thd->query{_length} either has been appropriately replaced or
825 826 827 828 829 830 831 832 833 834
       there is no need for replacements.
    1  Out of memory error.
*/

static bool subst_spvars(THD *thd, sp_instr *instr, LEX_STRING *query_str)
{
  DBUG_ENTER("subst_spvars");
  if (thd->prelocked_mode == NON_PRELOCKED && mysql_bin_log.is_open())
  {
    Dynamic_array<Item_splocal*> sp_vars_uses;
835 836 837
    char *pbuf, *cur, buffer[512];
    String qbuf(buffer, sizeof(buffer), &my_charset_bin);
    int prev_pos, res;
838 839 840 841

    /* Find all instances of item_splocal used in this statement */
    for (Item *item= instr->free_list; item; item= item->next)
    {
unknown's avatar
unknown committed
842 843 844 845 846 847
      if (item->is_splocal())
      {
        Item_splocal *item_spl= (Item_splocal*)item;
        if (item_spl->pos_in_query)
          sp_vars_uses.append(item_spl);
      }
848 849 850 851 852 853 854 855 856 857 858 859
    }
    if (!sp_vars_uses.elements())
      DBUG_RETURN(0);
      
    /* Sort SP var refs by their occurences in the query */
    sp_vars_uses.sort(cmp_splocal_locations);

    /* 
      Construct a statement string where SP local var refs are replaced
      with "NAME_CONST(name, value)"
    */
    qbuf.length(0);
860 861
    cur= query_str->str;
    prev_pos= res= 0;
862 863 864
    for (Item_splocal **splocal= sp_vars_uses.front(); 
         splocal < sp_vars_uses.back(); splocal++)
    {
865
      Item *val;
866
      (*splocal)->thd= thd;            // fix_fields() is not yet done
867
      /* append the text between sp ref occurences */
868
      res|= qbuf.append(cur + prev_pos, (*splocal)->pos_in_query - prev_pos);
869 870 871
      prev_pos= (*splocal)->pos_in_query + (*splocal)->m_name.length;
      
      /* append the spvar substitute */
872
      res|= qbuf.append(STRING_WITH_LEN(" NAME_CONST('"));
873
      res|= qbuf.append((*splocal)->m_name.str, (*splocal)->m_name.length);
874
      res|= qbuf.append(STRING_WITH_LEN("',"));
875
      val= (*splocal)->this_item();
876 877
      DBUG_PRINT("info", ("print %p", val));
      val->print(&qbuf);
878
      res|= qbuf.append(')');
879 880 881
      if (res)
        break;
    }
882
    res|= qbuf.append(cur + prev_pos, query_str->length - prev_pos);
883 884 885
    if (res)
      DBUG_RETURN(1);

886
    if (!(pbuf= thd->strmake(qbuf.ptr(), qbuf.length())))
887 888 889 890 891 892 893 894 895
      DBUG_RETURN(1);

    thd->query= pbuf;
    thd->query_length= qbuf.length();
  }
  DBUG_RETURN(0);
}


896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
/*
  Return appropriate error about recursion limit reaching

  SYNOPSIS
    sp_head::recursion_level_error()

  NOTE
    For functions and triggers we return error about prohibited recursion.
    For stored procedures we return about reaching recursion limit.
*/

void sp_head::recursion_level_error()
{
  if (m_type == TYPE_ENUM_PROCEDURE)
  {
    THD *thd= current_thd;
    my_error(ER_SP_RECURSION_LIMIT, MYF(0),
             thd->variables.max_sp_recursion_depth,
             m_name);
  }
  else
    my_error(ER_SP_NO_RECURSION, MYF(0));
}


921 922 923 924 925 926 927 928 929 930
/*
  Execute the routine. The main instruction jump loop is there 
  Assume the parameters already set.
  
  RETURN
    -1  on error

*/

int sp_head::execute(THD *thd)
931
{
932
  DBUG_ENTER("sp_head::execute");
933
  char olddb[128];
934
  bool dbchanged;
935
  sp_rcontext *ctx;
936
  int ret= 0;
937
  uint ip= 0;
938
  ulong save_sql_mode;
unknown's avatar
unknown committed
939
  Query_arena *old_arena;
940 941 942
  /* per-instruction arena */
  MEM_ROOT execute_mem_root;
  Query_arena execute_arena(&execute_mem_root, INITIALIZED_FOR_SP),
unknown's avatar
unknown committed
943
              backup_arena;
944
  query_id_t old_query_id;
945 946 947 948
  TABLE *old_derived_tables;
  LEX *old_lex;
  Item_change_list old_change_list;
  String old_packet;
949

950
  /* Use some extra margin for possible SP recursion and functions */
951
  if (check_stack_overrun(thd, 8 * STACK_MIN_SIZE, (char*)&old_packet))
952 953 954
  {
    DBUG_RETURN(-1);
  }
955

956 957 958 959
  /* init per-instruction memroot */
  init_alloc_root(&execute_mem_root, MEM_ROOT_BLOCK_SIZE, 0);

  DBUG_ASSERT(!(m_flags & IS_INVOKED));
960
  m_flags|= IS_INVOKED;
961 962 963
  m_first_instance->m_first_free_instance= m_next_cached_sp;
  DBUG_PRINT("info", ("first free for 0x%lx ++: 0x%lx->0x%lx, level: %lu, flags %x",
                      (ulong)m_first_instance, this, m_next_cached_sp,
964 965 966 967 968 969
                      (m_next_cached_sp ?
                       m_next_cached_sp->m_recursion_level :
                       0),
                      (m_next_cached_sp ?
                       m_next_cached_sp->m_flags :
                       0)));
970 971 972 973 974 975 976 977 978
  /*
    Check that if there are not any instances after this one then
    pointer to the last instance points on this instance or if there are
    some instances after this one then recursion level of next instance
    greater then recursion level of current instance on 1
  */
  DBUG_ASSERT((m_next_cached_sp == 0 &&
               m_first_instance->m_last_cached_sp == this) ||
              (m_recursion_level + 1 == m_next_cached_sp->m_recursion_level));
979

980
  dbchanged= FALSE;
981 982
  if (m_db.length &&
      (ret= sp_use_new_db(thd, m_db.str, olddb, sizeof(olddb), 0, &dbchanged)))
983
    goto done;
984

985
  if ((ctx= thd->spcont))
986
    ctx->clear_handler();
987
  thd->query_error= 0;
unknown's avatar
unknown committed
988
  old_arena= thd->stmt_arena;
989

990 991 992 993 994 995 996
  /*
    We have to save/restore this info when we are changing call level to
    be able properly do close_thread_tables() in instructions.
  */
  old_query_id= thd->query_id;
  old_derived_tables= thd->derived_tables;
  thd->derived_tables= 0;
997 998
  save_sql_mode= thd->variables.sql_mode;
  thd->variables.sql_mode= m_sql_mode;
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
  /*
    It is also more efficient to save/restore current thd->lex once when
    do it in each instruction
  */
  old_lex= thd->lex;
  /*
    We should also save Item tree change list to avoid rollback something
    too early in the calling query.
  */
  old_change_list= thd->change_list;
  thd->change_list.empty();
  /*
    Cursors will use thd->packet, so they may corrupt data which was prepared
    for sending by upper level. OTOH cursors in the same routine can share this
    buffer safely so let use use routine-local packet instead of having own
    packet buffer for each cursor.

    It is probably safe to use same thd->convert_buff everywhere.
  */
  old_packet.swap(thd->packet);

1020 1021 1022 1023
  /*
    Switch to per-instruction arena here. We can do it since we cleanup
    arena after every instruction.
  */
unknown's avatar
unknown committed
1024
  thd->set_n_backup_active_arena(&execute_arena, &backup_arena);
1025 1026 1027 1028 1029

  /*
    Save callers arena in order to store instruction results and out
    parameters in it later during sp_eval_func_item()
  */
unknown's avatar
unknown committed
1030
  thd->spcont->callers_arena= &backup_arena;
1031

1032 1033 1034
  do
  {
    sp_instr *i;
1035
    uint hip;			// Handler ip
1036 1037 1038 1039 1040

    i = get_instr(ip);	// Returns NULL when we're done.
    if (i == NULL)
      break;
    DBUG_PRINT("execute", ("Instruction %u", ip));
1041 1042 1043
    /* Don't change NOW() in FUNCTION or TRIGGER */
    if (!thd->in_sub_stmt)
      thd->set_time();		// Make current_time() et al work
1044
    
1045
    /*
unknown's avatar
unknown committed
1046
      We have to set thd->stmt_arena before executing the instruction
1047 1048 1049 1050
      to store in the instruction free_list all new items, created
      during the first execution (for example expanding of '*' or the
      items made during other permanent subquery transformations).
    */
unknown's avatar
unknown committed
1051
    thd->stmt_arena= i;
1052
    
1053 1054 1055 1056 1057
    /* 
      Will write this SP statement into binlog separately 
      (TODO: consider changing the condition to "not inside event union")
    */
    if (thd->prelocked_mode == NON_PRELOCKED)
1058 1059
      thd->user_var_events_alloc= thd->mem_root;
    
1060
    ret= i->execute(thd, &ip);
1061

1062
    /*
1063 1064 1065
      If this SP instruction have sent eof, it has caused no_send_error to be
      set. Clear it back to allow the next instruction to send error. (multi-
      statement execution code clears no_send_error between statements too)
1066 1067
    */
    thd->net.no_send_error= 0;
1068 1069
    if (i->free_list)
      cleanup_items(i->free_list);
1070
    i->state= Query_arena::EXECUTED;
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
    
    /* 
      If we've set thd->user_var_events_alloc to mem_root of this SP
      statement, clean all the events allocated in it.
    */
    if (thd->prelocked_mode == NON_PRELOCKED)
    {
      reset_dynamic(&thd->user_var_events);
      thd->user_var_events_alloc= NULL;//DEBUG
    }
1081

1082
    /* we should cleanup free_list and memroot, used by instruction */
1083
    thd->cleanup_after_query();
1084
    free_root(&execute_mem_root, MYF(0));    
1085

unknown's avatar
unknown committed
1086 1087 1088 1089 1090 1091 1092 1093
    /*
      Check if an exception has occurred and a handler has been found
      Note: We havo to check even if ret==0, since warnings (and some
      errors don't return a non-zero value.
      We also have to check even if thd->killed != 0, since some
      errors return with this even when a handler has been found
      (e.g. "bad data").
    */
1094
    if (ctx)
1095 1096 1097
    {
      uint hf;

1098
      switch (ctx->found_handler(&hip, &hf)) {
1099 1100 1101
      case SP_HANDLER_NONE:
	break;
      case SP_HANDLER_CONTINUE:
unknown's avatar
unknown committed
1102
        thd->restore_active_arena(&execute_arena, &backup_arena);
1103
        ctx->save_variables(hf);
unknown's avatar
unknown committed
1104
        thd->set_n_backup_active_arena(&execute_arena, &backup_arena);
1105
        ctx->push_hstack(ip);
unknown's avatar
unknown committed
1106
        // Fall through
1107 1108 1109 1110
      default:
	ip= hip;
	ret= 0;
	ctx->clear_handler();
1111
	ctx->enter_handler(hip);
unknown's avatar
unknown committed
1112
        thd->clear_error();
1113
	thd->killed= THD::NOT_KILLED;
1114 1115 1116
	continue;
      }
    }
unknown's avatar
unknown committed
1117
  } while (ret == 0 && !thd->killed);
1118

unknown's avatar
unknown committed
1119
  thd->restore_active_arena(&execute_arena, &backup_arena);
1120 1121


1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
  /* Restore all saved */
  old_packet.swap(thd->packet);
  DBUG_ASSERT(thd->change_list.is_empty());
  thd->change_list= old_change_list;
  /* To avoid wiping out thd->change_list on old_change_list destruction */
  old_change_list.empty();
  thd->lex= old_lex;
  thd->query_id= old_query_id;
  DBUG_ASSERT(!thd->derived_tables);
  thd->derived_tables= old_derived_tables;
1132
  thd->variables.sql_mode= save_sql_mode;
1133

unknown's avatar
unknown committed
1134
  thd->stmt_arena= old_arena;
1135
  state= EXECUTED;
1136

1137
 done:
1138 1139
  DBUG_PRINT("info", ("ret=%d killed=%d query_error=%d",
		      ret, thd->killed, thd->query_error));
1140

unknown's avatar
unknown committed
1141
  if (thd->killed)
1142
    ret= -1;
1143 1144
  /* If the DB has changed, the pointer has changed too, but the
     original thd->db will then have been freed */
1145
  if (dbchanged)
1146
  {
1147 1148 1149 1150
    /*
      No access check when changing back to where we came from.
      (It would generate an error from mysql_change_db() when olddb=="")
    */
1151
    if (! thd->killed)
1152
      ret|= (int) mysql_change_db(thd, olddb, 1);
1153
  }
1154
  m_flags&= ~IS_INVOKED;
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
  DBUG_PRINT("info", ("first free for 0x%lx --: 0x%lx->0x%lx, level: %lu, flags %x",
                      (ulong)m_first_instance,
                      m_first_instance->m_first_free_instance, this,
                      m_recursion_level, m_flags));
  /*
    Check that we have one of following:

    1) there are not free instances which means that this instance is last
    in the list of instances (pointer to the last instance point on it and
    ther are not other instances after this one in the list)

    2) There are some free instances which mean that first free instance
    should go just after this one and recursion level of that free instance
    should be on 1 more then recursion leven of this instance.
  */
  DBUG_ASSERT((m_first_instance->m_first_free_instance == 0 &&
               this == m_first_instance->m_last_cached_sp &&
               m_next_cached_sp == 0) ||
              (m_first_instance->m_first_free_instance != 0 &&
               m_first_instance->m_first_free_instance == m_next_cached_sp &&
               m_first_instance->m_first_free_instance->m_recursion_level ==
               m_recursion_level + 1));
  m_first_instance->m_first_free_instance= this;
1178 1179 1180 1181
  DBUG_RETURN(ret);
}


1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
/*
  Execute a function:
   - evaluate parameters
   - call sp_head::execute
   - evaluate the return value

  SYNOPSIS
    sp_head::execute_function()
      thd        Thread handle
      argp       Passed arguments (these are items from containing statement?)
      argcount   Number of passed arguments. We need to check if this is
                 correct.
      resp   OUT Put result item here (q: is it a constant Item always?) 
   
  RETURN
    0      on OK
    other  on error
*/

1201 1202 1203
int
sp_head::execute_function(THD *thd, Item **argp, uint argcount, Item **resp)
{
1204 1205 1206
  Item **param_values;
  ulonglong binlog_save_options;
  bool need_binlog_call;
1207
  DBUG_ENTER("sp_head::execute_function");
1208
  DBUG_PRINT("info", ("function %s", m_name.str));
1209 1210 1211 1212
  uint csize = m_pcont->max_pvars();
  uint params = m_pcont->current_pvars();
  uint hmax = m_pcont->max_handlers();
  uint cmax = m_pcont->max_cursors();
1213 1214 1215
  sp_rcontext *octx = thd->spcont;
  sp_rcontext *nctx = NULL;
  uint i;
1216
  int ret= -1;                                  // Assume error
1217

unknown's avatar
unknown committed
1218 1219
  if (argcount != params)
  {
unknown's avatar
unknown committed
1220
    /*
1221
      Need to use my_error here, or it will not terminate the
unknown's avatar
unknown committed
1222 1223
      invoking query properly.
    */
1224
    my_error(ER_SP_WRONG_NO_OF_ARGS, MYF(0),
1225
             "FUNCTION", m_qname.str, params, argcount);
1226
    goto end;
unknown's avatar
unknown committed
1227 1228
  }

1229 1230
  if (!(param_values= (Item**)thd->alloc(sizeof(Item*)*argcount)))
    DBUG_RETURN(-1);
1231

unknown's avatar
unknown committed
1232
  // QQ Should have some error checking here? (types, etc...)
1233
  if (!(nctx= new sp_rcontext(octx, csize, hmax, cmax)))
1234
    goto end;
1235 1236 1237
#ifndef DBUG_OFF
  nctx->owner= this;
#endif
1238
  for (i= 0 ; i < argcount ; i++)
1239
  {
1240
    sp_pvar_t *pvar = m_pcont->find_pvar(i);
1241
    Item *it= sp_eval_func_item(thd, argp++, pvar->type, NULL, FALSE);
1242
    param_values[i]= it;
1243

1244 1245 1246
    if (!it)
      goto end;                                 // EOM error
    nctx->push_item(it);
1247
  }
1248

1249

unknown's avatar
unknown committed
1250 1251
  /*
    The rest of the frame are local variables which are all IN.
1252 1253
    Push NULLs to get the right size (and make the reuse mechanism work) -
    the will be initialized by set instructions in each frame.
unknown's avatar
unknown committed
1254
  */
1255
  for (; i < csize ; i++)
1256 1257
    nctx->push_item(NULL);

1258 1259
  thd->spcont= nctx;

1260 1261 1262
  binlog_save_options= thd->options;
  need_binlog_call= mysql_bin_log.is_open() && (thd->options & OPTION_BIN_LOG);
  if (need_binlog_call)
1263 1264
  {
    reset_dynamic(&thd->user_var_events);
1265
    mysql_bin_log.start_union_events(thd);
1266
  }
1267 1268
    
  thd->options&= ~OPTION_BIN_LOG;
1269
  ret= execute(thd);
1270 1271 1272 1273 1274
  thd->options= binlog_save_options;
  
  if (need_binlog_call)
    mysql_bin_log.stop_union_events(thd);

1275
  if (need_binlog_call && thd->binlog_evt_union.unioned_events)
1276
  {
1277
    char buf[256];
1278 1279
    String bufstr(buf, sizeof(buf), &my_charset_bin);
    bufstr.length(0);
1280
    bufstr.append(STRING_WITH_LEN("DO "));
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
    append_identifier(thd, &bufstr, m_name.str, m_name.length);
    bufstr.append('(');
    for (uint i=0; i < argcount; i++)
    {
      if (i)
        bufstr.append(',');
      param_values[i]->print(&bufstr);
    }
    bufstr.append(')');
    
1291 1292 1293 1294
    Query_log_event qinfo(thd, bufstr.ptr(), bufstr.length(),
                          thd->binlog_evt_union.unioned_events_trans, FALSE);
    if (mysql_bin_log.write(&qinfo) && 
        thd->binlog_evt_union.unioned_events_trans)
1295
    {
1296 1297 1298
      push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, ER_UNKNOWN_ERROR,
                   "Invoked ROUTINE modified a transactional table but MySQL "
                   "failed to reflect this change in the binary log");
1299
    }
1300
    reset_dynamic(&thd->user_var_events);
1301
  }
1302 1303

  if (m_type == TYPE_ENUM_FUNCTION && ret == 0)
1304
  {
1305
    /* We need result only in function but not in trigger */
1306 1307 1308
    Item *it= nctx->get_result();

    if (it)
1309
      *resp= sp_eval_func_item(thd, &it, m_returns, NULL, FALSE);
1310 1311
    else
    {
1312
      my_error(ER_SP_NORETURNEND, MYF(0), m_name.str);
1313 1314 1315
      ret= -1;
    }
  }
1316

1317
  nctx->pop_all_cursors();	// To avoid memory leaks after an error
1318
  delete nctx;                                  // Doesn't do anything
1319
  thd->spcont= octx;
1320

1321
end:
1322 1323 1324
  DBUG_RETURN(ret);
}

1325 1326

static Item_func_get_user_var *item_is_user_var(Item *it)
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
{
  if (it->type() == Item::FUNC_ITEM)
  {
    Item_func *fi= static_cast<Item_func*>(it);

    if (fi->functype() == Item_func::GUSERVAR_FUNC)
      return static_cast<Item_func_get_user_var*>(fi);
  }
  return NULL;
}

1338

1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
/*
  Execute a procedure. 
  SYNOPSIS
    sp_head::execute_procedure()
      thd    Thread handle
      args   List of values passed as arguments.
      
  DESCRIPTION

  The function does the following steps:
   - Set all parameters 
   - call sp_head::execute
   - copy back values of INOUT and OUT parameters

  RETURN
    0   Ok
    -1  Error
*/

1358
int sp_head::execute_procedure(THD *thd, List<Item> *args)
1359
{
1360
  int ret= 0;
1361 1362 1363 1364
  uint csize = m_pcont->max_pvars();
  uint params = m_pcont->current_pvars();
  uint hmax = m_pcont->max_handlers();
  uint cmax = m_pcont->max_cursors();
1365
  sp_rcontext *save_spcont, *octx;
1366
  sp_rcontext *nctx = NULL;
1367 1368
  DBUG_ENTER("sp_head::execute_procedure");
  DBUG_PRINT("info", ("procedure %s", m_name.str));
1369

unknown's avatar
unknown committed
1370 1371
  if (args->elements != params)
  {
1372
    my_error(ER_SP_WRONG_NO_OF_ARGS, MYF(0), "PROCEDURE",
1373
             m_qname.str, params, args->elements);
unknown's avatar
unknown committed
1374 1375 1376
    DBUG_RETURN(-1);
  }

1377
  save_spcont= octx= thd->spcont;
1378 1379
  if (! octx)
  {				// Create a temporary old context
1380
    if (!(octx= new sp_rcontext(octx, csize, hmax, cmax)))
1381
      DBUG_RETURN(-1);
1382 1383 1384
#ifndef DBUG_OFF
    octx->owner= 0;
#endif
1385 1386 1387 1388 1389 1390
    thd->spcont= octx;

    /* set callers_arena to thd, for upper-level function to work */
    thd->spcont->callers_arena= thd;
  }

1391
  if (!(nctx= new sp_rcontext(octx, csize, hmax, cmax)))
1392 1393 1394 1395
  {
    thd->spcont= save_spcont;
    DBUG_RETURN(-1);
  }
1396 1397 1398
#ifndef DBUG_OFF
  nctx->owner= this;
#endif
1399

1400
  if (csize > 0 || hmax > 0 || cmax > 0)
1401
  {
1402
    Item_null *nit= NULL;	// Re-use this, and only create if needed
1403
    uint i;
1404
    List_iterator<Item> li(*args);
1405
    Item *it;
1406

1407
    /* Evaluate SP arguments (i.e. get the values passed as parameters) */
unknown's avatar
unknown committed
1408
    // QQ: Should do type checking?
1409
    DBUG_PRINT("info",(" %.*s: eval args", m_name.length, m_name.str));
1410 1411
    for (i = 0 ; (it= li++) && i < params ; i++)
    {
1412
      sp_pvar_t *pvar= m_pcont->find_pvar(i);
1413

1414
      if (pvar)
1415
      {
1416 1417 1418 1419 1420 1421 1422 1423 1424
	if (pvar->mode != sp_param_in)
	{
	  if (!it->is_splocal() && !item_is_user_var(it))
	  {
	    my_error(ER_SP_NOT_VAR_ARG, MYF(0), i+1, m_qname.str);
	    ret= -1;
	    break;
	  }
	}
1425
	if (pvar->mode == sp_param_out)
1426 1427
	{
	  if (! nit)
1428 1429 1430 1431 1432 1433 1434
          {
	    if (!(nit= new Item_null()))
            {
              ret= -1;
              break;
            }
          }
1435 1436
	  nctx->push_item(nit); // OUT
	}
1437
	else
1438
	{
1439
	  Item *it2= sp_eval_func_item(thd, li.ref(), pvar->type, NULL, FALSE);
1440

1441
	  if (!it2)
1442 1443 1444 1445
	  {
	    ret= -1;		// Eval failed
	    break;
	  }
1446
          nctx->push_item(it2); // IN or INOUT
1447
	}
1448
      }
1449
    }
1450

1451 1452
    /* 
      Okay, got values for all arguments. Close tables that might be used by 
1453 1454
      arguments evaluation. If arguments evaluation required prelocking mode, 
      we'll leave it here.
1455 1456
    */
    if (!thd->in_sub_stmt)
1457
      close_thread_tables(thd, 0, 0);
1458 1459

    DBUG_PRINT("info",(" %.*s: eval args done", m_name.length, m_name.str));
1460

unknown's avatar
unknown committed
1461 1462
    /*
      The rest of the frame are local variables which are all IN.
1463 1464
      Push NULLs to get the right size (and make the reuse mechanism work) -
      the will be initialized by set instructions in each frame.
unknown's avatar
unknown committed
1465
    */
1466
    for (; i < csize ; i++)
1467
      nctx->push_item(NULL);
1468 1469
  }

1470 1471
  thd->spcont= nctx;

1472 1473
  if (! ret)
    ret= execute(thd);
1474 1475 1476 1477 1478 1479 1480 1481

  /*
    In the case when we weren't able to employ reuse mechanism for
    OUT/INOUT paranmeters, we should reallocate memory. This
    allocation should be done on the arena which will live through
    all execution of calling routine.
  */
  thd->spcont->callers_arena= octx->callers_arena;
1482

unknown's avatar
unknown committed
1483
  if (!ret && csize > 0)
1484
  {
1485
    List_iterator<Item> li(*args);
1486
    Item *it;
1487

unknown's avatar
unknown committed
1488 1489 1490 1491
    /*
      Copy back all OUT or INOUT values to the previous frame, or
      set global user variables
    */
1492
    for (uint i = 0 ; (it= li++) && i < params ; i++)
1493
    {
1494
      sp_pvar_t *pvar= m_pcont->find_pvar(i);
1495

1496
      if (pvar->mode != sp_param_in)
1497
      {
1498
	if (it->is_splocal())
1499 1500 1501 1502 1503 1504
	{
	  // Have to copy the item to the caller's mem_root
	  Item *copy;
	  uint offset= static_cast<Item_splocal *>(it)->get_offset();
	  Item *val= nctx->get_item(i);
	  Item *orig= octx->get_item(offset);
1505 1506 1507 1508 1509 1510 1511

          /*
            We might need to allocate new item if we weren't able to
            employ reuse mechanism. Then we should do it on the callers arena.
          */
	  copy= sp_eval_func_item(thd, &val, pvar->type, orig, TRUE); // Copy

1512 1513 1514 1515 1516 1517 1518 1519
	  if (!copy)
	  {
	    ret= -1;
	    break;
	  }
	  if (copy != orig)
	    octx->set_item(offset, copy);
	}
1520
	else
1521
	{
1522 1523 1524
	  Item_func_get_user_var *guv= item_is_user_var(it);

	  if (guv)
1525
	  {
1526 1527 1528 1529 1530
	    Item *item= nctx->get_item(i);
	    Item_func_set_user_var *suv;

	    suv= new Item_func_set_user_var(guv->get_name(), item);
	    /*
1531 1532
              Item_func_set_user_var is not fixed after construction,
              call fix_fields().
1533
	    */
1534 1535 1536
            if ((ret= test(!suv || suv->fix_fields(thd, &item) ||
                           suv->check() || suv->update())))
              break;
1537
	  }
1538 1539
	}
      }
1540 1541 1542
    }
  }

1543 1544
  if (!save_spcont)
    delete octx;                                // Does nothing
1545

1546
  nctx->pop_all_cursors();	// To avoid memory leaks after an error
1547 1548
  delete nctx;                                  // Does nothing
  thd->spcont= save_spcont;
1549

1550
  DBUG_RETURN(ret);
1551 1552 1553
}


1554
// Reset lex during parsing, before we parse a sub statement.
1555 1556 1557
void
sp_head::reset_lex(THD *thd)
{
1558 1559
  DBUG_ENTER("sp_head::reset_lex");
  LEX *sublex;
1560
  LEX *oldlex= thd->lex;
1561
  my_lex_states state= oldlex->next_state; // Keep original next_state
1562

1563
  (void)m_lex.push_front(oldlex);
1564
  thd->lex= sublex= new st_lex;
unknown's avatar
unknown committed
1565

1566
  /* Reset most stuff. The length arguments doesn't matter here. */
unknown's avatar
unknown committed
1567
  lex_start(thd, oldlex->buf, (ulong) (oldlex->end_of_query - oldlex->ptr));
unknown's avatar
unknown committed
1568

1569 1570 1571 1572 1573
  /*
   * next_state is normally the same (0), but it happens that we swap lex in
   * "mid-sentence", so we must restore it.
   */
  sublex->next_state= state;
1574
  /* We must reset ptr and end_of_query again */
1575 1576 1577
  sublex->ptr= oldlex->ptr;
  sublex->end_of_query= oldlex->end_of_query;
  sublex->tok_start= oldlex->tok_start;
unknown's avatar
unknown committed
1578
  sublex->yylineno= oldlex->yylineno;
1579
  /* And keep the SP stuff too */
1580 1581
  sublex->sphead= oldlex->sphead;
  sublex->spcont= oldlex->spcont;
1582 1583
  /* And trigger related stuff too */
  sublex->trg_chistics= oldlex->trg_chistics;
1584
  sublex->trg_table_fields.empty();
1585
  sublex->sp_lex_in_use= FALSE;
1586
  DBUG_VOID_RETURN;
1587 1588
}

1589
// Restore lex during parsing, after we have parsed a sub statement.
1590 1591 1592
void
sp_head::restore_lex(THD *thd)
{
1593 1594
  DBUG_ENTER("sp_head::restore_lex");
  LEX *sublex= thd->lex;
1595 1596 1597 1598
  LEX *oldlex= (LEX *)m_lex.pop();

  if (! oldlex)
    return;			// Nothing to restore
1599

1600
  // Update some state in the old one first
1601 1602
  oldlex->ptr= sublex->ptr;
  oldlex->next_state= sublex->next_state;
1603
  oldlex->trg_table_fields.push_back(&sublex->trg_table_fields);
1604

1605
  /*
1606 1607
    Add routines which are used by statement to respective set for
    this routine.
1608
  */
1609
  sp_update_sp_used_routines(&m_sroutines, &sublex->sroutines);
1610 1611 1612 1613 1614
  /*
    Merge tables used by this statement (but not by its functions or
    procedures) to multiset of tables used by this routine.
  */
  merge_table_list(thd, sublex->query_tables, sublex);
1615 1616 1617
  if (! sublex->sp_lex_in_use)
    delete sublex;
  thd->lex= oldlex;
1618
  DBUG_VOID_RETURN;
1619 1620
}

1621
void
1622
sp_head::push_backpatch(sp_instr *i, sp_label_t *lab)
1623
{
1624
  bp_t *bp= (bp_t *)sql_alloc(sizeof(bp_t));
1625 1626 1627 1628 1629 1630 1631

  if (bp)
  {
    bp->lab= lab;
    bp->instr= i;
    (void)m_backpatch.push_front(bp);
  }
1632 1633 1634
}

void
1635
sp_head::backpatch(sp_label_t *lab)
1636
{
1637
  bp_t *bp;
1638
  uint dest= instructions();
1639
  List_iterator_fast<bp_t> li(m_backpatch);
1640

1641
  while ((bp= li++))
1642 1643 1644 1645
  {
    if (bp->lab == lab ||
	(bp->lab->type == SP_LAB_REF &&
	 my_strcasecmp(system_charset_info, bp->lab->name, lab->name) == 0))
1646
    {
1647 1648 1649 1650 1651
      if (bp->lab->type != SP_LAB_REF)
	bp->instr->backpatch(dest, lab->ctx);
      else
      {
	sp_label_t *dstlab= bp->lab->ctx->find_label(lab->name);
1652

1653 1654 1655 1656 1657 1658
	if (dstlab)
	{
	  bp->lab= lab;
	  bp->instr->backpatch(dest, dstlab->ctx);
	}
      }
1659 1660 1661 1662 1663 1664 1665 1666 1667
    }
  }
}

int
sp_head::check_backpatch(THD *thd)
{
  bp_t *bp;
  List_iterator_fast<bp_t> li(m_backpatch);
1668

1669 1670 1671 1672
  while ((bp= li++))
  {
    if (bp->lab->type == SP_LAB_REF)
    {
1673
      my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "GOTO", bp->lab->name);
1674
      return -1;
1675
    }
1676 1677
  }
  return 0;
1678 1679
}

1680
void
1681
sp_head::set_info(longlong created, longlong modified,
1682
		  st_sp_chistics *chistics, ulong sql_mode)
1683 1684 1685
{
  m_created= created;
  m_modified= modified;
unknown's avatar
unknown committed
1686 1687
  m_chistics= (st_sp_chistics *) memdup_root(mem_root, (char*) chistics,
                                             sizeof(*chistics));
1688 1689 1690
  if (m_chistics->comment.length == 0)
    m_chistics->comment.str= 0;
  else
unknown's avatar
unknown committed
1691
    m_chistics->comment.str= strmake_root(mem_root,
1692 1693
					  m_chistics->comment.str,
					  m_chistics->comment.length);
1694
  m_sql_mode= sql_mode;
1695 1696
}

1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724

void
sp_head::set_definer(char *definer, uint definerlen)
{
  char *p= strrchr(definer, '@');

  if (!p)
  {
    m_definer_user.str= strmake_root(mem_root, "", 0);
    m_definer_user.length= 0;
    
    m_definer_host.str= strmake_root(mem_root, "", 0);
    m_definer_host.length= 0;
  }
  else
  {
    const uint user_name_len= p - definer;
    const uint host_name_len= definerlen - user_name_len - 1;

    m_definer_user.str= strmake_root(mem_root, definer, user_name_len);
    m_definer_user.length= user_name_len;

    m_definer_host.str= strmake_root(mem_root, p + 1, host_name_len);
    m_definer_host.length= host_name_len;
  }
}


1725 1726 1727
void
sp_head::reset_thd_mem_root(THD *thd)
{
1728
  DBUG_ENTER("sp_head::reset_thd_mem_root");
1729
  m_thd_root= thd->mem_root;
unknown's avatar
unknown committed
1730
  thd->mem_root= &main_mem_root;
1731 1732 1733
  DBUG_PRINT("info", ("mem_root 0x%lx moved to thd mem root 0x%lx",
                      (ulong) &mem_root, (ulong) &thd->mem_root));
  free_list= thd->free_list; // Keep the old list
1734 1735 1736
  thd->free_list= NULL;	// Start a new one
  /* Copy the db, since substatements will point to it */
  m_thd_db= thd->db;
unknown's avatar
unknown committed
1737
  thd->db= thd->strmake(thd->db, thd->db_length);
1738
  m_thd= thd;
1739
  DBUG_VOID_RETURN;
1740 1741 1742 1743 1744
}

void
sp_head::restore_thd_mem_root(THD *thd)
{
1745 1746
  DBUG_ENTER("sp_head::restore_thd_mem_root");
  Item *flist= free_list;	// The old list
unknown's avatar
unknown committed
1747
  set_query_arena(thd);         // Get new free_list and mem_root
1748
  state= INITIALIZED_FOR_SP;
1749

1750 1751
  DBUG_PRINT("info", ("mem_root 0x%lx returned from thd mem root 0x%lx",
                      (ulong) &mem_root, (ulong) &thd->mem_root));
1752 1753 1754 1755
  thd->free_list= flist;	// Restore the old one
  thd->db= m_thd_db;		// Restore the original db pointer
  thd->mem_root= m_thd_root;
  m_thd= NULL;
1756
  DBUG_VOID_RETURN;
1757 1758 1759
}


1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774
/*
  Check if a user has access right to a routine

  SYNOPSIS
    check_show_routine_access()
    thd			Thread handler
    sp			SP
    full_access		Set to 1 if the user has SELECT right to the
			'mysql.proc' able or is the owner of the routine
  RETURN
    0  ok
    1  error
*/

bool check_show_routine_access(THD *thd, sp_head *sp, bool *full_access)
1775 1776 1777 1778 1779
{
  TABLE_LIST tables;
  bzero((char*) &tables,sizeof(tables));
  tables.db= (char*) "mysql";
  tables.table_name= tables.alias= (char*) "proc";
1780
  *full_access= (!check_table_access(thd, SELECT_ACL, &tables, 1) ||
1781 1782 1783 1784
                 (!strcmp(sp->m_definer_user.str,
                          thd->security_ctx->priv_user) &&
                  !strcmp(sp->m_definer_host.str,
                          thd->security_ctx->priv_host)));
1785
  if (!*full_access)
1786 1787
    return check_some_routine_access(thd, sp->m_db.str, sp->m_name.str,
                                     sp->m_type == TYPE_ENUM_PROCEDURE);
1788 1789 1790 1791
  return 0;
}


unknown's avatar
unknown committed
1792 1793 1794 1795 1796 1797 1798 1799
int
sp_head::show_create_procedure(THD *thd)
{
  Protocol *protocol= thd->protocol;
  char buff[2048];
  String buffer(buff, sizeof(buff), system_charset_info);
  int res;
  List<Item> field_list;
1800 1801
  byte *sql_mode_str;
  ulong sql_mode_len;
1802
  bool full_access;
unknown's avatar
unknown committed
1803 1804 1805

  DBUG_ENTER("sp_head::show_create_procedure");
  DBUG_PRINT("info", ("procedure %s", m_name.str));
1806 1807
  LINT_INIT(sql_mode_str);
  LINT_INIT(sql_mode_len);
1808

1809
  if (check_show_routine_access(thd, this, &full_access))
unknown's avatar
unknown committed
1810
    DBUG_RETURN(1);
1811

1812 1813 1814 1815
  sql_mode_str=
    sys_var_thd_sql_mode::symbolic_mode_representation(thd,
                                                       m_sql_mode,
                                                       &sql_mode_len);
1816
  field_list.push_back(new Item_empty_string("Procedure", NAME_LEN));
1817
  field_list.push_back(new Item_empty_string("sql_mode", sql_mode_len));
unknown's avatar
unknown committed
1818 1819
  // 1024 is for not to confuse old clients
  field_list.push_back(new Item_empty_string("Create Procedure",
1820
					     max(buffer.length(), 1024)));
1821 1822
  if (protocol->send_fields(&field_list, Protocol::SEND_NUM_ROWS |
                                         Protocol::SEND_EOF))
unknown's avatar
unknown committed
1823
    DBUG_RETURN(1);
unknown's avatar
unknown committed
1824 1825
  protocol->prepare_for_resend();
  protocol->store(m_name.str, m_name.length, system_charset_info);
1826
  protocol->store((char*) sql_mode_str, sql_mode_len, system_charset_info);
1827 1828
  if (full_access)
    protocol->store(m_defstr.str, m_defstr.length, system_charset_info);
unknown's avatar
unknown committed
1829 1830
  res= protocol->write();
  send_eof(thd);
1831

unknown's avatar
unknown committed
1832 1833 1834
  DBUG_RETURN(res);
}

1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847

/*
  Add instruction to SP

  SYNOPSIS
    sp_head::add_instr()
    instr   Instruction
*/

void sp_head::add_instr(sp_instr *instr)
{
  instr->free_list= m_thd->free_list;
  m_thd->free_list= 0;
1848 1849 1850 1851 1852 1853 1854
  /*
    Memory root of every instruction is designated for permanent
    transformations (optimizations) made on the parsed tree during
    the first execution. It points to the memory root of the
    entire stored procedure, as their life span is equal.
  */
  instr->mem_root= &main_mem_root;
1855 1856 1857 1858
  insert_dynamic(&m_instr, (gptr)&instr);
}


unknown's avatar
unknown committed
1859 1860 1861 1862 1863 1864 1865 1866
int
sp_head::show_create_function(THD *thd)
{
  Protocol *protocol= thd->protocol;
  char buff[2048];
  String buffer(buff, sizeof(buff), system_charset_info);
  int res;
  List<Item> field_list;
1867 1868
  byte *sql_mode_str;
  ulong sql_mode_len;
1869
  bool full_access;
unknown's avatar
unknown committed
1870 1871
  DBUG_ENTER("sp_head::show_create_function");
  DBUG_PRINT("info", ("procedure %s", m_name.str));
1872 1873
  LINT_INIT(sql_mode_str);
  LINT_INIT(sql_mode_len);
1874

1875
  if (check_show_routine_access(thd, this, &full_access))
unknown's avatar
unknown committed
1876
    DBUG_RETURN(1);
1877

1878 1879 1880 1881
  sql_mode_str=
    sys_var_thd_sql_mode::symbolic_mode_representation(thd,
                                                       m_sql_mode,
                                                       &sql_mode_len);
unknown's avatar
unknown committed
1882
  field_list.push_back(new Item_empty_string("Function",NAME_LEN));
1883
  field_list.push_back(new Item_empty_string("sql_mode", sql_mode_len));
unknown's avatar
unknown committed
1884 1885
  field_list.push_back(new Item_empty_string("Create Function",
					     max(buffer.length(),1024)));
1886 1887
  if (protocol->send_fields(&field_list,
                            Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
unknown's avatar
unknown committed
1888
    DBUG_RETURN(1);
unknown's avatar
unknown committed
1889 1890
  protocol->prepare_for_resend();
  protocol->store(m_name.str, m_name.length, system_charset_info);
1891
  protocol->store((char*) sql_mode_str, sql_mode_len, system_charset_info);
1892 1893
  if (full_access)
    protocol->store(m_defstr.str, m_defstr.length, system_charset_info);
unknown's avatar
unknown committed
1894 1895
  res= protocol->write();
  send_eof(thd);
1896

unknown's avatar
unknown committed
1897 1898
  DBUG_RETURN(res);
}
1899

1900 1901 1902 1903 1904 1905

/*
  TODO: what does this do??
*/

void sp_head::optimize()
1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
{
  List<sp_instr> bp;
  sp_instr *i;
  uint src, dst;

  opt_mark(0);

  bp.empty();
  src= dst= 0;
  while ((i= get_instr(src)))
  {
    if (! i->marked)
    {
      delete i;
      src+= 1;
    }
    else
    {
      if (src != dst)
      {
	sp_instr *ibp;
	List_iterator_fast<sp_instr> li(bp);

	set_dynamic(&m_instr, (gptr)&i, dst);
	while ((ibp= li++))
	{
	  sp_instr_jump *ji= static_cast<sp_instr_jump *>(ibp);
	  if (ji->m_dest == src)
	    ji->m_dest= dst;
	}
      }
      i->opt_move(dst, &bp);
      src+= 1;
      dst+= 1;
    }
  }
  m_instr.elements= dst;
  bp.empty();
}

void
sp_head::opt_mark(uint ip)
{
  sp_instr *i;

  while ((i= get_instr(ip)) && !i->marked)
    ip= i->opt_mark(this);
}

1955

unknown's avatar
unknown committed
1956 1957 1958 1959 1960 1961 1962 1963
#ifndef DBUG_OFF
int
sp_head::show_routine_code(THD *thd)
{
  Protocol *protocol= thd->protocol;
  char buff[2048];
  String buffer(buff, sizeof(buff), system_charset_info);
  List<Item> field_list;
1964
  sp_instr *i;
unknown's avatar
unknown committed
1965
  bool full_access;
1966
  int res= 0;
unknown's avatar
unknown committed
1967 1968
  uint ip;
  DBUG_ENTER("sp_head::show_routine_code");
1969
  DBUG_PRINT("info", ("procedure: %s", m_name.str));
unknown's avatar
unknown committed
1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988

  if (check_show_routine_access(thd, this, &full_access) || !full_access)
    DBUG_RETURN(1);

  field_list.push_back(new Item_uint("Pos", 9));
  // 1024 is for not to confuse old clients
  field_list.push_back(new Item_empty_string("Instruction",
					     max(buffer.length(), 1024)));
  if (protocol->send_fields(&field_list, Protocol::SEND_NUM_ROWS |
                                         Protocol::SEND_EOF))
    DBUG_RETURN(1);

  for (ip= 0; (i = get_instr(ip)) ; ip++)
  {
    protocol->prepare_for_resend();
    protocol->store((longlong)ip);

    buffer.set("", 0, system_charset_info);
    i->print(&buffer);
1989
    protocol->store(buffer.ptr(), buffer.length(), system_charset_info);
unknown's avatar
unknown committed
1990 1991 1992 1993 1994 1995 1996 1997 1998 1999
    if ((res= protocol->write()))
      break;
  }
  send_eof(thd);

  DBUG_RETURN(res);
}
#endif // ifndef DBUG_OFF


2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039
/*
  Prepare LEX and thread for execution of instruction, if requested open
  and lock LEX's tables, execute instruction's core function, perform
  cleanup afterwards.

  SYNOPSIS
    reset_lex_and_exec_core()
      thd         - thread context
      nextp       - out - next instruction
      open_tables - if TRUE then check read access to tables in LEX's table
                    list and open and lock them (used in instructions which
                    need to calculate some expression and don't execute
                    complete statement).
      sp_instr    - instruction for which we prepare context, and which core
                    function execute by calling its exec_core() method.

  NOTE
    We are not saving/restoring some parts of THD which may need this because
    we do this once for whole routine execution in sp_head::execute().

  RETURN VALUE
    0/non-0 - Success/Failure
*/

int
sp_lex_keeper::reset_lex_and_exec_core(THD *thd, uint *nextp,
                                       bool open_tables, sp_instr* instr)
{
  int res= 0;

  DBUG_ASSERT(!thd->derived_tables);
  DBUG_ASSERT(thd->change_list.is_empty());
  /*
    Use our own lex.
    We should not save old value since it is saved/restored in
    sp_head::execute() when we are entering/leaving routine.
  */
  thd->lex= m_lex;

  VOID(pthread_mutex_lock(&LOCK_thread_count));
2040
  thd->query_id= next_query_id();
2041 2042
  VOID(pthread_mutex_unlock(&LOCK_thread_count));

2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062
  if (thd->prelocked_mode == NON_PRELOCKED)
  {
    /*
      This statement will enter/leave prelocked mode on its own.
      Entering prelocked mode changes table list and related members
      of LEX, so we'll need to restore them.
    */
    if (lex_query_tables_own_last)
    {
      /*
        We've already entered/left prelocked mode with this statement.
        Attach the list of tables that need to be prelocked and mark m_lex
        as having such list attached.
      */
      *lex_query_tables_own_last= prelocking_tables;
      m_lex->mark_as_requiring_prelocking(lex_query_tables_own_last);
    }
  }
    
  reinit_stmt_before_use(thd, m_lex);
2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078
  /*
    If requested check whenever we have access to tables in LEX's table list
    and open and lock them before executing instructtions core function.
  */
  if (open_tables &&
      (check_table_access(thd, SELECT_ACL, m_lex->query_tables, 0) ||
       open_and_lock_tables(thd, m_lex->query_tables)))
      res= -1;

  if (!res)
    res= instr->exec_core(thd, nextp);

  m_lex->unit.cleanup();

  thd->proc_info="closing tables";
  close_thread_tables(thd);
unknown's avatar
unknown committed
2079
  thd->proc_info= 0;
2080

2081
  if (m_lex->query_tables_own_last)
2082
  {
2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095
    /*
      We've entered and left prelocking mode when executing statement
      stored in m_lex. 
      m_lex->query_tables(->next_global)* list now has a 'tail' - a list
      of tables that are added for prelocking. (If this is the first
      execution, the 'tail' was added by open_tables(), otherwise we've
      attached it above in this function).
      Now we'll save the 'tail', and detach it.
    */
    lex_query_tables_own_last= m_lex->query_tables_own_last;
    prelocking_tables= *lex_query_tables_own_last;
    *lex_query_tables_own_last= NULL;
    m_lex->mark_as_requiring_prelocking(NULL);
2096
  }
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107
  thd->rollback_item_tree_changes();

  /*
    Unlike for PS we should not call Item's destructors for newly created
    items after execution of each instruction in stored routine. This is
    because SP often create Item (like Item_int, Item_string etc...) when
    they want to store some value in local variable, pass return value and
    etc... So their life time should be longer than one instruction.

    cleanup_items() is called in sp_head::execute()
  */
2108
  return res || thd->net.report_error;
2109 2110 2111
}


unknown's avatar
unknown committed
2112 2113 2114 2115
/*
  sp_instr class functions
*/

2116
int sp_instr::exec_core(THD *thd, uint *nextp)
2117
{
2118 2119
  DBUG_ASSERT(0);
  return 0;
2120 2121
}

unknown's avatar
unknown committed
2122 2123 2124 2125
/*
  sp_instr_stmt class functions
*/

2126
int
2127
sp_instr_stmt::execute(THD *thd, uint *nextp)
2128
{
2129 2130
  char *query;
  uint32 query_length;
2131
  int res;
2132
  DBUG_ENTER("sp_instr_stmt::execute");
2133
  DBUG_PRINT("info", ("command: %d", m_lex_keeper.sql_command()));
2134 2135 2136

  query= thd->query;
  query_length= thd->query_length;
2137 2138
  if (!(res= alloc_query(thd, m_query.str, m_query.length+1)) &&
      !(res=subst_spvars(thd, this, &m_query)))
2139
  {
2140 2141 2142 2143
    /*
      (the order of query cache and subst_spvars calls is irrelevant because
      queries with SP vars can't be cached)
    */
2144 2145 2146
    if (query_cache_send_result_to_client(thd,
					  thd->query, thd->query_length) <= 0)
    {
2147
      res= m_lex_keeper.reset_lex_and_exec_core(thd, nextp, FALSE, this);
2148 2149
      query_cache_end_of_result(thd);
    }
2150 2151
    else
      *nextp= m_ip+1;
2152 2153 2154
    thd->query= query;
    thd->query_length= query_length;
  }
2155 2156 2157
  DBUG_RETURN(res);
}

2158 2159 2160 2161 2162 2163
/* 
   Sufficient max length of printed destinations and frame offsets (all uints).
*/
#define SP_INSTR_UINT_MAXLEN  8

#define SP_STMT_PRINT_MAXLEN 40
2164 2165 2166
void
sp_instr_stmt::print(String *str)
{
unknown's avatar
unknown committed
2167 2168
  uint i, len;

2169 2170
  /* stmt CMD "..." */
  if (str->reserve(SP_STMT_PRINT_MAXLEN+SP_INSTR_UINT_MAXLEN+8))
2171
    return;
2172
  str->qs_append(STRING_WITH_LEN("stmt "));
2173
  str->qs_append((uint)m_lex_keeper.sql_command());
2174
  str->qs_append(STRING_WITH_LEN(" \""));
unknown's avatar
unknown committed
2175 2176 2177 2178 2179
  len= m_query.length;
  /*
    Print the query string (but not too much of it), just to indicate which
    statement it is.
  */
2180 2181
  if (len > SP_STMT_PRINT_MAXLEN)
    len= SP_STMT_PRINT_MAXLEN-3;
unknown's avatar
unknown committed
2182 2183
  /* Copy the query string and replace '\n' with ' ' in the process */
  for (i= 0 ; i < len ; i++)
2184
  {
unknown's avatar
unknown committed
2185
    if (m_query.str[i] == '\n')
2186
      str->qs_append(' ');
unknown's avatar
unknown committed
2187
    else
2188 2189
      str->qs_append(m_query.str[i]);
  }
2190
  if (m_query.length > SP_STMT_PRINT_MAXLEN)
2191
    str->qs_append(STRING_WITH_LEN("...")); /* Indicate truncated string */
2192
  str->qs_append('"');
2193
}
2194
#undef SP_STMT_PRINT_MAXLEN
2195

2196
int
2197
sp_instr_stmt::exec_core(THD *thd, uint *nextp)
2198
{
2199 2200
  int res= mysql_execute_command(thd);
  *nextp= m_ip+1;
2201
  return res;
2202 2203
}

unknown's avatar
unknown committed
2204 2205 2206 2207 2208

/*
  sp_instr_set class functions
*/

2209
int
2210
sp_instr_set::execute(THD *thd, uint *nextp)
2211
{
2212 2213
  DBUG_ENTER("sp_instr_set::execute");
  DBUG_PRINT("info", ("offset: %u", m_offset));
2214 2215 2216 2217

  DBUG_RETURN(m_lex_keeper.reset_lex_and_exec_core(thd, nextp, TRUE, this));
}

unknown's avatar
unknown committed
2218

2219 2220 2221
int
sp_instr_set::exec_core(THD *thd, uint *nextp)
{
2222
  int res= thd->spcont->set_item_eval(thd, m_offset, &m_value, m_type);
2223

2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243
  if (res < 0 &&
      thd->spcont->get_item(m_offset) == NULL &&
      thd->spcont->found_handler_here())
  {
    /*
      Failed to evaluate the value, the variable is still not initialized,
      and a handler has been found. Set to null so we can continue.
    */
    Item *it= new Item_null();

    if (!it || thd->spcont->set_item_eval(thd, m_offset, &it, m_type) < 0)
    {                           /* If this also failed, we have to abort */
      sp_rcontext *spcont= thd->spcont;

      thd->spcont= 0;           /* Avoid handlers */
      my_error(ER_OUT_OF_RESOURCES, MYF(0));
      spcont->clear_handler();
      thd->spcont= spcont;
    }
  }
2244
  *nextp = m_ip+1;
2245
  return res;
2246 2247
}

2248 2249 2250
void
sp_instr_set::print(String *str)
{
2251 2252
  /* set name@offset ... */
  int rsrv = SP_INSTR_UINT_MAXLEN+6;
unknown's avatar
unknown committed
2253 2254 2255 2256 2257
  sp_pvar_t *var = m_ctx->find_pvar(m_offset);

  /* 'var' should always be non-null, but just in case... */
  if (var)
    rsrv+= var->name.length;
2258 2259
  if (str->reserve(rsrv))
    return;
2260
  str->qs_append(STRING_WITH_LEN("set "));
unknown's avatar
unknown committed
2261 2262
  if (var)
  {
2263 2264
    str->qs_append(var->name.str, var->name.length);
    str->qs_append('@');
unknown's avatar
unknown committed
2265
  }
2266
  str->qs_append(m_offset);
2267
  str->qs_append(' ');
2268 2269 2270
  m_value->print(str);
}

2271

unknown's avatar
unknown committed
2272 2273 2274 2275
/*
  sp_instr_set_trigger_field class functions
*/

2276 2277 2278 2279
int
sp_instr_set_trigger_field::execute(THD *thd, uint *nextp)
{
  DBUG_ENTER("sp_instr_set_trigger_field::execute");
2280 2281 2282 2283 2284 2285 2286 2287 2288 2289
  DBUG_RETURN(m_lex_keeper.reset_lex_and_exec_core(thd, nextp, TRUE, this));
}


int
sp_instr_set_trigger_field::exec_core(THD *thd, uint *nextp)
{
  int res= 0;
  Item *it= sp_prepare_func_item(thd, &value);
  if (!it ||
2290
      !trigger_field->fixed && trigger_field->fix_fields(thd, 0) ||
2291
      (it->save_in_field(trigger_field->field, 0) < 0))
2292
    res= -1;
2293 2294
  *nextp = m_ip+1;
  return res;
2295 2296 2297 2298 2299
}

void
sp_instr_set_trigger_field::print(String *str)
{
2300
  str->append(STRING_WITH_LEN("set_trigger_field "));
2301
  trigger_field->print(str);
2302
  str->append(STRING_WITH_LEN(":="));
2303 2304 2305
  value->print(str);
}

unknown's avatar
unknown committed
2306 2307 2308 2309 2310

/*
 sp_instr_jump class functions
*/

2311 2312 2313 2314 2315 2316 2317 2318 2319 2320
int
sp_instr_jump::execute(THD *thd, uint *nextp)
{
  DBUG_ENTER("sp_instr_jump::execute");
  DBUG_PRINT("info", ("destination: %u", m_dest));

  *nextp= m_dest;
  DBUG_RETURN(0);
}

2321 2322 2323
void
sp_instr_jump::print(String *str)
{
2324 2325
  /* jump dest */
  if (str->reserve(SP_INSTR_UINT_MAXLEN+5))
2326
    return;
2327
  str->qs_append(STRING_WITH_LEN("jump "));
2328 2329 2330
  str->qs_append(m_dest);
}

2331 2332 2333
uint
sp_instr_jump::opt_mark(sp_head *sp)
{
2334
  m_dest= opt_shortcut_jump(sp, this);
2335 2336
  if (m_dest != m_ip+1)		/* Jumping to following instruction? */
    marked= 1;
2337 2338 2339 2340 2341
  m_optdest= sp->get_instr(m_dest);
  return m_dest;
}

uint
2342
sp_instr_jump::opt_shortcut_jump(sp_head *sp, sp_instr *start)
2343 2344 2345 2346 2347 2348
{
  uint dest= m_dest;
  sp_instr *i;

  while ((i= sp->get_instr(dest)))
  {
2349
    uint ndest;
2350

2351
    if (start == i || this == i)
2352 2353
      break;
    ndest= i->opt_shortcut_jump(sp, start);
2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370
    if (ndest == dest)
      break;
    dest= ndest;
  }
  return dest;
}

void
sp_instr_jump::opt_move(uint dst, List<sp_instr> *bp)
{
  if (m_dest > m_ip)
    bp->push_back(this);	// Forward
  else if (m_optdest)
    m_dest= m_optdest->m_ip;	// Backward
  m_ip= dst;
}

unknown's avatar
unknown committed
2371 2372 2373 2374

/*
  sp_instr_jump_if class functions
*/
2375

2376 2377 2378
int
sp_instr_jump_if::execute(THD *thd, uint *nextp)
{
2379 2380
  DBUG_ENTER("sp_instr_jump_if::execute");
  DBUG_PRINT("info", ("destination: %u", m_dest));
2381 2382 2383 2384 2385 2386
  DBUG_RETURN(m_lex_keeper.reset_lex_and_exec_core(thd, nextp, TRUE, this));
}

int
sp_instr_jump_if::exec_core(THD *thd, uint *nextp)
{
2387 2388
  Item *it;
  int res;
2389

2390
  it= sp_prepare_func_item(thd, &m_expr);
2391 2392
  if (!it)
    res= -1;
2393
  else
2394 2395
  {
    res= 0;
2396
    if (it->val_bool())
2397 2398 2399 2400
      *nextp = m_dest;
    else
      *nextp = m_ip+1;
  }
2401 2402

  return res;
2403 2404
}

2405 2406 2407
void
sp_instr_jump_if::print(String *str)
{
2408 2409
  /* jump_if dest ... */
  if (str->reserve(SP_INSTR_UINT_MAXLEN+8+32)) // Add some for the expr. too
2410
    return;
2411
  str->qs_append(STRING_WITH_LEN("jump_if "));
2412
  str->qs_append(m_dest);
2413
  str->qs_append(' ');
2414 2415 2416
  m_expr->print(str);
}

2417 2418 2419 2420 2421 2422 2423 2424
uint
sp_instr_jump_if::opt_mark(sp_head *sp)
{
  sp_instr *i;

  marked= 1;
  if ((i= sp->get_instr(m_dest)))
  {
2425
    m_dest= i->opt_shortcut_jump(sp, this);
2426 2427 2428 2429 2430 2431
    m_optdest= sp->get_instr(m_dest);
  }
  sp->opt_mark(m_dest);
  return m_ip+1;
}

unknown's avatar
unknown committed
2432 2433 2434 2435 2436

/*
  sp_instr_jump_if_not class functions
*/

2437 2438 2439
int
sp_instr_jump_if_not::execute(THD *thd, uint *nextp)
{
2440 2441
  DBUG_ENTER("sp_instr_jump_if_not::execute");
  DBUG_PRINT("info", ("destination: %u", m_dest));
2442 2443 2444 2445 2446 2447 2448
  DBUG_RETURN(m_lex_keeper.reset_lex_and_exec_core(thd, nextp, TRUE, this));
}


int
sp_instr_jump_if_not::exec_core(THD *thd, uint *nextp)
{
2449 2450
  Item *it;
  int res;
2451

2452
  it= sp_prepare_func_item(thd, &m_expr);
2453 2454
  if (! it)
    res= -1;
2455
  else
2456 2457
  {
    res= 0;
2458
    if (! it->val_bool())
2459 2460 2461 2462
      *nextp = m_dest;
    else
      *nextp = m_ip+1;
  }
2463 2464

  return res;
2465
}
2466

unknown's avatar
unknown committed
2467

2468 2469 2470
void
sp_instr_jump_if_not::print(String *str)
{
2471 2472
  /* jump_if_not dest ... */
  if (str->reserve(SP_INSTR_UINT_MAXLEN+12+32)) // Add some for the expr. too
2473
    return;
2474
  str->qs_append(STRING_WITH_LEN("jump_if_not "));
2475
  str->qs_append(m_dest);
2476
  str->qs_append(' ');
2477 2478 2479
  m_expr->print(str);
}

unknown's avatar
unknown committed
2480

2481 2482 2483 2484 2485 2486 2487 2488
uint
sp_instr_jump_if_not::opt_mark(sp_head *sp)
{
  sp_instr *i;

  marked= 1;
  if ((i= sp->get_instr(m_dest)))
  {
2489
    m_dest= i->opt_shortcut_jump(sp, this);
2490 2491 2492 2493 2494 2495
    m_optdest= sp->get_instr(m_dest);
  }
  sp->opt_mark(m_dest);
  return m_ip+1;
}

unknown's avatar
unknown committed
2496 2497 2498 2499

/*
  sp_instr_freturn class functions
*/
2500

2501
int
2502
sp_instr_freturn::execute(THD *thd, uint *nextp)
2503
{
2504
  DBUG_ENTER("sp_instr_freturn::execute");
2505 2506 2507 2508 2509 2510 2511
  DBUG_RETURN(m_lex_keeper.reset_lex_and_exec_core(thd, nextp, TRUE, this));
}


int
sp_instr_freturn::exec_core(THD *thd, uint *nextp)
{
2512 2513
  Item *it;
  int res;
2514

2515
  it= sp_eval_func_item(thd, &m_value, m_type, NULL, TRUE);
2516 2517 2518 2519 2520 2521 2522
  if (! it)
    res= -1;
  else
  {
    res= 0;
    thd->spcont->set_result(it);
  }
2523
  *nextp= UINT_MAX;
2524 2525

  return res;
2526
}
2527

2528 2529 2530
void
sp_instr_freturn::print(String *str)
{
2531 2532
  /* freturn type expr... */
  if (str->reserve(UINT_MAX+8+32)) // Add some for the expr. too
2533
    return;
2534
  str->qs_append(STRING_WITH_LEN("freturn "));
2535
  str->qs_append((uint)m_type);
2536
  str->qs_append(' ');
2537 2538 2539
  m_value->print(str);
}

unknown's avatar
unknown committed
2540 2541 2542 2543
/*
  sp_instr_hpush_jump class functions
*/

2544 2545 2546 2547 2548 2549 2550 2551
int
sp_instr_hpush_jump::execute(THD *thd, uint *nextp)
{
  DBUG_ENTER("sp_instr_hpush_jump::execute");
  List_iterator_fast<sp_cond_type_t> li(m_cond);
  sp_cond_type_t *p;

  while ((p= li++))
2552
    thd->spcont->push_handler(p, m_ip+1, m_type, m_frame);
2553 2554 2555 2556 2557

  *nextp= m_dest;
  DBUG_RETURN(0);
}

2558 2559 2560
void
sp_instr_hpush_jump::print(String *str)
{
2561 2562
  /* hpush_jump dest fsize type */
  if (str->reserve(SP_INSTR_UINT_MAXLEN*2 + 21))
2563
    return;
2564
  str->qs_append(STRING_WITH_LEN("hpush_jump "));
2565
  str->qs_append(m_dest);
2566
  str->qs_append(' ');
2567
  str->qs_append(m_frame);
unknown's avatar
unknown committed
2568 2569 2570
  switch (m_type)
  {
  case SP_HANDLER_NONE:
2571
    str->qs_append(STRING_WITH_LEN(" NONE")); // This would be a bug
unknown's avatar
unknown committed
2572 2573
    break;
  case SP_HANDLER_EXIT:
2574
    str->qs_append(STRING_WITH_LEN(" EXIT"));
unknown's avatar
unknown committed
2575 2576
    break;
  case SP_HANDLER_CONTINUE:
2577
    str->qs_append(STRING_WITH_LEN(" CONTINUE"));
unknown's avatar
unknown committed
2578 2579
    break;
  case SP_HANDLER_UNDO:
2580
    str->qs_append(STRING_WITH_LEN(" UNDO"));
unknown's avatar
unknown committed
2581 2582
    break;
  default:
2583
    str->qs_append(STRING_WITH_LEN(" UNKNOWN:")); // This would be a bug as well
unknown's avatar
unknown committed
2584 2585
    str->qs_append(m_type);
  }
2586 2587
}

2588 2589 2590 2591 2592 2593 2594 2595
uint
sp_instr_hpush_jump::opt_mark(sp_head *sp)
{
  sp_instr *i;

  marked= 1;
  if ((i= sp->get_instr(m_dest)))
  {
2596
    m_dest= i->opt_shortcut_jump(sp, this);
2597 2598 2599 2600 2601 2602
    m_optdest= sp->get_instr(m_dest);
  }
  sp->opt_mark(m_dest);
  return m_ip+1;
}

unknown's avatar
unknown committed
2603 2604 2605 2606 2607

/*
  sp_instr_hpop class functions
*/

2608 2609 2610 2611 2612 2613 2614 2615 2616
int
sp_instr_hpop::execute(THD *thd, uint *nextp)
{
  DBUG_ENTER("sp_instr_hpop::execute");
  thd->spcont->pop_handlers(m_count);
  *nextp= m_ip+1;
  DBUG_RETURN(0);
}

2617 2618 2619
void
sp_instr_hpop::print(String *str)
{
2620 2621
  /* hpop count */
  if (str->reserve(SP_INSTR_UINT_MAXLEN+5))
2622
    return;
2623
  str->qs_append(STRING_WITH_LEN("hpop "));
2624 2625 2626
  str->qs_append(m_count);
}

2627 2628 2629 2630 2631 2632 2633
void
sp_instr_hpop::backpatch(uint dest, sp_pcontext *dst_ctx)
{
  m_count= m_ctx->diff_handlers(dst_ctx);
}


unknown's avatar
unknown committed
2634 2635 2636 2637
/*
  sp_instr_hreturn class functions
*/

2638 2639 2640 2641
int
sp_instr_hreturn::execute(THD *thd, uint *nextp)
{
  DBUG_ENTER("sp_instr_hreturn::execute");
2642 2643 2644 2645 2646 2647 2648
  if (m_dest)
    *nextp= m_dest;
  else
  {
    thd->spcont->restore_variables(m_frame);
    *nextp= thd->spcont->pop_hstack();
  }
2649
  thd->spcont->exit_handler();
2650 2651
  DBUG_RETURN(0);
}
2652

unknown's avatar
unknown committed
2653

2654 2655 2656
void
sp_instr_hreturn::print(String *str)
{
2657 2658
  /* hreturn framesize dest */
  if (str->reserve(SP_INSTR_UINT_MAXLEN*2 + 9))
2659
    return;
2660
  str->qs_append(STRING_WITH_LEN("hreturn "));
2661
  str->qs_append(m_frame);
2662
  if (m_dest)
2663
  {
2664
    str->qs_append(' ');
2665
    str->qs_append(m_dest);
2666
  }
2667 2668
}

unknown's avatar
unknown committed
2669

2670 2671 2672 2673 2674 2675 2676 2677 2678 2679
uint
sp_instr_hreturn::opt_mark(sp_head *sp)
{
  if (m_dest)
    return sp_instr_jump::opt_mark(sp);
  else
  {
    marked= 1;
    return UINT_MAX;
  }
2680 2681
}

2682

unknown's avatar
unknown committed
2683 2684 2685 2686
/*
  sp_instr_cpush class functions
*/

2687 2688 2689
int
sp_instr_cpush::execute(THD *thd, uint *nextp)
{
unknown's avatar
unknown committed
2690
  Query_arena backup_arena;
2691
  DBUG_ENTER("sp_instr_cpush::execute");
2692 2693 2694 2695 2696

  /*
    We should create cursors in the callers arena, as
    it could be (and usually is) used in several instructions.
  */
unknown's avatar
unknown committed
2697
  thd->set_n_backup_active_arena(thd->spcont->callers_arena, &backup_arena);
2698

2699
  thd->spcont->push_cursor(&m_lex_keeper, this);
2700

unknown's avatar
unknown committed
2701
  thd->restore_active_arena(thd->spcont->callers_arena, &backup_arena);
2702

2703
  *nextp= m_ip+1;
2704

2705 2706 2707
  DBUG_RETURN(0);
}

unknown's avatar
unknown committed
2708

2709 2710 2711
void
sp_instr_cpush::print(String *str)
{
unknown's avatar
unknown committed
2712 2713
  LEX_STRING n;
  my_bool found= m_ctx->find_cursor(m_cursor, &n);
2714 2715
  /* cpush name@offset */
  uint rsrv= SP_INSTR_UINT_MAXLEN+7;
unknown's avatar
unknown committed
2716

2717 2718 2719 2720
  if (found)
    rsrv+= n.length;
  if (str->reserve(rsrv))
    return;
2721
  str->qs_append(STRING_WITH_LEN("cpush "));
unknown's avatar
unknown committed
2722 2723
  if (found)
  {
2724 2725
    str->qs_append(n.str, n.length);
    str->qs_append('@');
unknown's avatar
unknown committed
2726 2727
  }
  str->qs_append(m_cursor);
2728 2729
}

unknown's avatar
unknown committed
2730 2731 2732 2733 2734

/*
  sp_instr_cpop class functions
*/

2735 2736 2737 2738 2739 2740 2741 2742 2743
int
sp_instr_cpop::execute(THD *thd, uint *nextp)
{
  DBUG_ENTER("sp_instr_cpop::execute");
  thd->spcont->pop_cursors(m_count);
  *nextp= m_ip+1;
  DBUG_RETURN(0);
}

unknown's avatar
unknown committed
2744

2745 2746 2747
void
sp_instr_cpop::print(String *str)
{
2748 2749
  /* cpop count */
  if (str->reserve(SP_INSTR_UINT_MAXLEN+5))
2750
    return;
2751
  str->qs_append(STRING_WITH_LEN("cpop "));
2752 2753 2754
  str->qs_append(m_count);
}

2755 2756 2757 2758 2759 2760
void
sp_instr_cpop::backpatch(uint dest, sp_pcontext *dst_ctx)
{
  m_count= m_ctx->diff_cursors(dst_ctx);
}

unknown's avatar
unknown committed
2761 2762 2763 2764 2765

/*
  sp_instr_copen class functions
*/

2766 2767 2768
int
sp_instr_copen::execute(THD *thd, uint *nextp)
{
2769 2770 2771 2772
  /*
    We don't store a pointer to the cursor in the instruction to be
    able to reuse the same instruction among different threads in future.
  */
2773 2774 2775 2776 2777 2778 2779 2780
  sp_cursor *c= thd->spcont->get_cursor(m_cursor);
  int res;
  DBUG_ENTER("sp_instr_copen::execute");

  if (! c)
    res= -1;
  else
  {
2781 2782
    sp_lex_keeper *lex_keeper= c->get_lex_keeper();
    Query_arena *old_arena= thd->stmt_arena;
2783

2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802
    /*
      Get the Query_arena from the cpush instruction, which contains
      the free_list of the query, so new items (if any) are stored in
      the right free_list, and we can cleanup after each open.
    */
    thd->stmt_arena= c->get_instr();
    res= lex_keeper->reset_lex_and_exec_core(thd, nextp, FALSE, this);
    /* Cleanup the query's items */
    if (thd->stmt_arena->free_list)
      cleanup_items(thd->stmt_arena->free_list);
    thd->stmt_arena= old_arena;
    /*
      Work around the fact that errors in selects are not returned properly
      (but instead converted into a warning), so if a condition handler
      caught, we have lost the result code.
    */
    if (!res)
    {
      uint dummy1, dummy2;
2803

2804 2805
      if (thd->spcont->found_handler(&dummy1, &dummy2))
        res= -1;
2806
    }
2807
    /* TODO: Assert here that we either have an error or a cursor */
2808 2809 2810 2811
  }
  DBUG_RETURN(res);
}

unknown's avatar
unknown committed
2812

2813 2814 2815
int
sp_instr_copen::exec_core(THD *thd, uint *nextp)
{
2816 2817
  sp_cursor *c= thd->spcont->get_cursor(m_cursor);
  int res= c->open(thd);
2818 2819 2820 2821
  *nextp= m_ip+1;
  return res;
}

2822 2823 2824
void
sp_instr_copen::print(String *str)
{
unknown's avatar
unknown committed
2825 2826
  LEX_STRING n;
  my_bool found= m_ctx->find_cursor(m_cursor, &n);
2827 2828
  /* copen name@offset */
  uint rsrv= SP_INSTR_UINT_MAXLEN+7;
unknown's avatar
unknown committed
2829

2830 2831 2832 2833
  if (found)
    rsrv+= n.length;
  if (str->reserve(rsrv))
    return;
2834
  str->qs_append(STRING_WITH_LEN("copen "));
unknown's avatar
unknown committed
2835 2836
  if (found)
  {
2837 2838
    str->qs_append(n.str, n.length);
    str->qs_append('@');
unknown's avatar
unknown committed
2839
  }
2840 2841 2842
  str->qs_append(m_cursor);
}

unknown's avatar
unknown committed
2843 2844 2845 2846 2847

/*
  sp_instr_cclose class functions
*/

2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862
int
sp_instr_cclose::execute(THD *thd, uint *nextp)
{
  sp_cursor *c= thd->spcont->get_cursor(m_cursor);
  int res;
  DBUG_ENTER("sp_instr_cclose::execute");

  if (! c)
    res= -1;
  else
    res= c->close(thd);
  *nextp= m_ip+1;
  DBUG_RETURN(res);
}

unknown's avatar
unknown committed
2863

2864 2865 2866
void
sp_instr_cclose::print(String *str)
{
unknown's avatar
unknown committed
2867 2868
  LEX_STRING n;
  my_bool found= m_ctx->find_cursor(m_cursor, &n);
2869 2870
  /* cclose name@offset */
  uint rsrv= SP_INSTR_UINT_MAXLEN+8;
unknown's avatar
unknown committed
2871

2872 2873 2874 2875
  if (found)
    rsrv+= n.length;
  if (str->reserve(rsrv))
    return;
2876
  str->qs_append(STRING_WITH_LEN("cclose "));
unknown's avatar
unknown committed
2877 2878
  if (found)
  {
2879 2880
    str->qs_append(n.str, n.length);
    str->qs_append('@');
unknown's avatar
unknown committed
2881
  }
2882 2883 2884
  str->qs_append(m_cursor);
}

unknown's avatar
unknown committed
2885 2886 2887 2888 2889

/*
  sp_instr_cfetch class functions
*/

2890 2891 2892 2893 2894
int
sp_instr_cfetch::execute(THD *thd, uint *nextp)
{
  sp_cursor *c= thd->spcont->get_cursor(m_cursor);
  int res;
unknown's avatar
unknown committed
2895
  Query_arena backup_arena;
2896 2897
  DBUG_ENTER("sp_instr_cfetch::execute");

2898
  res= c ? c->fetch(thd, &m_varlist) : -1;
2899

2900 2901 2902
  *nextp= m_ip+1;
  DBUG_RETURN(res);
}
2903

unknown's avatar
unknown committed
2904

2905 2906 2907 2908 2909
void
sp_instr_cfetch::print(String *str)
{
  List_iterator_fast<struct sp_pvar> li(m_varlist);
  sp_pvar_t *pv;
unknown's avatar
unknown committed
2910 2911
  LEX_STRING n;
  my_bool found= m_ctx->find_cursor(m_cursor, &n);
2912 2913
  /* cfetch name@offset vars... */
  uint rsrv= SP_INSTR_UINT_MAXLEN+8;
2914

2915 2916 2917 2918
  if (found)
    rsrv+= n.length;
  if (str->reserve(rsrv))
    return;
2919
  str->qs_append(STRING_WITH_LEN("cfetch "));
unknown's avatar
unknown committed
2920 2921
  if (found)
  {
2922 2923
    str->qs_append(n.str, n.length);
    str->qs_append('@');
unknown's avatar
unknown committed
2924
  }
2925 2926 2927
  str->qs_append(m_cursor);
  while ((pv= li++))
  {
2928
    if (str->reserve(pv->name.length+SP_INSTR_UINT_MAXLEN+2))
2929 2930 2931 2932
      return;
    str->qs_append(' ');
    str->qs_append(pv->name.str, pv->name.length);
    str->qs_append('@');
2933 2934 2935 2936
    str->qs_append(pv->offset);
  }
}

unknown's avatar
unknown committed
2937 2938 2939 2940 2941

/*
  sp_instr_error class functions
*/

2942 2943 2944 2945 2946
int
sp_instr_error::execute(THD *thd, uint *nextp)
{
  DBUG_ENTER("sp_instr_error::execute");

unknown's avatar
unknown committed
2947
  my_message(m_errcode, ER(m_errcode), MYF(0));
2948 2949 2950 2951
  *nextp= m_ip+1;
  DBUG_RETURN(-1);
}

unknown's avatar
unknown committed
2952

2953 2954 2955
void
sp_instr_error::print(String *str)
{
2956 2957
  /* error code */
  if (str->reserve(SP_INSTR_UINT_MAXLEN+6))
2958
    return;
2959
  str->qs_append(STRING_WITH_LEN("error "));
2960 2961 2962
  str->qs_append(m_errcode);
}

2963

unknown's avatar
unknown committed
2964
/* ------------------------------------------------------------------ */
2965

unknown's avatar
unknown committed
2966 2967 2968
/*
  Security context swapping
*/
2969

2970
#ifndef NO_EMBEDDED_ACCESS_CHECKS
2971
bool
2972
sp_change_security_context(THD *thd, sp_head *sp, Security_context **backup)
2973
{
2974
  *backup= 0;
2975 2976 2977 2978 2979
  if (sp->m_chistics->suid != SP_IS_NOT_SUID &&
      (strcmp(sp->m_definer_user.str,
              thd->security_ctx->priv_user) ||
       my_strcasecmp(system_charset_info, sp->m_definer_host.str,
                     thd->security_ctx->priv_host)))
2980
  {
2981 2982 2983 2984 2985
    if (acl_getroot_no_password(&sp->m_security_ctx, sp->m_definer_user.str,
                                sp->m_definer_host.str,
                                sp->m_definer_host.str,
                                sp->m_db.str))
    {
2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997
#ifdef NOT_YET_REPLICATION_SAFE
      /*
        Until we don't properly replicate information about stored routine
        definer with stored routine creation statement all stored routines
        on slave are created under ''@'' definer. Therefore we won't be able
        to run any routine which was replicated from master on slave server
        if we emit error here. This will cause big problems for users
        who use slave for fail-over. So until we fully implement WL#2897
        "Complete definer support in the stored routines" we run suid
        stored routines for which we were unable to find definer under
        invoker security context.
      */
2998 2999 3000
      my_error(ER_NO_SUCH_USER, MYF(0), sp->m_definer_user.str,
               sp->m_definer_host.str);
      return TRUE;
3001 3002 3003
#else
      return FALSE;
#endif
3004
    }
3005 3006
    *backup= thd->security_ctx;
    thd->security_ctx= &sp->m_security_ctx;
3007
  }
3008
  return FALSE;
3009 3010 3011
}

void
3012
sp_restore_security_context(THD *thd, Security_context *backup)
3013
{
3014 3015
  if (backup)
    thd->security_ctx= backup;
3016
}
3017 3018

#endif /* NO_EMBEDDED_ACCESS_CHECKS */
3019 3020

/*
3021 3022 3023 3024
  Structure that represent all instances of one table
  in optimized multi-set of tables used by routine.
*/

3025 3026
typedef struct st_sp_table
{
unknown's avatar
unknown committed
3027 3028 3029 3030
  LEX_STRING qname;     /* Multi-set key: db_name\0table_name\0alias\0 */
  uint db_length, table_name_length;
  bool temp;               /* true if corresponds to a temporary table */
  thr_lock_type lock_type; /* lock type used for prelocking */
3031 3032
  uint lock_count;
  uint query_lock_count;
3033 3034 3035 3036 3037 3038 3039 3040 3041 3042
} SP_TABLE;

byte *
sp_table_key(const byte *ptr, uint *plen, my_bool first)
{
  SP_TABLE *tab= (SP_TABLE *)ptr;
  *plen= tab->qname.length;
  return (byte *)tab->qname.str;
}

3043

3044
/*
3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063
  Merge the list of tables used by some query into the multi-set of
  tables used by routine.

  SYNOPSIS
    merge_table_list()
      thd               - thread context
      table             - table list
      lex_for_tmp_check - LEX of the query for which we are merging
                          table list.

  NOTE
    This method will use LEX provided to check whenever we are creating
    temporary table and mark it as such in target multi-set.

  RETURN VALUE
    TRUE  - Success
    FALSE - Error
*/

3064
bool
3065
sp_head::merge_table_list(THD *thd, TABLE_LIST *table, LEX *lex_for_tmp_check)
3066
{
3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078
  SP_TABLE *tab;

  if (lex_for_tmp_check->sql_command == SQLCOM_DROP_TABLE &&
      lex_for_tmp_check->drop_temporary)
    return TRUE;

  for (uint i= 0 ; i < m_sptabs.records ; i++)
  {
    tab= (SP_TABLE *)hash_element(&m_sptabs, i);
    tab->query_lock_count= 0;
  }

3079
  for (; table ; table= table->next_global)
3080
    if (!table->derived && !table->schema_table)
3081
    {
unknown's avatar
unknown committed
3082
      char tname[(NAME_LEN + 1) * 3];           // db\0table\0alias\0
3083 3084 3085 3086
      uint tlen, alen;

      tlen= table->db_length;
      memcpy(tname, table->db, tlen);
unknown's avatar
unknown committed
3087
      tname[tlen++]= '\0';
3088 3089
      memcpy(tname+tlen, table->table_name, table->table_name_length);
      tlen+= table->table_name_length;
unknown's avatar
unknown committed
3090
      tname[tlen++]= '\0';
3091 3092 3093 3094 3095
      alen= strlen(table->alias);
      memcpy(tname+tlen, table->alias, alen);
      tlen+= alen;
      tname[tlen]= '\0';

3096 3097 3098 3099 3100
      /*
        It is safe to store pointer to table list elements in hash,
        since they are supposed to have the same lifetime.
      */
      if ((tab= (SP_TABLE *)hash_search(&m_sptabs, (byte *)tname, tlen)))
3101
      {
3102 3103
        if (tab->lock_type < table->lock_type)
          tab->lock_type= table->lock_type; // Use the table with the highest lock type
3104 3105 3106
        tab->query_lock_count++;
        if (tab->query_lock_count > tab->lock_count)
          tab->lock_count++;
3107 3108 3109 3110 3111 3112
      }
      else
      {
	if (!(tab= (SP_TABLE *)thd->calloc(sizeof(SP_TABLE))))
	  return FALSE;
	tab->qname.length= tlen;
unknown's avatar
unknown committed
3113
	tab->qname.str= (char*) thd->memdup(tname, tab->qname.length + 1);
3114 3115
	if (!tab->qname.str)
	  return FALSE;
3116
	if (lex_for_tmp_check->sql_command == SQLCOM_CREATE_TABLE &&
3117 3118 3119
	    lex_for_tmp_check->query_tables == table &&
	    lex_for_tmp_check->create_info.options & HA_LEX_CREATE_TMP_TABLE)
	  tab->temp= TRUE;
unknown's avatar
unknown committed
3120 3121
        tab->table_name_length= table->table_name_length;
        tab->db_length= table->db_length;
3122
        tab->lock_type= table->lock_type;
3123 3124
        tab->lock_count= tab->query_lock_count= 1;
	my_hash_insert(&m_sptabs, (byte *)tab);
3125 3126 3127 3128 3129 3130
      }
    }
  return TRUE;
}


3131 3132
/*
  Add tables used by routine to the table list.
3133

3134 3135
  SYNOPSIS
    add_used_tables_to_table_list()
3136 3137 3138 3139 3140 3141
      thd                    [in]     Thread context
      query_tables_last_ptr  [in/out] Pointer to the next_global member of
                                      last element of the list where tables
                                      will be added (or to its root).
      belong_to_view         [in]     Uppermost view which uses this routine,
                                      0 if none.
3142

3143 3144 3145
  DESCRIPTION
    Converts multi-set of tables used by this routine to table list and adds
    this list to the end of table list specified by 'query_tables_last_ptr'.
3146

3147 3148
    Elements of list will be allocated in PS memroot, so this list will be
    persistent between PS executions.
3149

3150 3151 3152
  RETURN VALUE
    TRUE - if some elements were added, FALSE - otherwise.
*/
3153

3154 3155
bool
sp_head::add_used_tables_to_table_list(THD *thd,
3156 3157
                                       TABLE_LIST ***query_tables_last_ptr,
                                       TABLE_LIST *belong_to_view)
3158 3159
{
  uint i;
unknown's avatar
unknown committed
3160
  Query_arena *arena, backup;
3161 3162 3163 3164
  bool result= FALSE;
  DBUG_ENTER("sp_head::add_used_tables_to_table_list");

  /*
3165 3166 3167 3168 3169 3170
    Use persistent arena for table list allocation to be PS/SP friendly.
    Note that we also have to copy database/table names and alias to PS/SP
    memory since current instance of sp_head object can pass away before
    next execution of PS/SP for which tables are added to prelocking list.
    This will be fixed by introducing of proper invalidation mechanism
    once new TDC is ready.
3171
  */
unknown's avatar
unknown committed
3172
  arena= thd->activate_stmt_arena_if_needed(&backup);
3173

3174
  for (i=0 ; i < m_sptabs.records ; i++)
3175
  {
3176
    char *tab_buff, *key_buff;
unknown's avatar
unknown committed
3177
    TABLE_LIST *table;
3178
    SP_TABLE *stab= (SP_TABLE *)hash_element(&m_sptabs, i);
3179 3180 3181
    if (stab->temp)
      continue;

3182
    if (!(tab_buff= (char *)thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST)) *
3183 3184 3185
                                        stab->lock_count)) ||
        !(key_buff= (char*)thd->memdup(stab->qname.str,
                                       stab->qname.length + 1)))
3186
      DBUG_RETURN(FALSE);
3187

3188 3189 3190 3191
    for (uint j= 0; j < stab->lock_count; j++)
    {
      table= (TABLE_LIST *)tab_buff;

3192
      table->db= key_buff;
unknown's avatar
unknown committed
3193 3194 3195 3196
      table->db_length= stab->db_length;
      table->table_name= table->db + table->db_length + 1;
      table->table_name_length= stab->table_name_length;
      table->alias= table->table_name + table->table_name_length + 1;
3197
      table->lock_type= stab->lock_type;
3198 3199
      table->cacheable_table= 1;
      table->prelocking_placeholder= 1;
3200
      table->belong_to_view= belong_to_view;
3201 3202 3203 3204 3205 3206 3207 3208 3209 3210

      /* Everyting else should be zeroed */

      **query_tables_last_ptr= table;
      table->prev_global= *query_tables_last_ptr;
      *query_tables_last_ptr= &table->next_global;

      tab_buff+= ALIGN_SIZE(sizeof(TABLE_LIST));
      result= TRUE;
    }
3211
  }
3212 3213

  if (arena)
unknown's avatar
unknown committed
3214
    thd->restore_active_arena(arena, &backup);
3215 3216

  DBUG_RETURN(result);
3217 3218
}

unknown's avatar
unknown committed
3219

3220
/*
unknown's avatar
unknown committed
3221 3222 3223 3224
  Simple function for adding an explicetly named (systems) table to
  the global table list, e.g. "mysql", "proc".
*/

3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248
TABLE_LIST *
sp_add_to_query_tables(THD *thd, LEX *lex,
		       const char *db, const char *name,
		       thr_lock_type locktype)
{
  TABLE_LIST *table;

  if (!(table= (TABLE_LIST *)thd->calloc(sizeof(TABLE_LIST))))
  {
    my_error(ER_OUTOFMEMORY, MYF(0), sizeof(TABLE_LIST));
    return NULL;
  }
  table->db_length= strlen(db);
  table->db= thd->strmake(db, table->db_length);
  table->table_name_length= strlen(name);
  table->table_name= thd->strmake(name, table->table_name_length);
  table->alias= thd->strdup(name);
  table->lock_type= locktype;
  table->select_lex= lex->current_select; // QQ?
  table->cacheable_table= 1;
  
  lex->add_to_query_tables(table);
  return table;
}
3249