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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3 4
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
5
   the Free Software Foundation; version 2 of the License.
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
6

bk@work.mysql.com's avatar
bk@work.mysql.com committed
7 8 9 10
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
11

bk@work.mysql.com's avatar
bk@work.mysql.com committed
12 13 14 15 16 17 18
   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 */

19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
/*
  INSERT DELAYED

  Insert delayed is distinguished from a normal insert by lock_type ==
  TL_WRITE_DELAYED instead of TL_WRITE. It first tries to open a
  "delayed" table (delayed_get_table()), but falls back to
  open_and_lock_tables() on error and proceeds as normal insert then.

  Opening a "delayed" table means to find a delayed insert thread that
  has the table open already. If this fails, a new thread is created and
  waited for to open and lock the table.

  If accessing the thread succeeded, in
  delayed_insert::get_local_table() the table of the thread is copied
  for local use. A copy is required because the normal insert logic
  works on a target table, but the other threads table object must not
  be used. The insert logic uses the record buffer to create a record.
  And the delayed insert thread uses the record buffer to pass the
  record to the table handler. So there must be different objects. Also
  the copied table is not included in the lock, so that the statement
  can proceed even if the real table cannot be accessed at this moment.

  Copying a table object is not a trivial operation. Besides the TABLE
  object there are the field pointer array, the field objects and the
  record buffer. After copying the field objects, their pointers into
  the record must be "moved" to point to the new record buffer.

  After this setup the normal insert logic is used. Only that for
  delayed inserts write_delayed() is called instead of write_record().
  It inserts the rows into a queue and signals the delayed insert thread
  instead of writing directly to the table.

  The delayed insert thread awakes from the signal. It locks the table,
  inserts the rows from the queue, unlocks the table, and waits for the
  next signal. It does normally live until a FLUSH TABLES or SHUTDOWN.

*/

bk@work.mysql.com's avatar
bk@work.mysql.com committed
57
#include "mysql_priv.h"
58 59
#include "sp_head.h"
#include "sql_trigger.h"
60
#include "sql_select.h"
guilhem@gbichot3.local's avatar
guilhem@gbichot3.local committed
61
#include "slave.h"
bk@work.mysql.com's avatar
bk@work.mysql.com committed
62

63
#ifndef EMBEDDED_LIBRARY
bk@work.mysql.com's avatar
bk@work.mysql.com committed
64
static TABLE *delayed_get_table(THD *thd,TABLE_LIST *table_list);
65
static int write_delayed(THD *thd,TABLE *table, enum_duplicates dup, bool ignore,
66
			 char *query, uint query_length, bool log_on);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
67
static void end_delayed_insert(THD *thd);
68
pthread_handler_t handle_delayed_insert(void *arg);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
69
static void unlink_blobs(register TABLE *table);
70
#endif
71
static bool check_view_insertability(THD *thd, TABLE_LIST *view);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
72 73 74 75 76 77 78 79 80 81 82

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

83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
/*
  Check that insert/update fields are from the same single table of a view.

  SYNOPSIS
    check_view_single_update()
    fields            The insert/update fields to be checked.
    view              The view for insert.
    map     [in/out]  The insert table map.

  DESCRIPTION
    This function is called in 2 cases:
    1. to check insert fields. In this case *map will be set to 0.
       Insert fields are checked to be all from the same single underlying
       table of the given view. Otherwise the error is thrown. Found table
       map is returned in the map parameter.
    2. to check update fields of the ON DUPLICATE KEY UPDATE clause.
       In this case *map contains table_map found on the previous call of
       the function to check insert fields. Update fields are checked to be
       from the same table as the insert fields.

  RETURN
    0   OK
    1   Error
*/

bool check_view_single_update(List<Item> &fields, TABLE_LIST *view,
                              table_map *map)
{
  /* it is join view => we need to find the table for update */
  List_iterator_fast<Item> it(fields);
  Item *item;
  TABLE_LIST *tbl= 0;            // reset for call to check_single_table()
  table_map tables= 0;

  while ((item= it++))
    tables|= item->used_tables();

  /* Check found map against provided map */
  if (*map)
  {
    if (tables != *map)
      goto error;
    return FALSE;
  }

  if (view->check_single_table(&tbl, tables, view) || tbl == 0)
    goto error;

  view->table= tbl->table;
  *map= tables;

  return FALSE;

error:
  my_error(ER_VIEW_MULTIUPDATE, MYF(0),
           view->view_db.str, view->view_name.str);
  return TRUE;
}

142

bk@work.mysql.com's avatar
bk@work.mysql.com committed
143
/*
144
  Check if insert fields are correct.
145 146 147 148 149 150 151

  SYNOPSIS
    check_insert_fields()
    thd                         The current thread.
    table                       The table for insert.
    fields                      The insert fields.
    values                      The insert values.
ingo@mysql.com's avatar
ingo@mysql.com committed
152
    check_unique                If duplicate values should be rejected.
153 154 155 156 157 158 159 160 161

  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
bk@work.mysql.com's avatar
bk@work.mysql.com committed
162 163
*/

ingo@mysql.com's avatar
ingo@mysql.com committed
164 165
static int check_insert_fields(THD *thd, TABLE_LIST *table_list,
                               List<Item> &fields, List<Item> &values,
166
                               bool check_unique, table_map *map)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
167
{
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
168
  TABLE *table= table_list->table;
169

170 171
  if (!table_list->updatable)
  {
172
    my_error(ER_NON_INSERTABLE_TABLE, MYF(0), table_list->alias, "INSERT");
173 174 175
    return -1;
  }

bk@work.mysql.com's avatar
bk@work.mysql.com committed
176 177
  if (fields.elements == 0 && values.elements != 0)
  {
178 179 180 181 182 183
    if (!table)
    {
      my_error(ER_VIEW_NO_INSERT_FIELD_LIST, MYF(0),
               table_list->view_db.str, table_list->view_name.str);
      return -1;
    }
184
    if (values.elements != table->s->fields)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
185
    {
monty@mysql.com's avatar
monty@mysql.com committed
186
      my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), 1L);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
187 188
      return -1;
    }
hf@deer.(none)'s avatar
hf@deer.(none) committed
189
#ifndef NO_EMBEDDED_ACCESS_CHECKS
190
    if (grant_option)
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
191
    {
192 193
      Field_iterator_table field_it;
      field_it.set_table(table);
194
      if (check_grant_all_columns(thd, INSERT_ACL, &table->grant,
195
                                  table->s->db, table->s->table_name,
196
                                  &field_it))
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
197 198
        return -1;
    }
hf@deer.(none)'s avatar
hf@deer.(none) committed
199
#endif
200 201
    clear_timestamp_auto_bits(table->timestamp_field_type,
                              TIMESTAMP_AUTO_SET_ON_INSERT);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
202 203 204
  }
  else
  {						// Part field list
205 206
    SELECT_LEX *select_lex= &thd->lex->select_lex;
    Name_resolution_context *context= &select_lex->context;
207
    Name_resolution_context_state ctx_state;
208
    int res;
209

bk@work.mysql.com's avatar
bk@work.mysql.com committed
210 211
    if (fields.elements != values.elements)
    {
monty@mysql.com's avatar
monty@mysql.com committed
212
      my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), 1L);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
213 214 215 216
      return -1;
    }

    thd->dupp_field=0;
217 218 219
    select_lex->no_wrap_view_item= TRUE;

    /* Save the state of the current name resolution context. */
220
    ctx_state.save_state(context, table_list);
221 222 223 224 225

    /*
      Perform name resolution only in the first table - 'table_list',
      which is the table that is inserted into.
    */
226
    table_list->next_local= 0;
227 228
    context->resolve_in_table_list_only(table_list);
    res= setup_fields(thd, 0, fields, 1, 0, 0);
229 230

    /* Restore the current context. */
231
    ctx_state.restore_state(context, table_list);
232
    thd->lex->select_lex.no_wrap_view_item= FALSE;
233

234
    if (res)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
235
      return -1;
236

igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
237
    if (table_list->effective_algorithm == VIEW_ALGORITHM_MERGE)
238
    {
239
      if (check_view_single_update(fields, table_list, map))
240
        return -1;
241
      table= table_list->table;
242
    }
243

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
244
    if (check_unique && thd->dupp_field)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
245
    {
246
      my_error(ER_FIELD_SPECIFIED_TWICE, MYF(0), thd->dupp_field->field_name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
247 248 249
      return -1;
    }
    if (table->timestamp_field &&	// Don't set timestamp if used
250
	table->timestamp_field->query_id == thd->query_id)
251 252
      clear_timestamp_auto_bits(table->timestamp_field_type,
                                TIMESTAMP_AUTO_SET_ON_INSERT);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
253
  }
254
  // For the values we need select_priv
hf@deer.(none)'s avatar
hf@deer.(none) committed
255
#ifndef NO_EMBEDDED_ACCESS_CHECKS
256
  table->grant.want_privilege= (SELECT_ACL & ~table->grant.privilege);
hf@deer.(none)'s avatar
hf@deer.(none) committed
257
#endif
258 259 260

  if (check_key_in_view(thd, table_list) ||
      (table_list->view &&
261
       check_view_insertability(thd, table_list)))
262
  {
263
    my_error(ER_NON_INSERTABLE_TABLE, MYF(0), table_list->alias, "INSERT");
264 265 266
    return -1;
  }

bk@work.mysql.com's avatar
bk@work.mysql.com committed
267 268 269 270
  return 0;
}


271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
/*
  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
*/

ingo@mysql.com's avatar
ingo@mysql.com committed
290
static int check_update_fields(THD *thd, TABLE_LIST *insert_table_list,
291
                               List<Item> &update_fields, table_map *map)
292
{
ingo@mysql.com's avatar
ingo@mysql.com committed
293
  TABLE *table= insert_table_list->table;
294
  query_id_t timestamp_query_id;
295 296 297 298 299 300 301 302 303
  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;
ingo@mysql.com's avatar
ingo@mysql.com committed
304
    table->timestamp_field->query_id= thd->query_id - 1;
305 306 307 308 309 310
  }

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

314 315 316 317
  if (insert_table_list->effective_algorithm == VIEW_ALGORITHM_MERGE &&
      check_view_single_update(update_fields, insert_table_list, map))
    return -1;

318 319 320 321
  if (table->timestamp_field)
  {
    /* Don't set timestamp column if this is modified. */
    if (table->timestamp_field->query_id == thd->query_id)
322 323
      clear_timestamp_auto_bits(table->timestamp_field_type,
                                TIMESTAMP_AUTO_SET_ON_UPDATE);
324 325 326 327 328 329 330 331
    else
      table->timestamp_field->query_id= timestamp_query_id;
  }

  return 0;
}


332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
/*
  Mark fields used by triggers for INSERT-like statement.

  SYNOPSIS
    mark_fields_used_by_triggers_for_insert_stmt()
      thd     The current thread
      table   Table to which insert will happen
      duplic  Type of duplicate handling for insert which will happen

  NOTE
    For REPLACE there is no sense in marking particular fields
    used by ON DELETE trigger as to execute it properly we have
    to retrieve and store values for all table columns anyway.
*/

void mark_fields_used_by_triggers_for_insert_stmt(THD *thd, TABLE *table,
                                                  enum_duplicates duplic)
{
  if (table->triggers)
  {
    table->triggers->mark_fields_used(thd, TRG_EVENT_INSERT);
    if (duplic == DUP_UPDATE)
      table->triggers->mark_fields_used(thd, TRG_EVENT_UPDATE);
  }
}


359 360 361 362 363
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,
364 365
                  enum_duplicates duplic,
		  bool ignore)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
366
{
367
  int error, res;
368 369 370 371 372
  /*
    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).
  */
373
  bool transactional_table, joins_freed= FALSE;
374
  bool changed;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
375 376 377 378
  uint value_count;
  ulong counter = 1;
  ulonglong id;
  COPY_INFO info;
379
  TABLE *table= 0;
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
380
  List_iterator_fast<List_item> its(values_list);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
381
  List_item *values;
382
  Name_resolution_context *context;
383
  Name_resolution_context_state ctx_state;
384
#ifndef EMBEDDED_LIBRARY
385
  char *query= thd->query;
386
#endif
387 388
  bool log_on= (thd->options & OPTION_BIN_LOG) ||
    (!(thd->security_ctx->master_access & SUPER_ACL));
389
  thr_lock_type lock_type = table_list->lock_type;
monty@mysql.com's avatar
monty@mysql.com committed
390
  Item *unused_conds= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
391 392
  DBUG_ENTER("mysql_insert");

393 394 395 396 397
  /*
    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
   */
398 399 400 401
#ifdef EMBEDDED_LIBRARY
  if (lock_type == TL_WRITE_DELAYED)
    lock_type=TL_WRITE;
#else
402 403
  if ((lock_type == TL_WRITE_DELAYED &&
       ((specialflag & (SPECIAL_NO_NEW_FUNC | SPECIAL_SAFE_MODE)) ||
404
	thd->slave_thread || !thd->variables.max_insert_delayed_threads)) ||
405 406
      (lock_type == TL_WRITE_CONCURRENT_INSERT && duplic == DUP_REPLACE) ||
      (duplic == DUP_UPDATE))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
407
    lock_type=TL_WRITE;
408
#endif
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
  if ((lock_type == TL_WRITE_DELAYED) &&
      log_on && mysql_bin_log.is_open() &&
      (values_list.elements > 1))
  {
    /*
      Statement-based binary logging does not work in this case, because:
      a) two concurrent statements may have their rows intermixed in the
      queue, leading to autoincrement replication problems on slave (because
      the values generated used for one statement don't depend only on the
      value generated for the first row of this statement, so are not
      replicable)
      b) if first row of the statement has an error the full statement is
      not binlogged, while next rows of the statement may be inserted.
      c) if first row succeeds, statement is binlogged immediately with a
      zero error code (i.e. "no error"), if then second row fails, query
      will fail on slave too and slave will stop (wrongly believing that the
      master got no error).
      So we fallback to non-delayed INSERT.
    */
    lock_type= TL_WRITE;
  }
430
  table_list->lock_type= lock_type;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
431

432
#ifndef EMBEDDED_LIBRARY
bk@work.mysql.com's avatar
bk@work.mysql.com committed
433 434
  if (lock_type == TL_WRITE_DELAYED)
  {
435
    res= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
436 437
    if (thd->locked_tables)
    {
438 439
      DBUG_ASSERT(table_list->db); /* Must be set in the parser */
      if (find_locked_table(thd, table_list->db, table_list->table_name))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
440
      {
441
	my_error(ER_DELAYED_INSERT_TABLE_LOCKED, MYF(0),
442
                 table_list->table_name);
443
	DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
444 445
      }
    }
446
    if ((table= delayed_get_table(thd,table_list)) && !thd->is_fatal_error)
447
    {
448 449 450 451 452
      /*
        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);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
453 454 455 456 457 458
      /*
	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
459
    }
460
    else if (thd->net.last_errno != ER_WRONG_OBJECT)
461
    {
462 463
      /* Too many delayed insert threads;  Use a normal insert */
      table_list->lock_type= lock_type= TL_WRITE;
464
      res= open_and_lock_tables(thd, table_list);
465
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
466 467
  }
  else
468
#endif /* EMBEDDED_LIBRARY */
469
    res= open_and_lock_tables(thd, table_list);
470
  if (res || thd->is_fatal_error)
471
    DBUG_RETURN(TRUE);
472

bk@work.mysql.com's avatar
bk@work.mysql.com committed
473
  thd->proc_info="init";
474
  thd->used_tables=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
475
  values= its++;
476

monty@mysql.com's avatar
monty@mysql.com committed
477
  if (mysql_prepare_insert(thd, table_list, table, fields, values,
monty@mysql.com's avatar
monty@mysql.com committed
478 479
			   update_fields, update_values, duplic, &unused_conds,
                           FALSE))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
480
    goto abort;
481

482 483 484
  /* mysql_prepare_insert set table_list->table if it was not set */
  table= table_list->table;

485
  context= &thd->lex->select_lex.context;
486 487 488 489 490 491 492 493 494
  /*
    These three asserts test the hypothesis that the resetting of the name
    resolution context below is not necessary at all since the list of local
    tables for INSERT always consists of one table.
  */
  DBUG_ASSERT(!table_list->next_local);
  DBUG_ASSERT(!context->table_list->next_local);
  DBUG_ASSERT(!context->first_name_resolution_table->next_name_resolution_table);

495
  /* Save the state of the current name resolution context. */
496
  ctx_state.save_state(context, table_list);
497 498 499 500 501

  /*
    Perform name resolution only in the first table - 'table_list',
    which is the table that is inserted into.
  */
502
  table_list->next_local= 0;
503 504
  context->resolve_in_table_list_only(table_list);

bk@work.mysql.com's avatar
bk@work.mysql.com committed
505
  value_count= values->elements;
506
  while ((values= its++))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
507 508 509 510
  {
    counter++;
    if (values->elements != value_count)
    {
511
      my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), counter);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
512 513
      goto abort;
    }
514
    if (setup_fields(thd, 0, *values, 0, 0, 0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
515 516 517
      goto abort;
  }
  its.rewind ();
518 519
 
  /* Restore the current context. */
520
  ctx_state.restore_state(context, table_list);
521

bk@work.mysql.com's avatar
bk@work.mysql.com committed
522
  /*
523
    Fill in the given fields and dump it to the table file
bk@work.mysql.com's avatar
bk@work.mysql.com committed
524
  */
525
  info.records= info.deleted= info.copied= info.updated= info.touched= 0;
526
  info.ignore= ignore;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
527
  info.handle_duplicates=duplic;
528 529
  info.update_fields= &update_fields;
  info.update_values= &update_values;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
530
  info.view= (table_list->view ? table_list : 0);
531

532 533 534
  /*
    Count warnings for all inserts.
    For single line insert, generate an error if try to set a NOT NULL field
535
    to NULL.
536
  */
537
  thd->count_cuted_fields= ((values_list.elements == 1 &&
monty@mysql.com's avatar
monty@mysql.com committed
538
                             !ignore) ?
539 540
			    CHECK_FIELD_ERROR_FOR_NULL :
			    CHECK_FIELD_WARN);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
541 542 543
  thd->cuted_fields = 0L;
  table->next_number_field=table->found_next_number_field;

guilhem@gbichot3.local's avatar
guilhem@gbichot3.local committed
544 545 546 547 548 549 550 551
#ifdef HAVE_REPLICATION
  if (thd->slave_thread &&
      (info.handle_duplicates == DUP_UPDATE) &&
      (table->next_number_field != NULL) &&
      rpl_master_has_bug(&active_mi->rli, 24432))
    goto abort;
#endif

bk@work.mysql.com's avatar
bk@work.mysql.com committed
552 553 554
  error=0;
  id=0;
  thd->proc_info="update";
555
  if (duplic != DUP_ERROR || ignore)
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
556
    table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
557 558 559 560 561 562 563 564 565 566 567
  if (duplic == DUP_REPLACE)
  {
    if (!table->triggers || !table->triggers->has_delete_triggers())
      table->file->extra(HA_EXTRA_WRITE_CAN_REPLACE);
    /*
      REPLACE should change values of all columns so we should mark
      all columns as columns to be set. As nice side effect we will
      retrieve columns which values are needed for ON DELETE triggers.
    */
    table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
  }
568 569 570 571
  /*
    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.
572 573 574 575
    We should not start bulk inserts if this statement uses
    functions or invokes triggers since they may access
    to the same table and therefore should not see its
    inconsistent state created by this optimization.
576 577 578 579
    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.
  */
580
  if (lock_type != TL_WRITE_DELAYED && !thd->prelocked_mode)
581
    table->file->start_bulk_insert(values_list.elements);
582

583
  thd->no_trans_update= 0;
monty@mysql.com's avatar
monty@mysql.com committed
584
  thd->abort_on_warning= (!ignore &&
585 586 587 588
                          (thd->variables.sql_mode &
                           (MODE_STRICT_TRANS_TABLES |
                            MODE_STRICT_ALL_TABLES)));

589
  if ((fields.elements || !value_count) &&
590
      check_that_all_fields_are_given_values(thd, table, table_list))
591 592 593 594 595
  {
    /* thd->net.report_error is now set, which will abort the next loop */
    error= 1;
  }

596 597
  mark_fields_used_by_triggers_for_insert_stmt(thd, table, duplic);

598 599 600 601
  if (table_list->prepare_where(thd, 0, TRUE) ||
      table_list->prepare_check_option(thd))
    error= 1;

602
  while ((values= its++))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
603 604 605
  {
    if (fields.elements || !value_count)
    {
606
      restore_record(table,s->default_values);	// Get empty record
607 608 609
      if (fill_record_n_invoke_before_triggers(thd, fields, *values, 0,
                                               table->triggers,
                                               TRG_EVENT_INSERT))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
610
      {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
611
	if (values_list.elements != 1 && !thd->net.report_error)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
612 613 614 615
	{
	  info.records++;
	  continue;
	}
616 617 618 619 620
	/*
	  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.
        */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
621 622 623 624 625 626
	error=1;
	break;
      }
    }
    else
    {
627
      if (thd->used_tables)			// Column used in values()
628
	restore_record(table,s->default_values);	// Get empty record
629
      else
630 631 632 633 634 635 636 637 638 639 640
      {
        /*
          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))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
641
      {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
642
	if (values_list.elements != 1 && ! thd->net.report_error)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
643 644 645 646 647 648 649 650
	{
	  info.records++;
	  continue;
	}
	error=1;
	break;
      }
    }
651

652 653 654
    if ((res= table_list->view_check_option(thd,
					    (values_list.elements == 1 ?
					     0 :
655
					     ignore))) ==
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
656 657 658
        VIEW_CHECK_SKIP)
      continue;
    else if (res == VIEW_CHECK_ERROR)
659
    {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
660 661
      error= 1;
      break;
662
    }
663
#ifndef EMBEDDED_LIBRARY
664
    if (lock_type == TL_WRITE_DELAYED)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
665
    {
666
      error=write_delayed(thd, table, duplic, ignore, query, thd->query_length, log_on);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
667 668 669
      query=0;
    }
    else
670
#endif
671
      error=write_record(thd, table ,&info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
672
    /*
673 674
      If auto_increment values are used, save the first one for
      LAST_INSERT_ID() and for the update log.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
675 676 677 678 679
    */
    if (! id && thd->insert_id_used)
    {						// Get auto increment value
      id= thd->last_insert_id;
    }
680 681
    if (error)
      break;
682
    thd->row_count++;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
683
  }
684

685 686 687
  free_underlaid_joins(thd, &thd->lex->select_lex);
  joins_freed= TRUE;

688 689 690 691
  /*
    Now all rows are inserted.  Time to update logs and sends response to
    user
  */
692
#ifndef EMBEDDED_LIBRARY
bk@work.mysql.com's avatar
bk@work.mysql.com committed
693 694
  if (lock_type == TL_WRITE_DELAYED)
  {
695 696 697 698 699 700
    if (!error)
    {
      id=0;					// No auto_increment id
      info.copied=values_list.elements;
      end_delayed_insert(thd);
    }
701
    query_cache_invalidate3(thd, table_list, 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
702 703
  }
  else
704
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
705
  {
706
    if (!thd->prelocked_mode && table->file->end_bulk_insert() && !error)
707
    {
serg@serg.mylan's avatar
serg@serg.mylan committed
708 709
      table->file->print_error(my_errno,MYF(0));
      error=1;
710
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
711 712
    if (id && values_list.elements != 1)
      thd->insert_id(id);			// For update log
713
    else if (table->next_number_field && info.copied)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
714
      id=table->next_number_field->val_int();	// Return auto_increment value
715

716
    transactional_table= table->file->has_transactions();
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
717

718
    if ((changed= (info.copied || info.deleted || info.updated)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
719
    {
720 721 722 723 724 725 726
      /*
        Invalidate the table in the query cache if something changed.
        For the transactional algorithm to work the invalidation must be
        before binlog writing and ha_autocommit_or_rollback
      */
      query_cache_invalidate3(thd, table_list, 1);
      if (error <= 0 || !transactional_table)
727
      {
728 729 730 731 732 733 734 735 736 737 738
        if (mysql_bin_log.is_open())
        {
          if (error <= 0)
            thd->clear_error();
          Query_log_event qinfo(thd, thd->query, thd->query_length,
                                transactional_table, FALSE);
          if (mysql_bin_log.write(&qinfo) && transactional_table)
            error=1;
        }
        if (!transactional_table)
          thd->options|=OPTION_STATUS_NO_TRANS_UPDATE;
739
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
740
    }
741
    if (transactional_table)
742
      error=ha_autocommit_or_rollback(thd,error);
743

bk@work.mysql.com's avatar
bk@work.mysql.com committed
744 745 746
    if (thd->lock)
    {
      mysql_unlock_tables(thd, thd->lock);
747 748 749 750 751 752 753 754 755 756
      /*
        Invalidate the table in the query cache if something changed
        after unlocking when changes become fisible.
        TODO: this is workaround. right way will be move invalidating in
        the unlock procedure.
      */
      if (lock_type ==  TL_WRITE_CONCURRENT_INSERT && changed)
      {
        query_cache_invalidate3(thd, table_list, 1);
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
757 758 759 760 761
      thd->lock=0;
    }
  }
  thd->proc_info="end";
  table->next_number_field=0;
762
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
763
  thd->next_insert_id=0;			// Reset this if wrongly used
764
  if (duplic != DUP_ERROR || ignore)
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
765
    table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
766 767 768
  if (duplic == DUP_REPLACE &&
      (!table->triggers || !table->triggers->has_delete_triggers()))
    table->file->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
769

770 771
  /* Reset value of LAST_INSERT_ID if no rows were inserted or touched */
  if (!info.copied && !info.touched && thd->insert_id_used)
772 773 774 775
  {
    thd->insert_id(0);
    id=0;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
776 777 778 779
  if (error)
    goto abort;
  if (values_list.elements == 1 && (!(thd->options & OPTION_WARNINGS) ||
				    !thd->cuted_fields))
780 781
  {
    thd->row_count_func= info.copied+info.deleted+info.updated;
782
    send_ok(thd, (ulong) thd->row_count_func, id);
783
  }
784 785
  else
  {
bk@work.mysql.com's avatar
bk@work.mysql.com committed
786
    char buff[160];
787
    if (ignore)
788 789 790
      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);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
791
    else
792
      sprintf(buff, ER(ER_INSERT_INFO), (ulong) info.records,
monty@mysql.com's avatar
monty@mysql.com committed
793
	      (ulong) (info.deleted+info.updated), (ulong) thd->cuted_fields);
794
    thd->row_count_func= info.copied+info.deleted+info.updated;
795
    ::send_ok(thd, (ulong) thd->row_count_func, id, buff);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
796
  }
797
  thd->abort_on_warning= 0;
798
  DBUG_RETURN(FALSE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
799 800

abort:
801
#ifndef EMBEDDED_LIBRARY
bk@work.mysql.com's avatar
bk@work.mysql.com committed
802 803
  if (lock_type == TL_WRITE_DELAYED)
    end_delayed_insert(thd);
804
#endif
805 806
  if (!joins_freed)
    free_underlaid_joins(thd, &thd->lex->select_lex);
807
  thd->abort_on_warning= 0;
808
  DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
809 810 811
}


bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
812 813 814 815 816
/*
  Additional check for insertability for VIEW

  SYNOPSIS
    check_view_insertability()
817
    thd     - thread handler
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
818 819
    view    - reference on VIEW

820 821 822 823 824 825
  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)

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
826 827
  RETURN
    FALSE - OK
828 829 830
      view->contain_auto_increment is 1 if and only if the view contains an
      auto_increment field

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
831 832 833
    TRUE  - can't be used for insert
*/

834
static bool check_view_insertability(THD * thd, TABLE_LIST *view)
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
835
{
836
  uint num= view->view->select_lex.item_list.elements;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
837
  TABLE *table= view->table;
838 839 840
  Field_translator *trans_start= view->field_translation,
		   *trans_end= trans_start + num;
  Field_translator *trans;
841 842 843
  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;
844
  bool save_set_query_id= thd->set_query_id;
845 846
  DBUG_ENTER("check_key_in_view");

847 848 849
  if (!used_fields_buff)
    DBUG_RETURN(TRUE);  // EOM

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
850 851
  DBUG_ASSERT(view->table != 0 && view->field_translation != 0);

852 853
  VOID(bitmap_init(&used_fields, used_fields_buff, used_fields_buff_size * 8,
                   0));
854 855
  bitmap_clear_all(&used_fields);

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
856
  view->contain_auto_increment= 0;
857 858 859 860 861
  /* 
    we must not set query_id for fields as they're not 
    really used in this context
  */
  thd->set_query_id= 0;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
862
  /* check simplicity and prepare unique test of view */
863
  for (trans= trans_start; trans != trans_end; trans++)
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
864
  {
865
    if (!trans->item->fixed && trans->item->fix_fields(thd, &trans->item))
866 867 868 869
    {
      thd->set_query_id= save_set_query_id;
      DBUG_RETURN(TRUE);
    }
870
    Item_field *field;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
871
    /* simple SELECT list entry (field without expression) */
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
872
    if (!(field= trans->item->filed_for_view_update()))
873 874
    {
      thd->set_query_id= save_set_query_id;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
875
      DBUG_RETURN(TRUE);
876
    }
877
    if (field->field->unireg_check == Field::NEXT_NUMBER)
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
878 879
      view->contain_auto_increment= 1;
    /* prepare unique test */
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
880 881 882 883 884
    /*
      remove collation (or other transparent for update function) if we have
      it
    */
    trans->item= field;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
885
  }
886
  thd->set_query_id= save_set_query_id;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
887
  /* unique test */
888
  for (trans= trans_start; trans != trans_end; trans++)
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
889
  {
890
    /* Thanks to test above, we know that all columns are of type Item_field */
891
    Item_field *field= (Item_field *)trans->item;
892 893 894
    /* 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))
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
895 896 897 898 899 900 901
      DBUG_RETURN(TRUE);
  }

  DBUG_RETURN(FALSE);
}


bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
902
/*
903
  Check if table can be updated
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
904 905

  SYNOPSIS
906 907
     mysql_prepare_insert_check_table()
     thd		Thread handle
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
908
     table_list		Table list
909 910
     fields		List of fields to be updated
     where		Pointer to where clause
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
911
     select_insert      Check is making for SELECT ... INSERT
912 913

   RETURN
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
914 915
     FALSE ok
     TRUE  ERROR
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
916
*/
917

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
918 919 920
static bool mysql_prepare_insert_check_table(THD *thd, TABLE_LIST *table_list,
                                             List<Item> &fields, COND **where,
                                             bool select_insert)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
921
{
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
922
  bool insert_into_view= (table_list->view != 0);
923
  DBUG_ENTER("mysql_prepare_insert_check_table");
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
924

925 926 927 928 929 930 931
  /*
     first table in list is the one we'll INSERT into, requires INSERT_ACL.
     all others require SELECT_ACL only. the ACL requirement below is for
     new leaves only anyway (view-constituents), so check for SELECT rather
     than INSERT.
  */

932 933 934 935
  if (setup_tables_and_check_access(thd, &thd->lex->select_lex.context,
                                    &thd->lex->select_lex.top_join_list,
                                    table_list, where, 
                                    &thd->lex->select_lex.leaf_tables,
936
                                    select_insert, INSERT_ACL, SELECT_ACL))
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
937
    DBUG_RETURN(TRUE);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
938 939 940 941

  if (insert_into_view && !fields.elements)
  {
    thd->lex->empty_field_list_on_rset= 1;
942 943 944 945
    if (!table_list->table)
    {
      my_error(ER_VIEW_NO_INSERT_FIELD_LIST, MYF(0),
               table_list->view_db.str, table_list->view_name.str);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
946
      DBUG_RETURN(TRUE);
947
    }
948
    DBUG_RETURN(insert_view_fields(thd, &fields, table_list));
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
949 950
  }

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
951
  DBUG_RETURN(FALSE);
952 953 954 955 956 957 958 959 960 961
}


/*
  Prepare items in INSERT statement

  SYNOPSIS
    mysql_prepare_insert()
    thd			Thread handler
    table_list	        Global/local table list
monty@mysql.com's avatar
monty@mysql.com committed
962 963
    table		Table to insert into (can be NULL if table should
			be taken from table_list->table)    
monty@mysql.com's avatar
monty@mysql.com committed
964 965
    where		Where clause (for insert ... select)
    select_insert	TRUE if INSERT ... SELECT statement
966

monty@mishka.local's avatar
monty@mishka.local committed
967 968 969 970 971
  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
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
972

973 974 975
  WARNING
    You MUST set table->insert_values to 0 after calling this function
    before releasing the table object.
monty@mysql.com's avatar
monty@mysql.com committed
976
  
977
  RETURN VALUE
978 979
    FALSE OK
    TRUE  error
980 981
*/

monty@mysql.com's avatar
monty@mysql.com committed
982
bool mysql_prepare_insert(THD *thd, TABLE_LIST *table_list,
monty@mysql.com's avatar
monty@mysql.com committed
983
                          TABLE *table, List<Item> &fields, List_item *values,
monty@mishka.local's avatar
monty@mishka.local committed
984
                          List<Item> &update_fields, List<Item> &update_values,
monty@mysql.com's avatar
monty@mysql.com committed
985 986
                          enum_duplicates duplic,
                          COND **where, bool select_insert)
987
{
monty@mysql.com's avatar
monty@mysql.com committed
988
  SELECT_LEX *select_lex= &thd->lex->select_lex;
989
  Name_resolution_context *context= &select_lex->context;
990
  Name_resolution_context_state ctx_state;
991
  bool insert_into_view= (table_list->view != 0);
monty@mysql.com's avatar
monty@mysql.com committed
992
  bool res= 0;
993
  table_map map= 0;
994
  DBUG_ENTER("mysql_prepare_insert");
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
995 996 997
  DBUG_PRINT("enter", ("table_list 0x%lx, table 0x%lx, view %d",
		       (ulong)table_list, (ulong)table,
		       (int)insert_into_view));
998 999
  /* INSERT should have a SELECT or VALUES clause */
  DBUG_ASSERT (!select_insert || !values);
monty@mishka.local's avatar
monty@mishka.local committed
1000

1001 1002 1003 1004 1005 1006 1007
  /*
    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)
  {
monty@mysql.com's avatar
monty@mysql.com committed
1008
    for (SELECT_LEX_UNIT *un= select_lex->first_inner_unit();
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
         un;
         un= un->next_unit())
    {
      for (SELECT_LEX *sl= un->first_select();
           sl;
           sl= sl->next_select())
      {
        sl->context.outer_context= 0;
      }
    }
  }

monty@mishka.local's avatar
monty@mishka.local committed
1021
  if (duplic == DUP_UPDATE)
1022 1023
  {
    /* it should be allocated before Item::fix_fields() */
monty@mishka.local's avatar
monty@mishka.local committed
1024
    if (table_list->set_insert_values(thd->mem_root))
monty@mysql.com's avatar
monty@mysql.com committed
1025
      DBUG_RETURN(TRUE);
1026
  }
monty@mishka.local's avatar
monty@mishka.local committed
1027

monty@mysql.com's avatar
monty@mysql.com committed
1028 1029
  if (mysql_prepare_insert_check_table(thd, table_list, fields, where,
                                       select_insert))
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1030
    DBUG_RETURN(TRUE);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
1031

1032 1033

  /* Prepare the fields in the statement. */
1034
  if (values)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1035
  {
1036 1037 1038 1039 1040 1041
    /* if we have INSERT ... VALUES () we cannot have a GROUP BY clause */
    DBUG_ASSERT (!select_lex->group_list.elements);

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

1042
    /*
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
      Perform name resolution only in the first table - 'table_list',
      which is the table that is inserted into.
     */
    table_list->next_local= 0;
    context->resolve_in_table_list_only(table_list);

    if (!(res= check_insert_fields(thd, context->table_list, fields, *values,
                                 !insert_into_view, &map) ||
          setup_fields(thd, 0, *values, 0, 0, 0)) 
        && duplic == DUP_UPDATE)
monty@mysql.com's avatar
monty@mysql.com committed
1053
    {
1054 1055 1056
      select_lex->no_wrap_view_item= TRUE;
      res= check_update_fields(thd, context->table_list, update_fields, &map);
      select_lex->no_wrap_view_item= FALSE;
monty@mysql.com's avatar
monty@mysql.com committed
1057
    }
1058 1059 1060 1061

    /* Restore the current context. */
    ctx_state.restore_state(context, table_list);

monty@mysql.com's avatar
monty@mysql.com committed
1062 1063
    if (!res)
      res= setup_fields(thd, 0, update_values, 1, 0, 0);
monty@mysql.com's avatar
monty@mysql.com committed
1064
  }
1065

monty@mysql.com's avatar
monty@mysql.com committed
1066 1067 1068
  if (res)
    DBUG_RETURN(res);

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1069 1070 1071
  if (!table)
    table= table_list->table;

1072
  if (!select_insert)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1073
  {
1074
    Item *fake_conds= 0;
1075
    TABLE_LIST *duplicate;
1076
    if ((duplicate= unique_table(thd, table_list, table_list->next_global, 1)))
1077
    {
1078
      update_non_unique_table_error(table_list, "INSERT", duplicate);
1079 1080
      DBUG_RETURN(TRUE);
    }
1081
    select_lex->fix_prepare_information(thd, &fake_conds, &fake_conds);
monty@mysql.com's avatar
monty@mysql.com committed
1082
    select_lex->first_execution= 0;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1083
  }
1084 1085
  if (duplic == DUP_UPDATE || duplic == DUP_REPLACE)
    table->file->extra(HA_EXTRA_RETRIEVE_PRIMARY_KEY);
1086
  DBUG_RETURN(FALSE);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1087 1088 1089
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
1090 1091 1092 1093
	/* Check if there is more uniq keys after field */

static int last_uniq_key(TABLE *table,uint keynr)
{
1094
  while (++keynr < table->s->keys)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1095 1096 1097 1098 1099 1100 1101
    if (table->key_info[keynr].flags & HA_NOSAME)
      return 0;
  return 1;
}


/*
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
  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.
1112

1113 1114 1115 1116 1117
  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.
1118

1119 1120 1121 1122 1123 1124
    Sets thd->no_trans_update if table which is updated didn't have
    transactions.

  RETURN VALUE
    0     - success
    non-0 - error
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1125 1126 1127
*/


1128
int write_record(THD *thd, TABLE *table,COPY_INFO *info)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1129
{
1130
  int error, trg_error= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1131
  char *key=0;
1132
  DBUG_ENTER("write_record");
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1133

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1134
  info->records++;
1135 1136
  if (info->handle_duplicates == DUP_REPLACE ||
      info->handle_duplicates == DUP_UPDATE)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1137 1138 1139
  {
    while ((error=table->file->write_row(table->record[0])))
    {
1140
      uint key_nr;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1141
      if (error != HA_WRITE_SKIP)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1142 1143 1144
	goto err;
      if ((int) (key_nr = table->file->get_dup_key(error)) < 0)
      {
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1145
	error=HA_WRITE_SKIP;			/* Database can't find key */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1146 1147
	goto err;
      }
1148 1149 1150 1151 1152
      /*
	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.
      */
1153 1154
      if (info->handle_duplicates == DUP_REPLACE &&
          table->next_number_field &&
1155
          key_nr == table->s->next_number_index &&
1156 1157
	  table->file->auto_increment_column_changed)
	goto err;
1158
      if (table->file->table_flags() & HA_DUPP_POS)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1159 1160 1161 1162 1163 1164
      {
	if (table->file->rnd_pos(table->record[1],table->file->dupp_ref))
	  goto err;
      }
      else
      {
1165
	if (table->file->extra(HA_EXTRA_FLUSH_CACHE)) /* Not needed with NISAM */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1166 1167 1168 1169
	{
	  error=my_errno;
	  goto err;
	}
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1170

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1171 1172
	if (!key)
	{
1173
	  if (!(key=(char*) my_safe_alloca(table->s->max_unique_length,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1174 1175 1176 1177 1178 1179
					   MAX_KEY_LENGTH)))
	  {
	    error=ENOMEM;
	    goto err;
	  }
	}
1180
	key_copy((byte*) key,table->record[0],table->key_info+key_nr,0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1181
	if ((error=(table->file->index_read_idx(table->record[1],key_nr,
1182
						(byte*) key,
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1183 1184
						table->key_info[key_nr].
						key_length,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1185 1186 1187
						HA_READ_KEY_EXACT))))
	  goto err;
      }
1188
      if (info->handle_duplicates == DUP_UPDATE)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1189
      {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1190
        int res= 0;
monty@mysql.com's avatar
monty@mysql.com committed
1191 1192 1193 1194
        /*
          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
1195
        */
1196
	DBUG_ASSERT(table->insert_values != NULL);
1197 1198
        store_record(table,insert_values);
        restore_record(table,record[1]);
monty@mysql.com's avatar
monty@mysql.com committed
1199 1200
        DBUG_ASSERT(info->update_fields->elements ==
                    info->update_values->elements);
1201 1202 1203 1204 1205
        if (fill_record_n_invoke_before_triggers(thd, *info->update_fields,
                                                 *info->update_values, 0,
                                                 table->triggers,
                                                 TRG_EVENT_UPDATE))
          goto before_trg_err;
1206 1207

        /* CHECK OPTION for VIEW ... ON DUPLICATE KEY UPDATE ... */
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1208 1209 1210
        if (info->view &&
            (res= info->view->view_check_option(current_thd, info->ignore)) ==
            VIEW_CHECK_SKIP)
1211
          goto ok_or_after_trg_err;
monty@mysql.com's avatar
monty@mysql.com committed
1212
        if (res == VIEW_CHECK_ERROR)
1213
          goto before_trg_err;
1214

guilhem@gbichot3.local's avatar
guilhem@gbichot3.local committed
1215
        table->file->restore_auto_increment();
1216
        if ((error=table->file->update_row(table->record[1],table->record[0])))
1217 1218
        {
          if ((error == HA_ERR_FOUND_DUPP_KEY) && info->ignore)
1219
          {
1220
            goto ok_or_after_trg_err;
1221
          }
1222
          goto err;
1223
        }
1224 1225 1226 1227 1228 1229

        if (table->next_number_field)
          table->file->adjust_next_insert_id_after_explicit_value(
            table->next_number_field->val_int());
        info->touched++;

1230
        if ((table->file->table_flags() & HA_PARTIAL_COLUMN_READ) ||
1231
            compare_record(table, thd->query_id))
1232 1233
        {
          info->updated++;
1234

1235 1236 1237 1238 1239 1240
          trg_error= (table->triggers &&
                      table->triggers->process_triggers(thd, TRG_EVENT_UPDATE,
                                                        TRG_ACTION_AFTER,
                                                        TRUE));
          info->copied++;
        }
1241
        goto ok_or_after_trg_err;
1242 1243 1244
      }
      else /* DUP_REPLACE */
      {
monty@mysql.com's avatar
monty@mysql.com committed
1245 1246 1247 1248 1249
	/*
	  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.
1250 1251
          We also should not perform this conversion if we have 
          timestamp field with ON UPDATE which is different from DEFAULT.
1252 1253 1254 1255 1256 1257
          Another case when conversion should not be performed is when
          we have ON DELETE trigger on table so user may notice that
          we cheat here. Note that it is ok to do such conversion for
          tables which have ON UPDATE but have no ON DELETE triggers,
          we just should not expose this fact to users by invoking
          ON UPDATE triggers.
monty@mysql.com's avatar
monty@mysql.com committed
1258 1259
	*/
	if (last_uniq_key(table,key_nr) &&
1260
	    !table->file->referenced_by_foreign_key() &&
1261
            (table->timestamp_field_type == TIMESTAMP_NO_AUTO_SET ||
1262 1263
             table->timestamp_field_type == TIMESTAMP_AUTO_SET_ON_BOTH) &&
            (!table->triggers || !table->triggers->has_delete_triggers()))
1264
        {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1265 1266
          if ((error=table->file->update_row(table->record[1],
					     table->record[0])))
1267 1268
            goto err;
          info->deleted++;
1269 1270 1271 1272 1273
          /*
            Since we pretend that we have done insert we should call
            its after triggers.
          */
          goto after_trg_n_copied_inc;
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
        }
        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 */
1294
        }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1295 1296 1297 1298 1299
      }
    }
  }
  else if ((error=table->file->write_row(table->record[0])))
  {
1300
    if (!info->ignore ||
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1301 1302
	(error != HA_ERR_FOUND_DUPP_KEY && error != HA_ERR_FOUND_DUPP_UNIQUE))
      goto err;
1303
    table->file->restore_auto_increment();
1304
    goto ok_or_after_trg_err;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1305
  }
1306 1307 1308 1309 1310 1311

after_trg_n_copied_inc:
  info->copied++;
  trg_error= (table->triggers &&
              table->triggers->process_triggers(thd, TRG_EVENT_INSERT,
                                                TRG_ACTION_AFTER, TRUE));
1312 1313

ok_or_after_trg_err:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1314
  if (key)
1315
    my_safe_afree(key,table->s->max_unique_length,MAX_KEY_LENGTH);
1316 1317
  if (!table->file->has_transactions())
    thd->no_trans_update= 1;
1318
  DBUG_RETURN(trg_error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1319 1320

err:
1321
  info->last_errno= error;
1322 1323 1324
  /* current_select is NULL if this is a delayed insert */
  if (thd->lex->current_select)
    thd->lex->current_select->no_error= 0;        // Give error
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1325
  table->file->print_error(error,MYF(0));
1326 1327

before_trg_err:
1328
  table->file->restore_auto_increment();
1329 1330
  if (key)
    my_safe_afree(key, table->s->max_unique_length, MAX_KEY_LENGTH);
1331
  DBUG_RETURN(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1332 1333 1334 1335
}


/******************************************************************************
1336
  Check that all fields with arn't null_fields are used
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1337 1338
******************************************************************************/

1339 1340
int check_that_all_fields_are_given_values(THD *thd, TABLE *entry,
                                           TABLE_LIST *table_list)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1341
{
1342
  int err= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1343 1344
  for (Field **field=entry->field ; *field ; field++)
  {
1345
    if ((*field)->query_id != thd->query_id &&
1346 1347
        ((*field)->flags & NO_DEFAULT_VALUE_FLAG) &&
        ((*field)->real_type() != FIELD_TYPE_ENUM))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1348
    {
1349 1350 1351
      bool view= FALSE;
      if (table_list)
      {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1352
        table_list= table_list->top_table();
kent@mysql.com's avatar
kent@mysql.com committed
1353
        view= test(table_list->view);
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
      }
      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);
      }
1370
      err= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1371 1372
    }
  }
1373
  return thd->abort_on_warning ? err : 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1374 1375 1376
}

/*****************************************************************************
1377 1378
  Handling of delayed inserts
  A thread is created for each table that one uses with the DELAYED attribute.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1379 1380
*****************************************************************************/

1381 1382
#ifndef EMBEDDED_LIBRARY

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1383 1384 1385 1386 1387
class delayed_row :public ilink {
public:
  char *record,*query;
  enum_duplicates dup;
  time_t start_time;
1388
  bool query_start_used,last_insert_id_used,insert_id_used, ignore, log_query;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1389
  ulonglong last_insert_id;
1390 1391 1392
  ulonglong next_insert_id;
  ulong auto_increment_increment;
  ulong auto_increment_offset;
1393
  timestamp_auto_set_type timestamp_field_type;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1394 1395
  uint query_length;

1396 1397
  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) {}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
  ~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;
1416
  ulong group_count;
1417
  TABLE_LIST table_list;			// Argument
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1418 1419 1420 1421 1422 1423

  delayed_insert()
    :locks_in_memory(0),
     table(0),tables_in_use(0),stacked_inserts(0), status(0), dead(0),
     group_count(0)
  {
1424 1425
    thd.security_ctx->user=thd.security_ctx->priv_user=(char*) delayed_user;
    thd.security_ctx->host=(char*) my_localhost;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1426 1427 1428
    thd.current_tablenr=0;
    thd.version=refresh_version;
    thd.command=COM_DELAYED_INSERT;
1429 1430
    thd.lex->current_select= 0; 		// for my_message_sql
    thd.lex->sql_command= SQLCOM_INSERT;        // For innodb::store_lock()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1431

1432 1433
    bzero((char*) &thd.net, sizeof(thd.net));		// Safety
    bzero((char*) &table_list, sizeof(table_list));	// Safety
1434
    thd.system_thread= SYSTEM_THREAD_DELAYED_INSERT;
1435
    thd.security_ctx->host_or_ip= "";
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1436
    bzero((char*) &info,sizeof(info));
1437
    pthread_mutex_init(&mutex,MY_MUTEX_INIT_FAST);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1438 1439 1440 1441 1442 1443 1444 1445
    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()
  {
1446
    /* The following is not really needed, but just for safety */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1447 1448 1449 1450 1451 1452
    delayed_row *row;
    while ((row=rows.get()))
      delete row;
    if (table)
      close_thread_tables(&thd);
    VOID(pthread_mutex_lock(&LOCK_thread_count));
1453 1454 1455
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);
    pthread_cond_destroy(&cond_client);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1456 1457
    thd.unlink();				// Must be unlinked under lock
    x_free(thd.query);
1458
    thd.security_ctx->user= thd.security_ctx->host=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1459 1460 1461
    thread_count--;
    delayed_insert_threads--;
    VOID(pthread_mutex_unlock(&LOCK_thread_count));
1462
    VOID(pthread_cond_broadcast(&COND_thread_count)); /* Tell main we are ready */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
  }

  /* 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) &&
1504
	!strcmp(table_list->table_name,tmp->table->s->table_name))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
    {
      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;
1519
  TABLE *table;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1520 1521
  DBUG_ENTER("delayed_get_table");

1522 1523
  /* Must be set in the parser */
  DBUG_ASSERT(table_list->db);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1524

1525
  /* Find the thread which handles this table. */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1526 1527
  if (!(tmp=find_handler(thd,table_list)))
  {
1528 1529 1530 1531
    /*
      No match. Create a new thread to handle the table, but
      no more than max_insert_delayed_threads.
    */
1532
    if (delayed_insert_threads >= thd->variables.max_insert_delayed_threads)
1533
      DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1534 1535
    thd->proc_info="Creating delayed handler";
    pthread_mutex_lock(&LOCK_delayed_create);
1536 1537 1538 1539 1540
    /*
      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)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1541 1542 1543 1544
    {
      if (!(tmp=new delayed_insert()))
      {
	my_error(ER_OUTOFMEMORY,MYF(0),sizeof(delayed_insert));
1545
	goto err1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1546
      }
1547 1548 1549
      pthread_mutex_lock(&LOCK_thread_count);
      thread_count++;
      pthread_mutex_unlock(&LOCK_thread_count);
1550 1551 1552
      tmp->thd.set_db(table_list->db, strlen(table_list->db));
      tmp->thd.query= my_strdup(table_list->table_name,MYF(MY_WME));
      if (tmp->thd.db == NULL || tmp->thd.query == NULL)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1553 1554
      {
	delete tmp;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1555
	my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES), MYF(0));
1556
	goto err1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1557
      }
1558
      tmp->table_list= *table_list;			// Needed to open table
1559
      tmp->table_list.alias= tmp->table_list.table_name= tmp->thd.query;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
      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;
1571
	my_error(ER_CANT_CREATE_THREAD, MYF(0), error);
1572
	goto err1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584
      }

      /* Wait until table is open */
      thd->proc_info="waiting for handler open";
      while (!tmp->thd.killed && !tmp->table && !thd->killed)
      {
	pthread_cond_wait(&tmp->cond_client,&tmp->mutex);
      }
      pthread_mutex_unlock(&tmp->mutex);
      thd->proc_info="got old table";
      if (tmp->thd.killed)
      {
1585
	if (tmp->thd.is_fatal_error)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1586 1587
	{
	  /* Copy error message and abort */
1588
	  thd->fatal_error();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1589
	  strmov(thd->net.last_error,tmp->thd.net.last_error);
1590
	  thd->net.last_errno=tmp->thd.net.last_errno;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1591 1592
	}
	tmp->unlock();
1593
	goto err;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1594 1595 1596 1597
      }
      if (thd->killed)
      {
	tmp->unlock();
1598
	goto err;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1599 1600 1601 1602 1603 1604
      }
    }
    pthread_mutex_unlock(&LOCK_delayed_create);
  }

  pthread_mutex_lock(&tmp->mutex);
1605
  table= tmp->get_local_table(thd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1606 1607 1608
  pthread_mutex_unlock(&tmp->mutex);
  if (table)
    thd->di=tmp;
1609 1610
  else if (tmp->thd.is_fatal_error)
    thd->fatal_error();
1611 1612
  /* Unlock the delayed insert object after its last access. */
  tmp->unlock();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1613
  DBUG_RETURN((table_list->table=table));
1614 1615 1616 1617 1618 1619

 err1:
  thd->fatal_error();
 err:
  pthread_mutex_unlock(&LOCK_delayed_create);
  DBUG_RETURN(0); // Continue with normal insert
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632
}


/*
  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;
1633
  Field **field,**org_field, *found_next_number_field;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1634
  TABLE *copy;
1635
  DBUG_ENTER("delayed_insert::get_local_table");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658

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

1659 1660 1661 1662 1663 1664 1665
  /*
    Allocate memory for the TABLE object, the field pointers array, and
    one record buffer of reclength size. Normally a table has three
    record buffers of rec_buff_length size, which includes alignment
    bytes. Since the table copy is used for creating one record only,
    the other record buffers and alignment are unnecessary.
  */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1666
  client_thd->proc_info="allocating local table";
1667
  copy= (TABLE*) client_thd->alloc(sizeof(*copy)+
1668 1669
				   (table->s->fields+1)*sizeof(Field**)+
				   table->s->reclength);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1670 1671
  if (!copy)
    goto error;
1672 1673

  /* Copy the TABLE object. */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1674
  *copy= *table;
1675 1676 1677
  copy->s= &copy->share_not_to_be_used;
  // No name hashing
  bzero((char*) &copy->s->name_hash,sizeof(copy->s->name_hash));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1678 1679
  /* We don't need to change the file handler here */

1680 1681 1682 1683 1684
  /* Assign the pointers for the field pointers array and the record. */
  field= copy->field= (Field**) (copy + 1);
  copy->record[0]= (byte*) (field + table->s->fields + 1);
  memcpy((char*) copy->record[0], (char*) table->record[0],
         table->s->reclength);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1685

1686 1687 1688 1689 1690 1691 1692 1693
  /*
    Make a copy of all fields.
    The copied fields need to point into the copied record. This is done
    by copying the field objects with their old pointer values and then
    "move" the pointers by the distance between the original and copied
    records. That way we preserve the relative positions in the records.
  */
  adjust_ptrs= PTR_BYTE_DIFF(copy->record[0], table->record[0]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1694

1695 1696
  found_next_number_field= table->found_next_number_field;
  for (org_field= table->field; *org_field; org_field++, field++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1697
  {
1698 1699
    if (!(*field= (*org_field)->new_field(client_thd->mem_root, copy, 1)))
      DBUG_RETURN(0);
1700
    (*field)->orig_table= copy;			// Remove connection
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1701
    (*field)->move_field(adjust_ptrs);		// Point at copy->record[0]
1702 1703
    if (*org_field == found_next_number_field)
      (*field)->table->found_next_number_field= *field;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1704 1705 1706 1707 1708 1709 1710 1711
  }
  *field=0;

  /* Adjust timestamp */
  if (table->timestamp_field)
  {
    /* Restore offset as this may have been reset in handle_inserts */
    copy->timestamp_field=
1712
      (Field_timestamp*) copy->field[table->s->timestamp_field_offset];
1713
    copy->timestamp_field->unireg_check= table->timestamp_field->unireg_check;
1714
    copy->timestamp_field_type= copy->timestamp_field->get_auto_set_type();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1715 1716 1717 1718
  }

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

  /* Adjust in_use for pointing to client thread */
  copy->in_use= client_thd;
1722 1723 1724 1725

  /* Adjust lock_count. This table object is not part of a lock. */
  copy->lock_count= 0;

1726
  DBUG_RETURN(copy);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1727 1728 1729 1730 1731 1732

  /* Got fatal error */
 error:
  tables_in_use--;
  status=1;
  pthread_cond_signal(&cond);			// Inform thread about abort
1733
  DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1734 1735 1736 1737 1738
}


/* Put a question in queue */

1739
static int write_delayed(THD *thd,TABLE *table,enum_duplicates duplic, bool ignore,
1740
			 char *query, uint query_length, bool log_on)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751
{
  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";

1752
  if (thd->killed || !(row= new delayed_row(duplic, ignore, log_on)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1753 1754 1755 1756
    goto err;

  if (!query)
    query_length=0;
1757
  if (!(row->record= (char*) my_malloc(table->s->reclength+query_length+1,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1758 1759
				       MYF(MY_WME))))
    goto err;
1760
  memcpy(row->record, table->record[0], table->s->reclength);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1761 1762
  if (query_length)
  {
1763
    row->query= row->record+table->s->reclength;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1764 1765 1766 1767 1768 1769 1770 1771
    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;
1772
  row->timestamp_field_type=    table->timestamp_field_type;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1773

1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789
  /* The session variable settings can always be copied. */
  row->auto_increment_increment= thd->variables.auto_increment_increment;
  row->auto_increment_offset=    thd->variables.auto_increment_offset;
  /*
    Next insert id must be set for the first value in a multi-row insert
    only. So clear it after the first use. Assume a multi-row insert.
    Since the user thread doesn't really execute the insert,
    thd->next_insert_id is left untouched between the rows. If we copy
    the same insert id to every row of the multi-row insert, the delayed
    insert thread would copy this before inserting every row. Thus it
    tries to insert all rows with the same insert id. This fails on the
    unique constraint. So just the first row would be really inserted.
  */
  row->next_insert_id= thd->next_insert_id;
  thd->next_insert_id= 0;

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1790 1791 1792
  di->rows.push_back(row);
  di->stacked_inserts++;
  di->status=1;
1793
  if (table->s->blob_fields)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809
    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)
{
1810
  DBUG_ENTER("end_delayed_insert");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1811 1812
  delayed_insert *di=thd->di;
  pthread_mutex_lock(&di->mutex);
1813
  DBUG_PRINT("info",("tables in use: %d",di->tables_in_use));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1814 1815 1816 1817 1818 1819
  if (!--di->tables_in_use || di->thd.killed)
  {						// Unlock table
    di->status=1;
    pthread_cond_signal(&di->cond);
  }
  pthread_mutex_unlock(&di->mutex);
1820
  DBUG_VOID_RETURN;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833
}


/* 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++))
  {
hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
1834
    tmp->thd.killed= THD::KILL_CONNECTION;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1835 1836 1837
    if (tmp->thd.mysys_var)
    {
      pthread_mutex_lock(&tmp->thd.mysys_var->mutex);
1838
      if (tmp->thd.mysys_var->current_cond)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1839
      {
1840 1841 1842 1843 1844 1845
	/*
	  We need the following test because the main mutex may be locked
	  in handle_delayed_insert()
	*/
	if (&tmp->mutex != tmp->thd.mysys_var->current_mutex)
	  pthread_mutex_lock(tmp->thd.mysys_var->current_mutex);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1846
	pthread_cond_broadcast(tmp->thd.mysys_var->current_cond);
1847 1848
	if (&tmp->mutex != tmp->thd.mysys_var->current_mutex)
	  pthread_mutex_unlock(tmp->thd.mysys_var->current_mutex);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860
      }
      pthread_mutex_unlock(&tmp->thd.mysys_var->mutex);
    }
  }
  VOID(pthread_mutex_unlock(&LOCK_delayed_insert)); // For unlink from list
}


/*
 * Create a new delayed insert thread
*/

1861
pthread_handler_t handle_delayed_insert(void *arg)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1862 1863 1864 1865 1866 1867 1868 1869
{
  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++;
1870
  thd->end_time();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1871
  threads.append(thd);
hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
1872
  thd->killed=abort_loop ? THD::KILL_CONNECTION : THD::NOT_KILLED;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1873 1874
  pthread_mutex_unlock(&LOCK_thread_count);

1875 1876 1877 1878 1879 1880 1881 1882
  /*
    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.
  */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1883
  pthread_mutex_lock(&di->mutex);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1884
#if !defined( __WIN__) && !defined(OS2)	/* Win32 calls this in pthread_create */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1885 1886 1887 1888 1889 1890 1891 1892
  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");
1893
  thd->thread_stack= (char*) &thd;
1894
  if (init_thr_lock() || thd->store_globals())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1895
  {
1896
    thd->fatal_error();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1897 1898 1899
    strmov(thd->net.last_error,ER(thd->net.last_errno=ER_OUT_OF_RESOURCES));
    goto end;
  }
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1900
#if !defined(__WIN__) && !defined(OS2) && !defined(__NETWARE__)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1901 1902 1903 1904 1905 1906 1907
  sigset_t set;
  VOID(sigemptyset(&set));			// Get mask in use
  VOID(pthread_sigmask(SIG_UNBLOCK,&set,&thd->block_signals));
#endif

  /* open table */

1908
  if (!(di->table=open_ltable(thd,&di->table_list,TL_WRITE_DELAYED)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1909
  {
1910
    thd->fatal_error();				// Abort waiting inserts
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1911 1912
    goto end;
  }
1913
  if (!(di->table->file->table_flags() & HA_CAN_INSERT_DELAYED))
1914
  {
1915
    thd->fatal_error();
1916
    my_error(ER_ILLEGAL_HA, MYF(0), di->table_list.table_name);
1917 1918
    goto end;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933
  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 (;;)
  {
hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
1934
    if (thd->killed == THD::KILL_CONNECTION)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953
    {
      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;
1954
      set_timespec(abstime, delayed_insert_timeout);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1955 1956 1957 1958

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

1961
      DBUG_PRINT("info",("Waiting for someone to insert rows"));
1962
      while (!thd->killed)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1963 1964
      {
	int error;
1965
#if defined(HAVE_BROKEN_COND_TIMEDWAIT)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1966 1967 1968 1969
	error=pthread_cond_wait(&di->cond,&di->mutex);
#else
	error=pthread_cond_timedwait(&di->cond,&di->mutex,&abstime);
#ifdef EXTRA_DEBUG
1970
	if (error && error != EINTR && error != ETIMEDOUT)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1971 1972 1973 1974 1975 1976 1977 1978 1979
	{
	  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;
monty@mysql.com's avatar
monty@mysql.com committed
1980
	if (error == ETIMEDOUT || error == ETIME)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1981
	{
hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
1982
	  thd->killed= THD::KILL_CONNECTION;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1983 1984 1985
	  break;
	}
      }
1986 1987
      /* We can't lock di->mutex and mysys_var->mutex at the same time */
      pthread_mutex_unlock(&di->mutex);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1988 1989 1990 1991
      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);
1992
      pthread_mutex_lock(&di->mutex);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1993
    }
1994
    di->thd.proc_info=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1995 1996 1997

    if (di->tables_in_use && ! thd->lock)
    {
1998
      bool not_used;
1999 2000 2001 2002 2003 2004 2005 2006 2007 2008
      /*
        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.
      */
2009
      if (! (thd->lock= mysql_lock_tables(thd, &di->table, 1,
2010 2011
                                          MYSQL_LOCK_IGNORE_GLOBAL_READ_LOCK,
                                          &not_used)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2012
      {
2013 2014 2015
	/* Fatal error */
	di->dead= 1;
	thd->killed= THD::KILL_CONNECTION;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2016 2017 2018 2019 2020 2021 2022
      }
      pthread_cond_broadcast(&di->cond_client);
    }
    if (di->stacked_inserts)
    {
      if (di->handle_inserts())
      {
2023 2024 2025
	/* Some fatal error */
	di->dead= 1;
	thd->killed= THD::KILL_CONNECTION;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2026 2027 2028 2029 2030
      }
    }
    di->status=0;
    if (!di->stacked_inserts && !di->tables_in_use && thd->lock)
    {
monty@mysql.com's avatar
monty@mysql.com committed
2031 2032 2033 2034
      /*
        No one is doing a insert delayed
        Unlock table so that other threads can use it
      */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053
      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;
2054 2055
  di->dead= 1;                                  // If error
  thd->killed= THD::KILL_CONNECTION;	        // If error
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101
  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;
2102
  ulong max_rows;
2103 2104
  bool using_ignore= 0, using_opt_replace= 0;
  bool using_bin_log= mysql_bin_log.is_open();
2105
  delayed_row *row;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116
  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 */
2117
    sql_print_error(ER(ER_DELAYED_CANT_CHANGE_LOCK),table->s->table_name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2118 2119 2120 2121
    goto err;
  }

  thd.proc_info="insert";
2122
  max_rows= delayed_insert_limit;
2123
  if (thd.killed || table->s->version != refresh_version)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2124
  {
hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
2125
    thd.killed= THD::KILL_CONNECTION;
2126
    max_rows= ~(ulong)0;                        // Do as much as possible
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2127 2128
  }

2129 2130 2131 2132 2133 2134 2135
  /*
    We can't use row caching when using the binary log because if
    we get a crash, then binary log will contain rows that are not yet
    written to disk, which will cause problems in replication.
  */
  if (!using_bin_log)
    table->file->extra(HA_EXTRA_WRITE_CACHE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2136
  pthread_mutex_lock(&mutex);
2137 2138 2139 2140 2141 2142 2143 2144

  /* Reset auto-increment cacheing */
  if (thd.clear_next_insert_id)
  {
    thd.next_insert_id= 0;
    thd.clear_next_insert_id= 0;
  }

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2145 2146 2147 2148
  while ((row=rows.get()))
  {
    stacked_inserts--;
    pthread_mutex_unlock(&mutex);
2149
    memcpy(table->record[0],row->record,table->s->reclength);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2150 2151 2152 2153 2154 2155

    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;
2156
    table->timestamp_field_type= row->timestamp_field_type;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2157

2158 2159 2160 2161 2162 2163 2164 2165
    /* The session variable settings can always be copied. */
    thd.variables.auto_increment_increment= row->auto_increment_increment;
    thd.variables.auto_increment_offset=    row->auto_increment_offset;
    /* Next insert id must be used only if non-zero. */
    if (row->next_insert_id)
      thd.next_insert_id= row->next_insert_id;
    DBUG_PRINT("loop", ("next_insert_id: %lu", (ulong) thd.next_insert_id));

2166
    info.ignore= row->ignore;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2167
    info.handle_duplicates= row->dup;
2168
    if (info.ignore ||
2169
	info.handle_duplicates != DUP_ERROR)
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
2170 2171 2172 2173
    {
      table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
      using_ignore=1;
    }
2174 2175 2176 2177 2178 2179 2180
    if (info.handle_duplicates == DUP_REPLACE &&
        (!table->triggers ||
         !table->triggers->has_delete_triggers()))
    {
      table->file->extra(HA_EXTRA_WRITE_CAN_REPLACE);
      using_opt_replace= 1;
    }
2181
    thd.clear_error(); // reset error for binlog
2182
    if (write_record(&thd, table, &info))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2183
    {
2184
      info.error_count++;				// Ignore errors
2185
      thread_safe_increment(delayed_insert_errors,&LOCK_delayed_status);
sasha@laptop.slkc.uswest.net's avatar
sasha@laptop.slkc.uswest.net committed
2186
      row->log_query = 0;
2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200
      /*
        We must reset next_insert_id. Otherwise all following rows may
        become duplicates. If write_record() failed on a duplicate and
        next_insert_id would be left unchanged, the next rows would also
        be tried with the same insert id and would fail. Since the end
        of a multi-row statement is unknown here, all following rows in
        the queue would be dropped, regardless which thread added them.
        After the queue is used up, next_insert_id is cleared and the
        next run will succeed. This could even happen if these come from
        the same multi-row statement as the current queue contents. That
        way it would look somewhat random which rows are rejected after
        a duplicate.
      */
      thd.next_insert_id= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2201
    }
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
2202 2203 2204 2205 2206
    if (using_ignore)
    {
      using_ignore=0;
      table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
    }
2207 2208 2209 2210 2211
    if (using_opt_replace)
    {
      using_opt_replace= 0;
      table->file->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
    }
2212
    if (row->query && row->log_query && using_bin_log)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2213
    {
monty@mysql.com's avatar
monty@mysql.com committed
2214
      Query_log_event qinfo(&thd, row->query, row->query_length, 0, FALSE);
2215
      mysql_bin_log.write(&qinfo);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2216
    }
2217
    if (table->s->blob_fields)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2218 2219 2220 2221 2222 2223
      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;
2224 2225 2226 2227 2228 2229 2230
    /*
      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()) &&
2231
	(!(row->log_query & using_bin_log) ||
2232
	 row->query))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245
    {
      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);
2246
          DBUG_PRINT("error", ("HA_EXTRA_NO_CACHE failed in loop"));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2247 2248
	  goto err;
	}
2249
	query_cache_invalidate3(&thd, table, 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2250 2251 2252
	if (thr_reschedule_write_lock(*thd.lock->locks))
	{
	  /* This should never happen */
2253
	  sql_print_error(ER(ER_DELAYED_CANT_CHANGE_LOCK),table->s->table_name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2254
	}
2255 2256
	if (!using_bin_log)
	  table->file->extra(HA_EXTRA_WRITE_CACHE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271
	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);
2272
    DBUG_PRINT("error", ("HA_EXTRA_NO_CACHE failed after loop"));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2273 2274
    goto err;
  }
2275
  query_cache_invalidate3(&thd, table, 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2276 2277 2278 2279
  pthread_mutex_lock(&mutex);
  DBUG_RETURN(0);

 err:
2280
  DBUG_EXECUTE("error", max_rows= 0;);
2281 2282 2283 2284 2285 2286
  /* Remove all not used rows */
  while ((row=rows.get()))
  {
    delete row;
    thread_safe_increment(delayed_insert_errors,&LOCK_delayed_status);
    stacked_inserts--;
2287
    DBUG_EXECUTE("error", max_rows++;);
2288
  }
2289
  DBUG_PRINT("error", ("dropped %lu rows after an error", max_rows));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2290 2291 2292 2293
  thread_safe_increment(delayed_insert_errors, &LOCK_delayed_status);
  pthread_mutex_lock(&mutex);
  DBUG_RETURN(1);
}
2294
#endif /* EMBEDDED_LIBRARY */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2295 2296

/***************************************************************************
2297
  Store records in INSERT ... SELECT *
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2298 2299
***************************************************************************/

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2300 2301 2302 2303 2304 2305 2306 2307 2308

/*
  make insert specific preparation and checks after opening tables

  SYNOPSIS
    mysql_insert_select_prepare()
    thd         thread handler

  RETURN
2309 2310
    FALSE OK
    TRUE  Error
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2311 2312
*/

2313
bool mysql_insert_select_prepare(THD *thd)
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2314 2315
{
  LEX *lex= thd->lex;
monty@mysql.com's avatar
monty@mysql.com committed
2316
  SELECT_LEX *select_lex= &lex->select_lex;
monty@mysql.com's avatar
monty@mysql.com committed
2317
  TABLE_LIST *first_select_leaf_table;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2318
  DBUG_ENTER("mysql_insert_select_prepare");
monty@mysql.com's avatar
monty@mysql.com committed
2319

2320 2321
  /*
    SELECT_LEX do not belong to INSERT statement, so we can't add WHERE
monty@mysql.com's avatar
monty@mysql.com committed
2322
    clause if table is VIEW
2323
  */
monty@mysql.com's avatar
monty@mysql.com committed
2324
  
monty@mysql.com's avatar
monty@mysql.com committed
2325
  if (mysql_prepare_insert(thd, lex->query_tables,
monty@mysql.com's avatar
monty@mysql.com committed
2326 2327 2328
                           lex->query_tables->table, lex->field_list, 0,
                           lex->update_list, lex->value_list,
                           lex->duplicates,
monty@mysql.com's avatar
monty@mysql.com committed
2329
                           &select_lex->where, TRUE))
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2330
    DBUG_RETURN(TRUE);
monty@mysql.com's avatar
monty@mysql.com committed
2331

2332 2333 2334 2335
  /*
    exclude first table from leaf tables list, because it belong to
    INSERT
  */
monty@mysql.com's avatar
monty@mysql.com committed
2336 2337
  DBUG_ASSERT(select_lex->leaf_tables != 0);
  lex->leaf_tables_insert= select_lex->leaf_tables;
2338
  /* skip all leaf tables belonged to view where we are insert */
monty@mysql.com's avatar
monty@mysql.com committed
2339
  for (first_select_leaf_table= select_lex->leaf_tables->next_leaf;
2340 2341 2342 2343 2344 2345
       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)
  {}
monty@mysql.com's avatar
monty@mysql.com committed
2346
  select_lex->leaf_tables= first_select_leaf_table;
2347
  DBUG_RETURN(FALSE);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2348 2349 2350
}


2351
select_insert::select_insert(TABLE_LIST *table_list_par, TABLE *table_par,
monty@mishka.local's avatar
monty@mishka.local committed
2352
                             List<Item> *fields_par,
monty@mysql.com's avatar
monty@mysql.com committed
2353 2354
                             List<Item> *update_fields,
                             List<Item> *update_values,
monty@mishka.local's avatar
monty@mishka.local committed
2355
                             enum_duplicates duplic,
2356 2357 2358 2359 2360 2361
                             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));
monty@mishka.local's avatar
monty@mishka.local committed
2362 2363 2364 2365
  info.handle_duplicates= duplic;
  info.ignore= ignore_check_option_errors;
  info.update_fields= update_fields;
  info.update_values= update_values;
2366
  if (table_list_par)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2367
    info.view= (table_list_par->view ? table_list_par : 0);
2368 2369 2370
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
2371
int
2372
select_insert::prepare(List<Item> &values, SELECT_LEX_UNIT *u)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2373
{
2374
  LEX *lex= thd->lex;
2375
  int res;
2376
  table_map map= 0;
2377
  SELECT_LEX *lex_current_select_save= lex->current_select;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2378 2379
  DBUG_ENTER("select_insert::prepare");

2380
  unit= u;
2381 2382 2383 2384 2385 2386
  /*
    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;
2387
  res= check_insert_fields(thd, table_list, *fields, values,
2388
                           !insert_into_view, &map) ||
2389
       setup_fields(thd, 0, values, 0, 0, 0);
2390

2391 2392
  if (info.handle_duplicates == DUP_UPDATE)
  {
2393
    Name_resolution_context *context= &lex->select_lex.context;
2394 2395 2396 2397
    Name_resolution_context_state ctx_state;

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

    /* Perform name resolution only in the first table - 'table_list'. */
2400
    table_list->next_local= 0;
2401 2402
    context->resolve_in_table_list_only(table_list);

2403
    lex->select_lex.no_wrap_view_item= TRUE;
2404
    res= res || check_update_fields(thd, context->table_list,
2405
                                    *info.update_fields, &map);
2406 2407
    lex->select_lex.no_wrap_view_item= FALSE;
    /*
2408 2409 2410
      When we are not using GROUP BY and there are no ungrouped aggregate functions 
      we can refer to other tables in the ON DUPLICATE KEY part.
      We use next_name_resolution_table descructively, so check it first (views?)
2411
    */       
2412 2413 2414 2415 2416 2417 2418 2419 2420 2421
    DBUG_ASSERT (!table_list->next_name_resolution_table);
    if (lex->select_lex.group_list.elements == 0 &&
        !lex->select_lex.with_sum_func)
      /*
        We must make a single context out of the two separate name resolution contexts :
        the INSERT table and the tables in the SELECT part of INSERT ... SELECT.
        To do that we must concatenate the two lists
      */  
      table_list->next_name_resolution_table= ctx_state.get_first_name_resolution_table();

2422
    res= res || setup_fields(thd, 0, *info.update_values, 1, 0, 0);
2423 2424 2425 2426 2427 2428 2429 2430 2431 2432
    if (!res)
    {
      /*
        Traverse the update values list and substitute fields from the
        select for references (Item_ref objects) to them. This is done in
        order to get correct values from those fields when the select
        employs a temporary table.
      */
      List_iterator<Item> li(*info.update_values);
      Item *item;
2433

2434 2435 2436 2437 2438 2439
      while ((item= li++))
      {
        item->transform(&Item::update_value_transformer,
                        (byte*)lex->current_select);
      }
    }
2440
    /* Restore the current context. */
2441
    ctx_state.restore_state(context, table_list);
2442
  }
2443

2444 2445
  lex->current_select= lex_current_select_save;
  if (res)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2446
    DBUG_RETURN(1);
2447 2448 2449 2450 2451 2452 2453 2454 2455 2456
  /*
    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
  */
2457
  if (!(lex->current_select->options & OPTION_BUFFER_RESULT) &&
2458
      unique_table(thd, table_list, table_list->next_global, 0))
2459 2460
  {
    /* Using same table for INSERT and SELECT */
2461 2462
    lex->current_select->options|= OPTION_BUFFER_RESULT;
    lex->current_select->join->select_options|= OPTION_BUFFER_RESULT;
2463
  }
2464
  else if (!thd->prelocked_mode)
2465 2466 2467 2468 2469 2470 2471
  {
    /*
      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().
2472 2473
      We won't start bulk inserts at all if this statement uses functions or
      should invoke triggers since they may access to the same table too.
2474 2475 2476
    */
    table->file->start_bulk_insert((ha_rows) 0);
  }
2477
  restore_record(table,s->default_values);		// Get empty record
2478
  table->next_number_field=table->found_next_number_field;
guilhem@gbichot3.local's avatar
guilhem@gbichot3.local committed
2479 2480 2481 2482 2483 2484 2485 2486 2487

#ifdef HAVE_REPLICATION
  if (thd->slave_thread &&
      (info.handle_duplicates == DUP_UPDATE) &&
      (table->next_number_field != NULL) &&
      rpl_master_has_bug(&active_mi->rli, 24432))
    DBUG_RETURN(1);
#endif

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2488
  thd->cuted_fields=0;
monty@mysql.com's avatar
monty@mysql.com committed
2489 2490
  if (info.ignore || info.handle_duplicates != DUP_ERROR)
    table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
2491 2492 2493 2494 2495 2496
  if (info.handle_duplicates == DUP_REPLACE)
  {
    if (!table->triggers || !table->triggers->has_delete_triggers())
      table->file->extra(HA_EXTRA_WRITE_CAN_REPLACE);
    table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
  }
2497
  thd->no_trans_update= 0;
monty@mysql.com's avatar
monty@mysql.com committed
2498
  thd->abort_on_warning= (!info.ignore &&
2499 2500 2501
                          (thd->variables.sql_mode &
                           (MODE_STRICT_TRANS_TABLES |
                            MODE_STRICT_ALL_TABLES)));
2502 2503 2504 2505
  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));
2506 2507 2508 2509

  if (!res)
    mark_fields_used_by_triggers_for_insert_stmt(thd, table,
                                                 info.handle_duplicates);
2510
  DBUG_RETURN(res);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2511 2512
}

2513

2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532
/*
  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");
2533 2534
  if (thd->lex->current_select->options & OPTION_BUFFER_RESULT &&
      !thd->prelocked_mode)
2535
    table->file->start_bulk_insert((ha_rows) 0);
monty@mysql.com's avatar
monty@mysql.com committed
2536
  DBUG_RETURN(0);
2537 2538 2539
}


2540 2541 2542 2543 2544 2545
void select_insert::cleanup()
{
  /* select_insert/select_create are never re-used in prepared statement */
  DBUG_ASSERT(0);
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2546 2547
select_insert::~select_insert()
{
2548
  DBUG_ENTER("~select_insert");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2549 2550 2551
  if (table)
  {
    table->next_number_field=0;
2552
    table->file->reset();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2553
  }
2554
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;
2555
  thd->abort_on_warning= 0;
2556
  DBUG_VOID_RETURN;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2557 2558 2559 2560 2561
}


bool select_insert::send_data(List<Item> &values)
{
2562
  DBUG_ENTER("select_insert::send_data");
serg@serg.mylan's avatar
serg@serg.mylan committed
2563
  bool error=0;
2564
  if (unit->offset_limit_cnt)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2565
  {						// using limit offset,count
2566
    unit->offset_limit_cnt--;
2567
    DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2568
  }
monty@mysql.com's avatar
monty@mysql.com committed
2569

monty@mysql.com's avatar
monty@mysql.com committed
2570
  thd->count_cuted_fields= CHECK_FIELD_WARN;	// Calculate cuted fields
serg@serg.mylan's avatar
serg@serg.mylan committed
2571 2572
  store_values(values);
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;
monty@mysql.com's avatar
monty@mysql.com committed
2573 2574
  if (thd->net.report_error)
    DBUG_RETURN(1);
monty@mysql.com's avatar
monty@mysql.com committed
2575 2576
  if (table_list)                               // Not CREATE ... SELECT
  {
monty@mysql.com's avatar
monty@mysql.com committed
2577
    switch (table_list->view_check_option(thd, info.ignore)) {
monty@mysql.com's avatar
monty@mysql.com committed
2578 2579 2580 2581 2582
    case VIEW_CHECK_SKIP:
      DBUG_RETURN(0);
    case VIEW_CHECK_ERROR:
      DBUG_RETURN(1);
    }
2583
  }
2584
  if (!(error= write_record(thd, table, &info)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2585
  {
2586
    if (table->triggers || info.handle_duplicates == DUP_UPDATE)
2587 2588
    {
      /*
2589 2590 2591
        Restore fields of the record since it is possible that they were
        changed by ON DUPLICATE KEY UPDATE clause.
    
2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605
        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)
2606
        last_insert_id= thd->last_insert_id;
2607
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2608
  }
serg@serg.mylan's avatar
serg@serg.mylan committed
2609
  DBUG_RETURN(error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2610 2611 2612
}


serg@serg.mylan's avatar
serg@serg.mylan committed
2613 2614 2615
void select_insert::store_values(List<Item> &values)
{
  if (fields->elements)
2616 2617
    fill_record_n_invoke_before_triggers(thd, *fields, values, 1,
                                         table->triggers, TRG_EVENT_INSERT);
serg@serg.mylan's avatar
serg@serg.mylan committed
2618
  else
2619 2620
    fill_record_n_invoke_before_triggers(thd, table->field, values, 1,
                                         table->triggers, TRG_EVENT_INSERT);
serg@serg.mylan's avatar
serg@serg.mylan committed
2621 2622
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2623 2624
void select_insert::send_error(uint errcode,const char *err)
{
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2625 2626
  DBUG_ENTER("select_insert::send_error");

2627
  my_message(errcode, err, MYF(0));
2628 2629 2630 2631 2632 2633 2634 2635 2636

  if (!table)
  {
    /*
      This can only happen when using CREATE ... SELECT and the table was not
      created becasue of an syntax error
    */
    DBUG_VOID_RETURN;
  }
2637 2638
  if (!thd->prelocked_mode)
    table->file->end_bulk_insert();
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2639 2640 2641 2642 2643
  /*
    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).
2644
  */
serg@serg.mylan's avatar
serg@serg.mylan committed
2645
  if ((info.copied || info.deleted || info.updated) &&
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
2646
      !table->file->has_transactions())
2647 2648 2649 2650 2651 2652
  {
    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,
2653
                            table->file->has_transactions(), FALSE);
2654 2655
      mysql_bin_log.write(&qinfo);
    }
2656
    if (!table->s->tmp_table)
serg@serg.mylan's avatar
serg@serg.mylan committed
2657
      thd->options|=OPTION_STATUS_NO_TRANS_UPDATE;
2658
  }
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
2659
  if (info.copied || info.deleted || info.updated)
monty@mysql.com's avatar
monty@mysql.com committed
2660
  {
2661
    query_cache_invalidate3(thd, table, 1);
monty@mysql.com's avatar
monty@mysql.com committed
2662
  }
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2663
  ha_rollback_stmt(thd);
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2664
  DBUG_VOID_RETURN;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2665 2666 2667 2668 2669
}


bool select_insert::send_eof()
{
2670
  int error,error2;
2671 2672
  DBUG_ENTER("select_insert::send_eof");

2673
  error= (!thd->prelocked_mode) ? table->file->end_bulk_insert():0;
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
2674
  table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
2675
  table->file->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
2676

2677 2678
  /*
    We must invalidate the table in the query cache before binlog writing
2679
    and ha_autocommit_or_rollback
2680
  */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2681

vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
2682
  if (info.copied || info.deleted || info.updated)
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2683
  {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2684
    query_cache_invalidate3(thd, table, 1);
2685
    if (!(table->file->has_transactions() || table->s->tmp_table))
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2686 2687
      thd->options|=OPTION_STATUS_NO_TRANS_UPDATE;
  }
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2688

2689
  if (last_insert_id)
2690
    thd->insert_id(info.copied ? last_insert_id : 0);		// For binary log
2691 2692 2693
  /* Write to binlog before commiting transaction */
  if (mysql_bin_log.is_open())
  {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
2694 2695
    if (!error)
      thd->clear_error();
2696
    Query_log_event qinfo(thd, thd->query, thd->query_length,
2697
			  table->file->has_transactions(), FALSE);
2698 2699
    mysql_bin_log.write(&qinfo);
  }
2700 2701 2702
  if ((error2=ha_autocommit_or_rollback(thd,error)) && ! error)
    error=error2;
  if (error)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2703 2704
  {
    table->file->print_error(error,MYF(0));
2705
    DBUG_RETURN(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2706
  }
2707
  char buff[160];
2708
  if (info.ignore)
2709 2710
    sprintf(buff, ER(ER_INSERT_INFO), (ulong) info.records,
	    (ulong) (info.records - info.copied), (ulong) thd->cuted_fields);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2711
  else
2712
    sprintf(buff, ER(ER_INSERT_INFO), (ulong) info.records,
monty@mysql.com's avatar
monty@mysql.com committed
2713
	    (ulong) (info.deleted+info.updated), (ulong) thd->cuted_fields);
2714
  thd->row_count_func= info.copied+info.deleted+info.updated;
2715
  ::send_ok(thd, (ulong) thd->row_count_func, last_insert_id, buff);
2716
  DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2717 2718 2719 2720
}


/***************************************************************************
2721
  CREATE TABLE (SELECT) ...
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2722 2723
***************************************************************************/

2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734
/*
  Create table from lists of fields and items (or open existing table
  with same name).

  SYNOPSIS
    create_table_from_items()
      thd          in     Thread object
      create_info  in     Create information (like MAX_ROWS, ENGINE or
                          temporary table flag)
      create_table in     Pointer to TABLE_LIST object providing database
                          and name for table to be created or to be open
2735 2736
      alter_info   in/out Initial list of columns and indexes for the table
                          to be created
2737 2738
      items        in     List of items which should be used to produce rest
                          of fields for the table (corresponding fields will
2739
                          be added to the end of alter_info->create_list)
2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760
      lock         out    Pointer to the MYSQL_LOCK object for table created
                          (open) will be returned in this parameter. Since
                          this table is not included in THD::lock caller is
                          responsible for explicitly unlocking this table.

  NOTES
    If 'create_info->options' bitmask has HA_LEX_CREATE_IF_NOT_EXISTS
    flag and table with name provided already exists then this function will
    simply open existing table.
    Also note that create, open and lock sequence in this function is not
    atomic and thus contains gap for deadlock and can cause other troubles.
    Since this function contains some logic specific to CREATE TABLE ... SELECT
    it should be changed before it can be used in other contexts.

  RETURN VALUES
    non-zero  Pointer to TABLE object for table created or opened
    0         Error
*/

static TABLE *create_table_from_items(THD *thd, HA_CREATE_INFO *create_info,
                                      TABLE_LIST *create_table,
2761 2762
                                      Alter_info *alter_info,
                                      List<Item> *items,
2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786
                                      MYSQL_LOCK **lock)
{
  TABLE tmp_table;		// Used during 'create_field()'
  TABLE *table= 0;
  uint select_field_count= items->elements;
  /* Add selected items to field list */
  List_iterator_fast<Item> it(*items);
  Item *item;
  Field *tmp_field;
  bool not_used;
  DBUG_ENTER("create_table_from_items");

  tmp_table.alias= 0;
  tmp_table.timestamp_field= 0;
  tmp_table.s= &tmp_table.share_not_to_be_used;
  tmp_table.s->db_create_options=0;
  tmp_table.s->blob_ptr_size= portable_sizeof_char_ptr;
  tmp_table.s->db_low_byte_first= test(create_info->db_type == DB_TYPE_MYISAM ||
                                       create_info->db_type == DB_TYPE_HEAP);
  tmp_table.null_row=tmp_table.maybe_null=0;

  while ((item=it++))
  {
    create_field *cr_field;
2787
    Field *field, *def_field;
2788
    if (item->type() == Item::FUNC_ITEM)
2789
      field= item->tmp_table_field(&tmp_table);
2790
    else
2791 2792 2793
      field= create_tmp_field(thd, &tmp_table, item, item->type(),
                              (Item ***) 0, &tmp_field, &def_field, 0, 0, 0, 0,
                              0);
2794 2795 2796 2797 2798 2799 2800
    if (!field ||
	!(cr_field=new create_field(field,(item->type() == Item::FIELD_ITEM ?
					   ((Item_field *)item)->field :
					   (Field*) 0))))
      DBUG_RETURN(0);
    if (item->maybe_null)
      cr_field->flags &= ~NOT_NULL_FLAG;
2801
    alter_info->create_list.push_back(cr_field);
2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821
  }
  /*
    create and lock table

    We don't log the statement, it will be logged later.

    If this is a HEAP table, the automatic DELETE FROM which is written to the
    binlog when a HEAP table is opened for the first time since startup, must
    not be written: 1) it would be wrong (imagine we're in CREATE SELECT: we
    don't want to delete from it) 2) it would be written before the CREATE
    TABLE, which is a wrong order. So we keep binary logging disabled when we
    open_table().
    NOTE: By locking table which we just have created (or for which we just have
    have found that it already exists) separately from other tables used by the
    statement we create potential window for deadlock.
    TODO: create and open should be done atomic !
  */
  {
    tmp_disable_binlog(thd);
    if (!mysql_create_table(thd, create_table->db, create_table->table_name,
2822
                            create_info, alter_info, 0, select_field_count))
2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870
    {
      /*
        If we are here in prelocked mode we either create temporary table
        or prelocked mode is caused by the SELECT part of this statement.
      */
      DBUG_ASSERT(!thd->prelocked_mode ||
                  create_info->options & HA_LEX_CREATE_TMP_TABLE ||
                  thd->lex->requires_prelocking());

      /*
        NOTE: We don't want to ignore set of locked tables here if we are
              under explicit LOCK TABLES since it will open gap for deadlock
              too wide (and also is not backward compatible).
      */
      if (! (table= open_table(thd, create_table, thd->mem_root, (bool*) 0,
                               (MYSQL_LOCK_IGNORE_FLUSH |
                                ((thd->prelocked_mode == PRELOCKED) ?
                                 MYSQL_OPEN_IGNORE_LOCKED_TABLES:0)))))
        quick_rm_table(create_info->db_type, create_table->db,
                       table_case_name(create_info, create_table->table_name));
    }
    reenable_binlog(thd);
    if (!table)                                   // open failed
      DBUG_RETURN(0);
  }

  /*
    FIXME: What happens if trigger manages to be created while we are
           obtaining this lock ? May be it is sensible just to disable
           trigger execution in this case ? Or will MYSQL_LOCK_IGNORE_FLUSH
           save us from that ?
  */
  table->reginfo.lock_type=TL_WRITE;
  if (! ((*lock)= mysql_lock_tables(thd, &table, 1,
                                    MYSQL_LOCK_IGNORE_FLUSH, &not_used)))
  {
    VOID(pthread_mutex_lock(&LOCK_open));
    hash_delete(&open_cache,(byte*) table);
    VOID(pthread_mutex_unlock(&LOCK_open));
    quick_rm_table(create_info->db_type, create_table->db,
		   table_case_name(create_info, create_table->table_name));
    DBUG_RETURN(0);
  }
  table->file->extra(HA_EXTRA_WRITE_CACHE);
  DBUG_RETURN(table);
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
2871
int
2872
select_create::prepare(List<Item> &values, SELECT_LEX_UNIT *u)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2873 2874 2875
{
  DBUG_ENTER("select_create::prepare");

2876
  unit= u;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
2877
  table= create_table_from_items(thd, create_info, create_table,
2878
                                 alter_info, &values, &lock);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2879 2880 2881
  if (!table)
    DBUG_RETURN(-1);				// abort() deletes table

2882
  if (table->s->fields < values.elements)
2883
  {
2884
    my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), 1);
2885 2886 2887
    DBUG_RETURN(-1);
  }

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2888
  /* First field to copy */
2889 2890 2891 2892 2893
  field= table->field+table->s->fields - values.elements;

  /* Mark all fields that are given values */
  for (Field **f= field ; *f ; f++)
    (*f)->query_id= thd->query_id;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2894

2895
  /* Don't set timestamp if used */
2896
  table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
serg@serg.mylan's avatar
serg@serg.mylan committed
2897

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2898 2899
  table->next_number_field=table->found_next_number_field;

2900
  restore_record(table,s->default_values);      // Get empty record
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2901
  thd->cuted_fields=0;
2902
  if (info.ignore || info.handle_duplicates != DUP_ERROR)
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
2903
    table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
2904 2905 2906 2907 2908 2909
  if (info.handle_duplicates == DUP_REPLACE)
  {
    if (!table->triggers || !table->triggers->has_delete_triggers())
      table->file->extra(HA_EXTRA_WRITE_CAN_REPLACE);
    table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
  }
2910 2911
  if (!thd->prelocked_mode)
    table->file->start_bulk_insert((ha_rows) 0);
2912
  thd->no_trans_update= 0;
monty@mysql.com's avatar
monty@mysql.com committed
2913
  thd->abort_on_warning= (!info.ignore &&
2914 2915 2916
                          (thd->variables.sql_mode &
                           (MODE_STRICT_TRANS_TABLES |
                            MODE_STRICT_ALL_TABLES)));
2917 2918
  DBUG_RETURN(check_that_all_fields_are_given_values(thd, table,
                                                     table_list));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2919 2920 2921
}


serg@serg.mylan's avatar
serg@serg.mylan committed
2922
void select_create::store_values(List<Item> &values)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2923
{
2924 2925
  fill_record_n_invoke_before_triggers(thd, field, values, 1,
                                       table->triggers, TRG_EVENT_INSERT);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2926 2927
}

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

2929 2930 2931 2932 2933 2934 2935 2936 2937
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);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2938 2939
}

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2941 2942 2943 2944 2945 2946 2947
bool select_create::send_eof()
{
  bool tmp=select_insert::send_eof();
  if (tmp)
    abort();
  else
  {
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
2948
    table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
2949
    table->file->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2950 2951
    VOID(pthread_mutex_lock(&LOCK_open));
    mysql_unlock_tables(thd, lock);
2952 2953 2954 2955 2956
    /*
      TODO:
      Check if we can remove the following two rows.
      We should be able to just keep the table in the table cache.
    */
2957
    if (!table->s->tmp_table)
2958
    {
2959
      ulong version= table->s->version;
2960
      hash_delete(&open_cache,(byte*) table);
2961
      /* Tell threads waiting for refresh that something has happened */
2962
      if (version != refresh_version)
2963
        broadcast_refresh();
2964
    }
2965
    lock=0;
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
2966
    table=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981
    VOID(pthread_mutex_unlock(&LOCK_open));
  }
  return tmp;
}

void select_create::abort()
{
  VOID(pthread_mutex_lock(&LOCK_open));
  if (lock)
  {
    mysql_unlock_tables(thd, lock);
    lock=0;
  }
  if (table)
  {
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
2982
    table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
2983
    table->file->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
2984 2985
    enum db_type table_type=table->s->db_type;
    if (!table->s->tmp_table)
2986
    {
2987
      ulong version= table->s->version;
2988
      hash_delete(&open_cache,(byte*) table);
2989
      if (!create_info->table_existed)
2990
        quick_rm_table(table_type, create_table->db, create_table->table_name);
2991
      /* Tell threads waiting for refresh that something has happened */
2992
      if (version != refresh_version)
2993
        broadcast_refresh();
2994 2995
    }
    else if (!create_info->table_existed)
2996
      close_temporary_table(thd, create_table->db, create_table->table_name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2997 2998 2999 3000 3001 3002 3003
    table=0;
  }
  VOID(pthread_mutex_unlock(&LOCK_open));
}


/*****************************************************************************
3004
  Instansiate templates
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3005 3006
*****************************************************************************/

3007
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
3008
template class List_iterator_fast<List_item>;
3009
#ifndef EMBEDDED_LIBRARY
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3010 3011 3012
template class I_List<delayed_insert>;
template class I_List_iterator<delayed_insert>;
template class I_List<delayed_row>;
3013
#endif /* EMBEDDED_LIBRARY */
3014
#endif /* HAVE_EXPLICIT_TEMPLATE_INSTANTIATION */