sql_insert.cc 55.4 KB
Newer Older
unknown's avatar
unknown committed
1
/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
unknown's avatar
unknown committed
2

unknown's avatar
unknown 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.
unknown's avatar
unknown committed
7

unknown's avatar
unknown 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.
unknown's avatar
unknown committed
12

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

static int check_null_fields(THD *thd,TABLE *entry);
unknown's avatar
unknown committed
23
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
24
static TABLE *delayed_get_table(THD *thd,TABLE_LIST *table_list);
25
static int write_delayed(THD *thd,TABLE *table, enum_duplicates dup, bool ignore,
26
			 char *query, uint query_length, int log_on);
unknown's avatar
unknown committed
27
static void end_delayed_insert(THD *thd);
28
extern "C" pthread_handler_decl(handle_delayed_insert,arg);
unknown's avatar
unknown committed
29
static void unlink_blobs(register TABLE *table);
unknown's avatar
unknown committed
30
#endif
unknown's avatar
unknown committed
31 32 33 34 35 36 37 38 39 40 41

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

42 43
#define DELAYED_LOG_UPDATE 1
#define DELAYED_LOG_BIN    2
unknown's avatar
unknown committed
44

45

unknown's avatar
unknown committed
46
/*
47
  Check if insert fields are correct.
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63

  SYNOPSIS
    check_insert_fields()
    thd                         The current thread.
    table                       The table for insert.
    fields                      The insert fields.
    values                      The insert values.

  NOTE
    Clears TIMESTAMP_AUTO_SET_ON_INSERT from table->timestamp_field_type
    or leaves it as is, depending on if timestamp should be updated or
    not.

  RETURN
    0           OK
    -1          Error
unknown's avatar
unknown committed
64 65
*/

66 67
static int check_insert_fields(THD *thd, TABLE *table, List<Item> &fields,
                               List<Item> &values)
unknown's avatar
unknown committed
68 69 70 71 72 73 74
{
  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),
unknown's avatar
unknown committed
75
		      MYF(0), 1L);
unknown's avatar
unknown committed
76 77
      return -1;
    }
unknown's avatar
unknown committed
78
#ifndef NO_EMBEDDED_ACCESS_CHECKS
unknown's avatar
unknown committed
79 80 81
    if (grant_option &&
	check_grant_all_columns(thd,INSERT_ACL,table))
      return -1;
unknown's avatar
unknown committed
82
#endif
83 84
    clear_timestamp_auto_bits(table->timestamp_field_type,
                              TIMESTAMP_AUTO_SET_ON_INSERT);
unknown's avatar
unknown committed
85 86 87 88 89 90 91
  }
  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),
unknown's avatar
unknown committed
92
		      MYF(0), 1L);
unknown's avatar
unknown committed
93 94 95 96
      return -1;
    }
    TABLE_LIST table_list;
    bzero((char*) &table_list,sizeof(table_list));
97
    table_list.db=  table->table_cache_key;
98
    table_list.real_name= table_list.alias= table->table_name;
unknown's avatar
unknown committed
99 100 101 102
    table_list.table=table;
    table_list.grant=table->grant;

    thd->dupp_field=0;
103
    if (setup_tables(&table_list) ||
104
	setup_fields(thd, 0, &table_list,fields,1,0,0))
unknown's avatar
unknown committed
105
      return -1;
106

unknown's avatar
unknown committed
107 108 109 110 111 112
    if (thd->dupp_field)
    {
      my_error(ER_FIELD_SPECIFIED_TWICE,MYF(0), thd->dupp_field->field_name);
      return -1;
    }
    if (table->timestamp_field &&	// Don't set timestamp if used
113
	table->timestamp_field->query_id == thd->query_id)
114 115
      clear_timestamp_auto_bits(table->timestamp_field_type,
                                TIMESTAMP_AUTO_SET_ON_INSERT);
unknown's avatar
unknown committed
116
  }
unknown's avatar
unknown committed
117
  // For the values we need select_priv
unknown's avatar
unknown committed
118
#ifndef NO_EMBEDDED_ACCESS_CHECKS
unknown's avatar
unknown committed
119
  table->grant.want_privilege=(SELECT_ACL & ~table->grant.privilege);
unknown's avatar
unknown committed
120
#endif
unknown's avatar
unknown committed
121 122 123 124
  return 0;
}


125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
/*
  Check update fields for the timestamp field.

  SYNOPSIS
    check_update_fields()
    thd                         The current thread.
    insert_table_list           The insert table list.
    table                       The table for update.
    update_fields               The update fields.

  NOTE
    If the update fields include the timestamp field,
    remove TIMESTAMP_AUTO_SET_ON_UPDATE from table->timestamp_field_type.

  RETURN
    0           OK
    -1          Error
*/

static int check_update_fields(THD *thd, TABLE *table,
                               TABLE_LIST *insert_table_list,
                               List<Item> &update_fields)
{
  ulong		timestamp_query_id;
  LINT_INIT(timestamp_query_id);

  /*
    Change the query_id for the timestamp column so that we can
    check if this is modified directly.
  */
  if (table->timestamp_field)
  {
    timestamp_query_id= table->timestamp_field->query_id;
    table->timestamp_field->query_id= thd->query_id-1;
  }

  /*
    Check the fields we are going to modify. This will set the query_id
    of all used fields to the threads query_id.
  */
  if (setup_fields(thd, 0, insert_table_list, update_fields, 1, 0, 0))
    return -1;

  if (table->timestamp_field)
  {
    /* Don't set timestamp column if this is modified. */
    if (table->timestamp_field->query_id == thd->query_id)
172 173
      clear_timestamp_auto_bits(table->timestamp_field_type,
                                TIMESTAMP_AUTO_SET_ON_UPDATE);
174 175 176 177 178 179 180 181
    else
      table->timestamp_field->query_id= timestamp_query_id;
  }

  return 0;
}


182 183 184 185 186
int mysql_insert(THD *thd,TABLE_LIST *table_list,
                 List<Item> &fields,
                 List<List_item> &values_list,
                 List<Item> &update_fields,
                 List<Item> &update_values,
187 188
                 enum_duplicates duplic,
                 bool ignore)
unknown's avatar
unknown committed
189
{
190
  int error, res;
191 192 193 194 195 196
  /*
    log_on is about delayed inserts only.
    By default, both logs are enabled (this won't cause problems if the server
    runs without --log-update or --log-bin).
  */
  int log_on= DELAYED_LOG_UPDATE | DELAYED_LOG_BIN ;
197
  bool transactional_table, log_delayed, joins_freed= FALSE;
unknown's avatar
unknown committed
198 199 200 201 202
  uint value_count;
  ulong counter = 1;
  ulonglong id;
  COPY_INFO info;
  TABLE *table;
unknown's avatar
unknown committed
203
  List_iterator_fast<List_item> its(values_list);
unknown's avatar
unknown committed
204
  List_item *values;
unknown's avatar
unknown committed
205 206 207
#ifndef EMBEDDED_LIBRARY
  char *query= thd->query;
#endif
unknown's avatar
unknown committed
208
  thr_lock_type lock_type = table_list->lock_type;
209
  TABLE_LIST *insert_table_list= (TABLE_LIST*)
210
    thd->lex->select_lex.table_list.first;
unknown's avatar
unknown committed
211 212
  DBUG_ENTER("mysql_insert");

213 214 215 216
  if (!(thd->options & OPTION_UPDATE_LOG))
    log_on&= ~(int) DELAYED_LOG_UPDATE;
  if (!(thd->options & OPTION_BIN_LOG))
    log_on&= ~(int) DELAYED_LOG_BIN;
217 218 219 220 221
  /*
    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
   */
222 223 224 225
#ifdef EMBEDDED_LIBRARY
  if (lock_type == TL_WRITE_DELAYED)
    lock_type=TL_WRITE;
#else
unknown's avatar
unknown committed
226 227
  if ((lock_type == TL_WRITE_DELAYED &&
       ((specialflag & (SPECIAL_NO_NEW_FUNC | SPECIAL_SAFE_MODE)) ||
228
	thd->slave_thread || !thd->variables.max_insert_delayed_threads)) ||
229 230
      (lock_type == TL_WRITE_CONCURRENT_INSERT && duplic == DUP_REPLACE) ||
      (duplic == DUP_UPDATE))
unknown's avatar
unknown committed
231
    lock_type=TL_WRITE;
232
#endif
233
  table_list->lock_type= lock_type;
unknown's avatar
unknown committed
234

235
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
236 237 238 239 240 241 242 243 244 245 246 247 248 249
  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);
      }
    }
250
    if ((table= delayed_get_table(thd,table_list)) && !thd->is_fatal_error)
251 252 253
    {
      res= 0;
      if (table_list->next)			/* if sub select */
254
	res= open_and_lock_tables(thd, table_list->next);
255
    }
256
    else
257
    {
258 259
      /* Too many delayed insert threads;  Use a normal insert */
      table_list->lock_type= lock_type= TL_WRITE;
260
      res= open_and_lock_tables(thd, table_list);
261
    }
unknown's avatar
unknown committed
262 263
  }
  else
264
#endif /* EMBEDDED_LIBRARY */
265
    res= open_and_lock_tables(thd, table_list);
266
  if (res || thd->is_fatal_error)
unknown's avatar
unknown committed
267
    DBUG_RETURN(-1);
268 269

  table= table_list->table;
unknown's avatar
unknown committed
270
  thd->proc_info="init";
271
  thd->used_tables=0;
unknown's avatar
unknown committed
272
  values= its++;
unknown's avatar
unknown committed
273

unknown's avatar
unknown committed
274 275
  if (mysql_prepare_insert(thd, table_list, insert_table_list,
                           insert_table_list, table,
unknown's avatar
unknown committed
276 277
			   fields, values, update_fields,
			   update_values, duplic))
278 279
    goto abort;

unknown's avatar
unknown committed
280
  value_count= values->elements;
281
  while ((values= its++))
unknown's avatar
unknown committed
282 283 284 285 286 287 288 289 290
  {
    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;
    }
291
    if (setup_fields(thd, 0, insert_table_list, *values, 0, 0, 0))
unknown's avatar
unknown committed
292 293 294 295
      goto abort;
  }
  its.rewind ();
  /*
unknown's avatar
unknown committed
296
    Fill in the given fields and dump it to the table file
unknown's avatar
unknown committed
297 298
  */

unknown's avatar
unknown committed
299
  info.records= info.deleted= info.copied= info.updated= 0;
300
  info.ignore= ignore;
unknown's avatar
unknown committed
301
  info.handle_duplicates=duplic;
302 303
  info.update_fields= &update_fields;
  info.update_values= &update_values;
304 305 306 307 308 309 310 311
  /*
    Count warnings for all inserts.
    For single line insert, generate an error if try to set a NOT NULL field
    to NULL
  */
  thd->count_cuted_fields= ((values_list.elements == 1) ?
			    CHECK_FIELD_ERROR_FOR_NULL :
			    CHECK_FIELD_WARN);
unknown's avatar
unknown committed
312 313 314 315 316 317
  thd->cuted_fields = 0L;
  table->next_number_field=table->found_next_number_field;

  error=0;
  id=0;
  thd->proc_info="update";
318
  if (duplic != DUP_ERROR || ignore)
unknown's avatar
unknown committed
319
    table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
320 321 322 323 324 325 326 327 328
  /*
    let's *try* to start bulk inserts. It won't necessary
    start them as values_list.elements should be greater than
    some - handler dependent - threshold.
    So we call start_bulk_insert to perform nesessary checks on
    values_list.elements, and - if nothing else - to initialize
    the code to make the call of end_bulk_insert() below safe.
  */
  if (lock_type != TL_WRITE_DELAYED)
329
    table->file->start_bulk_insert(values_list.elements);
330

unknown's avatar
unknown committed
331
  while ((values= its++))
unknown's avatar
unknown committed
332 333 334
  {
    if (fields.elements || !value_count)
    {
unknown's avatar
unknown committed
335
      restore_record(table,default_values);	// Get empty record
unknown's avatar
unknown committed
336
      if (fill_record(fields, *values, 0)|| thd->net.report_error ||
unknown's avatar
unknown committed
337
	  check_null_fields(thd,table))
unknown's avatar
unknown committed
338
      {
unknown's avatar
unknown committed
339
	if (values_list.elements != 1 && !thd->net.report_error)
unknown's avatar
unknown committed
340 341 342 343 344 345 346 347 348 349
	{
	  info.records++;
	  continue;
	}
	error=1;
	break;
      }
    }
    else
    {
350
      if (thd->used_tables)			// Column used in values()
unknown's avatar
unknown committed
351
	restore_record(table,default_values);	// Get empty record
352
      else
unknown's avatar
unknown committed
353
	table->record[0][0]=table->default_values[0]; // Fix delete marker
unknown's avatar
unknown committed
354
      if (fill_record(table->field,*values, 0) || thd->net.report_error)
unknown's avatar
unknown committed
355
      {
unknown's avatar
unknown committed
356
	if (values_list.elements != 1 && ! thd->net.report_error)
unknown's avatar
unknown committed
357 358 359 360 361 362 363 364
	{
	  info.records++;
	  continue;
	}
	error=1;
	break;
      }
    }
365
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
366
    if (lock_type == TL_WRITE_DELAYED)
unknown's avatar
unknown committed
367
    {
368
      error=write_delayed(thd, table, duplic, ignore, query, thd->query_length, log_on);
unknown's avatar
unknown committed
369 370 371
      query=0;
    }
    else
372
#endif
unknown's avatar
unknown committed
373 374 375 376 377 378 379 380 381 382 383 384 385
      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;
    }
386
    thd->row_count++;
unknown's avatar
unknown committed
387
  }
388

389 390 391
  free_underlaid_joins(thd, &thd->lex->select_lex);
  joins_freed= TRUE;

392 393 394 395
  /*
    Now all rows are inserted.  Time to update logs and sends response to
    user
  */
396
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
397 398
  if (lock_type == TL_WRITE_DELAYED)
  {
399 400 401 402 403 404
    if (!error)
    {
      id=0;					// No auto_increment id
      info.copied=values_list.elements;
      end_delayed_insert(thd);
    }
unknown's avatar
unknown committed
405
    query_cache_invalidate3(thd, table_list, 1);
unknown's avatar
unknown committed
406 407
  }
  else
408
#endif
unknown's avatar
unknown committed
409
  {
unknown's avatar
unknown committed
410
    if (table->file->end_bulk_insert() && !error)
411
    {
unknown's avatar
unknown committed
412 413
      table->file->print_error(my_errno,MYF(0));
      error=1;
414
    }
unknown's avatar
unknown committed
415 416
    if (id && values_list.elements != 1)
      thd->insert_id(id);			// For update log
417
    else if (table->next_number_field && info.copied)
unknown's avatar
unknown committed
418
      id=table->next_number_field->val_int();	// Return auto_increment value
unknown's avatar
unknown committed
419

unknown's avatar
unknown committed
420 421 422 423 424
    /*
      Invalidate the table in the query cache if something changed.
      For the transactional algorithm to work the invalidation must be
      before binlog writing and ha_autocommit_...
    */
unknown's avatar
unknown committed
425
    if (info.copied || info.deleted || info.updated)
unknown's avatar
unknown committed
426 427
      query_cache_invalidate3(thd, table_list, 1);

428
    transactional_table= table->file->has_transactions();
unknown's avatar
unknown committed
429

430
    log_delayed= (transactional_table || table->tmp_table);
unknown's avatar
unknown committed
431
    if ((info.copied || info.deleted || info.updated) &&
unknown's avatar
unknown committed
432
	(error <= 0 || !transactional_table))
unknown's avatar
unknown committed
433
    {
434 435 436
      mysql_update_log.write(thd, thd->query, thd->query_length);
      if (mysql_bin_log.is_open())
      {
unknown's avatar
unknown committed
437 438
        if (error <= 0)
          thd->clear_error();
439
	Query_log_event qinfo(thd, thd->query, thd->query_length,
440
			      log_delayed, FALSE);
441
	if (mysql_bin_log.write(&qinfo) && transactional_table)
442
	  error=1;
443
      }
444
      if (!log_delayed)
445
	thd->options|=OPTION_STATUS_NO_TRANS_UPDATE;
unknown's avatar
unknown committed
446
    }
447
    if (transactional_table)
448
      error=ha_autocommit_or_rollback(thd,error);
unknown's avatar
unknown committed
449

unknown's avatar
unknown committed
450 451 452 453 454 455 456 457
    if (thd->lock)
    {
      mysql_unlock_tables(thd, thd->lock);
      thd->lock=0;
    }
  }
  thd->proc_info="end";
  table->next_number_field=0;
458
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;
unknown's avatar
unknown committed
459
  thd->next_insert_id=0;			// Reset this if wrongly used
460
  if (duplic != DUP_ERROR || ignore)
unknown's avatar
unknown committed
461
    table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
462 463 464 465 466 467 468

  /* Reset value of LAST_INSERT_ID if no rows where inserted */
  if (!info.copied && thd->insert_id_used)
  {
    thd->insert_id(0);
    id=0;
  }
unknown's avatar
unknown committed
469 470 471 472
  if (error)
    goto abort;
  if (values_list.elements == 1 && (!(thd->options & OPTION_WARNINGS) ||
				    !thd->cuted_fields))
unknown's avatar
unknown committed
473
    send_ok(thd,info.copied+info.deleted+info.updated,id);
474 475
  else
  {
unknown's avatar
unknown committed
476
    char buff[160];
477
    if (ignore)
478 479 480
      sprintf(buff, ER(ER_INSERT_INFO), (ulong) info.records,
	      (lock_type == TL_WRITE_DELAYED) ? (ulong) 0 :
	      (ulong) (info.records - info.copied), (ulong) thd->cuted_fields);
unknown's avatar
unknown committed
481
    else
482
      sprintf(buff, ER(ER_INSERT_INFO), (ulong) info.records,
unknown's avatar
unknown committed
483
	      (ulong) (info.deleted+info.updated), (ulong) thd->cuted_fields);
unknown's avatar
unknown committed
484
    ::send_ok(thd,info.copied+info.deleted+info.updated,(ulonglong)id,buff);
unknown's avatar
unknown committed
485
  }
unknown's avatar
unknown committed
486
  table->insert_values=0;
unknown's avatar
unknown committed
487 488 489
  DBUG_RETURN(0);

abort:
490
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
491 492
  if (lock_type == TL_WRITE_DELAYED)
    end_delayed_insert(thd);
493
#endif
494 495
  if (!joins_freed)
    free_underlaid_joins(thd, &thd->lex->select_lex);
unknown's avatar
unknown committed
496
  table->insert_values=0;
unknown's avatar
unknown committed
497 498 499 500
  DBUG_RETURN(-1);
}


unknown's avatar
unknown committed
501 502 503 504
/*
  Prepare items in INSERT statement

  SYNOPSIS
505
    mysql_prepare_insert()
unknown's avatar
unknown committed
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
    thd			thread handler
    table_list		global table list (not including first table for
			INSERT ... SELECT)
    insert_table_list	Table we are inserting into (for INSERT ... SELECT)
    dup_table_list	Tables to be used in ON DUPLICATE KEY
			It's either all global tables or only the table we
                        insert into, depending on if we are using GROUP BY
                        in the SELECT clause).
    values              Values to insert. NULL for INSERT ... SELECT

  TODO (in far future)
    In cases of:
    INSERT INTO t1 SELECT a, sum(a) as sum1 from t2 GROUP BY a
    ON DUPLICATE KEY ...
    we should be able to refer to sum1 in the ON DUPLICATE KEY part
unknown's avatar
unknown committed
521

522 523 524 525
  WARNING
    You MUST set table->insert_values to 0 after calling this function
    before releasing the table object.

unknown's avatar
unknown committed
526
  RETURN VALUE
unknown's avatar
unknown committed
527 528
    0   OK
    -1  error (message is not sent to user)
unknown's avatar
unknown committed
529
*/
unknown's avatar
unknown committed
530

unknown's avatar
unknown committed
531
int mysql_prepare_insert(THD *thd, TABLE_LIST *table_list,
unknown's avatar
unknown committed
532 533 534
			 TABLE_LIST *insert_table_list,
                         TABLE_LIST *dup_table_list,
                         TABLE *table,
unknown's avatar
unknown committed
535 536 537 538 539
			 List<Item> &fields, List_item *values,
			 List<Item> &update_fields, List<Item> &update_values,
			 enum_duplicates duplic)
{
  DBUG_ENTER("mysql_prepare_insert");
unknown's avatar
unknown committed
540

unknown's avatar
unknown committed
541 542 543
  if (duplic == DUP_UPDATE && !table->insert_values)
  {
    /* it should be allocated before Item::fix_fields() */
544
    table->insert_values=
unknown's avatar
unknown committed
545 546 547 548
      (byte *)alloc_root(thd->mem_root, table->rec_buff_length);
    if (!table->insert_values)
      DBUG_RETURN(-1);
  }
unknown's avatar
unknown committed
549
  if (setup_tables(insert_table_list))
unknown's avatar
unknown committed
550
    DBUG_RETURN(-1);
unknown's avatar
unknown committed
551
  if (values)
unknown's avatar
unknown committed
552
  {
unknown's avatar
unknown committed
553 554 555 556 557 558 559 560 561 562 563 564
    if (check_insert_fields(thd, table, fields, *values) ||
        setup_fields(thd, 0, insert_table_list, *values, 0, 0, 0) ||
        (duplic == DUP_UPDATE &&
         (check_update_fields(thd, table, insert_table_list, update_fields) ||
          setup_fields(thd, 0, dup_table_list, update_values, 1, 0, 0))))
      DBUG_RETURN(-1);
    if (find_real_table_in_list(table_list->next, table_list->db,
                                                  table_list->real_name))
    {
      my_error(ER_UPDATE_TABLE_USED, MYF(0), table_list->real_name);
      DBUG_RETURN(-1);
    }
unknown's avatar
unknown committed
565
  }
566 567 568
  if (duplic == DUP_UPDATE || duplic == DUP_REPLACE)
    table->file->extra(HA_EXTRA_RETRIEVE_PRIMARY_KEY);

unknown's avatar
unknown committed
569 570 571 572
  DBUG_RETURN(0);
}


unknown's avatar
unknown committed
573 574 575 576 577 578 579 580 581 582 583 584
	/* 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;
}


/*
unknown's avatar
unknown committed
585
  Write a record to table with optional deleting of conflicting records
unknown's avatar
unknown committed
586 587 588 589 590 591 592
*/


int write_record(TABLE *table,COPY_INFO *info)
{
  int error;
  char *key=0;
593
  DBUG_ENTER("write_record");
unknown's avatar
unknown committed
594

unknown's avatar
unknown committed
595
  info->records++;
596 597
  if (info->handle_duplicates == DUP_REPLACE ||
      info->handle_duplicates == DUP_UPDATE)
unknown's avatar
unknown committed
598 599 600
  {
    while ((error=table->file->write_row(table->record[0])))
    {
unknown's avatar
unknown committed
601
      if (error != HA_WRITE_SKIP)
unknown's avatar
unknown committed
602 603 604 605
	goto err;
      uint key_nr;
      if ((int) (key_nr = table->file->get_dup_key(error)) < 0)
      {
unknown's avatar
unknown committed
606
	error=HA_WRITE_SKIP;			/* Database can't find key */
unknown's avatar
unknown committed
607 608
	goto err;
      }
609 610 611 612 613
      /*
	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.
      */
614 615 616
      if (info->handle_duplicates == DUP_REPLACE &&
          table->next_number_field &&
          key_nr == table->next_number_index &&
617 618
	  table->file->auto_increment_column_changed)
	goto err;
619
      if (table->file->table_flags() & HA_DUPP_POS)
unknown's avatar
unknown committed
620 621 622 623 624 625
      {
	if (table->file->rnd_pos(table->record[1],table->file->dupp_ref))
	  goto err;
      }
      else
      {
626
	if (table->file->extra(HA_EXTRA_FLUSH_CACHE)) /* Not needed with NISAM */
unknown's avatar
unknown committed
627 628 629 630
	{
	  error=my_errno;
	  goto err;
	}
unknown's avatar
unknown committed
631

unknown's avatar
unknown committed
632 633 634 635 636 637 638 639 640 641 642
	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,
643
						(byte*) key,
unknown's avatar
unknown committed
644 645
						table->key_info[key_nr].
						key_length,
unknown's avatar
unknown committed
646 647 648
						HA_READ_KEY_EXACT))))
	  goto err;
      }
649
      if (info->handle_duplicates == DUP_UPDATE)
unknown's avatar
unknown committed
650
      {
651 652 653 654
        /* we don't check for other UNIQUE keys - the first row
           that matches, is updated. If update causes a conflict again,
           an error is returned
        */
unknown's avatar
unknown committed
655
	DBUG_ASSERT(table->insert_values != NULL);
unknown's avatar
unknown committed
656 657
        store_record(table,insert_values);
        restore_record(table,record[1]);
unknown's avatar
unknown committed
658
	DBUG_ASSERT(info->update_fields->elements==info->update_values->elements);
unknown's avatar
unknown committed
659
        if (fill_record(*info->update_fields, *info->update_values, 0))
660 661
          goto err;
        if ((error=table->file->update_row(table->record[1],table->record[0])))
662 663 664
	{
	  if ((error == HA_ERR_FOUND_DUPP_KEY) && info->ignore)
	    break;
665
          goto err;
666
	}
unknown's avatar
unknown committed
667
        info->updated++;
668 669 670 671
        break;
      }
      else /* DUP_REPLACE */
      {
unknown's avatar
unknown committed
672 673 674 675 676
	/*
	  The manual defines the REPLACE semantics that it is either
	  an INSERT or DELETE(s) + INSERT; FOREIGN KEY checks in
	  InnoDB do not function in the defined way if we allow MySQL
	  to convert the latter operation internally to an UPDATE.
677 678
          We also should not perform this conversion if we have 
          timestamp field with ON UPDATE which is different from DEFAULT.
unknown's avatar
unknown committed
679 680
	*/
	if (last_uniq_key(table,key_nr) &&
681
	    !table->file->referenced_by_foreign_key() &&
682 683
            (table->timestamp_field_type == TIMESTAMP_NO_AUTO_SET ||
             table->timestamp_field_type == TIMESTAMP_AUTO_SET_ON_BOTH))
684
        {
unknown's avatar
unknown committed
685 686
          if ((error=table->file->update_row(table->record[1],
					     table->record[0])))
687 688
            goto err;
          info->deleted++;
unknown's avatar
unknown committed
689
          break;				/* Update logfile and count */
690 691 692 693
        }
        else if ((error=table->file->delete_row(table->record[1])))
          goto err;
        info->deleted++;
unknown's avatar
unknown committed
694 695 696 697 698 699
      }
    }
    info->copied++;
  }
  else if ((error=table->file->write_row(table->record[0])))
  {
700
    if (!info->ignore ||
unknown's avatar
unknown committed
701 702 703 704 705 706 707
	(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);
708
  DBUG_RETURN(0);
unknown's avatar
unknown committed
709 710 711

err:
  if (key)
712
    my_safe_afree(key,table->max_unique_length,MAX_KEY_LENGTH);
713
  info->last_errno= error;
unknown's avatar
unknown committed
714
  table->file->print_error(error,MYF(0));
715
  DBUG_RETURN(1);
unknown's avatar
unknown committed
716 717 718 719
}


/******************************************************************************
unknown's avatar
unknown committed
720 721 722
  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.
unknown's avatar
unknown committed
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
******************************************************************************/

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

/*****************************************************************************
unknown's avatar
unknown committed
745 746
  Handling of delayed inserts
  A thread is created for each table that one uses with the DELAYED attribute.
unknown's avatar
unknown committed
747 748
*****************************************************************************/

749 750
#ifndef EMBEDDED_LIBRARY

unknown's avatar
unknown committed
751 752 753 754 755
class delayed_row :public ilink {
public:
  char *record,*query;
  enum_duplicates dup;
  time_t start_time;
756
  bool query_start_used,last_insert_id_used,insert_id_used, ignore;
757
  int log_query;
unknown's avatar
unknown committed
758
  ulonglong last_insert_id;
759
  timestamp_auto_set_type timestamp_field_type;
unknown's avatar
unknown committed
760 761
  uint query_length;

762 763
  delayed_row(enum_duplicates dup_arg, bool ignore_arg, int log_query_arg)
    :record(0),query(0),dup(dup_arg),ignore(ignore_arg),log_query(log_query_arg) {}
unknown's avatar
unknown committed
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
  ~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;
782
  ulong group_count;
unknown's avatar
unknown committed
783
  TABLE_LIST table_list;			// Argument
unknown's avatar
unknown committed
784 785 786 787 788 789

  delayed_insert()
    :locks_in_memory(0),
     table(0),tables_in_use(0),stacked_inserts(0), status(0), dead(0),
     group_count(0)
  {
790
    thd.user=thd.priv_user=(char*) delayed_user;
unknown's avatar
unknown committed
791
    thd.host=(char*) my_localhost;
unknown's avatar
unknown committed
792 793 794
    thd.current_tablenr=0;
    thd.version=refresh_version;
    thd.command=COM_DELAYED_INSERT;
795 796
    thd.lex->current_select= 0; 		// for my_message_sql
    thd.lex->sql_command= SQLCOM_INSERT;        // For innodb::store_lock()
unknown's avatar
unknown committed
797

798 799
    bzero((char*) &thd.net, sizeof(thd.net));		// Safety
    bzero((char*) &table_list, sizeof(table_list));	// Safety
800
    thd.system_thread= SYSTEM_THREAD_DELAYED_INSERT;
801
    thd.host_or_ip= "";
unknown's avatar
unknown committed
802
    bzero((char*) &info,sizeof(info));
803
    pthread_mutex_init(&mutex,MY_MUTEX_INIT_FAST);
unknown's avatar
unknown committed
804 805 806 807 808 809 810 811
    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()
  {
812
    /* The following is not really needed, but just for safety */
unknown's avatar
unknown committed
813 814 815 816 817 818
    delayed_row *row;
    while ((row=rows.get()))
      delete row;
    if (table)
      close_thread_tables(&thd);
    VOID(pthread_mutex_lock(&LOCK_thread_count));
unknown's avatar
unknown committed
819 820 821
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);
    pthread_cond_destroy(&cond_client);
unknown's avatar
unknown committed
822 823 824 825 826 827
    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));
828
    VOID(pthread_cond_broadcast(&COND_thread_count)); /* Tell main we are ready */
unknown's avatar
unknown committed
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 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
  }

  /* 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;
885
  TABLE *table;
unknown's avatar
unknown committed
886 887 888 889 890
  DBUG_ENTER("delayed_get_table");

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

891
  /* Find the thread which handles this table. */
unknown's avatar
unknown committed
892 893
  if (!(tmp=find_handler(thd,table_list)))
  {
894 895 896 897
    /*
      No match. Create a new thread to handle the table, but
      no more than max_insert_delayed_threads.
    */
898
    if (delayed_insert_threads >= thd->variables.max_insert_delayed_threads)
899
      DBUG_RETURN(0);
unknown's avatar
unknown committed
900 901
    thd->proc_info="Creating delayed handler";
    pthread_mutex_lock(&LOCK_delayed_create);
902 903 904 905 906
    /*
      The first search above was done without LOCK_delayed_create.
      Another thread might have created the handler in between. Search again.
    */
    if (! (tmp= find_handler(thd, table_list)))
unknown's avatar
unknown committed
907
    {
908 909 910 911
      /*
        Avoid that a global read lock steps in while we are creating the
        new thread. It would block trying to open the table. Hence, the
        DI thread and this thread would wait until after the global
912 913 914 915 916
        readlock is gone. Since the insert thread needs to wait for a
        global read lock anyway, we do it right now. Note that
        wait_if_global_read_lock() sets a protection against a new
        global read lock when it succeeds. This needs to be released by
        start_waiting_global_read_lock().
917
      */
918
      if (wait_if_global_read_lock(thd, 0, 1))
919
        goto err;
unknown's avatar
unknown committed
920 921 922
      if (!(tmp=new delayed_insert()))
      {
	my_error(ER_OUTOFMEMORY,MYF(0),sizeof(delayed_insert));
923
	goto err1;
unknown's avatar
unknown committed
924
      }
unknown's avatar
unknown committed
925 926 927
      pthread_mutex_lock(&LOCK_thread_count);
      thread_count++;
      pthread_mutex_unlock(&LOCK_thread_count);
unknown's avatar
unknown committed
928
      if (!(tmp->thd.db=my_strdup(table_list->db,MYF(MY_WME))) ||
929
	  !(tmp->thd.query=my_strdup(table_list->real_name,MYF(MY_WME))))
unknown's avatar
unknown committed
930 931 932
      {
	delete tmp;
	my_error(ER_OUT_OF_RESOURCES,MYF(0));
933
	goto err1;
unknown's avatar
unknown committed
934
      }
unknown's avatar
unknown committed
935 936
      tmp->table_list= *table_list;			// Needed to open table
      tmp->table_list.db= tmp->thd.db;
937
      tmp->table_list.alias= tmp->table_list.real_name=tmp->thd.query;
unknown's avatar
unknown committed
938 939 940 941 942 943 944 945 946 947 948
      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;
949
	net_printf(thd,ER_CANT_CREATE_THREAD,error);
950
	goto err1;
unknown's avatar
unknown committed
951 952 953 954 955 956 957 958 959
      }

      /* 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);
960 961 962 963 964
      /*
        Release the protection against the global read lock and wake
        everyone, who might want to set a global read lock.
      */
      start_waiting_global_read_lock(thd);
unknown's avatar
unknown committed
965 966 967
      thd->proc_info="got old table";
      if (tmp->thd.killed)
      {
968
	if (tmp->thd.is_fatal_error)
unknown's avatar
unknown committed
969 970
	{
	  /* Copy error message and abort */
971
	  thd->fatal_error();
unknown's avatar
unknown committed
972
	  strmov(thd->net.last_error,tmp->thd.net.last_error);
973
	  thd->net.last_errno=tmp->thd.net.last_errno;
unknown's avatar
unknown committed
974 975
	}
	tmp->unlock();
976
	goto err;
unknown's avatar
unknown committed
977 978 979 980
      }
      if (thd->killed)
      {
	tmp->unlock();
981
	goto err;
unknown's avatar
unknown committed
982 983 984 985 986 987
      }
    }
    pthread_mutex_unlock(&LOCK_delayed_create);
  }

  pthread_mutex_lock(&tmp->mutex);
988
  table=tmp->get_local_table(thd);
unknown's avatar
unknown committed
989 990 991
  pthread_mutex_unlock(&tmp->mutex);
  if (table)
    thd->di=tmp;
992 993
  else if (tmp->thd.is_fatal_error)
    thd->fatal_error();
994 995
  /* Unlock the delayed insert object after its last access. */
  tmp->unlock();
unknown's avatar
unknown committed
996
  DBUG_RETURN((table_list->table=table));
997 998 999

 err1:
  thd->fatal_error();
1000 1001 1002 1003 1004
  /*
    Release the protection against the global read lock and wake
    everyone, who might want to set a global read lock.
  */
  start_waiting_global_read_lock(thd);
1005 1006 1007
 err:
  pthread_mutex_unlock(&LOCK_delayed_create);
  DBUG_RETURN(0); // Continue with normal insert
unknown's avatar
unknown committed
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
}


/*
  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;
1021
  Field **field,**org_field, *found_next_number_field;
unknown's avatar
unknown committed
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
  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";
unknown's avatar
unknown committed
1047 1048 1049
  copy= (TABLE*) client_thd->alloc(sizeof(*copy)+
				   (table->fields+1)*sizeof(Field**)+
				   table->reclength);
unknown's avatar
unknown committed
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
  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]);

1064
  found_next_number_field=table->found_next_number_field;
unknown's avatar
unknown committed
1065 1066
  for (org_field=table->field ; *org_field ; org_field++,field++)
  {
unknown's avatar
unknown committed
1067
    if (!(*field= (*org_field)->new_field(client_thd->mem_root,copy)))
unknown's avatar
unknown committed
1068
      return 0;
1069
    (*field)->orig_table= copy;			// Remove connection
unknown's avatar
unknown committed
1070
    (*field)->move_field(adjust_ptrs);		// Point at copy->record[0]
1071 1072
    if (*org_field == found_next_number_field)
      (*field)->table->found_next_number_field= *field;
unknown's avatar
unknown committed
1073 1074 1075 1076 1077 1078 1079 1080 1081
  }
  *field=0;

  /* Adjust timestamp */
  if (table->timestamp_field)
  {
    /* Restore offset as this may have been reset in handle_inserts */
    copy->timestamp_field=
      (Field_timestamp*) copy->field[table->timestamp_field_offset];
1082
    copy->timestamp_field->unireg_check= table->timestamp_field->unireg_check;
1083
    copy->timestamp_field_type= copy->timestamp_field->get_auto_set_type();
unknown's avatar
unknown committed
1084 1085 1086 1087
  }

  /* _rowid is not used with delayed insert */
  copy->rowid_field=0;
1088 1089 1090 1091

  /* Adjust in_use for pointing to client thread */
  copy->in_use= client_thd;
  
unknown's avatar
unknown committed
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
  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 */

1105
static int write_delayed(THD *thd,TABLE *table,enum_duplicates duplic, bool ignore,
1106
			 char *query, uint query_length, int log_on)
unknown's avatar
unknown committed
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
{
  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";

1118
  if (thd->killed || !(row= new delayed_row(duplic, ignore, log_on)))
unknown's avatar
unknown committed
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
    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;
1138
  row->timestamp_field_type=    table->timestamp_field_type;
unknown's avatar
unknown committed
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159

  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)
{
1160
  DBUG_ENTER("end_delayed_insert");
unknown's avatar
unknown committed
1161 1162
  delayed_insert *di=thd->di;
  pthread_mutex_lock(&di->mutex);
1163
  DBUG_PRINT("info",("tables in use: %d",di->tables_in_use));
unknown's avatar
unknown committed
1164 1165 1166 1167 1168 1169
  if (!--di->tables_in_use || di->thd.killed)
  {						// Unlock table
    di->status=1;
    pthread_cond_signal(&di->cond);
  }
  pthread_mutex_unlock(&di->mutex);
1170
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
}


/* 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++))
  {
    tmp->thd.killed=1;
    if (tmp->thd.mysys_var)
    {
      pthread_mutex_lock(&tmp->thd.mysys_var->mutex);
unknown's avatar
unknown committed
1188
      if (tmp->thd.mysys_var->current_cond)
unknown's avatar
unknown committed
1189
      {
unknown's avatar
unknown committed
1190 1191 1192 1193 1194 1195
	/*
	  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);
unknown's avatar
unknown committed
1196
	pthread_cond_broadcast(tmp->thd.mysys_var->current_cond);
unknown's avatar
unknown committed
1197 1198
	if (&tmp->mutex != tmp->thd.mysys_var->current_mutex)
	  pthread_mutex_unlock(tmp->thd.mysys_var->current_mutex);
unknown's avatar
unknown committed
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
      }
      pthread_mutex_unlock(&tmp->thd.mysys_var->mutex);
    }
  }
  VOID(pthread_mutex_unlock(&LOCK_delayed_insert)); // For unlink from list
}


/*
 * Create a new delayed insert thread
*/

1211
extern "C" pthread_handler_decl(handle_delayed_insert,arg)
unknown's avatar
unknown committed
1212 1213 1214 1215 1216 1217 1218 1219
{
  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++;
1220
  thd->end_time();
unknown's avatar
unknown committed
1221
  threads.append(thd);
unknown's avatar
unknown committed
1222
  thd->killed=abort_loop;
unknown's avatar
unknown committed
1223 1224
  pthread_mutex_unlock(&LOCK_thread_count);

1225 1226 1227 1228 1229 1230 1231 1232
  /*
    Wait until the client runs into pthread_cond_wait(),
    where we free it after the table is opened and di linked in the list.
    If we did not wait here, the client might detect the opened table
    before it is linked to the list. It would release LOCK_delayed_create
    and allow another thread to create another handler for the same table,
    since it does not find one in the list.
  */
unknown's avatar
unknown committed
1233
  pthread_mutex_lock(&di->mutex);
unknown's avatar
unknown committed
1234
#if !defined( __WIN__) && !defined(OS2)	/* Win32 calls this in pthread_create */
unknown's avatar
unknown committed
1235 1236 1237 1238 1239 1240 1241 1242
  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");
unknown's avatar
unknown committed
1243
  if (init_thr_lock() || thd->store_globals())
unknown's avatar
unknown committed
1244
  {
1245
    thd->fatal_error();
unknown's avatar
unknown committed
1246 1247 1248
    strmov(thd->net.last_error,ER(thd->net.last_errno=ER_OUT_OF_RESOURCES));
    goto end;
  }
unknown's avatar
unknown committed
1249
#if !defined(__WIN__) && !defined(OS2) && !defined(__NETWARE__)
unknown's avatar
unknown committed
1250 1251 1252 1253 1254 1255 1256
  sigset_t set;
  VOID(sigemptyset(&set));			// Get mask in use
  VOID(pthread_sigmask(SIG_UNBLOCK,&set,&thd->block_signals));
#endif

  /* open table */

unknown's avatar
unknown committed
1257
  if (!(di->table=open_ltable(thd,&di->table_list,TL_WRITE_DELAYED)))
unknown's avatar
unknown committed
1258
  {
1259
    thd->fatal_error();				// Abort waiting inserts
unknown's avatar
unknown committed
1260 1261
    goto end;
  }
unknown's avatar
unknown committed
1262
  if (!(di->table->file->table_flags() & HA_CAN_INSERT_DELAYED))
unknown's avatar
unknown committed
1263
  {
1264
    thd->fatal_error();
unknown's avatar
unknown committed
1265
    my_error(ER_ILLEGAL_HA, MYF(0), di->table_list.real_name);
unknown's avatar
unknown committed
1266 1267
    goto end;
  }
unknown's avatar
unknown committed
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
  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;
1303
      set_timespec(abstime, delayed_insert_timeout);
unknown's avatar
unknown committed
1304 1305 1306 1307

      /* Information for pthread_kill */
      di->thd.mysys_var->current_mutex= &di->mutex;
      di->thd.mysys_var->current_cond= &di->cond;
1308
      di->thd.proc_info="Waiting for INSERT";
unknown's avatar
unknown committed
1309

1310
      DBUG_PRINT("info",("Waiting for someone to insert rows"));
unknown's avatar
unknown committed
1311
      while (!thd->killed)
unknown's avatar
unknown committed
1312 1313
      {
	int error;
1314
#if defined(HAVE_BROKEN_COND_TIMEDWAIT)
unknown's avatar
unknown committed
1315 1316 1317 1318
	error=pthread_cond_wait(&di->cond,&di->mutex);
#else
	error=pthread_cond_timedwait(&di->cond,&di->mutex,&abstime);
#ifdef EXTRA_DEBUG
1319
	if (error && error != EINTR && error != ETIMEDOUT)
unknown's avatar
unknown committed
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
	{
	  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;
	}
      }
unknown's avatar
unknown committed
1335 1336
      /* We can't lock di->mutex and mysys_var->mutex at the same time */
      pthread_mutex_unlock(&di->mutex);
unknown's avatar
unknown committed
1337 1338 1339 1340
      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);
unknown's avatar
unknown committed
1341
      pthread_mutex_lock(&di->mutex);
unknown's avatar
unknown committed
1342
    }
1343
    di->thd.proc_info=0;
unknown's avatar
unknown committed
1344 1345 1346

    if (di->tables_in_use && ! thd->lock)
    {
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
      /*
        Request for new delayed insert.
        Lock the table, but avoid to be blocked by a global read lock.
        If we got here while a global read lock exists, then one or more
        inserts started before the lock was requested. These are allowed
        to complete their work before the server returns control to the
        client which requested the global read lock. The delayed insert
        handler will close the table and finish when the outstanding
        inserts are done.
      */
1357 1358
      if (! (thd->lock= mysql_lock_tables(thd, &di->table, 1,
                                          MYSQL_LOCK_IGNORE_GLOBAL_READ_LOCK)))
unknown's avatar
unknown committed
1359
      {
unknown's avatar
unknown committed
1360 1361
	di->dead= 1;			// Some fatal error
        thd->killed= 1;
unknown's avatar
unknown committed
1362 1363 1364 1365 1366 1367 1368
      }
      pthread_cond_broadcast(&di->cond_client);
    }
    if (di->stacked_inserts)
    {
      if (di->handle_inserts())
      {
unknown's avatar
unknown committed
1369 1370
	di->dead= 1;			// Some fatal error
        thd->killed= 1;
unknown's avatar
unknown committed
1371 1372 1373 1374 1375
      }
    }
    di->status=0;
    if (!di->stacked_inserts && !di->tables_in_use && thd->lock)
    {
unknown's avatar
unknown committed
1376 1377 1378 1379
      /*
        No one is doing a insert delayed
        Unlock table so that other threads can use it
      */
unknown's avatar
unknown committed
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398
      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;
unknown's avatar
unknown committed
1399 1400
  di->dead= 1;                                  // If error
  thd->killed= 1;
unknown's avatar
unknown committed
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 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 1438 1439 1440 1441 1442 1443 1444 1445 1446
  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;
1447
  ulong max_rows;
1448
  bool using_ignore=0, using_bin_log=mysql_bin_log.is_open();
1449
  delayed_row *row;
unknown's avatar
unknown committed
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
  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";
1466
  max_rows= delayed_insert_limit;
unknown's avatar
unknown committed
1467 1468 1469
  if (thd.killed || table->version != refresh_version)
  {
    thd.killed=1;
1470
    max_rows= ~(ulong)0;                        // Do as much as possible
unknown's avatar
unknown committed
1471 1472
  }

1473 1474 1475 1476 1477 1478 1479
  /*
    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);
unknown's avatar
unknown committed
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
  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;
1492
    table->timestamp_field_type= row->timestamp_field_type;
unknown's avatar
unknown committed
1493

1494
    info.ignore= row->ignore;
unknown's avatar
unknown committed
1495
    info.handle_duplicates= row->dup;
1496
    if (info.ignore ||
1497
	info.handle_duplicates != DUP_ERROR)
unknown's avatar
unknown committed
1498 1499 1500 1501
    {
      table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
      using_ignore=1;
    }
unknown's avatar
unknown committed
1502
    thd.clear_error(); // reset error for binlog
unknown's avatar
unknown committed
1503 1504
    if (write_record(table,&info))
    {
1505
      info.error_count++;				// Ignore errors
1506
      thread_safe_increment(delayed_insert_errors,&LOCK_delayed_status);
unknown's avatar
unknown committed
1507
      row->log_query = 0;
unknown's avatar
unknown committed
1508
    }
unknown's avatar
unknown committed
1509 1510 1511 1512 1513
    if (using_ignore)
    {
      using_ignore=0;
      table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
    }
1514
    if (row->query)
unknown's avatar
unknown committed
1515
    {
1516 1517 1518
      if (row->log_query & DELAYED_LOG_UPDATE)
        mysql_update_log.write(&thd,row->query, row->query_length);
      if (row->log_query & DELAYED_LOG_BIN && using_bin_log)
1519
      {
1520
        Query_log_event qinfo(&thd, row->query, row->query_length,0, FALSE);
1521
        mysql_bin_log.write(&qinfo);
1522
      }
unknown's avatar
unknown committed
1523 1524 1525 1526 1527 1528 1529 1530
    }
    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;
1531 1532 1533 1534 1535 1536 1537 1538 1539
    /*
      Let READ clients do something once in a while
      We should however not break in the middle of a multi-line insert
      if we have binary logging enabled as we don't want other commands
      on this table until all entries has been processed
    */
    if (group_count++ >= max_rows && (row= rows.head()) &&
	(!(row->log_query & DELAYED_LOG_BIN && using_bin_log) ||
	 row->query))
unknown's avatar
unknown committed
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554
    {
      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;
	}
unknown's avatar
unknown committed
1555
	query_cache_invalidate3(&thd, table, 1);
unknown's avatar
unknown committed
1556 1557 1558 1559 1560
	if (thr_reschedule_write_lock(*thd.lock->locks))
	{
	  /* This should never happen */
	  sql_print_error(ER(ER_DELAYED_CANT_CHANGE_LOCK),table->real_name);
	}
1561 1562
	if (!using_bin_log)
	  table->file->extra(HA_EXTRA_WRITE_CACHE);
unknown's avatar
unknown committed
1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579
	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;
  }
unknown's avatar
unknown committed
1580
  query_cache_invalidate3(&thd, table, 1);
unknown's avatar
unknown committed
1581 1582 1583 1584
  pthread_mutex_lock(&mutex);
  DBUG_RETURN(0);

 err:
1585 1586 1587 1588 1589 1590 1591
  /* Remove all not used rows */
  while ((row=rows.get()))
  {
    delete row;
    thread_safe_increment(delayed_insert_errors,&LOCK_delayed_status);
    stacked_inserts--;
  }
unknown's avatar
unknown committed
1592 1593 1594 1595
  thread_safe_increment(delayed_insert_errors, &LOCK_delayed_status);
  pthread_mutex_lock(&mutex);
  DBUG_RETURN(1);
}
1596
#endif /* EMBEDDED_LIBRARY */
unknown's avatar
unknown committed
1597 1598

/***************************************************************************
unknown's avatar
unknown committed
1599
  Store records in INSERT ... SELECT *
unknown's avatar
unknown committed
1600 1601 1602
***************************************************************************/

int
1603
select_insert::prepare(List<Item> &values, SELECT_LEX_UNIT *u)
unknown's avatar
unknown committed
1604
{
1605 1606 1607
  int res;
  LEX *lex= thd->lex;
  SELECT_LEX *lex_current_select_save= lex->current_select;
unknown's avatar
unknown committed
1608
  bool lex_select_no_error= lex->select_lex.no_error;
unknown's avatar
unknown committed
1609 1610
  DBUG_ENTER("select_insert::prepare");

1611
  unit= u;
1612 1613 1614 1615
  /*
    Since table in which we are going to insert is added to the first
    select, LEX::current_select should point to the first select while
    we are fixing fields from insert list.
unknown's avatar
unknown committed
1616 1617
    Since these checks may cause the query to fail, we don't want the
    error messages to be converted into warnings, must force no_error=0
1618 1619
  */
  lex->current_select= &lex->select_lex;
unknown's avatar
unknown committed
1620 1621 1622 1623 1624 1625 1626
  lex->select_lex.no_error= 0;
  res=
    check_insert_fields(thd, table, *fields, values) ||
    setup_fields(thd, 0, insert_table_list, values, 0, 0, 0) ||
    (info.handle_duplicates == DUP_UPDATE &&
     (check_update_fields(thd, table, insert_table_list, *info.update_fields) ||
      setup_fields(thd, 0, dup_table_list, *info.update_values, 1, 0, 0)));
1627
  lex->current_select= lex_current_select_save;
unknown's avatar
unknown committed
1628
  lex->select_lex.no_error= lex_select_no_error;
1629
  if (res)
unknown's avatar
unknown committed
1630 1631
    DBUG_RETURN(1);

unknown's avatar
unknown committed
1632
  restore_record(table,default_values);			// Get empty record
unknown's avatar
unknown committed
1633
  table->next_number_field=table->found_next_number_field;
unknown's avatar
unknown committed
1634
  thd->cuted_fields=0;
1635
  if (info.ignore ||
1636
      info.handle_duplicates != DUP_ERROR)
unknown's avatar
unknown committed
1637
    table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
1638
  table->file->start_bulk_insert((ha_rows) 0);
unknown's avatar
unknown committed
1639 1640 1641
  DBUG_RETURN(0);
}

1642 1643 1644 1645 1646 1647 1648

void select_insert::cleanup()
{
  /* select_insert/select_create are never re-used in prepared statement */
  DBUG_ASSERT(0);
}

unknown's avatar
unknown committed
1649 1650 1651 1652 1653
select_insert::~select_insert()
{
  if (table)
  {
    table->next_number_field=0;
1654
    table->file->reset();
unknown's avatar
unknown committed
1655
  }
1656
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;
unknown's avatar
unknown committed
1657 1658 1659 1660 1661
}


bool select_insert::send_data(List<Item> &values)
{
1662
  DBUG_ENTER("select_insert::send_data");
unknown's avatar
unknown committed
1663
  bool error=0;
1664
  if (unit->offset_limit_cnt)
unknown's avatar
unknown committed
1665
  {						// using limit offset,count
1666
    unit->offset_limit_cnt--;
1667
    DBUG_RETURN(0);
unknown's avatar
unknown committed
1668
  }
unknown's avatar
unknown committed
1669 1670 1671 1672
  thd->count_cuted_fields= CHECK_FIELD_WARN;		// calc cuted fields
  store_values(values);
  error=thd->net.report_error || write_record(table,&info);
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;
1673 1674

  if (!error)
unknown's avatar
unknown committed
1675
  {
1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688
    /*
    Restore fields of the record since it is possible that they were
    changed by ON DUPLICATE KEY UPDATE clause.
    */
    if (info.handle_duplicates == DUP_UPDATE)
      restore_record(table, default_values);

    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();
    }
unknown's avatar
unknown committed
1689
  }
unknown's avatar
unknown committed
1690
  DBUG_RETURN(error);
unknown's avatar
unknown committed
1691 1692 1693
}


unknown's avatar
unknown committed
1694 1695 1696 1697 1698 1699 1700 1701
void select_insert::store_values(List<Item> &values)
{
  if (fields->elements)
    fill_record(*fields, values, 1);
  else
    fill_record(table->field, values, 1);
}

unknown's avatar
unknown committed
1702 1703
void select_insert::send_error(uint errcode,const char *err)
{
unknown's avatar
unknown committed
1704 1705
  DBUG_ENTER("select_insert::send_error");

1706
  /* TODO error should be sent at the query processing end */
1707
  ::send_error(thd,errcode,err);
1708 1709 1710 1711 1712 1713 1714 1715 1716

  if (!table)
  {
    /*
      This can only happen when using CREATE ... SELECT and the table was not
      created becasue of an syntax error
    */
    DBUG_VOID_RETURN;
  }
1717
  table->file->end_bulk_insert();
unknown's avatar
unknown committed
1718 1719 1720 1721 1722
  /*
    If at least one row has been inserted/modified and will stay in the table
    (the table doesn't have transactions) (example: we got a duplicate key
    error while inserting into a MyISAM table) we must write to the binlog (and
    the error code will make the slave stop).
1723
  */
unknown's avatar
unknown committed
1724
  if ((info.copied || info.deleted || info.updated) &&
unknown's avatar
unknown committed
1725
      !table->file->has_transactions())
1726 1727 1728 1729 1730 1731 1732
  {
    if (last_insert_id)
      thd->insert_id(last_insert_id);		// For binary log
    mysql_update_log.write(thd,thd->query,thd->query_length);
    if (mysql_bin_log.is_open())
    {
      Query_log_event qinfo(thd, thd->query, thd->query_length,
1733
                            table->file->has_transactions(), FALSE);
1734 1735
      mysql_bin_log.write(&qinfo);
    }
unknown's avatar
unknown committed
1736
    if (!table->tmp_table)
unknown's avatar
unknown committed
1737
      thd->options|=OPTION_STATUS_NO_TRANS_UPDATE;
1738
  }
unknown's avatar
unknown committed
1739
  if (info.copied || info.deleted || info.updated)
unknown's avatar
unknown committed
1740
    query_cache_invalidate3(thd, table, 1);
unknown's avatar
unknown committed
1741
  ha_rollback_stmt(thd);
unknown's avatar
unknown committed
1742
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
1743 1744 1745 1746 1747
}


bool select_insert::send_eof()
{
1748
  int error,error2;
unknown's avatar
unknown committed
1749 1750
  DBUG_ENTER("select_insert::send_eof");

unknown's avatar
unknown committed
1751
  error=table->file->end_bulk_insert();
unknown's avatar
unknown committed
1752
  table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
1753

1754 1755 1756 1757
  /*
    We must invalidate the table in the query cache before binlog writing
    and ha_autocommit_...
  */
unknown's avatar
unknown committed
1758

unknown's avatar
unknown committed
1759
  if (info.copied || info.deleted || info.updated)
unknown's avatar
unknown committed
1760
  {
unknown's avatar
unknown committed
1761
    query_cache_invalidate3(thd, table, 1);
unknown's avatar
unknown committed
1762 1763 1764
    if (!(table->file->has_transactions() || table->tmp_table))
      thd->options|=OPTION_STATUS_NO_TRANS_UPDATE;
  }
unknown's avatar
unknown committed
1765

1766 1767
  if (last_insert_id)
    thd->insert_id(last_insert_id);		// For binary log
1768
  /* Write to binlog before commiting transaction */
1769
  mysql_update_log.write(thd,thd->query,thd->query_length);
1770 1771
  if (mysql_bin_log.is_open())
  {
unknown's avatar
unknown committed
1772 1773
    if (!error)
      thd->clear_error();
1774
    Query_log_event qinfo(thd, thd->query, thd->query_length,
1775
			  table->file->has_transactions(), FALSE);
1776 1777
    mysql_bin_log.write(&qinfo);
  }
1778 1779 1780
  if ((error2=ha_autocommit_or_rollback(thd,error)) && ! error)
    error=error2;
  if (error)
unknown's avatar
unknown committed
1781 1782
  {
    table->file->print_error(error,MYF(0));
unknown's avatar
unknown committed
1783
    //TODO error should be sent at the query processing end
1784
    ::send_error(thd);
unknown's avatar
unknown committed
1785
    DBUG_RETURN(1);
unknown's avatar
unknown committed
1786
  }
unknown's avatar
unknown committed
1787
  char buff[160];
1788
  if (info.ignore)
unknown's avatar
unknown committed
1789 1790
    sprintf(buff, ER(ER_INSERT_INFO), (ulong) info.records,
	    (ulong) (info.records - info.copied), (ulong) thd->cuted_fields);
unknown's avatar
unknown committed
1791
  else
unknown's avatar
unknown committed
1792
    sprintf(buff, ER(ER_INSERT_INFO), (ulong) info.records,
unknown's avatar
unknown committed
1793
	    (ulong) (info.deleted+info.updated), (ulong) thd->cuted_fields);
unknown's avatar
unknown committed
1794
  ::send_ok(thd,info.copied+info.deleted+info.updated,last_insert_id,buff);
unknown's avatar
unknown committed
1795
  DBUG_RETURN(0);
unknown's avatar
unknown committed
1796 1797 1798 1799
}


/***************************************************************************
unknown's avatar
unknown committed
1800
  CREATE TABLE (SELECT) ...
unknown's avatar
unknown committed
1801 1802 1803
***************************************************************************/

int
1804
select_create::prepare(List<Item> &values, SELECT_LEX_UNIT *u)
unknown's avatar
unknown committed
1805 1806 1807
{
  DBUG_ENTER("select_create::prepare");

1808
  unit= u;
unknown's avatar
unknown committed
1809 1810
  table= create_table_from_items(thd, create_info, db, name,
				 extra_fields, keys, &values, &lock);
unknown's avatar
unknown committed
1811 1812 1813
  if (!table)
    DBUG_RETURN(-1);				// abort() deletes table

unknown's avatar
unknown committed
1814 1815 1816 1817 1818 1819 1820 1821
  if (table->fields < values.elements)
  {
    my_printf_error(ER_WRONG_VALUE_COUNT_ON_ROW,
                    ER(ER_WRONG_VALUE_COUNT_ON_ROW),
		    MYF(0),1);
    DBUG_RETURN(-1);
  }

unknown's avatar
unknown committed
1822 1823 1824
  /* First field to copy */
  field=table->field+table->fields - values.elements;

1825
  /* Don't set timestamp if used */
1826
  table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
unknown's avatar
unknown committed
1827

unknown's avatar
unknown committed
1828 1829
  table->next_number_field=table->found_next_number_field;

unknown's avatar
unknown committed
1830
  restore_record(table,default_values);			// Get empty record
unknown's avatar
unknown committed
1831
  thd->cuted_fields=0;
1832
  if (info.ignore ||
1833
      info.handle_duplicates != DUP_ERROR)
unknown's avatar
unknown committed
1834
    table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
1835
  table->file->start_bulk_insert((ha_rows) 0);
unknown's avatar
unknown committed
1836 1837 1838 1839
  DBUG_RETURN(0);
}


unknown's avatar
unknown committed
1840
void select_create::store_values(List<Item> &values)
unknown's avatar
unknown committed
1841
{
1842
  fill_record(field, values, 1);
unknown's avatar
unknown committed
1843 1844
}

unknown's avatar
unknown committed
1845

1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857
void select_create::send_error(uint errcode,const char *err)
{
  /*
   Disable binlog, because we "roll back" partial inserts in ::abort
   by removing the table, even for non-transactional tables.
  */
  tmp_disable_binlog(thd);
  select_insert::send_error(errcode, err);
  reenable_binlog(thd);
}


unknown's avatar
unknown committed
1858 1859 1860 1861 1862 1863 1864
bool select_create::send_eof()
{
  bool tmp=select_insert::send_eof();
  if (tmp)
    abort();
  else
  {
unknown's avatar
unknown committed
1865
    table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
unknown's avatar
unknown committed
1866 1867
    VOID(pthread_mutex_lock(&LOCK_open));
    mysql_unlock_tables(thd, lock);
1868 1869 1870 1871 1872
    /*
      TODO:
      Check if we can remove the following two rows.
      We should be able to just keep the table in the table cache.
    */
1873
    if (!table->tmp_table)
1874
    {
unknown's avatar
unknown committed
1875
      ulong version= table->version;
1876
      hash_delete(&open_cache,(byte*) table);
1877
      /* Tell threads waiting for refresh that something has happened */
unknown's avatar
unknown committed
1878
      if (version != refresh_version)
1879 1880
        VOID(pthread_cond_broadcast(&COND_refresh));
    }
unknown's avatar
unknown committed
1881
    lock=0;
unknown's avatar
unknown committed
1882
    table=0;
unknown's avatar
unknown committed
1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897
    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)
  {
unknown's avatar
unknown committed
1898
    table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
unknown's avatar
unknown committed
1899
    enum db_type table_type=table->db_type;
1900
    if (!table->tmp_table)
1901
    {
unknown's avatar
unknown committed
1902
      ulong version= table->version;
1903
      hash_delete(&open_cache,(byte*) table);
1904 1905
      if (!create_info->table_existed)
        quick_rm_table(table_type, db, name);
1906
      /* Tell threads waiting for refresh that something has happened */
unknown's avatar
unknown committed
1907
      if (version != refresh_version)
1908
        VOID(pthread_cond_broadcast(&COND_refresh));
1909 1910 1911
    }
    else if (!create_info->table_existed)
      close_temporary_table(thd, db, name);
unknown's avatar
unknown committed
1912 1913 1914 1915 1916 1917 1918
    table=0;
  }
  VOID(pthread_mutex_unlock(&LOCK_open));
}


/*****************************************************************************
unknown's avatar
unknown committed
1919
  Instansiate templates
unknown's avatar
unknown committed
1920 1921 1922
*****************************************************************************/

#ifdef __GNUC__
unknown's avatar
unknown committed
1923
template class List_iterator_fast<List_item>;
1924
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
1925 1926 1927
template class I_List<delayed_insert>;
template class I_List_iterator<delayed_insert>;
template class I_List<delayed_row>;
1928 1929
#endif /* EMBEDDED_LIBRARY */
#endif /* __GNUC__ */