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


#include "mysql_priv.h"
#include "sp.h"
#include "sp_head.h"
21
#include "sp_cache.h"
22
#include "sql_trigger.h"
23

24 25
static bool
create_string(THD *thd, String *buf,
26
	      int sp_type,
27
	      sp_name *name,
28 29 30 31
	      const char *params, ulong paramslen,
	      const char *returns, ulong returnslen,
	      const char *body, ulong bodylen,
	      st_sp_chistics *chistics);
32 33 34 35 36
static int
db_load_routine(THD *thd, int type, sp_name *name, sp_head **sphp,
                ulong sql_mode, const char *params, const char *returns,
                const char *body, st_sp_chistics &chistics,
                const char *definer, longlong created, longlong modified);
37

38 39 40 41 42 43
/*
 *
 * DB storage of Stored PROCEDUREs and FUNCTIONs
 *
 */

44 45
enum
{
46
  MYSQL_PROC_FIELD_DB = 0,
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
  MYSQL_PROC_FIELD_NAME,
  MYSQL_PROC_FIELD_TYPE,
  MYSQL_PROC_FIELD_SPECIFIC_NAME,
  MYSQL_PROC_FIELD_LANGUAGE,
  MYSQL_PROC_FIELD_ACCESS,
  MYSQL_PROC_FIELD_DETERMINISTIC,
  MYSQL_PROC_FIELD_SECURITY_TYPE,
  MYSQL_PROC_FIELD_PARAM_LIST,
  MYSQL_PROC_FIELD_RETURNS,
  MYSQL_PROC_FIELD_BODY,
  MYSQL_PROC_FIELD_DEFINER,
  MYSQL_PROC_FIELD_CREATED,
  MYSQL_PROC_FIELD_MODIFIED,
  MYSQL_PROC_FIELD_SQL_MODE,
  MYSQL_PROC_FIELD_COMMENT,
  MYSQL_PROC_FIELD_COUNT
};
64

65 66
bool mysql_proc_table_exists= 1;

67 68 69
/* Tells what SP_DEFAULT_ACCESS should be mapped to */
#define SP_DEFAULT_ACCESS_MAPPING SP_CONTAINS_SQL

70 71 72 73 74 75

/*
  Close mysql.proc, opened with open_proc_table_for_read().

  SYNOPSIS
    close_proc_table()
76 77 78 79
      thd     Thread context
      backup  Pointer to Open_tables_state instance which holds
              information about tables which were open before we
              decided to access mysql.proc.
80 81
*/

82
void close_proc_table(THD *thd, Open_tables_state *backup)
83
{
84
  close_thread_tables(thd);
85
  thd->restore_backup_open_tables_state(backup);
86
}
87

88 89 90 91 92 93

/*
  Open the mysql.proc table for read.

  SYNOPSIS
    open_proc_table_for_read()
94 95 96 97
      thd     Thread context
      backup  Pointer to Open_tables_state instance where information about
              currently open tables will be saved, and from which will be
              restored when we will end work with mysql.proc.
98 99 100 101 102 103 104 105 106 107 108 109 110

  NOTES
    Thanks to restrictions which we put on opening and locking of
    this table for writing, we can open and lock it for reading
    even when we already have some other tables open and locked.
    One must call close_proc_table() to close table opened with
    this call.

  RETURN
    0	Error
    #	Pointer to TABLE object of mysql.proc
*/

111
TABLE *open_proc_table_for_read(THD *thd, Open_tables_state *backup)
112 113 114
{
  TABLE_LIST tables;
  TABLE *table;
115
  bool not_used;
116
  DBUG_ENTER("open_proc_table");
117

118
  /*
119 120
    Speed up things if mysql.proc doesn't exists. mysql_proc_table_exists
    is set when we create or read stored procedure or on flush privileges.
121
  */
122 123
  if (!mysql_proc_table_exists)
    DBUG_RETURN(0);
124

125
  thd->reset_n_backup_open_tables_state(backup);
126 127 128 129

  bzero((char*) &tables, sizeof(tables));
  tables.db= (char*) "mysql";
  tables.table_name= tables.alias= (char*)"proc";
130
  if (!(table= open_table(thd, &tables, thd->mem_root, &not_used,
131
                          MYSQL_LOCK_IGNORE_FLUSH)))
132
  {
133
    thd->restore_backup_open_tables_state(backup);
134 135
    mysql_proc_table_exists= 0;
    DBUG_RETURN(0);
136
  }
137

138 139 140 141
  DBUG_ASSERT(table->s->system_table);

  table->reginfo.lock_type= TL_READ;
  /*
142 143
    We have to ensure we are not blocked by a flush tables, as this
    could lead to a deadlock if we have other tables opened.
144 145
  */
  if (!(thd->lock= mysql_lock_tables(thd, &table, 1,
146
                                     MYSQL_LOCK_IGNORE_FLUSH, &not_used)))
147
  {
148
    close_proc_table(thd, backup);
149
    DBUG_RETURN(0);
150
  }
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
  DBUG_RETURN(table);
}


/*
  Open the mysql.proc table for update.

  SYNOPSIS
    open_proc_table_for_update()
      thd  Thread context

  NOTES
    Table opened with this call should closed using close_thread_tables().

  RETURN
    0	Error
    #	Pointer to TABLE object of mysql.proc
*/

static TABLE *open_proc_table_for_update(THD *thd)
{
  TABLE_LIST tables;
  TABLE *table;
  DBUG_ENTER("open_proc_table");

  bzero((char*) &tables, sizeof(tables));
  tables.db= (char*) "mysql";
  tables.table_name= tables.alias= (char*)"proc";
  tables.lock_type= TL_WRITE;

  table= open_ltable(thd, &tables, TL_WRITE);

  /*
    Under explicit LOCK TABLES or in prelocked mode we should not
    say that mysql.proc table does not exist if we are unable to
    open and lock it for writing since this condition may be
    transient.
  */
  if (!(thd->locked_tables || thd->prelocked_mode) || table)
    mysql_proc_table_exists= test(table);

  DBUG_RETURN(table);
}


/*
  Find row in open mysql.proc table representing stored routine.

  SYNOPSIS
    db_find_routine_aux()
      thd    Thread context
      type   Type of routine to find (function or procedure)
      name   Name of routine
      table  TABLE object for open mysql.proc table.

  RETURN VALUE
    SP_OK           - Routine found
    SP_KEY_NOT_FOUND- No routine with given name
*/

static int
db_find_routine_aux(THD *thd, int type, sp_name *name, TABLE *table)
{
214
  byte key[MAX_KEY_LENGTH];	// db, name, optional key length type
215
  DBUG_ENTER("db_find_routine_aux");
216
  DBUG_PRINT("enter", ("type: %d name: %.*s",
217
		       type, name->m_name.length, name->m_name.str));
218

219 220 221 222 223 224 225
  /*
    Create key to find row. We have to use field->store() to be able to
    handle VARCHAR and CHAR fields.
    Assumption here is that the three first fields in the table are
    'db', 'name' and 'type' and the first key is the primary key over the
    same fields.
  */
226 227
  if (name->m_name.length > table->field[1]->field_length)
    DBUG_RETURN(SP_KEY_NOT_FOUND);
228 229 230
  table->field[0]->store(name->m_db.str, name->m_db.length, &my_charset_bin);
  table->field[1]->store(name->m_name.str, name->m_name.length,
                         &my_charset_bin);
231
  table->field[2]->store((longlong) type, TRUE);
232 233 234
  key_copy(key, table->record[0], table->key_info,
           table->key_info->key_length);

235
  if (table->file->index_read_idx(table->record[0], 0,
236
				  key, table->key_info->key_length,
237
				  HA_READ_KEY_EXACT))
238
    DBUG_RETURN(SP_KEY_NOT_FOUND);
239

240 241 242
  DBUG_RETURN(SP_OK);
}

unknown's avatar
unknown committed
243

244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
/*
  Find routine definition in mysql.proc table and create corresponding
  sp_head object for it.

  SYNOPSIS
    db_find_routine()
      thd   Thread context
      type  Type of routine (TYPE_ENUM_PROCEDURE/...)
      name  Name of routine
      sphp  Out parameter in which pointer to created sp_head
            object is returned (0 in case of error).

  NOTE
    This function may damage current LEX during execution, so it is good
    idea to create temporary LEX and make it active before calling it.

  RETURN VALUE
    0     - Success
    non-0 - Error (may be one of special codes like SP_KEY_NOT_FOUND)
*/

265
static int
266
db_find_routine(THD *thd, int type, sp_name *name, sp_head **sphp)
267 268 269
{
  extern int yyparse(void *thd);
  TABLE *table;
270
  const char *params, *returns, *body;
271
  int ret;
272
  const char *definer;
unknown's avatar
unknown committed
273 274
  longlong created;
  longlong modified;
275
  st_sp_chistics chistics;
unknown's avatar
unknown committed
276 277 278
  char *ptr;
  uint length;
  char buff[65];
279
  String str(buff, sizeof(buff), &my_charset_bin);
280
  ulong sql_mode;
281
  Open_tables_state open_tables_state_backup;
unknown's avatar
unknown committed
282
  DBUG_ENTER("db_find_routine");
283
  DBUG_PRINT("enter", ("type: %d name: %.*s",
284
		       type, name->m_name.length, name->m_name.str));
285

286
  *sphp= 0;                                     // In case of errors
287
  if (!(table= open_proc_table_for_read(thd, &open_tables_state_backup)))
288 289 290
    DBUG_RETURN(SP_OPEN_TABLE_FAILED);

  if ((ret= db_find_routine_aux(thd, type, name, table)) != SP_OK)
291
    goto done;
292

293
  if (table->s->fields != MYSQL_PROC_FIELD_COUNT)
294 295 296 297 298
  {
    ret= SP_GET_FIELD_FAILED;
    goto done;
  }

299
  bzero((char *)&chistics, sizeof(chistics));
unknown's avatar
unknown committed
300
  if ((ptr= get_field(thd->mem_root,
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
		      table->field[MYSQL_PROC_FIELD_ACCESS])) == NULL)
  {
    ret= SP_GET_FIELD_FAILED;
    goto done;
  }
  switch (ptr[0]) {
  case 'N':
    chistics.daccess= SP_NO_SQL;
    break;
  case 'C':
    chistics.daccess= SP_CONTAINS_SQL;
    break;
  case 'R':
    chistics.daccess= SP_READS_SQL_DATA;
    break;
  case 'M':
    chistics.daccess= SP_MODIFIES_SQL_DATA;
    break;
  default:
320
    chistics.daccess= SP_DEFAULT_ACCESS_MAPPING;
321 322
  }

unknown's avatar
unknown committed
323
  if ((ptr= get_field(thd->mem_root,
324
		      table->field[MYSQL_PROC_FIELD_DETERMINISTIC])) == NULL)
325 326 327 328
  {
    ret= SP_GET_FIELD_FAILED;
    goto done;
  }
329
  chistics.detistic= (ptr[0] == 'N' ? FALSE : TRUE);    
unknown's avatar
unknown committed
330

unknown's avatar
unknown committed
331
  if ((ptr= get_field(thd->mem_root,
332
		      table->field[MYSQL_PROC_FIELD_SECURITY_TYPE])) == NULL)
unknown's avatar
unknown committed
333 334 335 336
  {
    ret= SP_GET_FIELD_FAILED;
    goto done;
  }
337
  chistics.suid= (ptr[0] == 'I' ? SP_IS_NOT_SUID : SP_IS_SUID);
unknown's avatar
unknown committed
338

unknown's avatar
unknown committed
339
  if ((params= get_field(thd->mem_root,
340 341 342 343
			 table->field[MYSQL_PROC_FIELD_PARAM_LIST])) == NULL)
  {
    params= "";
  }
unknown's avatar
unknown committed
344

345 346
  if (type == TYPE_ENUM_PROCEDURE)
    returns= "";
unknown's avatar
unknown committed
347
  else if ((returns= get_field(thd->mem_root,
348 349 350 351 352 353
			       table->field[MYSQL_PROC_FIELD_RETURNS])) == NULL)
  {
    ret= SP_GET_FIELD_FAILED;
    goto done;
  }

unknown's avatar
unknown committed
354
  if ((body= get_field(thd->mem_root,
355
		       table->field[MYSQL_PROC_FIELD_BODY])) == NULL)
unknown's avatar
unknown committed
356 357 358 359
  {
    ret= SP_GET_FIELD_FAILED;
    goto done;
  }
360 361

  // Get additional information
unknown's avatar
unknown committed
362
  if ((definer= get_field(thd->mem_root,
363 364 365 366 367 368 369 370
			  table->field[MYSQL_PROC_FIELD_DEFINER])) == NULL)
  {
    ret= SP_GET_FIELD_FAILED;
    goto done;
  }

  modified= table->field[MYSQL_PROC_FIELD_MODIFIED]->val_int();
  created= table->field[MYSQL_PROC_FIELD_CREATED]->val_int();
unknown's avatar
unknown committed
371

unknown's avatar
unknown committed
372
  sql_mode= (ulong) table->field[MYSQL_PROC_FIELD_SQL_MODE]->val_int();
373

374 375
  table->field[MYSQL_PROC_FIELD_COMMENT]->val_str(&str, &str);

unknown's avatar
unknown committed
376
  ptr= 0;
377
  if ((length= str.length()))
378
    ptr= thd->strmake(str.ptr(), length);
379 380
  chistics.comment.str= ptr;
  chistics.comment.length= length;
unknown's avatar
unknown committed
381

382
  close_proc_table(thd, &open_tables_state_backup);
383
  table= 0;
384

385 386 387 388 389 390 391 392 393
  ret= db_load_routine(thd, type, name, sphp,
                       sql_mode, params, returns, body, chistics,
                       definer, created, modified);
                       
 done:
  if (table)
    close_proc_table(thd, &open_tables_state_backup);
  DBUG_RETURN(ret);
}
unknown's avatar
unknown committed
394

395

396 397 398 399 400 401
static int
db_load_routine(THD *thd, int type, sp_name *name, sp_head **sphp,
                ulong sql_mode, const char *params, const char *returns,
                const char *body, st_sp_chistics &chistics,
                const char *definer, longlong created, longlong modified)
{
unknown's avatar
unknown committed
402
  LEX *old_lex= thd->lex, newlex;
403 404 405 406
  String defstr;
  char olddb[128];
  bool dbchanged;
  ulong old_sql_mode= thd->variables.sql_mode;
unknown's avatar
unknown committed
407 408 409
  ha_rows old_select_limit= thd->variables.select_limit;
  sp_rcontext *old_spcont= thd->spcont;
  int ret;
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424

  thd->variables.sql_mode= sql_mode;
  thd->variables.select_limit= HA_POS_ERROR;

  thd->lex= &newlex;
  newlex.current_select= NULL;

  defstr.set_charset(system_charset_info);
  if (!create_string(thd, &defstr,
		     type,
		     name,
		     params, strlen(params),
		     returns, strlen(returns),
		     body, strlen(body),
		     &chistics))
unknown's avatar
unknown committed
425 426
  {
    ret= SP_INTERNAL_ERROR;
427
    goto end;
unknown's avatar
unknown committed
428
  }
429

430 431 432 433
  dbchanged= FALSE;
  if ((ret= sp_use_new_db(thd, name->m_db.str, olddb, sizeof(olddb),
			  1, &dbchanged)))
    goto end;
434

435
  lex_start(thd, (uchar*)defstr.c_ptr(), defstr.length());
436

unknown's avatar
merge  
unknown committed
437
  thd->spcont= 0;
438 439 440 441 442 443 444 445 446 447 448 449
  if (yyparse(thd) || thd->is_fatal_error || newlex.sphead == NULL)
  {
    sp_head *sp= newlex.sphead;

    if (dbchanged && (ret= mysql_change_db(thd, olddb, 1)))
      goto end;
    delete sp;
    ret= SP_PARSE_ERROR;
  }
  else
  {
    if (dbchanged && (ret= mysql_change_db(thd, olddb, 1)))
unknown's avatar
unknown committed
450
      goto end;
451
    *sphp= newlex.sphead;
unknown's avatar
merge  
unknown committed
452
    (*sphp)->set_definer((char*) definer, (uint) strlen(definer));
unknown's avatar
unknown committed
453
    (*sphp)->set_info(created, modified, &chistics, sql_mode);
454 455
    (*sphp)->optimize();
  }
unknown's avatar
unknown committed
456
end:
unknown's avatar
unknown committed
457
  thd->spcont= old_spcont;
458
  thd->variables.sql_mode= old_sql_mode;
unknown's avatar
unknown committed
459 460
  thd->variables.select_limit= old_select_limit;
  thd->lex= old_lex;
461
  return ret;
462 463
}

unknown's avatar
unknown committed
464

unknown's avatar
unknown committed
465 466 467
static void
sp_returns_type(THD *thd, String &result, sp_head *sp)
{
unknown's avatar
unknown committed
468
  TABLE table;
unknown's avatar
unknown committed
469
  Field *field;
unknown's avatar
unknown committed
470 471 472
  bzero(&table, sizeof(table));
  table.in_use= thd;
  table.s = &table.share_not_to_be_used;
473
  field= sp->create_result_field(0, 0, &table);
unknown's avatar
unknown committed
474 475 476 477
  field->sql_type(result);
  delete field;
}

478
static int
479
db_create_routine(THD *thd, int type, sp_head *sp)
480
{
481
  int ret;
482
  TABLE *table;
483
  char definer[USER_HOST_BUFF_SIZE];
484 485
  char olddb[128];
  bool dbchanged;
unknown's avatar
unknown committed
486
  DBUG_ENTER("db_create_routine");
487 488
  DBUG_PRINT("enter", ("type: %d name: %.*s",type,sp->m_name.length,
                       sp->m_name.str));
489

490 491 492 493 494 495 496 497
  dbchanged= FALSE;
  if ((ret= sp_use_new_db(thd, sp->m_db.str, olddb, sizeof(olddb),
			  0, &dbchanged)))
  {
    ret= SP_NO_DB_ERROR;
    goto done;
  }

498
  if (!(table= open_proc_table_for_update(thd)))
499 500
    ret= SP_OPEN_TABLE_FAILED;
  else
501
  {
502
    restore_record(table, s->default_values); // Get default values for fields
503 504
    strxmov(definer, thd->security_ctx->priv_user, "@",
            thd->security_ctx->priv_host, NullS);
505

506
    if (table->s->fields != MYSQL_PROC_FIELD_COUNT)
507 508 509 510
    {
      ret= SP_GET_FIELD_FAILED;
      goto done;
    }
511 512 513 514 515
    if (sp->m_name.length > table->field[MYSQL_PROC_FIELD_NAME]->field_length)
    {
      ret= SP_BAD_IDENTIFIER;
      goto done;
    }
516 517 518 519 520
    if (sp->m_body.length > table->field[MYSQL_PROC_FIELD_BODY]->field_length)
    {
      ret= SP_BODY_TOO_LONG;
      goto done;
    }
521 522
    table->field[MYSQL_PROC_FIELD_DB]->
      store(sp->m_db.str, sp->m_db.length, system_charset_info);
523 524 525 526 527 528
    table->field[MYSQL_PROC_FIELD_NAME]->
      store(sp->m_name.str, sp->m_name.length, system_charset_info);
    table->field[MYSQL_PROC_FIELD_TYPE]->
      store((longlong)type);
    table->field[MYSQL_PROC_FIELD_SPECIFIC_NAME]->
      store(sp->m_name.str, sp->m_name.length, system_charset_info);
529 530 531
    if (sp->m_chistics->daccess != SP_DEFAULT_ACCESS)
      table->field[MYSQL_PROC_FIELD_ACCESS]->
	store((longlong)sp->m_chistics->daccess);
532 533
    table->field[MYSQL_PROC_FIELD_DETERMINISTIC]->
      store((longlong)(sp->m_chistics->detistic ? 1 : 2));
534
    if (sp->m_chistics->suid != SP_IS_DEFAULT_SUID)
535 536 537 538
      table->field[MYSQL_PROC_FIELD_SECURITY_TYPE]->
	store((longlong)sp->m_chistics->suid);
    table->field[MYSQL_PROC_FIELD_PARAM_LIST]->
      store(sp->m_params.str, sp->m_params.length, system_charset_info);
unknown's avatar
unknown committed
539 540 541 542
    if (sp->m_type == TYPE_ENUM_FUNCTION)
    {
      String retstr(64);
      sp_returns_type(thd, retstr, sp);
543
      table->field[MYSQL_PROC_FIELD_RETURNS]->
unknown's avatar
unknown committed
544 545
	store(retstr.ptr(), retstr.length(), system_charset_info);
    }
546 547 548
    table->field[MYSQL_PROC_FIELD_BODY]->
      store(sp->m_body.str, sp->m_body.length, system_charset_info);
    table->field[MYSQL_PROC_FIELD_DEFINER]->
549
      store(definer, (uint)strlen(definer), system_charset_info);
550
    ((Field_timestamp *)table->field[MYSQL_PROC_FIELD_CREATED])->set_time();
551
    ((Field_timestamp *)table->field[MYSQL_PROC_FIELD_MODIFIED])->set_time();
552 553 554 555 556 557
    table->field[MYSQL_PROC_FIELD_SQL_MODE]->
      store((longlong)thd->variables.sql_mode);
    if (sp->m_chistics->comment.str)
      table->field[MYSQL_PROC_FIELD_COMMENT]->
	store(sp->m_chistics->comment.str, sp->m_chistics->comment.length,
	      system_charset_info);
558

unknown's avatar
merge  
unknown committed
559 560
    if ((sp->m_type == TYPE_ENUM_FUNCTION) &&
        !trust_function_creators && mysql_bin_log.is_open())
561 562 563 564
    {
      if (!sp->m_chistics->detistic)
      {
	/*
unknown's avatar
merge  
unknown committed
565
	  Note that this test is not perfect; one could use
566 567 568 569 570 571 572 573 574 575 576 577 578 579
	  a non-deterministic read-only function in an update statement.
	*/
	enum enum_sp_data_access access=
	  (sp->m_chistics->daccess == SP_DEFAULT_ACCESS) ?
	  SP_DEFAULT_ACCESS_MAPPING : sp->m_chistics->daccess;
	if (access == SP_CONTAINS_SQL ||
	    access == SP_MODIFIES_SQL_DATA)
	{
	  my_message(ER_BINLOG_UNSAFE_ROUTINE,
		     ER(ER_BINLOG_UNSAFE_ROUTINE), MYF(0));
	  ret= SP_INTERNAL_ERROR;
	  goto done;
	}
      }
580
      if (!(thd->security_ctx->master_access & SUPER_ACL))
581 582 583 584 585 586 587 588
      {
	my_message(ER_BINLOG_CREATE_ROUTINE_NEED_SUPER,
		   ER(ER_BINLOG_CREATE_ROUTINE_NEED_SUPER), MYF(0));
	ret= SP_INTERNAL_ERROR;
	goto done;
      }
    }

unknown's avatar
unknown committed
589
    ret= SP_OK;
590 591
    if (table->file->write_row(table->record[0]))
      ret= SP_WRITE_ROW_FAILED;
592 593 594 595 596 597 598 599
    else if (mysql_bin_log.is_open())
    {
      thd->clear_error();
      /* Such a statement can always go directly to binlog, no trans cache */
      Query_log_event qinfo(thd, thd->query, thd->query_length, 0, FALSE);
      mysql_bin_log.write(&qinfo);
    }

600 601
  }

602
done:
603
  close_thread_tables(thd);
604
  if (dbchanged)
605
    (void)mysql_change_db(thd, olddb, 1);
606 607
  DBUG_RETURN(ret);
}
608

unknown's avatar
unknown committed
609

610
static int
611
db_drop_routine(THD *thd, int type, sp_name *name)
612 613 614
{
  TABLE *table;
  int ret;
unknown's avatar
unknown committed
615
  DBUG_ENTER("db_drop_routine");
616
  DBUG_PRINT("enter", ("type: %d name: %.*s",
617
		       type, name->m_name.length, name->m_name.str));
618

619 620 621
  if (!(table= open_proc_table_for_update(thd)))
    DBUG_RETURN(SP_OPEN_TABLE_FAILED);
  if ((ret= db_find_routine_aux(thd, type, name, table)) == SP_OK)
622 623 624 625
  {
    if (table->file->delete_row(table->record[0]))
      ret= SP_DELETE_ROW_FAILED;
  }
626
  close_thread_tables(thd);
627 628 629
  DBUG_RETURN(ret);
}

unknown's avatar
unknown committed
630

unknown's avatar
unknown committed
631
static int
632
db_update_routine(THD *thd, int type, sp_name *name, st_sp_chistics *chistics)
unknown's avatar
unknown committed
633 634 635 636
{
  TABLE *table;
  int ret;
  bool opened;
unknown's avatar
unknown committed
637
  DBUG_ENTER("db_update_routine");
638
  DBUG_PRINT("enter", ("type: %d name: %.*s",
639
		       type, name->m_name.length, name->m_name.str));
unknown's avatar
unknown committed
640

641 642 643
  if (!(table= open_proc_table_for_update(thd)))
    DBUG_RETURN(SP_OPEN_TABLE_FAILED);
  if ((ret= db_find_routine_aux(thd, type, name, table)) == SP_OK)
unknown's avatar
unknown committed
644 645
  {
    store_record(table,record[1]);
unknown's avatar
unknown committed
646
    table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
unknown's avatar
unknown committed
647
    ((Field_timestamp *)table->field[MYSQL_PROC_FIELD_MODIFIED])->set_time();
648 649 650 651 652 653
    if (chistics->suid != SP_IS_DEFAULT_SUID)
      table->field[MYSQL_PROC_FIELD_SECURITY_TYPE]->
	store((longlong)chistics->suid);
    if (chistics->daccess != SP_DEFAULT_ACCESS)
      table->field[MYSQL_PROC_FIELD_ACCESS]->
	store((longlong)chistics->daccess);
654 655 656
    if (chistics->comment.str)
      table->field[MYSQL_PROC_FIELD_COMMENT]->store(chistics->comment.str,
						    chistics->comment.length,
unknown's avatar
unknown committed
657 658 659 660
						    system_charset_info);
    if ((table->file->update_row(table->record[1],table->record[0])))
      ret= SP_WRITE_ROW_FAILED;
  }
661
  close_thread_tables(thd);
unknown's avatar
unknown committed
662 663 664
  DBUG_RETURN(ret);
}

unknown's avatar
unknown committed
665

unknown's avatar
unknown committed
666 667 668 669 670 671 672 673 674 675
struct st_used_field
{
  const char *field_name;
  uint field_length;
  enum enum_field_types field_type;
  Field *field;
};

static struct st_used_field init_fields[]=
{
676
  { "Db",       NAME_LEN, MYSQL_TYPE_STRING,    0},
unknown's avatar
unknown committed
677 678
  { "Name",     NAME_LEN, MYSQL_TYPE_STRING,    0},
  { "Type",            9, MYSQL_TYPE_STRING,    0},
679
  { "Definer",        77, MYSQL_TYPE_STRING,    0},
unknown's avatar
unknown committed
680 681
  { "Modified",        0, MYSQL_TYPE_TIMESTAMP, 0},
  { "Created",         0, MYSQL_TYPE_TIMESTAMP, 0},
682
  { "Security_type",   1, MYSQL_TYPE_STRING,    0},
unknown's avatar
unknown committed
683 684 685 686
  { "Comment",  NAME_LEN, MYSQL_TYPE_STRING,    0},
  { 0,                 0, MYSQL_TYPE_STRING,    0}
};

unknown's avatar
unknown committed
687

688 689 690 691
static int
print_field_values(THD *thd, TABLE *table,
		   struct st_used_field *used_fields,
		   int type, const char *wild)
unknown's avatar
unknown committed
692 693 694 695 696
{
  Protocol *protocol= thd->protocol;

  if (table->field[MYSQL_PROC_FIELD_TYPE]->val_int() == type)
  {
697 698
    String db_string;
    String name_string;
unknown's avatar
unknown committed
699
    struct st_used_field *used_field= used_fields;
700

unknown's avatar
unknown committed
701
    if (get_field(thd->mem_root, used_field->field, &db_string))
702 703
      db_string.set_ascii("", 0);
    used_field+= 1;
unknown's avatar
unknown committed
704
    get_field(thd->mem_root, used_field->field, &name_string);
705 706

    if (!wild || !wild[0] || !wild_compare(name_string.ptr(), wild, 0))
unknown's avatar
unknown committed
707 708
    {
      protocol->prepare_for_resend();
709 710
      protocol->store(&db_string);
      protocol->store(&name_string);
unknown's avatar
unknown committed
711 712 713 714 715 716
      for (used_field++;
	   used_field->field_name;
	   used_field++)
      {
	switch (used_field->field_type) {
	case MYSQL_TYPE_TIMESTAMP:
717 718
	  {
	    TIME tmp_time;
719 720

	    bzero((char *)&tmp_time, sizeof(tmp_time));
721 722 723 724
	    ((Field_timestamp *) used_field->field)->get_time(&tmp_time);
	    protocol->store(&tmp_time);
	  }
	  break;
unknown's avatar
unknown committed
725
	default:
726
	  {
727
	    String tmp_string;
728

unknown's avatar
unknown committed
729
	    get_field(thd->mem_root, used_field->field, &tmp_string);
730
	    protocol->store(&tmp_string);
731 732
	  }
	  break;
unknown's avatar
unknown committed
733 734 735
	}
      }
      if (protocol->write())
736
	return SP_INTERNAL_ERROR;
unknown's avatar
unknown committed
737 738
    }
  }
739
  return SP_OK;
unknown's avatar
unknown committed
740 741
}

unknown's avatar
unknown committed
742

743
static int
unknown's avatar
unknown committed
744 745 746 747
db_show_routine_status(THD *thd, int type, const char *wild)
{
  TABLE *table;
  TABLE_LIST tables;
748
  int res;
unknown's avatar
unknown committed
749
  DBUG_ENTER("db_show_routine_status");
unknown's avatar
unknown committed
750 751 752

  memset(&tables, 0, sizeof(tables));
  tables.db= (char*)"mysql";
753
  tables.table_name= tables.alias= (char*)"proc";
unknown's avatar
unknown committed
754 755 756

  if (! (table= open_ltable(thd, &tables, TL_READ)))
  {
757 758
    res= SP_OPEN_TABLE_FAILED;
    goto done;
unknown's avatar
unknown committed
759 760 761 762 763 764
  }
  else
  {
    Item *item;
    List<Item> field_list;
    struct st_used_field *used_field;
765
    TABLE_LIST *leaves= 0;
unknown's avatar
unknown committed
766
    st_used_field used_fields[array_elements(init_fields)];
767

unknown's avatar
unknown committed
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
    memcpy((char*) used_fields, (char*) init_fields, sizeof(used_fields));
    /* Init header */
    for (used_field= &used_fields[0];
	 used_field->field_name;
	 used_field++)
    {
      switch (used_field->field_type) {
      case MYSQL_TYPE_TIMESTAMP:
	field_list.push_back(item=new Item_datetime(used_field->field_name));
	break;
      default:
	field_list.push_back(item=new Item_empty_string(used_field->field_name,
							used_field->
							field_length));
	break;
      }
    }
    /* Print header */
786 787
    if (thd->protocol->send_fields(&field_list, Protocol::SEND_NUM_ROWS |
                                                Protocol::SEND_EOF))
788 789
    {
      res= SP_INTERNAL_ERROR;
unknown's avatar
unknown committed
790
      goto err_case;
791
    }
unknown's avatar
unknown committed
792

unknown's avatar
VIEW  
unknown committed
793 794 795 796 797
    /*
      Init fields

      tables is not VIEW for sure => we can pass 0 as condition
    */
798 799
    thd->lex->select_lex.context.resolve_in_table_list_only(&tables);
    setup_tables(thd, &thd->lex->select_lex.context,
unknown's avatar
unknown committed
800
                 &thd->lex->select_lex.top_join_list,
801
                 &tables, 0, &leaves, FALSE);
unknown's avatar
unknown committed
802 803 804 805
    for (used_field= &used_fields[0];
	 used_field->field_name;
	 used_field++)
    {
806 807
      Item_field *field= new Item_field(&thd->lex->select_lex.context,
                                        "mysql", "proc",
unknown's avatar
unknown committed
808
					used_field->field_name);
809
      if (!field ||
unknown's avatar
unknown committed
810
          !(used_field->field= find_field_in_tables(thd, field, &tables, NULL,
811 812
						    0, REPORT_ALL_ERRORS, 1,
                                                    TRUE)))
813 814
      {
	res= SP_INTERNAL_ERROR;
unknown's avatar
unknown committed
815
	goto err_case1;
816
      }
unknown's avatar
unknown committed
817 818
    }

unknown's avatar
unknown committed
819
    table->file->ha_index_init(0);
820 821
    if ((res= table->file->index_first(table->record[0])))
    {
unknown's avatar
unknown committed
822
      res= (res == HA_ERR_END_OF_FILE) ? 0 : SP_INTERNAL_ERROR;
823 824 825
      goto err_case1;
    }
    if ((res= print_field_values(thd, table, used_fields, type, wild)))
unknown's avatar
unknown committed
826 827 828
      goto err_case1;
    while (!table->file->index_next(table->record[0]))
    {
829
      if ((res= print_field_values(thd, table, used_fields, type, wild)))
unknown's avatar
unknown committed
830 831
	goto err_case1;
    }
832
    res= SP_OK;
unknown's avatar
unknown committed
833
  }
834

unknown's avatar
unknown committed
835
err_case1:
unknown's avatar
unknown committed
836
  send_eof(thd);
unknown's avatar
unknown committed
837
err_case:
unknown's avatar
unknown committed
838
  table->file->ha_index_end();
unknown's avatar
unknown committed
839
  close_thread_tables(thd);
unknown's avatar
unknown committed
840
done:
841
  DBUG_RETURN(res);
unknown's avatar
unknown committed
842 843
}

844

845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
/* Drop all routines in database 'db' */
int
sp_drop_db_routines(THD *thd, char *db)
{
  TABLE *table;
  byte key[64];			// db
  uint keylen;
  int ret;
  DBUG_ENTER("sp_drop_db_routines");
  DBUG_PRINT("enter", ("db: %s", db));

  // Put the key used to read the row together
  keylen= strlen(db);
  if (keylen > 64)
    keylen= 64;
  memcpy(key, db, keylen);
  memset(key+keylen, (int)' ', 64-keylen); // Pad with space
  keylen= sizeof(key);

864 865 866
  ret= SP_OPEN_TABLE_FAILED;
  if (!(table= open_proc_table_for_update(thd)))
    goto err;
867 868

  ret= SP_OK;
unknown's avatar
unknown committed
869
  table->file->ha_index_init(0);
870 871 872 873 874 875
  if (! table->file->index_read(table->record[0],
				key, keylen, HA_READ_KEY_EXACT))
  {
    int nxtres;
    bool deleted= FALSE;

876 877
    do
    {
878 879 880 881 882
      if (! table->file->delete_row(table->record[0]))
	deleted= TRUE;		/* We deleted something */
      else
      {
	ret= SP_DELETE_ROW_FAILED;
883
	nxtres= 0;
884 885 886 887 888 889 890 891 892
	break;
      }
    } while (! (nxtres= table->file->index_next_same(table->record[0],
						     key, keylen)));
    if (nxtres != HA_ERR_END_OF_FILE)
      ret= SP_KEY_NOT_FOUND;
    if (deleted)
      sp_cache_invalidate();
  }
unknown's avatar
unknown committed
893
  table->file->ha_index_end();
894 895 896

  close_thread_tables(thd);

897
err:
898 899 900 901
  DBUG_RETURN(ret);
}


unknown's avatar
unknown committed
902 903 904
/*****************************************************************************
  PROCEDURE
******************************************************************************/
905

906
/*
907
  Obtain object representing stored procedure/function by its name from
908 909 910
  stored procedures cache and looking into mysql.proc if needed.

  SYNOPSIS
911
    sp_find_routine()
912
      thd        - thread context
913
      type       - type of object (TYPE_ENUM_FUNCTION or TYPE_ENUM_PROCEDURE)
914
      name       - name of procedure
915
      cp         - hash to look routine in
916 917 918 919 920 921 922 923
      cache_only - if true perform cache-only lookup
                   (Don't look in mysql.proc).

  RETURN VALUE
    Non-0 pointer to sp_head object for the procedure, or
    0 - in case of error.
*/

924
sp_head *
925 926
sp_find_routine(THD *thd, int type, sp_name *name, sp_cache **cp,
                bool cache_only)
927 928
{
  sp_head *sp;
929 930 931 932 933 934 935 936
  ulong depth= (type == TYPE_ENUM_PROCEDURE ?
                thd->variables.max_sp_recursion_depth :
                0);
  DBUG_ENTER("sp_find_routine");
  DBUG_PRINT("enter", ("name:  %.*s.%.*s, type: %d, cache only %d",
                       name->m_db.length, name->m_db.str,
                       name->m_name.length, name->m_name.str,
                       type, cache_only));
937

938
  if ((sp= sp_cache_lookup(cp, name)))
939
  {
940
    ulong level;
unknown's avatar
unknown committed
941 942
    sp_head *new_sp;
    const char *returns= "";
943
    char definer[USER_HOST_BUFF_SIZE];
unknown's avatar
unknown committed
944 945
    String retstr(64);

946 947 948 949 950 951 952 953 954 955
    DBUG_PRINT("info", ("found: 0x%lx", (ulong)sp));
    if (sp->m_first_free_instance)
    {
      DBUG_PRINT("info", ("first free: 0x%lx, level: %lu, flags %x",
                          (ulong)sp->m_first_free_instance,
                          sp->m_first_free_instance->m_recursion_level,
                          sp->m_first_free_instance->m_flags));
      DBUG_ASSERT(!(sp->m_first_free_instance->m_flags & sp_head::IS_INVOKED));
      if (sp->m_first_free_instance->m_recursion_level > depth)
      {
unknown's avatar
unknown committed
956
        sp->recursion_level_error(thd);
957 958 959 960 961 962 963
        DBUG_RETURN(0);
      }
      DBUG_RETURN(sp->m_first_free_instance);
    }
    level= sp->m_last_cached_sp->m_recursion_level + 1;
    if (level > depth)
    {
unknown's avatar
unknown committed
964
      sp->recursion_level_error(thd);
965 966
      DBUG_RETURN(0);
    }
unknown's avatar
unknown committed
967 968 969 970

    strxmov(definer, sp->m_definer_user.str, "@",
            sp->m_definer_host.str, NullS);
    if (type == TYPE_ENUM_FUNCTION)
971
    {
unknown's avatar
unknown committed
972 973 974 975 976 977 978 979 980 981 982 983 984
      sp_returns_type(thd, retstr, sp);
      returns= retstr.ptr();
    }
    if (db_load_routine(thd, type, name, &new_sp,
                        sp->m_sql_mode, sp->m_params.str, returns,
                        sp->m_body.str, *sp->m_chistics, definer,
                        sp->m_created, sp->m_modified) == SP_OK)
    {
      sp->m_last_cached_sp->m_next_cached_sp= new_sp;
      new_sp->m_recursion_level= level;
      new_sp->m_first_instance= sp;
      sp->m_last_cached_sp= sp->m_first_free_instance= new_sp;
      DBUG_PRINT("info", ("added level: 0x%lx, level: %lu, flags %x",
985 986
                          (ulong)new_sp, new_sp->m_recursion_level,
                          new_sp->m_flags));
unknown's avatar
unknown committed
987
      DBUG_RETURN(new_sp);
988
    }
unknown's avatar
unknown committed
989
    DBUG_RETURN(0);
990 991 992 993 994 995 996 997 998 999
  }
  if (!cache_only)
  {
    if (db_find_routine(thd, type, name, &sp) == SP_OK)
    {
      sp_cache_insert(cp, sp);
      DBUG_PRINT("info", ("added new: 0x%lx, level: %lu, flags %x",
                          (ulong)sp, sp->m_recursion_level,
                          sp->m_flags));
    }
1000
  }
1001 1002 1003
  DBUG_RETURN(sp);
}

unknown's avatar
unknown committed
1004

1005 1006 1007 1008
/*
  This is used by sql_acl.cc:mysql_routine_grant() and is used to find
  the routines in 'routines'.
*/
1009

1010
int
1011
sp_exist_routines(THD *thd, TABLE_LIST *routines, bool any, bool no_error)
1012
{
1013
  TABLE_LIST *routine;
1014 1015
  bool result= 0;
  DBUG_ENTER("sp_exists_routine");
1016
  for (routine= routines; routine; routine= routine->next_global)
1017 1018 1019 1020
  {
    sp_name *name;
    LEX_STRING lex_db;
    LEX_STRING lex_name;
1021 1022 1023 1024
    lex_db.length= strlen(routine->db);
    lex_name.length= strlen(routine->table_name);
    lex_db.str= thd->strmake(routine->db, lex_db.length);
    lex_name.str= thd->strmake(routine->table_name, lex_name.length);
1025 1026
    name= new sp_name(lex_db, lex_name);
    name->init_qname(thd);
1027 1028 1029 1030
    if (sp_find_routine(thd, TYPE_ENUM_PROCEDURE, name,
                        &thd->sp_proc_cache, FALSE) != NULL ||
        sp_find_routine(thd, TYPE_ENUM_FUNCTION, name,
                        &thd->sp_func_cache, FALSE) != NULL)
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
    {
      if (any)
        DBUG_RETURN(1);
      result= 1;
    }
    else if (!any)
    {
      if (!no_error)
      {
	my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "FUNCTION or PROCEDURE", 
1041
		 routine->table_name);
1042 1043 1044 1045 1046 1047 1048 1049 1050
	DBUG_RETURN(-1);
      }
      DBUG_RETURN(0);
    }
  }
  DBUG_RETURN(result);
}


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
/*
  Check if a routine exists in the mysql.proc table, without actually
  parsing the definition. (Used for dropping)

  SYNOPSIS
    sp_routine_exists_in_table()
      thd        - thread context
      name       - name of procedure

  RETURN VALUE
    0     - Success
    non-0 - Error;  SP_OPEN_TABLE_FAILED or SP_KEY_NOT_FOUND
*/

int
sp_routine_exists_in_table(THD *thd, int type, sp_name *name)
{
  TABLE *table;
  int ret;
  Open_tables_state open_tables_state_backup;

  if (!(table= open_proc_table_for_read(thd, &open_tables_state_backup)))
    ret= SP_OPEN_TABLE_FAILED;
  else
  {
    if ((ret= db_find_routine_aux(thd, type, name, table)) == SP_OK)
      ret= SP_OK;
    else
      ret= SP_KEY_NOT_FOUND;
    close_proc_table(thd, &open_tables_state_backup);
  }
  return ret;
}


1086
int
1087
sp_create_procedure(THD *thd, sp_head *sp)
1088
{
1089
  int ret;
1090
  DBUG_ENTER("sp_create_procedure");
1091
  DBUG_PRINT("enter", ("name: %.*s", sp->m_name.length, sp->m_name.str));
1092 1093 1094

  ret= db_create_routine(thd, TYPE_ENUM_PROCEDURE, sp);
  DBUG_RETURN(ret);
1095 1096
}

unknown's avatar
unknown committed
1097

1098
int
1099
sp_drop_procedure(THD *thd, sp_name *name)
1100
{
1101
  int ret;
1102
  DBUG_ENTER("sp_drop_procedure");
1103
  DBUG_PRINT("enter", ("name: %.*s", name->m_name.length, name->m_name.str));
1104

1105
  ret= db_drop_routine(thd, TYPE_ENUM_PROCEDURE, name);
unknown's avatar
unknown committed
1106
  if (!ret)
1107
    sp_cache_invalidate();
1108
  DBUG_RETURN(ret);
1109
}
1110

unknown's avatar
unknown committed
1111

unknown's avatar
unknown committed
1112
int
1113
sp_update_procedure(THD *thd, sp_name *name, st_sp_chistics *chistics)
unknown's avatar
unknown committed
1114
{
1115
  int ret;
unknown's avatar
unknown committed
1116
  DBUG_ENTER("sp_update_procedure");
1117
  DBUG_PRINT("enter", ("name: %.*s", name->m_name.length, name->m_name.str));
unknown's avatar
unknown committed
1118

1119
  ret= db_update_routine(thd, TYPE_ENUM_PROCEDURE, name, chistics);
unknown's avatar
unknown committed
1120
  if (!ret)
1121
    sp_cache_invalidate();
1122
  DBUG_RETURN(ret);
unknown's avatar
unknown committed
1123 1124
}

unknown's avatar
unknown committed
1125

unknown's avatar
unknown committed
1126
int
1127
sp_show_create_procedure(THD *thd, sp_name *name)
unknown's avatar
unknown committed
1128
{
unknown's avatar
unknown committed
1129
  sp_head *sp;
unknown's avatar
unknown committed
1130
  DBUG_ENTER("sp_show_create_procedure");
1131
  DBUG_PRINT("enter", ("name: %.*s", name->m_name.length, name->m_name.str));
unknown's avatar
unknown committed
1132

1133 1134
  if ((sp= sp_find_routine(thd, TYPE_ENUM_PROCEDURE, name,
                           &thd->sp_proc_cache, FALSE)))
1135 1136 1137 1138 1139
  {
    int ret= sp->show_create_procedure(thd);

    DBUG_RETURN(ret);
  }
unknown's avatar
unknown committed
1140

1141
  DBUG_RETURN(SP_KEY_NOT_FOUND);
unknown's avatar
unknown committed
1142 1143
}

unknown's avatar
unknown committed
1144

unknown's avatar
unknown committed
1145
int
1146
sp_show_status_procedure(THD *thd, const char *wild)
unknown's avatar
unknown committed
1147
{
1148
  int ret;
1149
  DBUG_ENTER("sp_show_status_procedure");
1150 1151 1152

  ret= db_show_routine_status(thd, TYPE_ENUM_PROCEDURE, wild);
  DBUG_RETURN(ret);
unknown's avatar
unknown committed
1153
}
1154

unknown's avatar
unknown committed
1155 1156 1157 1158

/*****************************************************************************
  FUNCTION
******************************************************************************/
1159 1160

int
1161
sp_create_function(THD *thd, sp_head *sp)
1162
{
1163
  int ret;
1164
  DBUG_ENTER("sp_create_function");
1165
  DBUG_PRINT("enter", ("name: %.*s", sp->m_name.length, sp->m_name.str));
1166

1167 1168
  ret= db_create_routine(thd, TYPE_ENUM_FUNCTION, sp);
  DBUG_RETURN(ret);
1169 1170
}

unknown's avatar
unknown committed
1171

1172
int
1173
sp_drop_function(THD *thd, sp_name *name)
1174
{
1175
  int ret;
1176
  DBUG_ENTER("sp_drop_function");
1177
  DBUG_PRINT("enter", ("name: %.*s", name->m_name.length, name->m_name.str));
1178

1179
  ret= db_drop_routine(thd, TYPE_ENUM_FUNCTION, name);
unknown's avatar
unknown committed
1180
  if (!ret)
1181
    sp_cache_invalidate();
1182
  DBUG_RETURN(ret);
1183
}
1184

unknown's avatar
unknown committed
1185

unknown's avatar
unknown committed
1186
int
1187
sp_update_function(THD *thd, sp_name *name, st_sp_chistics *chistics)
unknown's avatar
unknown committed
1188
{
1189
  int ret;
unknown's avatar
unknown committed
1190
  DBUG_ENTER("sp_update_procedure");
1191
  DBUG_PRINT("enter", ("name: %.*s", name->m_name.length, name->m_name.str));
unknown's avatar
unknown committed
1192

1193
  ret= db_update_routine(thd, TYPE_ENUM_FUNCTION, name, chistics);
unknown's avatar
unknown committed
1194
  if (!ret)
1195
    sp_cache_invalidate();
1196
  DBUG_RETURN(ret);
unknown's avatar
unknown committed
1197 1198
}

unknown's avatar
unknown committed
1199

unknown's avatar
unknown committed
1200
int
1201
sp_show_create_function(THD *thd, sp_name *name)
unknown's avatar
unknown committed
1202
{
unknown's avatar
unknown committed
1203
  sp_head *sp;
unknown's avatar
unknown committed
1204
  DBUG_ENTER("sp_show_create_function");
1205
  DBUG_PRINT("enter", ("name: %.*s", name->m_name.length, name->m_name.str));
unknown's avatar
unknown committed
1206

1207 1208
  if ((sp= sp_find_routine(thd, TYPE_ENUM_FUNCTION, name,
                           &thd->sp_func_cache, FALSE)))
1209 1210 1211 1212 1213
  {
    int ret= sp->show_create_function(thd);

    DBUG_RETURN(ret);
  }
1214
  DBUG_RETURN(SP_KEY_NOT_FOUND);
unknown's avatar
unknown committed
1215 1216
}

unknown's avatar
unknown committed
1217

unknown's avatar
unknown committed
1218
int
1219
sp_show_status_function(THD *thd, const char *wild)
unknown's avatar
unknown committed
1220
{
1221
  int ret;
1222
  DBUG_ENTER("sp_show_status_function");
1223 1224
  ret= db_show_routine_status(thd, TYPE_ENUM_FUNCTION, wild);
  DBUG_RETURN(ret);
unknown's avatar
unknown committed
1225 1226
}

unknown's avatar
unknown committed
1227

1228 1229 1230 1231 1232 1233 1234
/*
  Structure that represents element in the set of stored routines
  used by statement or routine.
*/
struct Sroutine_hash_entry;

struct Sroutine_hash_entry
1235
{
1236 1237 1238 1239 1240 1241 1242
  /* Set key consisting of one-byte routine type and quoted routine name. */
  LEX_STRING key;
  /*
    Next element in list linking all routines in set. See also comments
    for LEX::sroutine/sroutine_list and sp_head::m_sroutines.
  */
  Sroutine_hash_entry *next;
1243 1244 1245 1246 1247 1248
  /*
    Uppermost view which directly or indirectly uses this routine.
    0 if routine is not used in view. Note that it also can be 0 if
    statement uses routine both via view and directly.
  */
  TABLE_LIST *belong_to_view;
1249 1250 1251 1252 1253 1254 1255 1256
};


extern "C" byte* sp_sroutine_key(const byte *ptr, uint *plen, my_bool first)
{
  Sroutine_hash_entry *rn= (Sroutine_hash_entry *)ptr;
  *plen= rn->key.length;
  return (byte *)rn->key.str;
1257 1258
}

unknown's avatar
unknown committed
1259

1260
/*
1261 1262 1263 1264
  Check if
   - current statement (the one in thd->lex) needs table prelocking
   - first routine in thd->lex->sroutines_list needs to execute its body in
     prelocked mode.
1265 1266

  SYNOPSIS
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
    sp_get_prelocking_info()
      thd                  Current thread, thd->lex is the statement to be
                           checked.
      need_prelocking      OUT TRUE  - prelocked mode should be activated
                                       before executing the statement
                               FALSE - Don't activate prelocking 
      first_no_prelocking  OUT TRUE  - Tables used by first routine in
                                       thd->lex->sroutines_list should be
                                       prelocked.
                               FALSE - Otherwise.
1277 1278 1279 1280 1281 1282
  NOTES 
    This function assumes that for any "CALL proc(...)" statement routines_list 
    will have 'proc' as first element (it may have several, consider e.g.
    "proc(sp_func(...)))". This property is currently guaranted by the parser.
*/

1283 1284
void sp_get_prelocking_info(THD *thd, bool *need_prelocking, 
                            bool *first_no_prelocking)
1285 1286
{
  Sroutine_hash_entry *routine;
1287
  routine= (Sroutine_hash_entry*)thd->lex->sroutines_list.first;
1288

1289 1290
  DBUG_ASSERT(routine);
  bool first_is_procedure= (routine->key.str[0] == TYPE_ENUM_PROCEDURE);
1291

1292 1293
  *first_no_prelocking= first_is_procedure;
  *need_prelocking= !first_is_procedure || test(routine->next);
1294 1295 1296
}


1297 1298 1299 1300 1301 1302
/*
  Auxilary function that adds new element to the set of stored routines
  used by statement.

  SYNOPSIS
    add_used_routine()
1303 1304 1305 1306 1307
      lex             LEX representing statement
      arena           Arena in which memory for new element will be allocated
      key             Key for the hash representing set
      belong_to_view  Uppermost view which uses this routine
                      (0 if routine is not used by view)
1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328

  NOTES
    Will also add element to end of 'LEX::sroutines_list' list.

    In case when statement uses stored routines but does not need
    prelocking (i.e. it does not use any tables) we will access the
    elements of LEX::sroutines set on prepared statement re-execution.
    Because of this we have to allocate memory for both hash element
    and copy of its key in persistent arena.

  TODO
    When we will got rid of these accesses on re-executions we will be
    able to allocate memory for hash elements in non-persitent arena
    and directly use key values from sp_head::m_sroutines sets instead
    of making their copies.

  RETURN VALUE
    TRUE  - new element was added.
    FALSE - element was not added (because it is already present in the set).
*/

1329
static bool add_used_routine(LEX *lex, Query_arena *arena,
1330 1331
                             const LEX_STRING *key,
                             TABLE_LIST *belong_to_view)
1332
{
1333
  if (!hash_search(&lex->sroutines, (byte *)key->str, key->length))
1334
  {
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
    Sroutine_hash_entry *rn=
      (Sroutine_hash_entry *)arena->alloc(sizeof(Sroutine_hash_entry) +
                                          key->length);
    if (!rn)              // OOM. Error will be reported using fatal_error().
      return FALSE;
    rn->key.length= key->length;
    rn->key.str= (char *)rn + sizeof(Sroutine_hash_entry);
    memcpy(rn->key.str, key->str, key->length);
    my_hash_insert(&lex->sroutines, (byte *)rn);
    lex->sroutines_list.link_in_list((byte *)rn, (byte **)&rn->next);
1345
    rn->belong_to_view= belong_to_view;
1346
    return TRUE;
1347
  }
1348
  return FALSE;
1349 1350
}

unknown's avatar
unknown committed
1351

1352
/*
1353 1354
  Add routine which is explicitly used by statement to the set of stored
  routines used by this statement.
1355 1356

  SYNOPSIS
1357 1358 1359 1360 1361 1362 1363 1364
    sp_add_used_routine()
      lex     - LEX representing statement
      arena   - arena in which memory for new element of the set
                will be allocated
      rt      - routine name
      rt_type - routine type (one of TYPE_ENUM_PROCEDURE/...)

  NOTES
1365 1366
    Will also add element to end of 'LEX::sroutines_list' list (and will
    take into account that this is explicitly used routine).
1367 1368 1369 1370 1371

    To be friendly towards prepared statements one should pass
    persistent arena as second argument.
*/

1372
void sp_add_used_routine(LEX *lex, Query_arena *arena,
1373 1374 1375
                         sp_name *rt, char rt_type)
{
  rt->set_routine_type(rt_type);
1376
  (void)add_used_routine(lex, arena, &rt->m_sroutines_key, 0);
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
  lex->sroutines_list_own_last= lex->sroutines_list.next;
  lex->sroutines_list_own_elements= lex->sroutines_list.elements;
}


/*
  Remove routines which are only indirectly used by statement from
  the set of routines used by this statement.

  SYNOPSIS
    sp_remove_not_own_routines()
      lex  LEX representing statement
*/

void sp_remove_not_own_routines(LEX *lex)
{
  Sroutine_hash_entry *not_own_rt, *next_rt;
  for (not_own_rt= *(Sroutine_hash_entry **)lex->sroutines_list_own_last;
       not_own_rt; not_own_rt= next_rt)
  {
    /*
      It is safe to obtain not_own_rt->next after calling hash_delete() now
      but we want to be more future-proof.
    */
    next_rt= not_own_rt->next;
    hash_delete(&lex->sroutines, (byte *)not_own_rt);
  }

  *(Sroutine_hash_entry **)lex->sroutines_list_own_last= NULL;
  lex->sroutines_list.next= lex->sroutines_list_own_last;
  lex->sroutines_list.elements= lex->sroutines_list_own_elements;
1408 1409 1410 1411 1412 1413 1414 1415 1416
}


/*
  Merge contents of two hashes representing sets of routines used
  by statements or by other routines.

  SYNOPSIS
    sp_update_sp_used_routines()
1417 1418 1419
      dst - hash to which elements should be added
      src - hash from which elements merged

1420 1421 1422 1423 1424 1425 1426
  NOTE
    This procedure won't create new Sroutine_hash_entry objects,
    instead it will simply add elements from source to destination
    hash. Thus time of life of elements in destination hash becomes
    dependant on time of life of elements from source hash. It also
    won't touch lists linking elements in source and destination
    hashes.
1427 1428
*/

1429
void sp_update_sp_used_routines(HASH *dst, HASH *src)
1430
{
1431
  for (uint i=0 ; i < src->records ; i++)
1432
  {
1433 1434 1435
    Sroutine_hash_entry *rt= (Sroutine_hash_entry *)hash_element(src, i);
    if (!hash_search(dst, (byte *)rt->key.str, rt->key.length))
      my_hash_insert(dst, (byte *)rt);
1436 1437 1438
  }
}

unknown's avatar
unknown committed
1439

1440
/*
1441 1442
  Add contents of hash representing set of routines to the set of
  routines used by statement.
1443 1444

  SYNOPSIS
1445
    sp_update_stmt_used_routines()
1446 1447 1448 1449
      thd             Thread context
      lex             LEX representing statement
      src             Hash representing set from which routines will be added
      belong_to_view  Uppermost view which uses these routines, 0 if none
1450 1451 1452 1453 1454

  NOTE
    It will also add elements to end of 'LEX::sroutines_list' list.
*/

1455 1456 1457
static void
sp_update_stmt_used_routines(THD *thd, LEX *lex, HASH *src,
                             TABLE_LIST *belong_to_view)
1458 1459 1460 1461
{
  for (uint i=0 ; i < src->records ; i++)
  {
    Sroutine_hash_entry *rt= (Sroutine_hash_entry *)hash_element(src, i);
1462
    (void)add_used_routine(lex, thd->stmt_arena, &rt->key, belong_to_view);
1463 1464 1465 1466
  }
}


1467 1468 1469 1470 1471 1472
/*
  Add contents of list representing set of routines to the set of
  routines used by statement.

  SYNOPSIS
    sp_update_stmt_used_routines()
1473 1474 1475 1476
      thd             Thread context
      lex             LEX representing statement
      src             List representing set from which routines will be added
      belong_to_view  Uppermost view which uses these routines, 0 if none
1477 1478 1479 1480 1481

  NOTE
    It will also add elements to end of 'LEX::sroutines_list' list.
*/

1482 1483
static void sp_update_stmt_used_routines(THD *thd, LEX *lex, SQL_LIST *src,
                                         TABLE_LIST *belong_to_view)
1484 1485 1486
{
  for (Sroutine_hash_entry *rt= (Sroutine_hash_entry *)src->first;
       rt; rt= rt->next)
1487
    (void)add_used_routine(lex, thd->stmt_arena, &rt->key, belong_to_view);
1488 1489 1490
}


1491 1492 1493 1494 1495 1496 1497
/*
  Cache sub-set of routines used by statement, add tables used by these
  routines to statement table list. Do the same for all routines used
  by these routines.

  SYNOPSIS
    sp_cache_routines_and_add_tables_aux()
1498 1499 1500 1501 1502 1503 1504
      thd              - thread context
      lex              - LEX representing statement
      start            - first routine from the list of routines to be cached
                         (this list defines mentioned sub-set).
      first_no_prelock - If true, don't add tables or cache routines used by
                         the body of the first routine (i.e. *start)
                         will be executed in non-prelocked mode.
1505
      tabs_changed     - Set to TRUE some tables were added, FALSE otherwise
1506 1507 1508 1509
  NOTE
    If some function is missing this won't be reported here.
    Instead this fact will be discovered during query execution.

1510
  RETURN VALUE
1511 1512
     0     - success
     non-0 - failure
1513 1514
*/

1515
static int
1516
sp_cache_routines_and_add_tables_aux(THD *thd, LEX *lex,
1517
                                     Sroutine_hash_entry *start, 
1518
                                     bool first_no_prelock, bool *tabs_changed)
1519
{
1520
  int ret= 0;
1521
  bool tabschnd= 0;             /* Set if tables changed */
1522
  bool first= TRUE;
1523
  DBUG_ENTER("sp_cache_routines_and_add_tables_aux");
1524

1525
  for (Sroutine_hash_entry *rt= start; rt; rt= rt->next)
1526
  {
1527 1528 1529
    sp_name name(rt->key.str, rt->key.length);
    int type= rt->key.str[0];
    sp_head *sp;
1530

1531 1532 1533
    if (!(sp= sp_cache_lookup((type == TYPE_ENUM_FUNCTION ?
                              &thd->sp_func_cache : &thd->sp_proc_cache),
                              &name)))
1534
    {
1535 1536 1537 1538 1539 1540 1541
      name.m_name.str= strchr(name.m_qname.str, '.');
      name.m_db.length= name.m_name.str - name.m_qname.str;
      name.m_db.str= strmake_root(thd->mem_root, name.m_qname.str,
                                  name.m_db.length);
      name.m_name.str+= 1;
      name.m_name.length= name.m_qname.length - name.m_db.length - 1;

1542
      switch ((ret= db_find_routine(thd, type, &name, &sp)))
1543
      {
1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564
      case SP_OK:
        {
          if (type == TYPE_ENUM_FUNCTION)
            sp_cache_insert(&thd->sp_func_cache, sp);
          else
            sp_cache_insert(&thd->sp_proc_cache, sp);
        }
        break;
      case SP_KEY_NOT_FOUND:
        ret= SP_OK;
        break;
      case SP_OPEN_TABLE_FAILED:
        /*
          Force it to attempt opening it again on subsequent calls;
          otherwise we will get one error message the first time, and
          then ER_SP_PROC_TABLE_CORRUPT (below) on subsequent tries.
        */
        mysql_proc_table_exists= 1;
        /* Fall through */
      default:
        /*
1565 1566 1567 1568 1569 1570
          Any error when loading an existing routine is either some problem
          with the mysql.proc table, or a parse error because the contents
          has been tampered with (in which case we clear that error).
        */
        if (ret == SP_PARSE_ERROR)
          thd->clear_error();
1571 1572 1573 1574 1575
        /*
          If we cleared the parse error, or when db_find_routine() flagged
          an error with it's return value without calling my_error(), we
          set the generic "mysql.proc table corrupt" error here.
         */
1576 1577 1578 1579 1580 1581 1582 1583 1584
        if (!thd->net.report_error)
        {
          char n[NAME_LEN*2+2];

          /* m_qname.str is not always \0 terminated */
          memcpy(n, name.m_qname.str, name.m_qname.length);
          n[name.m_qname.length]= '\0';
          my_error(ER_SP_PROC_TABLE_CORRUPT, MYF(0), n, ret);
        }
1585
        break;
1586 1587 1588 1589
      }
    }
    if (sp)
    {
1590 1591
      if (!(first && first_no_prelock))
      {
1592 1593
        sp_update_stmt_used_routines(thd, lex, &sp->m_sroutines,
                                     rt->belong_to_view);
1594
        tabschnd|=
1595 1596
          sp->add_used_tables_to_table_list(thd, &lex->query_tables_last,
                                            rt->belong_to_view);
1597
      }
1598
    }
1599
    first= FALSE;
1600
  }
1601 1602
  if (tabs_changed)             /* it can be NULL  */
    *tabs_changed= tabschnd;
1603
  DBUG_RETURN(ret);
1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
}


/*
  Cache all routines from the set of used by statement, add tables used
  by those routines to statement table list. Do the same for all routines
  used by those routines.

  SYNOPSIS
    sp_cache_routines_and_add_tables()
1614 1615 1616 1617
      thd              - thread context
      lex              - LEX representing statement
      first_no_prelock - If true, don't add tables or cache routines used by
                         the body of the first routine (i.e. *start)
1618
      tabs_changed     - Set to TRUE some tables were added, FALSE otherwise
1619
                         
1620
  RETURN VALUE
1621 1622
     0     - success
     non-0 - failure
1623 1624
*/

1625 1626 1627
int
sp_cache_routines_and_add_tables(THD *thd, LEX *lex, bool first_no_prelock,
                                 bool *tabs_changed)
1628 1629
{
  return sp_cache_routines_and_add_tables_aux(thd, lex,
1630
           (Sroutine_hash_entry *)lex->sroutines_list.first,
1631
           first_no_prelock, tabs_changed);
1632 1633 1634 1635 1636 1637 1638 1639 1640 1641
}


/*
  Add all routines used by view to the set of routines used by statement.
  Add tables used by those routines to statement table list. Do the same
  for all routines used by these routines.

  SYNOPSIS
    sp_cache_routines_and_add_tables_for_view()
1642 1643 1644
      thd   Thread context
      lex   LEX representing statement
      view  Table list element representing view
1645

1646
  RETURN VALUE
1647 1648
     0     - success
     non-0 - failure
1649 1650
*/

1651
int
1652
sp_cache_routines_and_add_tables_for_view(THD *thd, LEX *lex, TABLE_LIST *view)
1653 1654 1655
{
  Sroutine_hash_entry **last_cached_routine_ptr=
                          (Sroutine_hash_entry **)lex->sroutines_list.next;
1656 1657
  sp_update_stmt_used_routines(thd, lex, &view->view->sroutines_list,
                               view->top_table());
1658 1659 1660
  return sp_cache_routines_and_add_tables_aux(thd, lex, 
                                              *last_cached_routine_ptr, FALSE,
                                              NULL);
1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
}


/*
  Add triggers for table to the set of routines used by statement.
  Add tables used by them to statement table list. Do the same for
  all implicitly used routines.

  SYNOPSIS
    sp_cache_routines_and_add_tables_for_triggers()
1671 1672 1673
      thd    thread context
      lex    LEX respresenting statement
      table  Table list element for table with trigger
1674 1675

  RETURN VALUE
1676 1677
     0     - success
     non-0 - failure
1678 1679
*/

1680
int
1681
sp_cache_routines_and_add_tables_for_triggers(THD *thd, LEX *lex,
1682
                                              TABLE_LIST *table)
1683
{
1684
  int ret= 0;
1685 1686 1687
  Table_triggers_list *triggers= table->table->triggers;
  if (add_used_routine(lex, thd->stmt_arena, &triggers->sroutines_key,
                       table->belong_to_view))
1688 1689 1690
  {
    Sroutine_hash_entry **last_cached_routine_ptr=
                            (Sroutine_hash_entry **)lex->sroutines_list.next;
1691
    for (int i= 0; i < (int)TRG_EVENT_MAX; i++)
unknown's avatar
unknown committed
1692
    {
1693
      for (int j= 0; j < (int)TRG_ACTION_MAX; j++)
unknown's avatar
unknown committed
1694
      {
1695
        if (triggers->bodies[i][j])
1696
        {
1697 1698 1699
          (void)triggers->bodies[i][j]->
                add_used_tables_to_table_list(thd, &lex->query_tables_last,
                                              table->belong_to_view);
1700
          sp_update_stmt_used_routines(thd, lex,
1701 1702
                                       &triggers->bodies[i][j]->m_sroutines,
                                       table->belong_to_view);
1703
        }
unknown's avatar
unknown committed
1704 1705
      }
    }
1706 1707 1708
    ret= sp_cache_routines_and_add_tables_aux(thd, lex,
                                              *last_cached_routine_ptr, 
                                              FALSE, NULL);
1709
  }
1710
  return ret;
1711
}
1712

1713

1714 1715 1716 1717 1718 1719
/*
 * Generates the CREATE... string from the table information.
 * Returns TRUE on success, FALSE on (alloc) failure.
 */
static bool
create_string(THD *thd, String *buf,
1720
	      int type,
1721
	      sp_name *name,
1722 1723 1724 1725 1726
	      const char *params, ulong paramslen,
	      const char *returns, ulong returnslen,
	      const char *body, ulong bodylen,
	      st_sp_chistics *chistics)
{
1727 1728 1729 1730
  /* Make some room to begin with */
  if (buf->alloc(100 + name->m_qname.length + paramslen + returnslen + bodylen +
		 chistics->comment.length))
    return FALSE;
unknown's avatar
unknown committed
1731

unknown's avatar
merge  
unknown committed
1732
  buf->append(STRING_WITH_LEN("CREATE "));
1733
  if (type == TYPE_ENUM_FUNCTION)
unknown's avatar
merge  
unknown committed
1734
    buf->append(STRING_WITH_LEN("FUNCTION "));
1735
  else
unknown's avatar
merge  
unknown committed
1736
    buf->append(STRING_WITH_LEN("PROCEDURE "));
1737 1738 1739 1740 1741 1742
  append_identifier(thd, buf, name->m_name.str, name->m_name.length);
  buf->append('(');
  buf->append(params, paramslen);
  buf->append(')');
  if (type == TYPE_ENUM_FUNCTION)
  {
unknown's avatar
merge  
unknown committed
1743
    buf->append(STRING_WITH_LEN(" RETURNS "));
1744 1745 1746
    buf->append(returns, returnslen);
  }
  buf->append('\n');
1747 1748
  switch (chistics->daccess) {
  case SP_NO_SQL:
unknown's avatar
merge  
unknown committed
1749
    buf->append(STRING_WITH_LEN("    NO SQL\n"));
1750 1751
    break;
  case SP_READS_SQL_DATA:
unknown's avatar
merge  
unknown committed
1752
    buf->append(STRING_WITH_LEN("    READS SQL DATA\n"));
1753 1754
    break;
  case SP_MODIFIES_SQL_DATA:
unknown's avatar
merge  
unknown committed
1755
    buf->append(STRING_WITH_LEN("    MODIFIES SQL DATA\n"));
1756
    break;
unknown's avatar
unknown committed
1757 1758 1759 1760
  case SP_DEFAULT_ACCESS:
  case SP_CONTAINS_SQL:
    /* Do nothing */
    break;
1761
  }
1762
  if (chistics->detistic)
unknown's avatar
merge  
unknown committed
1763
    buf->append(STRING_WITH_LEN("    DETERMINISTIC\n"));
1764
  if (chistics->suid == SP_IS_NOT_SUID)
unknown's avatar
merge  
unknown committed
1765
    buf->append(STRING_WITH_LEN("    SQL SECURITY INVOKER\n"));
1766
  if (chistics->comment.length)
unknown's avatar
unknown committed
1767
  {
unknown's avatar
merge  
unknown committed
1768
    buf->append(STRING_WITH_LEN("    COMMENT "));
1769 1770
    append_unescaped(buf, chistics->comment.str, chistics->comment.length);
    buf->append('\n');
unknown's avatar
unknown committed
1771
  }
1772 1773
  buf->append(body, bodylen);
  return TRUE;
1774
}
1775 1776 1777 1778 1779 1780 1781 1782


//
// Utilities...
//

int
sp_use_new_db(THD *thd, char *newdb, char *olddb, uint olddblen,
1783
	      bool no_access_check, bool *dbchangedp)
1784 1785 1786 1787 1788
{
  bool changeit;
  DBUG_ENTER("sp_use_new_db");
  DBUG_PRINT("enter", ("newdb: %s", newdb));

1789 1790
  if (! newdb)
    newdb= (char *)"";
1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810
  if (thd->db && thd->db[0])
  {
    if (my_strcasecmp(system_charset_info, thd->db, newdb) == 0)
      changeit= 0;
    else
    {
      changeit= 1;
      strnmov(olddb, thd->db, olddblen);
    }
  }
  else
  {				// thd->db empty
    if (newdb[0])
      changeit= 1;
    else
      changeit= 0;
    olddb[0] = '\0';
  }
  if (!changeit)
  {
1811
    *dbchangedp= FALSE;
1812 1813 1814 1815
    DBUG_RETURN(0);
  }
  else
  {
1816
    int ret= mysql_change_db(thd, newdb, no_access_check);
1817

1818 1819
    if (! ret)
      *dbchangedp= TRUE;
1820 1821 1822
    DBUG_RETURN(ret);
  }
}