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

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

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

unknown's avatar
unknown committed
12 13 14 15 16
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */


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

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

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

29
static bool compare_record(TABLE *table, query_id_t query_id)
unknown's avatar
unknown committed
30
{
31
  if (table->s->blob_fields + table->s->varchar_fields == 0)
unknown's avatar
unknown committed
32
    return cmp_record(table,record[1]);
unknown's avatar
unknown committed
33
  /* Compare null bits */
unknown's avatar
unknown committed
34
  if (memcmp(table->null_flags,
35 36
	     table->null_flags+table->s->rec_buff_length,
	     table->s->null_bytes))
37
    return TRUE;				// Diff in NULL value
unknown's avatar
unknown committed
38
  /* Compare updated fields */
unknown's avatar
unknown 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;
unknown's avatar
unknown committed
44
  }
45
  return FALSE;
unknown's avatar
unknown committed
46 47 48
}


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

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

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

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

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


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

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

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

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

unknown's avatar
unknown committed
139
  LINT_INIT(timestamp_query_id);
unknown's avatar
unknown 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
  }
unknown's avatar
unknown committed
161

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

unknown's avatar
unknown committed
167
  thd->proc_info="init";
unknown's avatar
unknown committed
168
  table= table_list->table;
unknown's avatar
unknown 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();
unknown's avatar
unknown committed
174

unknown's avatar
unknown committed
175
#ifndef NO_EMBEDDED_ACCESS_CHECKS
176 177
  /* TABLE_LIST contain right privilages request */
  want_privilege= table_list->grant.want_privilege;
unknown's avatar
unknown committed
178
#endif
179
  if (mysql_prepare_update(thd, table_list, &conds, order_num, order))
unknown's avatar
merge  
unknown committed
180
    DBUG_RETURN(1);
181

unknown's avatar
unknown committed
182
  old_used_keys= table->used_keys;		// Keys used in WHERE
unknown's avatar
unknown committed
183
  /*
184 185
    Change the query_id for the timestamp column so that we can
    check if this is modified directly
unknown's avatar
unknown committed
186
  */
187 188 189 190 191
  if (table->timestamp_field)
  {
    timestamp_query_id=table->timestamp_field->query_id;
    table->timestamp_field->query_id=thd->query_id-1;
  }
unknown's avatar
unknown committed
192

193
  /* Check the fields we are going to modify */
unknown's avatar
unknown committed
194
#ifndef NO_EMBEDDED_ACCESS_CHECKS
unknown's avatar
VIEW  
unknown committed
195
  table_list->grant.want_privilege= table->grant.want_privilege= want_privilege;
196
  table_list->register_want_access(want_privilege);
unknown's avatar
unknown committed
197
#endif
198 199
  if (setup_fields_with_no_wrap(thd, 0, fields, 1, 0, 0))
    DBUG_RETURN(1);                     /* purecov: inspected */
unknown's avatar
unknown committed
200
  if (table_list->view && check_fields(thd, fields))
unknown's avatar
VIEW  
unknown committed
201
  {
unknown's avatar
merge  
unknown committed
202
    DBUG_RETURN(1);
unknown's avatar
VIEW  
unknown committed
203 204 205
  }
  if (!table_list->updatable || check_key_in_view(thd, table_list))
  {
206
    my_error(ER_NON_UPDATABLE_TABLE, MYF(0), table_list->alias, "UPDATE");
unknown's avatar
merge  
unknown committed
207
    DBUG_RETURN(1);
unknown's avatar
VIEW  
unknown committed
208
  }
209 210 211 212
  if (table->timestamp_field)
  {
    // Don't set timestamp column if this is modified
    if (table->timestamp_field->query_id == thd->query_id)
213
      table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
214 215 216
    else
      table->timestamp_field->query_id=timestamp_query_id;
  }
217

unknown's avatar
unknown committed
218
#ifndef NO_EMBEDDED_ACCESS_CHECKS
219
  /* Check values */
unknown's avatar
VIEW  
unknown committed
220
  table_list->grant.want_privilege= table->grant.want_privilege=
unknown's avatar
unknown committed
221
    (SELECT_ACL & ~table->grant.privilege);
unknown's avatar
unknown committed
222
#endif
223
  if (setup_fields(thd, 0, values, 1, 0, 0))
unknown's avatar
unknown committed
224
  {
225
    free_underlaid_joins(thd, select_lex);
unknown's avatar
merge  
unknown committed
226
    DBUG_RETURN(1);				/* purecov: inspected */
unknown's avatar
unknown committed
227
  }
unknown's avatar
unknown committed
228

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

unknown's avatar
unknown committed
285
  if (used_key_is_modified || order)
unknown's avatar
unknown committed
286 287
  {
    /*
unknown's avatar
unknown committed
288 289
      We can't update table directly;  We must first search after all
      matching rows before updating the table!
unknown's avatar
unknown committed
290
    */
unknown's avatar
unknown committed
291
    table->file->extra(HA_EXTRA_RETRIEVE_ALL_COLS);
292
    if (used_index < MAX_KEY && old_used_keys.is_set(used_index))
unknown's avatar
unknown committed
293 294
    {
      table->key_read=1;
295
      table->file->extra(HA_EXTRA_KEYREAD);
unknown's avatar
unknown committed
296
    }
297

298
    /* note: can actually avoid sorting below.. */
299
    if (order && (need_sort || used_key_is_modified))
300
    {
unknown's avatar
unknown committed
301 302 303 304
      /*
	Doing an ORDER BY;  Let filesort find and sort the rows we are going
	to update
      */
305 306
      uint         length;
      SORT_FIELD  *sortorder;
307
      ha_rows examined_rows;
308

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

unknown's avatar
unknown committed
340 341 342
      /* If quick select is used, initialize it before retrieving rows. */
      if (select && select->quick && select->quick->reset())
        goto err;
343

344 345 346 347 348 349 350 351 352 353
      /*
        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
      */
354
      if (used_index == MAX_KEY || (select && select->quick))
355 356 357
        init_read_record(&info,thd,table,select,0,1);
      else
        init_read_record_idx(&info, thd, table, 1, used_index);
unknown's avatar
VIEW  
unknown committed
358

unknown's avatar
unknown committed
359 360
      thd->proc_info="Searching rows for update";
      uint tmp_limit= limit;
unknown's avatar
unknown committed
361

unknown's avatar
unknown committed
362
      while (!(error=info.read_record(&info)) && !thd->killed)
unknown's avatar
unknown committed
363
      {
364
	if (!(select && select->skip_record()))
unknown's avatar
unknown committed
365
	{
unknown's avatar
unknown committed
366 367 368 369 370 371 372 373
	  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)
374 375
	  {
	    error= -1;
unknown's avatar
unknown committed
376
	    break;
377
	  }
unknown's avatar
unknown committed
378
	}
unknown's avatar
unknown committed
379 380
	else
	  table->file->unlock_row();
unknown's avatar
unknown committed
381
      }
382 383
      if (thd->killed && !error)
	error= 1;				// Aborted
384
      limit= tmp_limit;
unknown's avatar
unknown committed
385
      end_read_record(&info);
386
     
unknown's avatar
unknown committed
387 388 389 390 391 392 393 394 395
      /* Change select to use tempfile */
      if (select)
      {
	delete select->quick;
	if (select->free_cond)
	  delete select->cond;
	select->quick=0;
	select->cond=0;
      }
unknown's avatar
unknown committed
396 397
      else
      {
unknown's avatar
unknown committed
398 399
	select= new SQL_SELECT;
	select->head=table;
unknown's avatar
unknown committed
400
      }
unknown's avatar
unknown committed
401 402 403 404
      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)
405
	goto err;
unknown's avatar
unknown committed
406 407 408 409 410 411 412 413
    }
    if (table->key_read)
    {
      table->key_read=0;
      table->file->extra(HA_EXTRA_NO_KEYREAD);
    }
  }

414
  if (ignore)
unknown's avatar
unknown committed
415
    table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
416 417 418
  
  if (select && select->quick && select->quick->reset())
        goto err;
unknown's avatar
unknown committed
419 420
  init_read_record(&info,thd,table,select,0,1);

421
  updated= found= 0;
422
  thd->count_cuted_fields= CHECK_FIELD_WARN;		/* calc cuted fields */
unknown's avatar
unknown committed
423
  thd->cuted_fields=0L;
424
  thd->proc_info="Updating";
425
  query_id=thd->query_id;
unknown's avatar
unknown committed
426

unknown's avatar
unknown committed
427 428
  transactional_table= table->file->has_transactions();
  thd->no_trans_update= 0;
unknown's avatar
unknown committed
429
  thd->abort_on_warning= test(!ignore &&
unknown's avatar
unknown committed
430 431 432
                              (thd->variables.sql_mode &
                               (MODE_STRICT_TRANS_TABLES |
                                MODE_STRICT_ALL_TABLES)));
unknown's avatar
unknown committed
433

434 435 436
  if (table->triggers)
    table->triggers->mark_fields_used(thd, TRG_EVENT_UPDATE);

437 438 439 440 441 442
  /*
    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);
unknown's avatar
unknown committed
443 444
  while (!(error=info.read_record(&info)) && !thd->killed)
  {
445
    if (!(select && select->skip_record()))
unknown's avatar
unknown committed
446
    {
unknown's avatar
unknown committed
447
      store_record(table,record[1]);
unknown's avatar
unknown committed
448 449 450
      if (fill_record_n_invoke_before_triggers(thd, fields, values, 0,
                                               table->triggers,
                                               TRG_EVENT_UPDATE))
unknown's avatar
unknown committed
451
	break; /* purecov: inspected */
unknown's avatar
unknown committed
452

unknown's avatar
unknown committed
453
      found++;
454

455
      if (!can_compare_record || compare_record(table, query_id))
unknown's avatar
unknown committed
456
      {
unknown's avatar
unknown committed
457
        if ((res= table_list->view_check_option(thd, ignore)) !=
unknown's avatar
unknown committed
458 459 460 461 462 463 464 465 466 467 468
            VIEW_CHECK_OK)
        {
          found--;
          if (res == VIEW_CHECK_SKIP)
            continue;
          else if (res == VIEW_CHECK_ERROR)
          {
            error= 1;
            break;
          }
        }
unknown's avatar
unknown committed
469 470 471 472
	if (!(error=table->file->update_row((byte*) table->record[1],
					    (byte*) table->record[0])))
	{
	  updated++;
unknown's avatar
unknown committed
473
          thd->no_trans_update= !transactional_table;
unknown's avatar
unknown committed
474 475 476 477 478 479 480 481

          if (table->triggers &&
              table->triggers->process_triggers(thd, TRG_EVENT_UPDATE,
                                                TRG_ACTION_AFTER, TRUE))
          {
            error= 1;
            break;
          }
unknown's avatar
unknown committed
482
	}
483
 	else if (!ignore || error != HA_ERR_FOUND_DUPP_KEY)
unknown's avatar
unknown committed
484
	{
485 486 487 488 489 490
          /*
            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 */
unknown's avatar
unknown committed
491 492 493 494 495
	  table->file->print_error(error,MYF(0));
	  error= 1;
	  break;
	}
      }
496

unknown's avatar
unknown committed
497 498 499 500 501
      if (!--limit && using_limit)
      {
	error= -1;				// Simulate end of file
	break;
      }
unknown's avatar
unknown committed
502
    }
unknown's avatar
unknown committed
503 504
    else
      table->file->unlock_row();
505
    thd->row_count++;
unknown's avatar
unknown committed
506
  }
507 508
  if (thd->killed && !error)
    error= 1;					// Aborted
unknown's avatar
unknown committed
509
  end_read_record(&info);
unknown's avatar
unknown committed
510
  free_io_cache(table);				// If ORDER BY
unknown's avatar
unknown committed
511
  delete select;
unknown's avatar
unknown committed
512
  thd->proc_info="end";
unknown's avatar
unknown committed
513
  VOID(table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY));
unknown's avatar
unknown committed
514 515 516 517 518 519

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

524 525 526 527 528 529 530 531 532 533
  /*
    error < 0 means really no error at all: we processed all rows until the
    last one without error. error > 0 means an error (e.g. unique key
    violation and no IGNORE or REPLACE). error == 0 is also an error (if
    preparing the record or invoking before triggers fails). See
    ha_autocommit_or_rollback(error>=0) and DBUG_RETURN(error>=0) below.
    Sometimes we want to binlog even if we updated no rows, in case user used
    it to be sure master and slave are in same state.
  */
  if ((error < 0) || (updated && !transactional_table))
unknown's avatar
unknown committed
534
  {
535 536
    if (mysql_bin_log.is_open())
    {
537
      if (error < 0)
unknown's avatar
unknown committed
538
        thd->clear_error();
539
      Query_log_event qinfo(thd, thd->query, thd->query_length,
unknown's avatar
unknown committed
540
			    transactional_table, FALSE);
541 542
      if (mysql_bin_log.write(&qinfo) && transactional_table)
	error=1;				// Rollback update
543
    }
unknown's avatar
unknown committed
544
    if (!transactional_table)
545
      thd->options|=OPTION_STATUS_NO_TRANS_UPDATE;
unknown's avatar
unknown committed
546
  }
547
  free_underlaid_joins(thd, select_lex);
unknown's avatar
unknown committed
548 549 550 551 552
  if (transactional_table)
  {
    if (ha_autocommit_or_rollback(thd, error >= 0))
      error=1;
  }
unknown's avatar
unknown committed
553

554 555 556 557 558 559
  if (thd->lock)
  {
    mysql_unlock_tables(thd, thd->lock);
    thd->lock=0;
  }

unknown's avatar
unknown committed
560
  if (error < 0)
unknown's avatar
unknown committed
561
  {
unknown's avatar
unknown committed
562
    char buff[STRING_BUFFER_USUAL_SIZE];
563 564
    sprintf(buff, ER(ER_UPDATE_INFO), (ulong) found, (ulong) updated,
	    (ulong) thd->cuted_fields);
565 566
    thd->row_count_func=
      (thd->client_capabilities & CLIENT_FOUND_ROWS) ? found : updated;
567
    send_ok(thd, (ulong) thd->row_count_func,
568
	    thd->insert_id_used ? thd->last_insert_id : 0L,buff);
unknown's avatar
unknown committed
569
    DBUG_PRINT("info",("%ld records updated", (long) updated));
unknown's avatar
unknown committed
570
  }
571
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;		/* calc cuted fields */
572
  thd->abort_on_warning= 0;
unknown's avatar
unknown committed
573
  free_io_cache(table);
unknown's avatar
merge  
unknown committed
574
  DBUG_RETURN((error >= 0 || thd->net.report_error) ? 1 : 0);
575 576 577

err:
  delete select;
578
  free_underlaid_joins(thd, select_lex);
579 580 581 582 583
  if (table->key_read)
  {
    table->key_read=0;
    table->file->extra(HA_EXTRA_NO_KEYREAD);
  }
unknown's avatar
unknown committed
584
  thd->abort_on_warning= 0;
unknown's avatar
merge  
unknown committed
585
  DBUG_RETURN(1);
unknown's avatar
unknown committed
586
}
587

unknown's avatar
unknown committed
588 589 590 591 592 593
/*
  Prepare items in UPDATE statement

  SYNOPSIS
    mysql_prepare_update()
    thd			- thread handler
unknown's avatar
VIEW  
unknown committed
594
    table_list		- global/local table list
unknown's avatar
unknown committed
595 596 597 598 599
    conds		- conditions
    order_num		- number of ORDER BY list entries
    order		- ORDER BY clause list

  RETURN VALUE
unknown's avatar
unknown committed
600 601
    FALSE OK
    TRUE  error
unknown's avatar
unknown committed
602
*/
unknown's avatar
unknown committed
603
bool mysql_prepare_update(THD *thd, TABLE_LIST *table_list,
unknown's avatar
unknown committed
604 605
			 Item **conds, uint order_num, ORDER *order)
{
606
  Item *fake_conds= 0;
unknown's avatar
unknown committed
607 608 609
  TABLE *table= table_list->table;
  TABLE_LIST tables;
  List<Item> all_fields;
610
  SELECT_LEX *select_lex= &thd->lex->select_lex;
unknown's avatar
unknown committed
611 612 613
  DBUG_ENTER("mysql_prepare_update");

#ifndef NO_EMBEDDED_ACCESS_CHECKS
unknown's avatar
VIEW  
unknown committed
614 615
  table_list->grant.want_privilege= table->grant.want_privilege= 
    (SELECT_ACL & ~table->grant.privilege);
616
  table_list->register_want_access(SELECT_ACL);
unknown's avatar
unknown committed
617 618 619 620 621
#endif

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

624 625 626 627
  if (setup_tables_and_check_access(thd, &select_lex->context, 
                                    &select_lex->top_join_list,
                                    table_list, conds, 
                                    &select_lex->leaf_tables,
628
                                    FALSE, UPDATE_ACL, SELECT_ACL) ||
629
      setup_conds(thd, table_list, select_lex->leaf_tables, conds) ||
630 631
      select_lex->setup_ref_array(thd, order_num) ||
      setup_order(thd, select_lex->ref_pointer_array,
unknown's avatar
VIEW  
unknown committed
632
		  table_list, all_fields, all_fields, order) ||
633
      setup_ftfuncs(select_lex))
unknown's avatar
unknown committed
634
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
635 636 637

  /* Check that we are not using table that we are updating in a sub select */
  {
638
    TABLE_LIST *duplicate;
639
    if ((duplicate= unique_table(thd, table_list, table_list->next_global)))
640 641 642 643 644
    {
      update_non_unique_table_error(table_list, "UPDATE", duplicate);
      my_error(ER_UPDATE_TABLE_USED, MYF(0), table_list->table_name);
      DBUG_RETURN(TRUE);
    }
unknown's avatar
unknown committed
645
  }
646
  select_lex->fix_prepare_information(thd, conds, &fake_conds);
unknown's avatar
unknown committed
647
  DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
648 649
}

unknown's avatar
unknown committed
650

651
/***************************************************************************
652
  Update multiple tables from join 
653 654
***************************************************************************/

unknown's avatar
unknown committed
655
/*
656
  Get table map for list of Item_field
unknown's avatar
unknown committed
657 658
*/

659 660 661 662 663 664 665 666
static table_map get_table_map(List<Item> *items)
{
  List_iterator_fast<Item> item_it(*items);
  Item_field *item;
  table_map map= 0;

  while ((item= (Item_field *) item_it++)) 
    map|= item->used_tables();
unknown's avatar
unknown committed
667
  DBUG_PRINT("info", ("table_map: 0x%08lx", (long) map));
668 669 670 671
  return map;
}


unknown's avatar
VIEW  
unknown committed
672 673
/*
  make update specific preparation and checks after opening tables
unknown's avatar
unknown committed
674

unknown's avatar
VIEW  
unknown committed
675 676 677
  SYNOPSIS
    mysql_multi_update_prepare()
    thd         thread handler
unknown's avatar
unknown committed
678

unknown's avatar
VIEW  
unknown committed
679
  RETURN
unknown's avatar
unknown committed
680 681
    FALSE OK
    TRUE  Error
unknown's avatar
VIEW  
unknown committed
682
*/
683

unknown's avatar
unknown committed
684
bool mysql_multi_update_prepare(THD *thd)
unknown's avatar
VIEW  
unknown committed
685 686 687
{
  LEX *lex= thd->lex;
  TABLE_LIST *table_list= lex->query_tables;
unknown's avatar
unknown committed
688
  TABLE_LIST *tl, *leaves;
unknown's avatar
VIEW  
unknown committed
689
  List<Item> *fields= &lex->select_lex.item_list;
unknown's avatar
unknown committed
690
  table_map tables_for_update;
unknown's avatar
unknown committed
691
  bool update_view= 0;
unknown's avatar
unknown committed
692 693 694 695 696 697
  /*
    if this multi-update was converted from usual update, here is table
    counter else junk will be assigned here, but then replaced with real
    count in open_tables()
  */
  uint  table_count= lex->table_count;
unknown's avatar
unknown committed
698
  const bool using_lock_tables= thd->locked_tables != 0;
unknown's avatar
unknown committed
699
  bool original_multiupdate= (thd->lex->sql_command == SQLCOM_UPDATE_MULTI);
700
  bool need_reopen= FALSE;
unknown's avatar
unknown committed
701 702
  DBUG_ENTER("mysql_multi_update_prepare");

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

706 707
reopen_tables:

unknown's avatar
unknown committed
708
  /* open tables and create derived ones, but do not lock and fill them */
709
  if (((original_multiupdate || need_reopen) &&
710
       open_tables(thd, &table_list, &table_count, 0)) ||
unknown's avatar
unknown committed
711
      mysql_handle_derived(lex, &mysql_derived_prepare))
712
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
713 714 715 716 717
  /*
    setup_tables() need for VIEWs. JOIN::prepare() will call setup_tables()
    second time, but this call will do nothing (there are check for second
    call in setup_tables()).
  */
unknown's avatar
merge  
unknown committed
718

719 720 721 722
  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,
723
                                    UPDATE_ACL, SELECT_ACL))
unknown's avatar
merge  
unknown committed
724
    DBUG_RETURN(TRUE);
725

726
  if (setup_fields_with_no_wrap(thd, 0, *fields, 1, 0, 0))
unknown's avatar
unknown committed
727
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
728 729 730 731 732 733 734 735 736 737 738

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

  if (update_view && check_fields(thd, *fields))
739
  {
unknown's avatar
unknown committed
740
    DBUG_RETURN(TRUE);
unknown's avatar
VIEW  
unknown committed
741 742
  }

unknown's avatar
unknown committed
743
  tables_for_update= get_table_map(fields);
unknown's avatar
unknown committed
744 745

  /*
unknown's avatar
unknown committed
746
    Setup timestamp handling and locking mode
unknown's avatar
unknown committed
747
  */
748
  leaves= lex->select_lex.leaf_tables;
749
  for (tl= leaves; tl; tl= tl->next_leaf)
750
  {
unknown's avatar
unknown committed
751
    TABLE *table= tl->table;
unknown's avatar
unknown committed
752
    /* Only set timestamp column if this is not modified */
753 754
    if (table->timestamp_field &&
        table->timestamp_field->query_id == thd->query_id)
unknown's avatar
unknown committed
755
      table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
unknown's avatar
VIEW  
unknown committed
756

unknown's avatar
unknown committed
757 758
    /* if table will be updated then check that it is unique */
    if (table->map & tables_for_update)
759
    {
unknown's avatar
unknown committed
760
      if (!tl->updatable || check_key_in_view(thd, tl))
unknown's avatar
unknown committed
761
      {
762
        my_error(ER_NON_UPDATABLE_TABLE, MYF(0), tl->alias, "UPDATE");
unknown's avatar
merge  
unknown committed
763
        DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
764
      }
unknown's avatar
unknown committed
765

766 767 768
      if (table->triggers)
        table->triggers->mark_fields_used(thd, TRG_EVENT_UPDATE);

unknown's avatar
unknown committed
769
      DBUG_PRINT("info",("setting table `%s` for update", tl->alias));
770 771 772 773
      /*
        If table will be updated we should not downgrade lock for it and
        leave it as is.
      */
unknown's avatar
unknown committed
774
    }
unknown's avatar
unknown committed
775 776 777
    else
    {
      DBUG_PRINT("info",("setting table `%s` for read-only", tl->alias));
unknown's avatar
unknown committed
778 779 780 781 782 783
      /*
        If we are using the binary log, we need TL_READ_NO_INSERT to get
        correct order of statements. Otherwise, we use a TL_READ lock to
        improve performance.
      */
      tl->lock_type= using_update_log ? TL_READ_NO_INSERT : TL_READ;
unknown's avatar
unknown committed
784
      tl->updating= 0;
785
      /* Update TABLE::lock_type accordingly. */
786
      if (!tl->placeholder() && !using_lock_tables)
787
        tl->table->reginfo.lock_type= tl->lock_type;
788
    }
unknown's avatar
unknown committed
789
  }
unknown's avatar
unknown committed
790
  for (tl= table_list; tl; tl= tl->next_local)
unknown's avatar
unknown committed
791
  {
unknown's avatar
unknown committed
792
    /* Check access privileges for table */
unknown's avatar
unknown committed
793
    if (!tl->derived)
794
    {
unknown's avatar
unknown committed
795 796
      uint want_privilege= tl->updating ? UPDATE_ACL : SELECT_ACL;
      if (check_access(thd, want_privilege,
797 798
                       tl->db, &tl->grant.privilege, 0, 0, 
                       test(tl->schema_table)) ||
unknown's avatar
unknown committed
799
          (grant_option && check_grant(thd, want_privilege, tl, 0, 1, 0)))
unknown's avatar
unknown committed
800
        DBUG_RETURN(TRUE);
801
    }
802
  }
unknown's avatar
unknown committed
803

unknown's avatar
unknown committed
804 805 806
  /* check single table update for view compound from several tables */
  for (tl= table_list; tl; tl= tl->next_local)
  {
unknown's avatar
unknown committed
807
    if (tl->effective_algorithm == VIEW_ALGORITHM_MERGE)
unknown's avatar
unknown committed
808 809
    {
      TABLE_LIST *for_update= 0;
unknown's avatar
unknown committed
810
      if (tl->check_single_table(&for_update, tables_for_update, tl))
unknown's avatar
unknown committed
811 812 813 814 815 816 817 818
      {
	my_error(ER_VIEW_MULTIUPDATE, MYF(0),
		 tl->view_db.str, tl->view_name.str);
	DBUG_RETURN(-1);
      }
    }
  }

unknown's avatar
unknown committed
819
  /* now lock and fill tables */
820
  if (lock_tables(thd, table_list, table_count, &need_reopen))
unknown's avatar
unknown committed
821
  {
822 823 824
    if (!need_reopen)
      DBUG_RETURN(TRUE);

unknown's avatar
unknown committed
825
    /*
826 827 828 829
      We have to reopen tables since some of them were altered or dropped
      during lock_tables() or something was done with their triggers.
      Let us do some cleanups to be able do setup_table() and setup_fields()
      once again.
unknown's avatar
unknown committed
830 831 832
    */
    List_iterator_fast<Item> it(*fields);
    Item *item;
unknown's avatar
unknown committed
833
    while ((item= it++))
unknown's avatar
unknown committed
834 835
      item->cleanup();

unknown's avatar
unknown committed
836
    /* We have to cleanup translation tables of views. */
unknown's avatar
unknown committed
837 838 839
    for (TABLE_LIST *tbl= table_list; tbl; tbl= tbl->next_global)
      tbl->cleanup_items();

840
    close_tables_for_reopen(thd, &table_list);
841
    goto reopen_tables;
unknown's avatar
unknown committed
842
  }
unknown's avatar
unknown committed
843

844 845 846 847 848
  /*
    Check that we are not using table that we are updating, but we should
    skip all tables of UPDATE SELECT itself
  */
  lex->select_lex.exclude_from_table_unique_test= TRUE;
unknown's avatar
unknown committed
849 850 851 852 853
  /* 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;
854
    if (!(tlist= tl->top_table())->derived)
unknown's avatar
unknown committed
855 856 857 858 859 860 861
    {
      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));
862
    if (tl->lock_type != TL_READ &&
863
        tl->lock_type != TL_READ_NO_INSERT)
864
    {
865
      TABLE_LIST *duplicate;
866
      if ((duplicate= unique_table(thd, tl, table_list)))
867 868 869 870
      {
        update_non_unique_table_error(table_list, "UPDATE", duplicate);
        DBUG_RETURN(TRUE);
      }
871
    }
unknown's avatar
unknown committed
872
  }
unknown's avatar
unknown committed
873 874 875 876 877 878
  /*
    Set exclude_from_table_unique_test value back to FALSE. It is needed for
    further check in multi_update::prepare whether to use record cache.
  */
  lex->select_lex.exclude_from_table_unique_test= FALSE;
 
unknown's avatar
unknown committed
879 880
  if (thd->fill_derived_tables() &&
      mysql_handle_derived(lex, &mysql_derived_filling))
881
    DBUG_RETURN(TRUE);
882

unknown's avatar
merge  
unknown committed
883
  DBUG_RETURN (FALSE);
unknown's avatar
VIEW  
unknown committed
884 885 886
}


unknown's avatar
unknown committed
887 888 889
/*
  Setup multi-update handling and call SELECT to do the join
*/
890

unknown's avatar
unknown committed
891 892 893 894 895
bool mysql_multi_update(THD *thd,
                        TABLE_LIST *table_list,
                        List<Item> *fields,
                        List<Item> *values,
                        COND *conds,
896
                        ulonglong options,
897
                        enum enum_duplicates handle_duplicates, bool ignore,
unknown's avatar
unknown committed
898
                        SELECT_LEX_UNIT *unit, SELECT_LEX *select_lex)
unknown's avatar
VIEW  
unknown committed
899 900 901 902
{
  multi_update *result;
  DBUG_ENTER("mysql_multi_update");

903
  if (!(result= new multi_update(table_list,
904 905
				 thd->lex->select_lex.leaf_tables,
				 fields, values,
906
				 handle_duplicates, ignore)))
unknown's avatar
unknown committed
907
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
908

unknown's avatar
unknown committed
909 910 911 912 913
  thd->no_trans_update= 0;
  thd->abort_on_warning= test(thd->variables.sql_mode &
                              (MODE_STRICT_TRANS_TABLES |
                               MODE_STRICT_ALL_TABLES));

unknown's avatar
unknown committed
914
  List<Item> total_list;
915 916 917 918 919 920 921 922
  (void) mysql_select(thd, &select_lex->ref_pointer_array,
                      table_list, select_lex->with_wild,
                      total_list,
                      conds, 0, (ORDER *) NULL, (ORDER *)NULL, (Item *) NULL,
                      (ORDER *)NULL,
                      options | SELECT_NO_JOIN_CACHE | SELECT_NO_UNLOCK |
                      OPTION_SETUP_TABLES_DONE,
                      result, unit, select_lex);
unknown's avatar
unknown committed
923
  delete result;
unknown's avatar
unknown committed
924
  thd->abort_on_warning= 0;
925
  DBUG_RETURN(FALSE);
926 927
}

unknown's avatar
unknown committed
928

929
multi_update::multi_update(TABLE_LIST *table_list,
930
			   TABLE_LIST *leaves_list,
unknown's avatar
unknown committed
931
			   List<Item> *field_list, List<Item> *value_list,
unknown's avatar
unknown committed
932 933
			   enum enum_duplicates handle_duplicates_arg,
                           bool ignore_arg)
934
  :all_tables(table_list), leaves(leaves_list), update_tables(0),
935
   tmp_tables(0), updated(0), found(0), fields(field_list),
936 937
   values(value_list), table_count(0), copy_field(0),
   handle_duplicates(handle_duplicates_arg), do_update(1), trans_safe(0),
938
   transactional_tables(1), ignore(ignore_arg)
unknown's avatar
unknown committed
939 940 941 942 943 944 945
{}


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

946 947
int multi_update::prepare(List<Item> &not_used_values,
			  SELECT_LEX_UNIT *lex_unit)
948
{
unknown's avatar
unknown committed
949 950
  TABLE_LIST *table_ref;
  SQL_LIST update;
951
  table_map tables_to_update;
unknown's avatar
unknown committed
952 953 954 955
  Item_field *item;
  List_iterator_fast<Item> field_it(*fields);
  List_iterator_fast<Item> value_it(*values);
  uint i, max_fields;
956
  DBUG_ENTER("multi_update::prepare");
unknown's avatar
unknown committed
957

958
  thd->count_cuted_fields= CHECK_FIELD_WARN;
959
  thd->cuted_fields=0L;
unknown's avatar
unknown committed
960 961
  thd->proc_info="updating main table";

962
  tables_to_update= get_table_map(fields);
963

unknown's avatar
unknown committed
964
  if (!tables_to_update)
965
  {
unknown's avatar
unknown committed
966
    my_message(ER_NO_TABLES_USED, ER(ER_NO_TABLES_USED), MYF(0));
unknown's avatar
unknown committed
967
    DBUG_RETURN(1);
968
  }
unknown's avatar
unknown committed
969

970
  /*
unknown's avatar
unknown committed
971 972
    We have to check values after setup_tables to get used_keys right in
    reference tables
973
  */
974

975
  if (setup_fields(thd, 0, *values, 1, 0, 0))
976 977
    DBUG_RETURN(1);

978
  /*
unknown's avatar
unknown committed
979 980 981
    Save tables beeing updated in update_tables
    update_table->shared is position for table
    Don't use key read on tables that are updated
982
  */
unknown's avatar
unknown committed
983 984

  update.empty();
985
  for (table_ref= leaves; table_ref; table_ref= table_ref->next_leaf)
986
  {
987
    /* TODO: add support of view of join support */
unknown's avatar
unknown committed
988 989
    TABLE *table=table_ref->table;
    if (tables_to_update & table->map)
990
    {
unknown's avatar
unknown committed
991 992 993
      TABLE_LIST *tl= (TABLE_LIST*) thd->memdup((char*) table_ref,
						sizeof(*tl));
      if (!tl)
994
	DBUG_RETURN(1);
unknown's avatar
VIEW  
unknown committed
995
      update.link_in_list((byte*) tl, (byte**) &tl->next_local);
unknown's avatar
unknown committed
996 997
      tl->shared= table_count++;
      table->no_keyread=1;
998
      table->used_keys.clear_all();
unknown's avatar
unknown committed
999
      table->pos_in_table_list= tl;
1000 1001
    }
  }
unknown's avatar
unknown committed
1002 1003


unknown's avatar
unknown committed
1004 1005 1006
  table_count=  update.elements;
  update_tables= (TABLE_LIST*) update.first;

1007
  tmp_tables = (TABLE**) thd->calloc(sizeof(TABLE *) * table_count);
unknown's avatar
unknown committed
1008 1009 1010 1011 1012 1013
  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);
1014
  if (thd->is_fatal_error)
unknown's avatar
unknown committed
1015 1016 1017 1018 1019 1020
    DBUG_RETURN(1);
  for (i=0 ; i < table_count ; i++)
  {
    fields_for_table[i]= new List_item;
    values_for_table[i]= new List_item;
  }
1021
  if (thd->is_fatal_error)
unknown's avatar
unknown committed
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
    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);
  }
1033
  if (thd->is_fatal_error)
unknown's avatar
unknown committed
1034 1035 1036 1037 1038 1039 1040
    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];
1041 1042
  DBUG_RETURN(thd->is_fatal_error != 0);
}
1043 1044


1045 1046
/*
  Check if table is safe to update on fly
1047

1048 1049 1050 1051 1052 1053
  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
1054

1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
  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.

1068 1069 1070 1071
    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.

1072 1073 1074 1075 1076 1077 1078 1079 1080
  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,
unknown's avatar
unknown committed
1081 1082
                               TABLE_LIST *table_ref, TABLE_LIST *all_tables,
                               List<Item> *fields)
1083 1084
{
  TABLE *table= join_tab->table;
unknown's avatar
unknown committed
1085
  if (unique_table(thd, table_ref, all_tables))
1086 1087 1088 1089 1090
    return 0;
  switch (join_tab->type) {
  case JT_SYSTEM:
  case JT_CONST:
  case JT_EQ_REF:
1091
    return TRUE;				// At most one matching row
1092
  case JT_REF:
1093 1094
  case JT_REF_OR_NULL:
    return !is_key_used(table, join_tab->ref.key, *fields);
1095 1096 1097
  case JT_ALL:
    /* If range search on index */
    if (join_tab->quick)
1098
      return !join_tab->quick->is_keys_used(fields);
1099 1100
    /* If scanning in clustered key */
    if ((table->file->table_flags() & HA_PRIMARY_KEY_IN_READ_INDEX) &&
1101 1102 1103
	table->s->primary_key < MAX_KEY)
      return !is_key_used(table, table->s->primary_key, *fields);
    return TRUE;
1104 1105
  default:
    break;					// Avoid compler warning
1106
  }
1107
  return FALSE;
1108 1109 1110
}


unknown's avatar
unknown committed
1111
/*
1112
  Initialize table for multi table
unknown's avatar
unknown committed
1113

1114 1115 1116 1117
  IMPLEMENTATION
    - Update first table in join on the fly, if possible
    - Create temporary tables to store changed values for all other tables
      that are updated (and main_table if the above doesn't hold).
unknown's avatar
unknown committed
1118 1119 1120
*/

bool
1121 1122
multi_update::initialize_tables(JOIN *join)
{
unknown's avatar
unknown committed
1123 1124 1125 1126 1127 1128 1129
  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();
1130 1131 1132
  table_to_update= 0;

  /* Create a temporary table for keys to all tables, except main table */
unknown's avatar
VIEW  
unknown committed
1133
  for (table_ref= update_tables; table_ref; table_ref= table_ref->next_local)
1134
  {
unknown's avatar
unknown committed
1135
    TABLE *table=table_ref->table;
1136
    uint cnt= table_ref->shared;
unknown's avatar
unknown committed
1137
    Item_field *ifield;
1138 1139
    List<Item> temp_fields= *fields_for_table[cnt];
    ORDER     group;
unknown's avatar
unknown committed
1140

1141 1142
    if (ignore)
      table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
1143 1144
    if (table == main_table)			// First table in join
    {
unknown's avatar
unknown committed
1145 1146
      if (safe_update_on_fly(thd, join->join_tab, table_ref, all_tables,
                             &temp_fields))
1147 1148 1149 1150
      {
	table_to_update= main_table;		// Update table on the fly
	continue;
      }
1151
    }
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162

    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",
unknown's avatar
unknown committed
1163
			table, &my_charset_bin);
1164 1165 1166 1167 1168
    /*
      The field will be converted to varstring when creating tmp table if
      table to be updated was created by mysql 4.1. Deny this.
    */
    offset.can_alter_field_type= 0;
unknown's avatar
unknown committed
1169
    if (!(ifield= new Item_field(((Field *) &offset))))
unknown's avatar
unknown committed
1170
      DBUG_RETURN(1);
unknown's avatar
unknown committed
1171 1172
    ifield->maybe_null= 0;
    if (temp_fields.push_front(ifield))
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
      DBUG_RETURN(1);

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

    tmp_param->quick_group=1;
    tmp_param->field_count=temp_fields.elements;
    tmp_param->group_parts=1;
    tmp_param->group_length= table->file->ref_length;
    if (!(tmp_tables[cnt]=create_tmp_table(thd,
					   tmp_param,
					   temp_fields,
unknown's avatar
unknown committed
1187 1188
					   (ORDER*) &group, 0, 0,
					   TMP_TABLE_ALL_COLUMNS,
1189 1190
					   HA_POS_ERROR,
					   (char *) "")))
1191 1192
      DBUG_RETURN(1);
    tmp_tables[cnt]->file->extra(HA_EXTRA_WRITE_CACHE);
1193
  }
unknown's avatar
unknown committed
1194
  DBUG_RETURN(0);
1195 1196 1197 1198 1199
}


multi_update::~multi_update()
{
unknown's avatar
unknown committed
1200
  TABLE_LIST *table;
unknown's avatar
VIEW  
unknown committed
1201
  for (table= update_tables ; table; table= table->next_local)
1202
  {
1203
    table->table->no_keyread= table->table->no_cache= 0;
1204 1205 1206
    if (ignore)
      table->table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
  }
unknown's avatar
unknown committed
1207

1208 1209
  if (tmp_tables)
  {
1210 1211 1212 1213 1214 1215 1216 1217
    for (uint cnt = 0; cnt < table_count; cnt++)
    {
      if (tmp_tables[cnt])
      {
	free_tmp_table(thd, tmp_tables[cnt]);
	tmp_table_param[cnt].cleanup();
      }
    }
1218
  }
unknown's avatar
unknown committed
1219 1220
  if (copy_field)
    delete [] copy_field;
1221
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;		// Restore this setting
unknown's avatar
unknown committed
1222 1223
  if (!trans_safe)
    thd->options|=OPTION_STATUS_NO_TRANS_UPDATE;
1224 1225 1226
}


unknown's avatar
unknown committed
1227
bool multi_update::send_data(List<Item> &not_used_values)
1228
{
unknown's avatar
unknown committed
1229 1230 1231
  TABLE_LIST *cur_table;
  DBUG_ENTER("multi_update::send_data");

unknown's avatar
VIEW  
unknown committed
1232
  for (cur_table= update_tables; cur_table; cur_table= cur_table->next_local)
1233
  {
unknown's avatar
unknown committed
1234
    TABLE *table= cur_table->table;
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
    /*
      Check if we are using outer join and we didn't find the row
      or if we have already updated this row in the previous call to this
      function.

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

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

    uint offset= cur_table->shared;
    table->file->position(table->record[0]);
1252 1253 1254 1255
    /*
      We can use compare_record() to optimize away updates if
      the table handler is returning all columns
    */
1256
    if (table == table_to_update)
1257
    {
1258 1259 1260
      bool can_compare_record;
      can_compare_record= !(table->file->table_flags() &
                            HA_PARTIAL_COLUMN_READ);
1261
      table->status|= STATUS_UPDATED;
unknown's avatar
unknown committed
1262
      store_record(table,record[1]);
unknown's avatar
unknown committed
1263 1264 1265 1266
      if (fill_record_n_invoke_before_triggers(thd, *fields_for_table[offset],
                                               *values_for_table[offset], 0,
                                               table->triggers,
                                               TRG_EVENT_UPDATE))
unknown's avatar
unknown committed
1267
	DBUG_RETURN(1);
unknown's avatar
unknown committed
1268

1269
      found++;
1270
      if (!can_compare_record || compare_record(table, thd->query_id))
1271
      {
unknown's avatar
unknown committed
1272
	int error;
unknown's avatar
unknown committed
1273
        if ((error= cur_table->view_check_option(thd, ignore)) !=
unknown's avatar
unknown committed
1274 1275 1276 1277 1278 1279 1280 1281
            VIEW_CHECK_OK)
        {
          found--;
          if (error == VIEW_CHECK_SKIP)
            continue;
          else if (error == VIEW_CHECK_ERROR)
            DBUG_RETURN(1);
        }
unknown's avatar
unknown committed
1282
	if (!updated++)
1283
	{
unknown's avatar
unknown committed
1284 1285 1286 1287 1288 1289
	  /*
	    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);
1290
	}
unknown's avatar
unknown committed
1291 1292
	if ((error=table->file->update_row(table->record[1],
					   table->record[0])))
1293
	{
unknown's avatar
unknown committed
1294
	  updated--;
1295
          if (!ignore || error != HA_ERR_FOUND_DUPP_KEY)
1296
	  {
1297 1298 1299 1300 1301 1302
            /*
              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 */
1303 1304 1305
	    table->file->print_error(error,MYF(0));
	    DBUG_RETURN(1);
	  }
1306
	}
unknown's avatar
unknown committed
1307 1308 1309 1310 1311 1312 1313 1314 1315
        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);
        }
1316
      }
unknown's avatar
unknown committed
1317 1318 1319 1320 1321
    }
    else
    {
      int error;
      TABLE *tmp_table= tmp_tables[offset];
unknown's avatar
unknown committed
1322
      fill_record(thd, tmp_table->field+1, *values_for_table[offset], 1);
unknown's avatar
unknown committed
1323 1324 1325 1326
      /* 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 */
1327
      if ((error= tmp_table->file->write_row(tmp_table->record[0])))
1328
      {
1329 1330 1331 1332
        if (error != HA_ERR_FOUND_DUPP_KEY &&
            error != HA_ERR_FOUND_DUPP_UNIQUE &&
            create_myisam_from_heap(thd, tmp_table,
                                         tmp_table_param + offset, error, 1))
1333
	{
unknown's avatar
unknown committed
1334 1335
	  do_update=0;
	  DBUG_RETURN(1);			// Not a table_is_full error
1336 1337
	}
      }
1338 1339
      else
        found++;
1340 1341
    }
  }
unknown's avatar
unknown committed
1342
  DBUG_RETURN(0);
1343 1344
}

unknown's avatar
unknown committed
1345

1346 1347 1348
void multi_update::send_error(uint errcode,const char *err)
{
  /* First send error what ever it is ... */
unknown's avatar
unknown committed
1349
  my_error(errcode, MYF(0), err);
1350 1351 1352 1353

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

1355
  /* Something already updated so we have to invalidate cache */
1356 1357
  query_cache_invalidate3(thd, update_tables, 1);

1358
  /*
unknown's avatar
unknown committed
1359 1360
    If all tables that has been updated are trans safe then just do rollback.
    If not attempt to do remaining updates.
1361
  */
unknown's avatar
unknown committed
1362 1363

  if (trans_safe)
1364
    ha_rollback_stmt(thd);
unknown's avatar
unknown committed
1365 1366 1367 1368 1369
  else if (do_update && table_count > 1)
  {
    /* Add warning here */
    VOID(do_updates(0));
  }
1370 1371 1372
}


unknown's avatar
unknown committed
1373
int multi_update::do_updates(bool from_send_error)
1374
{
unknown's avatar
unknown committed
1375 1376 1377
  TABLE_LIST *cur_table;
  int local_error;
  ha_rows org_updated;
unknown's avatar
unknown committed
1378
  TABLE *table, *tmp_table;
unknown's avatar
unknown committed
1379 1380
  DBUG_ENTER("do_updates");

unknown's avatar
unknown committed
1381
  do_update= 0;					// Don't retry this function
1382
  if (!found)
unknown's avatar
unknown committed
1383
    DBUG_RETURN(0);
unknown's avatar
VIEW  
unknown committed
1384
  for (cur_table= update_tables; cur_table; cur_table= cur_table->next_local)
1385
  {
1386
    byte *ref_pos;
1387
    bool can_compare_record;
unknown's avatar
unknown committed
1388

unknown's avatar
unknown committed
1389
    table = cur_table->table;
1390
    if (table == table_to_update)
unknown's avatar
unknown committed
1391 1392
      continue;					// Already updated
    org_updated= updated;
1393
    tmp_table= tmp_tables[cur_table->shared];
unknown's avatar
unknown committed
1394
    tmp_table->file->extra(HA_EXTRA_CACHE);	// Change to read cache
unknown's avatar
unknown committed
1395
    (void) table->file->ha_rnd_init(0);
unknown's avatar
unknown committed
1396 1397 1398 1399 1400 1401 1402 1403 1404
    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++)
1405
    {
unknown's avatar
unknown committed
1406 1407
      Item_field *item= (Item_field* ) field_it++;
      (copy_field_ptr++)->set(item->field, *field, 0);
1408
    }
unknown's avatar
unknown committed
1409 1410
    copy_field_end=copy_field_ptr;

unknown's avatar
unknown committed
1411
    if ((local_error = tmp_table->file->ha_rnd_init(1)))
unknown's avatar
unknown committed
1412 1413
      goto err;

1414 1415 1416
    can_compare_record= !(table->file->table_flags() &
                          HA_PARTIAL_COLUMN_READ);

unknown's avatar
unknown committed
1417 1418
    ref_pos= (byte*) tmp_table->field[0]->ptr;
    for (;;)
1419
    {
unknown's avatar
unknown committed
1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
      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;
1432
      table->status|= STATUS_UPDATED;
unknown's avatar
unknown committed
1433
      store_record(table,record[1]);
unknown's avatar
unknown committed
1434 1435 1436 1437 1438 1439 1440

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

unknown's avatar
unknown committed
1441 1442 1443 1444 1445
      if (table->triggers &&
          table->triggers->process_triggers(thd, TRG_EVENT_UPDATE,
                                            TRG_ACTION_BEFORE, TRUE))
        goto err2;

1446
      if (!can_compare_record || compare_record(table, thd->query_id))
1447
      {
unknown's avatar
unknown committed
1448 1449 1450
	if ((local_error=table->file->update_row(table->record[1],
						 table->record[0])))
	{
1451
	  if (!ignore || local_error != HA_ERR_FOUND_DUPP_KEY)
unknown's avatar
unknown committed
1452 1453 1454
	    goto err;
	}
	updated++;
unknown's avatar
unknown committed
1455 1456 1457 1458 1459

        if (table->triggers &&
            table->triggers->process_triggers(thd, TRG_EVENT_UPDATE,
                                              TRG_ACTION_AFTER, TRUE))
          goto err2;
1460
      }
unknown's avatar
unknown committed
1461 1462 1463 1464 1465
    }

    if (updated != org_updated)
    {
      if (table->file->has_transactions())
unknown's avatar
unknown committed
1466
	transactional_tables= 1;
1467
      else
unknown's avatar
unknown committed
1468
	trans_safe= 0;				// Can't do safe rollback
1469
    }
unknown's avatar
unknown committed
1470 1471
    (void) table->file->ha_rnd_end();
    (void) tmp_table->file->ha_rnd_end();
1472
  }
unknown's avatar
unknown committed
1473 1474 1475 1476
  DBUG_RETURN(0);

err:
  if (!from_send_error)
unknown's avatar
unknown committed
1477 1478
  {
    thd->fatal_error();
unknown's avatar
unknown committed
1479
    table->file->print_error(local_error,MYF(0));
unknown's avatar
unknown committed
1480
  }
unknown's avatar
unknown committed
1481

unknown's avatar
unknown committed
1482
err2:
unknown's avatar
unknown committed
1483 1484 1485
  (void) table->file->ha_rnd_end();
  (void) tmp_table->file->ha_rnd_end();

unknown's avatar
unknown committed
1486 1487 1488
  if (updated != org_updated)
  {
    if (table->file->has_transactions())
unknown's avatar
unknown committed
1489
      transactional_tables= 1;
unknown's avatar
unknown committed
1490 1491 1492 1493
    else
      trans_safe= 0;
  }
  DBUG_RETURN(1);
1494 1495 1496
}


unknown's avatar
unknown committed
1497 1498
/* out: 1 if error, 0 if success */

1499 1500
bool multi_update::send_eof()
{
unknown's avatar
unknown committed
1501
  char buff[STRING_BUFFER_USUAL_SIZE];
unknown's avatar
unknown committed
1502
  thd->proc_info="updating reference tables";
1503 1504

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

unknown's avatar
unknown committed
1508 1509 1510 1511 1512 1513 1514 1515
  /* We must invalidate the query cache before binlog writing and
  ha_autocommit_... */

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

unknown's avatar
unknown committed
1516 1517
  /*
    Write the SQL statement to the binlog if we updated
unknown's avatar
unknown committed
1518
    rows and we succeeded or if we updated some non
1519
    transactional tables.
unknown's avatar
unknown committed
1520
  */
1521

1522
  if ((local_error == 0) || (updated && !trans_safe))
1523
  {
unknown's avatar
unknown committed
1524 1525
    if (mysql_bin_log.is_open())
    {
1526
      if (local_error == 0)
unknown's avatar
unknown committed
1527
        thd->clear_error();
unknown's avatar
unknown committed
1528
      Query_log_event qinfo(thd, thd->query, thd->query_length,
unknown's avatar
unknown committed
1529
			    transactional_tables, FALSE);
unknown's avatar
unknown committed
1530
      if (mysql_bin_log.write(&qinfo) && trans_safe)
1531
	local_error= 1;				// Rollback update
unknown's avatar
unknown committed
1532
    }
unknown's avatar
unknown committed
1533
    if (!transactional_tables)
unknown's avatar
unknown committed
1534 1535
      thd->options|=OPTION_STATUS_NO_TRANS_UPDATE;
  }
1536

unknown's avatar
unknown committed
1537 1538
  if (transactional_tables)
  {
1539
    if (ha_autocommit_or_rollback(thd, local_error != 0))
unknown's avatar
unknown committed
1540 1541
      local_error=1;
  }
1542

unknown's avatar
unknown committed
1543 1544 1545 1546 1547
  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));
1548
    return TRUE;
1549
  }
unknown's avatar
unknown committed
1550 1551


1552 1553
  sprintf(buff, ER(ER_UPDATE_INFO), (ulong) found, (ulong) updated,
	  (ulong) thd->cuted_fields);
1554 1555
  thd->row_count_func=
    (thd->client_capabilities & CLIENT_FOUND_ROWS) ? found : updated;
1556
  ::send_ok(thd, (ulong) thd->row_count_func,
1557
	    thd->insert_id_used ? thd->last_insert_id : 0L,buff);
1558
  return FALSE;
1559
}