sql_class.cc 62 KB
Newer Older
unknown's avatar
unknown committed
1
/* Copyright (C) 2000-2006 MySQL AB
unknown's avatar
unknown committed
2

unknown's avatar
unknown committed
3 4
   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
unknown's avatar
unknown committed
5
   the Free Software Foundation; version 2 of the License.
unknown's avatar
unknown committed
6

unknown's avatar
unknown committed
7 8 9 10
   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.
unknown's avatar
unknown committed
11

unknown's avatar
unknown committed
12 13 14 15 16 17 18 19 20 21 22 23
   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 */


/*****************************************************************************
**
** This file implements classes defined in sql_class.h
** Especially the classes to handle a result from a select
**
*****************************************************************************/

24
#ifdef USE_PRAGMA_IMPLEMENTATION
unknown's avatar
unknown committed
25 26 27 28 29 30
#pragma implementation				// gcc: Class implementation
#endif

#include "mysql_priv.h"
#include <m_ctype.h>
#include <sys/stat.h>
31
#include <thr_alarm.h>
unknown's avatar
unknown committed
32 33 34
#ifdef	__WIN__
#include <io.h>
#endif
35
#include <mysys_err.h>
unknown's avatar
unknown committed
36

unknown's avatar
unknown committed
37 38
#include "sp_rcontext.h"
#include "sp_cache.h"
39

40 41 42 43 44
/*
  The following is used to initialise Table_ident with a internal
  table name
*/
char internal_table_name[2]= "*";
45
char empty_c_string[1]= {0};    /* used for not defined db */
46

47 48
const char * const THD::DEFAULT_WHERE= "field list";

49

unknown's avatar
unknown committed
50 51 52 53
/*****************************************************************************
** Instansiate templates
*****************************************************************************/

54
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
unknown's avatar
unknown committed
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
/* Used templates */
template class List<Key>;
template class List_iterator<Key>;
template class List<key_part_spec>;
template class List_iterator<key_part_spec>;
template class List<Alter_drop>;
template class List_iterator<Alter_drop>;
template class List<Alter_column>;
template class List_iterator<Alter_column>;
#endif

/****************************************************************************
** User variables
****************************************************************************/

70 71
extern "C" byte *get_var_key(user_var_entry *entry, uint *length,
			     my_bool not_used __attribute__((unused)))
unknown's avatar
unknown committed
72 73 74 75 76
{
  *length=(uint) entry->name.length;
  return (byte*) entry->name.str;
}

77
extern "C" void free_user_var(user_var_entry *entry)
unknown's avatar
unknown committed
78 79 80 81 82 83 84
{
  char *pos= (char*) entry+ALIGN_SIZE(sizeof(*entry));
  if (entry->value && entry->value != pos)
    my_free(entry->value, MYF(0));
  my_free((char*) entry,MYF(0));
}

85 86 87 88 89
bool key_part_spec::operator==(const key_part_spec& other) const
{
  return length == other.length && !strcmp(field_name, other.field_name);
}

90 91

/*
92
  Test if a foreign key (= generated key) is a prefix of the given key
93 94 95 96 97 98 99 100 101 102 103 104 105 106
  (ignoring key name, key type and order of columns)

  NOTES:
    This is only used to test if an index for a FOREIGN KEY exists

  IMPLEMENTATION
    We only compare field names

  RETURN
    0	Generated key is a prefix of other key
    1	Not equal
*/

bool foreign_key_prefix(Key *a, Key *b)
107
{
108 109 110 111
  /* Ensure that 'a' is the generated key */
  if (a->generated)
  {
    if (b->generated && a->columns.elements > b->columns.elements)
112
      swap_variables(Key*, a, b);               // Put shorter key in 'a'
113 114
  }
  else
115
  {
116 117
    if (!b->generated)
      return TRUE;                              // No foreign key
118
    swap_variables(Key*, a, b);                 // Put generated key in 'a'
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
  }

  /* Test if 'a' is a prefix of 'b' */
  if (a->columns.elements > b->columns.elements)
    return TRUE;                                // Can't be prefix

  List_iterator<key_part_spec> col_it1(a->columns);
  List_iterator<key_part_spec> col_it2(b->columns);
  const key_part_spec *col1, *col2;

#ifdef ENABLE_WHEN_INNODB_CAN_HANDLE_SWAPED_FOREIGN_KEY_COLUMNS
  while ((col1= col_it1++))
  {
    bool found= 0;
    col_it2.rewind();
    while ((col2= col_it2++))
135
    {
136 137 138 139 140
      if (*col1 == *col2)
      {
        found= TRUE;
	break;
      }
141
    }
142 143 144 145 146 147 148 149 150 151
    if (!found)
      return TRUE;                              // Error
  }
  return FALSE;                                 // Is prefix
#else
  while ((col1= col_it1++))
  {
    col2= col_it2++;
    if (!(*col1 == *col2))
      return TRUE;
152
  }
153 154
  return FALSE;                                 // Is prefix
#endif
155 156 157
}


unknown's avatar
unknown committed
158 159 160
/****************************************************************************
** Thread specific functions
****************************************************************************/
161

162 163
Open_tables_state::Open_tables_state(ulong version_arg)
  :version(version_arg)
164 165 166 167 168
{
  reset_open_tables_state();
}


unknown's avatar
unknown committed
169

170
THD::THD()
171 172
   :Statement(&main_lex, &main_mem_root, CONVENTIONAL_EXECUTION,
              /* statement id */ 0),
173
   Open_tables_state(refresh_version),
174
   lock_id(&main_lock_id),
175
   user_time(0), in_sub_stmt(0), global_read_lock(0), is_fatal_error(0),
176
   rand_used(0), time_zone_used(0),
177 178
   last_insert_id_used(0), last_insert_id_used_bin_log(0), insert_id_used(0),
   clear_next_insert_id(0), in_lock_tables(0), bootstrap(0),
179
   derived_tables_processing(FALSE), spcont(NULL), m_lip(NULL)
unknown's avatar
unknown committed
180
{
181 182
  ulong tmp;

183 184 185 186 187 188
  /*
    Pass nominal parameters to init_alloc_root only to ensure that
    the destructor works OK in case of an error. The main_mem_root
    will be re-initialized in init_for_queries().
  */
  init_sql_alloc(&main_mem_root, ALLOC_ROOT_MIN_BLOCK_SIZE, 0);
unknown's avatar
unknown committed
189
  stmt_arena= this;
190
  thread_stack= 0;
191
  db= 0;
192
  catalog= (char*)"std"; // the only catalog we have for now
193 194
  main_security_ctx.init();
  security_ctx= &main_security_ctx;
unknown's avatar
unknown committed
195
  locked=some_tables_deleted=no_errors=password= 0;
unknown's avatar
unknown committed
196
  query_start_used= 0;
197
  count_cuted_fields= CHECK_FIELD_IGNORE;
unknown's avatar
SCRUM  
unknown committed
198
  killed= NOT_KILLED;
199
  db_length= col_access=0;
200
  query_error= tmp_table_used= thread_specific_used= 0;
unknown's avatar
unknown committed
201
  next_insert_id=last_insert_id=0;
202
  hash_clear(&handler_tables_hash);
unknown's avatar
unknown committed
203
  tmp_table=0;
204
  used_tables=0;
205
  cuted_fields= sent_row_count= 0L;
206
  limit_found_rows= 0;
207
  statement_id_counter= 0UL;
208
  // Must be reset to handle error with THD's created for init of mysqld
unknown's avatar
unknown committed
209
  lex->current_select= 0;
unknown's avatar
unknown committed
210
  start_time=(time_t) 0;
211
  time_after_lock=(time_t) 0;
unknown's avatar
unknown committed
212
  current_linfo =  0;
213
  slave_thread = 0;
214
  thread_id= 0;
215
  one_shot_set= 0;
216
  file_id = 0;
217
  query_id= 0;
218
  warn_id= 0;
219
  db_charset= global_system_variables.collation_database;
220
  bzero(ha_data, sizeof(ha_data));
unknown's avatar
unknown committed
221
  mysys_var=0;
222
  binlog_evt_union.do_union= FALSE;
223 224
#ifndef DBUG_OFF
  dbug_sentry=THD_SENTRY_MAGIC;
225
#endif
226
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
227
  net.vio=0;
228
#endif
229
  client_capabilities= 0;                       // minimalistic client
230
  net.last_error[0]=0;                          // If error on boot
231
#ifdef HAVE_QUERY_CACHE
232
  query_cache_init_query(&net);                 // If error on boot
233
#endif
unknown's avatar
unknown committed
234
  ull=0;
235
  system_thread= cleanup_done= abort_on_warning= no_warnings_for_error= 0;
236
  peer_port= 0;					// For SHOW PROCESSLIST
unknown's avatar
unknown committed
237 238 239 240 241
#ifdef	__WIN__
  real_id = 0;
#endif
#ifdef SIGNAL_WITH_VIO_CLOSE
  active_vio = 0;
242
#endif
243
  pthread_mutex_init(&LOCK_delete, MY_MUTEX_INIT_FAST);
unknown's avatar
unknown committed
244 245 246

  /* Variables with default values */
  proc_info="login";
247
  where= THD::DEFAULT_WHERE;
unknown's avatar
unknown committed
248
  server_id = ::server_id;
249
  slave_net = 0;
unknown's avatar
unknown committed
250
  command=COM_CONNECT;
unknown's avatar
unknown committed
251
  *scramble= '\0';
unknown's avatar
unknown committed
252

unknown's avatar
unknown committed
253
  init();
unknown's avatar
unknown committed
254
  /* Initialize sub structures */
255
  init_sql_alloc(&warn_root, WARN_ALLOC_BLOCK_SIZE, WARN_ALLOC_PREALLOC_SIZE);
256
  user_connect=(USER_CONN *)0;
257
  hash_init(&user_vars, system_charset_info, USER_VARS_HASH_SIZE, 0, 0,
unknown's avatar
unknown committed
258
	    (hash_get_key) get_var_key,
259
	    (hash_free_key) free_user_var, 0);
260

261 262
  sp_proc_cache= NULL;
  sp_func_cache= NULL;
263

unknown's avatar
unknown committed
264 265 266
  /* For user vars replication*/
  if (opt_bin_log)
    my_init_dynamic_array(&user_var_events,
267
			  sizeof(BINLOG_USER_VAR_EVENT *), 16, 16);
unknown's avatar
unknown committed
268 269 270
  else
    bzero((char*) &user_var_events, sizeof(user_var_events));

271 272 273 274 275
  /* Protocol */
  protocol= &protocol_simple;			// Default protocol
  protocol_simple.init(this);
  protocol_prep.init(this);

unknown's avatar
unknown committed
276
  tablespace_op=FALSE;
277 278
  tmp= sql_rnd_with_mutex();
  randominit(&rand, tmp + (ulong) &rand, tmp + (ulong) ::global_query_id);
279
  substitute_null_with_insert_id = FALSE;
280 281
  thr_lock_info_init(&lock_info); /* safety: will be reset after start */
  thr_lock_owner_init(&main_lock_id, &lock_info);
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313

  m_internal_handler= NULL;
}


void THD::push_internal_handler(Internal_error_handler *handler)
{
  /*
    TODO: The current implementation is limited to 1 handler at a time only.
    THD and sp_rcontext need to be modified to use a common handler stack.
  */
  DBUG_ASSERT(m_internal_handler == NULL);
  m_internal_handler= handler;
}


bool THD::handle_error(uint sql_errno,
                       MYSQL_ERROR::enum_warning_level level)
{
  if (m_internal_handler)
  {
    return m_internal_handler->handle_error(sql_errno, level, this);
  }

  return FALSE;                                 // 'FALSE', as per coding style
}


void THD::pop_internal_handler()
{
  DBUG_ASSERT(m_internal_handler != NULL);
  m_internal_handler= NULL;
unknown's avatar
unknown committed
314 315
}

unknown's avatar
unknown committed
316 317 318 319 320 321 322

/*
  Init common variables that has to be reset on start and on change_user
*/

void THD::init(void)
{
323 324
  pthread_mutex_lock(&LOCK_global_system_variables);
  variables= global_system_variables;
325 326 327 328 329 330
  variables.time_format= date_time_format_copy((THD*) 0,
					       variables.time_format);
  variables.date_format= date_time_format_copy((THD*) 0,
					       variables.date_format);
  variables.datetime_format= date_time_format_copy((THD*) 0,
						   variables.datetime_format);
331 332 333 334 335 336
  /*
    variables= global_system_variables above has reset
    variables.pseudo_thread_id to 0. We need to correct it here to
    avoid temporary tables replication failure.
  */
  variables.pseudo_thread_id= thread_id;
337
  pthread_mutex_unlock(&LOCK_global_system_variables);
unknown's avatar
unknown committed
338
  server_status= SERVER_STATUS_AUTOCOMMIT;
339 340
  if (variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES)
    server_status|= SERVER_STATUS_NO_BACKSLASH_ESCAPES;
unknown's avatar
unknown committed
341
  options= thd_startup_options;
unknown's avatar
unknown committed
342
  no_trans_update.stmt= no_trans_update.all= FALSE;
unknown's avatar
unknown committed
343
  open_options=ha_open_options;
344 345 346
  update_lock_default= (variables.low_priority_updates ?
			TL_WRITE_LOW_PRIORITY :
			TL_WRITE);
unknown's avatar
unknown committed
347
  session_tx_isolation= (enum_tx_isolation) variables.tx_isolation;
348 349 350
  warn_list.empty();
  bzero((char*) warn_count, sizeof(warn_count));
  total_warn_count= 0;
351
  update_charset();
352
  bzero((char *) &status_var, sizeof(status_var));
unknown's avatar
unknown committed
353 354
}

355

356 357 358 359 360 361 362 363
/*
  Init THD for query processing.
  This has to be called once before we call mysql_parse.
  See also comments in sql_class.h.
*/

void THD::init_for_queries()
{
364
  set_time(); 
365
  ha_enable_transaction(this,TRUE);
366

unknown's avatar
unknown committed
367
  reset_root_defaults(mem_root, variables.query_alloc_block_size,
368
                      variables.query_prealloc_size);
369
#ifdef USING_TRANSACTIONS
370 371 372
  reset_root_defaults(&transaction.mem_root,
                      variables.trans_alloc_block_size,
                      variables.trans_prealloc_size);
373
#endif
374 375
  transaction.xid_state.xid.null();
  transaction.xid_state.in_thd=1;
376 377 378
}


unknown's avatar
unknown committed
379 380 381 382 383 384 385 386 387 388 389 390 391 392
/*
  Do what's needed when one invokes change user

  SYNOPSIS
    change_user()

  IMPLEMENTATION
    Reset all resources that are connection specific
*/


void THD::change_user(void)
{
  cleanup();
unknown's avatar
unknown committed
393
  cleanup_done= 0;
unknown's avatar
unknown committed
394
  init();
395
  stmt_map.reset();
396
  hash_init(&user_vars, system_charset_info, USER_VARS_HASH_SIZE, 0, 0,
unknown's avatar
unknown committed
397
	    (hash_get_key) get_var_key,
unknown's avatar
unknown committed
398
	    (hash_free_key) free_user_var, 0);
399 400
  sp_cache_clear(&sp_proc_cache);
  sp_cache_clear(&sp_func_cache);
unknown's avatar
unknown committed
401 402 403
}


unknown's avatar
unknown committed
404 405 406
/* Do operations that may take a long time */

void THD::cleanup(void)
unknown's avatar
unknown committed
407
{
unknown's avatar
unknown committed
408
  DBUG_ENTER("THD::cleanup");
unknown's avatar
unknown committed
409
#ifdef ENABLE_WHEN_BINLOG_WILL_BE_ABLE_TO_PREPARE
410 411 412 413
  if (transaction.xid_state.xa_state == XA_PREPARED)
  {
#error xid_state in the cache should be replaced by the allocated value
  }
unknown's avatar
unknown committed
414
#endif
415
  {
unknown's avatar
unknown committed
416
    ha_rollback(this);
417 418
    xid_cache_delete(&transaction.xid_state);
  }
unknown's avatar
unknown committed
419 420 421 422 423
  if (locked_tables)
  {
    lock=locked_tables; locked_tables=0;
    close_thread_tables(this);
  }
424
  mysql_ha_flush(this, (TABLE_LIST*) 0,
425
                 MYSQL_HA_CLOSE_FINAL | MYSQL_HA_FLUSH_ALL, FALSE);
426
  hash_free(&handler_tables_hash);
427 428
  delete_dynamic(&user_var_events);
  hash_free(&user_vars);
unknown's avatar
unknown committed
429
  close_temporary_tables(this);
430 431 432
  my_free((char*) variables.time_format, MYF(MY_ALLOW_ZERO_PTR));
  my_free((char*) variables.date_format, MYF(MY_ALLOW_ZERO_PTR));
  my_free((char*) variables.datetime_format, MYF(MY_ALLOW_ZERO_PTR));
433
  
434
  sp_cache_clear(&sp_proc_cache);
435 436
  sp_cache_clear(&sp_func_cache);

unknown's avatar
unknown committed
437 438 439
  if (global_read_lock)
    unlock_global_read_lock(this);
  if (ull)
440
  {
unknown's avatar
unknown committed
441 442 443 444
    pthread_mutex_lock(&LOCK_user_locks);
    item_user_lock_release(ull);
    pthread_mutex_unlock(&LOCK_user_locks);
    ull= 0;
445
  }
446

unknown's avatar
unknown committed
447 448 449 450
  cleanup_done=1;
  DBUG_VOID_RETURN;
}

unknown's avatar
unknown committed
451

unknown's avatar
unknown committed
452 453
THD::~THD()
{
454
  THD_CHECK_SENTRY(this);
unknown's avatar
unknown committed
455
  DBUG_ENTER("~THD()");
456 457 458
  /* Ensure that no one is using THD */
  pthread_mutex_lock(&LOCK_delete);
  pthread_mutex_unlock(&LOCK_delete);
459
  add_to_status(&global_status_var, &status_var);
460

unknown's avatar
unknown committed
461
  /* Close connection */
unknown's avatar
unknown committed
462
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
463 464 465
  if (net.vio)
  {
    vio_delete(net.vio);
unknown's avatar
unknown committed
466
    net_end(&net);
unknown's avatar
unknown committed
467
  }
468
#endif
469
  stmt_map.reset();                     /* close all prepared statements */
470
  DBUG_ASSERT(lock_info.n_cursors == 0);
unknown's avatar
unknown committed
471 472
  if (!cleanup_done)
    cleanup();
473

unknown's avatar
unknown committed
474
  ha_close_connection(this);
unknown's avatar
unknown committed
475

476 477
  DBUG_PRINT("info", ("freeing security context"));
  main_security_ctx.destroy();
478
  safeFree(db);
479
  free_root(&warn_root,MYF(0));
480
#ifdef USING_TRANSACTIONS
481
  free_root(&transaction.mem_root,MYF(0));
482
#endif
unknown's avatar
unknown committed
483
  mysys_var=0;					// Safety (shouldn't be needed)
484
  pthread_mutex_destroy(&LOCK_delete);
485
#ifndef DBUG_OFF
unknown's avatar
unknown committed
486
  dbug_sentry= THD_SENTRY_GONE;
487
#endif  
488
  free_root(&main_mem_root, MYF(0));
unknown's avatar
unknown committed
489 490 491
  DBUG_VOID_RETURN;
}

492

493
/*
unknown's avatar
unknown committed
494 495 496 497 498 499
  Add all status variables to another status variable array

  SYNOPSIS
   add_to_status()
   to_var       add to this array
   from_var     from this array
500 501 502 503 504 505 506 507 508

  NOTES
    This function assumes that all variables are long/ulong.
    If this assumption will change, then we have to explictely add
    the other variables after the while loop
*/

void add_to_status(STATUS_VAR *to_var, STATUS_VAR *from_var)
{
509 510
  ulong *end= (ulong*) ((byte*) to_var +
                        offsetof(STATUS_VAR, last_system_status_var) +
511 512 513 514 515 516 517 518
			sizeof(ulong));
  ulong *to= (ulong*) to_var, *from= (ulong*) from_var;

  while (to != end)
    *(to++)+= *(from++);
}


unknown's avatar
SCRUM  
unknown committed
519
void THD::awake(THD::killed_state state_to_set)
520
{
521
  THD_CHECK_SENTRY(this);
522 523
  safe_mutex_assert_owner(&LOCK_delete); 

unknown's avatar
SCRUM  
unknown committed
524 525
  killed= state_to_set;
  if (state_to_set != THD::KILL_QUERY)
526
  {
unknown's avatar
SCRUM  
unknown committed
527
    thr_alarm_kill(real_id);
528
#ifdef SIGNAL_WITH_VIO_CLOSE
529
    close_active_vio();
530
#endif    
531
  }
532
  if (mysys_var)
unknown's avatar
unknown committed
533 534 535 536 537 538 539 540 541
  {
    pthread_mutex_lock(&mysys_var->mutex);
    if (!system_thread)		// Don't abort locks
      mysys_var->abort=1;
    /*
      This broadcast could be up in the air if the victim thread
      exits the cond in the time between read and broadcast, but that is
      ok since all we want to do is to make the victim thread get out
      of waiting on current_cond.
542 543 544 545 546
      If we see a non-zero current_cond: it cannot be an old value (because
      then exit_cond() should have run and it can't because we have mutex); so
      it is the true value but maybe current_mutex is not yet non-zero (we're
      in the middle of enter_cond() and there is a "memory order
      inversion"). So we test the mutex too to not lock 0.
547

548
      Note that there is a small chance we fail to kill. If victim has locked
549 550 551 552 553
      current_mutex, but hasn't yet entered enter_cond() (which means that
      current_cond and current_mutex are 0), then the victim will not get
      a signal and it may wait "forever" on the cond (until
      we issue a second KILL or the status it's waiting for happens).
      It's true that we have set its thd->killed but it may not
554
      see it immediately and so may have time to reach the cond_wait().
unknown's avatar
unknown committed
555
    */
556
    if (mysys_var->current_cond && mysys_var->current_mutex)
557
    {
unknown's avatar
unknown committed
558 559 560
      pthread_mutex_lock(mysys_var->current_mutex);
      pthread_cond_broadcast(mysys_var->current_cond);
      pthread_mutex_unlock(mysys_var->current_mutex);
561
    }
unknown's avatar
unknown committed
562 563
    pthread_mutex_unlock(&mysys_var->mutex);
  }
564 565
}

unknown's avatar
unknown committed
566 567 568 569
/*
  Remember the location of thread info, the structure needed for
  sql_alloc() and the structure for the net buffer
*/
unknown's avatar
unknown committed
570 571 572

bool THD::store_globals()
{
573 574 575 576 577 578
  /*
    Assert that thread_stack is initialized: it's necessary to be able
    to track stack overrun.
  */
  DBUG_ASSERT(this->thread_stack);

579
  if (my_pthread_setspecific_ptr(THR_THD,  this) ||
unknown's avatar
unknown committed
580
      my_pthread_setspecific_ptr(THR_MALLOC, &mem_root))
581 582 583
    return 1;
  mysys_var=my_thread_var;
  dbug_thread_id=my_thread_id();
unknown's avatar
unknown committed
584 585 586 587
  /*
    By default 'slave_proxy_id' is 'thread_id'. They may later become different
    if this is the slave SQL thread.
  */
588 589 590
  /** @todo we already do it in init(), see if we still need to do it here.
      add DBUG_ASSERT(variables.pseudo_thread_id == thread_id)
  */
591
  variables.pseudo_thread_id= thread_id;
592 593 594 595
  /*
    We have to call thr_lock_info_init() again here as THD may have been
    created in another thread
  */
596
  thr_lock_info_init(&lock_info);
597
  return 0;
unknown's avatar
unknown committed
598 599
}

unknown's avatar
unknown committed
600

601 602 603 604 605
/*
  Cleanup after query.

  SYNOPSIS
    THD::cleanup_after_query()
606

607
  DESCRIPTION
608
    This function is used to reset thread data to its default state.
609 610 611 612 613 614 615

  NOTE
    This function is not suitable for setting thread data to some
    non-default values, as there is only one replication thread, so
    different master threads may overwrite data of each other on
    slave.
*/
616

617 618
void THD::cleanup_after_query()
{
619
  last_insert_id_used= FALSE;
620 621 622 623 624
  if (clear_next_insert_id)
  {
    clear_next_insert_id= 0;
    next_insert_id= 0;
  }
625 626 627 628 629 630 631 632 633 634 635 636
  /*
    Reset rand_used so that detection of calls to rand() will save random 
    seeds if needed by the slave.

    Do not reset rand_used if inside a stored function or trigger because 
    only the call to these operations is logged. Thus only the calling 
    statement needs to detect rand() calls made by its substatements. These
    substatements must not set rand_used to 0 because it would remove the
    detection of rand() by the calling statement. 
  */
  if (!in_sub_stmt)
    rand_used= 0;
637
  /* Free Items that were created during this execution */
638
  free_items();
639 640
  /* Reset where. */
  where= THD::DEFAULT_WHERE;
641 642
}

643

unknown's avatar
unknown committed
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
/*
  Convert a string to another character set

  SYNOPSIS
    convert_string()
    to				Store new allocated string here
    to_cs			New character set for allocated string
    from			String to convert
    from_length			Length of string to convert
    from_cs			Original character set

  NOTES
    to will be 0-terminated to make it easy to pass to system funcs

  RETURN
    0	ok
    1	End of memory.
        In this case to->str will point to 0 and to->length will be 0.
*/

bool THD::convert_string(LEX_STRING *to, CHARSET_INFO *to_cs,
			 const char *from, uint from_length,
			 CHARSET_INFO *from_cs)
{
  DBUG_ENTER("convert_string");
  size_s new_length= to_cs->mbmaxlen * from_length;
670
  uint dummy_errors;
unknown's avatar
unknown committed
671 672 673 674 675 676
  if (!(to->str= alloc(new_length+1)))
  {
    to->length= 0;				// Safety fix
    DBUG_RETURN(1);				// EOM
  }
  to->length= copy_and_convert((char*) to->str, new_length, to_cs,
677
			       from, from_length, from_cs, &dummy_errors);
unknown's avatar
unknown committed
678 679 680 681 682
  to->str[to->length]=0;			// Safety
  DBUG_RETURN(0);
}


683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
/*
  Convert string from source character set to target character set inplace.

  SYNOPSIS
    THD::convert_string

  DESCRIPTION
    Convert string using convert_buffer - buffer for character set 
    conversion shared between all protocols.

  RETURN
    0   ok
   !0   out of memory
*/

bool THD::convert_string(String *s, CHARSET_INFO *from_cs, CHARSET_INFO *to_cs)
{
700 701
  uint dummy_errors;
  if (convert_buffer.copy(s->ptr(), s->length(), from_cs, to_cs, &dummy_errors))
702 703 704 705 706 707 708 709 710 711 712
    return TRUE;
  /* If convert_buffer >> s copying is more efficient long term */
  if (convert_buffer.alloced_length() >= convert_buffer.length() * 2 ||
      !s->is_alloced())
  {
    return s->copy(convert_buffer);
  }
  s->swap(convert_buffer);
  return FALSE;
}

713

unknown's avatar
unknown committed
714 715 716 717 718 719
/*
  Update some cache variables when character set changes
*/

void THD::update_charset()
{
720 721 722 723 724 725 726
  uint32 not_used;
  charset_is_system_charset= !String::needs_conversion(0,charset(),
                                                       system_charset_info,
                                                       &not_used);
  charset_is_collation_connection= 
    !String::needs_conversion(0,charset(),variables.collation_connection,
                              &not_used);
unknown's avatar
unknown committed
727 728 729
  charset_is_character_set_filesystem= 
    !String::needs_conversion(0, charset(),
                              variables.character_set_filesystem, &not_used);
unknown's avatar
unknown committed
730 731 732
}


733 734 735 736 737 738 739 740 741 742 743 744 745 746
/* routings to adding tables to list of changed in transaction tables */

inline static void list_include(CHANGED_TABLE_LIST** prev,
				CHANGED_TABLE_LIST* curr,
				CHANGED_TABLE_LIST* new_table)
{
  if (new_table)
  {
    *prev = new_table;
    (*prev)->next = curr;
  }
}

/* add table to list of changed in transaction tables */
747

748 749
void THD::add_changed_table(TABLE *table)
{
750
  DBUG_ENTER("THD::add_changed_table(table)");
751

unknown's avatar
unknown committed
752
  DBUG_ASSERT((options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN)) &&
753
	      table->file->has_transactions());
754
  add_changed_table(table->s->table_cache_key, table->s->key_length);
unknown's avatar
unknown committed
755
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
756
}
757

758

unknown's avatar
unknown committed
759 760 761
void THD::add_changed_table(const char *key, long key_length)
{
  DBUG_ENTER("THD::add_changed_table(key)");
762 763
  CHANGED_TABLE_LIST **prev_changed = &transaction.changed_tables;
  CHANGED_TABLE_LIST *curr = transaction.changed_tables;
764

765
  for (; curr; prev_changed = &(curr->next), curr = curr->next)
766
  {
unknown's avatar
unknown committed
767
    int cmp =  (long)curr->key_length - (long)key_length;
768 769
    if (cmp < 0)
    {
770
      list_include(prev_changed, curr, changed_table_dup(key, key_length));
771
      DBUG_PRINT("info", 
unknown's avatar
unknown committed
772 773
		 ("key_length: %ld  %u", key_length,
                  (*prev_changed)->key_length));
774 775 776 777
      DBUG_VOID_RETURN;
    }
    else if (cmp == 0)
    {
unknown's avatar
unknown committed
778
      cmp = memcmp(curr->key, key, curr->key_length);
779 780
      if (cmp < 0)
      {
781
	list_include(prev_changed, curr, changed_table_dup(key, key_length));
782
	DBUG_PRINT("info", 
783
		   ("key_length:  %ld  %u", key_length,
784
		    (*prev_changed)->key_length));
785 786 787 788 789 790 791 792 793
	DBUG_VOID_RETURN;
      }
      else if (cmp == 0)
      {
	DBUG_PRINT("info", ("already in list"));
	DBUG_VOID_RETURN;
      }
    }
  }
794
  *prev_changed = changed_table_dup(key, key_length);
unknown's avatar
unknown committed
795
  DBUG_PRINT("info", ("key_length: %ld  %u", key_length,
796
		      (*prev_changed)->key_length));
797 798 799
  DBUG_VOID_RETURN;
}

800

unknown's avatar
unknown committed
801
CHANGED_TABLE_LIST* THD::changed_table_dup(const char *key, long key_length)
802 803 804
{
  CHANGED_TABLE_LIST* new_table = 
    (CHANGED_TABLE_LIST*) trans_alloc(ALIGN_SIZE(sizeof(CHANGED_TABLE_LIST))+
unknown's avatar
unknown committed
805
				      key_length + 1);
806 807
  if (!new_table)
  {
808 809
    my_error(EE_OUTOFMEMORY, MYF(ME_BELL),
             ALIGN_SIZE(sizeof(TABLE_LIST)) + key_length + 1);
unknown's avatar
SCRUM  
unknown committed
810
    killed= KILL_CONNECTION;
811 812 813 814 815 816
    return 0;
  }

  new_table->key = (char *) (((byte*)new_table)+
			     ALIGN_SIZE(sizeof(CHANGED_TABLE_LIST)));
  new_table->next = 0;
unknown's avatar
unknown committed
817 818
  new_table->key_length = key_length;
  ::memcpy(new_table->key, key, key_length);
819 820 821
  return new_table;
}

822

unknown's avatar
unknown committed
823 824 825 826
int THD::send_explain_fields(select_result *result)
{
  List<Item> field_list;
  Item *item;
827
  CHARSET_INFO *cs= system_charset_info;
828
  field_list.push_back(new Item_return_int("id",3, MYSQL_TYPE_LONGLONG));
829
  field_list.push_back(new Item_empty_string("select_type", 19, cs));
unknown's avatar
unknown committed
830 831 832 833
  field_list.push_back(item= new Item_empty_string("table", NAME_LEN, cs));
  item->maybe_null= 1;
  field_list.push_back(item= new Item_empty_string("type", 10, cs));
  item->maybe_null= 1;
unknown's avatar
unknown committed
834
  field_list.push_back(item=new Item_empty_string("possible_keys",
835
						  NAME_LEN*MAX_KEY, cs));
unknown's avatar
unknown committed
836
  item->maybe_null=1;
837
  field_list.push_back(item=new Item_empty_string("key", NAME_LEN, cs));
unknown's avatar
unknown committed
838
  item->maybe_null=1;
unknown's avatar
unknown committed
839 840
  field_list.push_back(item=new Item_empty_string("key_len",
						  NAME_LEN*MAX_KEY));
unknown's avatar
unknown committed
841 842
  item->maybe_null=1;
  field_list.push_back(item=new Item_empty_string("ref",
843
						  NAME_LEN*MAX_REF_PARTS, cs));
unknown's avatar
unknown committed
844
  item->maybe_null=1;
unknown's avatar
unknown committed
845 846 847
  field_list.push_back(item= new Item_return_int("rows", 10,
                                                 MYSQL_TYPE_LONGLONG));
  item->maybe_null= 1;
848
  field_list.push_back(new Item_empty_string("Extra", 255, cs));
849 850
  return (result->send_fields(field_list,
                              Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF));
unknown's avatar
unknown committed
851
}
852

unknown's avatar
unknown committed
853 854 855
#ifdef SIGNAL_WITH_VIO_CLOSE
void THD::close_active_vio()
{
unknown's avatar
unknown committed
856
  DBUG_ENTER("close_active_vio");
unknown's avatar
unknown committed
857
  safe_mutex_assert_owner(&LOCK_delete); 
unknown's avatar
unknown committed
858
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
859 860 861 862 863
  if (active_vio)
  {
    vio_close(active_vio);
    active_vio = 0;
  }
unknown's avatar
unknown committed
864
#endif
865
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
866 867 868
}
#endif

869

870 871 872 873 874
struct Item_change_record: public ilink
{
  Item **place;
  Item *old_value;
  /* Placement new was hidden by `new' in ilink (TODO: check): */
875
  static void *operator new(size_t size, void *mem) { return mem; }
876 877
  static void operator delete(void *ptr, size_t size) {}
  static void operator delete(void *ptr, void *mem) { /* never called */ }
878 879 880 881 882 883
};


/*
  Register an item tree tree transformation, performed by the query
  optimizer. We need a pointer to runtime_memroot because it may be !=
unknown's avatar
unknown committed
884
  thd->mem_root (due to possible set_n_backup_active_arena called for thd).
885 886 887 888 889 890 891 892 893 894 895 896 897 898
*/

void THD::nocheck_register_item_tree_change(Item **place, Item *old_value,
                                            MEM_ROOT *runtime_memroot)
{
  Item_change_record *change;
  /*
    Now we use one node per change, which adds some memory overhead,
    but still is rather fast as we use alloc_root for allocations.
    A list of item tree changes of an average query should be short.
  */
  void *change_mem= alloc_root(runtime_memroot, sizeof(*change));
  if (change_mem == 0)
  {
899 900 901 902
    /*
      OOM, thd->fatal_error() is called by the error handler of the
      memroot. Just return.
    */
903 904 905 906 907
    return;
  }
  change= new (change_mem) Item_change_record;
  change->place= place;
  change->old_value= old_value;
908
  change_list.append(change);
909 910 911 912 913 914 915
}


void THD::rollback_item_tree_changes()
{
  I_List_iterator<Item_change_record> it(change_list);
  Item_change_record *change;
unknown's avatar
unknown committed
916 917
  DBUG_ENTER("rollback_item_tree_changes");

918 919 920 921
  while ((change= it++))
    *change->place= change->old_value;
  /* We can forget about changes memory: it's allocated in runtime memroot */
  change_list.empty();
unknown's avatar
unknown committed
922
  DBUG_VOID_RETURN;
923 924 925
}


unknown's avatar
unknown committed
926 927 928 929 930 931 932 933 934
/*****************************************************************************
** Functions to provide a interface to select results
*****************************************************************************/

select_result::select_result()
{
  thd=current_thd;
}

935 936
void select_result::send_error(uint errcode,const char *err)
{
unknown's avatar
unknown committed
937
  my_message(errcode, err, MYF(0));
938 939
}

940 941 942 943 944 945

void select_result::cleanup()
{
  /* do nothing */
}

946 947 948 949 950 951 952
bool select_result::check_simple_select() const
{
  my_error(ER_SP_BAD_CURSOR_QUERY, MYF(0));
  return TRUE;
}


953 954 955
static String default_line_term("\n",default_charset_info);
static String default_escaped("\\",default_charset_info);
static String default_field_term("\t",default_charset_info);
unknown's avatar
unknown committed
956 957 958 959 960

sql_exchange::sql_exchange(char *name,bool flag)
  :file_name(name), opt_enclosed(0), dumpfile(flag), skip_lines(0)
{
  field_term= &default_field_term;
unknown's avatar
SCRUM  
unknown committed
961
  enclosed=   line_start= &my_empty_string;
unknown's avatar
unknown committed
962 963
  line_term=  &default_line_term;
  escaped=    &default_escaped;
964
  cs= NULL;
unknown's avatar
unknown committed
965 966
}

967
bool select_send::send_fields(List<Item> &list, uint flags)
unknown's avatar
unknown committed
968
{
969 970 971 972
  bool res;
  if (!(res= thd->protocol->send_fields(&list, flags)))
    status= 1;
  return res;
unknown's avatar
unknown committed
973 974
}

975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
void select_send::abort()
{
  DBUG_ENTER("select_send::abort");
  if (status && thd->spcont &&
      thd->spcont->find_handler(thd->net.last_errno,
                                MYSQL_ERROR::WARN_LEVEL_ERROR))
  {
    /*
      Executing stored procedure without a handler.
      Here we should actually send an error to the client,
      but as an error will break a multiple result set, the only thing we
      can do for now is to nicely end the current data set and remembering
      the error so that the calling routine will abort
    */
    thd->net.report_error= 0;
    send_eof();
    thd->net.report_error= 1; // Abort SP
  }
  DBUG_VOID_RETURN;
}


unknown's avatar
unknown committed
997 998 999 1000
/* Send data to client. Returns 0 if ok */

bool select_send::send_data(List<Item> &items)
{
1001
  if (unit->offset_limit_cnt)
unknown's avatar
unknown committed
1002
  {						// using limit offset,count
1003
    unit->offset_limit_cnt--;
1004
    return 0;
unknown's avatar
unknown committed
1005
  }
1006

unknown's avatar
unknown committed
1007 1008 1009 1010 1011
  /*
    We may be passing the control from mysqld to the client: release the
    InnoDB adaptive hash S-latch to avoid thread deadlocks if it was reserved
    by thd
  */
1012 1013
    ha_release_temporary_latches(thd);

1014 1015 1016
  List_iterator_fast<Item> li(items);
  Protocol *protocol= thd->protocol;
  char buff[MAX_FIELD_WIDTH];
unknown's avatar
unknown committed
1017
  String buffer(buff, sizeof(buff), &my_charset_bin);
1018
  DBUG_ENTER("select_send::send_data");
1019 1020

  protocol->prepare_for_resend();
unknown's avatar
unknown committed
1021 1022 1023
  Item *item;
  while ((item=li++))
  {
1024
    if (item->send(protocol, &buffer))
unknown's avatar
unknown committed
1025
    {
1026
      protocol->free();				// Free used buffer
unknown's avatar
unknown committed
1027
      my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES), MYF(0));
1028
      break;
unknown's avatar
unknown committed
1029 1030
    }
  }
1031
  thd->sent_row_count++;
1032
  if (!thd->vio_ok())
1033
    DBUG_RETURN(0);
unknown's avatar
unknown committed
1034
  if (!thd->net.report_error)
1035
    DBUG_RETURN(protocol->write());
1036
  protocol->remove_last_row();
1037
  DBUG_RETURN(1);
unknown's avatar
unknown committed
1038 1039 1040 1041
}

bool select_send::send_eof()
{
1042 1043 1044 1045 1046
  /* We may be passing the control from mysqld to the client: release the
     InnoDB adaptive hash S-latch to avoid thread deadlocks if it was reserved
     by thd */
    ha_release_temporary_latches(thd);

unknown's avatar
unknown committed
1047 1048 1049
  /* Unlock tables before sending packet to gain some speed */
  if (thd->lock)
  {
1050 1051
    mysql_unlock_tables(thd, thd->lock);
    thd->lock=0;
unknown's avatar
unknown committed
1052
  }
unknown's avatar
unknown committed
1053 1054
  if (!thd->net.report_error)
  {
unknown's avatar
unknown committed
1055
    ::send_eof(thd);
1056
    status= 0;
unknown's avatar
unknown committed
1057 1058 1059 1060
    return 0;
  }
  else
    return 1;
unknown's avatar
unknown committed
1061 1062 1063
}


1064 1065 1066
/************************************************************************
  Handling writing to file
************************************************************************/
unknown's avatar
unknown committed
1067

1068 1069
void select_to_file::send_error(uint errcode,const char *err)
{
unknown's avatar
unknown committed
1070
  my_message(errcode, err, MYF(0));
1071 1072 1073 1074 1075 1076 1077 1078
  if (file > 0)
  {
    (void) end_io_cache(&cache);
    (void) my_close(file,MYF(0));
    (void) my_delete(path,MYF(0));		// Delete file on error
    file= -1;
  }
}
unknown's avatar
unknown committed
1079 1080


1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
bool select_to_file::send_eof()
{
  int error= test(end_io_cache(&cache));
  if (my_close(file,MYF(MY_WME)))
    error= 1;
  if (!error)
    ::send_ok(thd,row_count);
  file= -1;
  return error;
}


void select_to_file::cleanup()
{
  /* In case of error send_eof() may be not called: close the file here. */
  if (file >= 0)
  {
    (void) end_io_cache(&cache);
    (void) my_close(file,MYF(0));
    file= -1;
  }
  path[0]= '\0';
  row_count= 0;
}


1107
select_to_file::~select_to_file()
unknown's avatar
unknown committed
1108 1109 1110 1111 1112 1113 1114
{
  if (file >= 0)
  {					// This only happens in case of error
    (void) end_io_cache(&cache);
    (void) my_close(file,MYF(0));
    file= -1;
  }
1115 1116 1117 1118 1119 1120 1121 1122
}

/***************************************************************************
** Export of select to textfile
***************************************************************************/

select_export::~select_export()
{
1123
  thd->sent_row_count=row_count;
unknown's avatar
unknown committed
1124 1125
}

1126

1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
/*
  Create file with IO cache

  SYNOPSIS
    create_file()
    thd			Thread handle
    path		File name
    exchange		Excange class
    cache		IO cache

  RETURN
    >= 0 	File handle
   -1		Error
*/


static File create_file(THD *thd, char *path, sql_exchange *exchange,
			IO_CACHE *cache)
unknown's avatar
unknown committed
1145
{
1146
  File file;
1147
  uint option= MY_UNPACK_FILENAME | MY_RELATIVE_PATH;
1148

unknown's avatar
unknown committed
1149
#ifdef DONT_ALLOW_FULL_LOAD_DATA_PATHS
1150
  option|= MY_REPLACE_DIR;			// Force use of db directory
unknown's avatar
unknown committed
1151
#endif
1152

unknown's avatar
unknown committed
1153
  if (!dirname_length(exchange->file_name))
1154 1155 1156 1157 1158 1159
  {
    strxnmov(path, FN_REFLEN, mysql_real_data_home, thd->db ? thd->db : "", NullS);
    (void) fn_format(path, exchange->file_name, path, "", option);
  }
  else
    (void) fn_format(path, exchange->file_name, mysql_real_data_home, "", option);
1160 1161 1162 1163 1164 1165 1166 1167 1168

  if (opt_secure_file_priv &&
      strncmp(opt_secure_file_priv, path, strlen(opt_secure_file_priv)))
  {
    /* Write only allowed to dir or subdir specified by secure_file_priv */
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--secure-file-priv");
    return -1;
  }

1169
  if (!access(path, F_OK))
unknown's avatar
unknown committed
1170
  {
1171
    my_error(ER_FILE_EXISTS_ERROR, MYF(0), exchange->file_name);
unknown's avatar
unknown committed
1172
    return -1;
unknown's avatar
unknown committed
1173 1174
  }
  /* Create the file world readable */
unknown's avatar
unknown committed
1175
  if ((file= my_create(path, 0666, O_WRONLY|O_EXCL, MYF(MY_WME))) < 0)
1176
    return file;
unknown's avatar
unknown committed
1177
#ifdef HAVE_FCHMOD
1178
  (void) fchmod(file, 0666);			// Because of umask()
unknown's avatar
unknown committed
1179
#else
1180
  (void) chmod(path, 0666);
unknown's avatar
unknown committed
1181
#endif
1182
  if (init_io_cache(cache, file, 0L, WRITE_CACHE, 0L, 1, MYF(MY_WME)))
unknown's avatar
unknown committed
1183
  {
1184
    my_close(file, MYF(0));
1185
    my_delete(path, MYF(0));  // Delete file on error, it was just created 
1186
    return -1;
unknown's avatar
unknown committed
1187
  }
1188
  return file;
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
}


int
select_export::prepare(List<Item> &list, SELECT_LEX_UNIT *u)
{
  bool blob_flag=0;
  unit= u;
  if ((uint) strlen(exchange->file_name) + NAME_LEN >= FN_REFLEN)
    strmake(path,exchange->file_name,FN_REFLEN-1);

1200
  if ((file= create_file(thd, path, exchange, &cache)) < 0)
1201
    return 1;
unknown's avatar
unknown committed
1202 1203
  /* Check if there is any blobs in data */
  {
unknown's avatar
unknown committed
1204
    List_iterator_fast<Item> li(list);
unknown's avatar
unknown committed
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
    Item *item;
    while ((item=li++))
    {
      if (item->max_length >= MAX_BLOB_WIDTH)
      {
	blob_flag=1;
	break;
      }
    }
  }
  field_term_length=exchange->field_term->length();
  if (!exchange->line_term->length())
    exchange->line_term=exchange->field_term;	// Use this if it exists
  field_sep_char= (exchange->enclosed->length() ? (*exchange->enclosed)[0] :
		   field_term_length ? (*exchange->field_term)[0] : INT_MAX);
  escape_char=	(exchange->escaped->length() ? (*exchange->escaped)[0] : -1);
unknown's avatar
unknown committed
1221
  is_ambiguous_field_sep= test(strchr(ESCAPE_CHARS, field_sep_char));
unknown's avatar
unknown committed
1222
  is_unsafe_field_sep= test(strchr(NUMERIC_CHARS, field_sep_char));
unknown's avatar
unknown committed
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
  line_sep_char= (exchange->line_term->length() ?
		  (*exchange->line_term)[0] : INT_MAX);
  if (!field_term_length)
    exchange->opt_enclosed=0;
  if (!exchange->enclosed->length())
    exchange->opt_enclosed=1;			// A little quicker loop
  fixed_row_size= (!field_term_length && !exchange->enclosed->length() &&
		   !blob_flag);
  return 0;
}


1235 1236 1237 1238 1239
#define NEED_ESCAPING(x) ((int) (uchar) (x) == escape_char    || \
                          (int) (uchar) (x) == field_sep_char || \
                          (int) (uchar) (x) == line_sep_char  || \
                          !(x))

unknown's avatar
unknown committed
1240 1241 1242
bool select_export::send_data(List<Item> &items)
{

1243
  DBUG_ENTER("select_export::send_data");
unknown's avatar
unknown committed
1244 1245
  char buff[MAX_FIELD_WIDTH],null_buff[2],space[MAX_FIELD_WIDTH];
  bool space_inited=0;
unknown's avatar
unknown committed
1246
  String tmp(buff,sizeof(buff),&my_charset_bin),*res;
unknown's avatar
unknown committed
1247 1248
  tmp.length(0);

1249
  if (unit->offset_limit_cnt)
unknown's avatar
unknown committed
1250
  {						// using limit offset,count
1251
    unit->offset_limit_cnt--;
unknown's avatar
unknown committed
1252 1253 1254 1255 1256
    DBUG_RETURN(0);
  }
  row_count++;
  Item *item;
  uint used_length=0,items_left=items.elements;
unknown's avatar
unknown committed
1257
  List_iterator_fast<Item> li(items);
unknown's avatar
unknown committed
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296

  if (my_b_write(&cache,(byte*) exchange->line_start->ptr(),
		 exchange->line_start->length()))
    goto err;
  while ((item=li++))
  {
    Item_result result_type=item->result_type();
    res=item->str_result(&tmp);
    if (res && (!exchange->opt_enclosed || result_type == STRING_RESULT))
    {
      if (my_b_write(&cache,(byte*) exchange->enclosed->ptr(),
		     exchange->enclosed->length()))
	goto err;
    }
    if (!res)
    {						// NULL
      if (!fixed_row_size)
      {
	if (escape_char != -1)			// Use \N syntax
	{
	  null_buff[0]=escape_char;
	  null_buff[1]='N';
	  if (my_b_write(&cache,(byte*) null_buff,2))
	    goto err;
	}
	else if (my_b_write(&cache,(byte*) "NULL",4))
	  goto err;
      }
      else
      {
	used_length=0;				// Fill with space
      }
    }
    else
    {
      if (fixed_row_size)
	used_length=min(res->length(),item->max_length);
      else
	used_length=res->length();
unknown's avatar
unknown committed
1297 1298
      if ((result_type == STRING_RESULT || is_unsafe_field_sep) &&
           escape_char != -1)
unknown's avatar
unknown committed
1299
      {
1300 1301 1302 1303 1304 1305 1306 1307 1308
        char *pos, *start, *end;
        CHARSET_INFO *res_charset= res->charset();
        CHARSET_INFO *character_set_client= thd->variables.
                                            character_set_client;
        bool check_second_byte= (res_charset == &my_charset_bin) &&
                                 character_set_client->
                                 escape_with_backslash_is_dangerous;
        DBUG_ASSERT(character_set_client->mbmaxlen == 2 ||
                    !character_set_client->escape_with_backslash_is_dangerous);
unknown's avatar
unknown committed
1309 1310 1311 1312 1313
	for (start=pos=(char*) res->ptr(),end=pos+used_length ;
	     pos != end ;
	     pos++)
	{
#ifdef USE_MB
unknown's avatar
unknown committed
1314
	  if (use_mb(res_charset))
unknown's avatar
unknown committed
1315 1316
	  {
	    int l;
unknown's avatar
unknown committed
1317
	    if ((l=my_ismbchar(res_charset, pos, end)))
unknown's avatar
unknown committed
1318 1319 1320 1321 1322 1323
	    {
	      pos += l-1;
	      continue;
	    }
	  }
#endif
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362

          /*
            Special case when dumping BINARY/VARBINARY/BLOB values
            for the clients with character sets big5, cp932, gbk and sjis,
            which can have the escape character (0x5C "\" by default)
            as the second byte of a multi-byte sequence.
            
            If
            - pos[0] is a valid multi-byte head (e.g 0xEE) and
            - pos[1] is 0x00, which will be escaped as "\0",
            
            then we'll get "0xEE + 0x5C + 0x30" in the output file.
            
            If this file is later loaded using this sequence of commands:
            
            mysql> create table t1 (a varchar(128)) character set big5;
            mysql> LOAD DATA INFILE 'dump.txt' INTO TABLE t1;
            
            then 0x5C will be misinterpreted as the second byte
            of a multi-byte character "0xEE + 0x5C", instead of
            escape character for 0x00.
            
            To avoid this confusion, we'll escape the multi-byte
            head character too, so the sequence "0xEE + 0x00" will be
            dumped as "0x5C + 0xEE + 0x5C + 0x30".
            
            Note, in the condition below we only check if
            mbcharlen is equal to 2, because there are no
            character sets with mbmaxlen longer than 2
            and with escape_with_backslash_is_dangerous set.
            DBUG_ASSERT before the loop makes that sure.
          */

          if (NEED_ESCAPING(*pos) ||
              (check_second_byte &&
               my_mbcharlen(character_set_client, (uchar) *pos) == 2 &&
               pos + 1 < end &&
               NEED_ESCAPING(pos[1])))
          {
unknown's avatar
unknown committed
1363
	    char tmp_buff[2];
unknown's avatar
unknown committed
1364 1365 1366
            tmp_buff[0]= ((int) *pos == field_sep_char &&
                          is_ambiguous_field_sep) ?
                          field_sep_char : escape_char;
unknown's avatar
unknown committed
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
	    tmp_buff[1]= *pos ? *pos : '0';
	    if (my_b_write(&cache,(byte*) start,(uint) (pos-start)) ||
		my_b_write(&cache,(byte*) tmp_buff,2))
	      goto err;
	    start=pos+1;
	  }
	}
	if (my_b_write(&cache,(byte*) start,(uint) (pos-start)))
	  goto err;
      }
      else if (my_b_write(&cache,(byte*) res->ptr(),used_length))
	goto err;
    }
    if (fixed_row_size)
    {						// Fill with space
      if (item->max_length > used_length)
      {
	/* QQ:  Fix by adding a my_b_fill() function */
	if (!space_inited)
	{
	  space_inited=1;
	  bfill(space,sizeof(space),' ');
	}
	uint length=item->max_length-used_length;
1391
	for (; length > sizeof(space) ; length-=sizeof(space))
unknown's avatar
unknown committed
1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
	{
	  if (my_b_write(&cache,(byte*) space,sizeof(space)))
	    goto err;
	}
	if (my_b_write(&cache,(byte*) space,length))
	  goto err;
      }
    }
    if (res && (!exchange->opt_enclosed || result_type == STRING_RESULT))
    {
1402 1403 1404
      if (my_b_write(&cache, (byte*) exchange->enclosed->ptr(),
                     exchange->enclosed->length()))
        goto err;
unknown's avatar
unknown committed
1405 1406 1407
    }
    if (--items_left)
    {
1408 1409 1410
      if (my_b_write(&cache, (byte*) exchange->field_term->ptr(),
                     field_term_length))
        goto err;
unknown's avatar
unknown committed
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
    }
  }
  if (my_b_write(&cache,(byte*) exchange->line_term->ptr(),
		 exchange->line_term->length()))
    goto err;
  DBUG_RETURN(0);
err:
  DBUG_RETURN(1);
}


/***************************************************************************
** Dump  of select to a binary file
***************************************************************************/


int
1428 1429
select_dump::prepare(List<Item> &list __attribute__((unused)),
		     SELECT_LEX_UNIT *u)
unknown's avatar
unknown committed
1430
{
1431
  unit= u;
1432
  return (int) ((file= create_file(thd, path, exchange, &cache)) < 0);
unknown's avatar
unknown committed
1433 1434 1435 1436 1437
}


bool select_dump::send_data(List<Item> &items)
{
unknown's avatar
unknown committed
1438
  List_iterator_fast<Item> li(items);
unknown's avatar
unknown committed
1439
  char buff[MAX_FIELD_WIDTH];
unknown's avatar
unknown committed
1440
  String tmp(buff,sizeof(buff),&my_charset_bin),*res;
unknown's avatar
unknown committed
1441 1442
  tmp.length(0);
  Item *item;
1443
  DBUG_ENTER("select_dump::send_data");
unknown's avatar
unknown committed
1444

1445
  if (unit->offset_limit_cnt)
unknown's avatar
unknown committed
1446
  {						// using limit offset,count
1447
    unit->offset_limit_cnt--;
unknown's avatar
unknown committed
1448 1449 1450 1451
    DBUG_RETURN(0);
  }
  if (row_count++ > 1) 
  {
unknown's avatar
unknown committed
1452
    my_message(ER_TOO_MANY_ROWS, ER(ER_TOO_MANY_ROWS), MYF(0));
unknown's avatar
unknown committed
1453 1454 1455 1456 1457
    goto err;
  }
  while ((item=li++))
  {
    res=item->str_result(&tmp);
1458
    if (!res)					// If NULL
unknown's avatar
unknown committed
1459
    {
1460 1461
      if (my_b_write(&cache,(byte*) "",1))
	goto err;
unknown's avatar
unknown committed
1462 1463 1464
    }
    else if (my_b_write(&cache,(byte*) res->ptr(),res->length()))
    {
1465
      my_error(ER_ERROR_ON_WRITE, MYF(0), path, my_errno);
unknown's avatar
unknown committed
1466 1467 1468 1469 1470 1471 1472 1473 1474
      goto err;
    }
  }
  DBUG_RETURN(0);
err:
  DBUG_RETURN(1);
}


1475
select_subselect::select_subselect(Item_subselect *item_arg)
1476
{
1477
  item= item_arg;
1478 1479
}

1480

unknown's avatar
unknown committed
1481
bool select_singlerow_subselect::send_data(List<Item> &items)
1482
{
unknown's avatar
unknown committed
1483 1484
  DBUG_ENTER("select_singlerow_subselect::send_data");
  Item_singlerow_subselect *it= (Item_singlerow_subselect *)item;
unknown's avatar
unknown committed
1485 1486
  if (it->assigned())
  {
1487
    my_message(ER_SUBQUERY_NO_1_ROW, ER(ER_SUBQUERY_NO_1_ROW), MYF(0));
unknown's avatar
unknown committed
1488 1489 1490
    DBUG_RETURN(1);
  }
  if (unit->offset_limit_cnt)
unknown's avatar
unknown committed
1491
  {				          // Using limit offset,count
unknown's avatar
unknown committed
1492 1493
    unit->offset_limit_cnt--;
    DBUG_RETURN(0);
1494
  }
unknown's avatar
unknown committed
1495
  List_iterator_fast<Item> li(items);
1496 1497 1498
  Item *val_item;
  for (uint i= 0; (val_item= li++); i++)
    it->store(i, val_item);
unknown's avatar
unknown committed
1499
  it->assigned(1);
unknown's avatar
unknown committed
1500
  DBUG_RETURN(0);
1501
}
unknown's avatar
unknown committed
1502

1503

1504 1505 1506 1507 1508 1509 1510 1511
void select_max_min_finder_subselect::cleanup()
{
  DBUG_ENTER("select_max_min_finder_subselect::cleanup");
  cache= 0;
  DBUG_VOID_RETURN;
}


1512 1513 1514
bool select_max_min_finder_subselect::send_data(List<Item> &items)
{
  DBUG_ENTER("select_max_min_finder_subselect::send_data");
1515
  Item_maxmin_subselect *it= (Item_maxmin_subselect *)item;
1516 1517
  List_iterator_fast<Item> li(items);
  Item *val_item= li++;
1518
  it->register_value();
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540
  if (it->assigned())
  {
    cache->store(val_item);
    if ((this->*op)())
      it->store(0, cache);
  }
  else
  {
    if (!cache)
    {
      cache= Item_cache::get_cache(val_item->result_type());
      switch (val_item->result_type())
      {
      case REAL_RESULT:
	op= &select_max_min_finder_subselect::cmp_real;
	break;
      case INT_RESULT:
	op= &select_max_min_finder_subselect::cmp_int;
	break;
      case STRING_RESULT:
	op= &select_max_min_finder_subselect::cmp_str;
	break;
unknown's avatar
unknown committed
1541 1542 1543
      case DECIMAL_RESULT:
        op= &select_max_min_finder_subselect::cmp_decimal;
        break;
1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
      case ROW_RESULT:
        // This case should never be choosen
	DBUG_ASSERT(0);
	op= 0;
      }
    }
    cache->store(val_item);
    it->store(0, cache);
  }
  it->assigned(1);
  DBUG_RETURN(0);
}

bool select_max_min_finder_subselect::cmp_real()
{
1559
  Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0);
1560
  double val1= cache->val_real(), val2= maxmin->val_real();
1561 1562 1563 1564
  if (fmax)
    return (cache->null_value && !maxmin->null_value) ||
      (!cache->null_value && !maxmin->null_value &&
       val1 > val2);
1565 1566 1567
  return (maxmin->null_value && !cache->null_value) ||
    (!cache->null_value && !maxmin->null_value &&
     val1 < val2);
1568 1569 1570 1571
}

bool select_max_min_finder_subselect::cmp_int()
{
1572
  Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0);
1573 1574 1575 1576 1577
  longlong val1= cache->val_int(), val2= maxmin->val_int();
  if (fmax)
    return (cache->null_value && !maxmin->null_value) ||
      (!cache->null_value && !maxmin->null_value &&
       val1 > val2);
1578 1579 1580
  return (maxmin->null_value && !cache->null_value) ||
    (!cache->null_value && !maxmin->null_value &&
     val1 < val2);
1581 1582
}

unknown's avatar
unknown committed
1583 1584
bool select_max_min_finder_subselect::cmp_decimal()
{
1585
  Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0);
unknown's avatar
unknown committed
1586 1587 1588 1589 1590 1591
  my_decimal cval, *cvalue= cache->val_decimal(&cval);
  my_decimal mval, *mvalue= maxmin->val_decimal(&mval);
  if (fmax)
    return (cache->null_value && !maxmin->null_value) ||
      (!cache->null_value && !maxmin->null_value &&
       my_decimal_cmp(cvalue, mvalue) > 0) ;
1592 1593 1594
  return (maxmin->null_value && !cache->null_value) ||
    (!cache->null_value && !maxmin->null_value &&
     my_decimal_cmp(cvalue,mvalue) < 0);
unknown's avatar
unknown committed
1595 1596
}

1597 1598 1599
bool select_max_min_finder_subselect::cmp_str()
{
  String *val1, *val2, buf1, buf2;
1600
  Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0);
1601 1602 1603 1604 1605 1606 1607 1608 1609 1610
  /*
    as far as both operand is Item_cache buf1 & buf2 will not be used,
    but added for safety
  */
  val1= cache->val_str(&buf1);
  val2= maxmin->val_str(&buf1);
  if (fmax)
    return (cache->null_value && !maxmin->null_value) ||
      (!cache->null_value && !maxmin->null_value &&
       sortcmp(val1, val2, cache->collation.collation) > 0) ;
1611 1612 1613
  return (maxmin->null_value && !cache->null_value) ||
    (!cache->null_value && !maxmin->null_value &&
     sortcmp(val1, val2, cache->collation.collation) < 0);
1614 1615
}

unknown's avatar
unknown committed
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
bool select_exists_subselect::send_data(List<Item> &items)
{
  DBUG_ENTER("select_exists_subselect::send_data");
  Item_exists_subselect *it= (Item_exists_subselect *)item;
  if (unit->offset_limit_cnt)
  {				          // Using limit offset,count
    unit->offset_limit_cnt--;
    DBUG_RETURN(0);
  }
  it->value= 1;
unknown's avatar
unknown committed
1626
  it->assigned(1);
unknown's avatar
unknown committed
1627 1628 1629
  DBUG_RETURN(0);
}

unknown's avatar
unknown committed
1630 1631

/***************************************************************************
1632
  Dump of select to variables
unknown's avatar
unknown committed
1633
***************************************************************************/
1634

1635
int select_dumpvar::prepare(List<Item> &list, SELECT_LEX_UNIT *u)
unknown's avatar
unknown committed
1636
{
1637
  unit= u;
1638
  
1639
  if (var_list.elements != list.elements)
unknown's avatar
unknown committed
1640
  {
unknown's avatar
unknown committed
1641 1642
    my_message(ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT,
               ER(ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT), MYF(0));
1643
    return 1;
1644
  }               
1645 1646
  return 0;
}
1647

1648

1649 1650 1651 1652 1653 1654 1655
bool select_dumpvar::check_simple_select() const
{
  my_error(ER_SP_BAD_CURSOR_SELECT, MYF(0));
  return TRUE;
}


1656 1657
void select_dumpvar::cleanup()
{
1658
  row_count= 0;
1659 1660 1661
}


unknown's avatar
unknown committed
1662
Query_arena::Type Query_arena::type() const
1663
{
unknown's avatar
unknown committed
1664
  DBUG_ASSERT(0); /* Should never be called */
1665
  return STATEMENT;
1666 1667 1668
}


1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
void Query_arena::free_items()
{
  Item *next;
  DBUG_ENTER("Query_arena::free_items");
  /* This works because items are allocated with sql_alloc() */
  for (; free_list; free_list= next)
  {
    next= free_list->next;
    free_list->delete_self();
  }
  /* Postcondition: free_list is 0 */
  DBUG_VOID_RETURN;
}


1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696
void Query_arena::set_query_arena(Query_arena *set)
{
  mem_root=  set->mem_root;
  free_list= set->free_list;
  state= set->state;
}


void Query_arena::cleanup_stmt()
{
  DBUG_ASSERT("Query_arena::cleanup_stmt()" == "not implemented");
}

1697 1698 1699 1700
/*
  Statement functions 
*/

1701 1702 1703
Statement::Statement(LEX *lex_arg, MEM_ROOT *mem_root_arg,
                     enum enum_state state_arg, ulong id_arg)
  :Query_arena(mem_root_arg, state_arg),
unknown's avatar
unknown committed
1704
  id(id_arg),
1705
  set_query_id(1),
1706
  lex(lex_arg),
1707
  query(0),
1708 1709
  query_length(0),
  cursor(0)
1710
{
1711
  name.str= NULL;
1712 1713 1714
}


unknown's avatar
unknown committed
1715
Query_arena::Type Statement::type() const
1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727
{
  return STATEMENT;
}


void Statement::set_statement(Statement *stmt)
{
  id=             stmt->id;
  set_query_id=   stmt->set_query_id;
  lex=            stmt->lex;
  query=          stmt->query;
  query_length=   stmt->query_length;
1728
  cursor=         stmt->cursor;
1729 1730 1731
}


1732 1733 1734
void
Statement::set_n_backup_statement(Statement *stmt, Statement *backup)
{
1735
  DBUG_ENTER("Statement::set_n_backup_statement");
1736 1737
  backup->set_statement(this);
  set_statement(stmt);
1738
  DBUG_VOID_RETURN;
1739 1740 1741 1742 1743
}


void Statement::restore_backup_statement(Statement *stmt, Statement *backup)
{
1744
  DBUG_ENTER("Statement::restore_backup_statement");
1745 1746
  stmt->set_statement(this);
  set_statement(backup);
1747
  DBUG_VOID_RETURN;
1748 1749 1750
}


1751
void THD::end_statement()
1752
{
1753
  /* Cleanup SQL processing state to reuse this statement in next query. */
1754 1755 1756
  lex_end(lex);
  delete lex->result;
  lex->result= 0;
1757 1758
  /* Note that free_list is freed in cleanup_after_query() */

1759 1760 1761 1762 1763 1764 1765
  /*
    Don't free mem_root, as mem_root is freed in the end of dispatch_command
    (once for any command).
  */
}


unknown's avatar
unknown committed
1766
void THD::set_n_backup_active_arena(Query_arena *set, Query_arena *backup)
unknown's avatar
unknown committed
1767
{
unknown's avatar
unknown committed
1768
  DBUG_ENTER("THD::set_n_backup_active_arena");
1769
  DBUG_ASSERT(backup->is_backup_arena == FALSE);
1770

unknown's avatar
unknown committed
1771 1772
  backup->set_query_arena(this);
  set_query_arena(set);
unknown's avatar
unknown committed
1773
#ifndef DBUG_OFF
1774
  backup->is_backup_arena= TRUE;
unknown's avatar
unknown committed
1775
#endif
1776
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
1777 1778 1779
}


unknown's avatar
unknown committed
1780
void THD::restore_active_arena(Query_arena *set, Query_arena *backup)
1781
{
unknown's avatar
unknown committed
1782
  DBUG_ENTER("THD::restore_active_arena");
1783
  DBUG_ASSERT(backup->is_backup_arena);
unknown's avatar
unknown committed
1784 1785
  set->set_query_arena(this);
  set_query_arena(backup);
unknown's avatar
unknown committed
1786
#ifndef DBUG_OFF
1787
  backup->is_backup_arena= FALSE;
1788
#endif
unknown's avatar
unknown committed
1789
  DBUG_VOID_RETURN;
1790 1791
}

1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811
Statement::~Statement()
{
}

C_MODE_START

static byte *
get_statement_id_as_hash_key(const byte *record, uint *key_length,
                             my_bool not_used __attribute__((unused)))
{
  const Statement *statement= (const Statement *) record; 
  *key_length= sizeof(statement->id);
  return (byte *) &((const Statement *) statement)->id;
}

static void delete_statement_as_hash_key(void *key)
{
  delete (Statement *) key;
}

1812 1813
static byte *get_stmt_name_hash_key(Statement *entry, uint *length,
                                    my_bool not_used __attribute__((unused)))
1814 1815 1816 1817 1818
{
  *length=(uint) entry->name.length;
  return (byte*) entry->name.str;
}

1819 1820 1821 1822 1823
C_MODE_END

Statement_map::Statement_map() :
  last_found_statement(0)
{
1824 1825 1826 1827 1828
  enum
  {
    START_STMT_HASH_SIZE = 16,
    START_NAME_HASH_SIZE = 16
  };
1829
  hash_init(&st_hash, &my_charset_bin, START_STMT_HASH_SIZE, 0, 0,
1830 1831
            get_statement_id_as_hash_key,
            delete_statement_as_hash_key, MYF(0));
1832
  hash_init(&names_hash, system_charset_info, START_NAME_HASH_SIZE, 0, 0,
1833 1834
            (hash_get_key) get_stmt_name_hash_key,
            NULL,MYF(0));
1835 1836
}

1837

1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859
/*
  Insert a new statement to the thread-local statement map.

  DESCRIPTION
    If there was an old statement with the same name, replace it with the
    new one. Otherwise, check if max_prepared_stmt_count is not reached yet,
    increase prepared_stmt_count, and insert the new statement. It's okay
    to delete an old statement and fail to insert the new one.

  POSTCONDITIONS
    All named prepared statements are also present in names_hash.
    Statement names in names_hash are unique.
    The statement is added only if prepared_stmt_count < max_prepard_stmt_count
    last_found_statement always points to a valid statement or is 0

  RETURN VALUE
    0  success
    1  error: out of resources or max_prepared_stmt_count limit has been
       reached. An error is sent to the client, the statement is deleted.
*/

int Statement_map::insert(THD *thd, Statement *statement)
1860
{
1861 1862 1863 1864 1865 1866 1867 1868 1869 1870
  if (my_hash_insert(&st_hash, (byte*) statement))
  {
    /*
      Delete is needed only in case of an insert failure. In all other
      cases hash_delete will also delete the statement.
    */
    delete statement;
    my_error(ER_OUT_OF_RESOURCES, MYF(0));
    goto err_st_hash;
  }
1871
  if (statement->name.str && my_hash_insert(&names_hash, (byte*) statement))
1872
  {
1873 1874
    my_error(ER_OUT_OF_RESOURCES, MYF(0));
    goto err_names_hash;
1875
  }
1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886
  pthread_mutex_lock(&LOCK_prepared_stmt_count);
  /*
    We don't check that prepared_stmt_count is <= max_prepared_stmt_count
    because we would like to allow to lower the total limit
    of prepared statements below the current count. In that case
    no new statements can be added until prepared_stmt_count drops below
    the limit.
  */
  if (prepared_stmt_count >= max_prepared_stmt_count)
  {
    pthread_mutex_unlock(&LOCK_prepared_stmt_count);
1887 1888
    my_error(ER_MAX_PREPARED_STMT_COUNT_REACHED, MYF(0),
             max_prepared_stmt_count);
1889 1890 1891 1892 1893
    goto err_max;
  }
  prepared_stmt_count++;
  pthread_mutex_unlock(&LOCK_prepared_stmt_count);

1894
  last_found_statement= statement;
1895 1896 1897 1898 1899 1900 1901 1902 1903
  return 0;

err_max:
  if (statement->name.str)
    hash_delete(&names_hash, (byte*) statement);
err_names_hash:
  hash_delete(&st_hash, (byte*) statement);
err_st_hash:
  return 1;
1904 1905
}

1906

1907 1908
void Statement_map::close_transient_cursors()
{
1909
#ifdef TO_BE_IMPLEMENTED
1910 1911 1912
  Statement *stmt;
  while ((stmt= transient_cursor_list.head()))
    stmt->close_cursor();                 /* deletes itself from the list */
1913
#endif
1914 1915 1916
}


1917 1918 1919 1920 1921 1922
void Statement_map::erase(Statement *statement)
{
  if (statement == last_found_statement)
    last_found_statement= 0;
  if (statement->name.str)
    hash_delete(&names_hash, (byte *) statement);
1923

1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942
  hash_delete(&st_hash, (byte *) statement);
  pthread_mutex_lock(&LOCK_prepared_stmt_count);
  DBUG_ASSERT(prepared_stmt_count > 0);
  prepared_stmt_count--;
  pthread_mutex_unlock(&LOCK_prepared_stmt_count);
}


void Statement_map::reset()
{
  /* Must be first, hash_free will reset st_hash.records */
  pthread_mutex_lock(&LOCK_prepared_stmt_count);
  DBUG_ASSERT(prepared_stmt_count >= st_hash.records);
  prepared_stmt_count-= st_hash.records;
  pthread_mutex_unlock(&LOCK_prepared_stmt_count);

  my_hash_reset(&names_hash);
  my_hash_reset(&st_hash);
  last_found_statement= 0;
1943 1944
}

1945

1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957
Statement_map::~Statement_map()
{
  /* Must go first, hash_free will reset st_hash.records */
  pthread_mutex_lock(&LOCK_prepared_stmt_count);
  DBUG_ASSERT(prepared_stmt_count >= st_hash.records);
  prepared_stmt_count-= st_hash.records;
  pthread_mutex_unlock(&LOCK_prepared_stmt_count);

  hash_free(&names_hash);
  hash_free(&st_hash);
}

1958 1959
bool select_dumpvar::send_data(List<Item> &items)
{
1960
  List_iterator_fast<my_var> var_li(var_list);
1961
  List_iterator<Item> it(items);
1962
  Item *item;
1963
  my_var *mv;
1964
  DBUG_ENTER("select_dumpvar::send_data");
1965

1966
  if (unit->offset_limit_cnt)
1967
  {						// using limit offset,count
1968 1969 1970
    unit->offset_limit_cnt--;
    DBUG_RETURN(0);
  }
1971 1972
  if (row_count++) 
  {
unknown's avatar
unknown committed
1973
    my_message(ER_TOO_MANY_ROWS, ER(ER_TOO_MANY_ROWS), MYF(0));
1974 1975
    DBUG_RETURN(1);
  }
1976
  while ((mv= var_li++) && (item= it++))
unknown's avatar
unknown committed
1977
  {
1978
    if (mv->local)
unknown's avatar
unknown committed
1979
    {
1980 1981
      if (thd->spcont->set_variable(thd, mv->offset, &item))
	    DBUG_RETURN(1);
unknown's avatar
unknown committed
1982 1983 1984
    }
    else
    {
1985 1986 1987
      Item_func_set_user_var *suv= new Item_func_set_user_var(mv->s, item);
      suv->fix_fields(thd, 0);
      suv->check(0);
1988
      suv->update();
unknown's avatar
unknown committed
1989
    }
unknown's avatar
unknown committed
1990
  }
unknown's avatar
unknown committed
1991 1992 1993 1994 1995
  DBUG_RETURN(0);
}

bool select_dumpvar::send_eof()
{
1996
  if (! row_count)
unknown's avatar
unknown committed
1997 1998
    push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                 ER_SP_FETCH_NO_DATA, ER(ER_SP_FETCH_NO_DATA));
1999 2000
  ::send_ok(thd,row_count);
  return 0;
unknown's avatar
unknown committed
2001
}
2002 2003 2004 2005 2006 2007 2008

/****************************************************************************
  TMP_TABLE_PARAM
****************************************************************************/

void TMP_TABLE_PARAM::init()
{
2009 2010
  DBUG_ENTER("TMP_TABLE_PARAM::init");
  DBUG_PRINT("enter", ("this: 0x%lx", (ulong)this));
2011 2012 2013
  field_count= sum_func_count= func_count= hidden_field_count= 0;
  group_parts= group_length= group_null_parts= 0;
  quick_group= 1;
unknown's avatar
unknown committed
2014
  table_charset= 0;
2015
  precomputed_group_by= 0;
2016
  DBUG_VOID_RETURN;
2017
}
2018 2019 2020 2021


void thd_increment_bytes_sent(ulong length)
{
unknown's avatar
unknown committed
2022
  THD *thd=current_thd;
unknown's avatar
unknown committed
2023
  if (likely(thd != 0))
unknown's avatar
unknown committed
2024 2025 2026
  { /* current_thd==0 when close_connection() calls net_send_error() */
    thd->status_var.bytes_sent+= length;
  }
2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045
}


void thd_increment_bytes_received(ulong length)
{
  current_thd->status_var.bytes_received+= length;
}


void thd_increment_net_big_packet_count(ulong length)
{
  current_thd->status_var.net_big_packet_count+= length;
}


void THD::set_status_var_init()
{
  bzero((char*) &status_var, sizeof(status_var));
}
2046

2047

2048
void Security_context::init()
2049 2050 2051
{
  host= user= priv_user= ip= 0;
  host_or_ip= "connecting host";
2052
  priv_host[0]= '\0';
2053 2054 2055 2056 2057 2058
#ifndef NO_EMBEDDED_ACCESS_CHECKS
  db_access= NO_ACCESS;
#endif
}


2059
void Security_context::destroy()
2060 2061 2062 2063 2064 2065 2066 2067 2068 2069
{
  // If not pointer to constant
  if (host != my_localhost)
    safeFree(host);
  if (user != delayed_user)
    safeFree(user);
  safeFree(ip);
}


2070
void Security_context::skip_grants()
2071 2072 2073 2074 2075 2076 2077 2078 2079
{
  /* privileges for the user are unknown everything is allowed */
  host_or_ip= (char *)"";
  master_access= ~NO_ACCESS;
  priv_user= (char *)"";
  *priv_host= '\0';
}


2080 2081 2082 2083 2084 2085 2086 2087
/****************************************************************************
  Handling of open and locked tables states.

  This is used when we want to open/lock (and then close) some tables when
  we already have a set of tables open and locked. We use these methods for
  access to mysql.proc table to find definitions of stored routines.
****************************************************************************/

2088
void THD::reset_n_backup_open_tables_state(Open_tables_state *backup)
2089
{
2090 2091
  DBUG_ENTER("reset_n_backup_open_tables_state");
  backup->set_open_tables_state(this);
2092
  reset_open_tables_state();
2093
  DBUG_VOID_RETURN;
2094 2095 2096
}


2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108
void THD::restore_backup_open_tables_state(Open_tables_state *backup)
{
  DBUG_ENTER("restore_backup_open_tables_state");
  /*
    Before we will throw away current open tables state we want
    to be sure that it was properly cleaned up.
  */
  DBUG_ASSERT(open_tables == 0 && temporary_tables == 0 &&
              handler_tables == 0 && derived_tables == 0 &&
              lock == 0 && locked_tables == 0 &&
              prelocked_mode == NON_PRELOCKED);
  set_open_tables_state(backup);
2109 2110
  DBUG_VOID_RETURN;
}
2111 2112


2113

2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126
/****************************************************************************
  Handling of statement states in functions and triggers.

  This is used to ensure that the function/trigger gets a clean state
  to work with and does not cause any side effects of the calling statement.

  It also allows most stored functions and triggers to replicate even
  if they are used items that would normally be stored in the binary
  replication (like last_insert_id() etc...)

  The following things is done
  - Disable binary logging for the duration of the statement
  - Disable multi-result-sets for the duration of the statement
2127
  - Value of last_insert_id() is saved and restored
2128 2129 2130 2131
  - Value set by 'SET INSERT_ID=#' is reset and restored
  - Value for found_rows() is reset and restored
  - examined_row_count is added to the total
  - cuted_fields is added to the total
2132
  - new savepoint level is created and destroyed
2133 2134 2135 2136 2137 2138

  NOTES:
    Seed for random() is saved for the first! usage of RAND()
    We reset examined_row_count and cuted_fields and add these to the
    result to ensure that if we have a bug that would reset these within
    a function, we are not loosing any rows from the main statement.
2139 2140

    We do not reset value of last_insert_id().
2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151
****************************************************************************/

void THD::reset_sub_statement_state(Sub_statement_state *backup,
                                    uint new_state)
{
  backup->options=         options;
  backup->in_sub_stmt=     in_sub_stmt;
  backup->no_send_ok=      net.no_send_ok;
  backup->enable_slow_log= enable_slow_log;
  backup->last_insert_id=  last_insert_id;
  backup->next_insert_id=  next_insert_id;
unknown's avatar
unknown committed
2152
  backup->current_insert_id=  current_insert_id;
2153
  backup->insert_id_used=  insert_id_used;
unknown's avatar
unknown committed
2154
  backup->last_insert_id_used=  last_insert_id_used;
2155
  backup->clear_next_insert_id= clear_next_insert_id;
2156 2157 2158 2159 2160
  backup->limit_found_rows= limit_found_rows;
  backup->examined_row_count= examined_row_count;
  backup->sent_row_count=   sent_row_count;
  backup->cuted_fields=     cuted_fields;
  backup->client_capabilities= client_capabilities;
2161
  backup->savepoints= transaction.savepoints;
2162

2163 2164
  if (!lex->requires_prelocking() || is_update_query(lex->sql_command))
    options&= ~OPTION_BIN_LOG;
2165 2166 2167 2168

  if ((backup->options & OPTION_BIN_LOG) && is_update_query(lex->sql_command))
    mysql_bin_log.start_union_events(this, this->query_id);

2169 2170 2171 2172 2173 2174 2175 2176
  /* Disable result sets */
  client_capabilities &= ~CLIENT_MULTI_RESULTS;
  in_sub_stmt|= new_state;
  next_insert_id= 0;
  insert_id_used= 0;
  examined_row_count= 0;
  sent_row_count= 0;
  cuted_fields= 0;
2177
  transaction.savepoints= 0;
2178 2179 2180 2181 2182 2183 2184 2185

  /* Surpress OK packets in case if we will execute statements */
  net.no_send_ok= TRUE;
}


void THD::restore_sub_statement_state(Sub_statement_state *backup)
{
2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200
  /*
    To save resources we want to release savepoints which were created
    during execution of function or trigger before leaving their savepoint
    level. It is enough to release first savepoint set on this level since
    all later savepoints will be released automatically.
  */
  if (transaction.savepoints)
  {
    SAVEPOINT *sv;
    for (sv= transaction.savepoints; sv->prev; sv= sv->prev)
    {}
    /* ha_release_savepoint() never returns error. */
    (void)ha_release_savepoint(this, sv);
  }
  transaction.savepoints= backup->savepoints;
2201 2202 2203 2204 2205 2206
  options=          backup->options;
  in_sub_stmt=      backup->in_sub_stmt;
  net.no_send_ok=   backup->no_send_ok;
  enable_slow_log=  backup->enable_slow_log;
  last_insert_id=   backup->last_insert_id;
  next_insert_id=   backup->next_insert_id;
unknown's avatar
unknown committed
2207
  current_insert_id= backup->current_insert_id;
2208
  insert_id_used=   backup->insert_id_used;
unknown's avatar
unknown committed
2209
  last_insert_id_used= backup->last_insert_id_used;
2210
  clear_next_insert_id= backup->clear_next_insert_id;
2211 2212 2213 2214
  limit_found_rows= backup->limit_found_rows;
  sent_row_count=   backup->sent_row_count;
  client_capabilities= backup->client_capabilities;

2215 2216 2217
  if ((options & OPTION_BIN_LOG) && is_update_query(lex->sql_command))
    mysql_bin_log.stop_union_events(this);

2218 2219 2220 2221 2222 2223 2224
  /*
    The following is added to the old values as we are interested in the
    total complexity of the query
  */
  examined_row_count+= backup->examined_row_count;
  cuted_fields+=       backup->cuted_fields;
}
2225 2226 2227 2228 2229 2230


/***************************************************************************
  Handling of XA id cacheing
***************************************************************************/

2231 2232 2233 2234 2235 2236
pthread_mutex_t LOCK_xid_cache;
HASH xid_cache;

static byte *xid_get_hash_key(const byte *ptr,uint *length,
                                  my_bool not_used __attribute__((unused)))
{
2237 2238
  *length=((XID_STATE*)ptr)->xid.key_length();
  return ((XID_STATE*)ptr)->xid.key();
2239 2240 2241 2242 2243
}

static void xid_free_hash (void *ptr)
{
  if (!((XID_STATE*)ptr)->in_thd)
unknown's avatar
unknown committed
2244
    my_free((gptr)ptr, MYF(0));
2245 2246 2247 2248 2249
}

bool xid_cache_init()
{
  pthread_mutex_init(&LOCK_xid_cache, MY_MUTEX_INIT_FAST);
unknown's avatar
unknown committed
2250 2251
  return hash_init(&xid_cache, &my_charset_bin, 100, 0, 0,
                   xid_get_hash_key, xid_free_hash, 0) != 0;
2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265
}

void xid_cache_free()
{
  if (hash_inited(&xid_cache))
  {
    hash_free(&xid_cache);
    pthread_mutex_destroy(&LOCK_xid_cache);
  }
}

XID_STATE *xid_cache_search(XID *xid)
{
  pthread_mutex_lock(&LOCK_xid_cache);
2266
  XID_STATE *res=(XID_STATE *)hash_search(&xid_cache, xid->key(), xid->key_length());
2267 2268 2269 2270
  pthread_mutex_unlock(&LOCK_xid_cache);
  return res;
}

2271

2272 2273 2274 2275 2276
bool xid_cache_insert(XID *xid, enum xa_states xa_state)
{
  XID_STATE *xs;
  my_bool res;
  pthread_mutex_lock(&LOCK_xid_cache);
2277
  if (hash_search(&xid_cache, xid->key(), xid->key_length()))
2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291
    res=0;
  else if (!(xs=(XID_STATE *)my_malloc(sizeof(*xs), MYF(MY_WME))))
    res=1;
  else
  {
    xs->xa_state=xa_state;
    xs->xid.set(xid);
    xs->in_thd=0;
    res=my_hash_insert(&xid_cache, (byte*)xs);
  }
  pthread_mutex_unlock(&LOCK_xid_cache);
  return res;
}

2292

2293 2294 2295
bool xid_cache_insert(XID_STATE *xid_state)
{
  pthread_mutex_lock(&LOCK_xid_cache);
2296 2297
  DBUG_ASSERT(hash_search(&xid_cache, xid_state->xid.key(),
                          xid_state->xid.key_length())==0);
2298 2299 2300 2301 2302
  my_bool res=my_hash_insert(&xid_cache, (byte*)xid_state);
  pthread_mutex_unlock(&LOCK_xid_cache);
  return res;
}

2303

2304 2305 2306 2307 2308 2309 2310
void xid_cache_delete(XID_STATE *xid_state)
{
  pthread_mutex_lock(&LOCK_xid_cache);
  hash_delete(&xid_cache, (byte *)xid_state);
  pthread_mutex_unlock(&LOCK_xid_cache);
}