sp_head.cc 28.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* 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 */

#ifdef __GNUC__
#pragma implementation
#endif

#include "mysql_priv.h"
22
#include "sql_acl.h"
23
#include "sp_head.h"
24
#include "sp.h"
25 26 27
#include "sp_pcontext.h"
#include "sp_rcontext.h"

28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
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:
  case MYSQL_TYPE_FLOAT:
  case MYSQL_TYPE_DOUBLE:
    return REAL_RESULT;
  default:
    return STRING_RESULT;
  }
}

48 49 50
/* Evaluate a (presumed) func item. Always returns an item, the parameter
** if nothing else.
*/
51 52
Item *
sp_eval_func_item(THD *thd, Item *it, enum enum_field_types type)
53
{
54
  DBUG_ENTER("sp_eval_func_item");
55
  it= it->this_item();
56
  DBUG_PRINT("info", ("type: %d", type));
57

58
  if (!it->fixed && it->fix_fields(thd, 0, &it))
59 60 61 62
  {
    DBUG_PRINT("info", ("fix_fields() failed"));
    DBUG_RETURN(it);		// Shouldn't happen?
  }
63

64
  /* QQ How do we do this? Is there some better way? */
65
  if (type == MYSQL_TYPE_NULL)
66 67
    it= new Item_null();
  else
68
  {
69 70
    switch (sp_map_result_type(type)) {
    case INT_RESULT:
71 72 73 74
      {
	longlong i= it->val_int();

	if (it->null_value)
75 76
	{
	  DBUG_PRINT("info", ("INT_RESULT: null"));
77
	  it= new Item_null();
78
	}
79
	else
80 81
	{
	  DBUG_PRINT("info", ("INT_RESULT: %d", i));
82
	  it= new Item_int(it->val_int());
83
	}
84 85
	break;
      }
86
    case REAL_RESULT:
87 88 89 90
      {
	double d= it->val();

	if (it->null_value)
91 92
	{
	  DBUG_PRINT("info", ("REAL_RESULT: null"));
93
	  it= new Item_null();
94
	}
95
	else
96
	{
97 98 99 100
	  /* 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;
101
	  DBUG_PRINT("info", ("REAL_RESULT: %g", d));
102
	  it= new Item_real(it->val());
103 104
	  it->decimals= decimals;
	  it->max_length= max_length;
105
	}
106 107
	break;
      }
108 109 110
    default:
      {
	char buffer[MAX_FIELD_WIDTH];
pem@mysql.telia.com's avatar
pem@mysql.telia.com committed
111
	String tmp(buffer, sizeof(buffer), it->collation.collation);
112 113
	String *s= it->val_str(&tmp);

114
	if (it->null_value)
115 116
	{
	  DBUG_PRINT("info", ("default result: null"));
117
	  it= new Item_null();
118
	}
119
	else
120 121
	{
	  DBUG_PRINT("info",("default result: %*s",s->length(),s->c_ptr_quick()));
122 123
	  it= new Item_string(thd->strmake(s->c_ptr_quick(), s->length()),
			      s->length(), it->collation.collation);
124
	}
125 126
	break;
      }
127 128 129
    }
  }

130
  DBUG_RETURN(it);
131 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

/*
 *
 *  sp_name
 *
 */

void
sp_name::init_qname(THD *thd)
{
  m_qname.length= m_db.length+m_name.length+1;
  m_qname.str= alloc_root(&thd->mem_root, m_qname.length+1);
  sprintf(m_qname.str, "%*s.%*s",
	  m_db.length, (m_db.length ? m_db.str : ""),
	  m_name.length, m_name.str);
}

/* ------------------------------------------------------------------ */


/*
 *
 *  sp_head
 *
 */

159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
void *
sp_head::operator new(size_t size)
{
  DBUG_ENTER("sp_head::operator new");
  MEM_ROOT own_root;
  sp_head *sp;

  bzero((char *)&own_root, sizeof(own_root));
  init_alloc_root(&own_root, MEM_ROOT_BLOCK_SIZE, MEM_ROOT_PREALLOC);
  sp= (sp_head *)alloc_root(&own_root, size);
  sp->m_mem_root= own_root;
  
  DBUG_RETURN(sp);
}

void 
sp_head::operator delete(void *ptr, size_t size)
{
  DBUG_ENTER("sp_head::operator delete");
  MEM_ROOT own_root;
  sp_head *sp= (sp_head *)ptr;

181
  DBUG_PRINT("info", ("root: %lx", &sp->m_mem_root));
182 183 184 185 186 187
  memcpy(&own_root, (const void *)&sp->m_mem_root, sizeof(MEM_ROOT));
  free_root(&own_root, MYF(0));

  DBUG_VOID_RETURN;
}

188
sp_head::sp_head()
189 190
  : Sql_alloc(), m_has_return(FALSE), m_simple_case(FALSE),
    m_multi_results(FALSE), m_free_list(NULL)
191
{
192
  DBUG_ENTER("sp_head::sp_head");
193 194 195 196 197 198 199

  m_backpatch.empty();
  m_lex.empty();
  DBUG_VOID_RETURN;
}

void
200
sp_head::init(LEX *lex)
201 202
{
  DBUG_ENTER("sp_head::init");
203 204 205 206

  lex->spcont= m_pcont= new sp_pcontext();
  my_init_dynamic_array(&m_instr, sizeof(sp_instr *), 16, 8);
  m_param_begin= m_param_end= m_returns_begin= m_returns_end= m_body_begin= 0;
207 208 209 210
  m_qname.str= m_db.str= m_name.str= m_params.str= m_retstr.str=
    m_body.str= m_defstr.str= 0;
  m_qname.length= m_db.length= m_name.length= m_params.length=
    m_retstr.length= m_body.length= m_defstr.length= 0;
211 212 213 214
  DBUG_VOID_RETURN;
}

void
215
sp_head::init_strings(THD *thd, LEX *lex, sp_name *name)
216 217
{
  DBUG_ENTER("sp_head::init_strings");
218 219
  /* During parsing, we must use thd->mem_root */
  MEM_ROOT *root= &thd->mem_root;
220

221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
  DBUG_PRINT("info", ("name: %*.s%*s",
		      name->m_db.length, name->m_db.str,
		      name->m_name.length, name->m_name.str));
  /* We have to copy strings to get them into the right memroot */
  if (name->m_db.length == 0)
  {
    m_db.length= strlen(thd->db);
    m_db.str= strmake_root(root, thd->db, m_db.length);
  }
  else
  {
    m_db.length= name->m_db.length;
    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);

243
  m_params.length= m_param_end- m_param_begin;
244
  m_params.str= strmake_root(root,
245
			     (char *)m_param_begin, m_params.length);
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
  if (m_returns_begin && m_returns_end)
  {
    /* QQ KLUDGE: We can't seem to cut out just the type in the parser
       (without the RETURNS), so we'll have to do it here. :-( */
    char *p= (char *)m_returns_begin+strspn((char *)m_returns_begin,"\t\n\r ");
    p+= strcspn(p, "\t\n\r ");
    p+= strspn(p, "\t\n\r ");
    if (p < (char *)m_returns_end)
      m_returns_begin= (uchar *)p;
    /* While we're at it, trim the end too. */
    p= (char *)m_returns_end-1;
    while (p > (char *)m_returns_begin &&
	   (*p == '\t' || *p == '\n' || *p == '\r' || *p == ' '))
      p-= 1;
    m_returns_end= (uchar *)p+1;
    m_retstr.length=  m_returns_end - m_returns_begin;
262
    m_retstr.str= strmake_root(root,
263
			       (char *)m_returns_begin, m_retstr.length);
264 265
  }
  m_body.length= lex->end_of_query - m_body_begin;
266
  m_body.str= strmake_root(root, (char *)m_body_begin, m_body.length);
267
  m_defstr.length= lex->end_of_query - lex->buf;
268
  m_defstr.str= strmake_root(root, (char *)lex->buf, m_defstr.length);
269
  DBUG_VOID_RETURN;
270 271 272 273 274
}

int
sp_head::create(THD *thd)
{
275
  DBUG_ENTER("sp_head::create");
276 277
  int ret;

278 279
  DBUG_PRINT("info", ("type: %d name: %s params: %s body: %s",
		      m_type, m_name.str, m_params.str, m_body.str));
280
  if (m_type == TYPE_ENUM_FUNCTION)
281
    ret= sp_create_function(thd, this);
282
  else
283
    ret= sp_create_procedure(thd, this);
284

285
  DBUG_RETURN(ret);
286 287
}

288 289 290 291 292 293 294
sp_head::~sp_head()
{
  destroy();
  if (m_thd)
    restore_thd_mem_root(m_thd);
}

295 296 297
void
sp_head::destroy()
{
298 299
  DBUG_ENTER("sp_head::destroy");
  DBUG_PRINT("info", ("name: %s", m_name.str));
300 301 302 303 304
  sp_instr *i;
  LEX *lex;

  for (uint ip = 0 ; (i = get_instr(ip)) ; ip++)
    delete i;
305 306
  delete_dynamic(&m_instr);
  m_pcont->destroy();
307 308 309 310 311 312
  free_items(m_free_list);
  while ((lex= (LEX *)m_lex.pop()))
  {
    if (lex != &m_thd->main_lex) // We got interrupted and have lex'es left
      delete lex;
  }
313
  DBUG_VOID_RETURN;
314
}
315

316 317 318
int
sp_head::execute(THD *thd)
{
319
  DBUG_ENTER("sp_head::execute");
320
  char olddbname[128];
321
  char *olddbptr= thd->db;
322
  sp_rcontext *ctx= thd->spcont;
323
  int ret= 0;
324 325
  uint ip= 0;

326 327 328 329 330 331
#ifndef EMBEDDED_LIBRARY
  if (check_stack_overrun(thd, olddbptr))
  {
    DBUG_RETURN(-1);
  }
#endif
332
  if (olddbptr)
333 334 335 336 337 338 339 340 341 342 343
  {
    uint i= 0;
    char *p= olddbptr;

    /* Fast inline strncpy without padding... */
    while (*p && i < sizeof(olddbname))
      olddbname[i++]= *p++;
    if (i == sizeof(olddbname))
      i-= 1;			// QQ Error or warning for truncate?
    olddbname[i]= '\0';
  }
344

345 346
  if (ctx)
    ctx->clear_handler();
347
  thd->query_error= 0;
348 349 350
  do
  {
    sp_instr *i;
351
    uint hip;			// Handler ip
352 353 354 355 356 357

    i = get_instr(ip);	// Returns NULL when we're done.
    if (i == NULL)
      break;
    DBUG_PRINT("execute", ("Instruction %u", ip));
    ret= i->execute(thd, &ip);
358
    // Check if an exception has occurred and a handler has been found
359 360 361
    // Note: We havo to check even if ret==0, since warnings (and some
    //       errors don't return a non-zero value.
    if (!thd->killed && ctx)
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
    {
      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);
	// Fall through
      default:
	ip= hip;
	ret= 0;
	ctx->clear_handler();
	continue;
      }
    }
380
  } while (ret == 0 && !thd->killed && !thd->query_error);
381

382 383 384
  DBUG_PRINT("info", ("ret=%d killed=%d query_error=%d",
		      ret, thd->killed, thd->query_error));
  if (thd->killed || thd->query_error)
385
    ret= -1;
386 387
  /* If the DB has changed, the pointer has changed too, but the
     original thd->db will then have been freed */
388
  if (olddbptr && olddbptr != thd->db)
389 390 391
  {
    /* QQ Maybe we should issue some special error message or warning here,
       if this fails?? */
392 393
    if (! thd->killed)
      ret= mysql_change_db(thd, olddbname);
394
  }
395 396 397 398 399 400 401
  DBUG_RETURN(ret);
}


int
sp_head::execute_function(THD *thd, Item **argp, uint argcount, Item **resp)
{
402
  DBUG_ENTER("sp_head::execute_function");
403
  DBUG_PRINT("info", ("function %s", m_name.str));
404 405
  uint csize = m_pcont->max_framesize();
  uint params = m_pcont->params();
406
  uint hmax = m_pcont->handlers();
407
  uint cmax = m_pcont->cursors();
408 409 410 411 412
  sp_rcontext *octx = thd->spcont;
  sp_rcontext *nctx = NULL;
  uint i;
  int ret;

413 414 415 416 417 418 419 420 421 422
  if (argcount != params)
  {
    // Need to use my_printf_error here, or it will not terminate the
    // invoking query properly.
    my_printf_error(ER_SP_WRONG_NO_OF_ARGS, ER(ER_SP_WRONG_NO_OF_ARGS), MYF(0),
		    "FUNCTION", m_name.str, params, argcount);
    DBUG_RETURN(-1);
  }

  // QQ Should have some error checking here? (types, etc...)
423
  nctx= new sp_rcontext(csize, hmax, cmax);
424 425
  for (i= 0 ; i < params && i < argcount ; i++)
  {
426
    sp_pvar_t *pvar = m_pcont->find_pvar(i);
427

428
    nctx->push_item(sp_eval_func_item(thd, *argp++, pvar->type));
429
  }
430 431 432
  // Close tables opened for subselect in argument list
  close_thread_tables(thd);

433
  // The rest of the frame are local variables which are all IN.
434 435 436 437 438 439 440 441 442 443 444
  // 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);
    }
  }
445 446 447 448
  thd->spcont= nctx;

  ret= execute(thd);
  if (ret == 0)
449 450 451 452 453 454 455 456 457 458 459 460
  {
    Item *it= nctx->get_result();

    if (it)
      *resp= it;
    else
    {
      my_printf_error(ER_SP_NORETURNEND, ER(ER_SP_NORETURNEND), MYF(0),
		      m_name.str);
      ret= -1;
    }
  }
461

462
  nctx->pop_all_cursors();	// To avoid memory leaks after an error
463 464 465 466 467 468 469
  thd->spcont= octx;
  DBUG_RETURN(ret);
}

int
sp_head::execute_procedure(THD *thd, List<Item> *args)
{
470
  DBUG_ENTER("sp_head::execute_procedure");
471
  DBUG_PRINT("info", ("procedure %s", m_name.str));
472
  int ret;
473 474
  uint csize = m_pcont->max_framesize();
  uint params = m_pcont->params();
475
  uint hmax = m_pcont->handlers();
476
  uint cmax = m_pcont->cursors();
477 478
  sp_rcontext *octx = thd->spcont;
  sp_rcontext *nctx = NULL;
479
  my_bool tmp_octx = FALSE;	// True if we have allocated a temporary octx
480

481 482 483 484 485 486 487
  if (args->elements != params)
  {
    net_printf(thd, ER_SP_WRONG_NO_OF_ARGS, "PROCEDURE", m_name.str,
	       params, args->elements);
    DBUG_RETURN(-1);
  }

488
  if (csize > 0 || hmax > 0 || cmax > 0)
489
  {
490
    Item_null *nit= NULL;	// Re-use this, and only create if needed
491
    uint i;
492
    List_iterator_fast<Item> li(*args);
493
    Item *it;
494

495
    nctx= new sp_rcontext(csize, hmax, cmax);
496 497
    if (! octx)
    {				// Create a temporary old context
498 499
      octx= new sp_rcontext(csize, hmax, cmax);
      tmp_octx= TRUE;
500
    }
501
    // QQ: Should do type checking?
502 503
    for (i = 0 ; (it= li++) && i < params ; i++)
    {
504
      sp_pvar_t *pvar = m_pcont->find_pvar(i);
505

506 507
      if (! pvar)
	nctx->set_oindex(i, -1); // Shouldn't happen
508
      else
509 510
      {
	if (pvar->mode == sp_param_out)
511 512 513 514 515
	{
	  if (! nit)
	    nit= new Item_null();
	  nctx->push_item(nit); // OUT
	}
516
	else
517
	  nctx->push_item(sp_eval_func_item(thd, it,pvar->type)); // IN or INOUT
518
	// Note: If it's OUT or INOUT, it must be a variable.
519 520
	// QQ: We can check for global variables here, or should we do it
	//     while parsing?
521 522 523 524 525
	if (pvar->mode == sp_param_in)
	  nctx->set_oindex(i, -1); // IN
	else			// OUT or INOUT
	  nctx->set_oindex(i, static_cast<Item_splocal *>(it)->get_offset());
      }
526
    }
527 528 529
    // Close tables opened for subselect in argument list
    close_thread_tables(thd);

530
    // The rest of the frame are local variables which are all IN.
531 532
    // Default all variables to null (those with default clauses will
    // be set by an set instruction).
533
    for (; i < csize ; i++)
534
    {
535 536 537
      if (! nit)
	nit= new Item_null();
      nctx->push_item(nit);
538
    }
539 540 541
    thd->spcont= nctx;
  }

542
  ret= execute(thd);
543 544 545 546

  // Don't copy back OUT values if we got an error
  if (ret == 0 && csize > 0)
  {
547
    List_iterator_fast<Item> li(*args);
548
    Item *it;
549 550 551 552

    // 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++)
553 554 555 556
    {
      int oi = nctx->get_oindex(i);

      if (oi >= 0)
557 558 559 560
      {
	if (! tmp_octx)
	  octx->set_item(nctx->get_oindex(i), nctx->get_item(i));
	else
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
	{
	  // QQ Currently we just silently ignore non-user-variable arguments.
	  //    We should check this during parsing, when setting up the call
	  //    above
	  if (it->type() == Item::FUNC_ITEM)
	  {
	    Item_func *fi= static_cast<Item_func*>(it);

	    if (fi->functype() == Item_func::GUSERVAR_FUNC)
	    {			// A global user variable
	      Item *item= nctx->get_item(i);
	      Item_func_set_user_var *suv;
	      Item_func_get_user_var *guv=
		static_cast<Item_func_get_user_var*>(fi);

	      suv= new Item_func_set_user_var(guv->get_name(), item);
	      suv->fix_fields(thd, NULL, &item);
	      suv->fix_length_and_dec();
pem@mysql.comhem.se's avatar
pem@mysql.comhem.se committed
579
	      suv->check();
580 581 582
	      suv->update();
	    }
	  }
583 584
	}
      }
585 586 587
    }
  }

588 589 590 591 592 593
  if (tmp_octx)
    octx= NULL;
  if (nctx)
    nctx->pop_all_cursors();	// To avoid memory leaks after an error
  thd->spcont= octx;

594
  DBUG_RETURN(ret);
595 596 597
}


598
// Reset lex during parsing, before we parse a sub statement.
599 600 601
void
sp_head::reset_lex(THD *thd)
{
602 603
  DBUG_ENTER("sp_head::reset_lex");
  LEX *sublex;
604
  LEX *oldlex= thd->lex;
605

606
  (void)m_lex.push_front(oldlex);
607
  thd->lex= sublex= new st_lex;
608
  sublex->yylineno= oldlex->yylineno;
609
  /* Reset most stuff. The length arguments doesn't matter here. */
610
  lex_start(thd, oldlex->buf, oldlex->end_of_query - oldlex->ptr);
611
  /* We must reset ptr and end_of_query again */
612 613 614
  sublex->ptr= oldlex->ptr;
  sublex->end_of_query= oldlex->end_of_query;
  sublex->tok_start= oldlex->tok_start;
615
  /* And keep the SP stuff too */
616 617
  sublex->sphead= oldlex->sphead;
  sublex->spcont= oldlex->spcont;
618
  mysql_init_query(thd, true);	// Only init lex
619
  sublex->sp_lex_in_use= FALSE;
620
  DBUG_VOID_RETURN;
621 622
}

623
// Restore lex during parsing, after we have parsed a sub statement.
624 625 626
void
sp_head::restore_lex(THD *thd)
{
627 628
  DBUG_ENTER("sp_head::restore_lex");
  LEX *sublex= thd->lex;
629
  LEX *oldlex= (LEX *)m_lex.pop();
630
  SELECT_LEX *sl;
631 632 633

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

635
  // Update some state in the old one first
636 637
  oldlex->ptr= sublex->ptr;
  oldlex->next_state= sublex->next_state;
638
  for (sl= sublex->all_selects_list ;
639 640 641
       sl ;
       sl= sl->next_select_in_list())
  {
642
    // Save WHERE clause pointers to avoid damaging by optimisation
643
    sl->prep_where= sl->where;
644 645 646 647 648 649 650 651
    if (sl->with_wild)
    {
      // Copy item_list. We will restore it before calling the
      // sub-statement, so it's ok to pop them.
      sl->item_list_copy.empty();
      while (Item *it= sl->item_list.pop())
	sl->item_list_copy.push_back(it);
    }
652
  }
653

654
  // Collect some data from the sub statement lex.
655 656
  sp_merge_funs(oldlex, sublex);
#ifdef NOT_USED_NOW
pem@mysql.com's avatar
pem@mysql.com committed
657
  // QQ We're not using this at the moment.
658
  if (sublex.sql_command == SQLCOM_CALL)
659
  {
660 661
    // It would be slightly faster to keep the list sorted, but we need
    // an "insert before" method to do that.
662
    char *proc= sublex.udf.name.str;
663

664 665
    List_iterator_fast<char *> li(m_calls);
    char **it;
666

667
    while ((it= li++))
668
      if (my_strcasecmp(system_charset_info, proc, *it) == 0)
669 670
	break;
    if (! it)
671
      m_calls.push_back(&proc);
672 673 674 675 676 677

  }
  // Merge used tables
  // QQ ...or just open tables in thd->open_tables?
  //    This is not entirerly clear at the moment, but for now, we collect
  //    tables here.
678
  for (sl= sublex.all_selects_list ;
679 680 681 682 683 684 685 686 687 688 689
       sl ;
       sl= sl->next_select())
  {
    for (TABLE_LIST *tables= sl->get_table_list() ;
	 tables ;
	 tables= tables->next)
    {
      List_iterator_fast<char *> li(m_tables);
      char **tb;

      while ((tb= li++))
690
	if (my_strcasecmp(system_charset_info, tables->real_name, *tb) == 0)
691 692 693 694
	  break;
      if (! tb)
	m_tables.push_back(&tables->real_name);
    }
695
  }
696
#endif
697 698 699
  if (! sublex->sp_lex_in_use)
    delete sublex;
  thd->lex= oldlex;
700
  DBUG_VOID_RETURN;
701 702
}

703
void
704
sp_head::push_backpatch(sp_instr *i, sp_label_t *lab)
705
{
706
  bp_t *bp= (bp_t *)sql_alloc(sizeof(bp_t));
707 708 709 710 711 712 713

  if (bp)
  {
    bp->lab= lab;
    bp->instr= i;
    (void)m_backpatch.push_front(bp);
  }
714 715 716
}

void
717
sp_head::backpatch(sp_label_t *lab)
718
{
719
  bp_t *bp;
720
  uint dest= instructions();
721
  List_iterator_fast<bp_t> li(m_backpatch);
722

723 724 725 726
  while ((bp= li++))
    if (bp->lab == lab)
    {
      sp_instr_jump *i= static_cast<sp_instr_jump *>(bp->instr);
727

728 729
      i->set_destination(dest);
    }
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
void
sp_head::set_info(char *definer, uint definerlen,
		  longlong created, longlong modified,
		  st_sp_chistics *chistics)
{
  char *p= strchr(definer, '@');
  uint len;

  if (! p)
    p= definer;		// Weird...
  len= p-definer;
  m_definer_user.str= strmake_root(&m_mem_root, definer, len);
  m_definer_user.length= len;
  len= definerlen-len-1;
  m_definer_host.str= strmake_root(&m_mem_root, p+1, len);
  m_definer_host.length= len;
  m_created= created;
  m_modified= modified;
  m_chistics= (st_sp_chistics *)alloc_root(&m_mem_root, sizeof(st_sp_chistics));
  memcpy(m_chistics, chistics, sizeof(st_sp_chistics));
  if (m_chistics->comment.length == 0)
    m_chistics->comment.str= 0;
  else
    m_chistics->comment.str= strmake_root(&m_mem_root,
					  m_chistics->comment.str,
					  m_chistics->comment.length);
}

760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
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;

  DBUG_ENTER("sp_head::show_create_procedure");
  DBUG_PRINT("info", ("procedure %s", m_name.str));

  field_list.push_back(new Item_empty_string("Procedure",NAME_LEN));
  // 1024 is for not to confuse old clients
  field_list.push_back(new Item_empty_string("Create Procedure",
					     max(buffer.length(),1024)));
  if (protocol->send_fields(&field_list, 1))
    DBUG_RETURN(1);
  protocol->prepare_for_resend();
  protocol->store(m_name.str, m_name.length, system_charset_info);
  protocol->store(m_defstr.str, m_defstr.length, system_charset_info);
  res= protocol->write();
  send_eof(thd);
  DBUG_RETURN(res);
}

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;

  DBUG_ENTER("sp_head::show_create_function");
  DBUG_PRINT("info", ("procedure %s", m_name.str));
797

798 799 800 801 802 803 804 805 806 807 808 809
  field_list.push_back(new Item_empty_string("Function",NAME_LEN));
  field_list.push_back(new Item_empty_string("Create Function",
					     max(buffer.length(),1024)));
  if (protocol->send_fields(&field_list, 1))
    DBUG_RETURN(1);
  protocol->prepare_for_resend();
  protocol->store(m_name.str, m_name.length, system_charset_info);
  protocol->store(m_defstr.str, m_defstr.length, system_charset_info);
  res= protocol->write();
  send_eof(thd);
  DBUG_RETURN(res);
}
810
// ------------------------------------------------------------------
811 812 813 814

//
// sp_instr_stmt
//
815 816 817 818 819 820
sp_instr_stmt::~sp_instr_stmt()
{
  if (m_lex)
    delete m_lex;
}

821
int
822
sp_instr_stmt::execute(THD *thd, uint *nextp)
823
{
824
  DBUG_ENTER("sp_instr_stmt::execute");
825
  DBUG_PRINT("info", ("command: %d", m_lex->sql_command));
826 827 828 829 830 831 832 833
  int res= exec_stmt(thd, m_lex);
  *nextp = m_ip+1;
  DBUG_RETURN(res);
}

int
sp_instr_stmt::exec_stmt(THD *thd, LEX *lex)
{
834
  LEX *olex;			// The other lex
835
  Item *freelist;
836
  SELECT_LEX *sl;
837
  int res;
838

839
  olex= thd->lex;		// Save the other lex
840
  thd->lex= lex;		// Use my own lex
841 842
  thd->lex->thd = thd;		// QQ Not reentrant!
  thd->lex->unit.thd= thd;	// QQ Not reentrant
843 844
  freelist= thd->free_list;
  thd->free_list= NULL;
845 846

  VOID(pthread_mutex_lock(&LOCK_thread_count));
847
  thd->query_id= query_id++;
848
  VOID(pthread_mutex_unlock(&LOCK_thread_count));
849 850 851

  // Copy WHERE clause pointers to avoid damaging by optimisation
  // Also clear ref_pointer_arrays.
852
  for (sl= lex->all_selects_list ;
853 854 855
       sl ;
       sl= sl->next_select_in_list())
  {
856 857 858 859 860
    if (lex->sql_command == SQLCOM_CREATE_TABLE ||
	lex->sql_command == SQLCOM_INSERT_SELECT)
    {				// Destroys sl->table_list.first
      sl->table_list_first_copy= sl->table_list.first;
    }
861 862
    if (sl->with_wild)
    {
863 864 865 866 867
      // Restore item_list
      // Note: We have to do this before executing the sub-statement,
      //       to make sure that the list nodes are in the right
      //       memroot.
      List_iterator_fast<Item> li(sl->item_list_copy);
868

869
      sl->item_list.empty();
870
      while (Item *it= li++)
871
	sl->item_list.push_back(it);
872
    }
873 874 875
    sl->ref_pointer_array= 0;
    if (sl->prep_where)
      sl->where= sl->prep_where->copy_andor_structure(thd);
876 877 878 879 880 881 882 883 884 885 886 887
    for (ORDER *order= (ORDER *)sl->order_list.first ;
	 order ;
	 order= order->next)
    {
      order->item_copy= order->item;
    }
    for (ORDER *group= (ORDER *)sl->group_list.first ;
	 group ;
	 group= group->next)
    {
      group->item_copy= group->item;
    }
888
  }
889

890
  res= mysql_execute_command(thd);
891

892 893 894 895 896
  if (thd->lock || thd->open_tables || thd->derived_tables)
  {
    thd->proc_info="closing tables";
    close_thread_tables(thd);			/* Free tables */
  }
897

898
  for (sl= lex->all_selects_list ;
899 900 901
       sl ;
       sl= sl->next_select_in_list())
  {
902 903
    TABLE_LIST *tabs;

Sinisa@sinisa.nasamreza.org's avatar
Sinisa@sinisa.nasamreza.org committed
904 905 906 907 908
    if (lex->sql_command == SQLCOM_CREATE_TABLE ||
	lex->sql_command == SQLCOM_INSERT_SELECT)
    {				// Restore sl->table_list.first
      sl->table_list.first= sl->table_list_first_copy;
    }
909 910 911 912
    // We have closed all tables, get rid of pointers to them
    for (tabs=(TABLE_LIST *)sl->table_list.first ;
	 tabs ;
	 tabs= tabs->next)
913
    {
914 915
      tabs->table= NULL;
    }
916 917 918 919 920 921 922 923 924 925 926 927
    for (ORDER *order= (ORDER *)sl->order_list.first ;
	 order ;
	 order= order->next)
    {
      order->item= order->item_copy;
    }
    for (ORDER *group= (ORDER *)sl->group_list.first ;
	 group ;
	 group= group->next)
    {
      group->item= group->item_copy;
    }
928
  }
929
  thd->lex= olex;		// Restore the other lex
930
  thd->free_list= freelist;
931

932
  return res;
933 934 935 936 937 938
}

//
// sp_instr_set
//
int
939
sp_instr_set::execute(THD *thd, uint *nextp)
940
{
941 942
  DBUG_ENTER("sp_instr_set::execute");
  DBUG_PRINT("info", ("offset: %u", m_offset));
943
  thd->spcont->set_item(m_offset, sp_eval_func_item(thd, m_value, m_type));
944
  *nextp = m_ip+1;
945
  DBUG_RETURN(0);
946 947
}

948 949 950 951 952 953 954 955 956 957 958 959 960
//
// 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);
}

961 962 963 964 965 966
//
// sp_instr_jump_if
//
int
sp_instr_jump_if::execute(THD *thd, uint *nextp)
{
967 968
  DBUG_ENTER("sp_instr_jump_if::execute");
  DBUG_PRINT("info", ("destination: %u", m_dest));
969
  Item *it= sp_eval_func_item(thd, m_expr, MYSQL_TYPE_TINY);
970 971 972 973 974

  if (it->val_int())
    *nextp = m_dest;
  else
    *nextp = m_ip+1;
975
  DBUG_RETURN(0);
976 977 978 979 980 981 982 983
}

//
// sp_instr_jump_if_not
//
int
sp_instr_jump_if_not::execute(THD *thd, uint *nextp)
{
984 985
  DBUG_ENTER("sp_instr_jump_if_not::execute");
  DBUG_PRINT("info", ("destination: %u", m_dest));
986
  Item *it= sp_eval_func_item(thd, m_expr, MYSQL_TYPE_TINY);
987 988 989 990 991

  if (! it->val_int())
    *nextp = m_dest;
  else
    *nextp = m_ip+1;
992
  DBUG_RETURN(0);
993
}
994 995

//
996
// sp_instr_freturn
997 998
//
int
999
sp_instr_freturn::execute(THD *thd, uint *nextp)
1000
{
1001
  DBUG_ENTER("sp_instr_freturn::execute");
1002
  thd->spcont->set_result(sp_eval_func_item(thd, m_value, m_type));
1003 1004 1005
  *nextp= UINT_MAX;
  DBUG_RETURN(0);
}
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046

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

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

//
// sp_instr_hreturn
//
int
sp_instr_hreturn::execute(THD *thd, uint *nextp)
{
  DBUG_ENTER("sp_instr_hreturn::execute");
  thd->spcont->restore_variables(m_frame);
  *nextp= thd->spcont->pop_hstack();
  DBUG_RETURN(0);
}
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097

//
// sp_instr_cpush
//
int
sp_instr_cpush::execute(THD *thd, uint *nextp)
{
  DBUG_ENTER("sp_instr_cpush::execute");
  thd->spcont->push_cursor(m_lex);
  *nextp= m_ip+1;
  DBUG_RETURN(0);
}

sp_instr_cpush::~sp_instr_cpush()
{
  if (m_lex)
    delete m_lex;
}

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

//
// 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
  {
    LEX *lex= c->pre_open(thd);

    if (! lex)
      res= -1;
    else
      res= exec_stmt(thd, lex);
1098
    c->post_open(thd, (lex ? TRUE : FALSE));
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
  }

  *nextp= m_ip+1;
  DBUG_RETURN(res);
}

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

//
// 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);
}
1140

1141 1142
/* ------------------------------------------------------------------ */

1143 1144 1145 1146

//
// Security context swapping
//
1147

1148
#ifndef NO_EMBEDDED_ACCESS_CHECKS
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
void
sp_change_security_context(THD *thd, sp_head *sp, st_sp_security_context *ctxp)
{
  ctxp->changed= (sp->m_chistics->suid != IS_NOT_SUID &&
		   (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->db= thd->db;
    ctxp->db_length= thd->db_length;
    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->db= ctxp->db;
      thd->db_length= ctxp->db_length;
      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->db= ctxp->db;
    thd->db_length= ctxp->db_length;
    thd->priv_user= ctxp->priv_user;
    strncpy(thd->priv_host, ctxp->priv_host, sizeof(thd->priv_host));
  }
}
1204 1205

#endif /* NO_EMBEDDED_ACCESS_CHECKS */