sql_insert.cc 75.8 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
   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"
21 22
#include "sp_head.h"
#include "sql_trigger.h"
23
#include "sql_select.h"
unknown's avatar
unknown committed
24 25

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

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

46

unknown's avatar
unknown committed
47
/*
48
  Check if insert fields are correct.
49 50 51 52 53 54 55

  SYNOPSIS
    check_insert_fields()
    thd                         The current thread.
    table                       The table for insert.
    fields                      The insert fields.
    values                      The insert values.
unknown's avatar
unknown committed
56
    check_unique                If duplicate values should be rejected.
57 58 59 60 61 62 63 64 65

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

unknown's avatar
unknown committed
68 69 70
static int check_insert_fields(THD *thd, TABLE_LIST *table_list,
                               List<Item> &fields, List<Item> &values,
                               bool check_unique)
unknown's avatar
unknown committed
71
{
unknown's avatar
VIEW  
unknown committed
72
  TABLE *table= table_list->table;
73

74 75 76 77 78 79
  if (!table_list->updatable)
  {
    my_error(ER_NON_UPDATABLE_TABLE, MYF(0), table_list->alias, "INSERT");
    return -1;
  }

unknown's avatar
unknown committed
80 81
  if (fields.elements == 0 && values.elements != 0)
  {
82 83 84 85 86 87
    if (!table)
    {
      my_error(ER_VIEW_NO_INSERT_FIELD_LIST, MYF(0),
               table_list->view_db.str, table_list->view_name.str);
      return -1;
    }
88
    if (values.elements != table->s->fields)
unknown's avatar
unknown committed
89
    {
unknown's avatar
unknown committed
90
      my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), 1L);
unknown's avatar
unknown committed
91 92
      return -1;
    }
unknown's avatar
SCRUM:  
unknown committed
93
#ifndef NO_EMBEDDED_ACCESS_CHECKS
94
    if (grant_option)
unknown's avatar
VIEW  
unknown committed
95 96 97
    {
      Field_iterator_table fields;
      fields.set_table(table);
98
      if (check_grant_all_columns(thd, INSERT_ACL, &table->grant,
99
                                  table->s->db, table->s->table_name,
unknown's avatar
VIEW  
unknown committed
100 101 102
                                  &fields))
        return -1;
    }
unknown's avatar
SCRUM:  
unknown committed
103
#endif
104 105
    clear_timestamp_auto_bits(table->timestamp_field_type,
                              TIMESTAMP_AUTO_SET_ON_INSERT);
unknown's avatar
unknown committed
106 107 108
  }
  else
  {						// Part field list
unknown's avatar
unknown committed
109 110
    SELECT_LEX *select_lex= &thd->lex->select_lex;
    Name_resolution_context *context= &select_lex->context;
111
    Name_resolution_context_state ctx_state;
unknown's avatar
unknown committed
112
    int res;
unknown's avatar
unknown committed
113

unknown's avatar
unknown committed
114 115
    if (fields.elements != values.elements)
    {
unknown's avatar
unknown committed
116
      my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), 1L);
unknown's avatar
unknown committed
117 118 119 120
      return -1;
    }

    thd->dupp_field=0;
unknown's avatar
unknown committed
121 122 123
    select_lex->no_wrap_view_item= TRUE;

    /* Save the state of the current name resolution context. */
124
    ctx_state.save_state(context, table_list);
unknown's avatar
unknown committed
125 126 127 128 129

    /*
      Perform name resolution only in the first table - 'table_list',
      which is the table that is inserted into.
    */
130
    table_list->next_local= 0;
131 132
    context->resolve_in_table_list_only(table_list);
    res= setup_fields(thd, 0, fields, 1, 0, 0);
unknown's avatar
unknown committed
133 134

    /* Restore the current context. */
135
    ctx_state.restore_state(context, table_list);
136
    thd->lex->select_lex.no_wrap_view_item= FALSE;
unknown's avatar
unknown committed
137

unknown's avatar
unknown committed
138
    if (res)
unknown's avatar
unknown committed
139
      return -1;
unknown's avatar
unknown committed
140

unknown's avatar
unknown committed
141
    if (table_list->effective_algorithm == VIEW_ALGORITHM_MERGE)
142 143 144 145
    {
      /* it is join view => we need to find table for update */
      List_iterator_fast<Item> it(fields);
      Item *item;
unknown's avatar
unknown committed
146
      TABLE_LIST *tbl= 0;            // reset for call to check_single_table()
147
      table_map map= 0;
unknown's avatar
unknown committed
148 149

      while ((item= it++))
150
        map|= item->used_tables();
unknown's avatar
unknown committed
151
      if (table_list->check_single_table(&tbl, map, table_list) || tbl == 0)
152 153 154 155 156 157 158
      {
        my_error(ER_VIEW_MULTIUPDATE, MYF(0),
                 table_list->view_db.str, table_list->view_name.str);
        return -1;
      }
      table_list->table= table= tbl->table;
    }
159

unknown's avatar
VIEW  
unknown committed
160
    if (check_unique && thd->dupp_field)
unknown's avatar
unknown committed
161
    {
162
      my_error(ER_FIELD_SPECIFIED_TWICE, MYF(0), thd->dupp_field->field_name);
unknown's avatar
unknown committed
163 164 165
      return -1;
    }
    if (table->timestamp_field &&	// Don't set timestamp if used
166
	table->timestamp_field->query_id == thd->query_id)
167 168
      clear_timestamp_auto_bits(table->timestamp_field_type,
                                TIMESTAMP_AUTO_SET_ON_INSERT);
unknown's avatar
unknown committed
169
  }
unknown's avatar
unknown committed
170
  // For the values we need select_priv
unknown's avatar
SCRUM:  
unknown committed
171
#ifndef NO_EMBEDDED_ACCESS_CHECKS
172
  table->grant.want_privilege= (SELECT_ACL & ~table->grant.privilege);
unknown's avatar
SCRUM:  
unknown committed
173
#endif
174 175 176

  if (check_key_in_view(thd, table_list) ||
      (table_list->view &&
177
       check_view_insertability(thd, table_list)))
178 179 180 181 182
  {
    my_error(ER_NON_UPDATABLE_TABLE, MYF(0), table_list->alias, "INSERT");
    return -1;
  }

unknown's avatar
unknown committed
183 184 185 186
  return 0;
}


187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
/*
  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
*/

unknown's avatar
unknown committed
206
static int check_update_fields(THD *thd, TABLE_LIST *insert_table_list,
207 208
                               List<Item> &update_fields)
{
unknown's avatar
unknown committed
209
  TABLE *table= insert_table_list->table;
210
  query_id_t timestamp_query_id;
211 212 213 214 215 216 217 218 219
  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;
unknown's avatar
unknown committed
220
    table->timestamp_field->query_id= thd->query_id - 1;
221 222 223 224 225 226
  }

  /*
    Check the fields we are going to modify. This will set the query_id
    of all used fields to the threads query_id.
  */
227
  if (setup_fields(thd, 0, update_fields, 1, 0, 0))
228 229 230 231 232 233
    return -1;

  if (table->timestamp_field)
  {
    /* Don't set timestamp column if this is modified. */
    if (table->timestamp_field->query_id == thd->query_id)
234 235
      clear_timestamp_auto_bits(table->timestamp_field_type,
                                TIMESTAMP_AUTO_SET_ON_UPDATE);
236 237 238 239 240 241 242 243
    else
      table->timestamp_field->query_id= timestamp_query_id;
  }

  return 0;
}


unknown's avatar
unknown committed
244 245 246 247 248
bool mysql_insert(THD *thd,TABLE_LIST *table_list,
                  List<Item> &fields,
                  List<List_item> &values_list,
                  List<Item> &update_fields,
                  List<Item> &update_values,
249 250
                  enum_duplicates duplic,
		  bool ignore)
unknown's avatar
unknown committed
251
{
252
  int error, res;
253 254 255 256 257
  /*
    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).
  */
258 259
  bool log_on= (thd->options & OPTION_BIN_LOG) ||
    (!(thd->security_ctx->master_access & SUPER_ACL));
unknown's avatar
unknown committed
260
  bool transactional_table;
unknown's avatar
unknown committed
261 262 263 264
  uint value_count;
  ulong counter = 1;
  ulonglong id;
  COPY_INFO info;
265
  TABLE *table= 0;
unknown's avatar
unknown committed
266
  List_iterator_fast<List_item> its(values_list);
unknown's avatar
unknown committed
267
  List_item *values;
unknown's avatar
unknown committed
268
  Name_resolution_context *context;
269
  Name_resolution_context_state ctx_state;
unknown's avatar
unknown committed
270 271 272
#ifndef EMBEDDED_LIBRARY
  char *query= thd->query;
#endif
unknown's avatar
unknown committed
273
  thr_lock_type lock_type = table_list->lock_type;
unknown's avatar
unknown committed
274
  Item *unused_conds= 0;
unknown's avatar
unknown committed
275 276
  DBUG_ENTER("mysql_insert");

277 278 279 280 281
  /*
    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
   */
282 283 284 285
#ifdef EMBEDDED_LIBRARY
  if (lock_type == TL_WRITE_DELAYED)
    lock_type=TL_WRITE;
#else
unknown's avatar
unknown committed
286 287
  if ((lock_type == TL_WRITE_DELAYED &&
       ((specialflag & (SPECIAL_NO_NEW_FUNC | SPECIAL_SAFE_MODE)) ||
288
	thd->slave_thread || !thd->variables.max_insert_delayed_threads)) ||
289 290
      (lock_type == TL_WRITE_CONCURRENT_INSERT && duplic == DUP_REPLACE) ||
      (duplic == DUP_UPDATE))
unknown's avatar
unknown committed
291
    lock_type=TL_WRITE;
292
#endif
unknown's avatar
unknown committed
293
  table_list->lock_type= lock_type;
unknown's avatar
unknown committed
294

295
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
296 297 298 299 300 301
  if (lock_type == TL_WRITE_DELAYED)
  {
    if (thd->locked_tables)
    {
      if (find_locked_table(thd,
			    table_list->db ? table_list->db : thd->db,
302
			    table_list->table_name))
unknown's avatar
unknown committed
303
      {
304
	my_error(ER_DELAYED_INSERT_TABLE_LOCKED, MYF(0),
305
                 table_list->table_name);
unknown's avatar
unknown committed
306
	DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
307 308
      }
    }
309
    if ((table= delayed_get_table(thd,table_list)) && !thd->is_fatal_error)
310
    {
311 312 313 314 315
      /*
        Open tables used for sub-selects or in stored functions, will also
        cache these functions.
      */
      res= open_and_lock_tables(thd, table_list->next_global);
unknown's avatar
VIEW  
unknown committed
316 317 318 319 320 321
      /*
	First is not processed by open_and_lock_tables() => we need set
	updateability flags "by hands".
      */
      if (!table_list->derived && !table_list->view)
        table_list->updatable= 1;  // usual table
322
    }
unknown's avatar
unknown committed
323
    else
324
    {
325 326
      /* Too many delayed insert threads;  Use a normal insert */
      table_list->lock_type= lock_type= TL_WRITE;
unknown's avatar
unknown committed
327
      res= open_and_lock_tables(thd, table_list);
328
    }
unknown's avatar
unknown committed
329 330
  }
  else
331
#endif /* EMBEDDED_LIBRARY */
unknown's avatar
unknown committed
332
    res= open_and_lock_tables(thd, table_list);
333
  if (res || thd->is_fatal_error)
unknown's avatar
unknown committed
334
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
335

unknown's avatar
unknown committed
336
  thd->proc_info="init";
337
  thd->used_tables=0;
unknown's avatar
unknown committed
338
  values= its++;
unknown's avatar
unknown committed
339

unknown's avatar
unknown committed
340
  if (mysql_prepare_insert(thd, table_list, table, fields, values,
unknown's avatar
unknown committed
341 342
			   update_fields, update_values, duplic, &unused_conds,
                           FALSE))
unknown's avatar
unknown committed
343
    goto abort;
344

345 346 347
  /* mysql_prepare_insert set table_list->table if it was not set */
  table= table_list->table;

unknown's avatar
unknown committed
348 349
  context= &thd->lex->select_lex.context;
  /* Save the state of the current name resolution context. */
350
  ctx_state.save_state(context, table_list);
unknown's avatar
unknown committed
351 352 353 354 355

  /*
    Perform name resolution only in the first table - 'table_list',
    which is the table that is inserted into.
  */
356
  table_list->next_local= 0;
unknown's avatar
unknown committed
357 358
  context->resolve_in_table_list_only(table_list);

unknown's avatar
unknown committed
359
  value_count= values->elements;
unknown's avatar
unknown committed
360
  while ((values= its++))
unknown's avatar
unknown committed
361 362 363 364
  {
    counter++;
    if (values->elements != value_count)
    {
365
      my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), counter);
unknown's avatar
unknown committed
366 367
      goto abort;
    }
368
    if (setup_fields(thd, 0, *values, 0, 0, 0))
unknown's avatar
unknown committed
369 370 371
      goto abort;
  }
  its.rewind ();
unknown's avatar
unknown committed
372 373
 
  /* Restore the current context. */
374
  ctx_state.restore_state(context, table_list);
unknown's avatar
unknown committed
375

unknown's avatar
unknown committed
376
  /*
unknown's avatar
unknown committed
377
    Fill in the given fields and dump it to the table file
unknown's avatar
unknown committed
378
  */
unknown's avatar
unknown committed
379
  info.records= info.deleted= info.copied= info.updated= 0;
380
  info.ignore= ignore;
unknown's avatar
unknown committed
381
  info.handle_duplicates=duplic;
382 383
  info.update_fields= &update_fields;
  info.update_values= &update_values;
unknown's avatar
unknown committed
384
  info.view= (table_list->view ? table_list : 0);
385

386 387 388
  /*
    Count warnings for all inserts.
    For single line insert, generate an error if try to set a NOT NULL field
unknown's avatar
unknown committed
389
    to NULL.
390
  */
unknown's avatar
unknown committed
391
  thd->count_cuted_fields= ((values_list.elements == 1 &&
unknown's avatar
unknown committed
392
                             !ignore) ?
393 394
			    CHECK_FIELD_ERROR_FOR_NULL :
			    CHECK_FIELD_WARN);
unknown's avatar
unknown committed
395 396 397 398 399 400
  thd->cuted_fields = 0L;
  table->next_number_field=table->found_next_number_field;

  error=0;
  id=0;
  thd->proc_info="update";
unknown's avatar
unknown committed
401
  if (duplic != DUP_ERROR || ignore)
unknown's avatar
unknown committed
402
    table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
403 404 405 406 407 408 409 410 411
  /*
    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)
412
    table->file->start_bulk_insert(values_list.elements);
413

unknown's avatar
unknown committed
414
  thd->no_trans_update= 0;
unknown's avatar
unknown committed
415
  thd->abort_on_warning= (!ignore &&
unknown's avatar
unknown committed
416 417 418 419
                          (thd->variables.sql_mode &
                           (MODE_STRICT_TRANS_TABLES |
                            MODE_STRICT_ALL_TABLES)));

420
  if ((fields.elements || !value_count) &&
421
      check_that_all_fields_are_given_values(thd, table, table_list))
unknown's avatar
unknown committed
422 423 424 425 426
  {
    /* thd->net.report_error is now set, which will abort the next loop */
    error= 1;
  }

427 428 429 430
  if (table_list->prepare_where(thd, 0, TRUE) ||
      table_list->prepare_check_option(thd))
    error= 1;

unknown's avatar
unknown committed
431
  while ((values= its++))
unknown's avatar
unknown committed
432 433 434
  {
    if (fields.elements || !value_count)
    {
435
      restore_record(table,s->default_values);	// Get empty record
unknown's avatar
unknown committed
436 437 438
      if (fill_record_n_invoke_before_triggers(thd, fields, *values, 0,
                                               table->triggers,
                                               TRG_EVENT_INSERT))
unknown's avatar
unknown committed
439
      {
unknown's avatar
unknown committed
440
	if (values_list.elements != 1 && !thd->net.report_error)
unknown's avatar
unknown committed
441 442 443 444
	{
	  info.records++;
	  continue;
	}
unknown's avatar
unknown committed
445 446 447 448 449
	/*
	  TODO: set thd->abort_on_warning if values_list.elements == 1
	  and check that all items return warning in case of problem with
	  storing field.
        */
unknown's avatar
unknown committed
450 451 452 453 454 455
	error=1;
	break;
      }
    }
    else
    {
456
      if (thd->used_tables)			// Column used in values()
457
	restore_record(table,s->default_values);	// Get empty record
458
      else
unknown's avatar
unknown committed
459 460 461 462 463 464 465 466 467 468 469
      {
        /*
          Fix delete marker. No need to restore rest of record since it will
          be overwritten by fill_record() anyway (and fill_record() does not
          use default values in this case).
        */
	table->record[0][0]= table->s->default_values[0];
      }
      if (fill_record_n_invoke_before_triggers(thd, table->field, *values, 0,
                                               table->triggers,
                                               TRG_EVENT_INSERT))
unknown's avatar
unknown committed
470
      {
unknown's avatar
unknown committed
471
	if (values_list.elements != 1 && ! thd->net.report_error)
unknown's avatar
unknown committed
472 473 474 475 476 477 478 479
	{
	  info.records++;
	  continue;
	}
	error=1;
	break;
      }
    }
480

481 482 483
    if ((res= table_list->view_check_option(thd,
					    (values_list.elements == 1 ?
					     0 :
484
					     ignore))) ==
unknown's avatar
unknown committed
485 486 487
        VIEW_CHECK_SKIP)
      continue;
    else if (res == VIEW_CHECK_ERROR)
unknown's avatar
unknown committed
488
    {
unknown's avatar
unknown committed
489 490
      error= 1;
      break;
unknown's avatar
unknown committed
491
    }
492
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
493
    if (lock_type == TL_WRITE_DELAYED)
unknown's avatar
unknown committed
494
    {
495
      error=write_delayed(thd, table, duplic, ignore, query, thd->query_length, log_on);
unknown's avatar
unknown committed
496 497 498
      query=0;
    }
    else
499
#endif
unknown's avatar
unknown committed
500
      error=write_record(thd, table ,&info);
unknown's avatar
unknown committed
501 502 503 504 505 506 507 508 509 510
    /*
      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;
    }
511 512
    if (error)
      break;
513
    thd->row_count++;
unknown's avatar
unknown committed
514
  }
515 516 517 518 519

  /*
    Now all rows are inserted.  Time to update logs and sends response to
    user
  */
520
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
521 522
  if (lock_type == TL_WRITE_DELAYED)
  {
523 524 525 526 527 528
    if (!error)
    {
      id=0;					// No auto_increment id
      info.copied=values_list.elements;
      end_delayed_insert(thd);
    }
unknown's avatar
unknown committed
529
    query_cache_invalidate3(thd, table_list, 1);
unknown's avatar
unknown committed
530 531
  }
  else
532
#endif
unknown's avatar
unknown committed
533
  {
unknown's avatar
unknown committed
534
    if (table->file->end_bulk_insert() && !error)
535
    {
unknown's avatar
unknown committed
536 537
      table->file->print_error(my_errno,MYF(0));
      error=1;
538
    }
unknown's avatar
unknown committed
539 540
    if (id && values_list.elements != 1)
      thd->insert_id(id);			// For update log
541
    else if (table->next_number_field && info.copied)
unknown's avatar
unknown committed
542
      id=table->next_number_field->val_int();	// Return auto_increment value
unknown's avatar
unknown committed
543

unknown's avatar
unknown committed
544 545 546
    /*
      Invalidate the table in the query cache if something changed.
      For the transactional algorithm to work the invalidation must be
unknown's avatar
unknown committed
547
      before binlog writing and ha_autocommit_or_rollback
unknown's avatar
unknown committed
548
    */
unknown's avatar
unknown committed
549
    if (info.copied || info.deleted || info.updated)
unknown's avatar
unknown committed
550
    {
unknown's avatar
unknown committed
551
      query_cache_invalidate3(thd, table_list, 1);
unknown's avatar
unknown committed
552
    }
unknown's avatar
unknown committed
553

554
    transactional_table= table->file->has_transactions();
unknown's avatar
unknown committed
555

unknown's avatar
unknown committed
556
    if ((info.copied || info.deleted || info.updated) &&
unknown's avatar
unknown committed
557
	(error <= 0 || !transactional_table))
unknown's avatar
unknown committed
558
    {
559 560
      if (mysql_bin_log.is_open())
      {
unknown's avatar
unknown committed
561 562
        if (error <= 0)
          thd->clear_error();
563
	Query_log_event qinfo(thd, thd->query, thd->query_length,
unknown's avatar
unknown committed
564
			      transactional_table, FALSE);
565
	if (mysql_bin_log.write(&qinfo) && transactional_table)
566
	  error=1;
567
      }
unknown's avatar
unknown committed
568
      if (!transactional_table)
569
	thd->options|=OPTION_STATUS_NO_TRANS_UPDATE;
unknown's avatar
unknown committed
570
    }
571
    if (transactional_table)
572
      error=ha_autocommit_or_rollback(thd,error);
unknown's avatar
unknown committed
573

unknown's avatar
unknown committed
574 575 576 577 578 579 580 581
    if (thd->lock)
    {
      mysql_unlock_tables(thd, thd->lock);
      thd->lock=0;
    }
  }
  thd->proc_info="end";
  table->next_number_field=0;
582
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;
unknown's avatar
unknown committed
583
  thd->next_insert_id=0;			// Reset this if wrongly used
unknown's avatar
unknown committed
584
  if (duplic != DUP_ERROR || ignore)
unknown's avatar
unknown committed
585
    table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
586 587 588 589 590 591 592

  /* 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
593 594 595 596
  if (error)
    goto abort;
  if (values_list.elements == 1 && (!(thd->options & OPTION_WARNINGS) ||
				    !thd->cuted_fields))
597 598
  {
    thd->row_count_func= info.copied+info.deleted+info.updated;
599
    send_ok(thd, (ulong) thd->row_count_func, id);
600
  }
601 602
  else
  {
unknown's avatar
unknown committed
603
    char buff[160];
604
    if (ignore)
605 606 607
      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
608
    else
609
      sprintf(buff, ER(ER_INSERT_INFO), (ulong) info.records,
unknown's avatar
unknown committed
610
	      (ulong) (info.deleted+info.updated), (ulong) thd->cuted_fields);
611
    thd->row_count_func= info.copied+info.deleted+info.updated;
612
    ::send_ok(thd, (ulong) thd->row_count_func, id, buff);
unknown's avatar
unknown committed
613
  }
unknown's avatar
unknown committed
614
  free_underlaid_joins(thd, &thd->lex->select_lex);
615
  thd->abort_on_warning= 0;
unknown's avatar
unknown committed
616
  DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
617 618

abort:
619
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
620 621
  if (lock_type == TL_WRITE_DELAYED)
    end_delayed_insert(thd);
622
#endif
unknown's avatar
unknown committed
623
  free_underlaid_joins(thd, &thd->lex->select_lex);
unknown's avatar
unknown committed
624
  thd->abort_on_warning= 0;
unknown's avatar
unknown committed
625
  DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
626 627 628
}


unknown's avatar
VIEW  
unknown committed
629 630 631 632 633
/*
  Additional check for insertability for VIEW

  SYNOPSIS
    check_view_insertability()
634
    thd     - thread handler
unknown's avatar
VIEW  
unknown committed
635 636
    view    - reference on VIEW

637 638 639 640 641 642
  IMPLEMENTATION
    A view is insertable if the folloings are true:
    - All columns in the view are columns from a table
    - All not used columns in table have a default values
    - All field in view are unique (not referring to the same column)

unknown's avatar
VIEW  
unknown committed
643 644
  RETURN
    FALSE - OK
645 646 647
      view->contain_auto_increment is 1 if and only if the view contains an
      auto_increment field

unknown's avatar
VIEW  
unknown committed
648 649 650
    TRUE  - can't be used for insert
*/

651
static bool check_view_insertability(THD * thd, TABLE_LIST *view)
unknown's avatar
VIEW  
unknown committed
652
{
653
  uint num= view->view->select_lex.item_list.elements;
unknown's avatar
VIEW  
unknown committed
654
  TABLE *table= view->table;
655 656 657
  Field_translator *trans_start= view->field_translation,
		   *trans_end= trans_start + num;
  Field_translator *trans;
unknown's avatar
VIEW  
unknown committed
658
  Field **field_ptr= table->field;
659 660 661
  uint used_fields_buff_size= (table->s->fields + 7) / 8;
  uchar *used_fields_buff= (uchar*)thd->alloc(used_fields_buff_size);
  MY_BITMAP used_fields;
662 663
  DBUG_ENTER("check_key_in_view");

664 665 666
  if (!used_fields_buff)
    DBUG_RETURN(TRUE);  // EOM

unknown's avatar
VIEW  
unknown committed
667 668
  DBUG_ASSERT(view->table != 0 && view->field_translation != 0);

669 670 671
  bitmap_init(&used_fields, used_fields_buff, used_fields_buff_size * 8, 0);
  bitmap_clear_all(&used_fields);

unknown's avatar
VIEW  
unknown committed
672 673
  view->contain_auto_increment= 0;
  /* check simplicity and prepare unique test of view */
674
  for (trans= trans_start; trans != trans_end; trans++)
unknown's avatar
VIEW  
unknown committed
675
  {
676 677
    if (!trans->item->fixed && trans->item->fix_fields(thd, &trans->item))
      return TRUE;
678
    Item_field *field;
unknown's avatar
VIEW  
unknown committed
679
    /* simple SELECT list entry (field without expression) */
unknown's avatar
merge  
unknown committed
680
    if (!(field= trans->item->filed_for_view_update()))
unknown's avatar
VIEW  
unknown committed
681
      DBUG_RETURN(TRUE);
682
    if (field->field->unireg_check == Field::NEXT_NUMBER)
unknown's avatar
VIEW  
unknown committed
683 684
      view->contain_auto_increment= 1;
    /* prepare unique test */
unknown's avatar
unknown committed
685 686 687 688 689
    /*
      remove collation (or other transparent for update function) if we have
      it
    */
    trans->item= field;
unknown's avatar
VIEW  
unknown committed
690 691
  }
  /* unique test */
692
  for (trans= trans_start; trans != trans_end; trans++)
unknown's avatar
VIEW  
unknown committed
693
  {
694
    /* Thanks to test above, we know that all columns are of type Item_field */
695
    Item_field *field= (Item_field *)trans->item;
696 697 698
    /* check fields belong to table in which we are inserting */
    if (field->field->table == table &&
        bitmap_fast_test_and_set(&used_fields, field->field->field_index))
unknown's avatar
VIEW  
unknown committed
699 700 701 702 703 704 705
      DBUG_RETURN(TRUE);
  }

  DBUG_RETURN(FALSE);
}


unknown's avatar
unknown committed
706
/*
707
  Check if table can be updated
unknown's avatar
unknown committed
708 709

  SYNOPSIS
710 711
     mysql_prepare_insert_check_table()
     thd		Thread handle
unknown's avatar
unknown committed
712
     table_list		Table list
713 714
     fields		List of fields to be updated
     where		Pointer to where clause
unknown's avatar
unknown committed
715
     select_insert      Check is making for SELECT ... INSERT
716 717

   RETURN
unknown's avatar
unknown committed
718 719
     FALSE ok
     TRUE  ERROR
unknown's avatar
unknown committed
720
*/
721

unknown's avatar
unknown committed
722 723 724
static bool mysql_prepare_insert_check_table(THD *thd, TABLE_LIST *table_list,
                                             List<Item> &fields, COND **where,
                                             bool select_insert)
unknown's avatar
unknown committed
725
{
unknown's avatar
VIEW  
unknown committed
726
  bool insert_into_view= (table_list->view != 0);
727
  DBUG_ENTER("mysql_prepare_insert_check_table");
unknown's avatar
VIEW  
unknown committed
728

729
  if (setup_tables(thd, &thd->lex->select_lex.context,
unknown's avatar
unknown committed
730
                   &thd->lex->select_lex.top_join_list,
731
                   table_list, where, &thd->lex->select_lex.leaf_tables,
732
		   select_insert))
unknown's avatar
unknown committed
733
    DBUG_RETURN(TRUE);
unknown's avatar
VIEW  
unknown committed
734 735 736 737

  if (insert_into_view && !fields.elements)
  {
    thd->lex->empty_field_list_on_rset= 1;
738 739 740 741
    if (!table_list->table)
    {
      my_error(ER_VIEW_NO_INSERT_FIELD_LIST, MYF(0),
               table_list->view_db.str, table_list->view_name.str);
unknown's avatar
unknown committed
742
      DBUG_RETURN(TRUE);
743
    }
744
    DBUG_RETURN(insert_view_fields(thd, &fields, table_list));
unknown's avatar
VIEW  
unknown committed
745 746
  }

unknown's avatar
unknown committed
747
  DBUG_RETURN(FALSE);
748 749 750 751 752 753 754 755 756 757
}


/*
  Prepare items in INSERT statement

  SYNOPSIS
    mysql_prepare_insert()
    thd			Thread handler
    table_list	        Global/local table list
unknown's avatar
unknown committed
758 759
    table		Table to insert into (can be NULL if table should
			be taken from table_list->table)    
unknown's avatar
unknown committed
760 761
    where		Where clause (for insert ... select)
    select_insert	TRUE if INSERT ... SELECT statement
762

unknown's avatar
unknown committed
763 764 765 766 767
  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
768

769 770 771
  WARNING
    You MUST set table->insert_values to 0 after calling this function
    before releasing the table object.
unknown's avatar
unknown committed
772
  
773
  RETURN VALUE
unknown's avatar
unknown committed
774 775
    FALSE OK
    TRUE  error
776 777
*/

unknown's avatar
unknown committed
778
bool mysql_prepare_insert(THD *thd, TABLE_LIST *table_list,
unknown's avatar
unknown committed
779
                          TABLE *table, List<Item> &fields, List_item *values,
unknown's avatar
unknown committed
780
                          List<Item> &update_fields, List<Item> &update_values,
unknown's avatar
unknown committed
781 782
                          enum_duplicates duplic,
                          COND **where, bool select_insert)
783
{
unknown's avatar
unknown committed
784
  SELECT_LEX *select_lex= &thd->lex->select_lex;
unknown's avatar
unknown committed
785
  Name_resolution_context *context= &select_lex->context;
786
  Name_resolution_context_state ctx_state;
787
  bool insert_into_view= (table_list->view != 0);
unknown's avatar
unknown committed
788
  bool res= 0;
789
  DBUG_ENTER("mysql_prepare_insert");
unknown's avatar
unknown committed
790 791 792
  DBUG_PRINT("enter", ("table_list 0x%lx, table 0x%lx, view %d",
		       (ulong)table_list, (ulong)table,
		       (int)insert_into_view));
unknown's avatar
unknown committed
793

794 795 796 797 798 799 800
  /*
    For subqueries in VALUES() we should not see the table in which we are
    inserting (for INSERT ... SELECT this is done by changing table_list,
    because INSERT ... SELECT share SELECT_LEX it with SELECT.
  */
  if (!select_insert)
  {
unknown's avatar
unknown committed
801
    for (SELECT_LEX_UNIT *un= select_lex->first_inner_unit();
802 803 804 805 806 807 808 809 810 811 812 813
         un;
         un= un->next_unit())
    {
      for (SELECT_LEX *sl= un->first_select();
           sl;
           sl= sl->next_select())
      {
        sl->context.outer_context= 0;
      }
    }
  }

unknown's avatar
unknown committed
814
  if (duplic == DUP_UPDATE)
unknown's avatar
unknown committed
815 816
  {
    /* it should be allocated before Item::fix_fields() */
unknown's avatar
unknown committed
817
    if (table_list->set_insert_values(thd->mem_root))
unknown's avatar
unknown committed
818
      DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
819
  }
unknown's avatar
unknown committed
820

unknown's avatar
unknown committed
821 822
  if (mysql_prepare_insert_check_table(thd, table_list, fields, where,
                                       select_insert))
unknown's avatar
unknown committed
823
    DBUG_RETURN(TRUE);
unknown's avatar
VIEW  
unknown committed
824

unknown's avatar
unknown committed
825
  /* Save the state of the current name resolution context. */
826
  ctx_state.save_state(context, table_list);
unknown's avatar
unknown committed
827

unknown's avatar
unknown committed
828 829 830 831
  /*
    Perform name resolution only in the first table - 'table_list',
    which is the table that is inserted into.
  */
unknown's avatar
unknown committed
832
  table_list->next_local= 0;
unknown's avatar
unknown committed
833 834 835
  context->resolve_in_table_list_only(table_list);

  /* Prepare the fields in the statement. */
836
  if (values &&
837 838 839
      !(res= check_insert_fields(thd, context->table_list, fields, *values,
                                 !insert_into_view) ||
        setup_fields(thd, 0, *values, 0, 0, 0)) &&
840
      duplic == DUP_UPDATE)
unknown's avatar
unknown committed
841
  {
unknown's avatar
unknown committed
842
    select_lex->no_wrap_view_item= TRUE;
unknown's avatar
unknown committed
843
    res= check_update_fields(thd, context->table_list, update_fields);
unknown's avatar
unknown committed
844
    select_lex->no_wrap_view_item= FALSE;
845 846 847 848
    /*
      When we are not using GROUP BY we can refer to other tables in the
      ON DUPLICATE KEY part.
    */       
unknown's avatar
unknown committed
849 850
    if (select_lex->group_list.elements == 0)
    {
851
      context->table_list->next_local=       ctx_state.save_next_local;
852
      /* first_name_resolution_table was set by resolve_in_table_list_only() */
unknown's avatar
unknown committed
853
      context->first_name_resolution_table->
854
        next_name_resolution_table=          ctx_state.save_next_local;
unknown's avatar
unknown committed
855 856 857
    }
    if (!res)
      res= setup_fields(thd, 0, update_values, 1, 0, 0);
unknown's avatar
unknown committed
858
  }
unknown's avatar
unknown committed
859 860

  /* Restore the current context. */
861
  ctx_state.restore_state(context, table_list);
unknown's avatar
unknown committed
862

unknown's avatar
unknown committed
863 864 865
  if (res)
    DBUG_RETURN(res);

unknown's avatar
unknown committed
866 867 868
  if (!table)
    table= table_list->table;

869
  if (!select_insert)
unknown's avatar
unknown committed
870
  {
871
    Item *fake_conds= 0;
872 873
    TABLE_LIST *duplicate;
    if ((duplicate= unique_table(table_list, table_list->next_global)))
874
    {
875
      update_non_unique_table_error(table_list, "INSERT", duplicate);
876 877
      DBUG_RETURN(TRUE);
    }
unknown's avatar
unknown committed
878 879
    select_lex->fix_prepare_information(thd, &fake_conds);
    select_lex->first_execution= 0;
unknown's avatar
unknown committed
880
  }
881 882
  if (duplic == DUP_UPDATE || duplic == DUP_REPLACE)
    table->file->extra(HA_EXTRA_RETRIEVE_PRIMARY_KEY);
unknown's avatar
unknown committed
883
  DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
884 885 886
}


unknown's avatar
unknown committed
887 888 889 890
	/* Check if there is more uniq keys after field */

static int last_uniq_key(TABLE *table,uint keynr)
{
891
  while (++keynr < table->s->keys)
unknown's avatar
unknown committed
892 893 894 895 896 897 898
    if (table->key_info[keynr].flags & HA_NOSAME)
      return 0;
  return 1;
}


/*
unknown's avatar
unknown committed
899 900 901 902 903 904 905 906 907 908
  Write a record to table with optional deleting of conflicting records,
  invoke proper triggers if needed.

  SYNOPSIS
     write_record()
      thd   - thread context
      table - table to which record should be written
      info  - COPY_INFO structure describing handling of duplicates
              and which is used for counting number of records inserted
              and deleted.
unknown's avatar
unknown committed
909

unknown's avatar
unknown committed
910 911 912 913 914
  NOTE
    Once this record will be written to table after insert trigger will
    be invoked. If instead of inserting new record we will update old one
    then both on update triggers will work instead. Similarly both on
    delete triggers will be invoked if we will delete conflicting records.
unknown's avatar
unknown committed
915

unknown's avatar
unknown committed
916 917 918 919 920 921
    Sets thd->no_trans_update if table which is updated didn't have
    transactions.

  RETURN VALUE
    0     - success
    non-0 - error
unknown's avatar
unknown committed
922 923 924
*/


unknown's avatar
unknown committed
925
int write_record(THD *thd, TABLE *table,COPY_INFO *info)
unknown's avatar
unknown committed
926
{
unknown's avatar
unknown committed
927
  int error, trg_error= 0;
unknown's avatar
unknown committed
928
  char *key=0;
929
  DBUG_ENTER("write_record");
unknown's avatar
unknown committed
930

unknown's avatar
unknown committed
931
  info->records++;
932 933
  if (info->handle_duplicates == DUP_REPLACE ||
      info->handle_duplicates == DUP_UPDATE)
unknown's avatar
unknown committed
934 935 936
  {
    while ((error=table->file->write_row(table->record[0])))
    {
937
      uint key_nr;
unknown's avatar
unknown committed
938
      if (error != HA_WRITE_SKIP)
unknown's avatar
unknown committed
939
	goto err;
940
      table->file->restore_auto_increment();
unknown's avatar
unknown committed
941 942
      if ((int) (key_nr = table->file->get_dup_key(error)) < 0)
      {
unknown's avatar
unknown committed
943
	error=HA_WRITE_SKIP;			/* Database can't find key */
unknown's avatar
unknown committed
944 945
	goto err;
      }
946 947 948 949 950
      /*
	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.
      */
951 952
      if (info->handle_duplicates == DUP_REPLACE &&
          table->next_number_field &&
953
          key_nr == table->s->next_number_index &&
954 955
	  table->file->auto_increment_column_changed)
	goto err;
unknown's avatar
unknown committed
956
      if (table->file->table_flags() & HA_DUPP_POS)
unknown's avatar
unknown committed
957 958 959 960 961 962
      {
	if (table->file->rnd_pos(table->record[1],table->file->dupp_ref))
	  goto err;
      }
      else
      {
963
	if (table->file->extra(HA_EXTRA_FLUSH_CACHE)) /* Not needed with NISAM */
unknown's avatar
unknown committed
964 965 966 967
	{
	  error=my_errno;
	  goto err;
	}
unknown's avatar
unknown committed
968

unknown's avatar
unknown committed
969 970
	if (!key)
	{
971
	  if (!(key=(char*) my_safe_alloca(table->s->max_unique_length,
unknown's avatar
unknown committed
972 973 974 975 976 977
					   MAX_KEY_LENGTH)))
	  {
	    error=ENOMEM;
	    goto err;
	  }
	}
978
	key_copy((byte*) key,table->record[0],table->key_info+key_nr,0);
unknown's avatar
unknown committed
979
	if ((error=(table->file->index_read_idx(table->record[1],key_nr,
980
						(byte*) key,
unknown's avatar
unknown committed
981 982
						table->key_info[key_nr].
						key_length,
unknown's avatar
unknown committed
983 984 985
						HA_READ_KEY_EXACT))))
	  goto err;
      }
986
      if (info->handle_duplicates == DUP_UPDATE)
unknown's avatar
unknown committed
987
      {
unknown's avatar
unknown committed
988
        int res= 0;
unknown's avatar
unknown committed
989 990 991 992
        /*
          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
993
        */
unknown's avatar
unknown committed
994
	DBUG_ASSERT(table->insert_values != NULL);
unknown's avatar
unknown committed
995 996
        store_record(table,insert_values);
        restore_record(table,record[1]);
unknown's avatar
unknown committed
997 998
        DBUG_ASSERT(info->update_fields->elements ==
                    info->update_values->elements);
unknown's avatar
unknown committed
999 1000 1001 1002 1003
        if (fill_record_n_invoke_before_triggers(thd, *info->update_fields,
                                                 *info->update_values, 0,
                                                 table->triggers,
                                                 TRG_EVENT_UPDATE))
          goto before_trg_err;
1004 1005

        /* CHECK OPTION for VIEW ... ON DUPLICATE KEY UPDATE ... */
unknown's avatar
unknown committed
1006 1007 1008
        if (info->view &&
            (res= info->view->view_check_option(current_thd, info->ignore)) ==
            VIEW_CHECK_SKIP)
unknown's avatar
unknown committed
1009
          goto ok_or_after_trg_err;
unknown's avatar
unknown committed
1010
        if (res == VIEW_CHECK_ERROR)
unknown's avatar
unknown committed
1011
          goto before_trg_err;
1012

1013 1014 1015 1016 1017 1018
        if (thd->clear_next_insert_id)
        {
          /* Reset auto-increment cacheing if we do an update */
          thd->clear_next_insert_id= 0;
          thd->next_insert_id= 0;
        }
1019
        if ((error=table->file->update_row(table->record[1],table->record[0])))
1020 1021
	{
	  if ((error == HA_ERR_FOUND_DUPP_KEY) && info->ignore)
unknown's avatar
unknown committed
1022
            goto ok_or_after_trg_err;
1023
          goto err;
1024
	}
unknown's avatar
unknown committed
1025
        info->updated++;
unknown's avatar
unknown committed
1026 1027 1028 1029 1030 1031

        trg_error= (table->triggers &&
                    table->triggers->process_triggers(thd, TRG_EVENT_UPDATE,
                                                      TRG_ACTION_AFTER, TRUE));
        info->copied++;
        goto ok_or_after_trg_err;
1032 1033 1034
      }
      else /* DUP_REPLACE */
      {
unknown's avatar
unknown committed
1035 1036 1037 1038 1039
	/*
	  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.
1040 1041
          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
1042 1043
	*/
	if (last_uniq_key(table,key_nr) &&
1044
	    !table->file->referenced_by_foreign_key() &&
1045 1046
            (table->timestamp_field_type == TIMESTAMP_NO_AUTO_SET ||
             table->timestamp_field_type == TIMESTAMP_AUTO_SET_ON_BOTH))
1047
        {
unknown's avatar
unknown committed
1048 1049 1050 1051
          if (table->triggers &&
              table->triggers->process_triggers(thd, TRG_EVENT_UPDATE,
                                                TRG_ACTION_BEFORE, TRUE))
            goto before_trg_err;
1052 1053 1054 1055 1056 1057
          if (thd->clear_next_insert_id)
          {
            /* Reset auto-increment cacheing if we do an update */
            thd->clear_next_insert_id= 0;
            thd->next_insert_id= 0;
          }
unknown's avatar
unknown committed
1058 1059
          if ((error=table->file->update_row(table->record[1],
					     table->record[0])))
1060 1061
            goto err;
          info->deleted++;
unknown's avatar
unknown committed
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
          trg_error= (table->triggers &&
                      table->triggers->process_triggers(thd, TRG_EVENT_UPDATE,
                                                        TRG_ACTION_AFTER,
                                                        TRUE));
          /* Update logfile and count */
          info->copied++;
          goto ok_or_after_trg_err;
        }
        else
        {
          if (table->triggers &&
              table->triggers->process_triggers(thd, TRG_EVENT_DELETE,
                                                TRG_ACTION_BEFORE, TRUE))
            goto before_trg_err;
          if ((error=table->file->delete_row(table->record[1])))
            goto err;
          info->deleted++;
          if (!table->file->has_transactions())
            thd->no_trans_update= 1;
          if (table->triggers &&
              table->triggers->process_triggers(thd, TRG_EVENT_DELETE,
                                                TRG_ACTION_AFTER, TRUE))
          {
            trg_error= 1;
            goto ok_or_after_trg_err;
          }
          /* Let us attempt do write_row() once more */
1089
        }
unknown's avatar
unknown committed
1090 1091 1092
      }
    }
    info->copied++;
unknown's avatar
unknown committed
1093 1094 1095
    trg_error= (table->triggers &&
                table->triggers->process_triggers(thd, TRG_EVENT_INSERT,
                                                  TRG_ACTION_AFTER, TRUE));
unknown's avatar
unknown committed
1096 1097 1098
  }
  else if ((error=table->file->write_row(table->record[0])))
  {
1099
    if (!info->ignore ||
unknown's avatar
unknown committed
1100 1101
	(error != HA_ERR_FOUND_DUPP_KEY && error != HA_ERR_FOUND_DUPP_UNIQUE))
      goto err;
1102
    table->file->restore_auto_increment();
unknown's avatar
unknown committed
1103 1104
  }
  else
unknown's avatar
unknown committed
1105
  {
unknown's avatar
unknown committed
1106
    info->copied++;
unknown's avatar
unknown committed
1107 1108 1109 1110 1111 1112
    trg_error= (table->triggers &&
                table->triggers->process_triggers(thd, TRG_EVENT_INSERT,
                                                  TRG_ACTION_AFTER, TRUE));
  }

ok_or_after_trg_err:
unknown's avatar
unknown committed
1113
  if (key)
1114
    my_safe_afree(key,table->s->max_unique_length,MAX_KEY_LENGTH);
unknown's avatar
unknown committed
1115 1116
  if (!table->file->has_transactions())
    thd->no_trans_update= 1;
unknown's avatar
unknown committed
1117
  DBUG_RETURN(trg_error);
unknown's avatar
unknown committed
1118 1119

err:
1120
  info->last_errno= error;
1121 1122 1123
  /* current_select is NULL if this is a delayed insert */
  if (thd->lex->current_select)
    thd->lex->current_select->no_error= 0;        // Give error
unknown's avatar
unknown committed
1124
  table->file->print_error(error,MYF(0));
unknown's avatar
unknown committed
1125 1126 1127 1128

before_trg_err:
  if (key)
    my_safe_afree(key, table->s->max_unique_length, MAX_KEY_LENGTH);
1129
  DBUG_RETURN(1);
unknown's avatar
unknown committed
1130 1131 1132 1133
}


/******************************************************************************
unknown's avatar
unknown committed
1134
  Check that all fields with arn't null_fields are used
unknown's avatar
unknown committed
1135 1136
******************************************************************************/

1137 1138
int check_that_all_fields_are_given_values(THD *thd, TABLE *entry,
                                           TABLE_LIST *table_list)
unknown's avatar
unknown committed
1139
{
1140
  int err= 0;
unknown's avatar
unknown committed
1141 1142
  for (Field **field=entry->field ; *field ; field++)
  {
unknown's avatar
unknown committed
1143
    if ((*field)->query_id != thd->query_id &&
1144 1145
        ((*field)->flags & NO_DEFAULT_VALUE_FLAG) &&
        ((*field)->real_type() != FIELD_TYPE_ENUM))
unknown's avatar
unknown committed
1146
    {
1147 1148 1149
      bool view= FALSE;
      if (table_list)
      {
unknown's avatar
unknown committed
1150
        table_list= table_list->top_table();
unknown's avatar
unknown committed
1151
        view= test(table_list->view);
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
      }
      if (view)
      {
        push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                            ER_NO_DEFAULT_FOR_VIEW_FIELD,
                            ER(ER_NO_DEFAULT_FOR_VIEW_FIELD),
                            table_list->view_db.str,
                            table_list->view_name.str);
      }
      else
      {
        push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                            ER_NO_DEFAULT_FOR_FIELD,
                            ER(ER_NO_DEFAULT_FOR_FIELD),
                            (*field)->field_name);
      }
1168
      err= 1;
unknown's avatar
unknown committed
1169 1170
    }
  }
1171
  return thd->abort_on_warning ? err : 0;
unknown's avatar
unknown committed
1172 1173 1174
}

/*****************************************************************************
unknown's avatar
unknown committed
1175 1176
  Handling of delayed inserts
  A thread is created for each table that one uses with the DELAYED attribute.
unknown's avatar
unknown committed
1177 1178
*****************************************************************************/

1179 1180
#ifndef EMBEDDED_LIBRARY

unknown's avatar
unknown committed
1181 1182 1183 1184 1185
class delayed_row :public ilink {
public:
  char *record,*query;
  enum_duplicates dup;
  time_t start_time;
1186
  bool query_start_used,last_insert_id_used,insert_id_used, ignore, log_query;
unknown's avatar
unknown committed
1187
  ulonglong last_insert_id;
1188
  timestamp_auto_set_type timestamp_field_type;
unknown's avatar
unknown committed
1189 1190
  uint query_length;

1191 1192
  delayed_row(enum_duplicates dup_arg, bool ignore_arg, bool log_query_arg)
    :record(0), query(0), dup(dup_arg), ignore(ignore_arg), log_query(log_query_arg) {}
unknown's avatar
unknown committed
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
  ~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;
1211
  ulong group_count;
unknown's avatar
unknown committed
1212
  TABLE_LIST table_list;			// Argument
unknown's avatar
unknown committed
1213 1214 1215 1216 1217 1218

  delayed_insert()
    :locks_in_memory(0),
     table(0),tables_in_use(0),stacked_inserts(0), status(0), dead(0),
     group_count(0)
  {
1219 1220
    thd.security_ctx->user=thd.security_ctx->priv_user=(char*) delayed_user;
    thd.security_ctx->host=(char*) my_localhost;
unknown's avatar
unknown committed
1221 1222 1223
    thd.current_tablenr=0;
    thd.version=refresh_version;
    thd.command=COM_DELAYED_INSERT;
1224 1225
    thd.lex->current_select= 0; 		// for my_message_sql
    thd.lex->sql_command= SQLCOM_INSERT;        // For innodb::store_lock()
unknown's avatar
unknown committed
1226

1227 1228
    bzero((char*) &thd.net, sizeof(thd.net));		// Safety
    bzero((char*) &table_list, sizeof(table_list));	// Safety
1229
    thd.system_thread= SYSTEM_THREAD_DELAYED_INSERT;
1230
    thd.security_ctx->host_or_ip= "";
unknown's avatar
unknown committed
1231
    bzero((char*) &info,sizeof(info));
1232
    pthread_mutex_init(&mutex,MY_MUTEX_INIT_FAST);
unknown's avatar
unknown committed
1233 1234 1235 1236 1237 1238 1239 1240
    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()
  {
1241
    /* The following is not really needed, but just for safety */
unknown's avatar
unknown committed
1242 1243 1244 1245 1246 1247
    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
1248 1249 1250
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);
    pthread_cond_destroy(&cond_client);
unknown's avatar
unknown committed
1251 1252
    thd.unlink();				// Must be unlinked under lock
    x_free(thd.query);
1253
    thd.security_ctx->user= thd.security_ctx->host=0;
unknown's avatar
unknown committed
1254 1255 1256
    thread_count--;
    delayed_insert_threads--;
    VOID(pthread_mutex_unlock(&LOCK_thread_count));
1257
    VOID(pthread_cond_broadcast(&COND_thread_count)); /* Tell main we are ready */
unknown's avatar
unknown committed
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
  }

  /* 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) &&
1299
	!strcmp(table_list->table_name,tmp->table->s->table_name))
unknown's avatar
unknown committed
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
    {
      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;
1314
  TABLE *table;
unknown's avatar
unknown committed
1315 1316 1317 1318 1319
  DBUG_ENTER("delayed_get_table");

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

1320
  /* Find the thread which handles this table. */
unknown's avatar
unknown committed
1321 1322
  if (!(tmp=find_handler(thd,table_list)))
  {
1323 1324 1325 1326
    /*
      No match. Create a new thread to handle the table, but
      no more than max_insert_delayed_threads.
    */
1327
    if (delayed_insert_threads >= thd->variables.max_insert_delayed_threads)
1328
      DBUG_RETURN(0);
unknown's avatar
unknown committed
1329 1330
    thd->proc_info="Creating delayed handler";
    pthread_mutex_lock(&LOCK_delayed_create);
1331 1332 1333 1334 1335
    /*
      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
1336
    {
1337 1338 1339 1340
      /*
        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
1341 1342 1343 1344 1345
        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().
1346
      */
1347
      if (wait_if_global_read_lock(thd, 0, 1))
1348
        goto err;
unknown's avatar
unknown committed
1349 1350 1351
      if (!(tmp=new delayed_insert()))
      {
	my_error(ER_OUTOFMEMORY,MYF(0),sizeof(delayed_insert));
1352
	goto err1;
unknown's avatar
unknown committed
1353
      }
unknown's avatar
unknown committed
1354 1355 1356
      pthread_mutex_lock(&LOCK_thread_count);
      thread_count++;
      pthread_mutex_unlock(&LOCK_thread_count);
unknown's avatar
unknown committed
1357
      if (!(tmp->thd.db=my_strdup(table_list->db,MYF(MY_WME))) ||
1358
	  !(tmp->thd.query=my_strdup(table_list->table_name,MYF(MY_WME))))
unknown's avatar
unknown committed
1359 1360
      {
	delete tmp;
unknown's avatar
unknown committed
1361
	my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES), MYF(0));
1362
	goto err1;
unknown's avatar
unknown committed
1363
      }
unknown's avatar
unknown committed
1364 1365
      tmp->table_list= *table_list;			// Needed to open table
      tmp->table_list.db= tmp->thd.db;
1366
      tmp->table_list.alias= tmp->table_list.table_name= tmp->thd.query;
unknown's avatar
unknown committed
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
      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;
unknown's avatar
unknown committed
1378
	my_error(ER_CANT_CREATE_THREAD, MYF(0), error);
1379
	goto err1;
unknown's avatar
unknown committed
1380 1381 1382 1383 1384 1385 1386 1387 1388
      }

      /* 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);
1389 1390 1391 1392 1393
      /*
        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
1394 1395 1396
      thd->proc_info="got old table";
      if (tmp->thd.killed)
      {
1397
	if (tmp->thd.is_fatal_error)
unknown's avatar
unknown committed
1398 1399
	{
	  /* Copy error message and abort */
1400
	  thd->fatal_error();
unknown's avatar
unknown committed
1401
	  strmov(thd->net.last_error,tmp->thd.net.last_error);
1402
	  thd->net.last_errno=tmp->thd.net.last_errno;
unknown's avatar
unknown committed
1403 1404
	}
	tmp->unlock();
1405
	goto err;
unknown's avatar
unknown committed
1406 1407 1408 1409
      }
      if (thd->killed)
      {
	tmp->unlock();
1410
	goto err;
unknown's avatar
unknown committed
1411 1412 1413 1414 1415 1416
      }
    }
    pthread_mutex_unlock(&LOCK_delayed_create);
  }

  pthread_mutex_lock(&tmp->mutex);
1417
  table= tmp->get_local_table(thd);
unknown's avatar
unknown committed
1418 1419 1420
  pthread_mutex_unlock(&tmp->mutex);
  if (table)
    thd->di=tmp;
1421 1422
  else if (tmp->thd.is_fatal_error)
    thd->fatal_error();
1423 1424
  /* Unlock the delayed insert object after its last access. */
  tmp->unlock();
unknown's avatar
unknown committed
1425
  DBUG_RETURN((table_list->table=table));
1426 1427 1428

 err1:
  thd->fatal_error();
1429 1430 1431 1432 1433
  /*
    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);
1434 1435 1436
 err:
  pthread_mutex_unlock(&LOCK_delayed_create);
  DBUG_RETURN(0); // Continue with normal insert
unknown's avatar
unknown committed
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449
}


/*
  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;
1450
  Field **field,**org_field, *found_next_number_field;
unknown's avatar
unknown committed
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
  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
1476
  copy= (TABLE*) client_thd->alloc(sizeof(*copy)+
1477 1478
				   (table->s->fields+1)*sizeof(Field**)+
				   table->s->reclength);
unknown's avatar
unknown committed
1479 1480 1481
  if (!copy)
    goto error;
  *copy= *table;
1482 1483 1484
  copy->s= &copy->share_not_to_be_used;
  // No name hashing
  bzero((char*) &copy->s->name_hash,sizeof(copy->s->name_hash));
unknown's avatar
unknown committed
1485 1486 1487
  /* We don't need to change the file handler here */

  field=copy->field=(Field**) (copy+1);
1488 1489
  copy->record[0]=(byte*) (field+table->s->fields+1);
  memcpy((char*) copy->record[0],(char*) table->record[0],table->s->reclength);
unknown's avatar
unknown committed
1490 1491 1492 1493 1494

  /* Make a copy of all fields */

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

1495
  found_next_number_field=table->found_next_number_field;
unknown's avatar
unknown committed
1496 1497
  for (org_field=table->field ; *org_field ; org_field++,field++)
  {
unknown's avatar
unknown committed
1498
    if (!(*field= (*org_field)->new_field(client_thd->mem_root,copy)))
unknown's avatar
unknown committed
1499
      return 0;
1500
    (*field)->orig_table= copy;			// Remove connection
unknown's avatar
unknown committed
1501
    (*field)->move_field(adjust_ptrs);		// Point at copy->record[0]
1502 1503
    if (*org_field == found_next_number_field)
      (*field)->table->found_next_number_field= *field;
unknown's avatar
unknown committed
1504 1505 1506 1507 1508 1509 1510 1511
  }
  *field=0;

  /* Adjust timestamp */
  if (table->timestamp_field)
  {
    /* Restore offset as this may have been reset in handle_inserts */
    copy->timestamp_field=
1512
      (Field_timestamp*) copy->field[table->s->timestamp_field_offset];
1513
    copy->timestamp_field->unireg_check= table->timestamp_field->unireg_check;
1514
    copy->timestamp_field_type= copy->timestamp_field->get_auto_set_type();
unknown's avatar
unknown committed
1515 1516 1517 1518
  }

  /* _rowid is not used with delayed insert */
  copy->rowid_field=0;
1519 1520 1521 1522

  /* Adjust in_use for pointing to client thread */
  copy->in_use= client_thd;
  
unknown's avatar
unknown committed
1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535
  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 */

1536
static int write_delayed(THD *thd,TABLE *table,enum_duplicates duplic, bool ignore,
1537
			 char *query, uint query_length, bool log_on)
unknown's avatar
unknown committed
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548
{
  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";

1549
  if (thd->killed || !(row= new delayed_row(duplic, ignore, log_on)))
unknown's avatar
unknown committed
1550 1551 1552 1553
    goto err;

  if (!query)
    query_length=0;
1554
  if (!(row->record= (char*) my_malloc(table->s->reclength+query_length+1,
unknown's avatar
unknown committed
1555 1556
				       MYF(MY_WME))))
    goto err;
1557
  memcpy(row->record, table->record[0], table->s->reclength);
unknown's avatar
unknown committed
1558 1559
  if (query_length)
  {
1560
    row->query= row->record+table->s->reclength;
unknown's avatar
unknown committed
1561 1562 1563 1564 1565 1566 1567 1568
    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;
1569
  row->timestamp_field_type=    table->timestamp_field_type;
unknown's avatar
unknown committed
1570 1571 1572 1573

  di->rows.push_back(row);
  di->stacked_inserts++;
  di->status=1;
1574
  if (table->s->blob_fields)
unknown's avatar
unknown committed
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590
    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)
{
1591
  DBUG_ENTER("end_delayed_insert");
unknown's avatar
unknown committed
1592 1593
  delayed_insert *di=thd->di;
  pthread_mutex_lock(&di->mutex);
1594
  DBUG_PRINT("info",("tables in use: %d",di->tables_in_use));
unknown's avatar
unknown committed
1595 1596 1597 1598 1599 1600
  if (!--di->tables_in_use || di->thd.killed)
  {						// Unlock table
    di->status=1;
    pthread_cond_signal(&di->cond);
  }
  pthread_mutex_unlock(&di->mutex);
1601
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614
}


/* 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++))
  {
unknown's avatar
unknown committed
1615
    /* Ensure that the thread doesn't kill itself while we are looking at it */
unknown's avatar
unknown committed
1616
    pthread_mutex_lock(&tmp->mutex);
unknown's avatar
SCRUM  
unknown committed
1617
    tmp->thd.killed= THD::KILL_CONNECTION;
unknown's avatar
unknown committed
1618 1619 1620
    if (tmp->thd.mysys_var)
    {
      pthread_mutex_lock(&tmp->thd.mysys_var->mutex);
unknown's avatar
unknown committed
1621
      if (tmp->thd.mysys_var->current_cond)
unknown's avatar
unknown committed
1622
      {
unknown's avatar
unknown committed
1623 1624 1625 1626 1627 1628
	/*
	  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
1629
	pthread_cond_broadcast(tmp->thd.mysys_var->current_cond);
unknown's avatar
unknown committed
1630 1631
	if (&tmp->mutex != tmp->thd.mysys_var->current_mutex)
	  pthread_mutex_unlock(tmp->thd.mysys_var->current_mutex);
unknown's avatar
unknown committed
1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
      }
      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
*/

1645
pthread_handler_t handle_delayed_insert(void *arg)
unknown's avatar
unknown committed
1646 1647 1648 1649 1650 1651 1652 1653
{
  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++;
1654
  thd->end_time();
unknown's avatar
unknown committed
1655
  threads.append(thd);
unknown's avatar
SCRUM  
unknown committed
1656
  thd->killed=abort_loop ? THD::KILL_CONNECTION : THD::NOT_KILLED;
unknown's avatar
unknown committed
1657 1658
  pthread_mutex_unlock(&LOCK_thread_count);

1659 1660 1661 1662 1663 1664 1665 1666
  /*
    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
1667
  pthread_mutex_lock(&di->mutex);
unknown's avatar
unknown committed
1668
#if !defined( __WIN__) && !defined(OS2)	/* Win32 calls this in pthread_create */
unknown's avatar
unknown committed
1669 1670 1671 1672 1673 1674 1675 1676
  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");
1677
  thd->thread_stack= (char*) &thd;
unknown's avatar
unknown committed
1678
  if (init_thr_lock() || thd->store_globals())
unknown's avatar
unknown committed
1679
  {
1680
    thd->fatal_error();
unknown's avatar
unknown committed
1681 1682 1683
    strmov(thd->net.last_error,ER(thd->net.last_errno=ER_OUT_OF_RESOURCES));
    goto end;
  }
unknown's avatar
unknown committed
1684
#if !defined(__WIN__) && !defined(OS2) && !defined(__NETWARE__)
unknown's avatar
unknown committed
1685 1686 1687 1688 1689 1690 1691
  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
1692
  if (!(di->table=open_ltable(thd,&di->table_list,TL_WRITE_DELAYED)))
unknown's avatar
unknown committed
1693
  {
1694
    thd->fatal_error();				// Abort waiting inserts
unknown's avatar
unknown committed
1695 1696
    goto end;
  }
unknown's avatar
unknown committed
1697
  if (!(di->table->file->table_flags() & HA_CAN_INSERT_DELAYED))
unknown's avatar
unknown committed
1698
  {
1699
    thd->fatal_error();
1700
    my_error(ER_ILLEGAL_HA, MYF(0), di->table_list.table_name);
unknown's avatar
unknown committed
1701 1702
    goto end;
  }
unknown's avatar
unknown committed
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717
  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 (;;)
  {
unknown's avatar
SCRUM  
unknown committed
1718
    if (thd->killed == THD::KILL_CONNECTION)
unknown's avatar
unknown committed
1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737
    {
      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;
1738
      set_timespec(abstime, delayed_insert_timeout);
unknown's avatar
unknown committed
1739 1740 1741 1742

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

1745
      DBUG_PRINT("info",("Waiting for someone to insert rows"));
unknown's avatar
unknown committed
1746
      while (!thd->killed)
unknown's avatar
unknown committed
1747 1748
      {
	int error;
1749
#if defined(HAVE_BROKEN_COND_TIMEDWAIT)
unknown's avatar
unknown committed
1750 1751 1752 1753
	error=pthread_cond_wait(&di->cond,&di->mutex);
#else
	error=pthread_cond_timedwait(&di->cond,&di->mutex,&abstime);
#ifdef EXTRA_DEBUG
1754
	if (error && error != EINTR && error != ETIMEDOUT)
unknown's avatar
unknown committed
1755 1756 1757 1758 1759 1760 1761 1762 1763
	{
	  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;
unknown's avatar
unknown committed
1764
	if (error == ETIMEDOUT || error == ETIME)
unknown's avatar
unknown committed
1765
	{
unknown's avatar
SCRUM  
unknown committed
1766
	  thd->killed= THD::KILL_CONNECTION;
unknown's avatar
unknown committed
1767 1768 1769
	  break;
	}
      }
unknown's avatar
unknown committed
1770 1771
      /* We can't lock di->mutex and mysys_var->mutex at the same time */
      pthread_mutex_unlock(&di->mutex);
unknown's avatar
unknown committed
1772 1773 1774 1775
      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
1776
      pthread_mutex_lock(&di->mutex);
unknown's avatar
unknown committed
1777
    }
1778
    di->thd.proc_info=0;
unknown's avatar
unknown committed
1779 1780 1781

    if (di->tables_in_use && ! thd->lock)
    {
1782
      bool not_used;
1783 1784 1785 1786 1787 1788 1789 1790 1791 1792
      /*
        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.
      */
1793
      if (! (thd->lock= mysql_lock_tables(thd, &di->table, 1,
1794 1795
                                          MYSQL_LOCK_IGNORE_GLOBAL_READ_LOCK,
                                          &not_used)))
unknown's avatar
unknown committed
1796
      {
1797 1798 1799
	/* Fatal error */
	di->dead= 1;
	thd->killed= THD::KILL_CONNECTION;
unknown's avatar
unknown committed
1800 1801 1802 1803 1804 1805 1806
      }
      pthread_cond_broadcast(&di->cond_client);
    }
    if (di->stacked_inserts)
    {
      if (di->handle_inserts())
      {
1807 1808 1809
	/* Some fatal error */
	di->dead= 1;
	thd->killed= THD::KILL_CONNECTION;
unknown's avatar
unknown committed
1810 1811 1812 1813 1814
      }
    }
    di->status=0;
    if (!di->stacked_inserts && !di->tables_in_use && thd->lock)
    {
unknown's avatar
unknown committed
1815 1816 1817 1818
      /*
        No one is doing a insert delayed
        Unlock table so that other threads can use it
      */
unknown's avatar
unknown committed
1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837
      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;
1838 1839
  di->dead= 1;                                  // If error
  thd->killed= THD::KILL_CONNECTION;	        // If error
unknown's avatar
unknown committed
1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885
  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;
1886
  ulong max_rows;
unknown's avatar
unknown committed
1887
  bool using_ignore=0, using_bin_log=mysql_bin_log.is_open();
1888
  delayed_row *row;
unknown's avatar
unknown committed
1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899
  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 */
1900
    sql_print_error(ER(ER_DELAYED_CANT_CHANGE_LOCK),table->s->table_name);
unknown's avatar
unknown committed
1901 1902 1903 1904
    goto err;
  }

  thd.proc_info="insert";
1905
  max_rows= delayed_insert_limit;
1906
  if (thd.killed || table->s->version != refresh_version)
unknown's avatar
unknown committed
1907
  {
unknown's avatar
SCRUM  
unknown committed
1908
    thd.killed= THD::KILL_CONNECTION;
1909
    max_rows= ~(ulong)0;                        // Do as much as possible
unknown's avatar
unknown committed
1910 1911
  }

unknown's avatar
unknown committed
1912 1913 1914 1915 1916 1917 1918
  /*
    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
1919 1920 1921 1922 1923
  pthread_mutex_lock(&mutex);
  while ((row=rows.get()))
  {
    stacked_inserts--;
    pthread_mutex_unlock(&mutex);
1924
    memcpy(table->record[0],row->record,table->s->reclength);
unknown's avatar
unknown committed
1925 1926 1927 1928 1929 1930

    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;
1931
    table->timestamp_field_type= row->timestamp_field_type;
unknown's avatar
unknown committed
1932

1933
    info.ignore= row->ignore;
unknown's avatar
unknown committed
1934
    info.handle_duplicates= row->dup;
1935
    if (info.ignore ||
unknown's avatar
unknown committed
1936
	info.handle_duplicates != DUP_ERROR)
unknown's avatar
unknown committed
1937 1938 1939 1940
    {
      table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
      using_ignore=1;
    }
unknown's avatar
unknown committed
1941
    thd.clear_error(); // reset error for binlog
unknown's avatar
unknown committed
1942
    if (write_record(&thd, table, &info))
unknown's avatar
unknown committed
1943
    {
1944
      info.error_count++;				// Ignore errors
1945
      thread_safe_increment(delayed_insert_errors,&LOCK_delayed_status);
unknown's avatar
unknown committed
1946
      row->log_query = 0;
unknown's avatar
unknown committed
1947
    }
unknown's avatar
unknown committed
1948 1949 1950 1951 1952
    if (using_ignore)
    {
      using_ignore=0;
      table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
    }
1953
    if (row->query && row->log_query && using_bin_log)
unknown's avatar
unknown committed
1954
    {
unknown's avatar
unknown committed
1955
      Query_log_event qinfo(&thd, row->query, row->query_length, 0, FALSE);
1956
      mysql_bin_log.write(&qinfo);
unknown's avatar
unknown committed
1957
    }
1958
    if (table->s->blob_fields)
unknown's avatar
unknown committed
1959 1960 1961 1962 1963 1964
      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;
1965 1966 1967 1968 1969 1970 1971
    /*
      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()) &&
1972
	(!(row->log_query & using_bin_log) ||
1973
	 row->query))
unknown's avatar
unknown committed
1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988
    {
      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
1989
	query_cache_invalidate3(&thd, table, 1);
unknown's avatar
unknown committed
1990 1991 1992
	if (thr_reschedule_write_lock(*thd.lock->locks))
	{
	  /* This should never happen */
1993
	  sql_print_error(ER(ER_DELAYED_CANT_CHANGE_LOCK),table->s->table_name);
unknown's avatar
unknown committed
1994
	}
unknown's avatar
unknown committed
1995 1996
	if (!using_bin_log)
	  table->file->extra(HA_EXTRA_WRITE_CACHE);
unknown's avatar
unknown committed
1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013
	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
2014
  query_cache_invalidate3(&thd, table, 1);
unknown's avatar
unknown committed
2015 2016 2017 2018
  pthread_mutex_lock(&mutex);
  DBUG_RETURN(0);

 err:
2019 2020 2021 2022 2023 2024 2025
  /* 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
2026 2027 2028 2029
  thread_safe_increment(delayed_insert_errors, &LOCK_delayed_status);
  pthread_mutex_lock(&mutex);
  DBUG_RETURN(1);
}
2030
#endif /* EMBEDDED_LIBRARY */
unknown's avatar
unknown committed
2031 2032

/***************************************************************************
unknown's avatar
unknown committed
2033
  Store records in INSERT ... SELECT *
unknown's avatar
unknown committed
2034 2035
***************************************************************************/

unknown's avatar
VIEW  
unknown committed
2036 2037 2038 2039 2040 2041 2042 2043 2044

/*
  make insert specific preparation and checks after opening tables

  SYNOPSIS
    mysql_insert_select_prepare()
    thd         thread handler

  RETURN
unknown's avatar
unknown committed
2045 2046
    FALSE OK
    TRUE  Error
unknown's avatar
VIEW  
unknown committed
2047 2048
*/

unknown's avatar
unknown committed
2049
bool mysql_insert_select_prepare(THD *thd)
unknown's avatar
VIEW  
unknown committed
2050 2051
{
  LEX *lex= thd->lex;
unknown's avatar
unknown committed
2052
  SELECT_LEX *select_lex= &lex->select_lex;
unknown's avatar
unknown committed
2053
  TABLE_LIST *first_select_leaf_table;
unknown's avatar
VIEW  
unknown committed
2054
  DBUG_ENTER("mysql_insert_select_prepare");
unknown's avatar
unknown committed
2055

unknown's avatar
unknown committed
2056 2057
  /*
    SELECT_LEX do not belong to INSERT statement, so we can't add WHERE
unknown's avatar
unknown committed
2058
    clause if table is VIEW
unknown's avatar
unknown committed
2059
  */
unknown's avatar
unknown committed
2060
  
unknown's avatar
unknown committed
2061
  if (mysql_prepare_insert(thd, lex->query_tables,
unknown's avatar
unknown committed
2062 2063 2064
                           lex->query_tables->table, lex->field_list, 0,
                           lex->update_list, lex->value_list,
                           lex->duplicates,
unknown's avatar
unknown committed
2065
                           &select_lex->where, TRUE))
unknown's avatar
unknown committed
2066
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
2067

2068 2069 2070 2071
  /*
    exclude first table from leaf tables list, because it belong to
    INSERT
  */
unknown's avatar
unknown committed
2072 2073
  DBUG_ASSERT(select_lex->leaf_tables != 0);
  lex->leaf_tables_insert= select_lex->leaf_tables;
2074
  /* skip all leaf tables belonged to view where we are insert */
unknown's avatar
unknown committed
2075
  for (first_select_leaf_table= select_lex->leaf_tables->next_leaf;
2076 2077 2078 2079 2080 2081
       first_select_leaf_table &&
       first_select_leaf_table->belong_to_view &&
       first_select_leaf_table->belong_to_view ==
       lex->leaf_tables_insert->belong_to_view;
       first_select_leaf_table= first_select_leaf_table->next_leaf)
  {}
unknown's avatar
unknown committed
2082
  select_lex->leaf_tables= first_select_leaf_table;
unknown's avatar
unknown committed
2083
  DBUG_RETURN(FALSE);
unknown's avatar
VIEW  
unknown committed
2084 2085 2086
}


2087
select_insert::select_insert(TABLE_LIST *table_list_par, TABLE *table_par,
unknown's avatar
unknown committed
2088
                             List<Item> *fields_par,
unknown's avatar
unknown committed
2089 2090
                             List<Item> *update_fields,
                             List<Item> *update_values,
unknown's avatar
unknown committed
2091
                             enum_duplicates duplic,
2092 2093 2094 2095 2096 2097
                             bool ignore_check_option_errors)
  :table_list(table_list_par), table(table_par), fields(fields_par),
   last_insert_id(0),
   insert_into_view(table_list_par && table_list_par->view != 0)
{
  bzero((char*) &info,sizeof(info));
unknown's avatar
unknown committed
2098 2099 2100 2101
  info.handle_duplicates= duplic;
  info.ignore= ignore_check_option_errors;
  info.update_fields= update_fields;
  info.update_values= update_values;
2102
  if (table_list_par)
unknown's avatar
unknown committed
2103
    info.view= (table_list_par->view ? table_list_par : 0);
2104 2105 2106
}


unknown's avatar
unknown committed
2107
int
2108
select_insert::prepare(List<Item> &values, SELECT_LEX_UNIT *u)
unknown's avatar
unknown committed
2109
{
2110
  LEX *lex= thd->lex;
2111
  int res;
2112
  SELECT_LEX *lex_current_select_save= lex->current_select;
unknown's avatar
unknown committed
2113 2114
  DBUG_ENTER("select_insert::prepare");

2115
  unit= u;
2116 2117 2118 2119 2120 2121
  /*
    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.
  */
  lex->current_select= &lex->select_lex;
2122
  res= check_insert_fields(thd, table_list, *fields, values,
2123 2124
                           !insert_into_view) ||
       setup_fields(thd, 0, values, 0, 0, 0);
2125

2126 2127
  if (info.handle_duplicates == DUP_UPDATE)
  {
2128 2129
    /* Save the state of the current name resolution context. */
    Name_resolution_context *context= &lex->select_lex.context;
2130 2131 2132 2133
    Name_resolution_context_state ctx_state;

    /* Save the state of the current name resolution context. */
    ctx_state.save_state(context, table_list);
2134 2135

    /* Perform name resolution only in the first table - 'table_list'. */
2136
    table_list->next_local= 0;
2137 2138
    context->resolve_in_table_list_only(table_list);

2139
    lex->select_lex.no_wrap_view_item= TRUE;
2140 2141
    res= res || check_update_fields(thd, context->table_list,
                                    *info.update_fields);
2142 2143 2144 2145 2146
    lex->select_lex.no_wrap_view_item= FALSE;
    /*
      When we are not using GROUP BY we can refer to other tables in the
      ON DUPLICATE KEY part
    */       
2147 2148
    if (lex->select_lex.group_list.elements == 0)
    {
2149
      context->table_list->next_local=       ctx_state.save_next_local;
2150
      /* first_name_resolution_table was set by resolve_in_table_list_only() */
2151
      context->first_name_resolution_table->
2152
        next_name_resolution_table=          ctx_state.save_next_local;
2153
    }
2154
    res= res || setup_fields(thd, 0, *info.update_values, 1, 0, 0);
2155 2156

    /* Restore the current context. */
2157
    ctx_state.restore_state(context, table_list);
2158
  }
2159

2160 2161
  lex->current_select= lex_current_select_save;
  if (res)
unknown's avatar
unknown committed
2162
    DBUG_RETURN(1);
2163 2164 2165 2166 2167 2168 2169 2170 2171 2172
  /*
    if it is INSERT into join view then check_insert_fields already found
    real table for insert
  */
  table= table_list->table;

  /*
    Is table which we are changing used somewhere in other parts of
    query
  */
2173
  if (!(lex->current_select->options & OPTION_BUFFER_RESULT) &&
unknown's avatar
unknown committed
2174
      unique_table(table_list, table_list->next_global))
2175 2176
  {
    /* Using same table for INSERT and SELECT */
2177 2178
    lex->current_select->options|= OPTION_BUFFER_RESULT;
    lex->current_select->join->select_options|= OPTION_BUFFER_RESULT;
2179
  }
2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190
  else
  {
    /*
      We must not yet prepare the result table if it is the same as one of the 
      source tables (INSERT SELECT). The preparation may disable 
      indexes on the result table, which may be used during the select, if it
      is the same table (Bug #6034). Do the preparation after the select phase
      in select_insert::prepare2().
    */
    table->file->start_bulk_insert((ha_rows) 0);
  }
2191
  restore_record(table,s->default_values);		// Get empty record
unknown's avatar
unknown committed
2192
  table->next_number_field=table->found_next_number_field;
unknown's avatar
unknown committed
2193
  thd->cuted_fields=0;
unknown's avatar
unknown committed
2194 2195
  if (info.ignore || info.handle_duplicates != DUP_ERROR)
    table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
unknown's avatar
unknown committed
2196
  thd->no_trans_update= 0;
unknown's avatar
unknown committed
2197
  thd->abort_on_warning= (!info.ignore &&
unknown's avatar
unknown committed
2198 2199 2200
                          (thd->variables.sql_mode &
                           (MODE_STRICT_TRANS_TABLES |
                            MODE_STRICT_ALL_TABLES)));
2201 2202 2203 2204 2205
  res= ((fields->elements &&
         check_that_all_fields_are_given_values(thd, table, table_list)) ||
        table_list->prepare_where(thd, 0, TRUE) ||
        table_list->prepare_check_option(thd));
  DBUG_RETURN(res);
unknown's avatar
unknown committed
2206 2207
}

2208

2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229
/*
  Finish the preparation of the result table.

  SYNOPSIS
    select_insert::prepare2()
    void

  DESCRIPTION
    If the result table is the same as one of the source tables (INSERT SELECT),
    the result table is not finally prepared at the join prepair phase.
    Do the final preparation now.
		       
  RETURN
    0   OK
*/

int select_insert::prepare2(void)
{
  DBUG_ENTER("select_insert::prepare2");
  if (thd->lex->current_select->options & OPTION_BUFFER_RESULT)
    table->file->start_bulk_insert((ha_rows) 0);
unknown's avatar
unknown committed
2230
  DBUG_RETURN(0);
2231 2232 2233
}


2234 2235 2236 2237 2238 2239
void select_insert::cleanup()
{
  /* select_insert/select_create are never re-used in prepared statement */
  DBUG_ASSERT(0);
}

unknown's avatar
unknown committed
2240 2241
select_insert::~select_insert()
{
2242
  DBUG_ENTER("~select_insert");
unknown's avatar
unknown committed
2243 2244 2245
  if (table)
  {
    table->next_number_field=0;
2246
    table->file->reset();
unknown's avatar
unknown committed
2247
  }
2248
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;
unknown's avatar
unknown committed
2249
  thd->abort_on_warning= 0;
2250
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
2251 2252 2253 2254 2255
}


bool select_insert::send_data(List<Item> &values)
{
2256
  DBUG_ENTER("select_insert::send_data");
unknown's avatar
unknown committed
2257
  bool error=0;
2258
  if (unit->offset_limit_cnt)
unknown's avatar
unknown committed
2259
  {						// using limit offset,count
2260
    unit->offset_limit_cnt--;
2261
    DBUG_RETURN(0);
unknown's avatar
unknown committed
2262
  }
unknown's avatar
unknown committed
2263

unknown's avatar
unknown committed
2264
  thd->count_cuted_fields= CHECK_FIELD_WARN;	// Calculate cuted fields
unknown's avatar
unknown committed
2265 2266
  store_values(values);
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;
unknown's avatar
unknown committed
2267 2268
  if (thd->net.report_error)
    DBUG_RETURN(1);
unknown's avatar
unknown committed
2269 2270
  if (table_list)                               // Not CREATE ... SELECT
  {
unknown's avatar
unknown committed
2271
    switch (table_list->view_check_option(thd, info.ignore)) {
unknown's avatar
unknown committed
2272 2273 2274 2275 2276
    case VIEW_CHECK_SKIP:
      DBUG_RETURN(0);
    case VIEW_CHECK_ERROR:
      DBUG_RETURN(1);
    }
unknown's avatar
unknown committed
2277
  }
unknown's avatar
unknown committed
2278
  if (!(error= write_record(thd, table, &info)))
unknown's avatar
unknown committed
2279
  {
unknown's avatar
unknown committed
2280
    if (table->triggers || info.handle_duplicates == DUP_UPDATE)
unknown's avatar
unknown committed
2281 2282
    {
      /*
unknown's avatar
unknown committed
2283 2284 2285
        Restore fields of the record since it is possible that they were
        changed by ON DUPLICATE KEY UPDATE clause.
    
unknown's avatar
unknown committed
2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301
        If triggers exist then whey can modify some fields which were not
        originally touched by INSERT ... SELECT, so we have to restore
        their original values for the next row.
      */
      restore_record(table, s->default_values);
    }
    if (table->next_number_field)
    {
      /*
        Clear auto-increment field for the next record, if triggers are used
        we will clear it twice, but this should be cheap.
      */
      table->next_number_field->reset();
      if (!last_insert_id && thd->insert_id_used)
        last_insert_id= thd->insert_id();
    }
unknown's avatar
unknown committed
2302
  }
unknown's avatar
unknown committed
2303
  DBUG_RETURN(error);
unknown's avatar
unknown committed
2304 2305 2306
}


unknown's avatar
unknown committed
2307 2308 2309
void select_insert::store_values(List<Item> &values)
{
  if (fields->elements)
unknown's avatar
unknown committed
2310 2311
    fill_record_n_invoke_before_triggers(thd, *fields, values, 1,
                                         table->triggers, TRG_EVENT_INSERT);
unknown's avatar
unknown committed
2312
  else
unknown's avatar
unknown committed
2313 2314
    fill_record_n_invoke_before_triggers(thd, table->field, values, 1,
                                         table->triggers, TRG_EVENT_INSERT);
unknown's avatar
unknown committed
2315 2316
}

unknown's avatar
unknown committed
2317 2318
void select_insert::send_error(uint errcode,const char *err)
{
unknown's avatar
unknown committed
2319 2320
  DBUG_ENTER("select_insert::send_error");

unknown's avatar
unknown committed
2321
  my_message(errcode, err, MYF(0));
2322 2323 2324 2325 2326 2327 2328 2329 2330

  if (!table)
  {
    /*
      This can only happen when using CREATE ... SELECT and the table was not
      created becasue of an syntax error
    */
    DBUG_VOID_RETURN;
  }
2331
  table->file->end_bulk_insert();
unknown's avatar
unknown committed
2332 2333 2334 2335 2336
  /*
    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).
2337
  */
unknown's avatar
unknown committed
2338
  if ((info.copied || info.deleted || info.updated) &&
unknown's avatar
unknown committed
2339
      !table->file->has_transactions())
2340 2341 2342 2343 2344 2345
  {
    if (last_insert_id)
      thd->insert_id(last_insert_id);		// For binary log
    if (mysql_bin_log.is_open())
    {
      Query_log_event qinfo(thd, thd->query, thd->query_length,
2346
                            table->file->has_transactions(), FALSE);
2347 2348
      mysql_bin_log.write(&qinfo);
    }
2349
    if (!table->s->tmp_table)
unknown's avatar
unknown committed
2350
      thd->options|=OPTION_STATUS_NO_TRANS_UPDATE;
2351
  }
unknown's avatar
unknown committed
2352
  if (info.copied || info.deleted || info.updated)
unknown's avatar
unknown committed
2353
  {
unknown's avatar
unknown committed
2354
    query_cache_invalidate3(thd, table, 1);
unknown's avatar
unknown committed
2355
  }
unknown's avatar
unknown committed
2356
  ha_rollback_stmt(thd);
unknown's avatar
unknown committed
2357
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
2358 2359 2360 2361 2362
}


bool select_insert::send_eof()
{
2363
  int error,error2;
unknown's avatar
unknown committed
2364 2365
  DBUG_ENTER("select_insert::send_eof");

unknown's avatar
unknown committed
2366
  error=table->file->end_bulk_insert();
unknown's avatar
unknown committed
2367
  table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
2368

2369 2370
  /*
    We must invalidate the table in the query cache before binlog writing
unknown's avatar
unknown committed
2371
    and ha_autocommit_or_rollback
2372
  */
unknown's avatar
unknown committed
2373

unknown's avatar
unknown committed
2374
  if (info.copied || info.deleted || info.updated)
unknown's avatar
unknown committed
2375
  {
unknown's avatar
unknown committed
2376
    query_cache_invalidate3(thd, table, 1);
2377
    if (!(table->file->has_transactions() || table->s->tmp_table))
unknown's avatar
unknown committed
2378 2379
      thd->options|=OPTION_STATUS_NO_TRANS_UPDATE;
  }
unknown's avatar
unknown committed
2380

2381 2382
  if (last_insert_id)
    thd->insert_id(last_insert_id);		// For binary log
2383 2384 2385
  /* Write to binlog before commiting transaction */
  if (mysql_bin_log.is_open())
  {
unknown's avatar
unknown committed
2386 2387
    if (!error)
      thd->clear_error();
2388
    Query_log_event qinfo(thd, thd->query, thd->query_length,
2389
			  table->file->has_transactions(), FALSE);
2390 2391
    mysql_bin_log.write(&qinfo);
  }
2392 2393 2394
  if ((error2=ha_autocommit_or_rollback(thd,error)) && ! error)
    error=error2;
  if (error)
unknown's avatar
unknown committed
2395 2396
  {
    table->file->print_error(error,MYF(0));
unknown's avatar
unknown committed
2397
    DBUG_RETURN(1);
unknown's avatar
unknown committed
2398
  }
unknown's avatar
unknown committed
2399
  char buff[160];
2400
  if (info.ignore)
unknown's avatar
unknown committed
2401 2402
    sprintf(buff, ER(ER_INSERT_INFO), (ulong) info.records,
	    (ulong) (info.records - info.copied), (ulong) thd->cuted_fields);
unknown's avatar
unknown committed
2403
  else
unknown's avatar
unknown committed
2404
    sprintf(buff, ER(ER_INSERT_INFO), (ulong) info.records,
unknown's avatar
unknown committed
2405
	    (ulong) (info.deleted+info.updated), (ulong) thd->cuted_fields);
2406
  thd->row_count_func= info.copied+info.deleted+info.updated;
2407
  ::send_ok(thd, (ulong) thd->row_count_func, last_insert_id, buff);
unknown's avatar
unknown committed
2408
  DBUG_RETURN(0);
unknown's avatar
unknown committed
2409 2410 2411 2412
}


/***************************************************************************
unknown's avatar
unknown committed
2413
  CREATE TABLE (SELECT) ...
unknown's avatar
unknown committed
2414 2415 2416
***************************************************************************/

int
2417
select_create::prepare(List<Item> &values, SELECT_LEX_UNIT *u)
unknown's avatar
unknown committed
2418 2419 2420
{
  DBUG_ENTER("select_create::prepare");

2421
  unit= u;
unknown's avatar
VIEW  
unknown committed
2422
  table= create_table_from_items(thd, create_info, create_table,
unknown's avatar
unknown committed
2423
				 extra_fields, keys, &values, &lock);
unknown's avatar
unknown committed
2424 2425 2426
  if (!table)
    DBUG_RETURN(-1);				// abort() deletes table

2427
  if (table->s->fields < values.elements)
unknown's avatar
unknown committed
2428
  {
2429
    my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), 1);
unknown's avatar
unknown committed
2430 2431 2432
    DBUG_RETURN(-1);
  }

unknown's avatar
unknown committed
2433
  /* First field to copy */
2434
  field=table->field+table->s->fields - values.elements;
unknown's avatar
unknown committed
2435

2436
  /* Don't set timestamp if used */
2437
  table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
unknown's avatar
unknown committed
2438

unknown's avatar
unknown committed
2439 2440
  table->next_number_field=table->found_next_number_field;

2441
  restore_record(table,s->default_values);      // Get empty record
unknown's avatar
unknown committed
2442
  thd->cuted_fields=0;
unknown's avatar
unknown committed
2443
  if (info.ignore || info.handle_duplicates != DUP_ERROR)
unknown's avatar
unknown committed
2444
    table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
2445
  table->file->start_bulk_insert((ha_rows) 0);
unknown's avatar
unknown committed
2446
  thd->no_trans_update= 0;
unknown's avatar
unknown committed
2447
  thd->abort_on_warning= (!info.ignore &&
unknown's avatar
unknown committed
2448 2449 2450
                          (thd->variables.sql_mode &
                           (MODE_STRICT_TRANS_TABLES |
                            MODE_STRICT_ALL_TABLES)));
2451 2452
  DBUG_RETURN(check_that_all_fields_are_given_values(thd, table,
                                                     table_list));
unknown's avatar
unknown committed
2453 2454 2455
}


unknown's avatar
unknown committed
2456
void select_create::store_values(List<Item> &values)
unknown's avatar
unknown committed
2457
{
unknown's avatar
unknown committed
2458 2459
  fill_record_n_invoke_before_triggers(thd, field, values, 1,
                                       table->triggers, TRG_EVENT_INSERT);
unknown's avatar
unknown committed
2460 2461
}

unknown's avatar
unknown committed
2462

2463 2464 2465 2466 2467 2468 2469 2470 2471
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
2472 2473
}

unknown's avatar
unknown committed
2474

unknown's avatar
unknown committed
2475 2476 2477 2478 2479 2480 2481
bool select_create::send_eof()
{
  bool tmp=select_insert::send_eof();
  if (tmp)
    abort();
  else
  {
unknown's avatar
unknown committed
2482
    table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
unknown's avatar
unknown committed
2483 2484
    VOID(pthread_mutex_lock(&LOCK_open));
    mysql_unlock_tables(thd, lock);
2485 2486 2487 2488 2489
    /*
      TODO:
      Check if we can remove the following two rows.
      We should be able to just keep the table in the table cache.
    */
2490
    if (!table->s->tmp_table)
2491
    {
2492
      ulong version= table->s->version;
2493
      hash_delete(&open_cache,(byte*) table);
2494
      /* Tell threads waiting for refresh that something has happened */
unknown's avatar
unknown committed
2495
      if (version != refresh_version)
2496 2497
        VOID(pthread_cond_broadcast(&COND_refresh));
    }
unknown's avatar
unknown committed
2498
    lock=0;
unknown's avatar
unknown committed
2499
    table=0;
unknown's avatar
unknown committed
2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514
    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
2515
    table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
2516 2517
    enum db_type table_type=table->s->db_type;
    if (!table->s->tmp_table)
2518
    {
2519
      ulong version= table->s->version;
2520
      hash_delete(&open_cache,(byte*) table);
2521
      if (!create_info->table_existed)
2522
        quick_rm_table(table_type, create_table->db, create_table->table_name);
2523
      /* Tell threads waiting for refresh that something has happened */
unknown's avatar
unknown committed
2524
      if (version != refresh_version)
2525
        VOID(pthread_cond_broadcast(&COND_refresh));
2526 2527
    }
    else if (!create_info->table_existed)
2528
      close_temporary_table(thd, create_table->db, create_table->table_name);
unknown's avatar
unknown committed
2529 2530 2531 2532 2533 2534 2535
    table=0;
  }
  VOID(pthread_mutex_unlock(&LOCK_open));
}


/*****************************************************************************
unknown's avatar
unknown committed
2536
  Instansiate templates
unknown's avatar
unknown committed
2537 2538
*****************************************************************************/

2539
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
unknown's avatar
unknown committed
2540
template class List_iterator_fast<List_item>;
2541
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
2542 2543 2544
template class I_List<delayed_insert>;
template class I_List_iterator<delayed_insert>;
template class I_List<delayed_row>;
2545
#endif /* EMBEDDED_LIBRARY */
2546
#endif /* HAVE_EXPLICIT_TEMPLATE_INSTANTIATION */