MySQL 5.6.14 Source Code Document
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
sql_delete.cc
1 /* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
2 
3  This program is free software; you can redistribute it and/or modify
4  it under the terms of the GNU General Public License as published by
5  the Free Software Foundation; version 2 of the License.
6 
7  This program is distributed in the hope that it will be useful,
8  but WITHOUT ANY WARRANTY; without even the implied warranty of
9  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  GNU General Public License for more details.
11 
12  You should have received a copy of the GNU General Public License
13  along with this program; if not, write to the Free Software
14  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
15 
16 /*
17  Delete of records tables.
18 
19  Multi-table deletes were introduced by Monty and Sinisa
20 */
21 
22 #include "sql_priv.h"
23 #include "unireg.h"
24 #include "sql_delete.h"
25 #include "sql_cache.h" // query_cache_*
26 #include "sql_base.h" // open_temprary_table
27 #include "sql_table.h" // build_table_filename
28 #include "sql_view.h" // check_key_in_view, mysql_frm_type
29 #include "sql_acl.h" // *_ACL
30 #include "filesort.h" // filesort
31 #include "sql_select.h"
32 #include "opt_trace.h" // Opt_trace_object
33 #include "opt_explain.h"
34 #include "records.h" // init_read_record,
35  // end_read_record
36 #include "sql_optimizer.h" // remove_eq_conds
37 #include "sql_resolver.h" // setup_order, fix_inner_refs
38 
47 bool mysql_delete(THD *thd, TABLE_LIST *table_list, Item *conds,
48  SQL_I_List<ORDER> *order_list, ha_rows limit, ulonglong options)
49 {
50  bool will_batch;
51  int error, loc_error;
52  TABLE *table;
53  SQL_SELECT *select=0;
54  READ_RECORD info;
55  bool using_limit=limit != HA_POS_ERROR;
56  bool transactional_table, safe_update, const_cond;
57  bool const_cond_result;
58  ha_rows deleted= 0;
59  bool reverse= FALSE;
60  bool read_removal= false;
61  bool skip_record;
62  bool need_sort= FALSE;
63  bool err= true;
64  ORDER *order= (ORDER *) ((order_list && order_list->elements) ?
65  order_list->first : NULL);
66  uint usable_index= MAX_KEY;
67  SELECT_LEX *select_lex= &thd->lex->select_lex;
68  THD::killed_state killed_status= THD::NOT_KILLED;
69  THD::enum_binlog_query_type query_type= THD::ROW_QUERY_TYPE;
70  DBUG_ENTER("mysql_delete");
71 
72  if (open_normal_and_derived_tables(thd, table_list, 0))
73  DBUG_RETURN(TRUE);
74 
75  if (!(table= table_list->table))
76  {
77  my_error(ER_VIEW_DELETE_MERGE_VIEW, MYF(0),
78  table_list->view_db.str, table_list->view_name.str);
79  DBUG_RETURN(TRUE);
80  }
81  THD_STAGE_INFO(thd, stage_init);
82  table->map=1;
83 
84  if (mysql_prepare_delete(thd, table_list, &conds))
85  DBUG_RETURN(TRUE);
86 
87  /* check ORDER BY even if it can be ignored */
88  if (order)
89  {
90  TABLE_LIST tables;
91  List<Item> fields;
92  List<Item> all_fields;
93 
94  memset(&tables, 0, sizeof(tables));
95  tables.table = table;
96  tables.alias = table_list->alias;
97 
98  if (select_lex->setup_ref_array(thd, order_list->elements) ||
99  setup_order(thd, select_lex->ref_pointer_array, &tables,
100  fields, all_fields, order))
101  {
102  free_underlaid_joins(thd, &thd->lex->select_lex);
103  DBUG_RETURN(TRUE);
104  }
105  }
106 
107 #ifdef WITH_PARTITION_STORAGE_ENGINE
108  /*
109  Non delete tables are pruned in JOIN::prepare,
110  only the delete table needs this.
111  */
112  if (prune_partitions(thd, table, conds))
113  DBUG_RETURN(true);
114  if (table->all_partitions_pruned_away)
115  goto exit_all_parts_pruned_away;
116 #endif
117 
118  if (lock_tables(thd, table_list, thd->lex->table_count, 0))
119  DBUG_RETURN(true);
120 
121  const_cond= (!conds || conds->const_item());
122  safe_update=test(thd->variables.option_bits & OPTION_SAFE_UPDATES);
123  if (safe_update && const_cond)
124  {
125  my_message(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE,
126  ER(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE), MYF(0));
127  DBUG_RETURN(TRUE);
128  }
129 
130  select_lex->no_error= thd->lex->ignore;
131 
132  const_cond_result= const_cond && (!conds || conds->val_int());
133  if (thd->is_error())
134  {
135  /* Error evaluating val_int(). */
136  DBUG_RETURN(TRUE);
137  }
138 
139  /*
140  Test if the user wants to delete all rows and deletion doesn't have
141  any side-effects (because of triggers), so we can use optimized
142  handler::delete_all_rows() method.
143 
144  We can use delete_all_rows() if and only if:
145  - We allow new functions (not using option --skip-new)
146  - There is no limit clause
147  - The condition is constant
148  - If there is a condition, then it it produces a non-zero value
149  - If the current command is DELETE FROM with no where clause, then:
150  - We should not be binlogging this statement in row-based, and
151  - there should be no delete triggers associated with the table.
152  */
153  if (!using_limit && const_cond_result &&
154  !(specialflag & SPECIAL_NO_NEW_FUNC) &&
155  (!thd->is_current_stmt_binlog_format_row() &&
156  !(table->triggers && table->triggers->has_delete_triggers())))
157  {
158  /* Update the table->file->stats.records number */
159  table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);
160  ha_rows const maybe_deleted= table->file->stats.records;
161 
162  if (thd->lex->describe)
163  {
164  err= explain_no_table(thd, "Deleting all rows", maybe_deleted);
165  goto exit_without_my_ok;
166  }
167 
168  DBUG_PRINT("debug", ("Trying to use delete_all_rows()"));
169  if (!(error=table->file->ha_delete_all_rows()))
170  {
171  /*
172  If delete_all_rows() is used, it is not possible to log the
173  query in row format, so we have to log it in statement format.
174  */
175  query_type= THD::STMT_QUERY_TYPE;
176  error= -1;
177  deleted= maybe_deleted;
178  goto cleanup;
179  }
180  if (error != HA_ERR_WRONG_COMMAND)
181  {
182  table->file->print_error(error,MYF(0));
183  error=0;
184  goto cleanup;
185  }
186  /* Handler didn't support fast delete; Delete rows one by one */
187  }
188 
189  if (conds)
190  {
191  COND_EQUAL *cond_equal= NULL;
192  Item::cond_result result;
193 
194  conds= optimize_cond(thd, conds, &cond_equal, select_lex->join_list,
195  true, &result);
196  if (result == Item::COND_FALSE) // Impossible where
197  {
198  limit= 0;
199 
200  if (thd->lex->describe)
201  {
202  err= explain_no_table(thd, "Impossible WHERE");
203  goto exit_without_my_ok;
204  }
205  }
206  if (conds)
207  {
208  conds= substitute_for_best_equal_field(conds, cond_equal, 0);
209  conds->update_used_tables();
210  }
211  }
212 
213  /* Update the table->file->stats.records number */
214  table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);
215 
216  table->covering_keys.clear_all();
217  table->quick_keys.clear_all(); // Can't use 'only index'
218  table->possible_quick_keys.clear_all();
219 
220 #ifdef WITH_PARTITION_STORAGE_ENGINE
221  /* Prune a second time to be able to prune on subqueries in WHERE clause. */
222  if (prune_partitions(thd, table, conds))
223  DBUG_RETURN(true);
224  if (table->all_partitions_pruned_away)
225  goto exit_all_parts_pruned_away;
226 #endif
227 
228  select=make_select(table, 0, 0, conds, 0, &error);
229  if (error)
230  DBUG_RETURN(TRUE);
231 
232  { // Enter scope for optimizer trace wrapper
233  Opt_trace_object wrapper(&thd->opt_trace);
234  wrapper.add_utf8_table(table);
235 
236  if ((select && select->check_quick(thd, safe_update, limit)) || !limit)
237  {
238  if (thd->lex->describe && !error && !thd->is_error())
239  {
240  err= explain_no_table(thd, "Impossible WHERE");
241  goto exit_without_my_ok;
242  }
243  delete select;
244  free_underlaid_joins(thd, select_lex);
245  /*
246  Error was already created by quick select evaluation (check_quick()).
247  TODO: Add error code output parameter to Item::val_xxx() methods.
248  Currently they rely on the user checking DA for
249  errors when unwinding the stack after calling Item::val_xxx().
250  */
251  if (thd->is_error())
252  DBUG_RETURN(true);
253  my_ok(thd, 0);
254  DBUG_RETURN(false); // Nothing to delete
255  }
256  } // Ends scope for optimizer trace wrapper
257 
258  /* If running in safe sql mode, don't allow updates without keys */
259  if (table->quick_keys.is_clear_all())
260  {
261  thd->server_status|=SERVER_QUERY_NO_INDEX_USED;
262  if (safe_update && !using_limit)
263  {
264  delete select;
265  free_underlaid_joins(thd, select_lex);
266  my_message(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE,
267  ER(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE), MYF(0));
268  DBUG_RETURN(TRUE);
269  }
270  }
271 
272  if (order)
273  {
274  table->update_const_key_parts(conds);
275  order= simple_remove_const(order, conds);
276 
277  usable_index= get_index_for_order(order, table, select, limit,
278  &need_sort, &reverse);
279  }
280 
281  if (thd->lex->describe)
282  {
283  err= explain_single_table_modification(thd, table, select, usable_index,
284  limit, false, need_sort, false);
285  goto exit_without_my_ok;
286  }
287 
288  if (options & OPTION_QUICK)
289  (void) table->file->extra(HA_EXTRA_QUICK);
290 
291  if (need_sort)
292  {
293  ha_rows examined_rows;
294  ha_rows found_rows;
295 
296  {
297  Filesort fsort(order, HA_POS_ERROR, select);
298  DBUG_ASSERT(usable_index == MAX_KEY);
299  table->sort.io_cache= (IO_CACHE *) my_malloc(sizeof(IO_CACHE),
300  MYF(MY_FAE | MY_ZEROFILL));
301 
302  if ((table->sort.found_records= filesort(thd, table, &fsort, true,
303  &examined_rows, &found_rows))
304  == HA_POS_ERROR)
305  {
306  goto exit_without_my_ok;
307  }
308  thd->inc_examined_row_count(examined_rows);
309  /*
310  Filesort has already found and selected the rows we want to delete,
311  so we don't need the where clause
312  */
313  delete select;
314  free_underlaid_joins(thd, select_lex);
315  select= 0;
316  }
317  }
318 
319  /* If quick select is used, initialize it before retrieving rows. */
320  if (select && select->quick && (error= select->quick->reset()))
321  {
322  table->file->print_error(error, MYF(0));
323  goto exit_without_my_ok;
324  }
325  if (usable_index==MAX_KEY || (select && select->quick))
326  error= init_read_record(&info, thd, table, select, 1, 1, FALSE);
327  else
328  error= init_read_record_idx(&info, thd, table, 1, usable_index, reverse);
329 
330  if (error)
331  goto exit_without_my_ok;
332  init_ftfuncs(thd, select_lex, 1);
333  THD_STAGE_INFO(thd, stage_updating);
334 
335  if (table->triggers &&
336  table->triggers->has_triggers(TRG_EVENT_DELETE,
337  TRG_ACTION_AFTER))
338  {
339  /*
340  The table has AFTER DELETE triggers that might access to subject table
341  and therefore might need delete to be done immediately. So we turn-off
342  the batching.
343  */
344  (void) table->file->extra(HA_EXTRA_DELETE_CANNOT_BATCH);
345  will_batch= FALSE;
346  }
347  else
348  will_batch= !table->file->start_bulk_delete();
349 
350  table->mark_columns_needed_for_delete();
351 
352  if ((table->file->ha_table_flags() & HA_READ_BEFORE_WRITE_REMOVAL) &&
353  !using_limit &&
354  select && select->quick && select->quick->index != MAX_KEY)
355  read_removal= table->check_read_removal(select->quick->index);
356 
357  while (!(error=info.read_record(&info)) && !thd->killed &&
358  ! thd->is_error())
359  {
360  thd->inc_examined_row_count(1);
361  // thd->is_error() is tested to disallow delete row on error
362  if (!select || (!select->skip_record(thd, &skip_record) && !skip_record))
363  {
364 
365  if (table->triggers &&
366  table->triggers->process_triggers(thd, TRG_EVENT_DELETE,
367  TRG_ACTION_BEFORE, FALSE))
368  {
369  error= 1;
370  break;
371  }
372 
373  if (!(error= table->file->ha_delete_row(table->record[0])))
374  {
375  deleted++;
376  if (table->triggers &&
377  table->triggers->process_triggers(thd, TRG_EVENT_DELETE,
378  TRG_ACTION_AFTER, FALSE))
379  {
380  error= 1;
381  break;
382  }
383  if (!--limit && using_limit)
384  {
385  error= -1;
386  break;
387  }
388  }
389  else
390  {
391  table->file->print_error(error,MYF(0));
392  /*
393  In < 4.0.14 we set the error number to 0 here, but that
394  was not sensible, because then MySQL would not roll back the
395  failed DELETE, and also wrote it to the binlog. For MyISAM
396  tables a DELETE probably never should fail (?), but for
397  InnoDB it can fail in a FOREIGN KEY error or an
398  out-of-tablespace error.
399  */
400  error= 1;
401  break;
402  }
403  }
404  /*
405  Don't try unlocking the row if skip_record reported an error since in
406  this case the transaction might have been rolled back already.
407  */
408  else if (!thd->is_error())
409  table->file->unlock_row(); // Row failed selection, release lock on it
410  else
411  break;
412  }
413  killed_status= thd->killed;
414  if (killed_status != THD::NOT_KILLED || thd->is_error())
415  error= 1; // Aborted
416  if (will_batch && (loc_error= table->file->end_bulk_delete()))
417  {
418  if (error != 1)
419  table->file->print_error(loc_error,MYF(0));
420  error=1;
421  }
422  if (read_removal)
423  {
424  /* Only handler knows how many records were really written */
425  deleted= table->file->end_read_removal();
426  }
427  THD_STAGE_INFO(thd, stage_end);
428  end_read_record(&info);
429  if (options & OPTION_QUICK)
430  (void) table->file->extra(HA_EXTRA_NORMAL);
431 
432 cleanup:
433  DBUG_ASSERT(!thd->lex->describe);
434  /*
435  Invalidate the table in the query cache if something changed. This must
436  be before binlog writing and ha_autocommit_...
437  */
438  if (deleted)
439  {
440  query_cache_invalidate3(thd, table_list, 1);
441  }
442 
443  delete select;
444  select= NULL;
445  transactional_table= table->file->has_transactions();
446 
447  if (!transactional_table && deleted > 0)
448  thd->transaction.stmt.mark_modified_non_trans_table();
449 
450  /* See similar binlogging code in sql_update.cc, for comments */
451  if ((error < 0) || thd->transaction.stmt.cannot_safely_rollback())
452  {
453  if (mysql_bin_log.is_open())
454  {
455  int errcode= 0;
456  if (error < 0)
457  thd->clear_error();
458  else
459  errcode= query_error_code(thd, killed_status == THD::NOT_KILLED);
460 
461  /*
462  [binlog]: If 'handler::delete_all_rows()' was called and the
463  storage engine does not inject the rows itself, we replicate
464  statement-based; otherwise, 'ha_delete_row()' was used to
465  delete specific rows which we might log row-based.
466  */
467  int log_result= thd->binlog_query(query_type,
468  thd->query(), thd->query_length(),
469  transactional_table, FALSE, FALSE,
470  errcode);
471 
472  if (log_result)
473  {
474  error=1;
475  }
476  }
477  }
478  DBUG_ASSERT(transactional_table || !deleted || thd->transaction.stmt.cannot_safely_rollback());
479  free_underlaid_joins(thd, select_lex);
480  if (error < 0 ||
481  (thd->lex->ignore && !thd->is_error() && !thd->is_fatal_error))
482  {
483  my_ok(thd, deleted);
484  DBUG_PRINT("info",("%ld records deleted",(long) deleted));
485  }
486  DBUG_RETURN(thd->is_error() || thd->killed);
487 
488 #ifdef WITH_PARTITION_STORAGE_ENGINE
489 exit_all_parts_pruned_away:
490  /* No matching records */
491  if (!thd->lex->describe)
492  {
493  my_ok(thd, 0);
494  DBUG_RETURN(0);
495  }
496  err= explain_no_table(thd, "No matching rows after partition pruning");
497 #endif
498 
499 exit_without_my_ok:
500  delete select;
501  free_underlaid_joins(thd, select_lex);
502  table->set_keyread(false);
503  DBUG_RETURN((err || thd->is_error() || thd->killed) ? 1 : 0);
504 }
505 
506 
507 /*
508  Prepare items in DELETE statement
509 
510  SYNOPSIS
511  mysql_prepare_delete()
512  thd - thread handler
513  table_list - global/local table list
514  conds - conditions
515 
516  RETURN VALUE
517  FALSE OK
518  TRUE error
519 */
520 int mysql_prepare_delete(THD *thd, TABLE_LIST *table_list, Item **conds)
521 {
522  Item *fake_conds= 0;
523  SELECT_LEX *select_lex= &thd->lex->select_lex;
524  DBUG_ENTER("mysql_prepare_delete");
525  List<Item> all_fields;
526 
527  thd->lex->allow_sum_func= 0;
528  if (setup_tables_and_check_access(thd, &thd->lex->select_lex.context,
529  &thd->lex->select_lex.top_join_list,
530  table_list,
531  &select_lex->leaf_tables, FALSE,
532  DELETE_ACL, SELECT_ACL) ||
533  setup_conds(thd, table_list, select_lex->leaf_tables, conds) ||
534  setup_ftfuncs(select_lex))
535  DBUG_RETURN(TRUE);
536  if (!table_list->updatable || check_key_in_view(thd, table_list))
537  {
538  my_error(ER_NON_UPDATABLE_TABLE, MYF(0), table_list->alias, "DELETE");
539  DBUG_RETURN(TRUE);
540  }
541  {
542  TABLE_LIST *duplicate;
543  if ((duplicate= unique_table(thd, table_list, table_list->next_global, 0)))
544  {
545  update_non_unique_table_error(table_list, "DELETE", duplicate);
546  DBUG_RETURN(TRUE);
547  }
548  }
549 
550  if (select_lex->inner_refs_list.elements &&
551  fix_inner_refs(thd, all_fields, select_lex, select_lex->ref_pointer_array))
552  DBUG_RETURN(TRUE);
553 
554  select_lex->fix_prepare_information(thd, conds, &fake_conds);
555  DBUG_RETURN(FALSE);
556 }
557 
558 
559 /***************************************************************************
560  Delete multiple tables from join
561 ***************************************************************************/
562 
563 #define MEM_STRIP_BUF_SIZE current_thd->variables.sortbuff_size
564 
565 extern "C" int refpos_order_cmp(const void* arg, const void *a,const void *b)
566 {
567  handler *file= (handler*)arg;
568  return file->cmp_ref((const uchar*)a, (const uchar*)b);
569 }
570 
581 int mysql_multi_delete_prepare(THD *thd, uint *table_count)
582 {
583  LEX *lex= thd->lex;
584  TABLE_LIST *aux_tables= lex->auxiliary_table_list.first;
585  TABLE_LIST *target_tbl;
586  DBUG_ENTER("mysql_multi_delete_prepare");
587 
588  /*
589  setup_tables() need for VIEWs. JOIN::prepare() will not do it second
590  time.
591 
592  lex->query_tables also point on local list of DELETE SELECT_LEX
593  */
594  if (setup_tables_and_check_access(thd, &thd->lex->select_lex.context,
595  &thd->lex->select_lex.top_join_list,
596  lex->query_tables,
597  &lex->select_lex.leaf_tables, FALSE,
598  DELETE_ACL, SELECT_ACL))
599  DBUG_RETURN(TRUE);
600 
601  *table_count= 0;
602 
603  /*
604  Multi-delete can't be constructed over-union => we always have
605  single SELECT on top and have to check underlying SELECTs of it
606  */
607  lex->select_lex.exclude_from_table_unique_test= TRUE;
608  /* Fix tables-to-be-deleted-from list to point at opened tables */
609  for (target_tbl= (TABLE_LIST*) aux_tables;
610  target_tbl;
611  target_tbl= target_tbl->next_local)
612  {
613  ++(*table_count);
614 
615  if (!(target_tbl->table= target_tbl->correspondent_table->table))
616  {
617  DBUG_ASSERT(target_tbl->correspondent_table->view &&
618  target_tbl->correspondent_table->multitable_view);
619  my_error(ER_VIEW_DELETE_MERGE_VIEW, MYF(0),
620  target_tbl->correspondent_table->view_db.str,
621  target_tbl->correspondent_table->view_name.str);
622  DBUG_RETURN(TRUE);
623  }
624 
625  if (!target_tbl->correspondent_table->updatable ||
626  check_key_in_view(thd, target_tbl->correspondent_table))
627  {
628  my_error(ER_NON_UPDATABLE_TABLE, MYF(0),
629  target_tbl->table_name, "DELETE");
630  DBUG_RETURN(TRUE);
631  }
632  /*
633  Check that table from which we delete is not used somewhere
634  inside subqueries/view.
635  */
636  {
637  TABLE_LIST *duplicate;
638  if ((duplicate= unique_table(thd, target_tbl->correspondent_table,
639  lex->query_tables, 0)))
640  {
641  update_non_unique_table_error(target_tbl->correspondent_table,
642  "DELETE", duplicate);
643  DBUG_RETURN(TRUE);
644  }
645  }
646  }
647  /*
648  Reset the exclude flag to false so it doesn't interfare
649  with further calls to unique_table
650  */
651  lex->select_lex.exclude_from_table_unique_test= FALSE;
652  DBUG_RETURN(FALSE);
653 }
654 
655 
656 multi_delete::multi_delete(TABLE_LIST *dt, uint num_of_tables_arg)
657  : delete_tables(dt), deleted(0), found(0),
658  num_of_tables(num_of_tables_arg), error(0),
659  do_delete(0), transactional_tables(0), normal_tables(0), error_handled(0)
660 {
661  tempfiles= (Unique **) sql_calloc(sizeof(Unique *) * num_of_tables);
662 }
663 
664 
665 int
666 multi_delete::prepare(List<Item> &values, SELECT_LEX_UNIT *u)
667 {
668  DBUG_ENTER("multi_delete::prepare");
669  unit= u;
670  do_delete= 1;
671  THD_STAGE_INFO(thd, stage_deleting_from_main_table);
672  DBUG_RETURN(0);
673 }
674 
675 
676 bool
677 multi_delete::initialize_tables(JOIN *join)
678 {
679  TABLE_LIST *walk;
680  Unique **tempfiles_ptr;
681  DBUG_ENTER("initialize_tables");
682 
683  if ((thd->variables.option_bits & OPTION_SAFE_UPDATES) && error_if_full_join(join))
684  DBUG_RETURN(1);
685 
686  table_map tables_to_delete_from=0;
687  delete_while_scanning= 1;
688  for (walk= delete_tables; walk; walk= walk->next_local)
689  {
690  tables_to_delete_from|= walk->table->map;
691  if (delete_while_scanning &&
692  unique_table(thd, walk, join->tables_list, false))
693  {
694  /*
695  If the table we are going to delete from appears
696  in join, we need to defer delete. So the delete
697  doesn't interfers with the scaning of results.
698  */
699  delete_while_scanning= 0;
700  }
701  }
702 
703 
704  walk= delete_tables;
705  for (uint i= 0; i < join->primary_tables; i++)
706  {
707  JOIN_TAB *const tab= join->join_tab + i;
708  if (tab->table->map & tables_to_delete_from)
709  {
710  /* We are going to delete from this table */
711  TABLE *tbl=walk->table=tab->table;
712  walk= walk->next_local;
713  /* Don't use KEYREAD optimization on this table */
714  tbl->no_keyread=1;
715  /* Don't use record cache */
716  tbl->no_cache= 1;
717  tbl->covering_keys.clear_all();
718  if (tbl->file->has_transactions())
719  transactional_tables= 1;
720  else
721  normal_tables= 1;
722  if (tbl->triggers &&
723  tbl->triggers->has_triggers(TRG_EVENT_DELETE,
724  TRG_ACTION_AFTER))
725  {
726  /*
727  The table has AFTER DELETE triggers that might access to subject
728  table and therefore might need delete to be done immediately.
729  So we turn-off the batching.
730  */
731  (void) tbl->file->extra(HA_EXTRA_DELETE_CANNOT_BATCH);
732  }
733  tbl->prepare_for_position();
734  tbl->mark_columns_needed_for_delete();
735  }
736  else if ((tab->type != JT_SYSTEM && tab->type != JT_CONST) &&
737  walk == delete_tables)
738  {
739  /*
740  We are not deleting from the table we are scanning. In this
741  case send_data() shouldn't delete any rows a we may touch
742  the rows in the deleted table many times
743  */
744  delete_while_scanning= 0;
745  }
746  }
747  walk= delete_tables;
748  tempfiles_ptr= tempfiles;
749  if (delete_while_scanning)
750  {
751  table_being_deleted= delete_tables;
752  walk= walk->next_local;
753  }
754  for (;walk ;walk= walk->next_local)
755  {
756  TABLE *table=walk->table;
757  *tempfiles_ptr++= new Unique (refpos_order_cmp,
758  (void *) table->file,
759  table->file->ref_length,
760  MEM_STRIP_BUF_SIZE);
761  }
762  init_ftfuncs(thd, thd->lex->current_select, 1);
763  DBUG_RETURN(thd->is_fatal_error != 0);
764 }
765 
766 
767 multi_delete::~multi_delete()
768 {
769  for (table_being_deleted= delete_tables;
770  table_being_deleted;
771  table_being_deleted= table_being_deleted->next_local)
772  {
773  TABLE *table= table_being_deleted->table;
774  table->no_keyread=0;
775  }
776 
777  for (uint counter= 0; counter < num_of_tables; counter++)
778  {
779  if (tempfiles[counter])
780  delete tempfiles[counter];
781  }
782 }
783 
784 
785 bool multi_delete::send_data(List<Item> &values)
786 {
787  int secure_counter= delete_while_scanning ? -1 : 0;
788  TABLE_LIST *del_table;
789  DBUG_ENTER("multi_delete::send_data");
790 
791  bool ignore= thd->lex->current_select->no_error;
792 
793  for (del_table= delete_tables;
794  del_table;
795  del_table= del_table->next_local, secure_counter++)
796  {
797  TABLE *table= del_table->table;
798 
799  /* Check if we are using outer join and we didn't find the row */
800  if (table->status & (STATUS_NULL_ROW | STATUS_DELETED))
801  continue;
802 
803  table->file->position(table->record[0]);
804  found++;
805 
806  if (secure_counter < 0)
807  {
808  /* We are scanning the current table */
809  DBUG_ASSERT(del_table == table_being_deleted);
810  if (table->triggers &&
811  table->triggers->process_triggers(thd, TRG_EVENT_DELETE,
812  TRG_ACTION_BEFORE, FALSE))
813  DBUG_RETURN(1);
814  table->status|= STATUS_DELETED;
815  if (!(error=table->file->ha_delete_row(table->record[0])))
816  {
817  deleted++;
818  if (!table->file->has_transactions())
819  thd->transaction.stmt.mark_modified_non_trans_table();
820  if (table->triggers &&
821  table->triggers->process_triggers(thd, TRG_EVENT_DELETE,
822  TRG_ACTION_AFTER, FALSE))
823  DBUG_RETURN(1);
824  }
825  else if (!ignore)
826  {
827  /*
828  If the IGNORE option is used errors caused by ha_delete_row don't
829  have to stop the iteration.
830  */
831  table->file->print_error(error,MYF(0));
832  DBUG_RETURN(1);
833  }
834  }
835  else
836  {
837  error=tempfiles[secure_counter]->unique_add((char*) table->file->ref);
838  if (error)
839  {
840  error= 1; // Fatal error
841  DBUG_RETURN(1);
842  }
843  }
844  }
845  DBUG_RETURN(0);
846 }
847 
848 
849 void multi_delete::send_error(uint errcode,const char *err)
850 {
851  DBUG_ENTER("multi_delete::send_error");
852 
853  /* First send error what ever it is ... */
854  my_message(errcode, err, MYF(0));
855 
856  DBUG_VOID_RETURN;
857 }
858 
859 
860 void multi_delete::abort_result_set()
861 {
862  DBUG_ENTER("multi_delete::abort_result_set");
863 
864  /* the error was handled or nothing deleted and no side effects return */
865  if (error_handled ||
866  (!thd->transaction.stmt.cannot_safely_rollback() && !deleted))
867  DBUG_VOID_RETURN;
868 
869  /* Something already deleted so we have to invalidate cache */
870  if (deleted)
871  query_cache_invalidate3(thd, delete_tables, 1);
872 
873  /*
874  If rows from the first table only has been deleted and it is
875  transactional, just do rollback.
876  The same if all tables are transactional, regardless of where we are.
877  In all other cases do attempt deletes ...
878  */
879  if (do_delete && normal_tables &&
880  (table_being_deleted != delete_tables ||
881  !table_being_deleted->table->file->has_transactions()))
882  {
883  /*
884  We have to execute the recorded do_deletes() and write info into the
885  error log
886  */
887  error= 1;
888  send_eof();
889  DBUG_ASSERT(error_handled);
890  DBUG_VOID_RETURN;
891  }
892 
893  if (thd->transaction.stmt.cannot_safely_rollback())
894  {
895  /*
896  there is only side effects; to binlog with the error
897  */
898  if (mysql_bin_log.is_open())
899  {
900  int errcode= query_error_code(thd, thd->killed == THD::NOT_KILLED);
901  /* possible error of writing binary log is ignored deliberately */
902  (void) thd->binlog_query(THD::ROW_QUERY_TYPE,
903  thd->query(), thd->query_length(),
904  transactional_tables, FALSE, FALSE, errcode);
905  }
906  }
907  DBUG_VOID_RETURN;
908 }
909 
910 
911 
923 int multi_delete::do_deletes()
924 {
925  DBUG_ENTER("do_deletes");
926  DBUG_ASSERT(do_delete);
927 
928  do_delete= 0; // Mark called
929  if (!found)
930  DBUG_RETURN(0);
931 
932  table_being_deleted= (delete_while_scanning ? delete_tables->next_local :
933  delete_tables);
934 
935  for (uint counter= 0; table_being_deleted;
936  table_being_deleted= table_being_deleted->next_local, counter++)
937  {
938  TABLE *table = table_being_deleted->table;
939  if (tempfiles[counter]->get(table))
940  DBUG_RETURN(1);
941 
942  int local_error=
943  do_table_deletes(table, thd->lex->current_select->no_error);
944 
945  if (thd->killed && !local_error)
946  DBUG_RETURN(1);
947 
948  if (local_error == -1) // End of file
949  local_error = 0;
950 
951  if (local_error)
952  DBUG_RETURN(local_error);
953  }
954  DBUG_RETURN(0);
955 }
956 
957 
973 int multi_delete::do_table_deletes(TABLE *table, bool ignore)
974 {
975  int local_error= 0;
976  READ_RECORD info;
977  ha_rows last_deleted= deleted;
978  DBUG_ENTER("do_deletes_for_table");
979  if (init_read_record(&info, thd, table, NULL, 0, 1, FALSE))
980  DBUG_RETURN(1);
981  /*
982  Ignore any rows not found in reference tables as they may already have
983  been deleted by foreign key handling
984  */
985  info.ignore_not_found_rows= 1;
986  bool will_batch= !table->file->start_bulk_delete();
987  while (!(local_error= info.read_record(&info)) && !thd->killed)
988  {
989  if (table->triggers &&
990  table->triggers->process_triggers(thd, TRG_EVENT_DELETE,
991  TRG_ACTION_BEFORE, FALSE))
992  {
993  local_error= 1;
994  break;
995  }
996 
997  local_error= table->file->ha_delete_row(table->record[0]);
998  if (local_error && !ignore)
999  {
1000  table->file->print_error(local_error, MYF(0));
1001  break;
1002  }
1003 
1004  /*
1005  Increase the reported number of deleted rows only if no error occurred
1006  during ha_delete_row.
1007  Also, don't execute the AFTER trigger if the row operation failed.
1008  */
1009  if (!local_error)
1010  {
1011  deleted++;
1012  if (table->triggers &&
1013  table->triggers->process_triggers(thd, TRG_EVENT_DELETE,
1014  TRG_ACTION_AFTER, FALSE))
1015  {
1016  local_error= 1;
1017  break;
1018  }
1019  }
1020  }
1021  if (will_batch)
1022  {
1023  int tmp_error= table->file->end_bulk_delete();
1024  if (tmp_error && !local_error)
1025  {
1026  local_error= tmp_error;
1027  table->file->print_error(local_error, MYF(0));
1028  }
1029  }
1030  if (last_deleted != deleted && !table->file->has_transactions())
1031  thd->transaction.stmt.mark_modified_non_trans_table();
1032 
1033  end_read_record(&info);
1034 
1035  DBUG_RETURN(local_error);
1036 }
1037 
1038 /*
1039  Send ok to the client
1040 
1041  return: 0 sucess
1042  1 error
1043 */
1044 
1045 bool multi_delete::send_eof()
1046 {
1047  THD::killed_state killed_status= THD::NOT_KILLED;
1048  THD_STAGE_INFO(thd, stage_deleting_from_reference_tables);
1049 
1050  /* Does deletes for the last n - 1 tables, returns 0 if ok */
1051  int local_error= do_deletes(); // returns 0 if success
1052 
1053  /* compute a total error to know if something failed */
1054  local_error= local_error || error;
1055  killed_status= (local_error == 0)? THD::NOT_KILLED : thd->killed;
1056  /* reset used flags */
1057  THD_STAGE_INFO(thd, stage_end);
1058 
1059  /*
1060  We must invalidate the query cache before binlog writing and
1061  ha_autocommit_...
1062  */
1063  if (deleted)
1064  {
1065  query_cache_invalidate3(thd, delete_tables, 1);
1066  }
1067  if ((local_error == 0) || thd->transaction.stmt.cannot_safely_rollback())
1068  {
1069  if (mysql_bin_log.is_open())
1070  {
1071  int errcode= 0;
1072  if (local_error == 0)
1073  thd->clear_error();
1074  else
1075  errcode= query_error_code(thd, killed_status == THD::NOT_KILLED);
1076  if (thd->binlog_query(THD::ROW_QUERY_TYPE,
1077  thd->query(), thd->query_length(),
1078  transactional_tables, FALSE, FALSE, errcode) &&
1079  !normal_tables)
1080  {
1081  local_error=1; // Log write failed: roll back the SQL statement
1082  }
1083  }
1084  }
1085  if (local_error != 0)
1086  error_handled= TRUE; // to force early leave from ::send_error()
1087 
1088  if (!local_error)
1089  {
1090  ::my_ok(thd, deleted);
1091  }
1092  return 0;
1093 }
1094