sql_update.cc 52.3 KB
Newer Older
1
/* Copyright (C) 2000-2006 MySQL AB
2

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

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

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

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

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

29
bool compare_record(TABLE *table, query_id_t query_id)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
30
{
31
  if (table->s->blob_fields + table->s->varchar_fields == 0)
32
    return cmp_record(table,record[1]);
33
  /* Compare null bits */
bk@work.mysql.com's avatar
bk@work.mysql.com 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
38
  /* Compare updated fields */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
39 40
  for (Field **ptr=table->field ; *ptr ; ptr++)
  {
41
    if ((*ptr)->query_id == query_id &&
42
	(*ptr)->cmp_binary_offset(table->s->rec_buff_length))
43
      return TRUE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
44
  }
45
  return FALSE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
46 47 48
}


bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
49 50 51 52 53
/*
  check that all fields are real fields

  SYNOPSIS
    check_fields()
54
    thd             thread handler
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua 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
*/

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

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
68 69
  while ((item= it++))
  {
70
    if (!(field= item->filed_for_view_update()))
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
71
    {
72
      /* item has name, because it comes from VIEW SELECT list */
73
      my_error(ER_NONUPDATEABLE_COLUMN, MYF(0), item->name);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
74 75
      return TRUE;
    }
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
    */
monty@mysql.com's avatar
monty@mysql.com committed
80
    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
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
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua 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,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
113
		 ha_rows limit,
114
		 enum enum_duplicates handle_duplicates, bool ignore)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
115
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
116
  bool		using_limit= limit != HA_POS_ERROR;
117
  bool		safe_update= test(thd->options & OPTION_SAFE_UPDATES);
118
  bool		used_key_is_modified, transactional_table;
119
  bool		can_compare_record;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
120
  int           res;
monty@mysql.com's avatar
monty@mysql.com committed
121
  int		error;
122 123
  uint		used_index= MAX_KEY;
  bool          need_sort= TRUE;
124 125 126
#ifndef NO_EMBEDDED_ACCESS_CHECKS
  uint		want_privilege;
#endif
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
127
  uint          table_count= 0;
128
  query_id_t	query_id=thd->query_id, timestamp_query_id;
129
  ha_rows	updated, found;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
130 131
  key_map	old_used_keys;
  TABLE		*table;
monty@mysql.com's avatar
monty@mysql.com committed
132
  SQL_SELECT	*select;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
133
  READ_RECORD	info;
134
  SELECT_LEX    *select_lex= &thd->lex->select_lex;
135
  bool need_reopen;
136
  List<Item> all_fields;
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
  for ( ; ; )
142
  {
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
    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);
159
    close_tables_for_reopen(thd, &table_list);
160
  }
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
161

162
  if (mysql_handle_derived(thd->lex, &mysql_derived_prepare) ||
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
163 164
      (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
165
    DBUG_RETURN(1);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
166

bk@work.mysql.com's avatar
bk@work.mysql.com committed
167
  thd->proc_info="init";
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
168
  table= table_list->table;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
169 170
  table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);

171
  /* Calculate "table->used_keys" based on the WHERE */
172
  table->used_keys= table->s->keys_in_use;
173
  table->quick_keys.clear_all();
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
174

hf@deer.(none)'s avatar
hf@deer.(none) committed
175
#ifndef NO_EMBEDDED_ACCESS_CHECKS
176 177 178
  /* Force privilege re-checking for views after they have been opened. */
  want_privilege= (table_list->view ? UPDATE_ACL :
                   table_list->grant.want_privilege);
hf@deer.(none)'s avatar
hf@deer.(none) committed
179
#endif
180
  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
181
    DBUG_RETURN(1);
182

monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
183
  old_used_keys= table->used_keys;		// Keys used in WHERE
bk@work.mysql.com's avatar
bk@work.mysql.com committed
184
  /*
185 186
    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
187
  */
188 189 190 191 192
  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
193

194
  /* Check the fields we are going to modify */
hf@deer.(none)'s avatar
hf@deer.(none) committed
195
#ifndef NO_EMBEDDED_ACCESS_CHECKS
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
196
  table_list->grant.want_privilege= table->grant.want_privilege= want_privilege;
197
  table_list->register_want_access(want_privilege);
hf@deer.(none)'s avatar
hf@deer.(none) committed
198
#endif
199 200
  if (setup_fields_with_no_wrap(thd, 0, fields, 1, 0, 0))
    DBUG_RETURN(1);                     /* purecov: inspected */
201
  if (table_list->view && check_fields(thd, fields))
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
202
  {
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
  }
  if (!table_list->updatable || check_key_in_view(thd, table_list))
  {
207
    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
208
    DBUG_RETURN(1);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
209
  }
210 211 212 213
  if (table->timestamp_field)
  {
    // Don't set timestamp column if this is modified
    if (table->timestamp_field->query_id == thd->query_id)
214
      table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
215 216 217
    else
      table->timestamp_field->query_id=timestamp_query_id;
  }
218

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

230 231 232 233
  if (select_lex->inner_refs_list.elements &&
    fix_inner_refs(thd, all_fields, select_lex, select_lex->ref_pointer_array))
    DBUG_RETURN(-1);

234 235 236 237 238 239 240
  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
  }
241
  // Don't count on usage of 'only index' when calculating which key to use
242
  table->used_keys.clear_all();
monty@mysql.com's avatar
monty@mysql.com committed
243
  select= make_select(table, 0, 0, conds, 0, &error);
244 245
  if (error || !limit ||
      (select && select->check_quick(thd, safe_update, limit)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
246 247
  {
    delete select;
248
    free_underlaid_joins(thd, select_lex);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
249 250
    if (error)
    {
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
251
      DBUG_RETURN(1);				// Error in where
bk@work.mysql.com's avatar
bk@work.mysql.com committed
252
    }
253
    send_ok(thd);				// No matching records
bk@work.mysql.com's avatar
bk@work.mysql.com committed
254 255
    DBUG_RETURN(0);
  }
256 257
  if (!select && limit != HA_POS_ERROR)
  {
258
    if ((used_index= get_index_for_order(table, order, limit)) != MAX_KEY)
259 260
      need_sort= FALSE;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
261
  /* If running in safe sql mode, don't allow updates without keys */
262
  if (table->quick_keys.is_clear_all())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
263
  {
264
    thd->server_status|=SERVER_QUERY_NO_INDEX_USED;
265
    if (safe_update && !using_limit)
266
    {
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
267 268 269
      my_message(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE,
		 ER(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE), MYF(0));
      goto err;
270
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
271
  }
272
  init_ftfuncs(thd, select_lex, 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
273
  /* Check if we are modifying a key that we are used to search with */
274
  
bk@work.mysql.com's avatar
bk@work.mysql.com committed
275
  if (select && select->quick)
276
  {
277
    used_index= select->quick->index;
278
    used_key_is_modified= (!select->quick->unique_key_range() &&
279
                          select->quick->is_keys_used(&fields));
280
  }
281
  else
282
  {
283 284 285 286
    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)
287
      used_key_is_modified= is_key_used(table, used_index, fields);
288
  }
289

290
  if (used_key_is_modified || order)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
291 292
  {
    /*
293 294
      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
295
    */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
296
    table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
297
    if (used_index < MAX_KEY && old_used_keys.is_set(used_index))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
298 299
    {
      table->key_read=1;
300
      table->file->extra(HA_EXTRA_KEYREAD);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
301
    }
302

303
    /* note: can actually avoid sorting below.. */
304
    if (order && (need_sort || used_key_is_modified))
305
    {
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
306 307 308 309
      /*
	Doing an ORDER BY;  Let filesort find and sort the rows we are going
	to update
      */
310
      uint         length= 0;
311
      SORT_FIELD  *sortorder;
312
      ha_rows examined_rows;
313

igor@hundin.mysql.fi's avatar
igor@hundin.mysql.fi committed
314
      table->sort.io_cache = (IO_CACHE *) my_malloc(sizeof(IO_CACHE),
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
315
						    MYF(MY_FAE | MY_ZEROFILL));
316
      if (!(sortorder=make_unireg_sortorder(order, &length, NULL)) ||
igor@hundin.mysql.fi's avatar
igor@hundin.mysql.fi committed
317
          (table->sort.found_records = filesort(thd, table, sortorder, length,
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
318
						select, limit,
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
319
						&examined_rows))
320 321
          == HA_POS_ERROR)
      {
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
322
	free_io_cache(table);
323
	goto err;
324
      }
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
325 326 327 328 329 330
      /*
	Filesort has already found and selected the rows we want to update,
	so we don't need the where clause
      */
      delete select;
      select= 0;
331
    }
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
332
    else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
333
    {
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
334 335 336 337 338 339 340 341 342
      /*
	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)))
343
	goto err;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
344

sergefp@mysql.com's avatar
sergefp@mysql.com committed
345 346 347
      /* If quick select is used, initialize it before retrieving rows. */
      if (select && select->quick && select->quick->reset())
        goto err;
348

349 350 351 352 353 354 355 356 357 358
      /*
        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
      */
359
      if (used_index == MAX_KEY || (select && select->quick))
360 361 362
        init_read_record(&info,thd,table,select,0,1);
      else
        init_read_record_idx(&info, thd, table, 1, used_index);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
363

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

monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
367
      while (!(error=info.read_record(&info)) && !thd->killed)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
368
      {
369
	if (!(select && select->skip_record()))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
370
	{
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
371 372 373 374 375 376 377 378
	  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)
379 380
	  {
	    error= -1;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
381
	    break;
382
	  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
383
	}
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
384 385
	else
	  table->file->unlock_row();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
386
      }
387 388
      if (thd->killed && !error)
	error= 1;				// Aborted
389
      limit= tmp_limit;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
390
      end_read_record(&info);
391
     
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
392 393 394 395 396 397 398 399 400
      /* 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
401 402
      else
      {
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
403 404
	select= new SQL_SELECT;
	select->head=table;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
405
      }
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
406 407 408 409
      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)
410
	goto err;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
411 412 413 414 415 416 417 418
    }
    if (table->key_read)
    {
      table->key_read=0;
      table->file->extra(HA_EXTRA_NO_KEYREAD);
    }
  }

419
  if (ignore)
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
420
    table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
421 422 423
  
  if (select && select->quick && select->quick->reset())
        goto err;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
424 425
  init_read_record(&info,thd,table,select,0,1);

426
  updated= found= 0;
427
  thd->count_cuted_fields= CHECK_FIELD_WARN;		/* calc cuted fields */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
428
  thd->cuted_fields=0L;
429
  thd->proc_info="Updating";
430
  query_id=thd->query_id;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
431

432
  transactional_table= table->file->has_transactions();
monty@mysql.com's avatar
monty@mysql.com committed
433
  thd->abort_on_warning= test(!ignore &&
434 435 436
                              (thd->variables.sql_mode &
                               (MODE_STRICT_TRANS_TABLES |
                                MODE_STRICT_ALL_TABLES)));
437

438
  if (table->triggers)
439
  {
440
    table->triggers->mark_fields_used(thd, TRG_EVENT_UPDATE);
441 442 443 444 445 446 447 448 449 450 451
    if (table->triggers->has_triggers(TRG_EVENT_UPDATE,
                                      TRG_ACTION_AFTER))
    {
      /*
	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);
    }
  }
452

453 454 455 456 457 458
  /*
    We can use compare_record() to optimize away updates if
    the table handler is returning all columns
  */
  can_compare_record= !(table->file->table_flags() &
                        HA_PARTIAL_COLUMN_READ);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
459 460
  while (!(error=info.read_record(&info)) && !thd->killed)
  {
461
    if (!(select && select->skip_record()))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
462
    {
463
      store_record(table,record[1]);
464 465 466
      if (fill_record_n_invoke_before_triggers(thd, fields, values, 0,
                                               table->triggers,
                                               TRG_EVENT_UPDATE))
467
        break; /* purecov: inspected */
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
468

bk@work.mysql.com's avatar
bk@work.mysql.com committed
469
      found++;
470

471
      if (!can_compare_record || compare_record(table, query_id))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
472
      {
monty@mysql.com's avatar
monty@mysql.com committed
473
        if ((res= table_list->view_check_option(thd, ignore)) !=
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
474 475 476 477 478 479 480 481 482 483 484
            VIEW_CHECK_OK)
        {
          found--;
          if (res == VIEW_CHECK_SKIP)
            continue;
          else if (res == VIEW_CHECK_ERROR)
          {
            error= 1;
            break;
          }
        }
485 486 487 488 489
        if (!(error=table->file->update_row((byte*) table->record[1],
                                            (byte*) table->record[0])))
        {
          updated++;
          
490 491 492 493 494 495 496
          if (table->triggers &&
              table->triggers->process_triggers(thd, TRG_EVENT_UPDATE,
                                                TRG_ACTION_AFTER, TRUE))
          {
            error= 1;
            break;
          }
497 498 499
        }
        else if (!ignore || error != HA_ERR_FOUND_DUPP_KEY)
        {
500 501 502 503 504 505
          /*
            If (ignore && error == HA_ERR_FOUND_DUPP_KEY) we don't have to
            do anything; otherwise...
          */
          if (error != HA_ERR_FOUND_DUPP_KEY)
            thd->fatal_error(); /* Other handler errors are fatal */
506 507 508 509
          table->file->print_error(error,MYF(0));
          error= 1;
          break;
        }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
510
      }
511
      
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
512 513
      if (!--limit && using_limit)
      {
514 515
        error= -1;				// Simulate end of file
        break;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
516
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
517
    }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
518 519
    else
      table->file->unlock_row();
520
    thd->row_count++;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
521
  }
522

523 524 525 526
  if (!transactional_table && updated > 0)
    thd->transaction.stmt.modified_non_trans_table= TRUE;


527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
  /*
    todo bug#27571: to avoid asynchronization of `error' and
    `error_code' of binlog event constructor

    The concept, which is a bit different for insert(!), is to
    replace `error' assignment with the following lines

       killed_status= thd->killed; // get the status of the volatile 
    
    Notice: thd->killed is type of "state" whereas the lhs has
    "status" the suffix which translates according to WordNet: a state
    at a particular time - at the time of the end of per-row loop in
    our case. Binlogging ops are conducted with the status.

       error= (killed_status == THD::NOT_KILLED)?  error : 1;
    
    which applies to most mysql_$query functions.
    Event's constructor will accept `killed_status' as an argument:
    
       Query_log_event qinfo(..., killed_status);
    
    thd->killed might be changed after killed_status had got cached and this
    won't affect binlogging event but other effects remain.

    Open issue: In a case the error happened not because of KILLED -
    and then KILLED was caught later still within the loop - we shall
    do something to avoid binlogging of incorrect ER_SERVER_SHUTDOWN
    error_code.
  */

557 558
  if (thd->killed && !error)
    error= 1;					// Aborted
bk@work.mysql.com's avatar
bk@work.mysql.com committed
559
  end_read_record(&info);
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
560
  free_io_cache(table);				// If ORDER BY
561
  delete select;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
562
  thd->proc_info="end";
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
563
  VOID(table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY));
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
564 565 566 567 568 569

  /*
    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
570
  {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
571
    query_cache_invalidate3(thd, table_list, 1);
monty@mysql.com's avatar
monty@mysql.com committed
572
  }
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
573

574 575 576 577 578 579 580 581 582
  /*
    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.
  */
583
  if ((error < 0) || thd->transaction.stmt.modified_non_trans_table)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
584
  {
585 586
    if (mysql_bin_log.is_open())
    {
587
      if (error < 0)
guilhem@mysql.com's avatar
guilhem@mysql.com committed
588
        thd->clear_error();
589
      Query_log_event qinfo(thd, thd->query, thd->query_length,
590
			    transactional_table, FALSE);
591 592
      if (mysql_bin_log.write(&qinfo) && transactional_table)
	error=1;				// Rollback update
593
    }
594 595
    if (thd->transaction.stmt.modified_non_trans_table)
      thd->transaction.all.modified_non_trans_table= TRUE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
596
  }
597
  DBUG_ASSERT(transactional_table || !updated || thd->transaction.stmt.modified_non_trans_table);
598
  free_underlaid_joins(thd, select_lex);
599 600 601 602 603
  if (transactional_table)
  {
    if (ha_autocommit_or_rollback(thd, error >= 0))
      error=1;
  }
604

605 606 607 608 609 610
  if (thd->lock)
  {
    mysql_unlock_tables(thd, thd->lock);
    thd->lock=0;
  }

611
  if (error < 0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
612
  {
613
    char buff[STRING_BUFFER_USUAL_SIZE];
614 615
    sprintf(buff, ER(ER_UPDATE_INFO), (ulong) found, (ulong) updated,
	    (ulong) thd->cuted_fields);
616 617
    thd->row_count_func=
      (thd->client_capabilities & CLIENT_FOUND_ROWS) ? found : updated;
618
    send_ok(thd, (ulong) thd->row_count_func,
619
	    thd->insert_id_used ? thd->last_insert_id : 0L,buff);
620
    DBUG_PRINT("info",("%ld records updated", (long) updated));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
621
  }
622
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;		/* calc cuted fields */
623
  thd->abort_on_warning= 0;
serg@serg.mysql.com's avatar
serg@serg.mysql.com committed
624
  free_io_cache(table);
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
625
  DBUG_RETURN((error >= 0 || thd->net.report_error) ? 1 : 0);
626 627 628

err:
  delete select;
629
  free_underlaid_joins(thd, select_lex);
630 631 632 633 634
  if (table->key_read)
  {
    table->key_read=0;
    table->file->extra(HA_EXTRA_NO_KEYREAD);
  }
635
  thd->abort_on_warning= 0;
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
636
  DBUG_RETURN(1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
637
}
638

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
639 640 641 642 643 644
/*
  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
645
    table_list		- global/local table list
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
646 647 648 649 650
    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
651 652
    FALSE OK
    TRUE  error
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
653
*/
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
654
bool mysql_prepare_update(THD *thd, TABLE_LIST *table_list,
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
655 656
			 Item **conds, uint order_num, ORDER *order)
{
657
  Item *fake_conds= 0;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
658 659 660
  TABLE *table= table_list->table;
  TABLE_LIST tables;
  List<Item> all_fields;
661
  SELECT_LEX *select_lex= &thd->lex->select_lex;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
662 663 664
  DBUG_ENTER("mysql_prepare_update");

#ifndef NO_EMBEDDED_ACCESS_CHECKS
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
665 666
  table_list->grant.want_privilege= table->grant.want_privilege= 
    (SELECT_ACL & ~table->grant.privilege);
667
  table_list->register_want_access(SELECT_ACL);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
668 669 670 671 672
#endif

  bzero((char*) &tables,sizeof(tables));	// For ORDER BY
  tables.table= table;
  tables.alias= table_list->alias;
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
673
  thd->lex->allow_sum_func= 0;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
674

675 676 677 678
  if (setup_tables_and_check_access(thd, &select_lex->context, 
                                    &select_lex->top_join_list,
                                    table_list, conds, 
                                    &select_lex->leaf_tables,
679
                                    FALSE, UPDATE_ACL, SELECT_ACL) ||
680
      setup_conds(thd, table_list, select_lex->leaf_tables, conds) ||
681 682
      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
683
		  table_list, all_fields, all_fields, order) ||
684
      setup_ftfuncs(select_lex))
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
685
    DBUG_RETURN(TRUE);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
686 687 688

  /* Check that we are not using table that we are updating in a sub select */
  {
689
    TABLE_LIST *duplicate;
690
    if ((duplicate= unique_table(thd, table_list, table_list->next_global, 0)))
691 692 693 694 695
    {
      update_non_unique_table_error(table_list, "UPDATE", duplicate);
      my_error(ER_UPDATE_TABLE_USED, MYF(0), table_list->table_name);
      DBUG_RETURN(TRUE);
    }
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
696
  }
697
  select_lex->fix_prepare_information(thd, conds, &fake_conds);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
698
  DBUG_RETURN(FALSE);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
699 700
}

701

702
/***************************************************************************
703
  Update multiple tables from join 
704 705
***************************************************************************/

706
/*
707
  Get table map for list of Item_field
708 709
*/

710 711 712 713 714 715 716 717
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();
718
  DBUG_PRINT("info", ("table_map: 0x%08lx", (long) map));
719 720 721 722
  return map;
}


bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
723 724
/*
  make update specific preparation and checks after opening tables
725

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
726 727 728
  SYNOPSIS
    mysql_multi_update_prepare()
    thd         thread handler
729

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
730
  RETURN
731 732
    FALSE OK
    TRUE  Error
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
733
*/
734

735
bool mysql_multi_update_prepare(THD *thd)
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
736 737 738
{
  LEX *lex= thd->lex;
  TABLE_LIST *table_list= lex->query_tables;
monty@mysql.com's avatar
monty@mysql.com committed
739
  TABLE_LIST *tl, *leaves;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
740
  List<Item> *fields= &lex->select_lex.item_list;
741
  table_map tables_for_update;
742
  bool update_view= 0;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
743 744 745 746 747 748
  /*
    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;
749
  const bool using_lock_tables= thd->locked_tables != 0;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
750
  bool original_multiupdate= (thd->lex->sql_command == SQLCOM_UPDATE_MULTI);
751
  bool need_reopen= FALSE;
monty@mysql.com's avatar
monty@mysql.com committed
752 753
  DBUG_ENTER("mysql_multi_update_prepare");

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

757 758
reopen_tables:

759
  /* open tables and create derived ones, but do not lock and fill them */
760
  if (((original_multiupdate || need_reopen) &&
761
       open_tables(thd, &table_list, &table_count, 0)) ||
762
      mysql_handle_derived(lex, &mysql_derived_prepare))
763
    DBUG_RETURN(TRUE);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
764 765 766 767 768
  /*
    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
769

770 771 772 773
  if (setup_tables_and_check_access(thd, &lex->select_lex.context,
                                    &lex->select_lex.top_join_list,
                                    table_list, &lex->select_lex.where,
                                    &lex->select_lex.leaf_tables, FALSE,
774
                                    UPDATE_ACL, SELECT_ACL))
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
775
    DBUG_RETURN(TRUE);
776

777
  if (setup_fields_with_no_wrap(thd, 0, *fields, 1, 0, 0))
778
    DBUG_RETURN(TRUE);
779 780 781 782 783 784 785 786 787 788 789

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

  if (update_view && check_fields(thd, *fields))
790
  {
791
    DBUG_RETURN(TRUE);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
792 793
  }

794
  tables_for_update= get_table_map(fields);
795 796

  /*
797
    Setup timestamp handling and locking mode
798
  */
799
  leaves= lex->select_lex.leaf_tables;
800
  for (tl= leaves; tl; tl= tl->next_leaf)
801
  {
802
    TABLE *table= tl->table;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
803
    /* Only set timestamp column if this is not modified */
804 805
    if (table->timestamp_field &&
        table->timestamp_field->query_id == thd->query_id)
monty@mysql.com's avatar
monty@mysql.com committed
806
      table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
807

808 809
    /* if table will be updated then check that it is unique */
    if (table->map & tables_for_update)
810
    {
811
      if (!tl->updatable || check_key_in_view(thd, tl))
812
      {
813
        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
814
        DBUG_RETURN(TRUE);
815
      }
816

817 818 819
      if (table->triggers)
        table->triggers->mark_fields_used(thd, TRG_EVENT_UPDATE);

820
      DBUG_PRINT("info",("setting table `%s` for update", tl->alias));
821 822 823 824
      /*
        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
825
    }
826 827 828
    else
    {
      DBUG_PRINT("info",("setting table `%s` for read-only", tl->alias));
monty@mysql.com's avatar
monty@mysql.com committed
829 830 831 832 833 834
      /*
        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;
835
      tl->updating= 0;
836
      /* Update TABLE::lock_type accordingly. */
837
      if (!tl->placeholder() && !using_lock_tables)
838
        tl->table->reginfo.lock_type= tl->lock_type;
839
    }
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
840
  }
841
  for (tl= table_list; tl; tl= tl->next_local)
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
842
  {
monty@mishka.local's avatar
monty@mishka.local committed
843
    /* Check access privileges for table */
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
844
    if (!tl->derived)
845
    {
monty@mysql.com's avatar
monty@mysql.com committed
846 847
      uint want_privilege= tl->updating ? UPDATE_ACL : SELECT_ACL;
      if (check_access(thd, want_privilege,
848 849
                       tl->db, &tl->grant.privilege, 0, 0, 
                       test(tl->schema_table)) ||
monty@mysql.com's avatar
monty@mysql.com committed
850
          (grant_option && check_grant(thd, want_privilege, tl, 0, 1, 0)))
monty@mishka.local's avatar
monty@mishka.local committed
851
        DBUG_RETURN(TRUE);
852
    }
853
  }
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
854

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
855 856 857
  /* 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
858
    if (tl->effective_algorithm == VIEW_ALGORITHM_MERGE)
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
859 860
    {
      TABLE_LIST *for_update= 0;
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
861
      if (tl->check_single_table(&for_update, tables_for_update, tl))
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
862 863 864 865 866 867 868 869
      {
	my_error(ER_VIEW_MULTIUPDATE, MYF(0),
		 tl->view_db.str, tl->view_name.str);
	DBUG_RETURN(-1);
      }
    }
  }

870
  /* now lock and fill tables */
871
  if (lock_tables(thd, table_list, table_count, &need_reopen))
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
872
  {
873 874 875
    if (!need_reopen)
      DBUG_RETURN(TRUE);

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
876
    /*
877 878 879 880
      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.
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
881 882 883
    */
    List_iterator_fast<Item> it(*fields);
    Item *item;
monty@mysql.com's avatar
monty@mysql.com committed
884
    while ((item= it++))
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
885 886
      item->cleanup();

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

891
    close_tables_for_reopen(thd, &table_list);
892
    goto reopen_tables;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
893
  }
monty@mysql.com's avatar
monty@mysql.com committed
894

895 896 897 898 899
  /*
    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
900 901 902 903 904
  /* 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;
905
    if (!(tlist= tl->top_table())->derived)
monty@mysql.com's avatar
monty@mysql.com committed
906 907 908 909 910 911 912
    {
      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));
913
    if (tl->lock_type != TL_READ &&
914
        tl->lock_type != TL_READ_NO_INSERT)
915
    {
916
      TABLE_LIST *duplicate;
917
      if ((duplicate= unique_table(thd, tl, table_list, 0)))
918 919 920 921
      {
        update_non_unique_table_error(table_list, "UPDATE", duplicate);
        DBUG_RETURN(TRUE);
      }
922
    }
monty@mysql.com's avatar
monty@mysql.com committed
923
  }
svoj@may.pils.ru's avatar
svoj@may.pils.ru committed
924 925 926 927 928 929
  /*
    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;
 
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
930 931
  if (thd->fill_derived_tables() &&
      mysql_handle_derived(lex, &mysql_derived_filling))
932
    DBUG_RETURN(TRUE);
933

bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
934
  DBUG_RETURN (FALSE);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
935 936 937
}


monty@mysql.com's avatar
monty@mysql.com committed
938 939 940
/*
  Setup multi-update handling and call SELECT to do the join
*/
941

942 943 944 945 946
bool mysql_multi_update(THD *thd,
                        TABLE_LIST *table_list,
                        List<Item> *fields,
                        List<Item> *values,
                        COND *conds,
947
                        ulonglong options,
948
                        enum enum_duplicates handle_duplicates, bool ignore,
949
                        SELECT_LEX_UNIT *unit, SELECT_LEX *select_lex)
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
950 951
{
  multi_update *result;
952
  bool res;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
953 954
  DBUG_ENTER("mysql_multi_update");

955
  if (!(result= new multi_update(table_list,
956 957
				 thd->lex->select_lex.leaf_tables,
				 fields, values,
958
				 handle_duplicates, ignore)))
959
    DBUG_RETURN(TRUE);
960

961 962 963 964
  thd->abort_on_warning= test(thd->variables.sql_mode &
                              (MODE_STRICT_TRANS_TABLES |
                               MODE_STRICT_ALL_TABLES));

965
  List<Item> total_list;
966
  res= mysql_select(thd, &select_lex->ref_pointer_array,
967 968 969 970 971 972 973
                      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);
974 975 976 977 978 979 980 981 982
  DBUG_PRINT("info",("res: %d  report_error: %d", res,
                     thd->net.report_error));
  res|= thd->net.report_error;
  if (unlikely(res))
  {
    /* If we had a another error reported earlier then this will be ignored */
    result->send_error(ER_UNKNOWN_ERROR, ER(ER_UNKNOWN_ERROR));
    result->abort();
  }
983
  delete result;
984
  thd->abort_on_warning= 0;
985
  DBUG_RETURN(FALSE);
986 987
}

988

989
multi_update::multi_update(TABLE_LIST *table_list,
990
			   TABLE_LIST *leaves_list,
991
			   List<Item> *field_list, List<Item> *value_list,
monty@mysql.com's avatar
monty@mysql.com committed
992 993
			   enum enum_duplicates handle_duplicates_arg,
                           bool ignore_arg)
994
  :all_tables(table_list), leaves(leaves_list), update_tables(0),
995
   tmp_tables(0), updated(0), found(0), fields(field_list),
996 997
   values(value_list), table_count(0), copy_field(0),
   handle_duplicates(handle_duplicates_arg), do_update(1), trans_safe(0),
998
   transactional_tables(1), ignore(ignore_arg)
999 1000 1001 1002 1003 1004 1005
{}


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

1006 1007
int multi_update::prepare(List<Item> &not_used_values,
			  SELECT_LEX_UNIT *lex_unit)
1008
{
1009 1010
  TABLE_LIST *table_ref;
  SQL_LIST update;
1011
  table_map tables_to_update;
1012 1013 1014 1015
  Item_field *item;
  List_iterator_fast<Item> field_it(*fields);
  List_iterator_fast<Item> value_it(*values);
  uint i, max_fields;
gshchepa/uchum@gleb.loc's avatar
gshchepa/uchum@gleb.loc committed
1016
  uint leaf_table_count= 0;
1017
  DBUG_ENTER("multi_update::prepare");
1018

1019
  thd->count_cuted_fields= CHECK_FIELD_WARN;
1020
  thd->cuted_fields=0L;
1021 1022
  thd->proc_info="updating main table";

1023
  tables_to_update= get_table_map(fields);
1024

1025
  if (!tables_to_update)
1026
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1027
    my_message(ER_NO_TABLES_USED, ER(ER_NO_TABLES_USED), MYF(0));
1028
    DBUG_RETURN(1);
1029
  }
1030

1031
  /*
1032 1033
    We have to check values after setup_tables to get used_keys right in
    reference tables
1034
  */
1035

1036
  if (setup_fields(thd, 0, *values, 1, 0, 0))
1037 1038
    DBUG_RETURN(1);

1039
  /*
1040 1041 1042
    Save tables beeing updated in update_tables
    update_table->shared is position for table
    Don't use key read on tables that are updated
1043
  */
1044 1045

  update.empty();
1046
  for (table_ref= leaves; table_ref; table_ref= table_ref->next_leaf)
1047
  {
1048
    /* TODO: add support of view of join support */
1049
    TABLE *table=table_ref->table;
gshchepa/uchum@gleb.loc's avatar
gshchepa/uchum@gleb.loc committed
1050
    leaf_table_count++;
1051
    if (tables_to_update & table->map)
1052
    {
1053 1054 1055
      TABLE_LIST *tl= (TABLE_LIST*) thd->memdup((char*) table_ref,
						sizeof(*tl));
      if (!tl)
1056
	DBUG_RETURN(1);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
1057
      update.link_in_list((byte*) tl, (byte**) &tl->next_local);
1058 1059
      tl->shared= table_count++;
      table->no_keyread=1;
1060
      table->used_keys.clear_all();
1061
      table->pos_in_table_list= tl;
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
      if (table->triggers)
      {
	table->triggers->mark_fields_used(thd, TRG_EVENT_UPDATE);
	if (table->triggers->has_triggers(TRG_EVENT_UPDATE,
					  TRG_ACTION_AFTER))
	{
	  /*
	    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);
	}
      }
1076 1077
    }
  }
Sinisa@sinisa.nasamreza.org's avatar
Sinisa@sinisa.nasamreza.org committed
1078 1079


1080 1081 1082
  table_count=  update.elements;
  update_tables= (TABLE_LIST*) update.first;

1083
  tmp_tables = (TABLE**) thd->calloc(sizeof(TABLE *) * table_count);
1084 1085 1086 1087 1088 1089
  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);
1090
  if (thd->is_fatal_error)
1091 1092 1093 1094 1095 1096
    DBUG_RETURN(1);
  for (i=0 ; i < table_count ; i++)
  {
    fields_for_table[i]= new List_item;
    values_for_table[i]= new List_item;
  }
1097
  if (thd->is_fatal_error)
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
    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);
  }
1109
  if (thd->is_fatal_error)
1110 1111 1112 1113 1114
    DBUG_RETURN(1);

  /* Allocate copy fields */
  max_fields=0;
  for (i=0 ; i < table_count ; i++)
gshchepa/uchum@gleb.loc's avatar
gshchepa/uchum@gleb.loc committed
1115
    set_if_bigger(max_fields, fields_for_table[i]->elements + leaf_table_count);
1116
  copy_field= new Copy_field[max_fields];
1117 1118
  DBUG_RETURN(thd->is_fatal_error != 0);
}
1119 1120


1121 1122
/*
  Check if table is safe to update on fly
1123

1124 1125 1126 1127 1128 1129
  SYNOPSIS
    safe_update_on_fly()
    thd                 Thread handler
    join_tab            How table is used in join
    all_tables          List of tables
    fields              Fields that are updated
1130

1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
  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.

1144 1145 1146 1147
    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.

1148 1149 1150 1151 1152 1153 1154 1155 1156
  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,
1157 1158
                               TABLE_LIST *table_ref, TABLE_LIST *all_tables,
                               List<Item> *fields)
1159 1160
{
  TABLE *table= join_tab->table;
1161
  if (unique_table(thd, table_ref, all_tables, 0))
1162 1163 1164 1165 1166
    return 0;
  switch (join_tab->type) {
  case JT_SYSTEM:
  case JT_CONST:
  case JT_EQ_REF:
1167
    return TRUE;				// At most one matching row
1168
  case JT_REF:
1169 1170
  case JT_REF_OR_NULL:
    return !is_key_used(table, join_tab->ref.key, *fields);
1171 1172 1173
  case JT_ALL:
    /* If range search on index */
    if (join_tab->quick)
1174
      return !join_tab->quick->is_keys_used(fields);
1175 1176
    /* If scanning in clustered key */
    if ((table->file->table_flags() & HA_PRIMARY_KEY_IN_READ_INDEX) &&
1177 1178 1179
	table->s->primary_key < MAX_KEY)
      return !is_key_used(table, table->s->primary_key, *fields);
    return TRUE;
1180 1181
  default:
    break;					// Avoid compler warning
1182
  }
1183
  return FALSE;
1184 1185 1186
}


1187
/*
1188
  Initialize table for multi table
1189

1190 1191 1192 1193
  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).
1194 1195 1196
*/

bool
1197 1198
multi_update::initialize_tables(JOIN *join)
{
1199 1200 1201 1202 1203 1204 1205
  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();
1206 1207
  table_to_update= 0;

gshchepa/uchum@gleb.loc's avatar
gshchepa/uchum@gleb.loc committed
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
  /* Any update has at least one pair (field, value) */
  DBUG_ASSERT(fields->elements);
  /*
   Only one table may be modified by UPDATE of an updatable view.
   For an updatable view first_table_for_update indicates this
   table.
   For a regular multi-update it refers to some updated table.
  */ 
  TABLE *first_table_for_update= ((Item_field *) fields->head())->field->table;

1218
  /* 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
1219
  for (table_ref= update_tables; table_ref; table_ref= table_ref->next_local)
1220
  {
1221
    TABLE *table=table_ref->table;
1222
    uint cnt= table_ref->shared;
gshchepa/uchum@gleb.loc's avatar
gshchepa/uchum@gleb.loc committed
1223
    List<Item> temp_fields;
1224
    ORDER     group;
1225

1226 1227
    if (ignore)
      table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
1228 1229
    if (table == main_table)			// First table in join
    {
1230
      if (safe_update_on_fly(thd, join->join_tab, table_ref, all_tables,
gshchepa/uchum@gleb.loc's avatar
gshchepa/uchum@gleb.loc committed
1231
                             fields_for_table[cnt]))
1232 1233 1234 1235
      {
	table_to_update= main_table;		// Update table on the fly
	continue;
      }
1236
    }
1237

gshchepa/uchum@gleb.loc's avatar
gshchepa/uchum@gleb.loc committed
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
    if (table == first_table_for_update && table_ref->check_option)
    {
      table_map unupdated_tables= table_ref->check_option->used_tables() &
                                  ~first_table_for_update->map;
      for (TABLE_LIST *tbl_ref =leaves;
           unupdated_tables && tbl_ref;
           tbl_ref= tbl_ref->next_leaf)
      {
        if (unupdated_tables & tbl_ref->table->map)
          unupdated_tables&= ~tbl_ref->table->map;
        else
          continue;
        if (unupdated_check_opt_tables.push_back(tbl_ref->table))
          DBUG_RETURN(1);
      }
    }

1255 1256 1257 1258 1259
    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
gshchepa/uchum@gleb.loc's avatar
gshchepa/uchum@gleb.loc committed
1260 1261 1262
      original row so that we can find and update it. For the updatable
      VIEW a few following fields are rowids of tables used in the CHECK
      OPTION condition.
1263 1264
    */

gshchepa/uchum@gleb.loc's avatar
gshchepa/uchum@gleb.loc committed
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
    List_iterator_fast<TABLE> tbl_it(unupdated_check_opt_tables);
    TABLE *tbl= table;
    do
    {
      Field_string *field= new Field_string(tbl->file->ref_length, 0,
                                            tbl->alias,
                                            tbl, &my_charset_bin);
      if (!field)
        DBUG_RETURN(1);
      /*
        The field will be converted to varstring when creating tmp table if
        table to be updated was created by mysql 4.1. Deny this.
      */
      field->can_alter_field_type= 0;
      Item_field *ifield= new Item_field((Field *) field);
      if (!ifield)
         DBUG_RETURN(1);
      ifield->maybe_null= 0;
      if (temp_fields.push_back(ifield))
        DBUG_RETURN(1);
    } while ((tbl= tbl_it++));

    temp_fields.concat(fields_for_table[cnt]);
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300

    /* 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
1301 1302
					   (ORDER*) &group, 0, 0,
					   TMP_TABLE_ALL_COLUMNS,
1303 1304
					   HA_POS_ERROR,
					   (char *) "")))
1305 1306
      DBUG_RETURN(1);
    tmp_tables[cnt]->file->extra(HA_EXTRA_WRITE_CACHE);
1307
  }
1308
  DBUG_RETURN(0);
1309 1310 1311 1312 1313
}


multi_update::~multi_update()
{
1314
  TABLE_LIST *table;
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
1315
  for (table= update_tables ; table; table= table->next_local)
1316
  {
1317
    table->table->no_keyread= table->table->no_cache= 0;
1318 1319 1320
    if (ignore)
      table->table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
  }
1321

1322 1323
  if (tmp_tables)
  {
1324 1325 1326 1327 1328 1329 1330 1331
    for (uint cnt = 0; cnt < table_count; cnt++)
    {
      if (tmp_tables[cnt])
      {
	free_tmp_table(thd, tmp_tables[cnt]);
	tmp_table_param[cnt].cleanup();
      }
    }
1332
  }
1333 1334
  if (copy_field)
    delete [] copy_field;
1335
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;		// Restore this setting
1336 1337
  DBUG_ASSERT(trans_safe || !updated || 
              thd->transaction.all.modified_non_trans_table);
1338 1339 1340
}


1341
bool multi_update::send_data(List<Item> &not_used_values)
1342
{
1343 1344 1345
  TABLE_LIST *cur_table;
  DBUG_ENTER("multi_update::send_data");

bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
1346
  for (cur_table= update_tables; cur_table; cur_table= cur_table->next_local)
1347
  {
1348
    TABLE *table= cur_table->table;
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
    /*
      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.
    */
1361 1362 1363 1364 1365
    if (table->status & (STATUS_NULL_ROW | STATUS_UPDATED))
      continue;

    uint offset= cur_table->shared;
    table->file->position(table->record[0]);
1366 1367 1368 1369
    /*
      We can use compare_record() to optimize away updates if
      the table handler is returning all columns
    */
1370
    if (table == table_to_update)
1371
    {
1372 1373 1374
      bool can_compare_record;
      can_compare_record= !(table->file->table_flags() &
                            HA_PARTIAL_COLUMN_READ);
1375
      table->status|= STATUS_UPDATED;
1376
      store_record(table,record[1]);
1377 1378 1379 1380
      if (fill_record_n_invoke_before_triggers(thd, *fields_for_table[offset],
                                               *values_for_table[offset], 0,
                                               table->triggers,
                                               TRG_EVENT_UPDATE))
1381
	DBUG_RETURN(1);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1382

1383
      found++;
1384
      if (!can_compare_record || compare_record(table, thd->query_id))
1385
      {
1386
	int error;
monty@mysql.com's avatar
monty@mysql.com committed
1387
        if ((error= cur_table->view_check_option(thd, ignore)) !=
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1388 1389 1390 1391 1392 1393 1394 1395
            VIEW_CHECK_OK)
        {
          found--;
          if (error == VIEW_CHECK_SKIP)
            continue;
          else if (error == VIEW_CHECK_ERROR)
            DBUG_RETURN(1);
        }
1396
	if (!updated++)
1397
	{
1398 1399 1400 1401 1402 1403
	  /*
	    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);
1404
	}
1405 1406
	if ((error=table->file->update_row(table->record[1],
					   table->record[0])))
1407
	{
1408
	  updated--;
1409
          if (!ignore || error != HA_ERR_FOUND_DUPP_KEY)
1410
	  {
1411 1412 1413 1414 1415 1416
            /*
              If (ignore && error == HA_ERR_FOUND_DUPP_KEY) we don't have to
              do anything; otherwise...
            */
            if (error != HA_ERR_FOUND_DUPP_KEY)
              thd->fatal_error(); /* Other handler errors are fatal */
1417 1418 1419
	    table->file->print_error(error,MYF(0));
	    DBUG_RETURN(1);
	  }
1420
	}
1421 1422
        else
        {
1423 1424 1425 1426 1427 1428 1429
          /* non-transactional or transactional table got modified   */
          /* either multi_update class' flag is raised in its branch */
          if (table->file->has_transactions())
            transactional_tables= 1;
          else
          {
            trans_safe= 0;
1430
            thd->transaction.stmt.modified_non_trans_table= TRUE;
1431
          }
1432 1433 1434 1435 1436
          if (table->triggers &&
              table->triggers->process_triggers(thd, TRG_EVENT_UPDATE,
                                                TRG_ACTION_AFTER, TRUE))
	    DBUG_RETURN(1);
        }
1437
      }
1438 1439 1440 1441 1442
    }
    else
    {
      int error;
      TABLE *tmp_table= tmp_tables[offset];
gshchepa/uchum@gleb.loc's avatar
gshchepa/uchum@gleb.loc committed
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
      /* Store regular updated fields in the row. */
      fill_record(thd,
                  tmp_table->field + 1 + unupdated_check_opt_tables.elements,
                  *values_for_table[offset], 1);
      /*
       For updatable VIEW store rowid of the updated table and
       rowids of tables used in the CHECK OPTION condition.
      */
      uint field_num= 0;
      List_iterator_fast<TABLE> tbl_it(unupdated_check_opt_tables);
      TABLE *tbl= table;
      do
      {
        if (tbl != table)
          tbl->file->position(tbl->record[0]);
        memcpy((char*) tmp_table->field[field_num]->ptr,
               (char*) tbl->file->ref, tbl->file->ref_length);
        field_num++;
      } while ((tbl= tbl_it++));

1463
      /* Write row, ignoring duplicated updates to a row */
1464 1465
      error= tmp_table->file->write_row(tmp_table->record[0]);
      if (error != HA_ERR_FOUND_DUPP_KEY && error != HA_ERR_FOUND_DUPP_UNIQUE)
1466
      {
1467
        if (error &&
1468
            create_myisam_from_heap(thd, tmp_table,
1469 1470 1471 1472 1473
                                    tmp_table_param + offset, error, 1))
        {
          do_update= 0;
          DBUG_RETURN(1);			// Not a table_is_full error
        }
1474
        found++;
1475
      }
1476 1477
    }
  }
1478
  DBUG_RETURN(0);
1479 1480
}

1481

1482 1483 1484
void multi_update::send_error(uint errcode,const char *err)
{
  /* First send error what ever it is ... */
1485
  my_error(errcode, MYF(0), err);
1486 1487

  /* If nothing updated return */
1488 1489
  if (updated == 0) /* the counter might be reset in send_eof */
    return;         /* and then the query has been binlogged */
1490

1491
  /* Something already updated so we have to invalidate cache */
1492
  query_cache_invalidate3(thd, update_tables, 1);
1493
  /*
1494 1495
    If all tables that has been updated are trans safe then just do rollback.
    If not attempt to do remaining updates.
1496
  */
1497 1498 1499

  if (trans_safe)
  {
1500 1501 1502 1503 1504
    DBUG_ASSERT(transactional_tables);
    (void) ha_autocommit_or_rollback(thd, 1);
  }
  else
  { 
1505
    DBUG_ASSERT(thd->transaction.stmt.modified_non_trans_table);
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
    if (do_update && table_count > 1)
    {
      /* Add warning here */
      /* 
         todo/fixme: do_update() is never called with the arg 1.
         should it change the signature to become argless?
      */
      VOID(do_updates(0));
    }
  }
1516
  if (thd->transaction.stmt.modified_non_trans_table)
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
  {
    /*
      The query has to binlog because there's a modified non-transactional table
      either from the query's list or via a stored routine: bug#13270,23333
    */
    if (mysql_bin_log.is_open())
    {
      Query_log_event qinfo(thd, thd->query, thd->query_length,
                            transactional_tables, FALSE);
      mysql_bin_log.write(&qinfo);
    }
    if (!trans_safe)
1529
      thd->transaction.all.modified_non_trans_table= TRUE;
1530
  }
1531
  DBUG_ASSERT(trans_safe || !updated || thd->transaction.stmt.modified_non_trans_table);
1532 1533 1534 1535
  
  if (transactional_tables)
  {
    (void) ha_autocommit_or_rollback(thd, 1);
1536
  }
1537 1538 1539
}


1540
int multi_update::do_updates(bool from_send_error)
1541
{
1542
  TABLE_LIST *cur_table;
gshchepa/uchum@gleb.loc's avatar
gshchepa/uchum@gleb.loc committed
1543
  int local_error= 0;
1544
  ha_rows org_updated;
1545
  TABLE *table, *tmp_table;
gshchepa/uchum@gleb.loc's avatar
gshchepa/uchum@gleb.loc committed
1546
  List_iterator_fast<TABLE> check_opt_it(unupdated_check_opt_tables);
1547 1548
  DBUG_ENTER("do_updates");

1549
  do_update= 0;					// Don't retry this function
1550
  if (!found)
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
1551
    DBUG_RETURN(0);
bell@sanja.is.com.ua's avatar
VIEW  
bell@sanja.is.com.ua committed
1552
  for (cur_table= update_tables; cur_table; cur_table= cur_table->next_local)
1553
  {
1554
    bool can_compare_record;
gshchepa/uchum@gleb.loc's avatar
gshchepa/uchum@gleb.loc committed
1555
    uint offset= cur_table->shared;
1556

1557
    table = cur_table->table;
1558
    if (table == table_to_update)
1559 1560
      continue;					// Already updated
    org_updated= updated;
1561
    tmp_table= tmp_tables[cur_table->shared];
1562
    tmp_table->file->extra(HA_EXTRA_CACHE);	// Change to read cache
1563
    (void) table->file->ha_rnd_init(0);
1564 1565
    table->file->extra(HA_EXTRA_NO_CACHE);

gshchepa/uchum@gleb.loc's avatar
gshchepa/uchum@gleb.loc committed
1566 1567 1568 1569 1570 1571 1572 1573
    check_opt_it.rewind();
    while(TABLE *tbl= check_opt_it++)
    {
      if (tbl->file->ha_rnd_init(1))
        goto err;
      tbl->file->extra(HA_EXTRA_CACHE);
    }

1574 1575 1576
    /*
      Setup copy functions to copy fields from temporary table
    */
gshchepa/uchum@gleb.loc's avatar
gshchepa/uchum@gleb.loc committed
1577 1578 1579
    List_iterator_fast<Item> field_it(*fields_for_table[offset]);
    Field **field= tmp_table->field + 
                   1 + unupdated_check_opt_tables.elements; // Skip row pointers
1580 1581
    Copy_field *copy_field_ptr= copy_field, *copy_field_end;
    for ( ; *field ; field++)
1582
    {
1583 1584
      Item_field *item= (Item_field* ) field_it++;
      (copy_field_ptr++)->set(item->field, *field, 0);
1585
    }
1586 1587
    copy_field_end=copy_field_ptr;

1588
    if ((local_error = tmp_table->file->ha_rnd_init(1)))
1589 1590
      goto err;

1591 1592 1593
    can_compare_record= !(table->file->table_flags() &
                          HA_PARTIAL_COLUMN_READ);

1594
    for (;;)
1595
    {
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605
      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;
      }
gshchepa/uchum@gleb.loc's avatar
gshchepa/uchum@gleb.loc committed
1606 1607 1608 1609 1610 1611 1612

      /* call rnd_pos() using rowids from temporary table */
      check_opt_it.rewind();
      TABLE *tbl= table;
      uint field_num= 0;
      do
      {
gshchepa/uchum@gleb.loc's avatar
gshchepa/uchum@gleb.loc committed
1613 1614 1615
        if((local_error=
              tbl->file->rnd_pos(tbl->record[0],
                                (byte *) tmp_table->field[field_num]->ptr)))
gshchepa/uchum@gleb.loc's avatar
gshchepa/uchum@gleb.loc committed
1616 1617 1618 1619
          goto err;
        field_num++;
      } while((tbl= check_opt_it++));

1620
      table->status|= STATUS_UPDATED;
1621
      store_record(table,record[1]);
1622 1623 1624 1625 1626 1627 1628

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

1629 1630 1631 1632 1633
      if (table->triggers &&
          table->triggers->process_triggers(thd, TRG_EVENT_UPDATE,
                                            TRG_ACTION_BEFORE, TRUE))
        goto err2;

1634
      if (!can_compare_record || compare_record(table, thd->query_id))
1635
      {
igor@olga.mysql.com's avatar
igor@olga.mysql.com committed
1636 1637 1638 1639 1640 1641 1642 1643 1644
        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;
        }
1645 1646 1647
	if ((local_error=table->file->update_row(table->record[1],
						 table->record[0])))
	{
1648
	  if (!ignore || local_error != HA_ERR_FOUND_DUPP_KEY)
1649 1650 1651
	    goto err;
	}
	updated++;
1652 1653 1654 1655 1656

        if (table->triggers &&
            table->triggers->process_triggers(thd, TRG_EVENT_UPDATE,
                                              TRG_ACTION_AFTER, TRUE))
          goto err2;
1657
      }
1658 1659 1660 1661 1662
    }

    if (updated != org_updated)
    {
      if (table->file->has_transactions())
1663
        transactional_tables= 1;
1664
      else
1665 1666
      {
        trans_safe= 0;				// Can't do safe rollback
1667
        thd->transaction.stmt.modified_non_trans_table= TRUE;
1668
      }
1669
    }
1670 1671
    (void) table->file->ha_rnd_end();
    (void) tmp_table->file->ha_rnd_end();
gshchepa/uchum@gleb.loc's avatar
gshchepa/uchum@gleb.loc committed
1672 1673 1674 1675
    check_opt_it.rewind();
    while (TABLE *tbl= check_opt_it++)
        tbl->file->ha_rnd_end();

1676
  }
1677 1678 1679 1680
  DBUG_RETURN(0);

err:
  if (!from_send_error)
monty@mysql.com's avatar
monty@mysql.com committed
1681 1682
  {
    thd->fatal_error();
1683
    table->file->print_error(local_error,MYF(0));
monty@mysql.com's avatar
monty@mysql.com committed
1684
  }
1685

1686
err2:
1687 1688
  (void) table->file->ha_rnd_end();
  (void) tmp_table->file->ha_rnd_end();
gshchepa/uchum@gleb.loc's avatar
gshchepa/uchum@gleb.loc committed
1689 1690 1691
  check_opt_it.rewind();
  while (TABLE *tbl= check_opt_it++)
      tbl->file->ha_rnd_end();
1692

1693 1694 1695
  if (updated != org_updated)
  {
    if (table->file->has_transactions())
1696
      transactional_tables= 1;
1697
    else
1698
    {
1699
      trans_safe= 0;
1700
      thd->transaction.stmt.modified_non_trans_table= TRUE;
1701
    }
1702 1703
  }
  DBUG_RETURN(1);
1704 1705 1706
}


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

1709 1710
bool multi_update::send_eof()
{
1711
  char buff[STRING_BUFFER_USUAL_SIZE];
1712
  thd->proc_info="updating reference tables";
1713 1714

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

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1718 1719 1720 1721 1722 1723 1724
  /* 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
1725 1726
  /*
    Write the SQL statement to the binlog if we updated
1727
    rows and we succeeded or if we updated some non
1728
    transactional tables.
1729 1730 1731
    
    The query has to binlog because there's a modified non-transactional table
    either from the query's list or via a stored routine: bug#13270,23333
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1732
  */
1733

1734 1735 1736
  DBUG_ASSERT(trans_safe || !updated || 
              thd->transaction.stmt.modified_non_trans_table);
  if (local_error == 0 || thd->transaction.stmt.modified_non_trans_table)
1737
  {
1738 1739
    if (mysql_bin_log.is_open())
    {
1740
      if (local_error == 0)
guilhem@mysql.com's avatar
guilhem@mysql.com committed
1741
        thd->clear_error();
1742 1743
      else
        updated= 0; /* if there's an error binlog it here not in ::send_error */
1744
      Query_log_event qinfo(thd, thd->query, thd->query_length,
1745
			    transactional_tables, FALSE);
1746
      if (mysql_bin_log.write(&qinfo) && trans_safe)
1747
        local_error= 1;				// Rollback update
1748
    }
1749 1750
    if (thd->transaction.stmt.modified_non_trans_table)
      thd->transaction.all.modified_non_trans_table= TRUE;
1751
  }
1752

1753 1754
  if (transactional_tables)
  {
1755
    if (ha_autocommit_or_rollback(thd, local_error != 0))
1756 1757
      local_error=1;
  }
1758

1759 1760
  if (local_error > 0) // if the above log write did not fail ...
  {
1761
    /* Safety: If we haven't got an error before (can happen in do_updates) */
1762 1763
    my_message(ER_UNKNOWN_ERROR, "An error occured in multi-table update",
	       MYF(0));
1764
    return TRUE;
1765
  }
1766 1767


1768 1769
  sprintf(buff, ER(ER_UPDATE_INFO), (ulong) found, (ulong) updated,
	  (ulong) thd->cuted_fields);
1770 1771
  thd->row_count_func=
    (thd->client_capabilities & CLIENT_FOUND_ROWS) ? found : updated;
1772
  ::send_ok(thd, (ulong) thd->row_count_func,
1773
	    thd->insert_id_used ? thd->last_insert_id : 0L,buff);
1774
  return FALSE;
1775
}