sql_class.cc 61.5 KB
Newer Older
1
/* Copyright (C) 2000-2006 MySQL AB
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2

bk@work.mysql.com's avatar
bk@work.mysql.com 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
5
   the Free Software Foundation; version 2 of the License.
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
6

bk@work.mysql.com's avatar
bk@work.mysql.com 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.
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
11

bk@work.mysql.com's avatar
bk@work.mysql.com 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
bk@work.mysql.com's avatar
bk@work.mysql.com 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>
bk@work.mysql.com's avatar
bk@work.mysql.com committed
32 33 34
#ifdef	__WIN__
#include <io.h>
#endif
35
#include <mysys_err.h>
bk@work.mysql.com's avatar
bk@work.mysql.com committed
36

monty@mysql.com's avatar
monty@mysql.com 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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
50 51 52 53
/*****************************************************************************
** Instansiate templates
*****************************************************************************/

54
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
bk@work.mysql.com's avatar
bk@work.mysql.com 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)))
bk@work.mysql.com's avatar
bk@work.mysql.com 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)
bk@work.mysql.com's avatar
bk@work.mysql.com 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
}


bk@work.mysql.com's avatar
bk@work.mysql.com 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();
}


bk@work.mysql.com's avatar
bk@work.mysql.com 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)
bk@work.mysql.com's avatar
bk@work.mysql.com 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);
konstantin@mysql.com's avatar
konstantin@mysql.com 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;
pem@mysql.com's avatar
pem@mysql.com committed
195
  locked=some_tables_deleted=no_errors=password= 0;
konstantin@oak.local's avatar
konstantin@oak.local committed
196
  query_start_used= 0;
197
  count_cuted_fields= CHECK_FIELD_IGNORE;
hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
198
  killed= NOT_KILLED;
199
  db_length= col_access=0;
200
  query_error= tmp_table_used= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
201
  next_insert_id=last_insert_id=0;
202
  hash_clear(&handler_tables_hash);
bk@work.mysql.com's avatar
bk@work.mysql.com 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
konstantin@oak.local's avatar
konstantin@oak.local committed
209
  lex->current_select= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
210
  start_time=(time_t) 0;
211
  time_after_lock=(time_t) 0;
212
  current_linfo =  0;
213
  slave_thread = 0;
214
  variables.pseudo_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));
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi 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
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi 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
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
234
  ull=0;
235
  system_thread= cleanup_done= abort_on_warning= no_warnings_for_error= 0;
236
  peer_port= 0;					// For SHOW PROCESSLIST
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi 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);
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
244 245 246

  /* Variables with default values */
  proc_info="login";
247
  where= THD::DEFAULT_WHERE;
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
248
  server_id = ::server_id;
249
  slave_net = 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
250
  command=COM_CONNECT;
251
  *scramble= '\0';
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
252

253
  init();
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi 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,
bk@work.mysql.com's avatar
bk@work.mysql.com 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

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

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi 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;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
314 315
}

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
  pthread_mutex_unlock(&LOCK_global_system_variables);
332
  server_status= SERVER_STATUS_AUTOCOMMIT;
333 334
  if (variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES)
    server_status|= SERVER_STATUS_NO_BACKSLASH_ESCAPES;
335
  options= thd_startup_options;
336
  no_trans_update.stmt= no_trans_update.all= FALSE;
337
  open_options=ha_open_options;
338 339 340
  update_lock_default= (variables.low_priority_updates ?
			TL_WRITE_LOW_PRIORITY :
			TL_WRITE);
341
  session_tx_isolation= (enum_tx_isolation) variables.tx_isolation;
342 343 344
  warn_list.empty();
  bzero((char*) warn_count, sizeof(warn_count));
  total_warn_count= 0;
345
  update_charset();
346
  bzero((char *) &status_var, sizeof(status_var));
347 348
}

349

350 351 352 353 354 355 356 357
/*
  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()
{
358
  set_time(); 
359
  ha_enable_transaction(this,TRUE);
360

361
  reset_root_defaults(mem_root, variables.query_alloc_block_size,
362
                      variables.query_prealloc_size);
363
#ifdef USING_TRANSACTIONS
364 365 366
  reset_root_defaults(&transaction.mem_root,
                      variables.trans_alloc_block_size,
                      variables.trans_prealloc_size);
367
#endif
368 369
  transaction.xid_state.xid.null();
  transaction.xid_state.in_thd=1;
370 371 372
}


373 374 375 376 377 378 379 380 381 382 383 384 385 386
/*
  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();
387
  cleanup_done= 0;
388
  init();
389
  stmt_map.reset();
390
  hash_init(&user_vars, system_charset_info, USER_VARS_HASH_SIZE, 0, 0,
391
	    (hash_get_key) get_var_key,
392
	    (hash_free_key) free_user_var, 0);
393 394
  sp_cache_clear(&sp_proc_cache);
  sp_cache_clear(&sp_func_cache);
395 396 397
}


monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
398 399 400
/* Do operations that may take a long time */

void THD::cleanup(void)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
401
{
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
402
  DBUG_ENTER("THD::cleanup");
403
#ifdef ENABLE_WHEN_BINLOG_WILL_BE_ABLE_TO_PREPARE
404 405 406 407
  if (transaction.xid_state.xa_state == XA_PREPARED)
  {
#error xid_state in the cache should be replaced by the allocated value
  }
408
#endif
409
  {
serg@serg.mylan's avatar
serg@serg.mylan committed
410
    ha_rollback(this);
411 412
    xid_cache_delete(&transaction.xid_state);
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
413 414 415 416 417
  if (locked_tables)
  {
    lock=locked_tables; locked_tables=0;
    close_thread_tables(this);
  }
418
  mysql_ha_flush(this, (TABLE_LIST*) 0,
419
                 MYSQL_HA_CLOSE_FINAL | MYSQL_HA_FLUSH_ALL, FALSE);
420
  hash_free(&handler_tables_hash);
421 422
  delete_dynamic(&user_var_events);
  hash_free(&user_vars);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
423
  close_temporary_tables(this);
424 425 426
  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));
427
  
428
  sp_cache_clear(&sp_proc_cache);
429 430
  sp_cache_clear(&sp_func_cache);

431 432 433
  if (global_read_lock)
    unlock_global_read_lock(this);
  if (ull)
434
  {
435 436 437 438
    pthread_mutex_lock(&LOCK_user_locks);
    item_user_lock_release(ull);
    pthread_mutex_unlock(&LOCK_user_locks);
    ull= 0;
439
  }
440

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
441 442 443 444
  cleanup_done=1;
  DBUG_VOID_RETURN;
}

445

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
446 447
THD::~THD()
{
448
  THD_CHECK_SENTRY(this);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
449
  DBUG_ENTER("~THD()");
450 451 452
  /* Ensure that no one is using THD */
  pthread_mutex_lock(&LOCK_delete);
  pthread_mutex_unlock(&LOCK_delete);
453
  add_to_status(&global_status_var, &status_var);
454

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
455
  /* Close connection */
serg@serg.mylan's avatar
serg@serg.mylan committed
456
#ifndef EMBEDDED_LIBRARY
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
457 458 459
  if (net.vio)
  {
    vio_delete(net.vio);
serg@serg.mylan's avatar
serg@serg.mylan committed
460
    net_end(&net);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
461
  }
462
#endif
463
  stmt_map.reset();                     /* close all prepared statements */
464
  DBUG_ASSERT(lock_info.n_cursors == 0);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
465 466
  if (!cleanup_done)
    cleanup();
467

serg@serg.mylan's avatar
serg@serg.mylan committed
468
  ha_close_connection(this);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
469

470 471
  DBUG_PRINT("info", ("freeing security context"));
  main_security_ctx.destroy();
472
  safeFree(db);
473
  free_root(&warn_root,MYF(0));
474
#ifdef USING_TRANSACTIONS
475
  free_root(&transaction.mem_root,MYF(0));
476
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
477
  mysys_var=0;					// Safety (shouldn't be needed)
478
  pthread_mutex_destroy(&LOCK_delete);
479
#ifndef DBUG_OFF
konstantin@oak.local's avatar
konstantin@oak.local committed
480
  dbug_sentry= THD_SENTRY_GONE;
481
#endif  
482
  free_root(&main_mem_root, MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
483 484 485
  DBUG_VOID_RETURN;
}

486

487
/*
488 489 490 491 492 493
  Add all status variables to another status variable array

  SYNOPSIS
   add_to_status()
   to_var       add to this array
   from_var     from this array
494 495 496 497 498 499 500 501 502

  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)
{
503 504
  ulong *end= (ulong*) ((byte*) to_var +
                        offsetof(STATUS_VAR, last_system_status_var) +
505 506 507 508 509 510 511 512
			sizeof(ulong));
  ulong *to= (ulong*) to_var, *from= (ulong*) from_var;

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


hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
513
void THD::awake(THD::killed_state state_to_set)
514
{
515
  THD_CHECK_SENTRY(this);
516 517
  safe_mutex_assert_owner(&LOCK_delete); 

hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
518 519
  killed= state_to_set;
  if (state_to_set != THD::KILL_QUERY)
520
  {
hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
521
    thr_alarm_kill(real_id);
522
#ifdef SIGNAL_WITH_VIO_CLOSE
523
    close_active_vio();
524
#endif    
525
  }
526
  if (mysys_var)
527 528 529 530 531 532 533 534 535
  {
    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.
536 537 538 539 540
      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.
541

542
      Note that there is a small chance we fail to kill. If victim has locked
543 544 545 546 547
      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
548
      see it immediately and so may have time to reach the cond_wait().
549
    */
550
    if (mysys_var->current_cond && mysys_var->current_mutex)
551
    {
552 553 554
      pthread_mutex_lock(mysys_var->current_mutex);
      pthread_cond_broadcast(mysys_var->current_cond);
      pthread_mutex_unlock(mysys_var->current_mutex);
555
    }
556 557
    pthread_mutex_unlock(&mysys_var->mutex);
  }
558 559
}

560 561 562 563
/*
  Remember the location of thread info, the structure needed for
  sql_alloc() and the structure for the net buffer
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
564 565 566

bool THD::store_globals()
{
567 568 569 570 571 572
  /*
    Assert that thread_stack is initialized: it's necessary to be able
    to track stack overrun.
  */
  DBUG_ASSERT(this->thread_stack);

573
  if (my_pthread_setspecific_ptr(THR_THD,  this) ||
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
574
      my_pthread_setspecific_ptr(THR_MALLOC, &mem_root))
575 576 577
    return 1;
  mysys_var=my_thread_var;
  dbug_thread_id=my_thread_id();
guilhem@mysql.com's avatar
guilhem@mysql.com committed
578 579 580 581
  /*
    By default 'slave_proxy_id' is 'thread_id'. They may later become different
    if this is the slave SQL thread.
  */
582
  variables.pseudo_thread_id= thread_id;
583 584 585 586
  /*
    We have to call thr_lock_info_init() again here as THD may have been
    created in another thread
  */
587
  thr_lock_info_init(&lock_info);
588
  return 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
589 590
}

591

592 593 594 595 596
/*
  Cleanup after query.

  SYNOPSIS
    THD::cleanup_after_query()
597

598
  DESCRIPTION
599
    This function is used to reset thread data to its default state.
600 601 602 603 604 605 606

  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.
*/
607

608 609
void THD::cleanup_after_query()
{
610
  last_insert_id_used= FALSE;
611 612 613 614 615
  if (clear_next_insert_id)
  {
    clear_next_insert_id= 0;
    next_insert_id= 0;
  }
616 617 618 619 620 621 622 623 624 625 626 627
  /*
    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;
628
  /* Free Items that were created during this execution */
629
  free_items();
630 631
  /* Reset where. */
  where= THD::DEFAULT_WHERE;
632 633
}

634

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
/*
  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;
661
  uint dummy_errors;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
662 663 664 665 666 667
  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,
668
			       from, from_length, from_cs, &dummy_errors);
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
669 670 671 672 673
  to->str[to->length]=0;			// Safety
  DBUG_RETURN(0);
}


674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
/*
  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)
{
691 692
  uint dummy_errors;
  if (convert_buffer.copy(s->ptr(), s->length(), from_cs, to_cs, &dummy_errors))
693 694 695 696 697 698 699 700 701 702 703
    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;
}

704

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
705 706 707 708 709 710
/*
  Update some cache variables when character set changes
*/

void THD::update_charset()
{
711 712 713 714 715 716 717
  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);
bar@mysql.com's avatar
bar@mysql.com committed
718 719 720
  charset_is_character_set_filesystem= 
    !String::needs_conversion(0, charset(),
                              variables.character_set_filesystem, &not_used);
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
721 722 723
}


724 725 726 727 728 729 730 731 732 733 734 735 736 737
/* 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 */
738

739 740
void THD::add_changed_table(TABLE *table)
{
741
  DBUG_ENTER("THD::add_changed_table(table)");
742

743
  DBUG_ASSERT((options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN)) &&
744
	      table->file->has_transactions());
745
  add_changed_table(table->s->table_cache_key, table->s->key_length);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
746
  DBUG_VOID_RETURN;
747
}
748

749

750 751 752
void THD::add_changed_table(const char *key, long key_length)
{
  DBUG_ENTER("THD::add_changed_table(key)");
753 754
  CHANGED_TABLE_LIST **prev_changed = &transaction.changed_tables;
  CHANGED_TABLE_LIST *curr = transaction.changed_tables;
755

756
  for (; curr; prev_changed = &(curr->next), curr = curr->next)
757
  {
758
    int cmp =  (long)curr->key_length - (long)key_length;
759 760
    if (cmp < 0)
    {
761
      list_include(prev_changed, curr, changed_table_dup(key, key_length));
762
      DBUG_PRINT("info", 
763 764
		 ("key_length: %ld  %u", key_length,
                  (*prev_changed)->key_length));
765 766 767 768
      DBUG_VOID_RETURN;
    }
    else if (cmp == 0)
    {
769
      cmp = memcmp(curr->key, key, curr->key_length);
770 771
      if (cmp < 0)
      {
772
	list_include(prev_changed, curr, changed_table_dup(key, key_length));
773
	DBUG_PRINT("info", 
774
		   ("key_length:  %ld  %u", key_length,
775
		    (*prev_changed)->key_length));
776 777 778 779 780 781 782 783 784
	DBUG_VOID_RETURN;
      }
      else if (cmp == 0)
      {
	DBUG_PRINT("info", ("already in list"));
	DBUG_VOID_RETURN;
      }
    }
  }
785
  *prev_changed = changed_table_dup(key, key_length);
786
  DBUG_PRINT("info", ("key_length: %ld  %u", key_length,
787
		      (*prev_changed)->key_length));
788 789 790
  DBUG_VOID_RETURN;
}

791

792
CHANGED_TABLE_LIST* THD::changed_table_dup(const char *key, long key_length)
793 794 795
{
  CHANGED_TABLE_LIST* new_table = 
    (CHANGED_TABLE_LIST*) trans_alloc(ALIGN_SIZE(sizeof(CHANGED_TABLE_LIST))+
796
				      key_length + 1);
797 798
  if (!new_table)
  {
799 800
    my_error(EE_OUTOFMEMORY, MYF(ME_BELL),
             ALIGN_SIZE(sizeof(TABLE_LIST)) + key_length + 1);
hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
801
    killed= KILL_CONNECTION;
802 803 804 805 806 807
    return 0;
  }

  new_table->key = (char *) (((byte*)new_table)+
			     ALIGN_SIZE(sizeof(CHANGED_TABLE_LIST)));
  new_table->next = 0;
808 809
  new_table->key_length = key_length;
  ::memcpy(new_table->key, key, key_length);
810 811 812
  return new_table;
}

813

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
814 815 816 817
int THD::send_explain_fields(select_result *result)
{
  List<Item> field_list;
  Item *item;
818
  CHARSET_INFO *cs= system_charset_info;
819
  field_list.push_back(new Item_return_int("id",3, MYSQL_TYPE_LONGLONG));
820
  field_list.push_back(new Item_empty_string("select_type", 19, cs));
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
821 822 823 824
  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;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
825
  field_list.push_back(item=new Item_empty_string("possible_keys",
826
						  NAME_LEN*MAX_KEY, cs));
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
827
  item->maybe_null=1;
828
  field_list.push_back(item=new Item_empty_string("key", NAME_LEN, cs));
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
829
  item->maybe_null=1;
830 831
  field_list.push_back(item=new Item_empty_string("key_len",
						  NAME_LEN*MAX_KEY));
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
832 833
  item->maybe_null=1;
  field_list.push_back(item=new Item_empty_string("ref",
834
						  NAME_LEN*MAX_REF_PARTS, cs));
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
835
  item->maybe_null=1;
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
836 837 838
  field_list.push_back(item= new Item_return_int("rows", 10,
                                                 MYSQL_TYPE_LONGLONG));
  item->maybe_null= 1;
839
  field_list.push_back(new Item_empty_string("Extra", 255, cs));
840 841
  return (result->send_fields(field_list,
                              Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF));
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
842
}
843

844 845 846
#ifdef SIGNAL_WITH_VIO_CLOSE
void THD::close_active_vio()
{
847
  DBUG_ENTER("close_active_vio");
848
  safe_mutex_assert_owner(&LOCK_delete); 
849
#ifndef EMBEDDED_LIBRARY
850 851 852 853 854
  if (active_vio)
  {
    vio_close(active_vio);
    active_vio = 0;
  }
855
#endif
856
  DBUG_VOID_RETURN;
857 858 859
}
#endif

860

861 862 863 864 865
struct Item_change_record: public ilink
{
  Item **place;
  Item *old_value;
  /* Placement new was hidden by `new' in ilink (TODO: check): */
866
  static void *operator new(size_t size, void *mem) { return mem; }
867 868
  static void operator delete(void *ptr, size_t size) {}
  static void operator delete(void *ptr, void *mem) { /* never called */ }
869 870 871 872 873 874
};


/*
  Register an item tree tree transformation, performed by the query
  optimizer. We need a pointer to runtime_memroot because it may be !=
konstantin@mysql.com's avatar
konstantin@mysql.com committed
875
  thd->mem_root (due to possible set_n_backup_active_arena called for thd).
876 877 878 879 880 881 882 883 884 885 886 887 888 889
*/

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)
  {
890 891 892 893
    /*
      OOM, thd->fatal_error() is called by the error handler of the
      memroot. Just return.
    */
894 895 896 897 898
    return;
  }
  change= new (change_mem) Item_change_record;
  change->place= place;
  change->old_value= old_value;
899
  change_list.append(change);
900 901 902 903 904 905 906
}


void THD::rollback_item_tree_changes()
{
  I_List_iterator<Item_change_record> it(change_list);
  Item_change_record *change;
monty@mysql.com's avatar
monty@mysql.com committed
907 908
  DBUG_ENTER("rollback_item_tree_changes");

909 910 911 912
  while ((change= it++))
    *change->place= change->old_value;
  /* We can forget about changes memory: it's allocated in runtime memroot */
  change_list.empty();
monty@mysql.com's avatar
monty@mysql.com committed
913
  DBUG_VOID_RETURN;
914 915 916
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
917 918 919 920 921 922 923 924 925
/*****************************************************************************
** Functions to provide a interface to select results
*****************************************************************************/

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

926 927
void select_result::send_error(uint errcode,const char *err)
{
928
  my_message(errcode, err, MYF(0));
929 930
}

931 932 933 934 935 936

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

937 938 939 940 941 942 943
bool select_result::check_simple_select() const
{
  my_error(ER_SP_BAD_CURSOR_QUERY, MYF(0));
  return TRUE;
}


944 945 946
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);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
947 948 949 950 951

sql_exchange::sql_exchange(char *name,bool flag)
  :file_name(name), opt_enclosed(0), dumpfile(flag), skip_lines(0)
{
  field_term= &default_field_term;
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
952
  enclosed=   line_start= &my_empty_string;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
953 954
  line_term=  &default_line_term;
  escaped=    &default_escaped;
955
  cs= NULL;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
956 957
}

958
bool select_send::send_fields(List<Item> &list, uint flags)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
959
{
960 961 962 963
  bool res;
  if (!(res= thd->protocol->send_fields(&list, flags)))
    status= 1;
  return res;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
964 965
}

966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
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;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
988 989 990 991
/* Send data to client. Returns 0 if ok */

bool select_send::send_data(List<Item> &items)
{
992
  if (unit->offset_limit_cnt)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
993
  {						// using limit offset,count
994
    unit->offset_limit_cnt--;
995
    return 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
996
  }
997

monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
998 999 1000 1001 1002
  /*
    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
  */
1003 1004
    ha_release_temporary_latches(thd);

1005 1006 1007
  List_iterator_fast<Item> li(items);
  Protocol *protocol= thd->protocol;
  char buff[MAX_FIELD_WIDTH];
1008
  String buffer(buff, sizeof(buff), &my_charset_bin);
1009
  DBUG_ENTER("select_send::send_data");
1010 1011

  protocol->prepare_for_resend();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1012 1013 1014
  Item *item;
  while ((item=li++))
  {
1015
    if (item->send(protocol, &buffer))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1016
    {
1017
      protocol->free();				// Free used buffer
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1018
      my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES), MYF(0));
1019
      break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1020 1021
    }
  }
1022
  thd->sent_row_count++;
1023
  if (!thd->vio_ok())
1024
    DBUG_RETURN(0);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1025
  if (!thd->net.report_error)
1026
    DBUG_RETURN(protocol->write());
1027
  protocol->remove_last_row();
1028
  DBUG_RETURN(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1029 1030 1031 1032
}

bool select_send::send_eof()
{
1033 1034 1035 1036 1037
  /* 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);

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1038 1039 1040
  /* Unlock tables before sending packet to gain some speed */
  if (thd->lock)
  {
1041 1042
    mysql_unlock_tables(thd, thd->lock);
    thd->lock=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1043
  }
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1044 1045
  if (!thd->net.report_error)
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1046
    ::send_eof(thd);
1047
    status= 0;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1048 1049 1050 1051
    return 0;
  }
  else
    return 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1052 1053 1054
}


1055 1056 1057
/************************************************************************
  Handling writing to file
************************************************************************/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1058

1059 1060
void select_to_file::send_error(uint errcode,const char *err)
{
1061
  my_message(errcode, err, MYF(0));
1062 1063 1064 1065 1066 1067 1068 1069
  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;
  }
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1070 1071


1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
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;
}


1098
select_to_file::~select_to_file()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1099 1100 1101 1102 1103 1104 1105
{
  if (file >= 0)
  {					// This only happens in case of error
    (void) end_io_cache(&cache);
    (void) my_close(file,MYF(0));
    file= -1;
  }
1106 1107 1108 1109 1110 1111 1112 1113
}

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

select_export::~select_export()
{
1114
  thd->sent_row_count=row_count;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1115 1116
}

1117

1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
/*
  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)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1136
{
1137
  File file;
1138
  uint option= MY_UNPACK_FILENAME | MY_RELATIVE_PATH;
1139

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1140
#ifdef DONT_ALLOW_FULL_LOAD_DATA_PATHS
1141
  option|= MY_REPLACE_DIR;			// Force use of db directory
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1142
#endif
1143

hf@deer.(none)'s avatar
hf@deer.(none) committed
1144
  if (!dirname_length(exchange->file_name))
1145 1146 1147 1148 1149 1150
  {
    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);
1151 1152 1153 1154 1155 1156 1157 1158 1159

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

1160
  if (!access(path, F_OK))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1161
  {
1162
    my_error(ER_FILE_EXISTS_ERROR, MYF(0), exchange->file_name);
1163
    return -1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1164 1165
  }
  /* Create the file world readable */
serg@serg.mylan's avatar
serg@serg.mylan committed
1166
  if ((file= my_create(path, 0666, O_WRONLY|O_EXCL, MYF(MY_WME))) < 0)
1167
    return file;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1168
#ifdef HAVE_FCHMOD
1169
  (void) fchmod(file, 0666);			// Because of umask()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1170
#else
1171
  (void) chmod(path, 0666);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1172
#endif
1173
  if (init_io_cache(cache, file, 0L, WRITE_CACHE, 0L, 1, MYF(MY_WME)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1174
  {
1175
    my_close(file, MYF(0));
1176
    my_delete(path, MYF(0));  // Delete file on error, it was just created 
1177
    return -1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1178
  }
1179
  return file;
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
}


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

1191
  if ((file= create_file(thd, path, exchange, &cache)) < 0)
1192
    return 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1193 1194
  /* Check if there is any blobs in data */
  {
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
1195
    List_iterator_fast<Item> li(list);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
    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);
gshchepa/uchum@gleb.loc's avatar
gshchepa/uchum@gleb.loc committed
1212
  is_ambiguous_field_sep= test(strchr(ESCAPE_CHARS, field_sep_char));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
  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;
}


1225 1226 1227 1228 1229
#define NEED_ESCAPING(x) ((int) (uchar) (x) == escape_char    || \
                          (int) (uchar) (x) == field_sep_char || \
                          (int) (uchar) (x) == line_sep_char  || \
                          !(x))

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1230 1231 1232
bool select_export::send_data(List<Item> &items)
{

1233
  DBUG_ENTER("select_export::send_data");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1234 1235
  char buff[MAX_FIELD_WIDTH],null_buff[2],space[MAX_FIELD_WIDTH];
  bool space_inited=0;
1236
  String tmp(buff,sizeof(buff),&my_charset_bin),*res;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1237 1238
  tmp.length(0);

1239
  if (unit->offset_limit_cnt)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1240
  {						// using limit offset,count
1241
    unit->offset_limit_cnt--;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1242 1243 1244 1245 1246
    DBUG_RETURN(0);
  }
  row_count++;
  Item *item;
  uint used_length=0,items_left=items.elements;
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
1247
  List_iterator_fast<Item> li(items);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 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

  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();
      if (result_type == STRING_RESULT && escape_char != -1)
      {
1289 1290 1291 1292 1293 1294 1295 1296 1297
        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);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1298 1299 1300 1301 1302
	for (start=pos=(char*) res->ptr(),end=pos+used_length ;
	     pos != end ;
	     pos++)
	{
#ifdef USE_MB
1303
	  if (use_mb(res_charset))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1304 1305
	  {
	    int l;
1306
	    if ((l=my_ismbchar(res_charset, pos, end)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1307 1308 1309 1310 1311 1312
	    {
	      pos += l-1;
	      continue;
	    }
	  }
#endif
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 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

          /*
            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])))
          {
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1352
	    char tmp_buff[2];
gshchepa/uchum@gleb.loc's avatar
gshchepa/uchum@gleb.loc committed
1353 1354 1355
            tmp_buff[0]= ((int) *pos == field_sep_char &&
                          is_ambiguous_field_sep) ?
                          field_sep_char : escape_char;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
	    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;
1380
	for (; length > sizeof(space) ; length-=sizeof(space))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
	{
	  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))
    {
1391 1392 1393
      if (my_b_write(&cache, (byte*) exchange->enclosed->ptr(),
                     exchange->enclosed->length()))
        goto err;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1394 1395 1396
    }
    if (--items_left)
    {
1397 1398 1399
      if (my_b_write(&cache, (byte*) exchange->field_term->ptr(),
                     field_term_length))
        goto err;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416
    }
  }
  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
1417 1418
select_dump::prepare(List<Item> &list __attribute__((unused)),
		     SELECT_LEX_UNIT *u)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1419
{
1420
  unit= u;
1421
  return (int) ((file= create_file(thd, path, exchange, &cache)) < 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1422 1423 1424 1425 1426
}


bool select_dump::send_data(List<Item> &items)
{
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
1427
  List_iterator_fast<Item> li(items);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1428
  char buff[MAX_FIELD_WIDTH];
1429
  String tmp(buff,sizeof(buff),&my_charset_bin),*res;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1430 1431
  tmp.length(0);
  Item *item;
1432
  DBUG_ENTER("select_dump::send_data");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1433

1434
  if (unit->offset_limit_cnt)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1435
  {						// using limit offset,count
1436
    unit->offset_limit_cnt--;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1437 1438 1439 1440
    DBUG_RETURN(0);
  }
  if (row_count++ > 1) 
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1441
    my_message(ER_TOO_MANY_ROWS, ER(ER_TOO_MANY_ROWS), MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1442 1443 1444 1445 1446
    goto err;
  }
  while ((item=li++))
  {
    res=item->str_result(&tmp);
1447
    if (!res)					// If NULL
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1448
    {
1449 1450
      if (my_b_write(&cache,(byte*) "",1))
	goto err;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1451 1452 1453
    }
    else if (my_b_write(&cache,(byte*) res->ptr(),res->length()))
    {
1454
      my_error(ER_ERROR_ON_WRITE, MYF(0), path, my_errno);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1455 1456 1457 1458 1459 1460 1461 1462 1463
      goto err;
    }
  }
  DBUG_RETURN(0);
err:
  DBUG_RETURN(1);
}


1464
select_subselect::select_subselect(Item_subselect *item_arg)
1465
{
1466
  item= item_arg;
1467 1468
}

1469

1470
bool select_singlerow_subselect::send_data(List<Item> &items)
1471
{
1472 1473
  DBUG_ENTER("select_singlerow_subselect::send_data");
  Item_singlerow_subselect *it= (Item_singlerow_subselect *)item;
Sinisa@sinisa.nasamreza.org's avatar
Sinisa@sinisa.nasamreza.org committed
1474 1475
  if (it->assigned())
  {
1476
    my_message(ER_SUBQUERY_NO_1_ROW, ER(ER_SUBQUERY_NO_1_ROW), MYF(0));
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1477 1478 1479
    DBUG_RETURN(1);
  }
  if (unit->offset_limit_cnt)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1480
  {				          // Using limit offset,count
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1481 1482
    unit->offset_limit_cnt--;
    DBUG_RETURN(0);
1483
  }
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1484
  List_iterator_fast<Item> li(items);
1485 1486 1487
  Item *val_item;
  for (uint i= 0; (val_item= li++); i++)
    it->store(i, val_item);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1488
  it->assigned(1);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1489
  DBUG_RETURN(0);
1490
}
1491

1492

1493 1494 1495 1496 1497 1498 1499 1500
void select_max_min_finder_subselect::cleanup()
{
  DBUG_ENTER("select_max_min_finder_subselect::cleanup");
  cache= 0;
  DBUG_VOID_RETURN;
}


1501 1502 1503
bool select_max_min_finder_subselect::send_data(List<Item> &items)
{
  DBUG_ENTER("select_max_min_finder_subselect::send_data");
1504
  Item_maxmin_subselect *it= (Item_maxmin_subselect *)item;
1505 1506
  List_iterator_fast<Item> li(items);
  Item *val_item= li++;
1507
  it->register_value();
1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
  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;
1530 1531 1532
      case DECIMAL_RESULT:
        op= &select_max_min_finder_subselect::cmp_decimal;
        break;
1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
      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()
{
1548
  Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0);
1549
  double val1= cache->val_real(), val2= maxmin->val_real();
1550 1551 1552 1553
  if (fmax)
    return (cache->null_value && !maxmin->null_value) ||
      (!cache->null_value && !maxmin->null_value &&
       val1 > val2);
1554 1555 1556
  return (maxmin->null_value && !cache->null_value) ||
    (!cache->null_value && !maxmin->null_value &&
     val1 < val2);
1557 1558 1559 1560
}

bool select_max_min_finder_subselect::cmp_int()
{
1561
  Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0);
1562 1563 1564 1565 1566
  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);
1567 1568 1569
  return (maxmin->null_value && !cache->null_value) ||
    (!cache->null_value && !maxmin->null_value &&
     val1 < val2);
1570 1571
}

1572 1573
bool select_max_min_finder_subselect::cmp_decimal()
{
1574
  Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0);
1575 1576 1577 1578 1579 1580
  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) ;
1581 1582 1583
  return (maxmin->null_value && !cache->null_value) ||
    (!cache->null_value && !maxmin->null_value &&
     my_decimal_cmp(cvalue,mvalue) < 0);
1584 1585
}

1586 1587 1588
bool select_max_min_finder_subselect::cmp_str()
{
  String *val1, *val2, buf1, buf2;
1589
  Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0);
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
  /*
    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) ;
1600 1601 1602
  return (maxmin->null_value && !cache->null_value) ||
    (!cache->null_value && !maxmin->null_value &&
     sortcmp(val1, val2, cache->collation.collation) < 0);
1603 1604
}

1605 1606 1607 1608 1609 1610 1611 1612 1613 1614
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;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1615
  it->assigned(1);
1616 1617 1618
  DBUG_RETURN(0);
}

Sinisa@sinisa.nasamreza.org's avatar
Sinisa@sinisa.nasamreza.org committed
1619 1620

/***************************************************************************
1621
  Dump of select to variables
Sinisa@sinisa.nasamreza.org's avatar
Sinisa@sinisa.nasamreza.org committed
1622
***************************************************************************/
1623

1624
int select_dumpvar::prepare(List<Item> &list, SELECT_LEX_UNIT *u)
Sinisa@sinisa.nasamreza.org's avatar
Sinisa@sinisa.nasamreza.org committed
1625
{
1626
  unit= u;
1627
  
1628
  if (var_list.elements != list.elements)
Sinisa@sinisa.nasamreza.org's avatar
Sinisa@sinisa.nasamreza.org committed
1629
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1630 1631
    my_message(ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT,
               ER(ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT), MYF(0));
1632
    return 1;
1633
  }               
1634 1635
  return 0;
}
1636

1637

1638 1639 1640 1641 1642 1643 1644
bool select_dumpvar::check_simple_select() const
{
  my_error(ER_SP_BAD_CURSOR_SELECT, MYF(0));
  return TRUE;
}


1645 1646
void select_dumpvar::cleanup()
{
1647
  row_count= 0;
1648 1649 1650
}


serg@serg.mylan's avatar
serg@serg.mylan committed
1651
Query_arena::Type Query_arena::type() const
1652
{
monty@mysql.com's avatar
monty@mysql.com committed
1653
  DBUG_ASSERT(0); /* Should never be called */
1654
  return STATEMENT;
1655 1656 1657
}


1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
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;
}


1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685
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");
}

1686 1687 1688 1689
/*
  Statement functions 
*/

1690 1691 1692
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),
1693
  id(id_arg),
1694
  set_query_id(1),
1695
  lex(lex_arg),
1696
  query(0),
1697 1698
  query_length(0),
  cursor(0)
1699
{
1700
  name.str= NULL;
1701 1702 1703
}


serg@serg.mylan's avatar
serg@serg.mylan committed
1704
Query_arena::Type Statement::type() const
1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716
{
  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;
1717
  cursor=         stmt->cursor;
1718 1719 1720
}


1721 1722 1723
void
Statement::set_n_backup_statement(Statement *stmt, Statement *backup)
{
1724
  DBUG_ENTER("Statement::set_n_backup_statement");
1725 1726
  backup->set_statement(this);
  set_statement(stmt);
1727
  DBUG_VOID_RETURN;
1728 1729 1730 1731 1732
}


void Statement::restore_backup_statement(Statement *stmt, Statement *backup)
{
1733
  DBUG_ENTER("Statement::restore_backup_statement");
1734 1735
  stmt->set_statement(this);
  set_statement(backup);
1736
  DBUG_VOID_RETURN;
1737 1738 1739
}


1740
void THD::end_statement()
1741
{
1742
  /* Cleanup SQL processing state to reuse this statement in next query. */
1743 1744 1745
  lex_end(lex);
  delete lex->result;
  lex->result= 0;
1746 1747
  /* Note that free_list is freed in cleanup_after_query() */

1748 1749 1750 1751 1752 1753 1754
  /*
    Don't free mem_root, as mem_root is freed in the end of dispatch_command
    (once for any command).
  */
}


konstantin@mysql.com's avatar
konstantin@mysql.com committed
1755
void THD::set_n_backup_active_arena(Query_arena *set, Query_arena *backup)
1756
{
konstantin@mysql.com's avatar
konstantin@mysql.com committed
1757
  DBUG_ENTER("THD::set_n_backup_active_arena");
1758
  DBUG_ASSERT(backup->is_backup_arena == FALSE);
1759

konstantin@mysql.com's avatar
konstantin@mysql.com committed
1760 1761
  backup->set_query_arena(this);
  set_query_arena(set);
monty@mysql.com's avatar
monty@mysql.com committed
1762
#ifndef DBUG_OFF
1763
  backup->is_backup_arena= TRUE;
monty@mysql.com's avatar
monty@mysql.com committed
1764
#endif
1765
  DBUG_VOID_RETURN;
1766 1767 1768
}


konstantin@mysql.com's avatar
konstantin@mysql.com committed
1769
void THD::restore_active_arena(Query_arena *set, Query_arena *backup)
1770
{
konstantin@mysql.com's avatar
konstantin@mysql.com committed
1771
  DBUG_ENTER("THD::restore_active_arena");
1772
  DBUG_ASSERT(backup->is_backup_arena);
konstantin@mysql.com's avatar
konstantin@mysql.com committed
1773 1774
  set->set_query_arena(this);
  set_query_arena(backup);
monty@mysql.com's avatar
monty@mysql.com committed
1775
#ifndef DBUG_OFF
1776
  backup->is_backup_arena= FALSE;
1777
#endif
monty@mysql.com's avatar
monty@mysql.com committed
1778
  DBUG_VOID_RETURN;
1779 1780
}

1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800
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;
}

1801 1802
static byte *get_stmt_name_hash_key(Statement *entry, uint *length,
                                    my_bool not_used __attribute__((unused)))
1803 1804 1805 1806 1807
{
  *length=(uint) entry->name.length;
  return (byte*) entry->name.str;
}

1808 1809 1810 1811 1812
C_MODE_END

Statement_map::Statement_map() :
  last_found_statement(0)
{
1813 1814 1815 1816 1817
  enum
  {
    START_STMT_HASH_SIZE = 16,
    START_NAME_HASH_SIZE = 16
  };
1818
  hash_init(&st_hash, &my_charset_bin, START_STMT_HASH_SIZE, 0, 0,
1819 1820
            get_statement_id_as_hash_key,
            delete_statement_as_hash_key, MYF(0));
1821
  hash_init(&names_hash, system_charset_info, START_NAME_HASH_SIZE, 0, 0,
1822 1823
            (hash_get_key) get_stmt_name_hash_key,
            NULL,MYF(0));
1824 1825
}

1826

1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848
/*
  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)
1849
{
1850 1851 1852 1853 1854 1855 1856 1857 1858 1859
  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;
  }
1860
  if (statement->name.str && my_hash_insert(&names_hash, (byte*) statement))
1861
  {
1862 1863
    my_error(ER_OUT_OF_RESOURCES, MYF(0));
    goto err_names_hash;
1864
  }
1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
  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);
1876 1877
    my_error(ER_MAX_PREPARED_STMT_COUNT_REACHED, MYF(0),
             max_prepared_stmt_count);
1878 1879 1880 1881 1882
    goto err_max;
  }
  prepared_stmt_count++;
  pthread_mutex_unlock(&LOCK_prepared_stmt_count);

1883
  last_found_statement= statement;
1884 1885 1886 1887 1888 1889 1890 1891 1892
  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;
1893 1894
}

1895

1896 1897
void Statement_map::close_transient_cursors()
{
1898
#ifdef TO_BE_IMPLEMENTED
1899 1900 1901
  Statement *stmt;
  while ((stmt= transient_cursor_list.head()))
    stmt->close_cursor();                 /* deletes itself from the list */
1902
#endif
1903 1904 1905
}


1906 1907 1908 1909 1910 1911
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);
1912

1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931
  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;
1932 1933
}

1934

1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946
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);
}

1947 1948
bool select_dumpvar::send_data(List<Item> &items)
{
1949
  List_iterator_fast<my_var> var_li(var_list);
1950
  List_iterator<Item> it(items);
1951
  Item *item;
1952
  my_var *mv;
1953
  DBUG_ENTER("select_dumpvar::send_data");
1954

1955
  if (unit->offset_limit_cnt)
1956
  {						// using limit offset,count
1957 1958 1959
    unit->offset_limit_cnt--;
    DBUG_RETURN(0);
  }
1960 1961
  if (row_count++) 
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1962
    my_message(ER_TOO_MANY_ROWS, ER(ER_TOO_MANY_ROWS), MYF(0));
1963 1964
    DBUG_RETURN(1);
  }
1965
  while ((mv= var_li++) && (item= it++))
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1966
  {
1967
    if (mv->local)
1968
    {
1969 1970
      if (thd->spcont->set_variable(thd, mv->offset, &item))
	    DBUG_RETURN(1);
1971 1972 1973
    }
    else
    {
1974 1975 1976
      Item_func_set_user_var *suv= new Item_func_set_user_var(mv->s, item);
      suv->fix_fields(thd, 0);
      suv->check(0);
1977
      suv->update();
1978
    }
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1979
  }
Sinisa@sinisa.nasamreza.org's avatar
Sinisa@sinisa.nasamreza.org committed
1980 1981 1982 1983 1984
  DBUG_RETURN(0);
}

bool select_dumpvar::send_eof()
{
1985
  if (! row_count)
serg@serg.mylan's avatar
serg@serg.mylan committed
1986 1987
    push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                 ER_SP_FETCH_NO_DATA, ER(ER_SP_FETCH_NO_DATA));
1988 1989
  ::send_ok(thd,row_count);
  return 0;
Sinisa@sinisa.nasamreza.org's avatar
Sinisa@sinisa.nasamreza.org committed
1990
}
1991 1992 1993 1994 1995 1996 1997

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

void TMP_TABLE_PARAM::init()
{
1998 1999
  DBUG_ENTER("TMP_TABLE_PARAM::init");
  DBUG_PRINT("enter", ("this: 0x%lx", (ulong)this));
2000 2001 2002
  field_count= sum_func_count= func_count= hidden_field_count= 0;
  group_parts= group_length= group_null_parts= 0;
  quick_group= 1;
2003
  table_charset= 0;
2004
  precomputed_group_by= 0;
2005
  DBUG_VOID_RETURN;
2006
}
2007 2008 2009 2010


void thd_increment_bytes_sent(ulong length)
{
serg@serg.mylan's avatar
serg@serg.mylan committed
2011
  THD *thd=current_thd;
lars@mysql.com's avatar
lars@mysql.com committed
2012
  if (likely(thd != 0))
serg@serg.mylan's avatar
serg@serg.mylan committed
2013 2014 2015
  { /* current_thd==0 when close_connection() calls net_send_error() */
    thd->status_var.bytes_sent+= length;
  }
2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034
}


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

2036

2037
void Security_context::init()
2038 2039 2040
{
  host= user= priv_user= ip= 0;
  host_or_ip= "connecting host";
2041
  priv_host[0]= '\0';
2042 2043 2044 2045 2046 2047
#ifndef NO_EMBEDDED_ACCESS_CHECKS
  db_access= NO_ACCESS;
#endif
}


2048
void Security_context::destroy()
2049 2050 2051 2052 2053 2054 2055 2056 2057 2058
{
  // If not pointer to constant
  if (host != my_localhost)
    safeFree(host);
  if (user != delayed_user)
    safeFree(user);
  safeFree(ip);
}


2059
void Security_context::skip_grants()
2060 2061 2062 2063 2064 2065 2066 2067 2068
{
  /* privileges for the user are unknown everything is allowed */
  host_or_ip= (char *)"";
  master_access= ~NO_ACCESS;
  priv_user= (char *)"";
  *priv_host= '\0';
}


2069 2070 2071 2072 2073 2074 2075 2076
/****************************************************************************
  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.
****************************************************************************/

2077
void THD::reset_n_backup_open_tables_state(Open_tables_state *backup)
2078
{
2079 2080
  DBUG_ENTER("reset_n_backup_open_tables_state");
  backup->set_open_tables_state(this);
2081
  reset_open_tables_state();
2082
  DBUG_VOID_RETURN;
2083 2084 2085
}


2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097
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);
2098 2099
  DBUG_VOID_RETURN;
}
2100 2101


2102

2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115
/****************************************************************************
  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
2116
  - Value of last_insert_id() is saved and restored
2117 2118 2119 2120
  - 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
2121
  - new savepoint level is created and destroyed
2122 2123 2124 2125 2126 2127

  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.
2128 2129

    We do not reset value of last_insert_id().
2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140
****************************************************************************/

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;
ramil@mysql.com's avatar
ramil@mysql.com committed
2141
  backup->current_insert_id=  current_insert_id;
2142
  backup->insert_id_used=  insert_id_used;
ramil@mysql.com's avatar
ramil@mysql.com committed
2143
  backup->last_insert_id_used=  last_insert_id_used;
2144
  backup->clear_next_insert_id= clear_next_insert_id;
2145 2146 2147 2148 2149
  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;
2150
  backup->savepoints= transaction.savepoints;
2151

2152 2153
  if (!lex->requires_prelocking() || is_update_query(lex->sql_command))
    options&= ~OPTION_BIN_LOG;
2154 2155 2156 2157

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

2158 2159 2160 2161 2162 2163 2164 2165
  /* 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;
2166
  transaction.savepoints= 0;
2167 2168 2169 2170 2171 2172 2173 2174

  /* 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)
{
2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189
  /*
    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;
2190 2191 2192 2193 2194 2195
  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;
ramil@mysql.com's avatar
ramil@mysql.com committed
2196
  current_insert_id= backup->current_insert_id;
2197
  insert_id_used=   backup->insert_id_used;
ramil@mysql.com's avatar
ramil@mysql.com committed
2198
  last_insert_id_used= backup->last_insert_id_used;
2199
  clear_next_insert_id= backup->clear_next_insert_id;
2200 2201 2202 2203
  limit_found_rows= backup->limit_found_rows;
  sent_row_count=   backup->sent_row_count;
  client_capabilities= backup->client_capabilities;

2204 2205 2206
  if ((options & OPTION_BIN_LOG) && is_update_query(lex->sql_command))
    mysql_bin_log.stop_union_events(this);

2207 2208 2209 2210 2211 2212 2213
  /*
    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;
}
2214 2215 2216 2217 2218 2219


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

2220 2221 2222 2223 2224 2225
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)))
{
2226 2227
  *length=((XID_STATE*)ptr)->xid.key_length();
  return ((XID_STATE*)ptr)->xid.key();
2228 2229 2230 2231 2232
}

static void xid_free_hash (void *ptr)
{
  if (!((XID_STATE*)ptr)->in_thd)
kent@mysql.com's avatar
kent@mysql.com committed
2233
    my_free((gptr)ptr, MYF(0));
2234 2235 2236 2237 2238
}

bool xid_cache_init()
{
  pthread_mutex_init(&LOCK_xid_cache, MY_MUTEX_INIT_FAST);
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
2239 2240
  return hash_init(&xid_cache, &my_charset_bin, 100, 0, 0,
                   xid_get_hash_key, xid_free_hash, 0) != 0;
2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254
}

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);
2255
  XID_STATE *res=(XID_STATE *)hash_search(&xid_cache, xid->key(), xid->key_length());
2256 2257 2258 2259
  pthread_mutex_unlock(&LOCK_xid_cache);
  return res;
}

2260

2261 2262 2263 2264 2265
bool xid_cache_insert(XID *xid, enum xa_states xa_state)
{
  XID_STATE *xs;
  my_bool res;
  pthread_mutex_lock(&LOCK_xid_cache);
2266
  if (hash_search(&xid_cache, xid->key(), xid->key_length()))
2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280
    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;
}

2281

2282 2283 2284
bool xid_cache_insert(XID_STATE *xid_state)
{
  pthread_mutex_lock(&LOCK_xid_cache);
2285 2286
  DBUG_ASSERT(hash_search(&xid_cache, xid_state->xid.key(),
                          xid_state->xid.key_length())==0);
2287 2288 2289 2290 2291
  my_bool res=my_hash_insert(&xid_cache, (byte*)xid_state);
  pthread_mutex_unlock(&LOCK_xid_cache);
  return res;
}

2292

2293 2294 2295 2296 2297 2298 2299
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);
}