sql_update.cc 51.5 KB
Newer Older
unknown's avatar
unknown committed
1
/* Copyright (C) 2000-2006 MySQL AB
2

unknown's avatar
unknown 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
unknown's avatar
unknown committed
5
   the Free Software Foundation; version 2 of the License.
6

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

unknown's avatar
unknown committed
12 13 14 15 16
   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 */


17 18 19
/*
  Single table and multi table updates of tables.
  Multi-table updates were introduced by Sinisa & Monty
unknown's avatar
unknown committed
20
*/
unknown's avatar
unknown committed
21 22

#include "mysql_priv.h"
unknown's avatar
unknown committed
23
#include "sql_select.h"
24 25
#include "sp_head.h"
#include "sql_trigger.h"
unknown's avatar
unknown committed
26 27 28

/* Return 0 if row hasn't changed */

unknown's avatar
unknown committed
29
bool compare_record(TABLE *table)
unknown's avatar
unknown committed
30
{
31
  if (table->s->blob_fields + table->s->varchar_fields == 0)
unknown's avatar
unknown committed
32
    return cmp_record(table,record[1]);
unknown's avatar
unknown committed
33
  /* Compare null bits */
unknown's avatar
unknown committed
34
  if (memcmp(table->null_flags,
35 36
	     table->null_flags+table->s->rec_buff_length,
	     table->s->null_bytes))
37
    return TRUE;				// Diff in NULL value
unknown's avatar
unknown committed
38
  /* Compare updated fields */
39
  for (Field **ptr= table->field ; *ptr ; ptr++)
unknown's avatar
unknown committed
40
  {
41
    if (bitmap_is_set(table->write_set, (*ptr)->field_index) &&
42
	(*ptr)->cmp_binary_offset(table->s->rec_buff_length))
43
      return TRUE;
unknown's avatar
unknown committed
44
  }
45
  return FALSE;
unknown's avatar
unknown committed
46 47 48
}


unknown's avatar
VIEW  
unknown committed
49 50 51 52 53
/*
  check that all fields are real fields

  SYNOPSIS
    check_fields()
unknown's avatar
unknown committed
54
    thd             thread handler
unknown's avatar
VIEW  
unknown committed
55 56 57 58 59 60 61
    items           Items for check

  RETURN
    TRUE  Items can't be used in UPDATE
    FALSE Items are OK
*/

unknown's avatar
unknown committed
62
static bool check_fields(THD *thd, List<Item> &items)
unknown's avatar
VIEW  
unknown committed
63
{
unknown's avatar
unknown committed
64
  List_iterator<Item> it(items);
unknown's avatar
VIEW  
unknown committed
65
  Item *item;
66
  Item_field *field;
67

unknown's avatar
VIEW  
unknown committed
68 69
  while ((item= it++))
  {
70
    if (!(field= item->filed_for_view_update()))
unknown's avatar
VIEW  
unknown committed
71
    {
72
      /* item has name, because it comes from VIEW SELECT list */
73
      my_error(ER_NONUPDATEABLE_COLUMN, MYF(0), item->name);
unknown's avatar
VIEW  
unknown committed
74 75
      return TRUE;
    }
unknown's avatar
unknown committed
76 77 78 79
    /*
      we make temporary copy of Item_field, to avoid influence of changing
      result_field on Item_ref which refer on this field
    */
unknown's avatar
unknown committed
80
    thd->change_item_tree(it.ref(), new Item_field(thd, field));
unknown's avatar
VIEW  
unknown committed
81 82 83 84 85
  }
  return FALSE;
}


86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
/*
  Process usual UPDATE

  SYNOPSIS
    mysql_update()
    thd			thread handler
    fields		fields for update
    values		values of fields for update
    conds		WHERE clause expression
    order_num		number of elemen in ORDER BY clause
    order		ORDER BY clause list
    limit		limit clause
    handle_duplicates	how to handle duplicates

  RETURN
    0  - OK
    2  - privilege check and openning table passed, but we need to convert to
         multi-update because of view substitution
unknown's avatar
merge  
unknown committed
104
    1  - error
105 106
*/

107 108 109 110 111
int mysql_update(THD *thd,
                 TABLE_LIST *table_list,
                 List<Item> &fields,
		 List<Item> &values,
                 COND *conds,
112
                 uint order_num, ORDER *order,
unknown's avatar
unknown committed
113
		 ha_rows limit,
114
		 enum enum_duplicates handle_duplicates, bool ignore)
unknown's avatar
unknown committed
115
{
unknown's avatar
unknown committed
116
  bool		using_limit= limit != HA_POS_ERROR;
117
  bool		safe_update= test(thd->options & OPTION_SAFE_UPDATES);
unknown's avatar
unknown committed
118
  bool		used_key_is_modified, transactional_table, will_batch;
119
  bool		can_compare_record;
unknown's avatar
unknown committed
120
  int           res;
unknown's avatar
unknown committed
121 122
  int		error, loc_error;
  uint		used_index= MAX_KEY, dup_key_found;
123
  bool          need_sort= TRUE;
124 125 126
#ifndef NO_EMBEDDED_ACCESS_CHECKS
  uint		want_privilege;
#endif
unknown's avatar
unknown committed
127
  uint          table_count= 0;
128
  ha_rows	updated, found;
129
  key_map	old_covering_keys;
unknown's avatar
unknown committed
130 131 132
  TABLE		*table;
  SQL_SELECT	*select;
  READ_RECORD	info;
133
  SELECT_LEX    *select_lex= &thd->lex->select_lex;
134 135
  bool          need_reopen;
  ulonglong     id;
136
  List<Item> all_fields;
unknown's avatar
unknown committed
137
  DBUG_ENTER("mysql_update");
unknown's avatar
unknown committed
138

139
  for ( ; ; )
140
  {
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
    if (open_tables(thd, &table_list, &table_count, 0))
      DBUG_RETURN(1);

    if (table_list->multitable_view)
    {
      DBUG_ASSERT(table_list->view != 0);
      DBUG_PRINT("info", ("Switch to multi-update"));
      /* pass counter value */
      thd->lex->table_count= table_count;
      /* convert to multiupdate */
      DBUG_RETURN(2);
    }
    if (!lock_tables(thd, table_list, table_count, &need_reopen))
      break;
    if (!need_reopen)
      DBUG_RETURN(1);
157
    close_tables_for_reopen(thd, &table_list);
158
  }
unknown's avatar
unknown committed
159

160
  if (mysql_handle_derived(thd->lex, &mysql_derived_prepare) ||
unknown's avatar
unknown committed
161 162
      (thd->fill_derived_tables() &&
       mysql_handle_derived(thd->lex, &mysql_derived_filling)))
unknown's avatar
merge  
unknown committed
163
    DBUG_RETURN(1);
unknown's avatar
unknown committed
164

unknown's avatar
unknown committed
165
  thd->proc_info="init";
unknown's avatar
merging  
unknown committed
166
  table= table_list->table;
unknown's avatar
unknown committed
167

168 169
  /* Calculate "table->covering_keys" based on the WHERE */
  table->covering_keys= table->s->keys_in_use;
unknown's avatar
unknown committed
170
  table->quick_keys.clear_all();
unknown's avatar
unknown committed
171

unknown's avatar
SCRUM:  
unknown committed
172
#ifndef NO_EMBEDDED_ACCESS_CHECKS
173 174 175
  /* Force privilege re-checking for views after they have been opened. */
  want_privilege= (table_list->view ? UPDATE_ACL :
                   table_list->grant.want_privilege);
unknown's avatar
SCRUM:  
unknown committed
176
#endif
177
  if (mysql_prepare_update(thd, table_list, &conds, order_num, order))
unknown's avatar
merge  
unknown committed
178
    DBUG_RETURN(1);
179

180
  old_covering_keys= table->covering_keys;		// Keys used in WHERE
181
  /* Check the fields we are going to modify */
unknown's avatar
SCRUM:  
unknown committed
182
#ifndef NO_EMBEDDED_ACCESS_CHECKS
unknown's avatar
VIEW  
unknown committed
183
  table_list->grant.want_privilege= table->grant.want_privilege= want_privilege;
184
  table_list->register_want_access(want_privilege);
unknown's avatar
SCRUM:  
unknown committed
185
#endif
186
  if (setup_fields_with_no_wrap(thd, 0, fields, MARK_COLUMNS_WRITE, 0, 0))
187
    DBUG_RETURN(1);                     /* purecov: inspected */
unknown's avatar
unknown committed
188
  if (table_list->view && check_fields(thd, fields))
unknown's avatar
VIEW  
unknown committed
189
  {
unknown's avatar
merge  
unknown committed
190
    DBUG_RETURN(1);
unknown's avatar
VIEW  
unknown committed
191 192 193
  }
  if (!table_list->updatable || check_key_in_view(thd, table_list))
  {
194
    my_error(ER_NON_UPDATABLE_TABLE, MYF(0), table_list->alias, "UPDATE");
unknown's avatar
merge  
unknown committed
195
    DBUG_RETURN(1);
unknown's avatar
VIEW  
unknown committed
196
  }
197 198 199
  if (table->timestamp_field)
  {
    // Don't set timestamp column if this is modified
200 201
    if (bitmap_is_set(table->write_set,
                      table->timestamp_field->field_index))
202
      table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
203
    else
204
    {
205 206 207 208
      if (table->timestamp_field_type == TIMESTAMP_AUTO_SET_ON_UPDATE ||
          table->timestamp_field_type == TIMESTAMP_AUTO_SET_ON_BOTH)
        bitmap_set_bit(table->write_set,
                       table->timestamp_field->field_index);
209
    }
210
  }
211

unknown's avatar
SCRUM:  
unknown committed
212
#ifndef NO_EMBEDDED_ACCESS_CHECKS
213
  /* Check values */
unknown's avatar
VIEW  
unknown committed
214
  table_list->grant.want_privilege= table->grant.want_privilege=
unknown's avatar
unknown committed
215
    (SELECT_ACL & ~table->grant.privilege);
unknown's avatar
SCRUM:  
unknown committed
216
#endif
217
  if (setup_fields(thd, 0, values, MARK_COLUMNS_READ, 0, 0))
unknown's avatar
unknown committed
218
  {
219
    free_underlaid_joins(thd, select_lex);
unknown's avatar
merge  
unknown committed
220
    DBUG_RETURN(1);				/* purecov: inspected */
unknown's avatar
unknown committed
221
  }
unknown's avatar
unknown committed
222

223 224 225 226
  if (select_lex->inner_refs_list.elements &&
    fix_inner_refs(thd, all_fields, select_lex, select_lex->ref_pointer_array))
    DBUG_RETURN(-1);

227 228 229 230 231 232 233
  if (conds)
  {
    Item::cond_result cond_value;
    conds= remove_eq_conds(thd, conds, &cond_value);
    if (cond_value == Item::COND_FALSE)
      limit= 0;                                   // Impossible WHERE
  }
234
  // Don't count on usage of 'only index' when calculating which key to use
235
  table->covering_keys.clear_all();
236 237 238 239 240 241 242 243 244

#ifdef WITH_PARTITION_STORAGE_ENGINE
  if (prune_partitions(thd, table, conds))
  {
    free_underlaid_joins(thd, select_lex);
    send_ok(thd);				// No matching records
    DBUG_RETURN(0);
  }
#endif
245
  /* Update the table->file->stats.records number */
246
  table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);
247

unknown's avatar
unknown committed
248
  select= make_select(table, 0, 0, conds, 0, &error);
249 250
  if (error || !limit ||
      (select && select->check_quick(thd, safe_update, limit)))
unknown's avatar
unknown committed
251 252
  {
    delete select;
253
    free_underlaid_joins(thd, select_lex);
unknown's avatar
unknown committed
254 255
    if (error)
    {
unknown's avatar
merge  
unknown committed
256
      DBUG_RETURN(1);				// Error in where
unknown's avatar
unknown committed
257
    }
258
    send_ok(thd);				// No matching records
unknown's avatar
unknown committed
259 260
    DBUG_RETURN(0);
  }
261 262
  if (!select && limit != HA_POS_ERROR)
  {
263
    if ((used_index= get_index_for_order(table, order, limit)) != MAX_KEY)
264 265
      need_sort= FALSE;
  }
unknown's avatar
unknown committed
266
  /* If running in safe sql mode, don't allow updates without keys */
unknown's avatar
unknown committed
267
  if (table->quick_keys.is_clear_all())
unknown's avatar
unknown committed
268
  {
269
    thd->server_status|=SERVER_QUERY_NO_INDEX_USED;
unknown's avatar
unknown committed
270
    if (safe_update && !using_limit)
271
    {
unknown's avatar
unknown committed
272 273 274
      my_message(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE,
		 ER(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE), MYF(0));
      goto err;
275
    }
unknown's avatar
unknown committed
276
  }
277
  init_ftfuncs(thd, select_lex, 1);
278 279 280

  table->mark_columns_needed_for_update();

unknown's avatar
unknown committed
281
  /* Check if we are modifying a key that we are used to search with */
282
  
unknown's avatar
unknown committed
283
  if (select && select->quick)
unknown's avatar
unknown committed
284
  {
285
    used_index= select->quick->index;
286
    used_key_is_modified= (!select->quick->unique_key_range() &&
287
                          select->quick->is_keys_used(table->write_set));
unknown's avatar
unknown committed
288
  }
unknown's avatar
unknown committed
289
  else
290
  {
291 292 293 294
    used_key_is_modified= 0;
    if (used_index == MAX_KEY)                  // no index for sort order
      used_index= table->file->key_used_on_scan;
    if (used_index != MAX_KEY)
295
      used_key_is_modified= is_key_used(table, used_index, table->write_set);
296
  }
297

298

299
#ifdef WITH_PARTITION_STORAGE_ENGINE
300
  if (used_key_is_modified || order ||
301
      partition_key_modified(table, table->write_set))
302
#else
unknown's avatar
unknown committed
303
  if (used_key_is_modified || order)
304
#endif
unknown's avatar
unknown committed
305 306
  {
    /*
unknown's avatar
unknown committed
307 308
      We can't update table directly;  We must first search after all
      matching rows before updating the table!
unknown's avatar
unknown committed
309
    */
310
    if (used_index < MAX_KEY && old_covering_keys.is_set(used_index))
unknown's avatar
unknown committed
311 312
    {
      table->key_read=1;
313 314 315 316 317
      table->mark_columns_used_by_index(used_index);
    }
    else
    {
      table->use_all_columns();
unknown's avatar
unknown committed
318
    }
319

320
    /* note: We avoid sorting avoid if we sort on the used index */
321
    if (order && (need_sort || used_key_is_modified))
322
    {
unknown's avatar
unknown committed
323 324 325
      /*
	Doing an ORDER BY;  Let filesort find and sort the rows we are going
	to update
326
        NOTE: filesort will call table->prepare_for_position()
unknown's avatar
unknown committed
327
      */
328
      uint         length= 0;
329
      SORT_FIELD  *sortorder;
330
      ha_rows examined_rows;
331

unknown's avatar
unknown committed
332
      table->sort.io_cache = (IO_CACHE *) my_malloc(sizeof(IO_CACHE),
unknown's avatar
unknown committed
333
						    MYF(MY_FAE | MY_ZEROFILL));
334
      if (!(sortorder=make_unireg_sortorder(order, &length, NULL)) ||
335 336 337
          (table->sort.found_records= filesort(thd, table, sortorder, length,
                                               select, limit, 1,
                                               &examined_rows))
338 339
          == HA_POS_ERROR)
      {
340
	goto err;
341
      }
unknown's avatar
unknown committed
342 343 344 345 346 347
      /*
	Filesort has already found and selected the rows we want to update,
	so we don't need the where clause
      */
      delete select;
      select= 0;
348
    }
unknown's avatar
unknown committed
349
    else
unknown's avatar
unknown committed
350
    {
unknown's avatar
unknown committed
351 352 353 354 355 356 357 358 359
      /*
	We are doing a search on a key that is updated. In this case
	we go trough the matching rows, save a pointer to them and
	update these in a separate loop based on the pointer.
      */

      IO_CACHE tempfile;
      if (open_cached_file(&tempfile, mysql_tmpdir,TEMP_PREFIX,
			   DISK_BUFFER_SIZE, MYF(MY_WME)))
360
	goto err;
unknown's avatar
unknown committed
361

unknown's avatar
unknown committed
362 363 364
      /* If quick select is used, initialize it before retrieving rows. */
      if (select && select->quick && select->quick->reset())
        goto err;
365
      table->file->try_semi_consistent_read(1);
366

367 368 369 370 371 372 373 374 375 376
      /*
        When we get here, we have one of the following options:
        A. used_index == MAX_KEY
           This means we should use full table scan, and start it with
           init_read_record call
        B. used_index != MAX_KEY
           B.1 quick select is used, start the scan with init_read_record
           B.2 quick select is not used, this is full index scan (with LIMIT)
               Full index scan must be started with init_read_record_idx
      */
377

378
      if (used_index == MAX_KEY || (select && select->quick))
379 380 381
        init_read_record(&info,thd,table,select,0,1);
      else
        init_read_record_idx(&info, thd, table, 1, used_index);
unknown's avatar
VIEW  
unknown committed
382

unknown's avatar
unknown committed
383 384
      thd->proc_info="Searching rows for update";
      uint tmp_limit= limit;
unknown's avatar
unknown committed
385

unknown's avatar
unknown committed
386
      while (!(error=info.read_record(&info)) && !thd->killed)
unknown's avatar
unknown committed
387
      {
388
	if (!(select && select->skip_record()))
unknown's avatar
unknown committed
389
	{
390 391 392
          if (table->file->was_semi_consistent_read())
	    continue;  /* repeat the read of the same row if it still exists */

unknown's avatar
unknown committed
393 394 395 396 397 398 399 400
	  table->file->position(table->record[0]);
	  if (my_b_write(&tempfile,table->file->ref,
			 table->file->ref_length))
	  {
	    error=1; /* purecov: inspected */
	    break; /* purecov: inspected */
	  }
	  if (!--limit && using_limit)
401 402
	  {
	    error= -1;
unknown's avatar
unknown committed
403
	    break;
404
	  }
unknown's avatar
unknown committed
405
	}
unknown's avatar
unknown committed
406 407
	else
	  table->file->unlock_row();
unknown's avatar
unknown committed
408
      }
409 410
      if (thd->killed && !error)
	error= 1;				// Aborted
411
      limit= tmp_limit;
412
      table->file->try_semi_consistent_read(0);
unknown's avatar
unknown committed
413
      end_read_record(&info);
414
     
unknown's avatar
unknown committed
415 416 417 418 419 420 421 422 423
      /* Change select to use tempfile */
      if (select)
      {
	delete select->quick;
	if (select->free_cond)
	  delete select->cond;
	select->quick=0;
	select->cond=0;
      }
unknown's avatar
unknown committed
424 425
      else
      {
unknown's avatar
unknown committed
426 427
	select= new SQL_SELECT;
	select->head=table;
unknown's avatar
unknown committed
428
      }
unknown's avatar
unknown committed
429 430 431 432
      if (reinit_io_cache(&tempfile,READ_CACHE,0L,0,0))
	error=1; /* purecov: inspected */
      select->file=tempfile;			// Read row ptrs from this file
      if (error >= 0)
433
	goto err;
unknown's avatar
unknown committed
434 435
    }
    if (table->key_read)
436
      table->restore_column_maps_after_mark_index();
unknown's avatar
unknown committed
437 438
  }

439
  if (ignore)
unknown's avatar
unknown committed
440
    table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
441 442
  
  if (select && select->quick && select->quick->reset())
443
    goto err;
444
  table->file->try_semi_consistent_read(1);
unknown's avatar
unknown committed
445 446
  init_read_record(&info,thd,table,select,0,1);

447
  updated= found= 0;
448
  thd->count_cuted_fields= CHECK_FIELD_WARN;		/* calc cuted fields */
unknown's avatar
unknown committed
449
  thd->cuted_fields=0L;
450
  thd->proc_info="Updating";
unknown's avatar
unknown committed
451

unknown's avatar
unknown committed
452
  transactional_table= table->file->has_transactions();
453
  thd->no_trans_update.stmt= FALSE;
unknown's avatar
unknown committed
454
  thd->abort_on_warning= test(!ignore &&
unknown's avatar
unknown committed
455 456 457
                              (thd->variables.sql_mode &
                               (MODE_STRICT_TRANS_TABLES |
                                MODE_STRICT_ALL_TABLES)));
458 459 460
  if (table->triggers &&
      table->triggers->has_triggers(TRG_EVENT_UPDATE,
                                    TRG_ACTION_AFTER))
461
  {
462 463 464 465 466 467 468
    /*
      The table has AFTER UPDATE triggers that might access to subject 
      table and therefore might need update to be done immediately. 
      So we turn-off the batching.
    */ 
    (void) table->file->extra(HA_EXTRA_UPDATE_CANNOT_BATCH);
    will_batch= FALSE;
469
  }
470 471
  else
    will_batch= !table->file->start_bulk_update();
472

473 474 475 476 477 478 479 480
  /*
    We can use compare_record() to optimize away updates if
    the table handler is returning all columns OR if
    if all updated columns are read
  */
  can_compare_record= (!(table->file->ha_table_flags() &
                         HA_PARTIAL_COLUMN_READ) ||
                       bitmap_is_subset(table->write_set, table->read_set));
481

unknown's avatar
unknown committed
482 483
  while (!(error=info.read_record(&info)) && !thd->killed)
  {
484
    if (!(select && select->skip_record()))
unknown's avatar
unknown committed
485
    {
486
      if (table->file->was_semi_consistent_read())
487
        continue;  /* repeat the read of the same row if it still exists */
488

unknown's avatar
unknown committed
489
      store_record(table,record[1]);
unknown's avatar
unknown committed
490 491 492
      if (fill_record_n_invoke_before_triggers(thd, fields, values, 0,
                                               table->triggers,
                                               TRG_EVENT_UPDATE))
493
        break; /* purecov: inspected */
unknown's avatar
unknown committed
494

unknown's avatar
unknown committed
495
      found++;
496

497
      if (!can_compare_record || compare_record(table))
unknown's avatar
unknown committed
498
      {
unknown's avatar
unknown committed
499
        if ((res= table_list->view_check_option(thd, ignore)) !=
unknown's avatar
unknown committed
500 501 502 503 504 505 506 507 508 509 510
            VIEW_CHECK_OK)
        {
          found--;
          if (res == VIEW_CHECK_SKIP)
            continue;
          else if (res == VIEW_CHECK_ERROR)
          {
            error= 1;
            break;
          }
        }
unknown's avatar
unknown committed
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
        if (will_batch)
        {
          /*
            Typically a batched handler can execute the batched jobs when:
            1) When specifically told to do so
            2) When it is not a good idea to batch anymore
            3) When it is necessary to send batch for other reasons
               (One such reason is when READ's must be performed)

            1) is covered by exec_bulk_update calls.
            2) and 3) is handled by the bulk_update_row method.
            
            bulk_update_row can execute the updates including the one
            defined in the bulk_update_row or not including the row
            in the call. This is up to the handler implementation and can
            vary from call to call.

            The dup_key_found reports the number of duplicate keys found
            in those updates actually executed. It only reports those if
            the extra call with HA_EXTRA_IGNORE_DUP_KEY have been issued.
            If this hasn't been issued it returns an error code and can
            ignore this number. Thus any handler that implements batching
            for UPDATE IGNORE must also handle this extra call properly.

            If a duplicate key is found on the record included in this
            call then it should be included in the count of dup_key_found
            and error should be set to 0 (only if these errors are ignored).
          */
539 540
          error= table->file->bulk_update_row(table->record[1],
                                              table->record[0],
unknown's avatar
unknown committed
541
                                              &dup_key_found);
unknown's avatar
unknown committed
542
          limit+= dup_key_found;
unknown's avatar
unknown committed
543
          updated-= dup_key_found;
unknown's avatar
unknown committed
544 545 546 547
        }
        else
        {
          /* Non-batched update */
548 549
	  error= table->file->ha_update_row((byte*) table->record[1],
	                                   (byte*) table->record[0]);
unknown's avatar
unknown committed
550 551
        }
        if (!error)
unknown's avatar
unknown committed
552 553
	{
	  updated++;
unknown's avatar
unknown committed
554
          thd->no_trans_update.stmt= !transactional_table;
unknown's avatar
unknown committed
555 556 557 558 559 560 561 562

          if (table->triggers &&
              table->triggers->process_triggers(thd, TRG_EVENT_UPDATE,
                                                TRG_ACTION_AFTER, TRUE))
          {
            error= 1;
            break;
          }
unknown's avatar
unknown committed
563
	}
564
 	else if (!ignore ||
565
                 table->file->is_fatal_error(error, HA_CHECK_DUP_KEY))
unknown's avatar
unknown committed
566
	{
567
          /*
568
            If (ignore && error is ignorable) we don't have to
569 570
            do anything; otherwise...
          */
571
          if (table->file->is_fatal_error(error, HA_CHECK_DUP_KEY))
572
            thd->fatal_error(); /* Other handler errors are fatal */
unknown's avatar
unknown committed
573 574 575 576 577
	  table->file->print_error(error,MYF(0));
	  error= 1;
	  break;
	}
      }
578

unknown's avatar
unknown committed
579 580
      if (!--limit && using_limit)
      {
unknown's avatar
unknown committed
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
        /*
          We have reached end-of-file in most common situations where no
          batching has occurred and if batching was supposed to occur but
          no updates were made and finally when the batch execution was
          performed without error and without finding any duplicate keys.
          If the batched updates were performed with errors we need to
          check and if no error but duplicate key's found we need to
          continue since those are not counted for in limit.
        */
        if (will_batch &&
            ((error= table->file->exec_bulk_update(&dup_key_found)) ||
            !dup_key_found))
        {
 	  if (error)
          {
            /*
              The handler should not report error of duplicate keys if they
              are ignored. This is a requirement on batching handlers.
            */
            table->file->print_error(error,MYF(0));
unknown's avatar
unknown committed
601
            error= 1;
unknown's avatar
unknown committed
602 603 604 605 606 607 608
            break;
          }
          /*
            Either an error was found and we are ignoring errors or there
            were duplicate keys found. In both cases we need to correct
            the counters and continue the loop.
          */
unknown's avatar
unknown committed
609 610
          limit= dup_key_found; //limit is 0 when we get here so need to +
          updated-= dup_key_found;
unknown's avatar
unknown committed
611 612 613 614 615 616
        }
        else
        {
	  error= -1;				// Simulate end of file
	  break;
        }
unknown's avatar
unknown committed
617
      }
unknown's avatar
unknown committed
618
    }
unknown's avatar
unknown committed
619 620
    else
      table->file->unlock_row();
621
    thd->row_count++;
unknown's avatar
unknown committed
622
  }
unknown's avatar
unknown committed
623
  dup_key_found= 0;
624 625
  if (thd->killed && !error)
    error= 1;					// Aborted
unknown's avatar
unknown committed
626 627 628 629 630 631 632 633 634 635 636 637 638
  else if (will_batch &&
           (loc_error= table->file->exec_bulk_update(&dup_key_found)))
    /*
      An error has occurred when a batched update was performed and returned
      an error indication. It cannot be an allowed duplicate key error since
      we require the batching handler to treat this as a normal behavior.

      Otherwise we simply remove the number of duplicate keys records found
      in the batched update.
    */
  {
    thd->fatal_error();
    table->file->print_error(loc_error,MYF(0));
unknown's avatar
unknown committed
639
    error= 1;
unknown's avatar
unknown committed
640 641
  }
  else
unknown's avatar
unknown committed
642
    updated-= dup_key_found;
unknown's avatar
unknown committed
643 644
  if (will_batch)
    table->file->end_bulk_update();
645
  table->file->try_semi_consistent_read(0);
unknown's avatar
unknown committed
646
  end_read_record(&info);
unknown's avatar
unknown committed
647
  delete select;
unknown's avatar
unknown committed
648
  thd->proc_info= "end";
unknown's avatar
unknown committed
649
  VOID(table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY));
unknown's avatar
unknown committed
650 651 652 653 654 655

  /*
    Invalidate the table in the query cache if something changed.
    This must be before binlog writing and ha_autocommit_...
  */
  if (updated)
unknown's avatar
unknown committed
656
  {
unknown's avatar
unknown committed
657
    query_cache_invalidate3(thd, table_list, 1);
unknown's avatar
unknown committed
658
  }
unknown's avatar
unknown committed
659

660 661 662 663 664 665 666 667 668 669
  /*
    error < 0 means really no error at all: we processed all rows until the
    last one without error. error > 0 means an error (e.g. unique key
    violation and no IGNORE or REPLACE). error == 0 is also an error (if
    preparing the record or invoking before triggers fails). See
    ha_autocommit_or_rollback(error>=0) and DBUG_RETURN(error>=0) below.
    Sometimes we want to binlog even if we updated no rows, in case user used
    it to be sure master and slave are in same state.
  */
  if ((error < 0) || (updated && !transactional_table))
unknown's avatar
unknown committed
670
  {
671 672
    if (mysql_bin_log.is_open())
    {
673
      if (error < 0)
unknown's avatar
unknown committed
674
        thd->clear_error();
675 676 677 678 679
      if (thd->binlog_query(THD::ROW_QUERY_TYPE,
                            thd->query, thd->query_length,
                            transactional_table, FALSE) &&
          transactional_table)
      {
680
        error=1;				// Rollback update
681
      }
682
    }
unknown's avatar
unknown committed
683
    if (!transactional_table)
684
      thd->no_trans_update.all= TRUE;
unknown's avatar
unknown committed
685
  }
686
  free_underlaid_joins(thd, select_lex);
unknown's avatar
unknown committed
687 688 689 690 691
  if (transactional_table)
  {
    if (ha_autocommit_or_rollback(thd, error >= 0))
      error=1;
  }
unknown's avatar
unknown committed
692

693 694 695 696 697 698
  if (thd->lock)
  {
    mysql_unlock_tables(thd, thd->lock);
    thd->lock=0;
  }

699 700 701 702
  /* If LAST_INSERT_ID(X) was used, report X */
  id= thd->arg_of_last_insert_id_function ?
    thd->first_successful_insert_id_in_prev_stmt : 0;

unknown's avatar
unknown committed
703
  if (error < 0)
unknown's avatar
unknown committed
704
  {
unknown's avatar
unknown committed
705
    char buff[STRING_BUFFER_USUAL_SIZE];
706 707
    sprintf(buff, ER(ER_UPDATE_INFO), (ulong) found, (ulong) updated,
	    (ulong) thd->cuted_fields);
708 709
    thd->row_count_func=
      (thd->client_capabilities & CLIENT_FOUND_ROWS) ? found : updated;
710
    send_ok(thd, (ulong) thd->row_count_func, id, buff);
unknown's avatar
unknown committed
711
    DBUG_PRINT("info",("%ld records updated", (long) updated));
unknown's avatar
unknown committed
712
  }
713
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;		/* calc cuted fields */
714
  thd->abort_on_warning= 0;
unknown's avatar
merge  
unknown committed
715
  DBUG_RETURN((error >= 0 || thd->net.report_error) ? 1 : 0);
716 717 718

err:
  delete select;
719
  free_underlaid_joins(thd, select_lex);
720 721 722 723 724
  if (table->key_read)
  {
    table->key_read=0;
    table->file->extra(HA_EXTRA_NO_KEYREAD);
  }
unknown's avatar
unknown committed
725
  thd->abort_on_warning= 0;
unknown's avatar
merge  
unknown committed
726
  DBUG_RETURN(1);
unknown's avatar
unknown committed
727
}
unknown's avatar
unknown committed
728

unknown's avatar
unknown committed
729 730 731 732 733 734
/*
  Prepare items in UPDATE statement

  SYNOPSIS
    mysql_prepare_update()
    thd			- thread handler
unknown's avatar
VIEW  
unknown committed
735
    table_list		- global/local table list
unknown's avatar
unknown committed
736 737 738 739 740
    conds		- conditions
    order_num		- number of ORDER BY list entries
    order		- ORDER BY clause list

  RETURN VALUE
unknown's avatar
unknown committed
741 742
    FALSE OK
    TRUE  error
unknown's avatar
unknown committed
743
*/
unknown's avatar
unknown committed
744
bool mysql_prepare_update(THD *thd, TABLE_LIST *table_list,
unknown's avatar
unknown committed
745 746
			 Item **conds, uint order_num, ORDER *order)
{
747
  Item *fake_conds= 0;
unknown's avatar
unknown committed
748 749 750
  TABLE *table= table_list->table;
  TABLE_LIST tables;
  List<Item> all_fields;
751
  SELECT_LEX *select_lex= &thd->lex->select_lex;
unknown's avatar
unknown committed
752 753 754
  DBUG_ENTER("mysql_prepare_update");

#ifndef NO_EMBEDDED_ACCESS_CHECKS
unknown's avatar
VIEW  
unknown committed
755 756
  table_list->grant.want_privilege= table->grant.want_privilege= 
    (SELECT_ACL & ~table->grant.privilege);
757
  table_list->register_want_access(SELECT_ACL);
unknown's avatar
unknown committed
758 759 760 761 762
#endif

  bzero((char*) &tables,sizeof(tables));	// For ORDER BY
  tables.table= table;
  tables.alias= table_list->alias;
unknown's avatar
unknown committed
763
  thd->lex->allow_sum_func= 0;
unknown's avatar
unknown committed
764

765 766
  if (setup_tables_and_check_access(thd, &select_lex->context, 
                                    &select_lex->top_join_list,
767
                                    table_list,
768
                                    &select_lex->leaf_tables,
769
                                    FALSE, UPDATE_ACL, SELECT_ACL) ||
770
      setup_conds(thd, table_list, select_lex->leaf_tables, conds) ||
771 772
      select_lex->setup_ref_array(thd, order_num) ||
      setup_order(thd, select_lex->ref_pointer_array,
unknown's avatar
VIEW  
unknown committed
773
		  table_list, all_fields, all_fields, order) ||
774
      setup_ftfuncs(select_lex))
unknown's avatar
unknown committed
775
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
776 777 778

  /* Check that we are not using table that we are updating in a sub select */
  {
779
    TABLE_LIST *duplicate;
780
    if ((duplicate= unique_table(thd, table_list, table_list->next_global, 0)))
781 782 783 784 785
    {
      update_non_unique_table_error(table_list, "UPDATE", duplicate);
      my_error(ER_UPDATE_TABLE_USED, MYF(0), table_list->table_name);
      DBUG_RETURN(TRUE);
    }
unknown's avatar
unknown committed
786
  }
787
  select_lex->fix_prepare_information(thd, conds, &fake_conds);
unknown's avatar
unknown committed
788
  DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
789 790
}

unknown's avatar
unknown committed
791

unknown's avatar
unknown committed
792
/***************************************************************************
793
  Update multiple tables from join 
unknown's avatar
unknown committed
794 795
***************************************************************************/

unknown's avatar
unknown committed
796
/*
797
  Get table map for list of Item_field
unknown's avatar
unknown committed
798 799
*/

800 801 802 803 804 805 806 807
static table_map get_table_map(List<Item> *items)
{
  List_iterator_fast<Item> item_it(*items);
  Item_field *item;
  table_map map= 0;

  while ((item= (Item_field *) item_it++)) 
    map|= item->used_tables();
unknown's avatar
unknown committed
808
  DBUG_PRINT("info", ("table_map: 0x%08lx", (long) map));
809 810 811 812
  return map;
}


unknown's avatar
VIEW  
unknown committed
813 814
/*
  make update specific preparation and checks after opening tables
unknown's avatar
unknown committed
815

unknown's avatar
VIEW  
unknown committed
816 817 818
  SYNOPSIS
    mysql_multi_update_prepare()
    thd         thread handler
unknown's avatar
unknown committed
819

unknown's avatar
VIEW  
unknown committed
820
  RETURN
unknown's avatar
unknown committed
821 822
    FALSE OK
    TRUE  Error
unknown's avatar
VIEW  
unknown committed
823
*/
824

unknown's avatar
unknown committed
825
bool mysql_multi_update_prepare(THD *thd)
unknown's avatar
VIEW  
unknown committed
826 827 828
{
  LEX *lex= thd->lex;
  TABLE_LIST *table_list= lex->query_tables;
unknown's avatar
unknown committed
829
  TABLE_LIST *tl, *leaves;
unknown's avatar
VIEW  
unknown committed
830
  List<Item> *fields= &lex->select_lex.item_list;
unknown's avatar
unknown committed
831
  table_map tables_for_update;
unknown's avatar
unknown committed
832
  bool update_view= 0;
unknown's avatar
unknown committed
833 834 835 836 837 838
  /*
    if this multi-update was converted from usual update, here is table
    counter else junk will be assigned here, but then replaced with real
    count in open_tables()
  */
  uint  table_count= lex->table_count;
unknown's avatar
unknown committed
839
  const bool using_lock_tables= thd->locked_tables != 0;
unknown's avatar
unknown committed
840
  bool original_multiupdate= (thd->lex->sql_command == SQLCOM_UPDATE_MULTI);
841
  bool need_reopen= FALSE;
unknown's avatar
unknown committed
842 843
  DBUG_ENTER("mysql_multi_update_prepare");

unknown's avatar
unknown committed
844 845
  /* following need for prepared statements, to run next time multi-update */
  thd->lex->sql_command= SQLCOM_UPDATE_MULTI;
unknown's avatar
unknown committed
846

847 848
reopen_tables:

unknown's avatar
unknown committed
849
  /* open tables and create derived ones, but do not lock and fill them */
850
  if (((original_multiupdate || need_reopen) &&
851
       open_tables(thd, &table_list, &table_count, 0)) ||
unknown's avatar
unknown committed
852
      mysql_handle_derived(lex, &mysql_derived_prepare))
853
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
854 855 856 857 858
  /*
    setup_tables() need for VIEWs. JOIN::prepare() will call setup_tables()
    second time, but this call will do nothing (there are check for second
    call in setup_tables()).
  */
unknown's avatar
merge  
unknown committed
859

860 861
  if (setup_tables_and_check_access(thd, &lex->select_lex.context,
                                    &lex->select_lex.top_join_list,
862
                                    table_list,
863
                                    &lex->select_lex.leaf_tables, FALSE,
864
                                    UPDATE_ACL, SELECT_ACL))
unknown's avatar
merge  
unknown committed
865
    DBUG_RETURN(TRUE);
866

867
  if (setup_fields_with_no_wrap(thd, 0, *fields, MARK_COLUMNS_WRITE, 0, 0))
unknown's avatar
unknown committed
868
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
869 870 871 872 873 874 875 876 877 878 879

  for (tl= table_list; tl ; tl= tl->next_local)
  {
    if (tl->view)
    {
      update_view= 1;
      break;
    }
  }

  if (update_view && check_fields(thd, *fields))
880
  {
unknown's avatar
unknown committed
881
    DBUG_RETURN(TRUE);
unknown's avatar
VIEW  
unknown committed
882 883
  }

unknown's avatar
unknown committed
884
  tables_for_update= get_table_map(fields);
unknown's avatar
unknown committed
885 886

  /*
unknown's avatar
unknown committed
887
    Setup timestamp handling and locking mode
unknown's avatar
unknown committed
888
  */
889
  leaves= lex->select_lex.leaf_tables;
890
  for (tl= leaves; tl; tl= tl->next_leaf)
unknown's avatar
unknown committed
891
  {
unknown's avatar
unknown committed
892
    TABLE *table= tl->table;
unknown's avatar
unknown committed
893
    /* Only set timestamp column if this is not modified */
894
    if (table->timestamp_field &&
895 896
        bitmap_is_set(table->write_set,
                      table->timestamp_field->field_index))
unknown's avatar
unknown committed
897
      table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
unknown's avatar
VIEW  
unknown committed
898

unknown's avatar
unknown committed
899 900
    /* if table will be updated then check that it is unique */
    if (table->map & tables_for_update)
901
    {
unknown's avatar
unknown committed
902
      if (!tl->updatable || check_key_in_view(thd, tl))
unknown's avatar
unknown committed
903
      {
904
        my_error(ER_NON_UPDATABLE_TABLE, MYF(0), tl->alias, "UPDATE");
unknown's avatar
merge  
unknown committed
905
        DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
906
      }
unknown's avatar
unknown committed
907

908
      table->mark_columns_needed_for_update();
unknown's avatar
unknown committed
909
      DBUG_PRINT("info",("setting table `%s` for update", tl->alias));
910 911 912 913
      /*
        If table will be updated we should not downgrade lock for it and
        leave it as is.
      */
unknown's avatar
unknown committed
914
    }
unknown's avatar
unknown committed
915 916 917
    else
    {
      DBUG_PRINT("info",("setting table `%s` for read-only", tl->alias));
unknown's avatar
unknown committed
918 919 920 921 922 923
      /*
        If we are using the binary log, we need TL_READ_NO_INSERT to get
        correct order of statements. Otherwise, we use a TL_READ lock to
        improve performance.
      */
      tl->lock_type= using_update_log ? TL_READ_NO_INSERT : TL_READ;
unknown's avatar
unknown committed
924
      tl->updating= 0;
925
      /* Update TABLE::lock_type accordingly. */
926
      if (!tl->placeholder() && !using_lock_tables)
927
        tl->table->reginfo.lock_type= tl->lock_type;
928
    }
unknown's avatar
unknown committed
929
  }
unknown's avatar
unknown committed
930
  for (tl= table_list; tl; tl= tl->next_local)
unknown's avatar
unknown committed
931
  {
unknown's avatar
unknown committed
932
    /* Check access privileges for table */
unknown's avatar
unknown committed
933
    if (!tl->derived)
934
    {
unknown's avatar
unknown committed
935 936
      uint want_privilege= tl->updating ? UPDATE_ACL : SELECT_ACL;
      if (check_access(thd, want_privilege,
937 938
                       tl->db, &tl->grant.privilege, 0, 0, 
                       test(tl->schema_table)) ||
unknown's avatar
unknown committed
939
          (grant_option && check_grant(thd, want_privilege, tl, 0, 1, 0)))
unknown's avatar
unknown committed
940
        DBUG_RETURN(TRUE);
941
    }
unknown's avatar
unknown committed
942
  }
unknown's avatar
unknown committed
943

unknown's avatar
unknown committed
944 945 946
  /* check single table update for view compound from several tables */
  for (tl= table_list; tl; tl= tl->next_local)
  {
unknown's avatar
unknown committed
947
    if (tl->effective_algorithm == VIEW_ALGORITHM_MERGE)
unknown's avatar
unknown committed
948 949
    {
      TABLE_LIST *for_update= 0;
unknown's avatar
unknown committed
950
      if (tl->check_single_table(&for_update, tables_for_update, tl))
unknown's avatar
unknown committed
951 952 953 954 955 956 957 958
      {
	my_error(ER_VIEW_MULTIUPDATE, MYF(0),
		 tl->view_db.str, tl->view_name.str);
	DBUG_RETURN(-1);
      }
    }
  }

unknown's avatar
unknown committed
959
  /* now lock and fill tables */
960
  if (lock_tables(thd, table_list, table_count, &need_reopen))
unknown's avatar
unknown committed
961
  {
962 963 964
    if (!need_reopen)
      DBUG_RETURN(TRUE);

unknown's avatar
unknown committed
965
    /*
966 967 968 969
      We have to reopen tables since some of them were altered or dropped
      during lock_tables() or something was done with their triggers.
      Let us do some cleanups to be able do setup_table() and setup_fields()
      once again.
unknown's avatar
unknown committed
970 971 972
    */
    List_iterator_fast<Item> it(*fields);
    Item *item;
unknown's avatar
unknown committed
973
    while ((item= it++))
unknown's avatar
unknown committed
974 975
      item->cleanup();

unknown's avatar
unknown committed
976
    /* We have to cleanup translation tables of views. */
unknown's avatar
unknown committed
977 978 979
    for (TABLE_LIST *tbl= table_list; tbl; tbl= tbl->next_global)
      tbl->cleanup_items();

980
    close_tables_for_reopen(thd, &table_list);
981
    goto reopen_tables;
unknown's avatar
unknown committed
982
  }
unknown's avatar
unknown committed
983

984 985 986 987 988
  /*
    Check that we are not using table that we are updating, but we should
    skip all tables of UPDATE SELECT itself
  */
  lex->select_lex.exclude_from_table_unique_test= TRUE;
unknown's avatar
unknown committed
989 990 991 992 993
  /* We only need SELECT privilege for columns in the values list */
  for (tl= leaves; tl; tl= tl->next_leaf)
  {
    TABLE *table= tl->table;
    TABLE_LIST *tlist;
994
    if (!(tlist= tl->top_table())->derived)
unknown's avatar
unknown committed
995 996 997 998 999 1000 1001
    {
      tlist->grant.want_privilege=
        (SELECT_ACL & ~tlist->grant.privilege);
      table->grant.want_privilege= (SELECT_ACL & ~table->grant.privilege);
    }
    DBUG_PRINT("info", ("table: %s  want_privilege: %u", tl->alias,
                        (uint) table->grant.want_privilege));
1002
    if (tl->lock_type != TL_READ &&
1003
        tl->lock_type != TL_READ_NO_INSERT)
1004
    {
1005
      TABLE_LIST *duplicate;
1006
      if ((duplicate= unique_table(thd, tl, table_list, 0)))
1007 1008 1009 1010
      {
        update_non_unique_table_error(table_list, "UPDATE", duplicate);
        DBUG_RETURN(TRUE);
      }
1011
    }
unknown's avatar
unknown committed
1012
  }
unknown's avatar
unknown committed
1013 1014 1015 1016 1017 1018
  /*
    Set exclude_from_table_unique_test value back to FALSE. It is needed for
    further check in multi_update::prepare whether to use record cache.
  */
  lex->select_lex.exclude_from_table_unique_test= FALSE;
 
unknown's avatar
unknown committed
1019 1020
  if (thd->fill_derived_tables() &&
      mysql_handle_derived(lex, &mysql_derived_filling))
1021
    DBUG_RETURN(TRUE);
1022

unknown's avatar
merge  
unknown committed
1023
  DBUG_RETURN (FALSE);
unknown's avatar
VIEW  
unknown committed
1024 1025 1026
}


unknown's avatar
unknown committed
1027 1028 1029
/*
  Setup multi-update handling and call SELECT to do the join
*/
1030

unknown's avatar
unknown committed
1031 1032 1033 1034 1035
bool mysql_multi_update(THD *thd,
                        TABLE_LIST *table_list,
                        List<Item> *fields,
                        List<Item> *values,
                        COND *conds,
1036
                        ulonglong options,
1037
                        enum enum_duplicates handle_duplicates, bool ignore,
unknown's avatar
unknown committed
1038
                        SELECT_LEX_UNIT *unit, SELECT_LEX *select_lex)
unknown's avatar
VIEW  
unknown committed
1039 1040 1041 1042
{
  multi_update *result;
  DBUG_ENTER("mysql_multi_update");

1043
  if (!(result= new multi_update(table_list,
1044 1045
				 thd->lex->select_lex.leaf_tables,
				 fields, values,
1046
				 handle_duplicates, ignore)))
unknown's avatar
unknown committed
1047
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
1048

1049
  thd->no_trans_update.stmt= FALSE;
unknown's avatar
unknown committed
1050 1051 1052 1053
  thd->abort_on_warning= test(thd->variables.sql_mode &
                              (MODE_STRICT_TRANS_TABLES |
                               MODE_STRICT_ALL_TABLES));

unknown's avatar
unknown committed
1054
  List<Item> total_list;
1055 1056 1057 1058 1059 1060 1061 1062
  (void) mysql_select(thd, &select_lex->ref_pointer_array,
                      table_list, select_lex->with_wild,
                      total_list,
                      conds, 0, (ORDER *) NULL, (ORDER *)NULL, (Item *) NULL,
                      (ORDER *)NULL,
                      options | SELECT_NO_JOIN_CACHE | SELECT_NO_UNLOCK |
                      OPTION_SETUP_TABLES_DONE,
                      result, unit, select_lex);
unknown's avatar
unknown committed
1063
  delete result;
unknown's avatar
unknown committed
1064
  thd->abort_on_warning= 0;
1065
  DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
1066 1067
}

unknown's avatar
unknown committed
1068

1069
multi_update::multi_update(TABLE_LIST *table_list,
1070
			   TABLE_LIST *leaves_list,
unknown's avatar
unknown committed
1071
			   List<Item> *field_list, List<Item> *value_list,
unknown's avatar
unknown committed
1072 1073
			   enum enum_duplicates handle_duplicates_arg,
                           bool ignore_arg)
1074
  :all_tables(table_list), leaves(leaves_list), update_tables(0),
1075
   tmp_tables(0), updated(0), found(0), fields(field_list),
1076 1077
   values(value_list), table_count(0), copy_field(0),
   handle_duplicates(handle_duplicates_arg), do_update(1), trans_safe(0),
1078
   transactional_tables(1), ignore(ignore_arg)
unknown's avatar
unknown committed
1079 1080 1081 1082 1083 1084 1085
{}


/*
  Connect fields with tables and create list of tables that are updated
*/

1086 1087
int multi_update::prepare(List<Item> &not_used_values,
			  SELECT_LEX_UNIT *lex_unit)
unknown's avatar
unknown committed
1088
{
unknown's avatar
unknown committed
1089 1090
  TABLE_LIST *table_ref;
  SQL_LIST update;
1091
  table_map tables_to_update;
unknown's avatar
unknown committed
1092 1093 1094 1095
  Item_field *item;
  List_iterator_fast<Item> field_it(*fields);
  List_iterator_fast<Item> value_it(*values);
  uint i, max_fields;
unknown's avatar
unknown committed
1096
  DBUG_ENTER("multi_update::prepare");
unknown's avatar
unknown committed
1097

1098
  thd->count_cuted_fields= CHECK_FIELD_WARN;
unknown's avatar
unknown committed
1099
  thd->cuted_fields=0L;
unknown's avatar
unknown committed
1100 1101
  thd->proc_info="updating main table";

1102
  tables_to_update= get_table_map(fields);
unknown's avatar
unknown committed
1103

unknown's avatar
unknown committed
1104
  if (!tables_to_update)
unknown's avatar
unknown committed
1105
  {
unknown's avatar
unknown committed
1106
    my_message(ER_NO_TABLES_USED, ER(ER_NO_TABLES_USED), MYF(0));
unknown's avatar
unknown committed
1107
    DBUG_RETURN(1);
unknown's avatar
unknown committed
1108
  }
unknown's avatar
unknown committed
1109

1110
  /*
1111
    We have to check values after setup_tables to get covering_keys right in
unknown's avatar
unknown committed
1112
    reference tables
1113
  */
unknown's avatar
unknown committed
1114

1115
  if (setup_fields(thd, 0, *values, MARK_COLUMNS_READ, 0, 0))
unknown's avatar
unknown committed
1116 1117
    DBUG_RETURN(1);

1118
  /*
unknown's avatar
unknown committed
1119 1120 1121
    Save tables beeing updated in update_tables
    update_table->shared is position for table
    Don't use key read on tables that are updated
1122
  */
unknown's avatar
unknown committed
1123 1124

  update.empty();
1125
  for (table_ref= leaves; table_ref; table_ref= table_ref->next_leaf)
unknown's avatar
unknown committed
1126
  {
1127
    /* TODO: add support of view of join support */
unknown's avatar
unknown committed
1128 1129
    TABLE *table=table_ref->table;
    if (tables_to_update & table->map)
unknown's avatar
unknown committed
1130
    {
unknown's avatar
unknown committed
1131 1132 1133
      TABLE_LIST *tl= (TABLE_LIST*) thd->memdup((char*) table_ref,
						sizeof(*tl));
      if (!tl)
unknown's avatar
unknown committed
1134
	DBUG_RETURN(1);
unknown's avatar
VIEW  
unknown committed
1135
      update.link_in_list((byte*) tl, (byte**) &tl->next_local);
unknown's avatar
unknown committed
1136 1137
      tl->shared= table_count++;
      table->no_keyread=1;
1138
      table->covering_keys.clear_all();
unknown's avatar
unknown committed
1139
      table->pos_in_table_list= tl;
unknown's avatar
unknown committed
1140 1141 1142
      if (table->triggers &&
          table->triggers->has_triggers(TRG_EVENT_UPDATE,
                                        TRG_ACTION_AFTER))
1143
      {
unknown's avatar
unknown committed
1144 1145 1146 1147 1148 1149
	/*
           The table has AFTER UPDATE triggers that might access to subject 
           table and therefore might need update to be done immediately. 
           So we turn-off the batching.
	*/ 
	(void) table->file->extra(HA_EXTRA_UPDATE_CANNOT_BATCH);
1150
      }
unknown's avatar
unknown committed
1151 1152
    }
  }
unknown's avatar
unknown committed
1153 1154


unknown's avatar
unknown committed
1155 1156 1157
  table_count=  update.elements;
  update_tables= (TABLE_LIST*) update.first;

1158
  tmp_tables = (TABLE**) thd->calloc(sizeof(TABLE *) * table_count);
unknown's avatar
unknown committed
1159 1160 1161 1162 1163 1164
  tmp_table_param = (TMP_TABLE_PARAM*) thd->calloc(sizeof(TMP_TABLE_PARAM) *
						   table_count);
  fields_for_table= (List_item **) thd->alloc(sizeof(List_item *) *
					      table_count);
  values_for_table= (List_item **) thd->alloc(sizeof(List_item *) *
					      table_count);
1165
  if (thd->is_fatal_error)
unknown's avatar
unknown committed
1166 1167 1168 1169 1170 1171
    DBUG_RETURN(1);
  for (i=0 ; i < table_count ; i++)
  {
    fields_for_table[i]= new List_item;
    values_for_table[i]= new List_item;
  }
1172
  if (thd->is_fatal_error)
unknown's avatar
unknown committed
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
    DBUG_RETURN(1);

  /* Split fields into fields_for_table[] and values_by_table[] */

  while ((item= (Item_field *) field_it++))
  {
    Item *value= value_it++;
    uint offset= item->field->table->pos_in_table_list->shared;
    fields_for_table[offset]->push_back(item);
    values_for_table[offset]->push_back(value);
  }
1184
  if (thd->is_fatal_error)
unknown's avatar
unknown committed
1185 1186 1187 1188 1189 1190 1191
    DBUG_RETURN(1);

  /* Allocate copy fields */
  max_fields=0;
  for (i=0 ; i < table_count ; i++)
    set_if_bigger(max_fields, fields_for_table[i]->elements);
  copy_field= new Copy_field[max_fields];
1192 1193
  DBUG_RETURN(thd->is_fatal_error != 0);
}
1194 1195


1196 1197
/*
  Check if table is safe to update on fly
1198

1199 1200 1201 1202 1203
  SYNOPSIS
    safe_update_on_fly()
    thd                 Thread handler
    join_tab            How table is used in join
    all_tables          List of tables
1204

1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
  NOTES
    We can update the first table in join on the fly if we know that
    a row in this table will never be read twice. This is true under
    the following conditions:

    - We are doing a table scan and the data is in a separate file (MyISAM) or
      if we don't update a clustered key.

    - We are doing a range scan and we don't update the scan key or
      the primary key for a clustered table handler.

    - Table is not joined to itself.

1218 1219
    This function gets information about fields to be updated from
    the TABLE::write_set bitmap.
1220

1221 1222 1223 1224 1225 1226 1227 1228 1229
  WARNING
    This code is a bit dependent of how make_join_readinfo() works.

  RETURN
    0		Not safe to update
    1		Safe to update
*/

static bool safe_update_on_fly(THD *thd, JOIN_TAB *join_tab,
1230
                               TABLE_LIST *table_ref, TABLE_LIST *all_tables)
1231 1232
{
  TABLE *table= join_tab->table;
1233
  if (unique_table(thd, table_ref, all_tables, 0))
1234 1235 1236 1237 1238
    return 0;
  switch (join_tab->type) {
  case JT_SYSTEM:
  case JT_CONST:
  case JT_EQ_REF:
1239
    return TRUE;				// At most one matching row
1240
  case JT_REF:
1241
  case JT_REF_OR_NULL:
1242
    return !is_key_used(table, join_tab->ref.key, table->write_set);
1243 1244 1245
  case JT_ALL:
    /* If range search on index */
    if (join_tab->quick)
1246
      return !join_tab->quick->is_keys_used(table->write_set);
1247
    /* If scanning in clustered key */
1248
    if ((table->file->ha_table_flags() & HA_PRIMARY_KEY_IN_READ_INDEX) &&
1249
	table->s->primary_key < MAX_KEY)
1250
      return !is_key_used(table, table->s->primary_key, table->write_set);
1251
    return TRUE;
1252 1253
  default:
    break;					// Avoid compler warning
1254
  }
1255
  return FALSE;
1256

unknown's avatar
unknown committed
1257 1258 1259
}


unknown's avatar
unknown committed
1260
/*
1261
  Initialize table for multi table
unknown's avatar
unknown committed
1262

1263 1264 1265 1266
  IMPLEMENTATION
    - Update first table in join on the fly, if possible
    - Create temporary tables to store changed values for all other tables
      that are updated (and main_table if the above doesn't hold).
unknown's avatar
unknown committed
1267 1268 1269
*/

bool
unknown's avatar
unknown committed
1270 1271
multi_update::initialize_tables(JOIN *join)
{
unknown's avatar
unknown committed
1272 1273 1274 1275 1276 1277 1278
  TABLE_LIST *table_ref;
  DBUG_ENTER("initialize_tables");

  if ((thd->options & OPTION_SAFE_UPDATES) && error_if_full_join(join))
    DBUG_RETURN(1);
  main_table=join->join_tab->table;
  trans_safe= transactional_tables= main_table->file->has_transactions();
1279 1280 1281
  table_to_update= 0;

  /* Create a temporary table for keys to all tables, except main table */
unknown's avatar
VIEW  
unknown committed
1282
  for (table_ref= update_tables; table_ref; table_ref= table_ref->next_local)
unknown's avatar
unknown committed
1283
  {
unknown's avatar
unknown committed
1284
    TABLE *table=table_ref->table;
1285
    uint cnt= table_ref->shared;
unknown's avatar
unknown committed
1286
    Item_field *ifield;
1287 1288
    List<Item> temp_fields= *fields_for_table[cnt];
    ORDER     group;
1289
    TMP_TABLE_PARAM *tmp_param;
unknown's avatar
unknown committed
1290

1291
    table->mark_columns_needed_for_update();
1292 1293
    if (ignore)
      table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
1294 1295
    if (table == main_table)			// First table in join
    {
1296
      if (safe_update_on_fly(thd, join->join_tab, table_ref, all_tables))
1297 1298 1299 1300
      {
	table_to_update= main_table;		// Update table on the fly
	continue;
      }
unknown's avatar
unknown committed
1301
    }
1302
    table->prepare_for_position();
1303

1304
    tmp_param= tmp_table_param+cnt;
1305 1306 1307 1308 1309 1310 1311 1312
    /*
      Create a temporary table to store all fields that are changed for this
      table. The first field in the temporary table is a pointer to the
      original row so that we can find and update it
    */

    /* ok to be on stack as this is not referenced outside of this func */
    Field_string offset(table->file->ref_length, 0, "offset",
unknown's avatar
unknown committed
1313 1314
			&my_charset_bin);
    offset.init(table);
1315 1316 1317 1318 1319
    /*
      The field will be converted to varstring when creating tmp table if
      table to be updated was created by mysql 4.1. Deny this.
    */
    offset.can_alter_field_type= 0;
unknown's avatar
unknown committed
1320
    if (!(ifield= new Item_field(((Field *) &offset))))
unknown's avatar
unknown committed
1321
      DBUG_RETURN(1);
unknown's avatar
unknown committed
1322 1323
    ifield->maybe_null= 0;
    if (temp_fields.push_front(ifield))
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
      DBUG_RETURN(1);

    /* Make an unique key over the first field to avoid duplicated updates */
    bzero((char*) &group, sizeof(group));
    group.asc= 1;
    group.item= (Item**) temp_fields.head_ref();

    tmp_param->quick_group=1;
    tmp_param->field_count=temp_fields.elements;
    tmp_param->group_parts=1;
    tmp_param->group_length= table->file->ref_length;
    if (!(tmp_tables[cnt]=create_tmp_table(thd,
					   tmp_param,
					   temp_fields,
unknown's avatar
unknown committed
1338 1339
					   (ORDER*) &group, 0, 0,
					   TMP_TABLE_ALL_COLUMNS,
1340 1341
					   HA_POS_ERROR,
					   (char *) "")))
1342 1343
      DBUG_RETURN(1);
    tmp_tables[cnt]->file->extra(HA_EXTRA_WRITE_CACHE);
unknown's avatar
unknown committed
1344
  }
unknown's avatar
unknown committed
1345
  DBUG_RETURN(0);
unknown's avatar
unknown committed
1346 1347 1348 1349 1350
}


multi_update::~multi_update()
{
unknown's avatar
unknown committed
1351
  TABLE_LIST *table;
unknown's avatar
VIEW  
unknown committed
1352
  for (table= update_tables ; table; table= table->next_local)
1353
  {
1354
    table->table->no_keyread= table->table->no_cache= 0;
1355 1356 1357
    if (ignore)
      table->table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
  }
unknown's avatar
unknown committed
1358

unknown's avatar
unknown committed
1359 1360
  if (tmp_tables)
  {
1361 1362 1363 1364 1365 1366 1367 1368
    for (uint cnt = 0; cnt < table_count; cnt++)
    {
      if (tmp_tables[cnt])
      {
	free_tmp_table(thd, tmp_tables[cnt]);
	tmp_table_param[cnt].cleanup();
      }
    }
unknown's avatar
unknown committed
1369
  }
unknown's avatar
unknown committed
1370 1371
  if (copy_field)
    delete [] copy_field;
1372
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;		// Restore this setting
unknown's avatar
unknown committed
1373
  if (!trans_safe)
1374
    thd->no_trans_update.all= TRUE;
unknown's avatar
unknown committed
1375 1376 1377
}


unknown's avatar
unknown committed
1378
bool multi_update::send_data(List<Item> &not_used_values)
unknown's avatar
unknown committed
1379
{
unknown's avatar
unknown committed
1380 1381 1382
  TABLE_LIST *cur_table;
  DBUG_ENTER("multi_update::send_data");

unknown's avatar
VIEW  
unknown committed
1383
  for (cur_table= update_tables; cur_table; cur_table= cur_table->next_local)
unknown's avatar
unknown committed
1384
  {
unknown's avatar
unknown committed
1385
    TABLE *table= cur_table->table;
1386
    uint offset= cur_table->shared;
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398
    /*
      Check if we are using outer join and we didn't find the row
      or if we have already updated this row in the previous call to this
      function.

      The same row may be presented here several times in a join of type
      UPDATE t1 FROM t1,t2 SET t1.a=t2.a

      In this case we will do the update for the first found row combination.
      The join algorithm guarantees that we will not find the a row in
      t1 several times.
    */
unknown's avatar
unknown committed
1399 1400 1401
    if (table->status & (STATUS_NULL_ROW | STATUS_UPDATED))
      continue;

1402 1403 1404 1405 1406
    /*
      We can use compare_record() to optimize away updates if
      the table handler is returning all columns OR if
      if all updated columns are read
    */
1407
    if (table == table_to_update)
unknown's avatar
unknown committed
1408
    {
1409 1410 1411 1412 1413
      bool can_compare_record;
      can_compare_record= (!(table->file->ha_table_flags() &
                             HA_PARTIAL_COLUMN_READ) ||
                           bitmap_is_subset(table->write_set,
                                            table->read_set));
unknown's avatar
unknown committed
1414
      table->status|= STATUS_UPDATED;
unknown's avatar
unknown committed
1415
      store_record(table,record[1]);
unknown's avatar
unknown committed
1416 1417 1418 1419
      if (fill_record_n_invoke_before_triggers(thd, *fields_for_table[offset],
                                               *values_for_table[offset], 0,
                                               table->triggers,
                                               TRG_EVENT_UPDATE))
unknown's avatar
unknown committed
1420
	DBUG_RETURN(1);
unknown's avatar
unknown committed
1421

1422
      found++;
1423
      if (!can_compare_record || compare_record(table))
unknown's avatar
unknown committed
1424
      {
unknown's avatar
unknown committed
1425
	int error;
unknown's avatar
unknown committed
1426
        if ((error= cur_table->view_check_option(thd, ignore)) !=
unknown's avatar
unknown committed
1427 1428 1429 1430 1431 1432 1433 1434
            VIEW_CHECK_OK)
        {
          found--;
          if (error == VIEW_CHECK_SKIP)
            continue;
          else if (error == VIEW_CHECK_ERROR)
            DBUG_RETURN(1);
        }
1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447
        if (!updated++)
        {
          /*
            Inform the main table that we are going to update the table even
            while we may be scanning it.  This will flush the read cache
            if it's used.
          */
          main_table->file->extra(HA_EXTRA_PREPARE_FOR_UPDATE);
        }
        if ((error=table->file->ha_update_row(table->record[1],
                                              table->record[0])))
        {
          updated--;
1448
          if (!ignore ||
1449
              table->file->is_fatal_error(error, HA_CHECK_DUP_KEY))
1450
          {
1451
            /*
1452
              If (ignore && error == is ignorable) we don't have to
1453 1454
              do anything; otherwise...
            */
1455
            if (table->file->is_fatal_error(error, HA_CHECK_DUP_KEY))
1456
              thd->fatal_error(); /* Other handler errors are fatal */
1457 1458 1459 1460
            table->file->print_error(error,MYF(0));
            DBUG_RETURN(1);
          }
        }
unknown's avatar
unknown committed
1461 1462 1463
        else
        {
          if (!table->file->has_transactions())
1464
            thd->no_trans_update.stmt= TRUE;
unknown's avatar
unknown committed
1465 1466 1467
          if (table->triggers &&
              table->triggers->process_triggers(thd, TRG_EVENT_UPDATE,
                                                TRG_ACTION_AFTER, TRUE))
1468
            DBUG_RETURN(1);
unknown's avatar
unknown committed
1469
        }
unknown's avatar
unknown committed
1470
      }
unknown's avatar
unknown committed
1471 1472 1473 1474 1475
    }
    else
    {
      int error;
      TABLE *tmp_table= tmp_tables[offset];
1476
      table->file->position(table->record[0]);
unknown's avatar
unknown committed
1477
      fill_record(thd, tmp_table->field+1, *values_for_table[offset], 1);
unknown's avatar
unknown committed
1478 1479 1480 1481
      /* Store pointer to row */
      memcpy((char*) tmp_table->field[0]->ptr,
	     (char*) table->file->ref, table->file->ref_length);
      /* Write row, ignoring duplicated updates to a row */
1482
      error= tmp_table->file->ha_write_row(tmp_table->record[0]);
1483
      if (error != HA_ERR_FOUND_DUPP_KEY && error != HA_ERR_FOUND_DUPP_UNIQUE)
unknown's avatar
unknown committed
1484
      {
1485
        if (error &&
1486
            create_myisam_from_heap(thd, tmp_table,
1487 1488 1489 1490 1491
                                    tmp_table_param + offset, error, 1))
        {
          do_update= 0;
          DBUG_RETURN(1);			// Not a table_is_full error
        }
1492
        found++;
1493
      }
unknown's avatar
unknown committed
1494 1495
    }
  }
unknown's avatar
unknown committed
1496
  DBUG_RETURN(0);
unknown's avatar
unknown committed
1497 1498
}

unknown's avatar
unknown committed
1499

unknown's avatar
unknown committed
1500 1501 1502
void multi_update::send_error(uint errcode,const char *err)
{
  /* First send error what ever it is ... */
unknown's avatar
unknown committed
1503
  my_error(errcode, MYF(0), err);
unknown's avatar
unknown committed
1504 1505 1506 1507

  /* If nothing updated return */
  if (!updated)
    return;
1508

1509
  /* Something already updated so we have to invalidate cache */
1510 1511
  query_cache_invalidate3(thd, update_tables, 1);

unknown's avatar
unknown committed
1512
  /*
unknown's avatar
unknown committed
1513 1514
    If all tables that has been updated are trans safe then just do rollback.
    If not attempt to do remaining updates.
unknown's avatar
unknown committed
1515
  */
unknown's avatar
unknown committed
1516 1517

  if (trans_safe)
unknown's avatar
unknown committed
1518
    ha_rollback_stmt(thd);
unknown's avatar
unknown committed
1519 1520 1521 1522 1523
  else if (do_update && table_count > 1)
  {
    /* Add warning here */
    VOID(do_updates(0));
  }
unknown's avatar
unknown committed
1524 1525 1526
}


unknown's avatar
unknown committed
1527
int multi_update::do_updates(bool from_send_error)
unknown's avatar
unknown committed
1528
{
unknown's avatar
unknown committed
1529 1530 1531
  TABLE_LIST *cur_table;
  int local_error;
  ha_rows org_updated;
unknown's avatar
unknown committed
1532
  TABLE *table, *tmp_table;
unknown's avatar
unknown committed
1533 1534
  DBUG_ENTER("do_updates");

unknown's avatar
unknown committed
1535
  do_update= 0;					// Don't retry this function
1536
  if (!found)
unknown's avatar
unknown committed
1537
    DBUG_RETURN(0);
unknown's avatar
VIEW  
unknown committed
1538
  for (cur_table= update_tables; cur_table; cur_table= cur_table->next_local)
unknown's avatar
unknown committed
1539
  {
1540
    byte *ref_pos;
1541
    bool can_compare_record;
unknown's avatar
unknown committed
1542

unknown's avatar
unknown committed
1543
    table = cur_table->table;
1544
    if (table == table_to_update)
unknown's avatar
unknown committed
1545 1546
      continue;					// Already updated
    org_updated= updated;
1547
    tmp_table= tmp_tables[cur_table->shared];
unknown's avatar
unknown committed
1548
    tmp_table->file->extra(HA_EXTRA_CACHE);	// Change to read cache
unknown's avatar
unknown committed
1549
    (void) table->file->ha_rnd_init(0);
unknown's avatar
unknown committed
1550 1551 1552 1553 1554 1555 1556 1557 1558
    table->file->extra(HA_EXTRA_NO_CACHE);

    /*
      Setup copy functions to copy fields from temporary table
    */
    List_iterator_fast<Item> field_it(*fields_for_table[cur_table->shared]);
    Field **field= tmp_table->field+1;		// Skip row pointer
    Copy_field *copy_field_ptr= copy_field, *copy_field_end;
    for ( ; *field ; field++)
unknown's avatar
unknown committed
1559
    {
unknown's avatar
unknown committed
1560 1561
      Item_field *item= (Item_field* ) field_it++;
      (copy_field_ptr++)->set(item->field, *field, 0);
unknown's avatar
unknown committed
1562
    }
unknown's avatar
unknown committed
1563 1564
    copy_field_end=copy_field_ptr;

unknown's avatar
unknown committed
1565
    if ((local_error = tmp_table->file->ha_rnd_init(1)))
unknown's avatar
unknown committed
1566 1567
      goto err;

1568 1569 1570 1571 1572
    can_compare_record= (!(table->file->ha_table_flags() &
                           HA_PARTIAL_COLUMN_READ) ||
                         bitmap_is_subset(table->write_set,
                                          table->read_set));

unknown's avatar
unknown committed
1573 1574
    ref_pos= (byte*) tmp_table->field[0]->ptr;
    for (;;)
unknown's avatar
unknown committed
1575
    {
unknown's avatar
unknown committed
1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587
      if (thd->killed && trans_safe)
	goto err;
      if ((local_error=tmp_table->file->rnd_next(tmp_table->record[0])))
      {
	if (local_error == HA_ERR_END_OF_FILE)
	  break;
	if (local_error == HA_ERR_RECORD_DELETED)
	  continue;				// May happen on dup key
	goto err;
      }
      if ((local_error= table->file->rnd_pos(table->record[0], ref_pos)))
	goto err;
unknown's avatar
unknown committed
1588
      table->status|= STATUS_UPDATED;
unknown's avatar
unknown committed
1589
      store_record(table,record[1]);
unknown's avatar
unknown committed
1590 1591 1592 1593 1594 1595 1596

      /* Copy data from temporary table to current table */
      for (copy_field_ptr=copy_field;
	   copy_field_ptr != copy_field_end;
	   copy_field_ptr++)
	(*copy_field_ptr->do_copy)(copy_field_ptr);

unknown's avatar
unknown committed
1597 1598 1599 1600 1601
      if (table->triggers &&
          table->triggers->process_triggers(thd, TRG_EVENT_UPDATE,
                                            TRG_ACTION_BEFORE, TRUE))
        goto err2;

1602
      if (!can_compare_record || compare_record(table))
unknown's avatar
unknown committed
1603
      {
unknown's avatar
unknown committed
1604 1605 1606 1607 1608 1609 1610 1611 1612
        int error;
        if ((error= cur_table->view_check_option(thd, ignore)) !=
            VIEW_CHECK_OK)
        {
          if (error == VIEW_CHECK_SKIP)
            continue;
          else if (error == VIEW_CHECK_ERROR)
            goto err;
        }
1613 1614
	if ((local_error=table->file->ha_update_row(table->record[1],
						    table->record[0])))
unknown's avatar
unknown committed
1615
	{
1616
	  if (!ignore ||
1617
              table->file->is_fatal_error(local_error, HA_CHECK_DUP_KEY))
unknown's avatar
unknown committed
1618 1619 1620
	    goto err;
	}
	updated++;
unknown's avatar
unknown committed
1621 1622 1623 1624 1625

        if (table->triggers &&
            table->triggers->process_triggers(thd, TRG_EVENT_UPDATE,
                                              TRG_ACTION_AFTER, TRUE))
          goto err2;
unknown's avatar
unknown committed
1626
      }
unknown's avatar
unknown committed
1627 1628 1629 1630 1631
    }

    if (updated != org_updated)
    {
      if (table->file->has_transactions())
unknown's avatar
unknown committed
1632
	transactional_tables= 1;
unknown's avatar
unknown committed
1633
      else
unknown's avatar
unknown committed
1634
	trans_safe= 0;				// Can't do safe rollback
unknown's avatar
unknown committed
1635
    }
unknown's avatar
unknown committed
1636 1637
    (void) table->file->ha_rnd_end();
    (void) tmp_table->file->ha_rnd_end();
unknown's avatar
unknown committed
1638
  }
unknown's avatar
unknown committed
1639 1640 1641 1642
  DBUG_RETURN(0);

err:
  if (!from_send_error)
unknown's avatar
unknown committed
1643 1644
  {
    thd->fatal_error();
unknown's avatar
unknown committed
1645
    table->file->print_error(local_error,MYF(0));
unknown's avatar
unknown committed
1646
  }
unknown's avatar
unknown committed
1647

unknown's avatar
unknown committed
1648
err2:
unknown's avatar
unknown committed
1649 1650 1651
  (void) table->file->ha_rnd_end();
  (void) tmp_table->file->ha_rnd_end();

unknown's avatar
unknown committed
1652 1653 1654
  if (updated != org_updated)
  {
    if (table->file->has_transactions())
unknown's avatar
unknown committed
1655
      transactional_tables= 1;
unknown's avatar
unknown committed
1656 1657 1658 1659
    else
      trans_safe= 0;
  }
  DBUG_RETURN(1);
unknown's avatar
unknown committed
1660 1661 1662
}


unknown's avatar
unknown committed
1663 1664
/* out: 1 if error, 0 if success */

unknown's avatar
unknown committed
1665 1666
bool multi_update::send_eof()
{
unknown's avatar
unknown committed
1667
  char buff[STRING_BUFFER_USUAL_SIZE];
1668
  ulonglong id;
unknown's avatar
unknown committed
1669
  thd->proc_info="updating reference tables";
unknown's avatar
unknown committed
1670 1671

  /* Does updates for the last n - 1 tables, returns 0 if ok */
unknown's avatar
unknown committed
1672
  int local_error = (table_count) ? do_updates(0) : 0;
1673
  thd->proc_info= "end";
unknown's avatar
unknown committed
1674

unknown's avatar
unknown committed
1675 1676 1677 1678 1679 1680 1681 1682
  /* We must invalidate the query cache before binlog writing and
  ha_autocommit_... */

  if (updated)
  {
    query_cache_invalidate3(thd, update_tables, 1);
  }

unknown's avatar
unknown committed
1683 1684
  /*
    Write the SQL statement to the binlog if we updated
unknown's avatar
unknown committed
1685
    rows and we succeeded or if we updated some non
1686
    transactional tables.
unknown's avatar
unknown committed
1687
  */
unknown's avatar
unknown committed
1688

1689
  if ((local_error == 0) || (updated && !trans_safe))
unknown's avatar
unknown committed
1690
  {
unknown's avatar
unknown committed
1691 1692
    if (mysql_bin_log.is_open())
    {
1693
      if (local_error == 0)
unknown's avatar
unknown committed
1694
        thd->clear_error();
1695 1696 1697 1698 1699
      if (thd->binlog_query(THD::ROW_QUERY_TYPE,
                            thd->query, thd->query_length,
                            transactional_tables, FALSE) &&
          trans_safe)
      {
1700
	local_error= 1;				// Rollback update
1701
      }
unknown's avatar
unknown committed
1702
    }
unknown's avatar
unknown committed
1703
    if (!transactional_tables)
1704
     thd->no_trans_update.all= TRUE;
unknown's avatar
unknown committed
1705
  }
unknown's avatar
unknown committed
1706

unknown's avatar
unknown committed
1707 1708
  if (transactional_tables)
  {
1709
    if (ha_autocommit_or_rollback(thd, local_error != 0))
unknown's avatar
unknown committed
1710 1711
      local_error=1;
  }
unknown's avatar
unknown committed
1712

unknown's avatar
unknown committed
1713 1714 1715 1716 1717
  if (local_error > 0) // if the above log write did not fail ...
  {
    /* Safety: If we haven't got an error before (should not happen) */
    my_message(ER_UNKNOWN_ERROR, "An error occured in multi-table update",
	       MYF(0));
1718
    return TRUE;
unknown's avatar
unknown committed
1719
  }
unknown's avatar
unknown committed
1720

1721 1722
  id= thd->arg_of_last_insert_id_function ?
    thd->first_successful_insert_id_in_prev_stmt : 0;
1723 1724
  sprintf(buff, ER(ER_UPDATE_INFO), (ulong) found, (ulong) updated,
	  (ulong) thd->cuted_fields);
1725 1726
  thd->row_count_func=
    (thd->client_capabilities & CLIENT_FOUND_ROWS) ? found : updated;
1727
  ::send_ok(thd, (ulong) thd->row_count_func, id, buff);
1728
  return FALSE;
unknown's avatar
unknown committed
1729
}