sql_insert.cc 40.5 KB
Newer Older
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1
/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult 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 5 6
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
7

bk@work.mysql.com's avatar
bk@work.mysql.com committed
8 9 10 11
   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
12

bk@work.mysql.com's avatar
bk@work.mysql.com committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
   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 */


/* Insert of records */

#include "mysql_priv.h"
#include "sql_acl.h"

static int check_null_fields(THD *thd,TABLE *entry);
static TABLE *delayed_get_table(THD *thd,TABLE_LIST *table_list);
static int write_delayed(THD *thd,TABLE *table, enum_duplicates dup,
			 char *query, uint query_length, bool log_on);
static void end_delayed_insert(THD *thd);
28
extern "C" pthread_handler_decl(handle_delayed_insert,arg);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
static void unlink_blobs(register TABLE *table);

/* Define to force use of my_malloc() if the allocated memory block is big */

#ifndef HAVE_ALLOCA
#define my_safe_alloca(size, min_length) my_alloca(size)
#define my_safe_afree(ptr, size, min_length) my_afree(ptr)
#else
#define my_safe_alloca(size, min_length) ((size <= min_length) ? my_alloca(size) : my_malloc(size,MYF(0)))
#define my_safe_afree(ptr, size, min_length) if (size > min_length) my_free(ptr,MYF(0))
#endif


/*
  Check if insert fields are correct
44 45
  Updates table->time_stamp to point to timestamp field or 0, depending on
  if timestamp should be updated or not.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
*/

static int
check_insert_fields(THD *thd,TABLE *table,List<Item> &fields,
		    List<Item> &values, ulong counter)
{
  if (fields.elements == 0 && values.elements != 0)
  {
    if (values.elements != table->fields)
    {
      my_printf_error(ER_WRONG_VALUE_COUNT_ON_ROW,
		      ER(ER_WRONG_VALUE_COUNT_ON_ROW),
		      MYF(0),counter);
      return -1;
    }
    if (grant_option &&
	check_grant_all_columns(thd,INSERT_ACL,table))
      return -1;
64
    table->time_stamp=0;			// This is saved by caller
bk@work.mysql.com's avatar
bk@work.mysql.com committed
65 66 67 68 69 70 71 72 73 74 75 76
  }
  else
  {						// Part field list
    if (fields.elements != values.elements)
    {
      my_printf_error(ER_WRONG_VALUE_COUNT_ON_ROW,
		      ER(ER_WRONG_VALUE_COUNT_ON_ROW),
		      MYF(0),counter);
      return -1;
    }
    TABLE_LIST table_list;
    bzero((char*) &table_list,sizeof(table_list));
77
    table_list.db=  table->table_cache_key;
78
    table_list.real_name= table_list.alias= table->table_name;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
79 80 81 82
    table_list.table=table;
    table_list.grant=table->grant;

    thd->dupp_field=0;
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
83 84
    if (setup_tables(&table_list) ||
	setup_fields(thd,&table_list,fields,1,0,0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
85 86 87 88 89 90
      return -1;
    if (thd->dupp_field)
    {
      my_error(ER_FIELD_SPECIFIED_TWICE,MYF(0), thd->dupp_field->field_name);
      return -1;
    }
91
    table->time_stamp=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
92
    if (table->timestamp_field &&	// Don't set timestamp if used
93 94
	table->timestamp_field->query_id != thd->query_id)
      table->time_stamp= table->timestamp_field->offset()+1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
95
  }
96
  // For the values we need select_priv
bk@work.mysql.com's avatar
bk@work.mysql.com committed
97 98 99 100 101 102
  table->grant.want_privilege=(SELECT_ACL & ~table->grant.privilege);
  return 0;
}


int mysql_insert(THD *thd,TABLE_LIST *table_list, List<Item> &fields,
103
		 List<List_item> &values_list,enum_duplicates duplic)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
104 105 106
{
  int error;
  bool log_on= ((thd->options & OPTION_UPDATE_LOG) ||
107
		!(thd->master_access & SUPER_ACL));
108
  bool transactional_table, log_delayed, bulk_insert;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
109 110 111 112 113
  uint value_count;
  ulong counter = 1;
  ulonglong id;
  COPY_INFO info;
  TABLE *table;
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
114
  List_iterator_fast<List_item> its(values_list);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
115 116
  List_item *values;
  char *query=thd->query;
117
  thr_lock_type lock_type = table_list->lock_type;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
118 119
  DBUG_ENTER("mysql_insert");

120 121 122 123 124
  /*
    in safe mode or with skip-new change delayed insert to be regular
    if we are told to replace duplicates, the insert cannot be concurrent
    delayed insert changed to regular in slave thread
   */
125 126 127 128
  if ((lock_type == TL_WRITE_DELAYED &&
       ((specialflag & (SPECIAL_NO_NEW_FUNC | SPECIAL_SAFE_MODE)) ||
	thd->slave_thread)) ||
      (lock_type == TL_WRITE_CONCURRENT_INSERT && duplic == DUP_REPLACE))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
    lock_type=TL_WRITE;

  if (lock_type == TL_WRITE_DELAYED)
  {
    if (thd->locked_tables)
    {
      if (find_locked_table(thd,
			    table_list->db ? table_list->db : thd->db,
			    table_list->real_name))
      {
	my_printf_error(ER_DELAYED_INSERT_TABLE_LOCKED,
			ER(ER_DELAYED_INSERT_TABLE_LOCKED),
			MYF(0), table_list->real_name);
	DBUG_RETURN(-1);
      }
    }
    if (!(table = delayed_get_table(thd,table_list)) && !thd->fatal_error)
      table = open_ltable(thd,table_list,lock_type=thd->update_lock_default);
  }
  else
    table = open_ltable(thd,table_list,lock_type);
  if (!table)
    DBUG_RETURN(-1);
  thd->proc_info="init";
153
  thd->used_tables=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
154 155
  values= its++;
  if (check_insert_fields(thd,table,fields,*values,1) ||
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
156
      setup_tables(table_list) || setup_fields(thd,table_list,*values,0,0,0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
157 158 159 160 161 162 163 164 165 166 167 168
    goto abort;
  value_count= values->elements;
  while ((values = its++))
  {
    counter++;
    if (values->elements != value_count)
    {
      my_printf_error(ER_WRONG_VALUE_COUNT_ON_ROW,
		      ER(ER_WRONG_VALUE_COUNT_ON_ROW),
		      MYF(0),counter);
      goto abort;
    }
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
169
    if (setup_fields(thd,table_list,*values,0,0,0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
170 171 172 173
      goto abort;
  }
  its.rewind ();
  /*
174
    Fill in the given fields and dump it to the table file
bk@work.mysql.com's avatar
bk@work.mysql.com committed
175 176 177 178 179 180 181 182 183 184 185 186 187
  */

  info.records=info.deleted=info.copied=0;
  info.handle_duplicates=duplic;
  // Don't count warnings for simple inserts
  if (values_list.elements > 1 || (thd->options & OPTION_WARNINGS))
    thd->count_cuted_fields = 1;
  thd->cuted_fields = 0L;
  table->next_number_field=table->found_next_number_field;

  error=0;
  id=0;
  thd->proc_info="update";
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
188 189
  if (duplic == DUP_IGNORE || duplic == DUP_REPLACE)
    table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
190 191
  if ((lock_type != TL_WRITE_DELAYED && !(specialflag & SPECIAL_SAFE_MODE)) &&
      values_list.elements >= MIN_ROWS_TO_USE_BULK_INSERT)
192
  {
193
    table->file->extra_opt(HA_EXTRA_WRITE_CACHE,
194 195
			   min(thd->variables.read_buff_size,
			       table->avg_row_length*values_list.elements));
196 197
    table->file->deactivate_non_unique_index(values_list.elements);
    bulk_insert=1;
198
  }
199 200
  else
    bulk_insert=0;
201

202
  while ((values= its++))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
  {
    if (fields.elements || !value_count)
    {
      restore_record(table,2);			// Get empty record
      if (fill_record(fields,*values) || check_null_fields(thd,table))
      {
	if (values_list.elements != 1)
	{
	  info.records++;
	  continue;
	}
	error=1;
	break;
      }
    }
    else
    {
220 221 222 223
      if (thd->used_tables)			// Column used in values()
	restore_record(table,2);		// Get empty record
      else
	table->record[0][0]=table->record[2][0]; // Fix delete marker
bk@work.mysql.com's avatar
bk@work.mysql.com committed
224 225 226 227 228 229 230 231 232 233 234
      if (fill_record(table->field,*values))
      {
	if (values_list.elements != 1)
	{
	  info.records++;
	  continue;
	}
	error=1;
	break;
      }
    }
235
    if (lock_type == TL_WRITE_DELAYED)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
    {
      error=write_delayed(thd,table,duplic,query, thd->query_length, log_on);
      query=0;
    }
    else
      error=write_record(table,&info);
    if (error)
      break;
    /*
      If auto_increment values are used, save the first one
       for LAST_INSERT_ID() and for the update log.
       We can't use insert_id() as we don't want to touch the
       last_insert_id_used flag.
    */
    if (! id && thd->insert_id_used)
    {						// Get auto increment value
      id= thd->last_insert_id;
    }
  }
  if (lock_type == TL_WRITE_DELAYED)
  {
257 258 259 260 261 262
    if (!error)
    {
      id=0;					// No auto_increment id
      info.copied=values_list.elements;
      end_delayed_insert(thd);
    }
263
    query_cache_invalidate3(thd, table_list, 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
264 265 266
  }
  else
  {
267 268 269 270 271 272 273 274 275 276
    if (bulk_insert)
    {
      if (table->file->extra(HA_EXTRA_NO_CACHE))
      {
	if (!error)
	{
	  table->file->print_error(my_errno,MYF(0));
	  error=1;
	}
      }
277
      if (table->file->activate_all_index(thd))
278 279 280 281 282 283 284 285
      {
	if (!error)
	{
	  table->file->print_error(my_errno,MYF(0));
	  error=1;
	}
      }
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
286 287 288 289
    if (id && values_list.elements != 1)
      thd->insert_id(id);			// For update log
    else if (table->next_number_field)
      id=table->next_number_field->val_int();	// Return auto_increment value
290 291 292 293
    
    transactional_table= table->file->has_transactions();
    log_delayed= (transactional_table || table->tmp_table);
    if ((info.copied || info.deleted) && (error <= 0 || !transactional_table))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
294
    {
295 296 297
      mysql_update_log.write(thd, thd->query, thd->query_length);
      if (mysql_bin_log.is_open())
      {
298
	Query_log_event qinfo(thd, thd->query, thd->query_length,
299 300
			      log_delayed);
	if (mysql_bin_log.write(&qinfo) && transactional_table)
301
	  error=1;
302
      }
303
      if (!log_delayed)
304
	thd->options|=OPTION_STATUS_NO_TRANS_UPDATE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
305
    }
306
    if (transactional_table)
307
      error=ha_autocommit_or_rollback(thd,error);
308 309

    /*
310 311
      Store table for future invalidation  or invalidate it in
      the query cache if something changed
312
    */
313
    if (info.copied || info.deleted)
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
314
    {
315
      query_cache_invalidate3(thd, table_list, 1);
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
316
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
317 318 319 320 321 322 323 324 325 326
    if (thd->lock)
    {
      mysql_unlock_tables(thd, thd->lock);
      thd->lock=0;
    }
  }
  thd->proc_info="end";
  table->next_number_field=0;
  thd->count_cuted_fields=0;
  thd->next_insert_id=0;			// Reset this if wrongly used
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
327 328
  if (duplic == DUP_IGNORE || duplic == DUP_REPLACE)
    table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
329 330 331 332 333 334
  if (error)
    goto abort;

  if (values_list.elements == 1 && (!(thd->options & OPTION_WARNINGS) ||
				    !thd->cuted_fields))
    send_ok(&thd->net,info.copied+info.deleted,id);
335 336
  else
  {
bk@work.mysql.com's avatar
bk@work.mysql.com committed
337 338
    char buff[160];
    if (duplic == DUP_IGNORE)
339 340 341
      sprintf(buff,ER(ER_INSERT_INFO),info.records,
	      (lock_type == TL_WRITE_DELAYED) ? 0 : 
	      info.records-info.copied,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
342 343 344 345
	      thd->cuted_fields);
    else
      sprintf(buff,ER(ER_INSERT_INFO),info.records,info.deleted,
	      thd->cuted_fields);
346
    ::send_ok(&thd->net,info.copied+info.deleted,(ulonglong)id,buff);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
  }
  DBUG_RETURN(0);

abort:
  if (lock_type == TL_WRITE_DELAYED)
    end_delayed_insert(thd);
  DBUG_RETURN(-1);
}


	/* Check if there is more uniq keys after field */

static int last_uniq_key(TABLE *table,uint keynr)
{
  while (++keynr < table->keys)
    if (table->key_info[keynr].flags & HA_NOSAME)
      return 0;
  return 1;
}


/*
369
  Write a record to table with optional deleting of conflicting records
bk@work.mysql.com's avatar
bk@work.mysql.com committed
370 371 372 373 374 375 376
*/


int write_record(TABLE *table,COPY_INFO *info)
{
  int error;
  char *key=0;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
377

bk@work.mysql.com's avatar
bk@work.mysql.com committed
378 379 380 381 382
  info->records++;
  if (info->handle_duplicates == DUP_REPLACE)
  {
    while ((error=table->file->write_row(table->record[0])))
    {
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
383
      if (error != HA_WRITE_SKIP)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
384 385 386 387
	goto err;
      uint key_nr;
      if ((int) (key_nr = table->file->get_dup_key(error)) < 0)
      {
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
388
	error=HA_WRITE_SKIP;			/* Database can't find key */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
389 390
	goto err;
      }
391 392 393 394 395 396 397 398
      /*
	Don't allow REPLACE to replace a row when a auto_increment column
	was used.  This ensures that we don't get a problem when the
	whole range of the key has been used.
      */
      if (table->next_number_field && key_nr == table->next_number_index &&
	  table->file->auto_increment_column_changed)
	goto err;
399
      if (table->file->table_flags() & HA_DUPP_POS)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
400 401 402 403 404 405
      {
	if (table->file->rnd_pos(table->record[1],table->file->dupp_ref))
	  goto err;
      }
      else
      {
406
	if (table->file->extra(HA_EXTRA_FLUSH_CACHE)) /* Not needed with NISAM */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
407 408 409 410
	{
	  error=my_errno;
	  goto err;
	}
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
411

bk@work.mysql.com's avatar
bk@work.mysql.com committed
412 413 414 415 416 417 418 419 420 421 422
	if (!key)
	{
	  if (!(key=(char*) my_safe_alloca(table->max_unique_length,
					   MAX_KEY_LENGTH)))
	  {
	    error=ENOMEM;
	    goto err;
	  }
	}
	key_copy((byte*) key,table,key_nr,0);
	if ((error=(table->file->index_read_idx(table->record[1],key_nr,
423 424
						(byte*) key,
						table->key_info[key_nr].key_length,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
						HA_READ_KEY_EXACT))))
	  goto err;
      }
      if (last_uniq_key(table,key_nr))
      {
	if ((error=table->file->update_row(table->record[1],table->record[0])))
	  goto err;
	info->deleted++;
	break;					/* Update logfile and count */
      }
      else if ((error=table->file->delete_row(table->record[1])))
	goto err;
      info->deleted++;
    }
    info->copied++;
  }
  else if ((error=table->file->write_row(table->record[0])))
  {
    if (info->handle_duplicates != DUP_IGNORE ||
	(error != HA_ERR_FOUND_DUPP_KEY && error != HA_ERR_FOUND_DUPP_UNIQUE))
      goto err;
  }
  else
    info->copied++;
  if (key)
    my_safe_afree(key,table->max_unique_length,MAX_KEY_LENGTH);
  return 0;

err:
  if (key)
    my_afree(key);
456
  info->last_errno= error;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
457 458 459 460 461 462
  table->file->print_error(error,MYF(0));
  return 1;
}


/******************************************************************************
463 464 465
  Check that all fields with arn't null_fields are used
  If DONT_USE_DEFAULT_FIELDS isn't defined use default value for not set
  fields.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
******************************************************************************/

static int check_null_fields(THD *thd __attribute__((unused)),
			     TABLE *entry __attribute__((unused)))
{
#ifdef DONT_USE_DEFAULT_FIELDS
  for (Field **field=entry->field ; *field ; field++)
  {
    if ((*field)->query_id != thd->query_id && !(*field)->maybe_null() &&
	*field != entry->timestamp_field &&
	*field != entry->next_number_field)
    {
      my_printf_error(ER_BAD_NULL_ERROR, ER(ER_BAD_NULL_ERROR),MYF(0),
		      (*field)->field_name);
      return 1;
    }
  }
#endif
  return 0;
}

/*****************************************************************************
488 489
  Handling of delayed inserts
  A thread is created for each table that one uses with the DELAYED attribute.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
*****************************************************************************/

class delayed_row :public ilink {
public:
  char *record,*query;
  enum_duplicates dup;
  time_t start_time;
  bool query_start_used,last_insert_id_used,insert_id_used,log_query;
  ulonglong last_insert_id;
  ulong time_stamp;
  uint query_length;

  delayed_row(enum_duplicates dup_arg, bool log_query_arg)
    :record(0),query(0),dup(dup_arg),log_query(log_query_arg) {}
  ~delayed_row()
  {
    x_free(record);
  }
};


class delayed_insert :public ilink {
  uint locks_in_memory;
public:
  THD thd;
  TABLE *table;
  pthread_mutex_t mutex;
  pthread_cond_t cond,cond_client;
  volatile uint tables_in_use,stacked_inserts;
  volatile bool status,dead;
  COPY_INFO info;
  I_List<delayed_row> rows;
  uint group_count;
523
  TABLE_LIST table_list;			// Argument
bk@work.mysql.com's avatar
bk@work.mysql.com committed
524 525 526 527 528 529

  delayed_insert()
    :locks_in_memory(0),
     table(0),tables_in_use(0),stacked_inserts(0), status(0), dead(0),
     group_count(0)
  {
530 531
    thd.user=thd.priv_user=(char*) delayed_user;
    thd.host=(char*) localhost;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
532 533 534 535 536 537 538
    thd.current_tablenr=0;
    thd.version=refresh_version;
    thd.command=COM_DELAYED_INSERT;

    bzero((char*) &thd.net,sizeof(thd.net));	// Safety
    thd.system_thread=1;
    bzero((char*) &info,sizeof(info));
539
    pthread_mutex_init(&mutex,MY_MUTEX_INIT_FAST);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
540 541 542 543 544 545 546 547
    pthread_cond_init(&cond,NULL);
    pthread_cond_init(&cond_client,NULL);
    VOID(pthread_mutex_lock(&LOCK_thread_count));
    delayed_insert_threads++;
    VOID(pthread_mutex_unlock(&LOCK_thread_count));
  }
  ~delayed_insert()
  {
548
    /* The following is not really needed, but just for safety */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
549 550 551 552 553 554
    delayed_row *row;
    while ((row=rows.get()))
      delete row;
    if (table)
      close_thread_tables(&thd);
    VOID(pthread_mutex_lock(&LOCK_thread_count));
555 556 557
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);
    pthread_cond_destroy(&cond_client);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
558 559 560 561 562 563
    thd.unlink();				// Must be unlinked under lock
    x_free(thd.query);
    thd.user=thd.host=0;
    thread_count--;
    delayed_insert_threads--;
    VOID(pthread_mutex_unlock(&LOCK_thread_count));
564
    VOID(pthread_cond_broadcast(&COND_thread_count)); /* Tell main we are ready */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
  }

  /* The following is for checking when we can delete ourselves */
  inline void lock()
  {
    locks_in_memory++;				// Assume LOCK_delay_insert
  }
  void unlock()
  {
    pthread_mutex_lock(&LOCK_delayed_insert);
    if (!--locks_in_memory)
    {
      pthread_mutex_lock(&mutex);
      if (thd.killed && ! stacked_inserts && ! tables_in_use)
      {
	pthread_cond_signal(&cond);
	status=1;
      }
      pthread_mutex_unlock(&mutex);
    }
    pthread_mutex_unlock(&LOCK_delayed_insert);
  }
  inline uint lock_count() { return locks_in_memory; }

  TABLE* get_local_table(THD* client_thd);
  bool handle_inserts(void);
};


I_List<delayed_insert> delayed_threads;


delayed_insert *find_handler(THD *thd, TABLE_LIST *table_list)
{
  thd->proc_info="waiting for delay_list";
  pthread_mutex_lock(&LOCK_delayed_insert);	// Protect master list
  I_List_iterator<delayed_insert> it(delayed_threads);
  delayed_insert *tmp;
  while ((tmp=it++))
  {
    if (!strcmp(tmp->thd.db,table_list->db) &&
	!strcmp(table_list->real_name,tmp->table->real_name))
    {
      tmp->lock();
      break;
    }
  }
  pthread_mutex_unlock(&LOCK_delayed_insert); // For unlink from list
  return tmp;
}


static TABLE *delayed_get_table(THD *thd,TABLE_LIST *table_list)
{
  int error;
  delayed_insert *tmp;
  DBUG_ENTER("delayed_get_table");

  if (!table_list->db)
    table_list->db=thd->db;

  /* no match; create a new thread to handle the table */
  if (!(tmp=find_handler(thd,table_list)))
  {
    thd->proc_info="Creating delayed handler";
    pthread_mutex_lock(&LOCK_delayed_create);
    if (!(tmp=find_handler(thd,table_list)))	// Was just created
    {
      if (!(tmp=new delayed_insert()))
      {
	thd->fatal_error=1;
	my_error(ER_OUTOFMEMORY,MYF(0),sizeof(delayed_insert));
	pthread_mutex_unlock(&LOCK_delayed_create);
	DBUG_RETURN(0);
      }
640 641 642
      pthread_mutex_lock(&LOCK_thread_count);
      thread_count++;
      pthread_mutex_unlock(&LOCK_thread_count);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
643
      if (!(tmp->thd.db=my_strdup(table_list->db,MYF(MY_WME))) ||
644
	  !(tmp->thd.query=my_strdup(table_list->real_name,MYF(MY_WME))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
645 646 647 648 649 650 651
      {
	delete tmp;
	thd->fatal_error=1;
	my_error(ER_OUT_OF_RESOURCES,MYF(0));
	pthread_mutex_unlock(&LOCK_delayed_create);
	DBUG_RETURN(0);
      }
652 653
      tmp->table_list= *table_list;			// Needed to open table
      tmp->table_list.db= tmp->thd.db;
654
      tmp->table_list.alias= tmp->table_list.real_name=tmp->thd.query;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
      tmp->lock();
      pthread_mutex_lock(&tmp->mutex);
      if ((error=pthread_create(&tmp->thd.real_id,&connection_attrib,
				handle_delayed_insert,(void*) tmp)))
      {
	DBUG_PRINT("error",
		   ("Can't create thread to handle delayed insert (error %d)",
		    error));
	pthread_mutex_unlock(&tmp->mutex);
	tmp->unlock();
	delete tmp;
	thd->fatal_error=1;
	pthread_mutex_unlock(&LOCK_delayed_create);
	net_printf(&thd->net,ER_CANT_CREATE_THREAD,error);
	DBUG_RETURN(0);
      }

      /* Wait until table is open */
      thd->proc_info="waiting for handler open";
      while (!tmp->thd.killed && !tmp->table && !thd->killed)
      {
	pthread_cond_wait(&tmp->cond_client,&tmp->mutex);
      }
      pthread_mutex_unlock(&tmp->mutex);
      thd->proc_info="got old table";
      if (tmp->thd.killed)
      {
	if (tmp->thd.fatal_error)
	{
	  /* Copy error message and abort */
	  thd->fatal_error=1;
	  strmov(thd->net.last_error,tmp->thd.net.last_error);
687
	  thd->net.last_errno=tmp->thd.net.last_errno;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724
	}
	tmp->unlock();
	pthread_mutex_unlock(&LOCK_delayed_create);
	DBUG_RETURN(0);				// Continue with normal insert
      }
      if (thd->killed)
      {
	tmp->unlock();
	pthread_mutex_unlock(&LOCK_delayed_create);
	DBUG_RETURN(0);
      }
    }
    pthread_mutex_unlock(&LOCK_delayed_create);
  }

  pthread_mutex_lock(&tmp->mutex);
  TABLE *table=tmp->get_local_table(thd);
  pthread_mutex_unlock(&tmp->mutex);
  tmp->unlock();
  if (table)
    thd->di=tmp;
  else if (tmp->thd.fatal_error)
    thd->fatal_error=1;
  DBUG_RETURN((table_list->table=table));
}


/*
  As we can't let many threads modify the same TABLE structure, we create
  an own structure for each tread.  This includes a row buffer to save the
  column values and new fields that points to the new row buffer.
  The memory is allocated in the client thread and is freed automaticly.
*/

TABLE *delayed_insert::get_local_table(THD* client_thd)
{
  my_ptrdiff_t adjust_ptrs;
725
  Field **field,**org_field, *found_next_number_field;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
  TABLE *copy;

  /* First request insert thread to get a lock */
  status=1;
  tables_in_use++;
  if (!thd.lock)				// Table is not locked
  {
    client_thd->proc_info="waiting for handler lock";
    pthread_cond_signal(&cond);			// Tell handler to lock table
    while (!dead && !thd.lock && ! client_thd->killed)
    {
      pthread_cond_wait(&cond_client,&mutex);
    }
    client_thd->proc_info="got handler lock";
    if (client_thd->killed)
      goto error;
    if (dead)
    {
      strmov(client_thd->net.last_error,thd.net.last_error);
      client_thd->net.last_errno=thd.net.last_errno;
      goto error;
    }
  }

  client_thd->proc_info="allocating local table";
751 752 753
  copy= (TABLE*) client_thd->alloc(sizeof(*copy)+
				   (table->fields+1)*sizeof(Field**)+
				   table->reclength);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
754 755 756 757 758 759 760 761 762 763 764 765 766 767
  if (!copy)
    goto error;
  *copy= *table;
  bzero((char*) &copy->name_hash,sizeof(copy->name_hash)); // No name hashing
  /* We don't need to change the file handler here */

  field=copy->field=(Field**) (copy+1);
  copy->record[0]=(byte*) (field+table->fields+1);
  memcpy((char*) copy->record[0],(char*) table->record[0],table->reclength);

  /* Make a copy of all fields */

  adjust_ptrs=PTR_BYTE_DIFF(copy->record[0],table->record[0]);

768
  found_next_number_field=table->found_next_number_field;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
769 770
  for (org_field=table->field ; *org_field ; org_field++,field++)
  {
771
    if (!(*field= (*org_field)->new_field(&client_thd->mem_root,copy)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
772 773
      return 0;
    (*field)->move_field(adjust_ptrs);		// Point at copy->record[0]
774 775
    if (*org_field == found_next_number_field)
      (*field)->table->found_next_number_field= *field;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
  }
  *field=0;

  /* Adjust timestamp */
  if (table->timestamp_field)
  {
    /* Restore offset as this may have been reset in handle_inserts */
    copy->time_stamp=table->timestamp_field->offset()+1;
    copy->timestamp_field=
      (Field_timestamp*) copy->field[table->timestamp_field_offset];
  }

  /* _rowid is not used with delayed insert */
  copy->rowid_field=0;
  return copy;

  /* Got fatal error */
 error:
  tables_in_use--;
  status=1;
  pthread_cond_signal(&cond);			// Inform thread about abort
  return 0;
}


/* Put a question in queue */

static int write_delayed(THD *thd,TABLE *table,enum_duplicates duplic,
			 char *query, uint query_length, bool log_on)
{
  delayed_row *row=0;
  delayed_insert *di=thd->di;
  DBUG_ENTER("write_delayed");

  thd->proc_info="waiting for handler insert";
  pthread_mutex_lock(&di->mutex);
  while (di->stacked_inserts >= delayed_queue_size && !thd->killed)
    pthread_cond_wait(&di->cond_client,&di->mutex);
  thd->proc_info="storing row into queue";

  if (thd->killed || !(row= new delayed_row(duplic, log_on)))
    goto err;

  if (!query)
    query_length=0;
  if (!(row->record= (char*) my_malloc(table->reclength+query_length+1,
				       MYF(MY_WME))))
    goto err;
  memcpy(row->record,table->record[0],table->reclength);
  if (query_length)
  {
    row->query=row->record+table->reclength;
    memcpy(row->query,query,query_length+1);
  }
  row->query_length=		query_length;
  row->start_time=		thd->start_time;
  row->query_start_used=	thd->query_start_used;
  row->last_insert_id_used=	thd->last_insert_id_used;
  row->insert_id_used=		thd->insert_id_used;
  row->last_insert_id=		thd->last_insert_id;
  row->time_stamp=		table->time_stamp;

  di->rows.push_back(row);
  di->stacked_inserts++;
  di->status=1;
  if (table->blob_fields)
    unlink_blobs(table);
  pthread_cond_signal(&di->cond);

  thread_safe_increment(delayed_rows_in_use,&LOCK_delayed_status);
  pthread_mutex_unlock(&di->mutex);
  DBUG_RETURN(0);

 err:
  delete row;
  pthread_mutex_unlock(&di->mutex);
  DBUG_RETURN(1);
}


static void end_delayed_insert(THD *thd)
{
858
  DBUG_ENTER("end_delayed_insert");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
859 860
  delayed_insert *di=thd->di;
  pthread_mutex_lock(&di->mutex);
861
  DBUG_PRINT("info",("tables in use: %d",di->tables_in_use));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
862 863 864 865 866 867
  if (!--di->tables_in_use || di->thd.killed)
  {						// Unlock table
    di->status=1;
    pthread_cond_signal(&di->cond);
  }
  pthread_mutex_unlock(&di->mutex);
868
  DBUG_VOID_RETURN;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
869 870 871 872 873 874 875 876 877 878 879 880 881
}


/* We kill all delayed threads when doing flush-tables */

void kill_delayed_threads(void)
{
  VOID(pthread_mutex_lock(&LOCK_delayed_insert)); // For unlink from list

  I_List_iterator<delayed_insert> it(delayed_threads);
  delayed_insert *tmp;
  while ((tmp=it++))
  {
882
    /* Ensure that the thread doesn't kill itself while we are looking at it */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
883 884 885 886 887
    pthread_mutex_lock(&tmp->mutex);
    tmp->thd.killed=1;
    if (tmp->thd.mysys_var)
    {
      pthread_mutex_lock(&tmp->thd.mysys_var->mutex);
888
      if (tmp->thd.mysys_var->current_cond)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
889
      {
890 891 892 893 894 895
	/*
	  We need the following test because the main mutex may be locked
	  in handle_delayed_insert()
	*/
	if (&tmp->mutex != tmp->thd.mysys_var->current_mutex)
	  pthread_mutex_lock(tmp->thd.mysys_var->current_mutex);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
896
	pthread_cond_broadcast(tmp->thd.mysys_var->current_cond);
897 898
	if (&tmp->mutex != tmp->thd.mysys_var->current_mutex)
	  pthread_mutex_unlock(tmp->thd.mysys_var->current_mutex);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
899 900 901 902 903 904 905 906 907 908 909 910 911
      }
      pthread_mutex_unlock(&tmp->thd.mysys_var->mutex);
    }
    pthread_mutex_unlock(&tmp->mutex);
  }
  VOID(pthread_mutex_unlock(&LOCK_delayed_insert)); // For unlink from list
}


/*
 * Create a new delayed insert thread
*/

912
extern "C" pthread_handler_decl(handle_delayed_insert,arg)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
913 914 915 916 917 918 919 920
{
  delayed_insert *di=(delayed_insert*) arg;
  THD *thd= &di->thd;

  pthread_detach_this_thread();
  /* Add thread to THD list so that's it's visible in 'show processlist' */
  pthread_mutex_lock(&LOCK_thread_count);
  thd->thread_id=thread_id++;
921
  thd->end_time();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
922
  threads.append(thd);
923
  thd->killed=abort_loop;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
924 925 926
  pthread_mutex_unlock(&LOCK_thread_count);

  pthread_mutex_lock(&di->mutex);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
927
#if !defined( __WIN__) && !defined(OS2)	/* Win32 calls this in pthread_create */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
928 929 930 931 932 933 934 935
  if (my_thread_init())
  {
    strmov(thd->net.last_error,ER(thd->net.last_errno=ER_OUT_OF_RESOURCES));
    goto end;
  }
#endif

  DBUG_ENTER("handle_delayed_insert");
936
  if (init_thr_lock() || thd->store_globals())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
937
  {
938
    thd->fatal_error=1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
939 940 941
    strmov(thd->net.last_error,ER(thd->net.last_errno=ER_OUT_OF_RESOURCES));
    goto end;
  }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
942
#if !defined(__WIN__) && !defined(OS2)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
943 944 945 946 947 948 949
  sigset_t set;
  VOID(sigemptyset(&set));			// Get mask in use
  VOID(pthread_sigmask(SIG_UNBLOCK,&set,&thd->block_signals));
#endif

  /* open table */

950
  if (!(di->table=open_ltable(thd,&di->table_list,TL_WRITE_DELAYED)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
951 952 953 954
  {
    thd->fatal_error=1;				// Abort waiting inserts
    goto end;
  }
955 956 957
  if (di->table->file->has_transactions())
  {
    thd->fatal_error=1;
958
    my_error(ER_ILLEGAL_HA, MYF(0), di->table_list.real_name);
959 960
    goto end;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
  di->table->copy_blobs=1;

  /* One can now use this */
  pthread_mutex_lock(&LOCK_delayed_insert);
  delayed_threads.append(di);
  pthread_mutex_unlock(&LOCK_delayed_insert);

  /* Tell client that the thread is initialized */
  pthread_cond_signal(&di->cond_client);

  /* Now wait until we get an insert or lock to handle */
  /* We will not abort as long as a client thread uses this thread */

  for (;;)
  {
    if (thd->killed)
    {
      uint lock_count;
      /*
	Remove this from delay insert list so that no one can request a
	table from this
      */
      pthread_mutex_unlock(&di->mutex);
      pthread_mutex_lock(&LOCK_delayed_insert);
      di->unlink();
      lock_count=di->lock_count();
      pthread_mutex_unlock(&LOCK_delayed_insert);
      pthread_mutex_lock(&di->mutex);
      if (!lock_count && !di->tables_in_use && !di->stacked_inserts)
	break;					// Time to die
    }

    if (!di->status && !di->stacked_inserts)
    {
      struct timespec abstime;
996
      set_timespec(abstime, delayed_insert_timeout);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
997 998 999 1000

      /* Information for pthread_kill */
      di->thd.mysys_var->current_mutex= &di->mutex;
      di->thd.mysys_var->current_cond= &di->cond;
1001
      di->thd.proc_info="Waiting for INSERT";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1002

1003
      DBUG_PRINT("info",("Waiting for someone to insert rows"));
1004
      while (!thd->killed)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
      {
	int error;
#if (defined(HAVE_BROKEN_COND_TIMEDWAIT) || defined(HAVE_LINUXTHREADS))
	error=pthread_cond_wait(&di->cond,&di->mutex);
#else
	error=pthread_cond_timedwait(&di->cond,&di->mutex,&abstime);
#ifdef EXTRA_DEBUG
	if (error && error != EINTR)
	{
	  fprintf(stderr, "Got error %d from pthread_cond_timedwait\n",error);
	  DBUG_PRINT("error",("Got error %d from pthread_cond_timedwait",
			      error));
	}
#endif
#endif
	if (thd->killed || di->status)
	  break;
	if (error == ETIME || error == ETIMEDOUT)
	{
	  thd->killed=1;
	  break;
	}
      }
1028 1029
      /* We can't lock di->mutex and mysys_var->mutex at the same time */
      pthread_mutex_unlock(&di->mutex);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1030 1031 1032 1033
      pthread_mutex_lock(&di->thd.mysys_var->mutex);
      di->thd.mysys_var->current_mutex= 0;
      di->thd.mysys_var->current_cond= 0;
      pthread_mutex_unlock(&di->thd.mysys_var->mutex);
1034
      pthread_mutex_lock(&di->mutex);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1035
    }
1036
    di->thd.proc_info=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125

    if (di->tables_in_use && ! thd->lock)
    {
      /* request for new delayed insert */
      if (!(thd->lock=mysql_lock_tables(thd,&di->table,1)))
      {
	di->dead=thd->killed=1;			// Fatal error
      }
      pthread_cond_broadcast(&di->cond_client);
    }
    if (di->stacked_inserts)
    {
      if (di->handle_inserts())
      {
	di->dead=thd->killed=1;			// Some fatal error
      }
    }
    di->status=0;
    if (!di->stacked_inserts && !di->tables_in_use && thd->lock)
    {
      /* No one is doing a insert delayed;
	 Unlock it so that other threads can use it */
      MYSQL_LOCK *lock=thd->lock;
      thd->lock=0;
      pthread_mutex_unlock(&di->mutex);
      mysql_unlock_tables(thd, lock);
      di->group_count=0;
      pthread_mutex_lock(&di->mutex);
    }
    if (di->tables_in_use)
      pthread_cond_broadcast(&di->cond_client); // If waiting clients
  }

end:
  /*
    di should be unlinked from the thread handler list and have no active
    clients
  */

  close_thread_tables(thd);			// Free the table
  di->table=0;
  di->dead=thd->killed=1;			// If error
  pthread_cond_broadcast(&di->cond_client);	// Safety
  pthread_mutex_unlock(&di->mutex);

  pthread_mutex_lock(&LOCK_delayed_create);	// Because of delayed_get_table
  pthread_mutex_lock(&LOCK_delayed_insert);	
  delete di;
  pthread_mutex_unlock(&LOCK_delayed_insert);
  pthread_mutex_unlock(&LOCK_delayed_create);  

  my_thread_end();
  pthread_exit(0);
  DBUG_RETURN(0);
}


/* Remove pointers from temporary fields to allocated values */

static void unlink_blobs(register TABLE *table)
{
  for (Field **ptr=table->field ; *ptr ; ptr++)
  {
    if ((*ptr)->flags & BLOB_FLAG)
      ((Field_blob *) (*ptr))->clear_temporary();
  }
}

/* Free blobs stored in current row */

static void free_delayed_insert_blobs(register TABLE *table)
{
  for (Field **ptr=table->field ; *ptr ; ptr++)
  {
    if ((*ptr)->flags & BLOB_FLAG)
    {
      char *str;
      ((Field_blob *) (*ptr))->get_ptr(&str);
      my_free(str,MYF(MY_ALLOW_ZERO_PTR));
      ((Field_blob *) (*ptr))->reset();
    }
  }
}


bool delayed_insert::handle_inserts(void)
{
  int error;
  uint max_rows;
1126
  bool using_ignore=0, using_bin_log=mysql_bin_log.is_open();
1127
  delayed_row *row;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
  DBUG_ENTER("handle_inserts");

  /* Allow client to insert new rows */
  pthread_mutex_unlock(&mutex);

  table->next_number_field=table->found_next_number_field;

  thd.proc_info="upgrading lock";
  if (thr_upgrade_write_delay_lock(*thd.lock->locks))
  {
    /* This can only happen if thread is killed by shutdown */
    sql_print_error(ER(ER_DELAYED_CANT_CHANGE_LOCK),table->real_name);
    goto err;
  }

  thd.proc_info="insert";
  max_rows=delayed_insert_limit;
  if (thd.killed || table->version != refresh_version)
  {
    thd.killed=1;
    max_rows= ~0;				// Do as much as possible
  }

1151 1152 1153 1154 1155 1156 1157
  /*
    We can't use row caching when using the binary log because if
    we get a crash, then binary log will contain rows that are not yet
    written to disk, which will cause problems in replication.
  */
  if (!using_bin_log)
    table->file->extra(HA_EXTRA_WRITE_CACHE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
  pthread_mutex_lock(&mutex);
  while ((row=rows.get()))
  {
    stacked_inserts--;
    pthread_mutex_unlock(&mutex);
    memcpy(table->record[0],row->record,table->reclength);

    thd.start_time=row->start_time;
    thd.query_start_used=row->query_start_used;
    thd.last_insert_id=row->last_insert_id;
    thd.last_insert_id_used=row->last_insert_id_used;
    thd.insert_id_used=row->insert_id_used;
    table->time_stamp=row->time_stamp;

    info.handle_duplicates= row->dup;
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1173 1174 1175 1176 1177 1178
    if (info.handle_duplicates == DUP_IGNORE ||
	info.handle_duplicates == DUP_REPLACE)
    {
      table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
      using_ignore=1;
    }
1179
    thd.net.last_errno = 0; // reset error for binlog
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1180 1181
    if (write_record(table,&info))
    {
1182
      info.error_count++;				// Ignore errors
1183
      thread_safe_increment(delayed_insert_errors,&LOCK_delayed_status);
sasha@laptop.slkc.uswest.net's avatar
sasha@laptop.slkc.uswest.net committed
1184
      row->log_query = 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1185
    }
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1186 1187 1188 1189 1190
    if (using_ignore)
    {
      using_ignore=0;
      table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1191 1192
    if (row->query && row->log_query)
    {
1193
      mysql_update_log.write(&thd,row->query, row->query_length);
1194
      if (using_bin_log)
1195
      {
1196
	Query_log_event qinfo(&thd, row->query, row->query_length,0);
1197 1198
	mysql_bin_log.write(&qinfo);
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
    }
    if (table->blob_fields)
      free_delayed_insert_blobs(table);
    thread_safe_sub(delayed_rows_in_use,1,&LOCK_delayed_status);
    thread_safe_increment(delayed_insert_writes,&LOCK_delayed_status);
    pthread_mutex_lock(&mutex);

    delete row;
    /* Let READ clients do something once in a while */
    if (group_count++ == max_rows)
    {
      group_count=0;
      if (stacked_inserts || tables_in_use)	// Let these wait a while
      {
	if (tables_in_use)
	  pthread_cond_broadcast(&cond_client); // If waiting clients
	thd.proc_info="reschedule";
	pthread_mutex_unlock(&mutex);
	if ((error=table->file->extra(HA_EXTRA_NO_CACHE)))
	{
	  /* This should never happen */
	  table->file->print_error(error,MYF(0));
	  sql_print_error("%s",thd.net.last_error);
	  goto err;
	}
1224
	query_cache_invalidate3(&thd, table, 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1225 1226 1227 1228 1229
	if (thr_reschedule_write_lock(*thd.lock->locks))
	{
	  /* This should never happen */
	  sql_print_error(ER(ER_DELAYED_CANT_CHANGE_LOCK),table->real_name);
	}
1230 1231
	if (!using_bin_log)
	  table->file->extra(HA_EXTRA_WRITE_CACHE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
	pthread_mutex_lock(&mutex);
	thd.proc_info="insert";
      }
      if (tables_in_use)
	pthread_cond_broadcast(&cond_client);	// If waiting clients
    }
  }

  thd.proc_info=0;
  table->next_number_field=0;
  pthread_mutex_unlock(&mutex);
  if ((error=table->file->extra(HA_EXTRA_NO_CACHE)))
  {						// This shouldn't happen
    table->file->print_error(error,MYF(0));
    sql_print_error("%s",thd.net.last_error);
    goto err;
  }
1249
  query_cache_invalidate3(&thd, table, 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1250 1251 1252 1253
  pthread_mutex_lock(&mutex);
  DBUG_RETURN(0);

 err:
1254 1255 1256 1257 1258 1259 1260
  /* Remove all not used rows */
  while ((row=rows.get()))
  {
    delete row;
    thread_safe_increment(delayed_insert_errors,&LOCK_delayed_status);
    stacked_inserts--;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1261 1262 1263 1264 1265 1266 1267 1268
  thread_safe_increment(delayed_insert_errors, &LOCK_delayed_status);
  pthread_mutex_lock(&mutex);
  DBUG_RETURN(1);
}



/***************************************************************************
1269
  Store records in INSERT ... SELECT *
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
***************************************************************************/

int
select_insert::prepare(List<Item> &values)
{
  DBUG_ENTER("select_insert::prepare");

  if (check_insert_fields(thd,table,*fields,values,1))
    DBUG_RETURN(1);

1280
  restore_record(table,2);			// Get empty record
1281
  table->next_number_field=table->found_next_number_field;
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
1282
  thd->count_cuted_fields=1;			// calc cuted fields
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1283
  thd->cuted_fields=0;
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
1284 1285 1286 1287 1288 1289
  if (info.handle_duplicates != DUP_REPLACE)
    table->file->extra(HA_EXTRA_WRITE_CACHE);
  if (info.handle_duplicates == DUP_IGNORE ||
      info.handle_duplicates == DUP_REPLACE)
    table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
  table->file->deactivate_non_unique_index((ha_rows) 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1290 1291 1292 1293 1294 1295 1296 1297
  DBUG_RETURN(0);
}

select_insert::~select_insert()
{
  if (table)
  {
    table->next_number_field=0;
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1298
    table->file->extra(HA_EXTRA_RESET);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
  }
  thd->count_cuted_fields=0;
}


bool select_insert::send_data(List<Item> &values)
{
  if (thd->offset_limit)
  {						// using limit offset,count
    thd->offset_limit--;
    return 0;
  }
  if (fields->elements)
    fill_record(*fields,values);
  else
    fill_record(table->field,values);
  if (write_record(table,&info))
    return 1;
  if (table->next_number_field)		// Clear for next record
  {
    table->next_number_field->reset();
    if (! last_insert_id && thd->insert_id_used)
      last_insert_id=thd->insert_id();
  }
  return 0;
}


void select_insert::send_error(uint errcode,const char *err)
{
  ::send_error(&thd->net,errcode,err);
1330 1331
  table->file->extra(HA_EXTRA_NO_CACHE);
  table->file->activate_all_index(thd);
1332
  ha_rollback_stmt(thd);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1333
  if (info.copied || info.deleted)
1334
  {
1335
    query_cache_invalidate3(thd, table, 1);
1336
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1337 1338 1339 1340 1341
}


bool select_insert::send_eof()
{
1342 1343 1344
  int error,error2;
  if (!(error=table->file->extra(HA_EXTRA_NO_CACHE)))
    error=table->file->activate_all_index(thd);
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1345
  table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
1346 1347
  if ((error2=ha_autocommit_or_rollback(thd,error)) && ! error)
    error=error2;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1348
  if (info.copied || info.deleted)
1349
  {
1350
    query_cache_invalidate3(thd, table, 1);
1351
  }
1352
  if (error)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
  {
    table->file->print_error(error,MYF(0));
    ::send_error(&thd->net);
    return 1;
  }
  else
  {
    char buff[160];
    if (info.handle_duplicates == DUP_IGNORE)
      sprintf(buff,ER(ER_INSERT_INFO),info.records,info.records-info.copied,
	      thd->cuted_fields);
    else
      sprintf(buff,ER(ER_INSERT_INFO),info.records,info.deleted,
	      thd->cuted_fields);
    if (last_insert_id)
      thd->insert_id(last_insert_id);		// For update log
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
1369
    ::send_ok(&thd->net,info.copied,last_insert_id,buff);
1370 1371 1372
    mysql_update_log.write(thd,thd->query,thd->query_length);
    if (mysql_bin_log.is_open())
    {
1373
      Query_log_event qinfo(thd, thd->query, thd->query_length,
1374
			    table->file->has_transactions());
1375 1376
      mysql_bin_log.write(&qinfo);
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1377 1378 1379 1380 1381 1382
    return 0;
  }
}


/***************************************************************************
1383
  CREATE TABLE (SELECT) ...
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408
***************************************************************************/

int
select_create::prepare(List<Item> &values)
{
  DBUG_ENTER("select_create::prepare");

  table=create_table_from_items(thd, create_info, db, name,
				extra_fields, keys, &values, &lock);
  if (!table)
    DBUG_RETURN(-1);				// abort() deletes table

  /* First field to copy */
  field=table->field+table->fields - values.elements;

  if (table->timestamp_field)			// Don't set timestamp if used
  {
    table->timestamp_field->set_time();
    table->time_stamp=0;			// This should be saved
  }
  table->next_number_field=table->found_next_number_field;

  restore_record(table,2);			// Get empty record
  thd->count_cuted_fields=1;			// count warnings
  thd->cuted_fields=0;
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1409 1410 1411
  if (info.handle_duplicates == DUP_IGNORE ||
      info.handle_duplicates == DUP_REPLACE)
    table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
1412
  table->file->deactivate_non_unique_index((ha_rows) 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
  DBUG_RETURN(0);
}


bool select_create::send_data(List<Item> &values)
{
  if (thd->offset_limit)
  {						// using limit offset,count
    thd->offset_limit--;
    return 0;
  }
  fill_record(field,values);
  if (write_record(table,&info))
    return 1;
  if (table->next_number_field)		// Clear for next record
  {
    table->next_number_field->reset();
    if (! last_insert_id && thd->insert_id_used)
      last_insert_id=thd->insert_id();
  }
  return 0;
}

extern HASH open_cache;

monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
1438

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1439 1440 1441 1442 1443 1444 1445
bool select_create::send_eof()
{
  bool tmp=select_insert::send_eof();
  if (tmp)
    abort();
  else
  {
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1446
    table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1447 1448
    VOID(pthread_mutex_lock(&LOCK_open));
    mysql_unlock_tables(thd, lock);
1449 1450 1451 1452 1453
    /*
      TODO:
      Check if we can remove the following two rows.
      We should be able to just keep the table in the table cache.
    */
1454 1455
    if (!table->tmp_table)
      hash_delete(&open_cache,(byte*) table);
1456
    lock=0; 
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
1457
    table=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
    VOID(pthread_mutex_unlock(&LOCK_open));
  }
  return tmp;
}

void select_create::abort()
{
  VOID(pthread_mutex_lock(&LOCK_open));
  if (lock)
  {
    mysql_unlock_tables(thd, lock);
    lock=0;
  }
  if (table)
  {
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1473
    table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1474
    enum db_type table_type=table->db_type;
1475 1476
    if (!table->tmp_table)
      hash_delete(&open_cache,(byte*) table);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1477 1478 1479 1480 1481 1482 1483 1484
    quick_rm_table(table_type,db,name);
    table=0;
  }
  VOID(pthread_mutex_unlock(&LOCK_open));
}


/*****************************************************************************
1485
  Instansiate templates
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1486 1487 1488
*****************************************************************************/

#ifdef __GNUC__
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
1489
template class List_iterator_fast<List_item>;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1490 1491 1492 1493
template class I_List<delayed_insert>;
template class I_List_iterator<delayed_insert>;
template class I_List<delayed_row>;
#endif