~ubuntu-branches/ubuntu/trusty/drizzle/trusty

« back to all changes in this revision

Viewing changes to drizzled/sql_delete.cc

  • Committer: Bazaar Package Importer
  • Author(s): Monty Taylor
  • Date: 2010-03-18 12:12:31 UTC
  • Revision ID: james.westby@ubuntu.com-20100318121231-k6g1xe6cshbwa0f8
Tags: upstream-2010.03.1347
ImportĀ upstreamĀ versionĀ 2010.03.1347

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* Copyright (C) 2000 MySQL AB
 
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
 
15
 
 
16
/*
 
17
  Delete of records and truncate of tables.
 
18
 
 
19
  Multi-table deletes were introduced by Monty and Sinisa
 
20
*/
 
21
#include "config.h"
 
22
#include "drizzled/sql_select.h"
 
23
#include "drizzled/error.h"
 
24
#include "drizzled/probes.h"
 
25
#include "drizzled/sql_parse.h"
 
26
#include "drizzled/sql_base.h"
 
27
#include "drizzled/lock.h"
 
28
#include "drizzled/probes.h"
 
29
#include "drizzled/optimizer/range.h"
 
30
#include "drizzled/records.h"
 
31
#include "drizzled/internal/iocache.h"
 
32
#include "drizzled/transaction_services.h"
 
33
 
 
34
namespace drizzled
 
35
{
 
36
 
 
37
/**
 
38
  Implement DELETE SQL word.
 
39
 
 
40
  @note Like implementations of other DDL/DML in MySQL, this function
 
41
  relies on the caller to close the thread tables. This is done in the
 
42
  end of dispatch_command().
 
43
*/
 
44
 
 
45
bool mysql_delete(Session *session, TableList *table_list, COND *conds,
 
46
                  SQL_LIST *order, ha_rows limit, uint64_t,
 
47
                  bool reset_auto_increment)
 
48
{
 
49
  int           error;
 
50
  Table         *table;
 
51
  optimizer::SqlSelect *select= NULL;
 
52
  READ_RECORD   info;
 
53
  bool          using_limit=limit != HA_POS_ERROR;
 
54
  bool          transactional_table, const_cond;
 
55
  bool          const_cond_result;
 
56
  ha_rows       deleted= 0;
 
57
  uint32_t usable_index= MAX_KEY;
 
58
  Select_Lex   *select_lex= &session->lex->select_lex;
 
59
  Session::killed_state killed_status= Session::NOT_KILLED;
 
60
 
 
61
  if (session->openTablesLock(table_list))
 
62
  {
 
63
    DRIZZLE_DELETE_DONE(1, 0);
 
64
    return true;
 
65
  }
 
66
 
 
67
  table= table_list->table;
 
68
  assert(table);
 
69
 
 
70
  session->set_proc_info("init");
 
71
  table->map=1;
 
72
 
 
73
  if (mysql_prepare_delete(session, table_list, &conds))
 
74
    goto err;
 
75
 
 
76
  /* check ORDER BY even if it can be ignored */
 
77
  if (order && order->elements)
 
78
  {
 
79
    TableList   tables;
 
80
    List<Item>   fields;
 
81
    List<Item>   all_fields;
 
82
 
 
83
    memset(&tables, 0, sizeof(tables));
 
84
    tables.table = table;
 
85
    tables.alias = table_list->alias;
 
86
 
 
87
      if (select_lex->setup_ref_array(session, order->elements) ||
 
88
          setup_order(session, select_lex->ref_pointer_array, &tables,
 
89
                    fields, all_fields, (order_st*) order->first))
 
90
    {
 
91
      delete select;
 
92
      free_underlaid_joins(session, &session->lex->select_lex);
 
93
      goto err;
 
94
    }
 
95
  }
 
96
 
 
97
  const_cond= (!conds || conds->const_item());
 
98
 
 
99
  select_lex->no_error= session->lex->ignore;
 
100
 
 
101
  const_cond_result= const_cond && (!conds || conds->val_int());
 
102
  if (session->is_error())
 
103
  {
 
104
    /* Error evaluating val_int(). */
 
105
    return(true);
 
106
  }
 
107
 
 
108
  /*
 
109
    Test if the user wants to delete all rows and deletion doesn't have
 
110
    any side-effects (because of triggers), so we can use optimized
 
111
    handler::delete_all_rows() method.
 
112
 
 
113
    We implement fast TRUNCATE for InnoDB even if triggers are
 
114
    present.  TRUNCATE ignores triggers.
 
115
 
 
116
    We can use delete_all_rows() if and only if:
 
117
    - We allow new functions (not using option --skip-new), and are
 
118
      not in safe mode (not using option --safe-mode)
 
119
    - There is no limit clause
 
120
    - The condition is constant
 
121
    - If there is a condition, then it it produces a non-zero value
 
122
    - If the current command is DELETE FROM with no where clause
 
123
      (i.e., not TRUNCATE) then:
 
124
      - We should not be binlogging this statement row-based, and
 
125
      - there should be no delete triggers associated with the table.
 
126
  */
 
127
  if (!using_limit && const_cond_result)
 
128
  {
 
129
    /* Update the table->cursor->stats.records number */
 
130
    table->cursor->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);
 
131
    ha_rows const maybe_deleted= table->cursor->stats.records;
 
132
    if (!(error=table->cursor->ha_delete_all_rows()))
 
133
    {
 
134
      error= -1;                                // ok
 
135
      deleted= maybe_deleted;
 
136
      goto cleanup;
 
137
    }
 
138
    if (error != HA_ERR_WRONG_COMMAND)
 
139
    {
 
140
      table->print_error(error,MYF(0));
 
141
      error=0;
 
142
      goto cleanup;
 
143
    }
 
144
    /* Handler didn't support fast delete; Delete rows one by one */
 
145
  }
 
146
  if (conds)
 
147
  {
 
148
    Item::cond_result result;
 
149
    conds= remove_eq_conds(session, conds, &result);
 
150
    if (result == Item::COND_FALSE)             // Impossible where
 
151
      limit= 0;
 
152
  }
 
153
 
 
154
  /* Update the table->cursor->stats.records number */
 
155
  table->cursor->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);
 
156
 
 
157
  table->covering_keys.reset();
 
158
  table->quick_keys.reset();            // Can't use 'only index'
 
159
  select= optimizer::make_select(table, 0, 0, conds, 0, &error);
 
160
  if (error)
 
161
    goto err;
 
162
  if ((select && select->check_quick(session, false, limit)) || !limit)
 
163
  {
 
164
    delete select;
 
165
    free_underlaid_joins(session, select_lex);
 
166
    session->row_count_func= 0;
 
167
    DRIZZLE_DELETE_DONE(0, 0);
 
168
    /**
 
169
     * Resetting the Diagnostic area to prevent
 
170
     * lp bug# 439719
 
171
     */
 
172
    session->main_da.reset_diagnostics_area();
 
173
    session->my_ok((ha_rows) session->row_count_func);
 
174
    /*
 
175
      We don't need to call reset_auto_increment in this case, because
 
176
      mysql_truncate always gives a NULL conds argument, hence we never
 
177
      get here.
 
178
    */
 
179
    return 0; // Nothing to delete
 
180
  }
 
181
 
 
182
  /* If running in safe sql mode, don't allow updates without keys */
 
183
  if (table->quick_keys.none())
 
184
  {
 
185
    session->server_status|=SERVER_QUERY_NO_INDEX_USED;
 
186
  }
 
187
 
 
188
  if (order && order->elements)
 
189
  {
 
190
    uint32_t         length= 0;
 
191
    SORT_FIELD  *sortorder;
 
192
    ha_rows examined_rows;
 
193
 
 
194
    if ((!select || table->quick_keys.none()) && limit != HA_POS_ERROR)
 
195
      usable_index= optimizer::get_index_for_order(table, (order_st*)(order->first), limit);
 
196
 
 
197
    if (usable_index == MAX_KEY)
 
198
    {
 
199
      table->sort.io_cache= new internal::IO_CACHE;
 
200
      memset(table->sort.io_cache, 0, sizeof(internal::IO_CACHE));
 
201
 
 
202
 
 
203
      if (!(sortorder= make_unireg_sortorder((order_st*) order->first,
 
204
                                             &length, NULL)) ||
 
205
          (table->sort.found_records = filesort(session, table, sortorder, length,
 
206
                                                select, HA_POS_ERROR, 1,
 
207
                                                &examined_rows))
 
208
          == HA_POS_ERROR)
 
209
      {
 
210
        delete select;
 
211
        free_underlaid_joins(session, &session->lex->select_lex);
 
212
        goto err;
 
213
      }
 
214
      /*
 
215
        Filesort has already found and selected the rows we want to delete,
 
216
        so we don't need the where clause
 
217
      */
 
218
      delete select;
 
219
      free_underlaid_joins(session, select_lex);
 
220
      select= 0;
 
221
    }
 
222
  }
 
223
 
 
224
  /* If quick select is used, initialize it before retrieving rows. */
 
225
  if (select && select->quick && select->quick->reset())
 
226
  {
 
227
    delete select;
 
228
    free_underlaid_joins(session, select_lex);
 
229
    goto err;
 
230
  }
 
231
 
 
232
  if (usable_index==MAX_KEY)
 
233
    init_read_record(&info,session,table,select,1,1);
 
234
  else
 
235
    init_read_record_idx(&info, session, table, 1, usable_index);
 
236
 
 
237
  session->set_proc_info("updating");
 
238
 
 
239
  table->mark_columns_needed_for_delete();
 
240
 
 
241
  while (!(error=info.read_record(&info)) && !session->killed &&
 
242
         ! session->is_error())
 
243
  {
 
244
    // session->is_error() is tested to disallow delete row on error
 
245
    if (!(select && select->skip_record())&& ! session->is_error() )
 
246
    {
 
247
      if (!(error= table->cursor->ha_delete_row(table->record[0])))
 
248
      {
 
249
        deleted++;
 
250
        if (!--limit && using_limit)
 
251
        {
 
252
          error= -1;
 
253
          break;
 
254
        }
 
255
      }
 
256
      else
 
257
      {
 
258
        table->print_error(error,MYF(0));
 
259
        /*
 
260
          In < 4.0.14 we set the error number to 0 here, but that
 
261
          was not sensible, because then MySQL would not roll back the
 
262
          failed DELETE, and also wrote it to the binlog. For MyISAM
 
263
          tables a DELETE probably never should fail (?), but for
 
264
          InnoDB it can fail in a FOREIGN KEY error or an
 
265
          out-of-tablespace error.
 
266
        */
 
267
        error= 1;
 
268
        break;
 
269
      }
 
270
    }
 
271
    else
 
272
      table->cursor->unlock_row();  // Row failed selection, release lock on it
 
273
  }
 
274
  killed_status= session->killed;
 
275
  if (killed_status != Session::NOT_KILLED || session->is_error())
 
276
    error= 1;                                   // Aborted
 
277
 
 
278
  session->set_proc_info("end");
 
279
  end_read_record(&info);
 
280
 
 
281
cleanup:
 
282
 
 
283
  if (reset_auto_increment && (error < 0))
 
284
  {
 
285
    /*
 
286
      We're really doing a truncate and need to reset the table's
 
287
      auto-increment counter.
 
288
    */
 
289
    int error2= table->cursor->ha_reset_auto_increment(0);
 
290
 
 
291
    if (error2 && (error2 != HA_ERR_WRONG_COMMAND))
 
292
    {
 
293
      table->print_error(error2, MYF(0));
 
294
      error= 1;
 
295
    }
 
296
  }
 
297
 
 
298
  delete select;
 
299
  transactional_table= table->cursor->has_transactions();
 
300
 
 
301
  if (!transactional_table && deleted > 0)
 
302
    session->transaction.stmt.markModifiedNonTransData();
 
303
 
 
304
  /* See similar binlogging code in sql_update.cc, for comments */
 
305
  if ((error < 0) || session->transaction.stmt.hasModifiedNonTransData())
 
306
  {
 
307
    if (session->transaction.stmt.hasModifiedNonTransData())
 
308
      session->transaction.all.markModifiedNonTransData();
 
309
  }
 
310
  assert(transactional_table || !deleted || session->transaction.stmt.hasModifiedNonTransData());
 
311
  free_underlaid_joins(session, select_lex);
 
312
 
 
313
  DRIZZLE_DELETE_DONE((error >= 0 || session->is_error()), deleted);
 
314
  if (error < 0 || (session->lex->ignore && !session->is_fatal_error))
 
315
  {
 
316
    session->row_count_func= deleted;
 
317
    /**
 
318
     * Resetting the Diagnostic area to prevent
 
319
     * lp bug# 439719
 
320
     */
 
321
    session->main_da.reset_diagnostics_area();    
 
322
    session->my_ok((ha_rows) session->row_count_func);
 
323
  }
 
324
  return (error >= 0 || session->is_error());
 
325
 
 
326
err:
 
327
  DRIZZLE_DELETE_DONE(1, 0);
 
328
  return true;
 
329
}
 
330
 
 
331
 
 
332
/*
 
333
  Prepare items in DELETE statement
 
334
 
 
335
  SYNOPSIS
 
336
    mysql_prepare_delete()
 
337
    session                     - thread handler
 
338
    table_list          - global/local table list
 
339
    conds               - conditions
 
340
 
 
341
  RETURN VALUE
 
342
    false OK
 
343
    true  error
 
344
*/
 
345
int mysql_prepare_delete(Session *session, TableList *table_list, Item **conds)
 
346
{
 
347
  Select_Lex *select_lex= &session->lex->select_lex;
 
348
 
 
349
  List<Item> all_fields;
 
350
 
 
351
  session->lex->allow_sum_func= 0;
 
352
  if (setup_tables_and_check_access(session, &session->lex->select_lex.context,
 
353
                                    &session->lex->select_lex.top_join_list,
 
354
                                    table_list,
 
355
                                    &select_lex->leaf_tables, false) ||
 
356
      session->setup_conds(table_list, conds))
 
357
    return(true);
 
358
  {
 
359
    TableList *duplicate;
 
360
    if ((duplicate= unique_table(table_list, table_list->next_global)))
 
361
    {
 
362
      my_error(ER_UPDATE_TABLE_USED, MYF(0), table_list->alias);
 
363
      return(true);
 
364
    }
 
365
  }
 
366
 
 
367
  if (select_lex->inner_refs_list.elements &&
 
368
    fix_inner_refs(session, all_fields, select_lex, select_lex->ref_pointer_array))
 
369
    return(-1);
 
370
 
 
371
  return(false);
 
372
}
 
373
 
 
374
 
 
375
/***************************************************************************
 
376
  TRUNCATE Table
 
377
****************************************************************************/
 
378
 
 
379
/*
 
380
  Optimize delete of all rows by doing a full generate of the table
 
381
  This will work even if the .ISM and .ISD tables are destroyed
 
382
*/
 
383
 
 
384
bool mysql_truncate(Session& session, TableList *table_list)
 
385
{
 
386
  bool error;
 
387
  TransactionServices &transaction_services= TransactionServices::singleton();
 
388
 
 
389
  uint64_t save_options= session.options;
 
390
  table_list->lock_type= TL_WRITE;
 
391
  session.options&= ~(OPTION_BEGIN | OPTION_NOT_AUTOCOMMIT);
 
392
  mysql_init_select(session.lex);
 
393
  error= mysql_delete(&session, table_list, (COND*) 0, (SQL_LIST*) 0,
 
394
                      HA_POS_ERROR, 0L, true);
 
395
  /*
 
396
    Safety, in case the engine ignored ha_enable_transaction(false)
 
397
    above. Also clears session->transaction.*.
 
398
  */
 
399
  error= transaction_services.ha_autocommit_or_rollback(&session, error);
 
400
  session.options= save_options;
 
401
 
 
402
  return error;
 
403
}
 
404
 
 
405
} /* namespace drizzled */