sp_head.cc 56.3 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:
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
/*
 * Returns TRUE if the 'cmd' is a command that might result in
 * multiple result sets being sent back.
 * Note: This does not include SQLCOM_SELECT which is treated
 *       separately in sql_yacc.yy.
 */
bool
sp_multi_results_command(enum enum_sql_command cmd)
{
  switch (cmd) {
  case SQLCOM_ANALYZE:
60
  case SQLCOM_CHECKSUM:
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
  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:
79
  case SQLCOM_SHOW_MUTEX_STATUS:
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
  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:
    return TRUE;
  default:
    return FALSE;
  }
}

99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128

/*
  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);

  if (!it->fixed && (*it_addr)->fix_fields(thd, 0, it_addr))
  {
    DBUG_PRINT("info", ("fix_fields() failed"));
    DBUG_RETURN(NULL);
  }
  DBUG_RETURN(*it_addr);
}


129 130 131
/* Evaluate a (presumed) func item. Always returns an item, the parameter
** if nothing else.
*/
132
Item *
133 134
sp_eval_func_item(THD *thd, Item **it_addr, enum enum_field_types type,
		  Item *reuse)
135
{
136
  DBUG_ENTER("sp_eval_func_item");
137
  Item *it= sp_prepare_func_item(thd, it_addr);
138
  uint rsize;
139
  DBUG_PRINT("info", ("type: %d", type));
140

141
  if (!it)
142
  {
143
    DBUG_RETURN(NULL);
144
  }
145

146
  /* QQ How do we do this? Is there some better way? */
147
  if (type == MYSQL_TYPE_NULL)
148
    it= new(reuse, &rsize) Item_null();
149
  else
150
  {
151 152
    switch (sp_map_result_type(type)) {
    case INT_RESULT:
153 154 155 156
      {
	longlong i= it->val_int();

	if (it->null_value)
157 158
	{
	  DBUG_PRINT("info", ("INT_RESULT: null"));
159
	  it= new(reuse, &rsize) Item_null();
160
	}
161
	else
162 163
	{
	  DBUG_PRINT("info", ("INT_RESULT: %d", i));
164
          it= new(reuse, &rsize) Item_int(i);
165
	}
166 167
	break;
      }
168
    case REAL_RESULT:
169
      {
170
	double d= it->val_real();
171 172

	if (it->null_value)
173 174
	{
	  DBUG_PRINT("info", ("REAL_RESULT: null"));
175
	  it= new(reuse, &rsize) Item_null();
176
	}
177
	else
178
	{
179 180 181 182
	  /* There's some difference between Item::new_item() and the
	   * constructor; the former crashes, the latter works... weird. */
	  uint8 decimals= it->decimals;
	  uint32 max_length= it->max_length;
183
	  DBUG_PRINT("info", ("REAL_RESULT: %g", d));
184
          it= new(reuse, &rsize) Item_float(d);
185 186
	  it->decimals= decimals;
	  it->max_length= max_length;
187
	}
188 189
	break;
      }
190 191
    case DECIMAL_RESULT:
      {
192
        my_decimal value, *val= it->val_decimal(&value);
193
        if (it->null_value)
194
          it= new(reuse, &rsize) Item_null();
195
        else
196
          it= new(reuse, &rsize) Item_decimal(val);
197 198 199 200
#ifndef DBUG_OFF
        char dbug_buff[DECIMAL_MAX_STR_LENGTH+1];
        DBUG_PRINT("info", ("DECIMAL_RESULT: %s", dbug_decimal_as_string(dbug_buff, val)));
#endif
201 202 203
        break;
      }
    case STRING_RESULT:
204 205
      {
	char buffer[MAX_FIELD_WIDTH];
pem@mysql.telia.com's avatar
pem@mysql.telia.com committed
206
	String tmp(buffer, sizeof(buffer), it->collation.collation);
207 208
	String *s= it->val_str(&tmp);

209
	if (it->null_value)
210 211
	{
	  DBUG_PRINT("info", ("default result: null"));
212
	  it= new(reuse, &rsize) Item_null();
213
	}
214
	else
215
	{
216 217
	  DBUG_PRINT("info",("default result: %*s",
                             s->length(), s->c_ptr_quick()));
218 219 220 221
	  it= new(reuse, &rsize) Item_string(thd->strmake(s->ptr(),
							  s->length()),
					     s->length(),
					     it->collation.collation);
222
	}
223 224
	break;
      }
225 226 227
    case ROW_RESULT:
    default:
      DBUG_ASSERT(0);
228 229
    }
  }
230
  it->rsize= rsize;
231

232
  DBUG_RETURN(it);
233 234
}

235 236 237 238 239 240 241 242 243 244

/*
 *
 *  sp_name
 *
 */

void
sp_name::init_qname(THD *thd)
{
245 246 247 248 249
  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;
250 251 252 253 254
  sprintf(m_qname.str, "%*s.%*s",
	  m_db.length, (m_db.length ? m_db.str : ""),
	  m_name.length, m_name.str);
}

255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
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;
}


275 276 277 278 279 280 281 282 283
/* ------------------------------------------------------------------ */


/*
 *
 *  sp_head
 *
 */

284 285 286 287 288 289 290 291
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);
monty@mysql.com's avatar
monty@mysql.com committed
292 293
  sp= (sp_head *) alloc_root(&own_root, size);
  sp->main_mem_root= own_root;
294
  DBUG_PRINT("info", ("mem_root 0x%lx", (ulong) &sp->mem_root));
295 296 297 298 299 300 301 302
  DBUG_RETURN(sp);
}

void 
sp_head::operator delete(void *ptr, size_t size)
{
  DBUG_ENTER("sp_head::operator delete");
  MEM_ROOT own_root;
monty@mysql.com's avatar
monty@mysql.com committed
303
  sp_head *sp= (sp_head *) ptr;
304

monty@mysql.com's avatar
monty@mysql.com committed
305 306
  /* Make a copy of main_mem_root as free_root will free the sp */
  own_root= sp->main_mem_root;
307 308
  DBUG_PRINT("info", ("mem_root 0x%lx moved to 0x%lx",
                      (ulong) &sp->mem_root, (ulong) &own_root));
309 310 311 312 313
  free_root(&own_root, MYF(0));

  DBUG_VOID_RETURN;
}

314

315
sp_head::sp_head()
316
  :Item_arena((bool)FALSE), m_returns_cs(NULL), m_has_return(FALSE),
317
   m_simple_case(FALSE), m_multi_results(FALSE), m_in_handler(FALSE)
318
{
319 320
  extern byte *
    sp_table_key(const byte *ptr, uint *plen, my_bool first);
321
  DBUG_ENTER("sp_head::sp_head");
322

323
  state= INITIALIZED_FOR_SP;
324 325
  m_backpatch.empty();
  m_lex.empty();
326
  hash_init(&m_sptabs, system_charset_info, 0, 0, 0, sp_table_key, 0, 0);
327
  hash_init(&m_sroutines, system_charset_info, 0, 0, 0, sp_sroutine_key, 0, 0);
328 329 330
  DBUG_VOID_RETURN;
}

331

332
void
333
sp_head::init(LEX *lex)
334 335
{
  DBUG_ENTER("sp_head::init");
336

337
  lex->spcont= m_pcont= new sp_pcontext(NULL);
338 339 340 341 342
  /*
    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();
343
  my_init_dynamic_array(&m_instr, sizeof(sp_instr *), 16, 8);
344 345
  m_param_begin= m_param_end= m_body_begin= 0;
  m_qname.str= m_db.str= m_name.str= m_params.str= 
346 347
    m_body.str= m_defstr.str= 0;
  m_qname.length= m_db.length= m_name.length= m_params.length=
348
    m_body.length= m_defstr.length= 0;
349
  m_returns_cs= NULL;
350 351 352 353
  DBUG_VOID_RETURN;
}

void
354
sp_head::init_strings(THD *thd, LEX *lex, sp_name *name)
355 356
{
  DBUG_ENTER("sp_head::init_strings");
357
  uint n;			/* Counter for nul trimming */ 
358
  /* During parsing, we must use thd->mem_root */
monty@mysql.com's avatar
monty@mysql.com committed
359
  MEM_ROOT *root= thd->mem_root;
360

361
  /* We have to copy strings to get them into the right memroot */
362 363
  if (name)
  {
364
    m_db.length= name->m_db.length;
365
    if (name->m_db.length == 0)
366
      m_db.str= NULL;
367 368 369 370 371 372 373 374 375 376
    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);
  }
377
  else if (thd->db)
378
  {
379
    m_db.length= thd->db_length;
380
    m_db.str= strmake_root(root, thd->db, m_db.length);
381
  }
382

383
  if (m_param_begin && m_param_end)
384
  {
385 386 387
    m_params.length= m_param_end - m_param_begin;
    m_params.str= strmake_root(root,
                               (char *)m_param_begin, m_params.length);
388
  }
389

390 391 392 393 394 395 396 397
  m_body.length= lex->ptr - m_body_begin;
  /* Trim nuls at the end */
  n= 0;
  while (m_body.length && m_body_begin[m_body.length-1] == '\0')
  {
    m_body.length-= 1;
    n+= 1;
  }
398
  m_body.str= strmake_root(root, (char *)m_body_begin, m_body.length);
399 400
  m_defstr.length= lex->ptr - lex->buf;
  m_defstr.length-= n;
401
  m_defstr.str= strmake_root(root, (char *)lex->buf, m_defstr.length);
402
  DBUG_VOID_RETURN;
403 404
}

405 406 407 408
TYPELIB *
sp_head::create_typelib(List<String> *src)
{
  TYPELIB *result= NULL;
409
  CHARSET_INFO *cs= m_returns_cs;
410 411 412 413 414 415 416
  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 **)
417
          alloc_root(mem_root,(sizeof(char *)+sizeof(int))*(result->count+1))))
418
      return 0;
419
    result->type_lengths= (unsigned int *)(result->type_names + result->count+1);
420
    List_iterator<String> it(*src);
421 422
    String conv;
    for (uint i=0; i < result->count; i++)
423
    {
424 425 426 427
      uint32 dummy;
      uint length;
      String *tmp= it++;

428 429 430 431 432
      if (String::needs_conversion(tmp->length(), tmp->charset(),
      				   cs, &dummy))
      {
        uint cnv_errs;
        conv.copy(tmp->ptr(), tmp->length(), tmp->charset(), cs, &cnv_errs);
433 434 435 436

        length= conv.length();
        result->type_names[i]= (char*) strmake_root(mem_root, conv.ptr(),
                                                    length);
437
      }
438 439 440 441
      else
      {
        length= tmp->length();
        result->type_names[i]= strmake_root(mem_root, tmp->ptr(), length);
442
      }
443 444

      // Strip trailing spaces.
445 446 447
      length= cs->cset->lengthsp(cs, result->type_names[i], length);
      result->type_lengths[i]= length;
      ((uchar *)result->type_names[i])[length]= '\0';
448
    }
449
    result->type_names[result->count]= 0;
450
    result->type_lengths[result->count]= 0;
451 452 453 454
  }
  return result;
}

455 456 457
int
sp_head::create(THD *thd)
{
458
  DBUG_ENTER("sp_head::create");
459 460
  int ret;

461 462
  DBUG_PRINT("info", ("type: %d name: %s params: %s body: %s",
		      m_type, m_name.str, m_params.str, m_body.str));
463

464
#ifndef DBUG_OFF
465
  optimize();
466
  {
467 468 469 470 471 472
    String s;
    sp_instr *i;
    uint ip= 0;
    while ((i = get_instr(ip)))
    {
      char buf[8];
473

474 475 476 477 478 479 480 481
      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()));
482 483 484
  }
#endif

485
  if (m_type == TYPE_ENUM_FUNCTION)
486
    ret= sp_create_function(thd, this);
487
  else
488
    ret= sp_create_procedure(thd, this);
489

490
  DBUG_RETURN(ret);
491 492
}

493 494 495 496 497 498 499
sp_head::~sp_head()
{
  destroy();
  if (m_thd)
    restore_thd_mem_root(m_thd);
}

500 501 502
void
sp_head::destroy()
{
503 504
  sp_instr *i;
  LEX *lex;
505 506
  DBUG_ENTER("sp_head::destroy");
  DBUG_PRINT("info", ("name: %s", m_name.str));
507 508 509

  for (uint ip = 0 ; (i = get_instr(ip)) ; ip++)
    delete i;
510 511
  delete_dynamic(&m_instr);
  m_pcont->destroy();
512
  free_items(free_list);
513 514 515 516 517 518 519 520 521 522

  /*
    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);
523 524
  while ((lex= (LEX *)m_lex.pop()))
  {
525 526
    delete m_thd->lex;
    m_thd->lex= lex;
527
  }
528

529
  hash_free(&m_sptabs);
530
  hash_free(&m_sroutines);
531
  DBUG_VOID_RETURN;
532
}
533

534

535 536 537 538 539 540 541 542
/*
 *  This is only used for result fields from functions (both during
 *  fix_length_and_dec() and evaluation).
 *
 *  Since the current mem_root during a will be freed and the result
 *  field will be used by the caller, we have to put it in the caller's
 *  or main mem_root.
 */
543 544 545 546
Field *
sp_head::make_field(uint max_length, const char *name, TABLE *dummy)
{
  Field *field;
547 548
  MEM_ROOT *tmp_mem_root;
  THD *thd;
549
  DBUG_ENTER("sp_head::make_field");
550 551 552 553 554 555 556

  thd= current_thd;
  tmp_mem_root= thd->mem_root;
  if (thd->spcont && thd->spcont->callers_mem_root)
    thd->mem_root= thd->spcont->callers_mem_root;
  else
    thd->mem_root= &thd->main_mem_root;
557 558 559 560 561 562
  field= ::make_field((char *)0,
		!m_returns_len ? max_length : m_returns_len, 
		(uchar *)"", 0, m_returns_pack, m_returns, m_returns_cs,
		(enum Field::geometry_type)0, Field::NONE, 
		m_returns_typelib,
		name ? name : (const char *)m_name.str, dummy);
563
  thd->mem_root= tmp_mem_root;
564 565 566
  DBUG_RETURN(field);
}

567 568 569
int
sp_head::execute(THD *thd)
{
570
  DBUG_ENTER("sp_head::execute");
571
  char olddb[128];
572
  bool dbchanged;
573
  sp_rcontext *ctx;
574
  int ret= 0;
575
  uint ip= 0;
576
  Item_arena *old_arena;
577
  query_id_t old_query_id;
578 579 580 581
  TABLE *old_derived_tables;
  LEX *old_lex;
  Item_change_list old_change_list;
  String old_packet;
582

583
  /* Use some extra margin for possible SP recursion and functions */
584
  if (check_stack_overrun(thd, 4*STACK_MIN_SIZE, olddb))
585 586 587
  {
    DBUG_RETURN(-1);
  }
588

589
  dbchanged= FALSE;
590 591
  if (m_db.length &&
      (ret= sp_use_new_db(thd, m_db.str, olddb, sizeof(olddb), 0, &dbchanged)))
592
    goto done;
593

594
  if ((ctx= thd->spcont))
595
    ctx->clear_handler();
596
  thd->query_error= 0;
597
  old_arena= thd->current_arena;
598
  thd->current_arena= this;
599

600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
  /*
    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;
  /*
    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);

628 629 630
  do
  {
    sp_instr *i;
631
    uint hip;			// Handler ip
632 633 634 635 636

    i = get_instr(ip);	// Returns NULL when we're done.
    if (i == NULL)
      break;
    DBUG_PRINT("execute", ("Instruction %u", ip));
637
    thd->set_time();		// Make current_time() et al work
638
    ret= i->execute(thd, &ip);
639 640
    if (i->free_list)
      cleanup_items(i->free_list);
641
    // Check if an exception has occurred and a handler has been found
642 643
    // Note: We havo to check even if ret==0, since warnings (and some
    //       errors don't return a non-zero value.
644 645 646 647
    //       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").
    if (ctx)
648 649 650 651 652 653 654 655 656 657
    {
      uint hf;

      switch (ctx->found_handler(&hip, &hf))
      {
      case SP_HANDLER_NONE:
	break;
      case SP_HANDLER_CONTINUE:
	ctx->save_variables(hf);
	ctx->push_hstack(ip);
658
        // Fall through
659 660 661 662
      default:
	ip= hip;
	ret= 0;
	ctx->clear_handler();
663
	ctx->in_handler= TRUE;
664
        thd->clear_error();
665
	thd->killed= THD::NOT_KILLED;
666 667 668
	continue;
      }
    }
669
  } while (ret == 0 && !thd->killed);
670

671 672 673 674 675 676 677 678 679 680 681
  /* 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;

682
  cleanup_items(thd->current_arena->free_list);
683 684
  thd->current_arena= old_arena;

685
 done:
686 687
  DBUG_PRINT("info", ("ret=%d killed=%d query_error=%d",
		      ret, thd->killed, thd->query_error));
688

689
  if (thd->killed)
690
    ret= -1;
691 692
  /* If the DB has changed, the pointer has changed too, but the
     original thd->db will then have been freed */
693
  if (dbchanged)
694
  {
695
    if (! thd->killed)
696
      ret= sp_change_db(thd, olddb, 0);
697
  }
698 699 700 701 702 703 704
  DBUG_RETURN(ret);
}


int
sp_head::execute_function(THD *thd, Item **argp, uint argcount, Item **resp)
{
705
  DBUG_ENTER("sp_head::execute_function");
706
  DBUG_PRINT("info", ("function %s", m_name.str));
707 708 709 710
  uint csize = m_pcont->max_pvars();
  uint params = m_pcont->current_pvars();
  uint hmax = m_pcont->max_handlers();
  uint cmax = m_pcont->max_cursors();
711 712 713 714
  sp_rcontext *octx = thd->spcont;
  sp_rcontext *nctx = NULL;
  uint i;
  int ret;
715 716
  MEM_ROOT *old_mem_root, call_mem_root;
  Item *old_free_list, *call_free_list;
717

718 719 720 721
  if (argcount != params)
  {
    // Need to use my_printf_error here, or it will not terminate the
    // invoking query properly.
722
    my_error(ER_SP_WRONG_NO_OF_ARGS, MYF(0),
723
             "FUNCTION", m_qname.str, params, argcount);
724 725 726
    DBUG_RETURN(-1);
  }

727
  init_alloc_root(&call_mem_root, MEM_ROOT_BLOCK_SIZE, 0);
728 729 730 731 732
  old_mem_root= thd->mem_root;
  thd->mem_root= &call_mem_root;
  old_free_list= thd->free_list; // Keep the old list
  thd->free_list= NULL;	// Start a new one

733
  // QQ Should have some error checking here? (types, etc...)
734
  nctx= new sp_rcontext(csize, hmax, cmax);
735 736
  nctx->callers_mem_root= old_mem_root;
  for (i= 0 ; i < argcount ; i++)
737
  {
738
    sp_pvar_t *pvar = m_pcont->find_pvar(i);
739
    Item *it= sp_eval_func_item(thd, argp++, pvar->type, NULL);
740

741 742 743 744 745 746
    if (it)
      nctx->push_item(it);
    else
    {
      DBUG_RETURN(-1);
    }
747 748
  }
  // The rest of the frame are local variables which are all IN.
749 750 751 752 753 754 755 756 757 758 759
  // Default all variables to null (those with default clauses will
  // be set by an set instruction).
  {
    Item_null *nit= NULL;	// Re-use this, and only create if needed
    for (; i < csize ; i++)
    {
      if (! nit)
	nit= new Item_null();
      nctx->push_item(nit);
    }
  }
760 761 762
  thd->spcont= nctx;

  ret= execute(thd);
763

764 765 766 767 768 769 770
  // Partially restore context now.
  // We still need the call mem root and free list for processing
  // of the result.
  call_free_list= thd->free_list;
  thd->free_list= old_free_list;
  thd->mem_root= old_mem_root;

771
  if (m_type == TYPE_ENUM_FUNCTION && ret == 0)
772
  {
773
    /* We need result only in function but not in trigger */
774 775 776
    Item *it= nctx->get_result();

    if (it)
777
      *resp= sp_eval_func_item(thd, &it, m_returns, NULL);
778 779
    else
    {
780
      my_error(ER_SP_NORETURNEND, MYF(0), m_name.str);
781 782 783
      ret= -1;
    }
  }
784

785
  nctx->pop_all_cursors();	// To avoid memory leaks after an error
786
  thd->spcont= octx;
787 788 789 790 791 792

  // Now get rid of the rest of the callee context
  cleanup_items(call_free_list);
  free_items(call_free_list);
  free_root(&call_mem_root, MYF(0));

793 794 795
  DBUG_RETURN(ret);
}

796 797 798 799 800 801 802 803 804 805 806 807 808
static Item_func_get_user_var *
item_is_user_var(Item *it)
{
  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;
}

809 810 811
int
sp_head::execute_procedure(THD *thd, List<Item> *args)
{
812
  DBUG_ENTER("sp_head::execute_procedure");
813
  DBUG_PRINT("info", ("procedure %s", m_name.str));
814
  int ret= 0;
815 816 817 818
  uint csize = m_pcont->max_pvars();
  uint params = m_pcont->current_pvars();
  uint hmax = m_pcont->max_handlers();
  uint cmax = m_pcont->max_cursors();
819 820
  sp_rcontext *octx = thd->spcont;
  sp_rcontext *nctx = NULL;
821
  my_bool tmp_octx = FALSE;	// True if we have allocated a temporary octx
822 823
  MEM_ROOT *old_mem_root, call_mem_root;
  Item *old_free_list, *call_free_list;
824

825 826
  if (args->elements != params)
  {
827
    my_error(ER_SP_WRONG_NO_OF_ARGS, MYF(0), "PROCEDURE",
828
             m_qname.str, params, args->elements);
829 830 831
    DBUG_RETURN(-1);
  }

832
  init_alloc_root(&call_mem_root, MEM_ROOT_BLOCK_SIZE, 0);
833 834 835 836 837
  old_mem_root= thd->mem_root;
  thd->mem_root= &call_mem_root;
  old_free_list= thd->free_list; // Keep the old list
  thd->free_list= NULL;	// Start a new one

838
  if (csize > 0 || hmax > 0 || cmax > 0)
839
  {
840
    Item_null *nit= NULL;	// Re-use this, and only create if needed
841
    uint i;
842
    List_iterator<Item> li(*args);
843
    Item *it;
844

845
    nctx= new sp_rcontext(csize, hmax, cmax);
846 847
    if (! octx)
    {				// Create a temporary old context
848 849
      octx= new sp_rcontext(csize, hmax, cmax);
      tmp_octx= TRUE;
850
    }
851
    // QQ: Should do type checking?
852 853
    for (i = 0 ; (it= li++) && i < params ; i++)
    {
854
      sp_pvar_t *pvar= m_pcont->find_pvar(i);
855

856
      if (pvar)
857
      {
858 859 860 861 862 863 864 865 866
	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;
	  }
	}
867
	if (pvar->mode == sp_param_out)
868 869 870 871 872
	{
	  if (! nit)
	    nit= new Item_null();
	  nctx->push_item(nit); // OUT
	}
873
	else
874
	{
875
	  Item *it2= sp_eval_func_item(thd, li.ref(), pvar->type, NULL);
876 877 878 879 880 881 882 883 884

	  if (it2)
	    nctx->push_item(it2); // IN or INOUT
	  else
	  {
	    ret= -1;		// Eval failed
	    break;
	  }
	}
885
      }
886
    }
887

888
    // The rest of the frame are local variables which are all IN.
889 890
    // Default all variables to null (those with default clauses will
    // be set by an set instruction).
891
    for (; i < csize ; i++)
892
    {
893 894 895
      if (! nit)
	nit= new Item_null();
      nctx->push_item(nit);
896
    }
897 898 899
    thd->spcont= nctx;
  }

900 901
  if (! ret)
    ret= execute(thd);
902

903 904 905 906 907 908 909
  // Partially restore context now.
  // We still need the call mem root and free list for processing
  // of out parameters.
  call_free_list= thd->free_list;
  thd->free_list= old_free_list;
  thd->mem_root= old_mem_root;

910
  if (!ret && csize > 0)
911
  {
912
    List_iterator<Item> li(*args);
913
    Item *it;
914 915 916 917

    // Copy back all OUT or INOUT values to the previous frame, or
    // set global user variables
    for (uint i = 0 ; (it= li++) && i < params ; i++)
918
    {
919
      sp_pvar_t *pvar= m_pcont->find_pvar(i);
920

921
      if (pvar->mode != sp_param_in)
922
      {
923
	if (it->is_splocal())
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
	{
	  // 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);
	  Item *o_item_next;
	  Item *o_free_list= thd->free_list;
	  LINT_INIT(o_item_next);

	  if (orig)
	    o_item_next= orig->next;
	  copy= sp_eval_func_item(thd, &val, pvar->type, orig); // Copy
	  if (!copy)
	  {
	    ret= -1;
	    break;
	  }
	  if (copy != orig)
	    octx->set_item(offset, copy);
	  if (orig && copy == orig)
	  {
	    // A reused item slot, where the constructor put it in the
	    // free_list, so we have to restore the list.
	    thd->free_list= o_free_list;
	    copy->next= o_item_next;
	  }
	}
952
	else
953
	{
954 955 956
	  Item_func_get_user_var *guv= item_is_user_var(it);

	  if (guv)
957
	  {
958 959 960 961 962 963 964 965 966 967 968 969
	    Item *item= nctx->get_item(i);
	    Item_func_set_user_var *suv;

	    suv= new Item_func_set_user_var(guv->get_name(), item);
	    /*
	      we do not check suv->fixed, because it can't be fixed after
	      creation
	    */
	    suv->fix_fields(thd, NULL, &item);
	    suv->fix_length_and_dec();
	    suv->check();
	    suv->update();
970
	  }
971 972
	}
      }
973 974 975
    }
  }

976 977 978 979 980 981
  if (tmp_octx)
    octx= NULL;
  if (nctx)
    nctx->pop_all_cursors();	// To avoid memory leaks after an error
  thd->spcont= octx;

982 983 984
  // Now get rid of the rest of the callee context
  cleanup_items(call_free_list);
  free_items(call_free_list);
985
  thd->lex->unit.cleanup();
986 987
  free_root(&call_mem_root, MYF(0));

988
  DBUG_RETURN(ret);
989 990 991
}


992
// Reset lex during parsing, before we parse a sub statement.
993 994 995
void
sp_head::reset_lex(THD *thd)
{
996 997
  DBUG_ENTER("sp_head::reset_lex");
  LEX *sublex;
998
  LEX *oldlex= thd->lex;
999

1000
  (void)m_lex.push_front(oldlex);
1001
  thd->lex= sublex= new st_lex;
serg@serg.mylan's avatar
serg@serg.mylan committed
1002

1003
  /* Reset most stuff. The length arguments doesn't matter here. */
monty@mysql.com's avatar
monty@mysql.com committed
1004
  lex_start(thd, oldlex->buf, (ulong) (oldlex->end_of_query - oldlex->ptr));
serg@serg.mylan's avatar
serg@serg.mylan committed
1005

1006
  /* We must reset ptr and end_of_query again */
1007 1008 1009
  sublex->ptr= oldlex->ptr;
  sublex->end_of_query= oldlex->end_of_query;
  sublex->tok_start= oldlex->tok_start;
serg@serg.mylan's avatar
serg@serg.mylan committed
1010
  sublex->yylineno= oldlex->yylineno;
1011
  /* And keep the SP stuff too */
1012 1013
  sublex->sphead= oldlex->sphead;
  sublex->spcont= oldlex->spcont;
1014 1015
  /* And trigger related stuff too */
  sublex->trg_chistics= oldlex->trg_chistics;
1016
  sublex->trg_table_fields.empty();
1017
  sublex->sp_lex_in_use= FALSE;
1018
  DBUG_VOID_RETURN;
1019 1020
}

1021
// Restore lex during parsing, after we have parsed a sub statement.
1022 1023 1024
void
sp_head::restore_lex(THD *thd)
{
1025 1026
  DBUG_ENTER("sp_head::restore_lex");
  LEX *sublex= thd->lex;
1027 1028
  LEX *oldlex= (LEX *)m_lex.pop();

1029
  init_stmt_after_parse(thd, sublex);
1030 1031
  if (! oldlex)
    return;			// Nothing to restore
1032

1033
  // Update some state in the old one first
1034 1035
  oldlex->ptr= sublex->ptr;
  oldlex->next_state= sublex->next_state;
1036
  oldlex->trg_table_fields.push_back(&sublex->trg_table_fields);
1037

1038
  /*
1039 1040
    Add routines which are used by statement to respective set for
    this routine.
1041
  */
1042
  sp_update_sp_used_routines(&m_sroutines, &sublex->sroutines);
1043 1044 1045 1046 1047
  /*
    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);
1048 1049 1050
  if (! sublex->sp_lex_in_use)
    delete sublex;
  thd->lex= oldlex;
1051
  DBUG_VOID_RETURN;
1052 1053
}

1054
void
1055
sp_head::push_backpatch(sp_instr *i, sp_label_t *lab)
1056
{
1057
  bp_t *bp= (bp_t *)sql_alloc(sizeof(bp_t));
1058 1059 1060 1061 1062 1063 1064

  if (bp)
  {
    bp->lab= lab;
    bp->instr= i;
    (void)m_backpatch.push_front(bp);
  }
1065 1066 1067
}

void
1068
sp_head::backpatch(sp_label_t *lab)
1069
{
1070
  bp_t *bp;
1071
  uint dest= instructions();
1072
  List_iterator_fast<bp_t> li(m_backpatch);
1073

1074
  while ((bp= li++))
1075 1076 1077 1078
  {
    if (bp->lab == lab ||
	(bp->lab->type == SP_LAB_REF &&
	 my_strcasecmp(system_charset_info, bp->lab->name, lab->name) == 0))
1079
    {
1080 1081 1082 1083 1084
      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);
1085

1086 1087 1088 1089 1090 1091
	if (dstlab)
	{
	  bp->lab= lab;
	  bp->instr->backpatch(dest, dstlab->ctx);
	}
      }
1092 1093 1094 1095 1096 1097 1098 1099 1100
    }
  }
}

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

1102 1103 1104 1105
  while ((bp= li++))
  {
    if (bp->lab->type == SP_LAB_REF)
    {
1106
      my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "GOTO", bp->lab->name);
1107
      return -1;
1108
    }
1109 1110
  }
  return 0;
1111 1112
}

1113 1114 1115
void
sp_head::set_info(char *definer, uint definerlen,
		  longlong created, longlong modified,
1116
		  st_sp_chistics *chistics, ulong sql_mode)
1117 1118 1119 1120 1121 1122 1123
{
  char *p= strchr(definer, '@');
  uint len;

  if (! p)
    p= definer;		// Weird...
  len= p-definer;
monty@mysql.com's avatar
monty@mysql.com committed
1124
  m_definer_user.str= strmake_root(mem_root, definer, len);
1125 1126
  m_definer_user.length= len;
  len= definerlen-len-1;
monty@mysql.com's avatar
monty@mysql.com committed
1127
  m_definer_host.str= strmake_root(mem_root, p+1, len);
1128 1129 1130
  m_definer_host.length= len;
  m_created= created;
  m_modified= modified;
monty@mysql.com's avatar
monty@mysql.com committed
1131 1132
  m_chistics= (st_sp_chistics *) memdup_root(mem_root, (char*) chistics,
                                             sizeof(*chistics));
1133 1134 1135
  if (m_chistics->comment.length == 0)
    m_chistics->comment.str= 0;
  else
monty@mysql.com's avatar
monty@mysql.com committed
1136
    m_chistics->comment.str= strmake_root(mem_root,
1137 1138
					  m_chistics->comment.str,
					  m_chistics->comment.length);
1139
  m_sql_mode= sql_mode;
1140 1141
}

1142 1143 1144
void
sp_head::reset_thd_mem_root(THD *thd)
{
1145
  DBUG_ENTER("sp_head::reset_thd_mem_root");
1146
  m_thd_root= thd->mem_root;
monty@mysql.com's avatar
monty@mysql.com committed
1147
  thd->mem_root= &main_mem_root;
1148 1149 1150
  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
1151 1152 1153
  thd->free_list= NULL;	// Start a new one
  /* Copy the db, since substatements will point to it */
  m_thd_db= thd->db;
monty@mysql.com's avatar
monty@mysql.com committed
1154
  thd->db= thd->strmake(thd->db, thd->db_length);
1155
  m_thd= thd;
1156
  DBUG_VOID_RETURN;
1157 1158 1159 1160 1161
}

void
sp_head::restore_thd_mem_root(THD *thd)
{
1162 1163
  DBUG_ENTER("sp_head::restore_thd_mem_root");
  Item *flist= free_list;	// The old list
1164
  set_item_arena(thd);          // Get new free_list and mem_root
1165
  state= INITIALIZED_FOR_SP;
1166

1167 1168
  DBUG_PRINT("info", ("mem_root 0x%lx returned from thd mem root 0x%lx",
                      (ulong) &mem_root, (ulong) &thd->mem_root));
1169 1170 1171 1172
  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;
1173
  DBUG_VOID_RETURN;
1174 1175 1176
}


1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
/*
  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)
1192 1193 1194 1195 1196
{
  TABLE_LIST tables;
  bzero((char*) &tables,sizeof(tables));
  tables.db= (char*) "mysql";
  tables.table_name= tables.alias= (char*) "proc";
1197 1198 1199 1200
  *full_access= (!check_table_access(thd, SELECT_ACL, &tables, 1) ||
                 (!strcmp(sp->m_definer_user.str, thd->priv_user) &&
                  !strcmp(sp->m_definer_host.str, thd->priv_host)));
  if (!*full_access)
1201 1202
    return check_some_routine_access(thd, sp->m_db.str, sp->m_name.str,
                                     sp->m_type == TYPE_ENUM_PROCEDURE);
1203 1204 1205 1206
  return 0;
}


1207 1208 1209 1210 1211 1212 1213 1214
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;
1215 1216 1217 1218
  ulong old_sql_mode;
  sys_var *sql_mode_var;
  byte *sql_mode_str;
  ulong sql_mode_len;
1219
  bool full_access;
1220 1221 1222

  DBUG_ENTER("sp_head::show_create_procedure");
  DBUG_PRINT("info", ("procedure %s", m_name.str));
1223 1224
  LINT_INIT(sql_mode_str);
  LINT_INIT(sql_mode_len);
1225

1226
  if (check_show_routine_access(thd, this, &full_access))
1227
    return 1;
1228
  
1229 1230 1231 1232 1233 1234
  old_sql_mode= thd->variables.sql_mode;
  thd->variables.sql_mode= m_sql_mode;
  sql_mode_var= find_sys_var("SQL_MODE", 8);
  if (sql_mode_var)
  {
    sql_mode_str= sql_mode_var->value_ptr(thd, OPT_SESSION, 0);
1235
    sql_mode_len= strlen((char*) sql_mode_str);
1236 1237 1238 1239 1240
  }

  field_list.push_back(new Item_empty_string("Procedure", NAME_LEN));
  if (sql_mode_var)
    field_list.push_back(new Item_empty_string("sql_mode", sql_mode_len));
1241 1242
  // 1024 is for not to confuse old clients
  field_list.push_back(new Item_empty_string("Create Procedure",
1243
					     max(buffer.length(), 1024)));
1244 1245
  if (protocol->send_fields(&field_list, Protocol::SEND_NUM_ROWS |
                                         Protocol::SEND_EOF))
1246 1247 1248 1249
  {
    res= 1;
    goto done;
  }
1250 1251
  protocol->prepare_for_resend();
  protocol->store(m_name.str, m_name.length, system_charset_info);
1252
  if (sql_mode_var)
1253
    protocol->store((char*) sql_mode_str, sql_mode_len, system_charset_info);
1254 1255
  if (full_access)
    protocol->store(m_defstr.str, m_defstr.length, system_charset_info);
1256 1257
  res= protocol->write();
  send_eof(thd);
1258 1259 1260

 done:
  thd->variables.sql_mode= old_sql_mode;
1261 1262 1263
  DBUG_RETURN(res);
}

1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280

/*
  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;
  insert_dynamic(&m_instr, (gptr)&instr);
}


1281 1282 1283 1284 1285 1286 1287 1288
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;
1289 1290 1291 1292
  ulong old_sql_mode;
  sys_var *sql_mode_var;
  byte *sql_mode_str;
  ulong sql_mode_len;
1293
  bool full_access;
1294 1295
  DBUG_ENTER("sp_head::show_create_function");
  DBUG_PRINT("info", ("procedure %s", m_name.str));
1296 1297
  LINT_INIT(sql_mode_str);
  LINT_INIT(sql_mode_len);
1298

1299
  if (check_show_routine_access(thd, this, &full_access))
1300 1301
    return 1;

1302 1303 1304 1305 1306 1307
  old_sql_mode= thd->variables.sql_mode;
  thd->variables.sql_mode= m_sql_mode;
  sql_mode_var= find_sys_var("SQL_MODE", 8);
  if (sql_mode_var)
  {
    sql_mode_str= sql_mode_var->value_ptr(thd, OPT_SESSION, 0);
1308
    sql_mode_len= strlen((char*) sql_mode_str);
1309 1310
  }

1311
  field_list.push_back(new Item_empty_string("Function",NAME_LEN));
1312 1313
  if (sql_mode_var)
    field_list.push_back(new Item_empty_string("sql_mode", sql_mode_len));
1314 1315
  field_list.push_back(new Item_empty_string("Create Function",
					     max(buffer.length(),1024)));
1316 1317
  if (protocol->send_fields(&field_list,
                            Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
1318 1319 1320 1321
  {
    res= 1;
    goto done;
  }
1322 1323
  protocol->prepare_for_resend();
  protocol->store(m_name.str, m_name.length, system_charset_info);
1324
  if (sql_mode_var)
1325
    protocol->store((char*) sql_mode_str, sql_mode_len, system_charset_info);
1326 1327
  if (full_access)
    protocol->store(m_defstr.str, m_defstr.length, system_charset_info);
1328 1329
  res= protocol->write();
  send_eof(thd);
1330 1331 1332

 done:
  thd->variables.sql_mode= old_sql_mode;
1333 1334
  DBUG_RETURN(res);
}
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386

void
sp_head::optimize()
{
  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);
}

1387
// ------------------------------------------------------------------
1388

1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429

/*
  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));
1430
  thd->query_id= next_query_id();
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
  VOID(pthread_mutex_unlock(&LOCK_thread_count));

  /*
    FIXME. Resetting statement (and using it) is not reentrant, thus recursive
           functions which try to use the same LEX twice will crash server.
           We should prevent such situations by tracking if LEX is already
           in use and throwing error about unallowed recursion if needed.
           OTOH it is nice to allow recursion in cases when LEX is not really
           used (e.g. in mathematical functions), so such tracking should be
           implemented at the same time as ability not to store LEX for
           instruction if it is not really used.
  */
1443
  reinit_stmt_before_use(thd, m_lex);
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483

  /*
    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);

  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.

    Probably we can call destructors for most of them then we are leaving
    routine. But this won't help much as they are allocated in main query
    MEM_ROOT anyway. So they all go to global thd->free_list.

    May be we can use some other MEM_ROOT for this purprose ???

    What else should we do for cleanup ?
    cleanup_items() is called in sp_head::execute()
  */
  return res;
}


1484
//
1485
// sp_instr
1486
//
1487
int sp_instr::exec_core(THD *thd, uint *nextp)
1488
{
1489 1490
  DBUG_ASSERT(0);
  return 0;
1491 1492
}

1493 1494 1495 1496

//
// sp_instr_stmt
//
1497
int
1498
sp_instr_stmt::execute(THD *thd, uint *nextp)
1499
{
1500 1501
  char *query;
  uint32 query_length;
1502
  DBUG_ENTER("sp_instr_stmt::execute");
1503
  DBUG_PRINT("info", ("command: %d", m_lex_keeper.sql_command()));
1504 1505 1506 1507 1508 1509 1510 1511 1512
  int res;

  query= thd->query;
  query_length= thd->query_length;
  if (!(res= alloc_query(thd, m_query.str, m_query.length+1)))
  {
    if (query_cache_send_result_to_client(thd,
					  thd->query, thd->query_length) <= 0)
    {
1513
      res= m_lex_keeper.reset_lex_and_exec_core(thd, nextp, FALSE, this);
1514 1515
      query_cache_end_of_result(thd);
    }
1516 1517
    else
      *nextp= m_ip+1;
1518 1519 1520
    thd->query= query;
    thd->query_length= query_length;
  }
1521 1522 1523
  DBUG_RETURN(res);
}

1524 1525 1526 1527 1528
void
sp_instr_stmt::print(String *str)
{
  str->reserve(12);
  str->append("stmt ");
1529
  str->qs_append((uint)m_lex_keeper.sql_command());
1530 1531 1532
}


1533
int
1534
sp_instr_stmt::exec_core(THD *thd, uint *nextp)
1535
{
1536 1537
  int res= mysql_execute_command(thd);
  *nextp= m_ip+1;
1538
  return res;
1539 1540 1541 1542 1543 1544
}

//
// sp_instr_set
//
int
1545
sp_instr_set::execute(THD *thd, uint *nextp)
1546
{
1547 1548
  DBUG_ENTER("sp_instr_set::execute");
  DBUG_PRINT("info", ("offset: %u", m_offset));
1549 1550 1551 1552 1553 1554 1555

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

int
sp_instr_set::exec_core(THD *thd, uint *nextp)
{
1556
  int res= thd->spcont->set_item_eval(thd, m_offset, &m_value, m_type);
1557

1558
  *nextp = m_ip+1;
1559
  return res;
1560 1561
}

1562 1563 1564 1565 1566 1567 1568 1569 1570 1571
void
sp_instr_set::print(String *str)
{
  str->reserve(12);
  str->append("set ");
  str->qs_append(m_offset);
  str->append(' ');
  m_value->print(str);
}

1572 1573 1574 1575 1576 1577 1578 1579

//
// sp_instr_set_trigger_field
//
int
sp_instr_set_trigger_field::execute(THD *thd, uint *nextp)
{
  DBUG_ENTER("sp_instr_set_trigger_field::execute");
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591
  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 ||
      !trigger_field->fixed && trigger_field->fix_fields(thd, 0, 0) ||
      (it->save_in_field(trigger_field->field, 0) < 0))
1592
    res= -1;
1593 1594
  *nextp = m_ip+1;
  return res;
1595 1596 1597 1598 1599 1600
}

void
sp_instr_set_trigger_field::print(String *str)
{
  str->append("set ", 4);
1601
  trigger_field->print(str);
1602 1603 1604 1605
  str->append(":=", 2);
  value->print(str);
}

1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
//
// sp_instr_jump
//
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);
}

1619 1620 1621 1622 1623 1624 1625 1626
void
sp_instr_jump::print(String *str)
{
  str->reserve(12);
  str->append("jump ");
  str->qs_append(m_dest);
}

1627 1628 1629
uint
sp_instr_jump::opt_mark(sp_head *sp)
{
1630
  m_dest= opt_shortcut_jump(sp, this);
1631 1632
  if (m_dest != m_ip+1)		/* Jumping to following instruction? */
    marked= 1;
1633 1634 1635 1636 1637
  m_optdest= sp->get_instr(m_dest);
  return m_dest;
}

uint
1638
sp_instr_jump::opt_shortcut_jump(sp_head *sp, sp_instr *start)
1639 1640 1641 1642 1643 1644
{
  uint dest= m_dest;
  sp_instr *i;

  while ((i= sp->get_instr(dest)))
  {
1645
    uint ndest;
1646

1647
    if (start == i || this == i)
1648 1649
      break;
    ndest= i->opt_shortcut_jump(sp, start);
1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
    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;
}

1667 1668 1669
//
// sp_instr_jump_if
//
1670

1671 1672 1673
int
sp_instr_jump_if::execute(THD *thd, uint *nextp)
{
1674 1675
  DBUG_ENTER("sp_instr_jump_if::execute");
  DBUG_PRINT("info", ("destination: %u", m_dest));
1676 1677 1678 1679 1680 1681
  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)
{
1682 1683
  Item *it;
  int res;
1684

1685
  it= sp_prepare_func_item(thd, &m_expr);
1686 1687
  if (!it)
    res= -1;
1688
  else
1689 1690
  {
    res= 0;
1691
    if (it->val_bool())
1692 1693 1694 1695
      *nextp = m_dest;
    else
      *nextp = m_ip+1;
  }
1696 1697

  return res;
1698 1699
}

1700 1701 1702 1703 1704 1705 1706 1707 1708 1709
void
sp_instr_jump_if::print(String *str)
{
  str->reserve(12);
  str->append("jump_if ");
  str->qs_append(m_dest);
  str->append(' ');
  m_expr->print(str);
}

1710 1711 1712 1713 1714 1715 1716 1717
uint
sp_instr_jump_if::opt_mark(sp_head *sp)
{
  sp_instr *i;

  marked= 1;
  if ((i= sp->get_instr(m_dest)))
  {
1718
    m_dest= i->opt_shortcut_jump(sp, this);
1719 1720 1721 1722 1723 1724
    m_optdest= sp->get_instr(m_dest);
  }
  sp->opt_mark(m_dest);
  return m_ip+1;
}

1725 1726 1727 1728 1729 1730
//
// sp_instr_jump_if_not
//
int
sp_instr_jump_if_not::execute(THD *thd, uint *nextp)
{
1731 1732
  DBUG_ENTER("sp_instr_jump_if_not::execute");
  DBUG_PRINT("info", ("destination: %u", m_dest));
1733 1734 1735 1736 1737 1738 1739
  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)
{
1740 1741
  Item *it;
  int res;
1742

1743
  it= sp_prepare_func_item(thd, &m_expr);
1744 1745
  if (! it)
    res= -1;
1746
  else
1747 1748
  {
    res= 0;
1749
    if (! it->val_bool())
1750 1751 1752 1753
      *nextp = m_dest;
    else
      *nextp = m_ip+1;
  }
1754 1755

  return res;
1756
}
1757

1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
void
sp_instr_jump_if_not::print(String *str)
{
  str->reserve(16);
  str->append("jump_if_not ");
  str->qs_append(m_dest);
  str->append(' ');
  m_expr->print(str);
}

1768 1769 1770 1771 1772 1773 1774 1775
uint
sp_instr_jump_if_not::opt_mark(sp_head *sp)
{
  sp_instr *i;

  marked= 1;
  if ((i= sp->get_instr(m_dest)))
  {
1776
    m_dest= i->opt_shortcut_jump(sp, this);
1777 1778 1779 1780 1781 1782
    m_optdest= sp->get_instr(m_dest);
  }
  sp->opt_mark(m_dest);
  return m_ip+1;
}

1783
//
1784
// sp_instr_freturn
1785
//
1786

1787
int
1788
sp_instr_freturn::execute(THD *thd, uint *nextp)
1789
{
1790
  DBUG_ENTER("sp_instr_freturn::execute");
1791 1792 1793 1794 1795 1796 1797
  DBUG_RETURN(m_lex_keeper.reset_lex_and_exec_core(thd, nextp, TRUE, this));
}


int
sp_instr_freturn::exec_core(THD *thd, uint *nextp)
{
1798 1799
  Item *it;
  int res;
1800

1801
  it= sp_eval_func_item(thd, &m_value, m_type, NULL);
1802 1803 1804 1805 1806 1807 1808
  if (! it)
    res= -1;
  else
  {
    res= 0;
    thd->spcont->set_result(it);
  }
1809
  *nextp= UINT_MAX;
1810 1811

  return res;
1812
}
1813

1814 1815 1816 1817 1818
void
sp_instr_freturn::print(String *str)
{
  str->reserve(12);
  str->append("freturn ");
1819
  str->qs_append((uint)m_type);
1820 1821 1822 1823
  str->append(' ');
  m_value->print(str);
}

1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840
//
// sp_instr_hpush_jump
//
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++))
    thd->spcont->push_handler(p, m_handler, m_type, m_frame);

  *nextp= m_dest;
  DBUG_RETURN(0);
}

1841 1842 1843 1844 1845
void
sp_instr_hpush_jump::print(String *str)
{
  str->reserve(32);
  str->append("hpush_jump ");
1846 1847
  str->qs_append(m_dest);
  str->append(" t=");
1848
  str->qs_append(m_type);
1849
  str->append(" f=");
1850
  str->qs_append(m_frame);
1851
  str->append(" h=");
1852 1853 1854
  str->qs_append(m_handler);
}

1855 1856 1857 1858 1859 1860 1861 1862
uint
sp_instr_hpush_jump::opt_mark(sp_head *sp)
{
  sp_instr *i;

  marked= 1;
  if ((i= sp->get_instr(m_dest)))
  {
1863
    m_dest= i->opt_shortcut_jump(sp, this);
1864 1865 1866 1867 1868 1869
    m_optdest= sp->get_instr(m_dest);
  }
  sp->opt_mark(m_dest);
  return m_ip+1;
}

1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881
//
// sp_instr_hpop
//
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);
}

1882 1883 1884 1885 1886 1887 1888 1889
void
sp_instr_hpop::print(String *str)
{
  str->reserve(12);
  str->append("hpop ");
  str->qs_append(m_count);
}

1890 1891 1892 1893 1894 1895 1896
void
sp_instr_hpop::backpatch(uint dest, sp_pcontext *dst_ctx)
{
  m_count= m_ctx->diff_handlers(dst_ctx);
}


1897 1898 1899 1900 1901 1902 1903
//
// sp_instr_hreturn
//
int
sp_instr_hreturn::execute(THD *thd, uint *nextp)
{
  DBUG_ENTER("sp_instr_hreturn::execute");
1904 1905 1906 1907 1908 1909 1910 1911
  if (m_dest)
    *nextp= m_dest;
  else
  {
    thd->spcont->restore_variables(m_frame);
    *nextp= thd->spcont->pop_hstack();
  }
  thd->spcont->in_handler= FALSE;
1912 1913
  DBUG_RETURN(0);
}
1914

1915 1916 1917
void
sp_instr_hreturn::print(String *str)
{
1918
  str->reserve(16);
1919 1920
  str->append("hreturn ");
  str->qs_append(m_frame);
1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934
  if (m_dest)
    str->qs_append(m_dest);
}

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;
  }
1935 1936
}

1937

1938 1939 1940 1941 1942 1943 1944
//
// sp_instr_cpush
//
int
sp_instr_cpush::execute(THD *thd, uint *nextp)
{
  DBUG_ENTER("sp_instr_cpush::execute");
1945
  thd->spcont->push_cursor(&m_lex_keeper);
1946 1947 1948 1949
  *nextp= m_ip+1;
  DBUG_RETURN(0);
}

1950 1951 1952 1953 1954 1955
void
sp_instr_cpush::print(String *str)
{
  str->append("cpush");
}

1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967
//
// sp_instr_cpop
//
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);
}

1968 1969 1970 1971 1972 1973 1974 1975
void
sp_instr_cpop::print(String *str)
{
  str->reserve(12);
  str->append("cpop ");
  str->qs_append(m_count);
}

1976 1977 1978 1979 1980 1981
void
sp_instr_cpop::backpatch(uint dest, sp_pcontext *dst_ctx)
{
  m_count= m_ctx->diff_cursors(dst_ctx);
}

1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995
//
// sp_instr_copen
//
int
sp_instr_copen::execute(THD *thd, uint *nextp)
{
  sp_cursor *c= thd->spcont->get_cursor(m_cursor);
  int res;
  DBUG_ENTER("sp_instr_copen::execute");

  if (! c)
    res= -1;
  else
  {
1996
    sp_lex_keeper *lex_keeper= c->pre_open(thd);
monty@mysql.com's avatar
monty@mysql.com committed
1997
    if (!lex_keeper)                            // cursor already open or OOM
1998
    {
1999
      res= -1;
2000 2001
      *nextp= m_ip+1;
    }
2002
    else
2003
    {
2004
      res= lex_keeper->reset_lex_and_exec_core(thd, nextp, FALSE, this);
monty@mysql.com's avatar
merge  
monty@mysql.com committed
2005 2006 2007 2008 2009 2010 2011 2012
      /*
        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;
2013

monty@mysql.com's avatar
merge  
monty@mysql.com committed
2014 2015 2016
        if (thd->spcont->found_handler(&dummy1, &dummy2))
  	  res= -1;
      }
monty@mysql.com's avatar
monty@mysql.com committed
2017
      c->post_open(thd, res ? FALSE : TRUE);
2018
    }
2019 2020 2021 2022
  }
  DBUG_RETURN(res);
}

monty@mysql.com's avatar
monty@mysql.com committed
2023

2024 2025 2026 2027 2028 2029 2030 2031
int
sp_instr_copen::exec_core(THD *thd, uint *nextp)
{
  int res= mysql_execute_command(thd);
  *nextp= m_ip+1;
  return res;
}

2032 2033 2034 2035 2036 2037 2038 2039
void
sp_instr_copen::print(String *str)
{
  str->reserve(12);
  str->append("copen ");
  str->qs_append(m_cursor);
}

2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057
//
// sp_instr_cclose
//
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);
}

2058 2059 2060 2061 2062 2063 2064 2065
void
sp_instr_cclose::print(String *str)
{
  str->reserve(12);
  str->append("cclose ");
  str->qs_append(m_cursor);
}

2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082
//
// sp_instr_cfetch
//
int
sp_instr_cfetch::execute(THD *thd, uint *nextp)
{
  sp_cursor *c= thd->spcont->get_cursor(m_cursor);
  int res;
  DBUG_ENTER("sp_instr_cfetch::execute");

  if (! c)
    res= -1;
  else
    res= c->fetch(thd, &m_varlist);
  *nextp= m_ip+1;
  DBUG_RETURN(res);
}
2083

2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108
void
sp_instr_cfetch::print(String *str)
{
  List_iterator_fast<struct sp_pvar> li(m_varlist);
  sp_pvar_t *pv;

  str->reserve(12);
  str->append("cfetch ");
  str->qs_append(m_cursor);
  while ((pv= li++))
  {
    str->reserve(8);
    str->append(' ');
    str->qs_append(pv->offset);
  }
}

//
// sp_instr_error
//
int
sp_instr_error::execute(THD *thd, uint *nextp)
{
  DBUG_ENTER("sp_instr_error::execute");

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2109
  my_message(m_errcode, ER(m_errcode), MYF(0));
2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121
  *nextp= m_ip+1;
  DBUG_RETURN(-1);
}

void
sp_instr_error::print(String *str)
{
  str->reserve(12);
  str->append("error ");
  str->qs_append(m_errcode);
}

2122 2123
/* ------------------------------------------------------------------ */

2124 2125 2126 2127

//
// Security context swapping
//
2128

2129
#ifndef NO_EMBEDDED_ACCESS_CHECKS
2130 2131 2132
void
sp_change_security_context(THD *thd, sp_head *sp, st_sp_security_context *ctxp)
{
2133
  ctxp->changed= (sp->m_chistics->suid != SP_IS_NOT_SUID &&
2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178
		   (strcmp(sp->m_definer_user.str, thd->priv_user) ||
		    strcmp(sp->m_definer_host.str, thd->priv_host)));

  if (ctxp->changed)
  {
    ctxp->master_access= thd->master_access;
    ctxp->db_access= thd->db_access;
    ctxp->priv_user= thd->priv_user;
    strncpy(ctxp->priv_host, thd->priv_host, sizeof(ctxp->priv_host));
    ctxp->user= thd->user;
    ctxp->host= thd->host;
    ctxp->ip= thd->ip;

    /* Change thise just to do the acl_getroot_no_password */
    thd->user= sp->m_definer_user.str;
    thd->host= thd->ip = sp->m_definer_host.str;

    if (acl_getroot_no_password(thd))
    {			// Failed, run as invoker for now
      ctxp->changed= FALSE;
      thd->master_access= ctxp->master_access;
      thd->db_access= ctxp->db_access;
      thd->priv_user= ctxp->priv_user;
      strncpy(thd->priv_host, ctxp->priv_host, sizeof(thd->priv_host));
    }

    /* Restore these immiediately */
    thd->user= ctxp->user;
    thd->host= ctxp->host;
    thd->ip= ctxp->ip;
  }
}

void
sp_restore_security_context(THD *thd, sp_head *sp, st_sp_security_context *ctxp)
{
  if (ctxp->changed)
  {
    ctxp->changed= FALSE;
    thd->master_access= ctxp->master_access;
    thd->db_access= ctxp->db_access;
    thd->priv_user= ctxp->priv_user;
    strncpy(thd->priv_host, ctxp->priv_host, sizeof(thd->priv_host));
  }
}
2179 2180

#endif /* NO_EMBEDDED_ACCESS_CHECKS */
2181 2182

/*
2183 2184 2185 2186
  Structure that represent all instances of one table
  in optimized multi-set of tables used by routine.
*/

2187 2188
typedef struct st_sp_table
{
serg@serg.mylan's avatar
serg@serg.mylan committed
2189 2190 2191 2192
  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 */
2193 2194
  uint lock_count;
  uint query_lock_count;
2195 2196 2197 2198 2199 2200 2201 2202 2203 2204
} 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;
}

2205

2206
/*
2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225
  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
*/

2226
bool
2227
sp_head::merge_table_list(THD *thd, TABLE_LIST *table, LEX *lex_for_tmp_check)
2228
{
2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240
  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;
  }

2241
  for (; table ; table= table->next_global)
2242
    if (!table->derived && !table->schema_table)
2243
    {
serg@serg.mylan's avatar
serg@serg.mylan committed
2244
      char tname[(NAME_LEN + 1) * 3];           // db\0table\0alias\0
2245 2246 2247 2248
      uint tlen, alen;

      tlen= table->db_length;
      memcpy(tname, table->db, tlen);
serg@serg.mylan's avatar
serg@serg.mylan committed
2249
      tname[tlen++]= '\0';
2250 2251
      memcpy(tname+tlen, table->table_name, table->table_name_length);
      tlen+= table->table_name_length;
serg@serg.mylan's avatar
serg@serg.mylan committed
2252
      tname[tlen++]= '\0';
2253 2254 2255 2256 2257
      alen= strlen(table->alias);
      memcpy(tname+tlen, table->alias, alen);
      tlen+= alen;
      tname[tlen]= '\0';

2258 2259 2260 2261 2262
      /*
        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)))
2263
      {
2264 2265
        if (tab->lock_type < table->lock_type)
          tab->lock_type= table->lock_type; // Use the table with the highest lock type
2266 2267 2268
        tab->query_lock_count++;
        if (tab->query_lock_count > tab->lock_count)
          tab->lock_count++;
2269 2270 2271 2272 2273 2274
      }
      else
      {
	if (!(tab= (SP_TABLE *)thd->calloc(sizeof(SP_TABLE))))
	  return FALSE;
	tab->qname.length= tlen;
serg@serg.mylan's avatar
serg@serg.mylan committed
2275
	tab->qname.str= (char*) thd->memdup(tname, tab->qname.length + 1);
2276 2277
	if (!tab->qname.str)
	  return FALSE;
2278
	if (lex_for_tmp_check->sql_command == SQLCOM_CREATE_TABLE &&
2279 2280 2281
	    lex_for_tmp_check->query_tables == table &&
	    lex_for_tmp_check->create_info.options & HA_LEX_CREATE_TMP_TABLE)
	  tab->temp= TRUE;
serg@serg.mylan's avatar
serg@serg.mylan committed
2282 2283
        tab->table_name_length= table->table_name_length;
        tab->db_length= table->db_length;
2284
        tab->lock_type= table->lock_type;
2285 2286
        tab->lock_count= tab->query_lock_count= 1;
	my_hash_insert(&m_sptabs, (byte *)tab);
2287 2288 2289 2290 2291 2292
      }
    }
  return TRUE;
}


2293 2294
/*
  Add tables used by routine to the table list.
2295

2296 2297 2298 2299 2300 2301
  SYNOPSIS
    add_used_tables_to_table_list()
      thd                   - thread context
      query_tables_last_ptr - (in/out) pointer the next_global member of last
                              element of the list where tables will be added
                              (or to its root).
2302

2303 2304 2305
  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'.
2306

2307 2308
    Elements of list will be allocated in PS memroot, so this list will be
    persistent between PS executions.
2309

2310 2311 2312
  RETURN VALUE
    TRUE - if some elements were added, FALSE - otherwise.
*/
2313

2314 2315 2316
bool
sp_head::add_used_tables_to_table_list(THD *thd,
                                       TABLE_LIST ***query_tables_last_ptr)
2317 2318
{
  uint i;
2319 2320 2321 2322 2323 2324 2325 2326
  Item_arena *arena, backup;
  bool result= FALSE;
  DBUG_ENTER("sp_head::add_used_tables_to_table_list");

  /*
    Use persistent arena for table list allocation to be PS friendly.
  */
  arena= thd->change_arena_if_needed(&backup);
2327

2328
  for (i=0 ; i < m_sptabs.records ; i++)
2329
  {
2330
    char *tab_buff;
serg@serg.mylan's avatar
serg@serg.mylan committed
2331
    TABLE_LIST *table;
2332
    SP_TABLE *stab= (SP_TABLE *)hash_element(&m_sptabs, i);
2333 2334 2335
    if (stab->temp)
      continue;

2336 2337 2338
    if (!(tab_buff= (char *)thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST)) *
                                        stab->lock_count)))
      DBUG_RETURN(FALSE);
2339

2340 2341 2342 2343 2344 2345 2346 2347 2348 2349
    for (uint j= 0; j < stab->lock_count; j++)
    {
      table= (TABLE_LIST *)tab_buff;

      /*
        It's enough to just copy the pointers as the data will not change
        during the lifetime of the SP. If the SP is used by PS, we assume
        that the PS will be invalidated if the functions is deleted or
        changed.
      */
serg@serg.mylan's avatar
serg@serg.mylan committed
2350 2351 2352 2353 2354
      table->db= stab->qname.str;
      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;
2355
      table->lock_type= stab->lock_type;
2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367
      table->cacheable_table= 1;
      table->prelocking_placeholder= 1;

      /* 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;
    }
2368
  }
2369 2370 2371 2372 2373

  if (arena)
    thd->restore_backup_item_arena(arena, &backup);

  DBUG_RETURN(result);
2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404
}

/*
 * Simple function for adding an explicetly named (systems) table to
 * the global table list, e.g. "mysql", "proc".
 *
 */
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;
}
2405