sql_update.cc 43.9 KB
Newer Older
unknown's avatar
unknown committed
1
/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
2

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

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

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


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

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

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

unknown's avatar
unknown committed
30 31
/* Return 0 if row hasn't changed */

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


unknown's avatar
VIEW  
unknown committed
52 53 54 55 56
/*
  check that all fields are real fields

  SYNOPSIS
    check_fields()
unknown's avatar
unknown committed
57
    thd             thread handler
unknown's avatar
VIEW  
unknown committed
58 59 60 61 62 63 64
    items           Items for check

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

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

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


90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
/*
  Process usual UPDATE

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

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

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

unknown's avatar
unknown committed
141
  LINT_INIT(timestamp_query_id);
unknown's avatar
unknown committed
142

143
  for ( ; ; )
144
  {
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
    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);
161
    close_tables_for_reopen(thd, &table_list);
162
  }
unknown's avatar
unknown committed
163

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

unknown's avatar
unknown committed
169
  thd->proc_info="init";
unknown's avatar
unknown committed
170
  table= table_list->table;
unknown's avatar
unknown committed
171 172
  table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);

173
  /* Calculate "table->used_keys" based on the WHERE */
174
  table->used_keys= table->s->keys_in_use;
175
  table->quick_keys.clear_all();
unknown's avatar
unknown committed
176

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

unknown's avatar
unknown committed
184
  old_used_keys= table->used_keys;		// Keys used in WHERE
unknown's avatar
unknown committed
185
  /*
186 187
    Change the query_id for the timestamp column so that we can
    check if this is modified directly
unknown's avatar
unknown committed
188
  */
189 190 191 192 193
  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
194

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

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

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

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

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

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

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

346 347 348 349 350 351 352 353 354 355
      /*
        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
      */
356
      if (used_index == MAX_KEY || (select && select->quick))
357 358 359
        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
360

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

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

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

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

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

unknown's avatar
unknown committed
436 437
  while (!(error=info.read_record(&info)) && !thd->killed)
  {
438
    if (!(select && select->skip_record()))
unknown's avatar
unknown committed
439
    {
unknown's avatar
unknown committed
440
      store_record(table,record[1]);
unknown's avatar
unknown committed
441 442 443
      if (fill_record_n_invoke_before_triggers(thd, fields, values, 0,
                                               table->triggers,
                                               TRG_EVENT_UPDATE))
unknown's avatar
unknown committed
444
	break; /* purecov: inspected */
unknown's avatar
unknown committed
445

unknown's avatar
unknown committed
446
      found++;
447

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

          if (table->triggers &&
              table->triggers->process_triggers(thd, TRG_EVENT_UPDATE,
                                                TRG_ACTION_AFTER, TRUE))
          {
            error= 1;
            break;
          }
unknown's avatar
unknown committed
475
	}
476
 	else if (!ignore || error != HA_ERR_FOUND_DUPP_KEY)
unknown's avatar
unknown committed
477
	{
478 479 480 481 482 483
          /*
            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
484 485 486 487 488
	  table->file->print_error(error,MYF(0));
	  error= 1;
	  break;
	}
      }
489

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

  /*
    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
513
  {
unknown's avatar
unknown committed
514
    query_cache_invalidate3(thd, table_list, 1);
unknown's avatar
unknown committed
515
  }
unknown's avatar
unknown committed
516

517 518 519 520 521 522 523 524 525 526
  /*
    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
527
  {
528 529
    if (mysql_bin_log.is_open())
    {
530
      if (error < 0)
unknown's avatar
unknown committed
531
        thd->clear_error();
532
      Query_log_event qinfo(thd, thd->query, thd->query_length,
unknown's avatar
unknown committed
533
			    transactional_table, FALSE);
534 535
      if (mysql_bin_log.write(&qinfo) && transactional_table)
	error=1;				// Rollback update
536
    }
unknown's avatar
unknown committed
537
    if (!transactional_table)
538
      thd->options|=OPTION_STATUS_NO_TRANS_UPDATE;
unknown's avatar
unknown committed
539
  }
540
  free_underlaid_joins(thd, select_lex);
unknown's avatar
unknown committed
541 542 543 544 545
  if (transactional_table)
  {
    if (ha_autocommit_or_rollback(thd, error >= 0))
      error=1;
  }
unknown's avatar
unknown committed
546

547 548 549 550 551 552
  if (thd->lock)
  {
    mysql_unlock_tables(thd, thd->lock);
    thd->lock=0;
  }

unknown's avatar
unknown committed
553
  if (error < 0)
unknown's avatar
unknown committed
554
  {
unknown's avatar
unknown committed
555
    char buff[STRING_BUFFER_USUAL_SIZE];
556 557
    sprintf(buff, ER(ER_UPDATE_INFO), (ulong) found, (ulong) updated,
	    (ulong) thd->cuted_fields);
558 559
    thd->row_count_func=
      (thd->client_capabilities & CLIENT_FOUND_ROWS) ? found : updated;
560
    send_ok(thd, (ulong) thd->row_count_func,
unknown's avatar
unknown committed
561 562 563
	    thd->insert_id_used ? thd->insert_id() : 0L,buff);
    DBUG_PRINT("info",("%d records updated",updated));
  }
564
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;		/* calc cuted fields */
565
  thd->abort_on_warning= 0;
unknown's avatar
unknown committed
566
  free_io_cache(table);
unknown's avatar
merge  
unknown committed
567
  DBUG_RETURN((error >= 0 || thd->net.report_error) ? 1 : 0);
568 569 570

err:
  delete select;
571
  free_underlaid_joins(thd, select_lex);
572 573 574 575 576
  if (table->key_read)
  {
    table->key_read=0;
    table->file->extra(HA_EXTRA_NO_KEYREAD);
  }
unknown's avatar
unknown committed
577
  thd->abort_on_warning= 0;
unknown's avatar
merge  
unknown committed
578
  DBUG_RETURN(1);
unknown's avatar
unknown committed
579
}
580

unknown's avatar
unknown committed
581 582 583 584 585 586
/*
  Prepare items in UPDATE statement

  SYNOPSIS
    mysql_prepare_update()
    thd			- thread handler
unknown's avatar
VIEW  
unknown committed
587
    table_list		- global/local table list
unknown's avatar
unknown committed
588 589 590 591 592
    conds		- conditions
    order_num		- number of ORDER BY list entries
    order		- ORDER BY clause list

  RETURN VALUE
unknown's avatar
unknown committed
593 594
    FALSE OK
    TRUE  error
unknown's avatar
unknown committed
595
*/
unknown's avatar
unknown committed
596
bool mysql_prepare_update(THD *thd, TABLE_LIST *table_list,
unknown's avatar
unknown committed
597 598 599 600 601
			 Item **conds, uint order_num, ORDER *order)
{
  TABLE *table= table_list->table;
  TABLE_LIST tables;
  List<Item> all_fields;
602
  SELECT_LEX *select_lex= &thd->lex->select_lex;
unknown's avatar
unknown committed
603 604 605
  DBUG_ENTER("mysql_prepare_update");

#ifndef NO_EMBEDDED_ACCESS_CHECKS
unknown's avatar
VIEW  
unknown committed
606 607
  table_list->grant.want_privilege= table->grant.want_privilege= 
    (SELECT_ACL & ~table->grant.privilege);
608
  table_list->register_want_access(SELECT_ACL);
unknown's avatar
unknown committed
609 610 611 612 613
#endif

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

unknown's avatar
unknown committed
616
  if (setup_tables(thd, &select_lex->context, &select_lex->top_join_list,
617 618
                   table_list, conds, &select_lex->leaf_tables,
                   FALSE) ||
619
      setup_conds(thd, table_list, select_lex->leaf_tables, conds) ||
620 621
      select_lex->setup_ref_array(thd, order_num) ||
      setup_order(thd, select_lex->ref_pointer_array,
unknown's avatar
VIEW  
unknown committed
622
		  table_list, all_fields, all_fields, order) ||
623
      setup_ftfuncs(select_lex))
unknown's avatar
unknown committed
624
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
625 626 627

  /* Check that we are not using table that we are updating in a sub select */
  {
628
    TABLE_LIST *duplicate;
629
    if ((duplicate= unique_table(thd, table_list, table_list->next_global)))
630 631 632 633 634
    {
      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
635
  }
unknown's avatar
VIEW  
unknown committed
636
  select_lex->fix_prepare_information(thd, conds);
unknown's avatar
unknown committed
637
  DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
638 639
}

unknown's avatar
unknown committed
640

641
/***************************************************************************
642
  Update multiple tables from join 
643 644
***************************************************************************/

unknown's avatar
unknown committed
645
/*
646
  Get table map for list of Item_field
unknown's avatar
unknown committed
647 648
*/

649 650 651 652 653 654 655 656 657 658 659 660 661
static table_map get_table_map(List<Item> *items)
{
  List_iterator_fast<Item> item_it(*items);
  Item_field *item;
  table_map map= 0;

  while ((item= (Item_field *) item_it++)) 
    map|= item->used_tables();
  DBUG_PRINT("info",("table_map: 0x%08x", map));
  return map;
}


unknown's avatar
VIEW  
unknown committed
662 663
/*
  make update specific preparation and checks after opening tables
unknown's avatar
unknown committed
664

unknown's avatar
VIEW  
unknown committed
665 666 667
  SYNOPSIS
    mysql_multi_update_prepare()
    thd         thread handler
unknown's avatar
unknown committed
668

unknown's avatar
VIEW  
unknown committed
669
  RETURN
unknown's avatar
unknown committed
670 671
    FALSE OK
    TRUE  Error
unknown's avatar
VIEW  
unknown committed
672
*/
673

unknown's avatar
unknown committed
674
bool mysql_multi_update_prepare(THD *thd)
unknown's avatar
VIEW  
unknown committed
675 676 677
{
  LEX *lex= thd->lex;
  TABLE_LIST *table_list= lex->query_tables;
unknown's avatar
unknown committed
678
  TABLE_LIST *tl, *leaves;
unknown's avatar
VIEW  
unknown committed
679
  List<Item> *fields= &lex->select_lex.item_list;
unknown's avatar
unknown committed
680
  table_map tables_for_update;
unknown's avatar
unknown committed
681
  bool update_view= 0;
unknown's avatar
unknown committed
682 683 684 685 686 687
  /*
    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
688
  const bool using_lock_tables= thd->locked_tables != 0;
unknown's avatar
unknown committed
689
  bool original_multiupdate= (thd->lex->sql_command == SQLCOM_UPDATE_MULTI);
690
  bool need_reopen= FALSE;
unknown's avatar
unknown committed
691 692
  DBUG_ENTER("mysql_multi_update_prepare");

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

696 697
reopen_tables:

unknown's avatar
unknown committed
698
  /* open tables and create derived ones, but do not lock and fill them */
699
  if (((original_multiupdate || need_reopen) &&
700
       open_tables(thd, &table_list, &table_count, 0)) ||
unknown's avatar
unknown committed
701
      mysql_handle_derived(lex, &mysql_derived_prepare))
702
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
703 704 705 706 707
  /*
    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
708

709
  if (setup_tables(thd, &lex->select_lex.context,
unknown's avatar
unknown committed
710
                   &lex->select_lex.top_join_list,
711
                   table_list, &lex->select_lex.where,
712
                   &lex->select_lex.leaf_tables, FALSE))
unknown's avatar
merge  
unknown committed
713
    DBUG_RETURN(TRUE);
714

715
  if (setup_fields_with_no_wrap(thd, 0, *fields, 1, 0, 0))
unknown's avatar
unknown committed
716
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
717 718 719 720 721 722 723 724 725 726 727

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

  if (update_view && check_fields(thd, *fields))
728
  {
unknown's avatar
unknown committed
729
    DBUG_RETURN(TRUE);
unknown's avatar
VIEW  
unknown committed
730 731
  }

unknown's avatar
unknown committed
732
  tables_for_update= get_table_map(fields);
unknown's avatar
unknown committed
733 734

  /*
unknown's avatar
unknown committed
735
    Setup timestamp handling and locking mode
unknown's avatar
unknown committed
736
  */
737
  leaves= lex->select_lex.leaf_tables;
738
  for (tl= leaves; tl; tl= tl->next_leaf)
739
  {
unknown's avatar
unknown committed
740
    TABLE *table= tl->table;
unknown's avatar
unknown committed
741
    /* Only set timestamp column if this is not modified */
742 743
    if (table->timestamp_field &&
        table->timestamp_field->query_id == thd->query_id)
unknown's avatar
unknown committed
744
      table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
unknown's avatar
VIEW  
unknown committed
745

unknown's avatar
unknown committed
746 747
    /* if table will be updated then check that it is unique */
    if (table->map & tables_for_update)
748
    {
unknown's avatar
unknown committed
749
      if (!tl->updatable || check_key_in_view(thd, tl))
unknown's avatar
unknown committed
750
      {
751
        my_error(ER_NON_UPDATABLE_TABLE, MYF(0), tl->alias, "UPDATE");
unknown's avatar
merge  
unknown committed
752
        DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
753
      }
unknown's avatar
unknown committed
754 755

      DBUG_PRINT("info",("setting table `%s` for update", tl->alias));
756 757 758 759
      /*
        If table will be updated we should not downgrade lock for it and
        leave it as is.
      */
unknown's avatar
unknown committed
760
    }
unknown's avatar
unknown committed
761 762 763
    else
    {
      DBUG_PRINT("info",("setting table `%s` for read-only", tl->alias));
unknown's avatar
unknown committed
764 765 766 767 768 769
      /*
        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
770
      tl->updating= 0;
771 772 773
      /* Update TABLE::lock_type accordingly. */
      if (!tl->placeholder() && !tl->schema_table && !using_lock_tables)
        tl->table->reginfo.lock_type= tl->lock_type;
774
    }
unknown's avatar
unknown committed
775
  }
unknown's avatar
unknown committed
776
  for (tl= table_list; tl; tl= tl->next_local)
unknown's avatar
unknown committed
777
  {
unknown's avatar
unknown committed
778
    /* Check access privileges for table */
unknown's avatar
unknown committed
779
    if (!tl->derived)
780
    {
unknown's avatar
unknown committed
781 782
      uint want_privilege= tl->updating ? UPDATE_ACL : SELECT_ACL;
      if (check_access(thd, want_privilege,
783 784
                       tl->db, &tl->grant.privilege, 0, 0, 
                       test(tl->schema_table)) ||
unknown's avatar
unknown committed
785
          (grant_option && check_grant(thd, want_privilege, tl, 0, 1, 0)))
unknown's avatar
unknown committed
786
        DBUG_RETURN(TRUE);
787
    }
788
  }
unknown's avatar
unknown committed
789

unknown's avatar
unknown committed
790 791 792
  /* check single table update for view compound from several tables */
  for (tl= table_list; tl; tl= tl->next_local)
  {
unknown's avatar
unknown committed
793
    if (tl->effective_algorithm == VIEW_ALGORITHM_MERGE)
unknown's avatar
unknown committed
794 795
    {
      TABLE_LIST *for_update= 0;
unknown's avatar
unknown committed
796
      if (tl->check_single_table(&for_update, tables_for_update, tl))
unknown's avatar
unknown committed
797 798 799 800 801 802 803 804
      {
	my_error(ER_VIEW_MULTIUPDATE, MYF(0),
		 tl->view_db.str, tl->view_name.str);
	DBUG_RETURN(-1);
      }
    }
  }

unknown's avatar
unknown committed
805
  /* now lock and fill tables */
806
  if (lock_tables(thd, table_list, table_count, &need_reopen))
unknown's avatar
unknown committed
807
  {
808 809 810
    if (!need_reopen)
      DBUG_RETURN(TRUE);

unknown's avatar
unknown committed
811
    /*
812 813 814 815
      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
816 817 818
    */
    List_iterator_fast<Item> it(*fields);
    Item *item;
unknown's avatar
unknown committed
819
    while ((item= it++))
unknown's avatar
unknown committed
820 821
      item->cleanup();

unknown's avatar
unknown committed
822
    /* We have to cleanup translation tables of views. */
unknown's avatar
unknown committed
823 824 825
    for (TABLE_LIST *tbl= table_list; tbl; tbl= tbl->next_global)
      tbl->cleanup_items();

826
    close_tables_for_reopen(thd, &table_list);
827
    goto reopen_tables;
unknown's avatar
unknown committed
828
  }
unknown's avatar
unknown committed
829

830 831 832 833 834
  /*
    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
835 836 837 838 839
  /* 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;
840
    if (!(tlist= tl->top_table())->derived)
unknown's avatar
unknown committed
841 842 843 844 845 846 847
    {
      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));
848
    if (tl->lock_type != TL_READ &&
849
        tl->lock_type != TL_READ_NO_INSERT)
850
    {
851
      TABLE_LIST *duplicate;
852
      if ((duplicate= unique_table(thd, tl, table_list)))
853 854 855 856
      {
        update_non_unique_table_error(table_list, "UPDATE", duplicate);
        DBUG_RETURN(TRUE);
      }
857
    }
unknown's avatar
unknown committed
858 859
  }

unknown's avatar
unknown committed
860 861
  if (thd->fill_derived_tables() &&
      mysql_handle_derived(lex, &mysql_derived_filling))
862
    DBUG_RETURN(TRUE);
863

unknown's avatar
merge  
unknown committed
864
  DBUG_RETURN (FALSE);
unknown's avatar
VIEW  
unknown committed
865 866 867
}


unknown's avatar
unknown committed
868 869 870
/*
  Setup multi-update handling and call SELECT to do the join
*/
871

unknown's avatar
unknown committed
872 873 874 875 876
bool mysql_multi_update(THD *thd,
                        TABLE_LIST *table_list,
                        List<Item> *fields,
                        List<Item> *values,
                        COND *conds,
877
                        ulonglong options,
878
                        enum enum_duplicates handle_duplicates, bool ignore,
unknown's avatar
unknown committed
879
                        SELECT_LEX_UNIT *unit, SELECT_LEX *select_lex)
unknown's avatar
VIEW  
unknown committed
880 881 882 883
{
  multi_update *result;
  DBUG_ENTER("mysql_multi_update");

884
  if (!(result= new multi_update(table_list,
885 886
				 thd->lex->select_lex.leaf_tables,
				 fields, values,
887
				 handle_duplicates, ignore)))
unknown's avatar
unknown committed
888
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
889

unknown's avatar
unknown committed
890 891 892 893 894
  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
895
  List<Item> total_list;
896 897 898 899 900 901 902 903
  (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
904
  delete result;
unknown's avatar
unknown committed
905
  thd->abort_on_warning= 0;
906
  DBUG_RETURN(FALSE);
907 908
}

unknown's avatar
unknown committed
909

910
multi_update::multi_update(TABLE_LIST *table_list,
911
			   TABLE_LIST *leaves_list,
unknown's avatar
unknown committed
912
			   List<Item> *field_list, List<Item> *value_list,
unknown's avatar
unknown committed
913 914
			   enum enum_duplicates handle_duplicates_arg,
                           bool ignore_arg)
915
  :all_tables(table_list), leaves(leaves_list), update_tables(0),
916
   tmp_tables(0), updated(0), found(0), fields(field_list),
917 918
   values(value_list), table_count(0), copy_field(0),
   handle_duplicates(handle_duplicates_arg), do_update(1), trans_safe(0),
919
   transactional_tables(1), ignore(ignore_arg)
unknown's avatar
unknown committed
920 921 922 923 924 925 926
{}


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

927 928
int multi_update::prepare(List<Item> &not_used_values,
			  SELECT_LEX_UNIT *lex_unit)
929
{
unknown's avatar
unknown committed
930 931
  TABLE_LIST *table_ref;
  SQL_LIST update;
932
  table_map tables_to_update;
unknown's avatar
unknown committed
933 934 935 936
  Item_field *item;
  List_iterator_fast<Item> field_it(*fields);
  List_iterator_fast<Item> value_it(*values);
  uint i, max_fields;
937
  DBUG_ENTER("multi_update::prepare");
unknown's avatar
unknown committed
938

939
  thd->count_cuted_fields= CHECK_FIELD_WARN;
940
  thd->cuted_fields=0L;
unknown's avatar
unknown committed
941 942
  thd->proc_info="updating main table";

943
  tables_to_update= get_table_map(fields);
944

unknown's avatar
unknown committed
945
  if (!tables_to_update)
946
  {
unknown's avatar
unknown committed
947
    my_message(ER_NO_TABLES_USED, ER(ER_NO_TABLES_USED), MYF(0));
unknown's avatar
unknown committed
948
    DBUG_RETURN(1);
949
  }
unknown's avatar
unknown committed
950

951
  /*
unknown's avatar
unknown committed
952 953
    We have to check values after setup_tables to get used_keys right in
    reference tables
954
  */
955

956
  if (setup_fields(thd, 0, *values, 1, 0, 0))
957 958
    DBUG_RETURN(1);

959
  /*
unknown's avatar
unknown committed
960 961 962
    Save tables beeing updated in update_tables
    update_table->shared is position for table
    Don't use key read on tables that are updated
963
  */
unknown's avatar
unknown committed
964 965

  update.empty();
966
  for (table_ref= leaves; table_ref; table_ref= table_ref->next_leaf)
967
  {
968
    /* TODO: add support of view of join support */
unknown's avatar
unknown committed
969 970
    TABLE *table=table_ref->table;
    if (tables_to_update & table->map)
971
    {
unknown's avatar
unknown committed
972 973 974
      TABLE_LIST *tl= (TABLE_LIST*) thd->memdup((char*) table_ref,
						sizeof(*tl));
      if (!tl)
975
	DBUG_RETURN(1);
unknown's avatar
VIEW  
unknown committed
976
      update.link_in_list((byte*) tl, (byte**) &tl->next_local);
unknown's avatar
unknown committed
977 978
      tl->shared= table_count++;
      table->no_keyread=1;
979
      table->used_keys.clear_all();
unknown's avatar
unknown committed
980
      table->pos_in_table_list= tl;
981 982
    }
  }
unknown's avatar
unknown committed
983 984


unknown's avatar
unknown committed
985 986 987
  table_count=  update.elements;
  update_tables= (TABLE_LIST*) update.first;

988
  tmp_tables = (TABLE**) thd->calloc(sizeof(TABLE *) * table_count);
unknown's avatar
unknown committed
989 990 991 992 993 994
  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);
995
  if (thd->is_fatal_error)
unknown's avatar
unknown committed
996 997 998 999 1000 1001
    DBUG_RETURN(1);
  for (i=0 ; i < table_count ; i++)
  {
    fields_for_table[i]= new List_item;
    values_for_table[i]= new List_item;
  }
1002
  if (thd->is_fatal_error)
unknown's avatar
unknown committed
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
    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);
  }
1014
  if (thd->is_fatal_error)
unknown's avatar
unknown committed
1015 1016 1017 1018 1019 1020 1021
    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];
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034

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

    The problem is that for queries like

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

    the row buffer may contain things that doesn't match what is on disk
    which will cause an error when reading a row.
    (This issue is mostly relevent for MyISAM tables)
  */
1035
  for (table_ref= leaves;  table_ref; table_ref= table_ref->next_leaf)
1036 1037
  {
    TABLE *table=table_ref->table;
1038
    if (!(tables_to_update & table->map) &&
1039
        unique_table(thd, table_ref, update_tables))
1040 1041
      table->no_cache= 1;			// Disable row cache
  }
1042
  DBUG_RETURN(thd->is_fatal_error != 0);
1043 1044 1045
}


unknown's avatar
unknown committed
1046
/*
1047
  Initialize table for multi table
unknown's avatar
unknown committed
1048

1049 1050 1051 1052
  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
1053 1054 1055
*/

bool
1056 1057
multi_update::initialize_tables(JOIN *join)
{
unknown's avatar
unknown committed
1058 1059 1060 1061 1062 1063 1064
  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();
1065 1066 1067
  table_to_update= 0;

  /* Create a temporary table for keys to all tables, except main table */
unknown's avatar
VIEW  
unknown committed
1068
  for (table_ref= update_tables; table_ref; table_ref= table_ref->next_local)
1069
  {
unknown's avatar
unknown committed
1070
    TABLE *table=table_ref->table;
1071
    uint cnt= table_ref->shared;
unknown's avatar
unknown committed
1072
    Item_field *ifield;
1073 1074
    List<Item> temp_fields= *fields_for_table[cnt];
    ORDER     group;
unknown's avatar
unknown committed
1075

1076 1077 1078 1079 1080 1081 1082
    if (table == main_table)			// First table in join
    {
      if (safe_update_on_fly(join->join_tab, &temp_fields))
      {
	table_to_update= main_table;		// Update table on the fly
	continue;
      }
1083
    }
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094

    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
1095
			table, &my_charset_bin);
1096 1097 1098 1099 1100
    /*
      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
1101
    if (!(ifield= new Item_field(((Field *) &offset))))
unknown's avatar
unknown committed
1102
      DBUG_RETURN(1);
unknown's avatar
unknown committed
1103 1104
    ifield->maybe_null= 0;
    if (temp_fields.push_front(ifield))
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
      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
1119 1120
					   (ORDER*) &group, 0, 0,
					   TMP_TABLE_ALL_COLUMNS,
1121 1122
					   HA_POS_ERROR,
					   (char *) "")))
1123 1124
      DBUG_RETURN(1);
    tmp_tables[cnt]->file->extra(HA_EXTRA_WRITE_CACHE);
1125
  }
unknown's avatar
unknown committed
1126
  DBUG_RETURN(0);
1127 1128
}

1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
/*
  Check if table is safe to update on fly

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

  NOTES
    We can update the first table in join on the fly if we know that
unknown's avatar
unknown committed
1139 1140
    a row in this table will never be read twice. This is true under
    the following conditions:
1141 1142 1143 1144 1145 1146 1147

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

unknown's avatar
unknown committed
1148 1149 1150 1151
    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.

1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
  WARNING
    This code is a bit dependent of how make_join_readinfo() works.

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

static bool safe_update_on_fly(JOIN_TAB *join_tab, List<Item> *fields)
{
  TABLE *table= join_tab->table;
  switch (join_tab->type) {
  case JT_SYSTEM:
  case JT_CONST:
  case JT_EQ_REF:
1167
    return TRUE;				// At most one matching row
1168
  case JT_REF:
unknown's avatar
unknown committed
1169
  case JT_REF_OR_NULL:
unknown's avatar
unknown committed
1170 1171 1172
    return !check_if_key_used(table, join_tab->ref.key, *fields) &&
           !(table->triggers &&
             table->triggers->has_before_update_triggers());
1173 1174 1175
  case JT_ALL:
    /* If range search on index */
    if (join_tab->quick)
unknown's avatar
unknown committed
1176 1177 1178
      return !join_tab->quick->check_if_keys_used(fields) &&
             !(table->triggers &&
               table->triggers->has_before_update_triggers());
1179 1180
    /* If scanning in clustered key */
    if ((table->file->table_flags() & HA_PRIMARY_KEY_IN_READ_INDEX) &&
1181
	table->s->primary_key < MAX_KEY)
unknown's avatar
unknown committed
1182 1183 1184
      return !check_if_key_used(table, table->s->primary_key, *fields) &&
             !(table->triggers &&
               table->triggers->has_before_update_triggers());
1185
    return TRUE;
1186 1187 1188
  default:
    break;					// Avoid compler warning
  }
1189
  return FALSE;
1190 1191
}

1192 1193 1194

multi_update::~multi_update()
{
unknown's avatar
unknown committed
1195
  TABLE_LIST *table;
unknown's avatar
VIEW  
unknown committed
1196
  for (table= update_tables ; table; table= table->next_local)
1197
    table->table->no_keyread= table->table->no_cache= 0;
unknown's avatar
unknown committed
1198

1199 1200
  if (tmp_tables)
  {
1201 1202 1203 1204 1205 1206 1207 1208
    for (uint cnt = 0; cnt < table_count; cnt++)
    {
      if (tmp_tables[cnt])
      {
	free_tmp_table(thd, tmp_tables[cnt]);
	tmp_table_param[cnt].cleanup();
      }
    }
1209
  }
unknown's avatar
unknown committed
1210 1211
  if (copy_field)
    delete [] copy_field;
1212
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;		// Restore this setting
unknown's avatar
unknown committed
1213 1214
  if (!trans_safe)
    thd->options|=OPTION_STATUS_NO_TRANS_UPDATE;
1215 1216 1217
}


unknown's avatar
unknown committed
1218
bool multi_update::send_data(List<Item> &not_used_values)
1219
{
unknown's avatar
unknown committed
1220 1221 1222
  TABLE_LIST *cur_table;
  DBUG_ENTER("multi_update::send_data");

unknown's avatar
VIEW  
unknown committed
1223
  for (cur_table= update_tables; cur_table; cur_table= cur_table->next_local)
1224
  {
unknown's avatar
unknown committed
1225
    TABLE *table= cur_table->table;
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
    /*
      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
1238 1239 1240 1241 1242
    if (table->status & (STATUS_NULL_ROW | STATUS_UPDATED))
      continue;

    uint offset= cur_table->shared;
    table->file->position(table->record[0]);
1243
    if (table == table_to_update)
1244 1245
    {
      table->status|= STATUS_UPDATED;
unknown's avatar
unknown committed
1246
      store_record(table,record[1]);
unknown's avatar
unknown committed
1247 1248 1249 1250
      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
1251
	DBUG_RETURN(1);
unknown's avatar
unknown committed
1252

1253
      found++;
unknown's avatar
unknown committed
1254
      if (compare_record(table, thd->query_id))
1255
      {
unknown's avatar
unknown committed
1256
	int error;
unknown's avatar
unknown committed
1257
        if ((error= cur_table->view_check_option(thd, ignore)) !=
unknown's avatar
unknown committed
1258 1259 1260 1261 1262 1263 1264 1265
            VIEW_CHECK_OK)
        {
          found--;
          if (error == VIEW_CHECK_SKIP)
            continue;
          else if (error == VIEW_CHECK_ERROR)
            DBUG_RETURN(1);
        }
unknown's avatar
unknown committed
1266
	if (!updated++)
1267
	{
unknown's avatar
unknown committed
1268 1269 1270 1271 1272 1273
	  /*
	    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);
1274
	}
unknown's avatar
unknown committed
1275 1276
	if ((error=table->file->update_row(table->record[1],
					   table->record[0])))
1277
	{
unknown's avatar
unknown committed
1278
	  updated--;
1279
          if (!ignore || error != HA_ERR_FOUND_DUPP_KEY)
1280
	  {
1281 1282 1283 1284 1285 1286
            /*
              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 */
1287 1288 1289
	    table->file->print_error(error,MYF(0));
	    DBUG_RETURN(1);
	  }
1290
	}
unknown's avatar
unknown committed
1291 1292 1293 1294 1295 1296 1297 1298 1299
        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);
        }
1300
      }
unknown's avatar
unknown committed
1301 1302 1303 1304 1305
    }
    else
    {
      int error;
      TABLE *tmp_table= tmp_tables[offset];
unknown's avatar
unknown committed
1306
      fill_record(thd, tmp_table->field+1, *values_for_table[offset], 1);
unknown's avatar
unknown committed
1307 1308 1309 1310
      /* 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 */
1311
      if ((error= tmp_table->file->write_row(tmp_table->record[0])))
1312
      {
1313 1314 1315 1316
        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))
1317
	{
unknown's avatar
unknown committed
1318 1319
	  do_update=0;
	  DBUG_RETURN(1);			// Not a table_is_full error
1320 1321
	}
      }
1322 1323
      else
        found++;
1324 1325
    }
  }
unknown's avatar
unknown committed
1326
  DBUG_RETURN(0);
1327 1328
}

unknown's avatar
unknown committed
1329

1330 1331 1332
void multi_update::send_error(uint errcode,const char *err)
{
  /* First send error what ever it is ... */
unknown's avatar
unknown committed
1333
  my_error(errcode, MYF(0), err);
1334 1335 1336 1337

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

1339
  /* Something already updated so we have to invalidate cache */
1340 1341
  query_cache_invalidate3(thd, update_tables, 1);

1342
  /*
unknown's avatar
unknown committed
1343 1344
    If all tables that has been updated are trans safe then just do rollback.
    If not attempt to do remaining updates.
1345
  */
unknown's avatar
unknown committed
1346 1347

  if (trans_safe)
1348
    ha_rollback_stmt(thd);
unknown's avatar
unknown committed
1349 1350 1351 1352 1353
  else if (do_update && table_count > 1)
  {
    /* Add warning here */
    VOID(do_updates(0));
  }
1354 1355 1356
}


unknown's avatar
unknown committed
1357
int multi_update::do_updates(bool from_send_error)
1358
{
unknown's avatar
unknown committed
1359 1360 1361
  TABLE_LIST *cur_table;
  int local_error;
  ha_rows org_updated;
unknown's avatar
unknown committed
1362
  TABLE *table, *tmp_table;
unknown's avatar
unknown committed
1363 1364
  DBUG_ENTER("do_updates");

unknown's avatar
unknown committed
1365
  do_update= 0;					// Don't retry this function
1366
  if (!found)
unknown's avatar
unknown committed
1367
    DBUG_RETURN(0);
unknown's avatar
VIEW  
unknown committed
1368
  for (cur_table= update_tables; cur_table; cur_table= cur_table->next_local)
1369
  {
1370
    byte *ref_pos;
unknown's avatar
unknown committed
1371

unknown's avatar
unknown committed
1372
    table = cur_table->table;
1373
    if (table == table_to_update)
unknown's avatar
unknown committed
1374 1375
      continue;					// Already updated
    org_updated= updated;
1376
    tmp_table= tmp_tables[cur_table->shared];
unknown's avatar
unknown committed
1377
    tmp_table->file->extra(HA_EXTRA_CACHE);	// Change to read cache
unknown's avatar
unknown committed
1378
    (void) table->file->ha_rnd_init(0);
unknown's avatar
unknown committed
1379 1380 1381 1382 1383 1384 1385 1386 1387
    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++)
1388
    {
unknown's avatar
unknown committed
1389 1390
      Item_field *item= (Item_field* ) field_it++;
      (copy_field_ptr++)->set(item->field, *field, 0);
1391
    }
unknown's avatar
unknown committed
1392 1393
    copy_field_end=copy_field_ptr;

unknown's avatar
unknown committed
1394
    if ((local_error = tmp_table->file->ha_rnd_init(1)))
unknown's avatar
unknown committed
1395 1396 1397 1398
      goto err;

    ref_pos= (byte*) tmp_table->field[0]->ptr;
    for (;;)
1399
    {
unknown's avatar
unknown committed
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
      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;
1412
      table->status|= STATUS_UPDATED;
unknown's avatar
unknown committed
1413
      store_record(table,record[1]);
unknown's avatar
unknown committed
1414 1415 1416 1417 1418 1419 1420

      /* 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
1421 1422 1423 1424 1425
      if (table->triggers &&
          table->triggers->process_triggers(thd, TRG_EVENT_UPDATE,
                                            TRG_ACTION_BEFORE, TRUE))
        goto err2;

unknown's avatar
unknown committed
1426
      if (compare_record(table, thd->query_id))
1427
      {
unknown's avatar
unknown committed
1428 1429 1430
	if ((local_error=table->file->update_row(table->record[1],
						 table->record[0])))
	{
1431
	  if (!ignore || local_error != HA_ERR_FOUND_DUPP_KEY)
unknown's avatar
unknown committed
1432 1433 1434
	    goto err;
	}
	updated++;
unknown's avatar
unknown committed
1435 1436 1437 1438 1439

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

    if (updated != org_updated)
    {
      if (table->file->has_transactions())
unknown's avatar
unknown committed
1446
	transactional_tables= 1;
1447
      else
unknown's avatar
unknown committed
1448
	trans_safe= 0;				// Can't do safe rollback
1449
    }
unknown's avatar
unknown committed
1450 1451
    (void) table->file->ha_rnd_end();
    (void) tmp_table->file->ha_rnd_end();
1452
  }
unknown's avatar
unknown committed
1453 1454 1455 1456
  DBUG_RETURN(0);

err:
  if (!from_send_error)
unknown's avatar
unknown committed
1457 1458
  {
    thd->fatal_error();
unknown's avatar
unknown committed
1459
    table->file->print_error(local_error,MYF(0));
unknown's avatar
unknown committed
1460
  }
unknown's avatar
unknown committed
1461

unknown's avatar
unknown committed
1462
err2:
unknown's avatar
unknown committed
1463 1464 1465
  (void) table->file->ha_rnd_end();
  (void) tmp_table->file->ha_rnd_end();

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


unknown's avatar
unknown committed
1477 1478
/* out: 1 if error, 0 if success */

1479 1480
bool multi_update::send_eof()
{
unknown's avatar
unknown committed
1481
  char buff[STRING_BUFFER_USUAL_SIZE];
unknown's avatar
unknown committed
1482
  thd->proc_info="updating reference tables";
1483 1484

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

unknown's avatar
unknown committed
1488 1489 1490 1491 1492 1493 1494 1495
  /* 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
1496 1497
  /*
    Write the SQL statement to the binlog if we updated
unknown's avatar
unknown committed
1498
    rows and we succeeded or if we updated some non
1499
    transactional tables.
unknown's avatar
unknown committed
1500
  */
1501

1502
  if ((local_error == 0) || (updated && !trans_safe))
1503
  {
unknown's avatar
unknown committed
1504 1505
    if (mysql_bin_log.is_open())
    {
1506
      if (local_error == 0)
unknown's avatar
unknown committed
1507
        thd->clear_error();
unknown's avatar
unknown committed
1508
      Query_log_event qinfo(thd, thd->query, thd->query_length,
unknown's avatar
unknown committed
1509
			    transactional_tables, FALSE);
unknown's avatar
unknown committed
1510
      if (mysql_bin_log.write(&qinfo) && trans_safe)
1511
	local_error= 1;				// Rollback update
unknown's avatar
unknown committed
1512
    }
unknown's avatar
unknown committed
1513
    if (!transactional_tables)
unknown's avatar
unknown committed
1514 1515
      thd->options|=OPTION_STATUS_NO_TRANS_UPDATE;
  }
1516

unknown's avatar
unknown committed
1517 1518
  if (transactional_tables)
  {
1519
    if (ha_autocommit_or_rollback(thd, local_error != 0))
unknown's avatar
unknown committed
1520 1521
      local_error=1;
  }
1522

unknown's avatar
unknown committed
1523 1524 1525 1526 1527
  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));
1528
    return TRUE;
1529
  }
unknown's avatar
unknown committed
1530 1531


1532 1533
  sprintf(buff, ER(ER_UPDATE_INFO), (ulong) found, (ulong) updated,
	  (ulong) thd->cuted_fields);
1534 1535
  thd->row_count_func=
    (thd->client_capabilities & CLIENT_FOUND_ROWS) ? found : updated;
1536
  ::send_ok(thd, (ulong) thd->row_count_func,
unknown's avatar
unknown committed
1537
	    thd->insert_id_used ? thd->insert_id() : 0L,buff);
1538
  return FALSE;
1539
}