sql_update.cc 45.5 KB
Newer Older
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1
/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
2

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3 4 5 6
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
7

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

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


18 19 20
/*
  Single table and multi table updates of tables.
  Multi-table updates were introduced by Sinisa & Monty
21
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
22 23

#include "mysql_priv.h"
24
#include "sql_select.h"
25 26
#include "sp_head.h"
#include "sql_trigger.h"
bk@work.mysql.com's avatar
bk@work.mysql.com committed
27

28 29
static bool safe_update_on_fly(JOIN_TAB *join_tab, List<Item> *fields);

bk@work.mysql.com's avatar
bk@work.mysql.com committed
30 31
/* Return 0 if row hasn't changed */

32
static bool compare_record(TABLE *table, query_id_t query_id)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
33
{
34
  if (table->s->blob_fields + table->s->varchar_fields == 0)
35
    return cmp_record(table,record[1]);
36
  /* Compare null bits */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
37
  if (memcmp(table->null_flags,
38 39
	     table->null_flags+table->s->rec_buff_length,
	     table->s->null_bytes))
40
    return TRUE;				// Diff in NULL value
41
  /* Compare updated fields */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
42 43
  for (Field **ptr=table->field ; *ptr ; ptr++)
  {
44
    if ((*ptr)->query_id == query_id &&
45
	(*ptr)->cmp_binary_offset(table->s->rec_buff_length))
46
      return TRUE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
47
  }
48
  return FALSE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
49 50 51
}


bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
52 53 54 55 56
/*
  check that all fields are real fields

  SYNOPSIS
    check_fields()
57
    thd             thread handler
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
58 59 60 61 62 63 64
    items           Items for check

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

65
static bool check_fields(THD *thd, List<Item> &items)
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
66
{
67
  List_iterator<Item> it(items);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
68
  Item *item;
69
  Item_field *field;
70 71
  Name_resolution_context *context= &thd->lex->select_lex.context;

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


90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
/*
  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
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
108
    1  - error
109 110
*/

111 112 113 114 115
int mysql_update(THD *thd,
                 TABLE_LIST *table_list,
                 List<Item> &fields,
		 List<Item> &values,
                 COND *conds,
116
                 uint order_num, ORDER *order,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
117
		 ha_rows limit,
118
		 enum enum_duplicates handle_duplicates, bool ignore)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
119
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
120
  bool		using_limit= limit != HA_POS_ERROR;
121
  bool		safe_update= thd->options & OPTION_SAFE_UPDATES;
mronstrom@mysql.com[mikron]'s avatar
mronstrom@mysql.com[mikron] committed
122
  bool		used_key_is_modified, transactional_table, will_batch;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
123
  int           res;
mronstrom@mysql.com[mikron]'s avatar
mronstrom@mysql.com[mikron] committed
124 125
  int		error=0, loc_error;
  uint		used_index, dup_key_found;
126 127 128
#ifndef NO_EMBEDDED_ACCESS_CHECKS
  uint		want_privilege;
#endif
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
129
  uint          table_count= 0;
130
  query_id_t	query_id=thd->query_id, timestamp_query_id;
131
  ha_rows	updated, found;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
132 133 134 135
  key_map	old_used_keys;
  TABLE		*table;
  SQL_SELECT	*select;
  READ_RECORD	info;
136
  SELECT_LEX    *select_lex= &thd->lex->select_lex;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
137
  DBUG_ENTER("mysql_update");
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
138

139
  LINT_INIT(timestamp_query_id);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
140

141
  if (open_tables(thd, &table_list, &table_count))
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
142
    DBUG_RETURN(1);
143

igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
144
  if (table_list->multitable_view)
145
  {
146
    DBUG_ASSERT(table_list->view != 0);
147
    DBUG_PRINT("info", ("Switch to multi-update"));
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
148 149
    /* pass counter value */
    thd->lex->table_count= table_count;
150
    /* convert to multiupdate */
151
    DBUG_RETURN(2);
152
  }
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
153 154 155 156 157

  if (lock_tables(thd, table_list, table_count) ||
      mysql_handle_derived(thd->lex, &mysql_derived_prepare) ||
      (thd->fill_derived_tables() &&
       mysql_handle_derived(thd->lex, &mysql_derived_filling)))
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
158
    DBUG_RETURN(1);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
159

bk@work.mysql.com's avatar
bk@work.mysql.com committed
160
  thd->proc_info="init";
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
161
  table= table_list->table;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
162 163
  table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);

164
  /* Calculate "table->used_keys" based on the WHERE */
165
  table->used_keys= table->s->keys_in_use;
166
  table->quick_keys.clear_all();
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
167

hf@deer.(none)'s avatar
hf@deer.(none) committed
168
#ifndef NO_EMBEDDED_ACCESS_CHECKS
169 170
  /* TABLE_LIST contain right privilages request */
  want_privilege= table_list->grant.want_privilege;
hf@deer.(none)'s avatar
hf@deer.(none) committed
171
#endif
172
  if (mysql_prepare_update(thd, table_list, &conds, order_num, order))
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
173
    DBUG_RETURN(1);
174

monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
175
  old_used_keys= table->used_keys;		// Keys used in WHERE
bk@work.mysql.com's avatar
bk@work.mysql.com committed
176
  /*
177 178
    Change the query_id for the timestamp column so that we can
    check if this is modified directly
bk@work.mysql.com's avatar
bk@work.mysql.com committed
179
  */
180 181 182 183 184
  if (table->timestamp_field)
  {
    timestamp_query_id=table->timestamp_field->query_id;
    table->timestamp_field->query_id=thd->query_id-1;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
185

186
  /* Check the fields we are going to modify */
hf@deer.(none)'s avatar
hf@deer.(none) committed
187
#ifndef NO_EMBEDDED_ACCESS_CHECKS
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
188
  table_list->grant.want_privilege= table->grant.want_privilege= want_privilege;
hf@deer.(none)'s avatar
hf@deer.(none) committed
189
#endif
tomas@poseidon.ndb.mysql.com's avatar
Merge  
tomas@poseidon.ndb.mysql.com committed
190 191 192 193 194
  /*
    Indicate that the set of fields is to be updated by passing 2 for
    set_query_id.
  */
  if (setup_fields_with_no_wrap(thd, 0, fields, 2, 0, 0))
195
    DBUG_RETURN(1);                     /* purecov: inspected */
196
  if (table_list->view && check_fields(thd, fields))
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
197
  {
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
198
    DBUG_RETURN(1);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
199 200 201
  }
  if (!table_list->updatable || check_key_in_view(thd, table_list))
  {
202
    my_error(ER_NON_UPDATABLE_TABLE, MYF(0), table_list->alias, "UPDATE");
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
203
    DBUG_RETURN(1);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
204
  }
205 206 207 208
  if (table->timestamp_field)
  {
    // Don't set timestamp column if this is modified
    if (table->timestamp_field->query_id == thd->query_id)
209
      table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
210
    else
211
    {
212
      table->timestamp_field->query_id=timestamp_query_id;
213 214
      table->file->ha_set_bit_in_write_set(table->timestamp_field->fieldnr);
    }
215
  }
216

hf@deer.(none)'s avatar
hf@deer.(none) committed
217
#ifndef NO_EMBEDDED_ACCESS_CHECKS
218
  /* Check values */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
219
  table_list->grant.want_privilege= table->grant.want_privilege=
220
    (SELECT_ACL & ~table->grant.privilege);
hf@deer.(none)'s avatar
hf@deer.(none) committed
221
#endif
222
  if (setup_fields(thd, 0, values, 1, 0, 0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
223
  {
224
    free_underlaid_joins(thd, select_lex);
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
225
    DBUG_RETURN(1);				/* purecov: inspected */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
226
  }
227

228
  // Don't count on usage of 'only index' when calculating which key to use
229
  table->used_keys.clear_all();
monty@mysql.com's avatar
monty@mysql.com committed
230
  select= make_select(table, 0, 0, conds, 0, &error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
231
  if (error ||
232
      (select && select->check_quick(thd, safe_update, limit)) || !limit)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
233 234
  {
    delete select;
235
    free_underlaid_joins(thd, select_lex);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
236 237
    if (error)
    {
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
238
      DBUG_RETURN(1);				// Error in where
bk@work.mysql.com's avatar
bk@work.mysql.com committed
239
    }
240
    send_ok(thd);				// No matching records
bk@work.mysql.com's avatar
bk@work.mysql.com committed
241 242 243
    DBUG_RETURN(0);
  }
  /* If running in safe sql mode, don't allow updates without keys */
244
  if (table->quick_keys.is_clear_all())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
245
  {
246
    thd->server_status|=SERVER_QUERY_NO_INDEX_USED;
247
    if (safe_update && !using_limit)
248
    {
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
249 250 251
      my_message(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE,
		 ER(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE), MYF(0));
      goto err;
252
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
253
  }
254
  init_ftfuncs(thd, select_lex, 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
255
  /* Check if we are modifying a key that we are used to search with */
256
  
bk@work.mysql.com's avatar
bk@work.mysql.com committed
257
  if (select && select->quick)
258
  {
259
    used_index= select->quick->index;
260 261
    used_key_is_modified= (!select->quick->unique_key_range() &&
                          select->quick->check_if_keys_used(&fields));
262
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
263 264 265 266
  else if ((used_index=table->file->key_used_on_scan) < MAX_KEY)
    used_key_is_modified=check_if_key_used(table, used_index, fields);
  else
    used_key_is_modified=0;
267

268 269 270 271
#ifdef HAVE_PARTITION_DB
  if (used_key_is_modified || order ||
      partition_key_modified(table, fields))
#else
mronstrom@mysql.com's avatar
mronstrom@mysql.com committed
272
  if (used_key_is_modified || order)
273
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
274 275
  {
    /*
276 277
      We can't update table directly;  We must first search after all
      matching rows before updating the table!
bk@work.mysql.com's avatar
bk@work.mysql.com committed
278
    */
279
    table->file->ha_retrieve_all_cols();
280
    if (used_index < MAX_KEY && old_used_keys.is_set(used_index))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
281 282 283 284
    {
      table->key_read=1;
      table->file->extra(HA_EXTRA_KEYREAD);
    }
285 286 287

    if (order)
    {
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
288 289 290 291
      /*
	Doing an ORDER BY;  Let filesort find and sort the rows we are going
	to update
      */
292 293
      uint         length;
      SORT_FIELD  *sortorder;
294
      ha_rows examined_rows;
295

igor@hundin.mysql.fi's avatar
igor@hundin.mysql.fi committed
296
      table->sort.io_cache = (IO_CACHE *) my_malloc(sizeof(IO_CACHE),
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
297
						    MYF(MY_FAE | MY_ZEROFILL));
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
298
      if (!(sortorder=make_unireg_sortorder(order, &length)) ||
igor@hundin.mysql.fi's avatar
igor@hundin.mysql.fi committed
299
          (table->sort.found_records = filesort(thd, table, sortorder, length,
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
300
						select, limit,
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
301
						&examined_rows))
302 303
          == HA_POS_ERROR)
      {
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
304
	free_io_cache(table);
305
	goto err;
306
      }
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
307 308 309 310 311 312
      /*
	Filesort has already found and selected the rows we want to update,
	so we don't need the where clause
      */
      delete select;
      select= 0;
313
    }
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
314
    else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
315
    {
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
316 317 318 319 320 321 322 323 324
      /*
	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)))
325
	goto err;
326
      
sergefp@mysql.com's avatar
sergefp@mysql.com committed
327 328 329
      /* If quick select is used, initialize it before retrieving rows. */
      if (select && select->quick && select->quick->reset())
        goto err;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
330
      init_read_record(&info,thd,table,select,0,1);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
331

monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
332 333
      thd->proc_info="Searching rows for update";
      uint tmp_limit= limit;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
334

monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
335
      while (!(error=info.read_record(&info)) && !thd->killed)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
336
      {
337
	if (!(select && select->skip_record()))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
338
	{
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
339 340 341 342 343 344 345 346
	  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)
347 348
	  {
	    error= -1;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
349
	    break;
350
	  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
351
	}
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
352 353
	else
	  table->file->unlock_row();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
354
      }
355 356
      if (thd->killed && !error)
	error= 1;				// Aborted
357
      limit= tmp_limit;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
358 359 360 361 362 363 364 365 366 367
      end_read_record(&info);
      /* Change select to use tempfile */
      if (select)
      {
	delete select->quick;
	if (select->free_cond)
	  delete select->cond;
	select->quick=0;
	select->cond=0;
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
368 369
      else
      {
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
370 371
	select= new SQL_SELECT;
	select->head=table;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
372
      }
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
373 374 375 376
      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)
377
	goto err;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
378 379 380 381 382 383 384 385
    }
    if (table->key_read)
    {
      table->key_read=0;
      table->file->extra(HA_EXTRA_NO_KEYREAD);
    }
  }

386
  if (ignore)
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
387
    table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
388 389 390
  
  if (select && select->quick && select->quick->reset())
        goto err;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
391 392
  init_read_record(&info,thd,table,select,0,1);

393
  updated= found= 0;
394
  thd->count_cuted_fields= CHECK_FIELD_WARN;		/* calc cuted fields */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
395
  thd->cuted_fields=0L;
396
  thd->proc_info="Updating";
397
  query_id=thd->query_id;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
398

399 400
  transactional_table= table->file->has_transactions();
  thd->no_trans_update= 0;
monty@mysql.com's avatar
monty@mysql.com committed
401
  thd->abort_on_warning= test(!ignore &&
402 403 404
                              (thd->variables.sql_mode &
                               (MODE_STRICT_TRANS_TABLES |
                                MODE_STRICT_ALL_TABLES)));
mronstrom@mysql.com's avatar
mronstrom@mysql.com committed
405
  will_batch= !table->file->start_bulk_update();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
406 407
  while (!(error=info.read_record(&info)) && !thd->killed)
  {
408
    if (!(select && select->skip_record()))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
409
    {
410
      store_record(table,record[1]);
411 412 413
      if (fill_record_n_invoke_before_triggers(thd, fields, values, 0,
                                               table->triggers,
                                               TRG_EVENT_UPDATE))
414
	break; /* purecov: inspected */
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
415

bk@work.mysql.com's avatar
bk@work.mysql.com committed
416
      found++;
417

418
      if (compare_record(table, query_id))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
419
      {
monty@mysql.com's avatar
monty@mysql.com committed
420
        if ((res= table_list->view_check_option(thd, ignore)) !=
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
421 422 423 424 425 426 427 428 429 430 431
            VIEW_CHECK_OK)
        {
          found--;
          if (res == VIEW_CHECK_SKIP)
            continue;
          else if (res == VIEW_CHECK_ERROR)
          {
            error= 1;
            break;
          }
        }
mronstrom@mysql.com[mikron]'s avatar
mronstrom@mysql.com[mikron] committed
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
        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).
          */
460 461
          error= table->file->bulk_update_row(table->record[1],
                                              table->record[0],
mronstrom@mysql.com's avatar
mronstrom@mysql.com committed
462
                                              &dup_key_found);
mronstrom@mysql.com[mikron]'s avatar
mronstrom@mysql.com[mikron] committed
463
          limit+= dup_key_found;
mronstrom@mysql.com's avatar
mronstrom@mysql.com committed
464
          updated-= dup_key_found;
mronstrom@mysql.com[mikron]'s avatar
mronstrom@mysql.com[mikron] committed
465 466 467 468
        }
        else
        {
          /* Non-batched update */
mronstrom@mysql.com's avatar
mronstrom@mysql.com committed
469 470
	  error= table->file->update_row((byte*) table->record[1],
	                                 (byte*) table->record[0]);
mronstrom@mysql.com[mikron]'s avatar
mronstrom@mysql.com[mikron] committed
471 472
        }
        if (!error)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
473 474
	{
	  updated++;
475
          thd->no_trans_update= !transactional_table;
476 477 478 479 480 481 482 483

          if (table->triggers &&
              table->triggers->process_triggers(thd, TRG_EVENT_UPDATE,
                                                TRG_ACTION_AFTER, TRUE))
          {
            error= 1;
            break;
          }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
484
	}
485
 	else if (!ignore || error != HA_ERR_FOUND_DUPP_KEY)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
486
	{
monty@mysql.com's avatar
monty@mysql.com committed
487
          thd->fatal_error();                   // Force error message
bk@work.mysql.com's avatar
bk@work.mysql.com committed
488 489 490 491 492
	  table->file->print_error(error,MYF(0));
	  error= 1;
	  break;
	}
      }
493

monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
494 495
      if (!--limit && using_limit)
      {
mronstrom@mysql.com[mikron]'s avatar
mronstrom@mysql.com[mikron] committed
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
        /*
          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));
mronstrom@mysql.com's avatar
mronstrom@mysql.com committed
516
            error= 1;
mronstrom@mysql.com[mikron]'s avatar
mronstrom@mysql.com[mikron] committed
517 518 519 520 521 522 523
            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.
          */
mronstrom@mysql.com's avatar
mronstrom@mysql.com committed
524 525
          limit= dup_key_found; //limit is 0 when we get here so need to +
          updated-= dup_key_found;
mronstrom@mysql.com[mikron]'s avatar
mronstrom@mysql.com[mikron] committed
526 527 528 529 530 531
        }
        else
        {
	  error= -1;				// Simulate end of file
	  break;
        }
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
532
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
533
    }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
534 535
    else
      table->file->unlock_row();
536
    thd->row_count++;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
537
  }
mronstrom@mysql.com's avatar
mronstrom@mysql.com committed
538
  dup_key_found= 0;
539 540
  if (thd->killed && !error)
    error= 1;					// Aborted
mronstrom@mysql.com[mikron]'s avatar
mronstrom@mysql.com[mikron] committed
541 542 543 544 545 546 547 548 549 550 551 552 553
  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));
mronstrom@mysql.com's avatar
mronstrom@mysql.com committed
554
    error= 1;
mronstrom@mysql.com[mikron]'s avatar
mronstrom@mysql.com[mikron] committed
555 556
  }
  else
mronstrom@mysql.com's avatar
mronstrom@mysql.com committed
557
    updated-= dup_key_found;
mronstrom@mysql.com[mikron]'s avatar
mronstrom@mysql.com[mikron] committed
558 559
  if (will_batch)
    table->file->end_bulk_update();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
560
  end_read_record(&info);
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
561
  free_io_cache(table);				// If ORDER BY
562
  delete select;
mronstrom@mysql.com's avatar
mronstrom@mysql.com committed
563
  thd->proc_info= "end";
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
564
  VOID(table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY));
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
565 566 567 568 569 570

  /*
    Invalidate the table in the query cache if something changed.
    This must be before binlog writing and ha_autocommit_...
  */
  if (updated)
monty@mysql.com's avatar
monty@mysql.com committed
571
  {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
572
    query_cache_invalidate3(thd, table_list, 1);
monty@mysql.com's avatar
monty@mysql.com committed
573
  }
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
574

575
  if ((updated || (error < 0)) && (error <= 0 || !transactional_table))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
576
  {
577 578
    if (mysql_bin_log.is_open())
    {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
579 580
      if (error <= 0)
        thd->clear_error();
581
      Query_log_event qinfo(thd, thd->query, thd->query_length,
582
			    transactional_table, FALSE);
583 584
      if (mysql_bin_log.write(&qinfo) && transactional_table)
	error=1;				// Rollback update
585
    }
586
    if (!transactional_table)
587
      thd->options|=OPTION_STATUS_NO_TRANS_UPDATE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
588
  }
589 590 591 592 593
  if (transactional_table)
  {
    if (ha_autocommit_or_rollback(thd, error >= 0))
      error=1;
  }
594

595 596 597 598 599 600
  if (thd->lock)
  {
    mysql_unlock_tables(thd, thd->lock);
    thd->lock=0;
  }

601
  free_underlaid_joins(thd, select_lex);
602
  if (error < 0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
603
  {
604
    char buff[STRING_BUFFER_USUAL_SIZE];
605 606
    sprintf(buff, ER(ER_UPDATE_INFO), (ulong) found, (ulong) updated,
	    (ulong) thd->cuted_fields);
607 608
    thd->row_count_func=
      (thd->client_capabilities & CLIENT_FOUND_ROWS) ? found : updated;
609
    send_ok(thd, (ulong) thd->row_count_func,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
610 611 612
	    thd->insert_id_used ? thd->insert_id() : 0L,buff);
    DBUG_PRINT("info",("%d records updated",updated));
  }
613
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;		/* calc cuted fields */
614
  thd->abort_on_warning= 0;
serg@serg.mysql.com's avatar
serg@serg.mysql.com committed
615
  free_io_cache(table);
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
616
  DBUG_RETURN((error >= 0 || thd->net.report_error) ? 1 : 0);
617 618 619

err:
  delete select;
620
  free_underlaid_joins(thd, select_lex);
621 622 623 624 625
  if (table->key_read)
  {
    table->key_read=0;
    table->file->extra(HA_EXTRA_NO_KEYREAD);
  }
626
  thd->abort_on_warning= 0;
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
627
  DBUG_RETURN(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
628
}
629

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
630 631 632 633 634 635
/*
  Prepare items in UPDATE statement

  SYNOPSIS
    mysql_prepare_update()
    thd			- thread handler
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
636
    table_list		- global/local table list
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
637 638 639 640 641
    conds		- conditions
    order_num		- number of ORDER BY list entries
    order		- ORDER BY clause list

  RETURN VALUE
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
642 643
    FALSE OK
    TRUE  error
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
644
*/
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
645
bool mysql_prepare_update(THD *thd, TABLE_LIST *table_list,
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
646 647 648 649 650
			 Item **conds, uint order_num, ORDER *order)
{
  TABLE *table= table_list->table;
  TABLE_LIST tables;
  List<Item> all_fields;
651
  SELECT_LEX *select_lex= &thd->lex->select_lex;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
652 653 654
  DBUG_ENTER("mysql_prepare_update");

#ifndef NO_EMBEDDED_ACCESS_CHECKS
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
655 656
  table_list->grant.want_privilege= table->grant.want_privilege= 
    (SELECT_ACL & ~table->grant.privilege);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
657 658 659 660 661 662
#endif

  bzero((char*) &tables,sizeof(tables));	// For ORDER BY
  tables.table= table;
  tables.alias= table_list->alias;

663 664 665
  if (setup_tables(thd, &select_lex->context,
                   table_list, conds, &select_lex->leaf_tables,
                   FALSE) ||
666
      setup_conds(thd, table_list, select_lex->leaf_tables, conds) ||
667 668
      select_lex->setup_ref_array(thd, order_num) ||
      setup_order(thd, select_lex->ref_pointer_array,
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
669
		  table_list, all_fields, all_fields, order) ||
670
      setup_ftfuncs(select_lex))
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
671
    DBUG_RETURN(TRUE);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
672 673

  /* Check that we are not using table that we are updating in a sub select */
674
  if (unique_table(table_list, table_list->next_global))
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
675
  {
676
    my_error(ER_UPDATE_TABLE_USED, MYF(0), table_list->table_name);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
677
    DBUG_RETURN(TRUE);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
678
  }
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
679
  select_lex->fix_prepare_information(thd, conds);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
680
  DBUG_RETURN(FALSE);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
681 682
}

683

684
/***************************************************************************
685
  Update multiple tables from join 
686 687
***************************************************************************/

688
/*
689
  Get table map for list of Item_field
690 691
*/

692 693 694 695 696 697 698 699 700 701 702 703 704
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();
  DBUG_PRINT("info",("table_map: 0x%08x", map));
  return map;
}


bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
705 706
/*
  make update specific preparation and checks after opening tables
707

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
708 709 710
  SYNOPSIS
    mysql_multi_update_prepare()
    thd         thread handler
711

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
712
  RETURN
713 714
    FALSE OK
    TRUE  Error
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
715
*/
716

717
bool mysql_multi_update_prepare(THD *thd)
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
718 719
{
  LEX *lex= thd->lex;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
720
  ulong opened_tables;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
721
  TABLE_LIST *table_list= lex->query_tables;
monty@mysql.com's avatar
monty@mysql.com committed
722
  TABLE_LIST *tl, *leaves;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
723
  List<Item> *fields= &lex->select_lex.item_list;
724
  table_map tables_for_update;
725
  bool update_view= 0;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
726 727 728 729 730 731
  /*
    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;
732
  const bool using_lock_tables= thd->locked_tables != 0;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
733
  bool original_multiupdate= (thd->lex->sql_command == SQLCOM_UPDATE_MULTI);
monty@mysql.com's avatar
monty@mysql.com committed
734 735
  DBUG_ENTER("mysql_multi_update_prepare");

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
736 737
  /* following need for prepared statements, to run next time multi-update */
  thd->lex->sql_command= SQLCOM_UPDATE_MULTI;
738 739

  /* open tables and create derived ones, but do not lock and fill them */
740
  if ((original_multiupdate && open_tables(thd, &table_list, & table_count)) ||
741
      mysql_handle_derived(lex, &mysql_derived_prepare))
742
    DBUG_RETURN(TRUE);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
743 744 745 746 747
  /*
    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()).
  */
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
748

749 750
  if (setup_tables(thd, &lex->select_lex.context,
                   table_list, &lex->select_lex.where,
751
                   &lex->select_lex.leaf_tables, FALSE))
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
752
    DBUG_RETURN(TRUE);
753

tomas@poseidon.ndb.mysql.com's avatar
Merge  
tomas@poseidon.ndb.mysql.com committed
754
  if (setup_fields_with_no_wrap(thd, 0, *fields, 2, 0, 0))
755
    DBUG_RETURN(TRUE);
756 757 758 759 760 761 762 763 764 765 766

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

  if (update_view && check_fields(thd, *fields))
767
  {
768
    DBUG_RETURN(TRUE);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
769 770
  }

771
  tables_for_update= get_table_map(fields);
772 773

  /*
774
    Setup timestamp handling and locking mode
775
  */
776
  leaves= lex->select_lex.leaf_tables;
777
  for (tl= leaves; tl; tl= tl->next_leaf)
778
  {
779
    TABLE *table= tl->table;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
780
    /* Only set timestamp column if this is not modified */
781 782
    if (table->timestamp_field &&
        table->timestamp_field->query_id == thd->query_id)
monty@mysql.com's avatar
monty@mysql.com committed
783
      table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
784

785 786
    /* if table will be updated then check that it is unique */
    if (table->map & tables_for_update)
787
    {
788
      if (!tl->updatable || check_key_in_view(thd, tl))
789
      {
790
        my_error(ER_NON_UPDATABLE_TABLE, MYF(0), tl->alias, "UPDATE");
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
791
        DBUG_RETURN(TRUE);
792
      }
793 794

      DBUG_PRINT("info",("setting table `%s` for update", tl->alias));
795 796 797 798
      /*
        If table will be updated we should not downgrade lock for it and
        leave it as is.
      */
monty@mysql.com's avatar
monty@mysql.com committed
799
    }
800 801 802
    else
    {
      DBUG_PRINT("info",("setting table `%s` for read-only", tl->alias));
monty@mysql.com's avatar
monty@mysql.com committed
803 804 805 806 807 808
      /*
        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;
809
      tl->updating= 0;
810 811 812
      /* Update TABLE::lock_type accordingly. */
      if (!tl->placeholder() && !tl->schema_table && !using_lock_tables)
        tl->table->reginfo.lock_type= tl->lock_type;
813
    }
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
814
  }
815
  for (tl= table_list; tl; tl= tl->next_local)
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
816
  {
monty@mishka.local's avatar
monty@mishka.local committed
817
    /* Check access privileges for table */
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
818
    if (!tl->derived)
819
    {
monty@mysql.com's avatar
monty@mysql.com committed
820 821 822 823
      uint want_privilege= tl->updating ? UPDATE_ACL : SELECT_ACL;
      if (check_access(thd, want_privilege,
                        tl->db, &tl->grant.privilege, 0, 0) ||
          (grant_option && check_grant(thd, want_privilege, tl, 0, 1, 0)))
monty@mishka.local's avatar
monty@mishka.local committed
824
        DBUG_RETURN(TRUE);
825
    }
826
  }
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
827

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
828 829 830
  /* check single table update for view compound from several tables */
  for (tl= table_list; tl; tl= tl->next_local)
  {
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
831
    if (tl->effective_algorithm == VIEW_ALGORITHM_MERGE)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
832 833
    {
      TABLE_LIST *for_update= 0;
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
834
      if (tl->check_single_table(&for_update, tables_for_update, tl))
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
835 836 837 838 839 840 841 842
      {
	my_error(ER_VIEW_MULTIUPDATE, MYF(0),
		 tl->view_db.str, tl->view_name.str);
	DBUG_RETURN(-1);
      }
    }
  }

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
843
  opened_tables= thd->status_var.opened_tables;
844
  /* now lock and fill tables */
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
845
  if (lock_tables(thd, table_list, table_count))
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
846
    DBUG_RETURN(TRUE);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
847 848 849 850 851 852 853 854 855 856 857 858 859

  /*
    we have to re-call fixfields for fixed items, because lock maybe
    reopened tables
  */
  if (opened_tables != thd->status_var.opened_tables)
  {
    /*
      Fields items cleanup(). There are only Item_fields in the list, so we
      do not do Item tree walking
    */
    List_iterator_fast<Item> it(*fields);
    Item *item;
monty@mysql.com's avatar
monty@mysql.com committed
860
    while ((item= it++))
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
861 862
      item->cleanup();

monty@mysql.com's avatar
monty@mysql.com committed
863
    /* We have to cleanup translation tables of views. */
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
864 865 866
    for (TABLE_LIST *tbl= table_list; tbl; tbl= tbl->next_global)
      tbl->cleanup_items();

867 868
    if (setup_tables(thd, &lex->select_lex.context,
                     table_list, &lex->select_lex.where,
869
                     &lex->select_lex.leaf_tables, FALSE) ||
tomas@poseidon.ndb.mysql.com's avatar
Merge  
tomas@poseidon.ndb.mysql.com committed
870
        setup_fields_with_no_wrap(thd, 0, *fields, 2, 0, 0))
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
871
      DBUG_RETURN(TRUE);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
872
  }
monty@mysql.com's avatar
monty@mysql.com committed
873

874 875 876 877 878
  /*
    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;
monty@mysql.com's avatar
monty@mysql.com committed
879 880 881 882 883 884 885 886 887 888 889 890 891
  /* 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;
    if (!(tlist= tl->belong_to_view ? tl->belong_to_view : tl)->derived)
    {
      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));
892 893 894 895 896 897 898
    if (tl->lock_type != TL_READ &&
        tl->lock_type != TL_READ_NO_INSERT &&
        unique_table(tl, table_list))
    {
      my_error(ER_UPDATE_TABLE_USED, MYF(0), table_list->table_name);
      DBUG_RETURN(TRUE);
    }
monty@mysql.com's avatar
monty@mysql.com committed
899 900
  }

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
901 902
  if (thd->fill_derived_tables() &&
      mysql_handle_derived(lex, &mysql_derived_filling))
903
    DBUG_RETURN(TRUE);
904

bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
905
  DBUG_RETURN (FALSE);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
906 907 908
}


monty@mysql.com's avatar
monty@mysql.com committed
909 910 911
/*
  Setup multi-update handling and call SELECT to do the join
*/
912

913 914 915 916 917 918
bool mysql_multi_update(THD *thd,
                        TABLE_LIST *table_list,
                        List<Item> *fields,
                        List<Item> *values,
                        COND *conds,
                        ulong options,
919
                        enum enum_duplicates handle_duplicates, bool ignore,
920
                        SELECT_LEX_UNIT *unit, SELECT_LEX *select_lex)
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
921 922 923 924
{
  multi_update *result;
  DBUG_ENTER("mysql_multi_update");

925 926
  if (mysql_multi_update_prepare(thd))
    DBUG_RETURN(TRUE);
927

928 929 930
  if (!(result= new multi_update(thd, table_list,
				 thd->lex->select_lex.leaf_tables,
				 fields, values,
931
				 handle_duplicates, ignore)))
932
    DBUG_RETURN(TRUE);
933

934 935 936 937 938
  thd->no_trans_update= 0;
  thd->abort_on_warning= test(thd->variables.sql_mode &
                              (MODE_STRICT_TRANS_TABLES |
                               MODE_STRICT_ALL_TABLES));

939
  List<Item> total_list;
940 941 942 943 944 945 946 947
  (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);
948
  delete result;
949
  thd->abort_on_warning= 0;
950
  DBUG_RETURN(FALSE);
951 952
}

953 954

multi_update::multi_update(THD *thd_arg, TABLE_LIST *table_list,
955
			   TABLE_LIST *leaves_list,
956
			   List<Item> *field_list, List<Item> *value_list,
monty@mysql.com's avatar
monty@mysql.com committed
957 958
			   enum enum_duplicates handle_duplicates_arg,
                           bool ignore_arg)
959 960 961 962
  :all_tables(table_list), leaves(leaves_list), update_tables(0),
   thd(thd_arg), tmp_tables(0), updated(0), found(0), fields(field_list),
   values(value_list), table_count(0), copy_field(0),
   handle_duplicates(handle_duplicates_arg), do_update(1), trans_safe(0),
963
   transactional_tables(1), ignore(ignore_arg)
964 965 966 967 968 969 970
{}


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

971 972
int multi_update::prepare(List<Item> &not_used_values,
			  SELECT_LEX_UNIT *lex_unit)
973
{
974 975
  TABLE_LIST *table_ref;
  SQL_LIST update;
976
  table_map tables_to_update;
977 978 979 980
  Item_field *item;
  List_iterator_fast<Item> field_it(*fields);
  List_iterator_fast<Item> value_it(*values);
  uint i, max_fields;
981
  DBUG_ENTER("multi_update::prepare");
982

983
  thd->count_cuted_fields= CHECK_FIELD_WARN;
984
  thd->cuted_fields=0L;
985 986
  thd->proc_info="updating main table";

987
  tables_to_update= get_table_map(fields);
988

989
  if (!tables_to_update)
990
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
991
    my_message(ER_NO_TABLES_USED, ER(ER_NO_TABLES_USED), MYF(0));
992
    DBUG_RETURN(1);
993
  }
994

995
  /*
996 997
    We have to check values after setup_tables to get used_keys right in
    reference tables
998
  */
999

1000
  if (setup_fields(thd, 0, *values, 1, 0, 0))
1001 1002
    DBUG_RETURN(1);

1003
  /*
1004 1005 1006
    Save tables beeing updated in update_tables
    update_table->shared is position for table
    Don't use key read on tables that are updated
1007
  */
1008 1009

  update.empty();
1010
  for (table_ref= leaves; table_ref; table_ref= table_ref->next_leaf)
1011
  {
1012
    /* TODO: add support of view of join support */
1013 1014
    TABLE *table=table_ref->table;
    if (tables_to_update & table->map)
1015
    {
1016 1017 1018
      TABLE_LIST *tl= (TABLE_LIST*) thd->memdup((char*) table_ref,
						sizeof(*tl));
      if (!tl)
1019
	DBUG_RETURN(1);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
1020
      update.link_in_list((byte*) tl, (byte**) &tl->next_local);
1021 1022
      tl->shared= table_count++;
      table->no_keyread=1;
1023
      table->used_keys.clear_all();
1024
      table->pos_in_table_list= tl;
1025 1026
    }
  }
Sinisa@sinisa.nasamreza.org's avatar
Sinisa@sinisa.nasamreza.org committed
1027 1028


1029 1030 1031
  table_count=  update.elements;
  update_tables= (TABLE_LIST*) update.first;

1032
  tmp_tables = (TABLE**) thd->calloc(sizeof(TABLE *) * table_count);
1033 1034 1035 1036 1037 1038
  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);
1039
  if (thd->is_fatal_error)
1040 1041 1042 1043 1044 1045
    DBUG_RETURN(1);
  for (i=0 ; i < table_count ; i++)
  {
    fields_for_table[i]= new List_item;
    values_for_table[i]= new List_item;
  }
1046
  if (thd->is_fatal_error)
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
    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);
  }
1058
  if (thd->is_fatal_error)
1059 1060 1061 1062 1063 1064 1065
    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];
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078

  /*
    Mark all copies of tables that are updates to ensure that
    init_read_record() will not try to enable a cache on them

    The problem is that for queries like

    UPDATE t1, t1 AS t2 SET t1.b=t2.c WHERE t1.a=t2.a;

    the row buffer may contain things that doesn't match what is on disk
    which will cause an error when reading a row.
    (This issue is mostly relevent for MyISAM tables)
  */
1079
  for (table_ref= leaves;  table_ref; table_ref= table_ref->next_leaf)
1080 1081
  {
    TABLE *table=table_ref->table;
1082
    if (!(tables_to_update & table->map) &&
1083
	find_table_in_local_list(update_tables, table_ref->db,
1084
				table_ref->table_name))
1085 1086
      table->no_cache= 1;			// Disable row cache
  }
1087
  DBUG_RETURN(thd->is_fatal_error != 0);
1088 1089 1090
}


1091
/*
1092
  Initialize table for multi table
1093

1094 1095 1096 1097
  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).
1098 1099 1100
*/

bool
1101 1102
multi_update::initialize_tables(JOIN *join)
{
1103 1104 1105 1106 1107 1108 1109
  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();
1110 1111 1112
  table_to_update= 0;

  /* Create a temporary table for keys to all tables, except main table */
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
1113
  for (table_ref= update_tables; table_ref; table_ref= table_ref->next_local)
1114
  {
1115
    TABLE *table=table_ref->table;
1116
    uint cnt= table_ref->shared;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1117
    Item_field *ifield;
1118 1119
    List<Item> temp_fields= *fields_for_table[cnt];
    ORDER     group;
1120

1121 1122 1123 1124 1125 1126 1127
    if (table == main_table)			// First table in join
    {
      if (safe_update_on_fly(join->join_tab, &temp_fields))
      {
	table_to_update= main_table;		// Update table on the fly
	continue;
      }
1128
    }
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139

    TMP_TABLE_PARAM *tmp_param= tmp_table_param+cnt;

    /*
      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",
1140
			table, &my_charset_bin);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1141
    if (!(ifield= new Item_field(((Field *) &offset))))
Sinisa@sinisa.nasamreza.org's avatar
Sinisa@sinisa.nasamreza.org committed
1142
      DBUG_RETURN(1);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1143 1144
    ifield->maybe_null= 0;
    if (temp_fields.push_front(ifield))
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
      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,
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
1159 1160
					   (ORDER*) &group, 0, 0,
					   TMP_TABLE_ALL_COLUMNS,
1161 1162
					   HA_POS_ERROR,
					   (char *) "")))
1163 1164
      DBUG_RETURN(1);
    tmp_tables[cnt]->file->extra(HA_EXTRA_WRITE_CACHE);
1165
  }
1166
  DBUG_RETURN(0);
1167 1168
}

1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
/*
  Check if table is safe to update on fly

  SYNOPSIS
    safe_update_on_fly
    join_tab		How table is used in join
    fields		Fields that are updated

  NOTES
    We can update the first table in join on the fly if we know that
1179 1180
    a row in this table will never be read twice. This is true under
    the following conditions:
1181 1182 1183 1184 1185 1186 1187

    - 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.

1188 1189 1190 1191
    When checking for above cases we also should take into account that
    BEFORE UPDATE trigger potentially may change value of any field in row
    being updated.

1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
  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(JOIN_TAB *join_tab, List<Item> *fields)
{
  TABLE *table= join_tab->table;
  switch (join_tab->type) {
  case JT_SYSTEM:
  case JT_CONST:
  case JT_EQ_REF:
1207
    return TRUE;				// At most one matching row
1208
  case JT_REF:
monty@mysql.com's avatar
monty@mysql.com committed
1209
  case JT_REF_OR_NULL:
1210 1211 1212
    return !check_if_key_used(table, join_tab->ref.key, *fields) &&
           !(table->triggers &&
             table->triggers->has_before_update_triggers());
1213 1214 1215
  case JT_ALL:
    /* If range search on index */
    if (join_tab->quick)
1216 1217 1218
      return !join_tab->quick->check_if_keys_used(fields) &&
             !(table->triggers &&
               table->triggers->has_before_update_triggers());
1219 1220
    /* If scanning in clustered key */
    if ((table->file->table_flags() & HA_PRIMARY_KEY_IN_READ_INDEX) &&
1221
	table->s->primary_key < MAX_KEY)
1222 1223 1224
      return !check_if_key_used(table, table->s->primary_key, *fields) &&
             !(table->triggers &&
               table->triggers->has_before_update_triggers());
1225
    return TRUE;
1226 1227 1228
  default:
    break;					// Avoid compler warning
  }
1229
  return FALSE;
1230 1231
}

1232 1233 1234

multi_update::~multi_update()
{
1235
  TABLE_LIST *table;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
1236
  for (table= update_tables ; table; table= table->next_local)
1237
    table->table->no_keyread= table->table->no_cache= 0;
1238

1239 1240
  if (tmp_tables)
  {
1241 1242 1243 1244 1245 1246 1247 1248
    for (uint cnt = 0; cnt < table_count; cnt++)
    {
      if (tmp_tables[cnt])
      {
	free_tmp_table(thd, tmp_tables[cnt]);
	tmp_table_param[cnt].cleanup();
      }
    }
1249
  }
1250 1251
  if (copy_field)
    delete [] copy_field;
1252
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;		// Restore this setting
1253 1254
  if (!trans_safe)
    thd->options|=OPTION_STATUS_NO_TRANS_UPDATE;
1255 1256 1257
}


1258
bool multi_update::send_data(List<Item> &not_used_values)
1259
{
1260 1261 1262
  TABLE_LIST *cur_table;
  DBUG_ENTER("multi_update::send_data");

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
1263
  for (cur_table= update_tables; cur_table; cur_table= cur_table->next_local)
1264
  {
1265
    TABLE *table= cur_table->table;
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
    /*
      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.
    */
1278 1279 1280 1281 1282
    if (table->status & (STATUS_NULL_ROW | STATUS_UPDATED))
      continue;

    uint offset= cur_table->shared;
    table->file->position(table->record[0]);
1283
    if (table == table_to_update)
1284 1285
    {
      table->status|= STATUS_UPDATED;
1286
      store_record(table,record[1]);
1287 1288 1289 1290
      if (fill_record_n_invoke_before_triggers(thd, *fields_for_table[offset],
                                               *values_for_table[offset], 0,
                                               table->triggers,
                                               TRG_EVENT_UPDATE))
1291
	DBUG_RETURN(1);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1292

1293
      found++;
1294
      if (compare_record(table, thd->query_id))
1295
      {
1296
	int error;
monty@mysql.com's avatar
monty@mysql.com committed
1297
        if ((error= cur_table->view_check_option(thd, ignore)) !=
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1298 1299 1300 1301 1302 1303 1304 1305
            VIEW_CHECK_OK)
        {
          found--;
          if (error == VIEW_CHECK_SKIP)
            continue;
          else if (error == VIEW_CHECK_ERROR)
            DBUG_RETURN(1);
        }
1306
	if (!updated++)
1307
	{
1308 1309 1310 1311 1312 1313
	  /*
	    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);
1314
	}
1315 1316
	if ((error=table->file->update_row(table->record[1],
					   table->record[0])))
1317
	{
1318
	  updated--;
1319
          if (!ignore || error != HA_ERR_FOUND_DUPP_KEY)
1320
	  {
monty@mysql.com's avatar
monty@mysql.com committed
1321
            thd->fatal_error();                 // Force error message
1322 1323 1324
	    table->file->print_error(error,MYF(0));
	    DBUG_RETURN(1);
	  }
1325
	}
1326 1327 1328 1329 1330 1331 1332 1333 1334
        else
        {
          if (!table->file->has_transactions())
            thd->no_trans_update= 1;
          if (table->triggers &&
              table->triggers->process_triggers(thd, TRG_EVENT_UPDATE,
                                                TRG_ACTION_AFTER, TRUE))
	    DBUG_RETURN(1);
        }
1335
      }
1336 1337 1338 1339 1340
    }
    else
    {
      int error;
      TABLE *tmp_table= tmp_tables[offset];
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1341
      fill_record(thd, tmp_table->field+1, *values_for_table[offset], 1);
1342
      found++;
1343 1344 1345 1346 1347 1348 1349
      /* 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 */
      if ((error= tmp_table->file->write_row(tmp_table->record[0])) &&
	  (error != HA_ERR_FOUND_DUPP_KEY &&
	   error != HA_ERR_FOUND_DUPP_UNIQUE))
1350
      {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1351
	if (create_myisam_from_heap(thd, tmp_table, tmp_table_param + offset,
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1352
				    error, 1))
1353
	{
1354 1355
	  do_update=0;
	  DBUG_RETURN(1);			// Not a table_is_full error
1356 1357 1358 1359
	}
      }
    }
  }
1360
  DBUG_RETURN(0);
1361 1362
}

1363

1364 1365 1366
void multi_update::send_error(uint errcode,const char *err)
{
  /* First send error what ever it is ... */
1367
  my_error(errcode, MYF(0), err);
1368 1369 1370 1371

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

1373
  /* Something already updated so we have to invalidate cache */
1374 1375
  query_cache_invalidate3(thd, update_tables, 1);

1376
  /*
1377 1378
    If all tables that has been updated are trans safe then just do rollback.
    If not attempt to do remaining updates.
1379
  */
1380 1381

  if (trans_safe)
1382
    ha_rollback_stmt(thd);
1383 1384 1385 1386 1387
  else if (do_update && table_count > 1)
  {
    /* Add warning here */
    VOID(do_updates(0));
  }
1388 1389 1390
}


1391
int multi_update::do_updates(bool from_send_error)
1392
{
1393 1394 1395
  TABLE_LIST *cur_table;
  int local_error;
  ha_rows org_updated;
1396
  TABLE *table, *tmp_table;
1397 1398
  DBUG_ENTER("do_updates");

1399
  do_update= 0;					// Don't retry this function
1400
  if (!found)
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
1401
    DBUG_RETURN(0);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
1402
  for (cur_table= update_tables; cur_table; cur_table= cur_table->next_local)
1403
  {
1404
    byte *ref_pos;
1405

1406
    table = cur_table->table;
1407
    if (table == table_to_update)
1408 1409
      continue;					// Already updated
    org_updated= updated;
1410
    tmp_table= tmp_tables[cur_table->shared];
1411
    tmp_table->file->extra(HA_EXTRA_CACHE);	// Change to read cache
1412
    (void) table->file->ha_rnd_init(0);
1413 1414 1415 1416 1417 1418 1419 1420 1421
    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++)
1422
    {
1423 1424
      Item_field *item= (Item_field* ) field_it++;
      (copy_field_ptr++)->set(item->field, *field, 0);
1425
    }
1426 1427
    copy_field_end=copy_field_ptr;

1428
    if ((local_error = tmp_table->file->ha_rnd_init(1)))
1429 1430 1431 1432
      goto err;

    ref_pos= (byte*) tmp_table->field[0]->ptr;
    for (;;)
1433
    {
1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
      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;
1446
      table->status|= STATUS_UPDATED;
1447
      store_record(table,record[1]);
1448 1449 1450 1451 1452 1453 1454

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

1455 1456 1457 1458 1459
      if (table->triggers &&
          table->triggers->process_triggers(thd, TRG_EVENT_UPDATE,
                                            TRG_ACTION_BEFORE, TRUE))
        goto err2;

1460
      if (compare_record(table, thd->query_id))
1461
      {
1462 1463 1464
	if ((local_error=table->file->update_row(table->record[1],
						 table->record[0])))
	{
1465
	  if (!ignore || local_error != HA_ERR_FOUND_DUPP_KEY)
1466 1467 1468
	    goto err;
	}
	updated++;
1469 1470 1471 1472 1473

        if (table->triggers &&
            table->triggers->process_triggers(thd, TRG_EVENT_UPDATE,
                                              TRG_ACTION_AFTER, TRUE))
          goto err2;
1474
      }
1475 1476 1477 1478 1479
    }

    if (updated != org_updated)
    {
      if (table->file->has_transactions())
1480
	transactional_tables= 1;
1481
      else
1482
	trans_safe= 0;				// Can't do safe rollback
1483
    }
1484 1485
    (void) table->file->ha_rnd_end();
    (void) tmp_table->file->ha_rnd_end();
1486
  }
1487 1488 1489 1490
  DBUG_RETURN(0);

err:
  if (!from_send_error)
monty@mysql.com's avatar
monty@mysql.com committed
1491 1492
  {
    thd->fatal_error();
1493
    table->file->print_error(local_error,MYF(0));
monty@mysql.com's avatar
monty@mysql.com committed
1494
  }
1495

1496
err2:
1497 1498 1499
  (void) table->file->ha_rnd_end();
  (void) tmp_table->file->ha_rnd_end();

1500 1501 1502
  if (updated != org_updated)
  {
    if (table->file->has_transactions())
1503
      transactional_tables= 1;
1504 1505 1506 1507
    else
      trans_safe= 0;
  }
  DBUG_RETURN(1);
1508 1509 1510
}


monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1511 1512
/* out: 1 if error, 0 if success */

1513 1514
bool multi_update::send_eof()
{
1515
  char buff[STRING_BUFFER_USUAL_SIZE];
1516
  thd->proc_info="updating reference tables";
1517 1518

  /* Does updates for the last n - 1 tables, returns 0 if ok */
1519
  int local_error = (table_count) ? do_updates(0) : 0;
1520
  thd->proc_info= "end";
1521

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1522 1523 1524 1525 1526 1527 1528 1529
  /* We must invalidate the query cache before binlog writing and
  ha_autocommit_... */

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

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1530 1531
  /*
    Write the SQL statement to the binlog if we updated
1532
    rows and we succeeded or if we updated some non
1533 1534 1535
    transacational tables.
    Note that if we updated nothing we don't write to the binlog (TODO:
    fix this).
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1536
  */
1537

1538
  if (updated && (local_error <= 0 || !trans_safe))
1539
  {
1540 1541
    if (mysql_bin_log.is_open())
    {
guilhem@mysql.com's avatar
guilhem@mysql.com committed
1542 1543
      if (local_error <= 0)
        thd->clear_error();
1544
      Query_log_event qinfo(thd, thd->query, thd->query_length,
1545
			    transactional_tables, FALSE);
1546
      if (mysql_bin_log.write(&qinfo) && trans_safe)
1547
	local_error= 1;				// Rollback update
1548
    }
1549
    if (!transactional_tables)
1550 1551
      thd->options|=OPTION_STATUS_NO_TRANS_UPDATE;
  }
1552

1553 1554
  if (transactional_tables)
  {
1555
    if (ha_autocommit_or_rollback(thd, local_error != 0))
1556 1557
      local_error=1;
  }
1558

1559 1560 1561 1562 1563
  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));
1564
    return TRUE;
1565
  }
1566 1567


1568 1569
  sprintf(buff, ER(ER_UPDATE_INFO), (ulong) found, (ulong) updated,
	  (ulong) thd->cuted_fields);
1570 1571
  thd->row_count_func=
    (thd->client_capabilities & CLIENT_FOUND_ROWS) ? found : updated;
1572
  ::send_ok(thd, (ulong) thd->row_count_func,
1573
	    thd->insert_id_used ? thd->insert_id() : 0L,buff);
1574
  return FALSE;
1575
}