~drizzle-trunk/drizzle/development

1 by brian
clean slate
1
/* Copyright (C) 2000-2006 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
1802.10.2 by Monty Taylor
Update all of the copyright headers to include the correct address.
14
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */
1 by brian
clean slate
15
16
17
/*
18
  Single table and multi table updates of tables.
19
*/
2148.7.12 by Brian Aker
Merge in header fixes.
20
2173.2.1 by Monty Taylor
Fixes incorrect usage of include
21
#include <config.h>
2148.7.12 by Brian Aker
Merge in header fixes.
22
2173.2.1 by Monty Taylor
Fixes incorrect usage of include
23
#include <drizzled/sql_select.h>
24
#include <drizzled/error.h>
25
#include <drizzled/probes.h>
26
#include <drizzled/sql_base.h>
27
#include <drizzled/field/epoch.h>
28
#include <drizzled/sql_parse.h>
29
#include <drizzled/optimizer/range.h>
30
#include <drizzled/records.h>
31
#include <drizzled/internal/my_sys.h>
32
#include <drizzled/internal/iocache.h>
33
#include <drizzled/transaction_services.h>
34
#include <drizzled/filesort.h>
35
#include <drizzled/plugin/storage_engine.h>
2198.1.1 by Olaf van der Spek
Remove unnecessary alter* includes
36
#include <drizzled/key.h>
2234.1.4 by Olaf van der Spek
Refactor includes
37
#include <drizzled/sql_lex.h>
2239.1.5 by Olaf van der Spek
Refactor includes
38
#include <drizzled/diagnostics_area.h>
2239.1.9 by Olaf van der Spek
Refactor includes
39
#include <drizzled/util/test.h>
2241.3.1 by Olaf van der Spek
Refactor Session::status_var
40
#include <drizzled/statistics_variables.h>
2241.3.4 by Olaf van der Spek
Refactor Session::transaction
41
#include <drizzled/session/transactions.h>
1 by brian
clean slate
42
1802.16.6 by Padraig O'Sullivan
Added temporary conversion of a bitmap to dynamic_bitset in order to remove references to MyBitmap within optimizer code.
43
#include <boost/dynamic_bitset.hpp>
997.4.1 by Padraig O'Sullivan
Removed 1 instance of SQL_LIST from the source base. Replaced it with
44
#include <list>
982.1.3 by Padraig O'Sullivan
Various small cleanups to numerous files to now have calls to the correct
45
46
using namespace std;
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
47
2241.3.1 by Olaf van der Spek
Refactor Session::status_var
48
namespace drizzled {
1005.2.3 by Monty Taylor
Further reversion of P.
49
1 by brian
clean slate
50
/**
51
  Re-read record if more columns are needed for error message.
52
53
  If we got a duplicate key error, we want to write an error
54
  message containing the value of the duplicate key. If we do not have
1672.3.6 by Brian Aker
First pass in encapsulating row
55
  all fields of the key value in getInsertRecord(), we need to re-read the
1 by brian
clean slate
56
  record with a proper read_set.
57
58
  @param[in] error   error number
59
  @param[in] table   table
60
*/
61
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
62
static void prepare_record_for_error_message(int error, Table *table)
1 by brian
clean slate
63
{
1802.16.1 by Padraig O'Sullivan
Replaced one instance of MyBitmap with dynamic_bitset from boost. Added some utility functions to MyBitmap temporarily in order to accomplish this.
64
  Field **field_p= NULL;
65
  Field *field= NULL;
66
  uint32_t keynr= 0;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
67
1 by brian
clean slate
68
  /*
69
    Only duplicate key errors print the key value.
70
    If storage engine does always read all columns, we have the value alraedy.
71
  */
72
  if ((error != HA_ERR_FOUND_DUPP_KEY) ||
1802.16.1 by Padraig O'Sullivan
Replaced one instance of MyBitmap with dynamic_bitset from boost. Added some utility functions to MyBitmap temporarily in order to accomplish this.
73
      ! (table->cursor->getEngine()->check_flag(HTON_BIT_PARTIAL_COLUMN_READ)))
51.2.2 by Patrick Galbraith
Removed DBUGs from
74
    return;
1 by brian
clean slate
75
76
  /*
77
    Get the number of the offended index.
78
    We will see MAX_KEY if the engine cannot determine the affected index.
79
  */
1216.1.1 by Brian Aker
Move print_error up to Engine.
80
  if ((keynr= table->get_dup_key(error)) >= MAX_KEY)
51.2.2 by Patrick Galbraith
Removed DBUGs from
81
    return;
1 by brian
clean slate
82
83
  /* Create unique_map with all fields used by that index. */
1835.1.5 by Brian Aker
Cleans up some spots where we were using mutable but did not need too.
84
  boost::dynamic_bitset<> unique_map(table->getShare()->sizeFields()); /* Fields in offended unique. */
1802.16.1 by Padraig O'Sullivan
Replaced one instance of MyBitmap with dynamic_bitset from boost. Added some utility functions to MyBitmap temporarily in order to accomplish this.
85
  table->mark_columns_used_by_index_no_reset(keynr, unique_map);
1 by brian
clean slate
86
87
  /* Subtract read_set and write_set. */
1802.16.8 by Padraig O'Sullivan
Removal of all MyBitmap from the code base. Compiles but test failures exist now.
88
  unique_map-= *table->read_set;
89
  unique_map-= *table->write_set;
1 by brian
clean slate
90
91
  /*
92
    If the unique index uses columns that are neither in read_set
93
    nor in write_set, we must re-read the record.
94
    Otherwise no need to do anything.
95
  */
1802.16.1 by Padraig O'Sullivan
Replaced one instance of MyBitmap with dynamic_bitset from boost. Added some utility functions to MyBitmap temporarily in order to accomplish this.
96
  if (unique_map.none())
51.2.2 by Patrick Galbraith
Removed DBUGs from
97
    return;
1 by brian
clean slate
98
1208.3.2 by brian
Update for Cursor renaming.
99
  /* Get identifier of last read record into table->cursor->ref. */
1672.3.6 by Brian Aker
First pass in encapsulating row
100
  table->cursor->position(table->getInsertRecord());
1 by brian
clean slate
101
  /* Add all fields used by unique index to read_set. */
1802.16.8 by Padraig O'Sullivan
Removal of all MyBitmap from the code base. Compiles but test failures exist now.
102
  *table->read_set|= unique_map;
1208.3.2 by brian
Update for Cursor renaming.
103
  /* Read record that is identified by table->cursor->ref. */
1672.3.6 by Brian Aker
First pass in encapsulating row
104
  (void) table->cursor->rnd_pos(table->getUpdateRecord(), table->cursor->ref);
1 by brian
clean slate
105
  /* Copy the newly read columns into the new record. */
1578.2.16 by Brian Aker
Merge in change to getTable() to private the field objects.
106
  for (field_p= table->getFields(); (field= *field_p); field_p++)
107
  {
1999.4.2 by Brian Aker
Encapsulate the field's position.
108
    if (unique_map.test(field->position()))
1578.2.16 by Brian Aker
Merge in change to getTable() to private the field objects.
109
    {
1574 by Brian Aker
Rollup patch for hiding tableshare.
110
      field->copy_from_tmp(table->getShare()->rec_buff_length);
1578.2.16 by Brian Aker
Merge in change to getTable() to private the field objects.
111
    }
112
  }
113
51.2.2 by Patrick Galbraith
Removed DBUGs from
114
  return;
1 by brian
clean slate
115
}
116
117
118
/*
119
  Process usual UPDATE
120
121
  SYNOPSIS
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
122
    update_query()
520.1.22 by Brian Aker
Second pass of thd cleanup
123
    session			thread handler
1 by brian
clean slate
124
    fields		fields for update
125
    values		values of fields for update
126
    conds		WHERE clause expression
1273.2.8 by Stewart Smith
fix accidental mangling of comment: s/order_st BY/ORDER BY/. in sql_update.cc
127
    order_num		number of elemen in ORDER BY clause
327.2.3 by Brian Aker
Refactoring of class Table
128
    order		order_st BY clause list
1 by brian
clean slate
129
    limit		limit clause
130
    handle_duplicates	how to handle duplicates
131
132
  RETURN
133
    0  - OK
134
    1  - error
135
*/
136
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
137
int update_query(Session *session, TableList *table_list,
575.1.2 by Monty Taylor
Changed a bunch of __attribute__((unused)) to removing the parameter name instead.
138
                 List<Item> &fields, List<Item> &values, COND *conds,
1892.3.3 by tdavies
struct order_st changed and renamed to c++ class named:Order
139
                 uint32_t order_num, Order *order,
575.1.2 by Monty Taylor
Changed a bunch of __attribute__((unused)) to removing the parameter name instead.
140
                 ha_rows limit, enum enum_duplicates,
77.1.45 by Monty Taylor
Warning fixes.
141
                 bool ignore)
1 by brian
clean slate
142
{
143
  bool		using_limit= limit != HA_POS_ERROR;
1235.1.9 by Brian Aker
Remove code around update batch handler (we have no engines supporting
144
  bool		used_key_is_modified;
145
  bool		transactional_table;
2049.2.1 by Stewart Smith
doStartTableScan() result not checked.
146
  int		error= 0;
1 by brian
clean slate
147
  uint		used_index= MAX_KEY, dup_key_found;
56 by brian
Next pass of true/false update.
148
  bool          need_sort= true;
1 by brian
clean slate
149
  ha_rows	updated, found;
150
  key_map	old_covering_keys;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
151
  Table		*table;
1237.13.3 by Padraig O'Sullivan
Performed numerous style cleanups in range.[cc,h].
152
  optimizer::SqlSelect *select= NULL;
1538 by Brian Aker
Code shuffle on ReadRecord
153
  ReadRecord	info;
2227.4.8 by Olaf van der Spek
Session::lex()
154
  Select_Lex    *select_lex= &session->lex().select_lex;
151 by Brian Aker
Ulonglong to uint64_t
155
  uint64_t     id;
1 by brian
clean slate
156
  List<Item> all_fields;
1910.2.8 by Brian Aker
Enapsulate Kill.
157
  Session::killed_state_t killed_status= Session::NOT_KILLED;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
158
1932.2.3 by Brian Aker
Updates for D-trace
159
  DRIZZLE_UPDATE_START(session->getQueryString()->c_str());
1109.1.3 by Brian Aker
Move names around a bit (to align similar methods)
160
  if (session->openTablesLock(table_list))
1126.10.17 by Padraig O'Sullivan
Added calls to the update related dtrace probes.
161
  {
162
    DRIZZLE_UPDATE_DONE(1, 0, 0);
1109.1.2 by Brian Aker
More from the table patch
163
    return 1;
1126.10.17 by Padraig O'Sullivan
Added calls to the update related dtrace probes.
164
  }
1109.1.2 by Brian Aker
More from the table patch
165
520.1.22 by Brian Aker
Second pass of thd cleanup
166
  session->set_proc_info("init");
1 by brian
clean slate
167
  table= table_list->table;
168
169
  /* Calculate "table->covering_keys" based on the WHERE */
1574 by Brian Aker
Rollup patch for hiding tableshare.
170
  table->covering_keys= table->getShare()->keys_in_use;
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
171
  table->quick_keys.reset();
1 by brian
clean slate
172
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
173
  if (prepare_update(session, table_list, &conds, order_num, order))
1864.3.22 by Brian Aker
Goto removal.
174
  {
175
    DRIZZLE_UPDATE_DONE(1, 0, 0);
176
    return 1;
177
  }
1 by brian
clean slate
178
179
  old_covering_keys= table->covering_keys;		// Keys used in WHERE
180
  /* Check the fields we are going to modify */
520.1.22 by Brian Aker
Second pass of thd cleanup
181
  if (setup_fields_with_no_wrap(session, 0, fields, MARK_COLUMNS_WRITE, 0, 0))
1864.3.22 by Brian Aker
Goto removal.
182
  {
183
    DRIZZLE_UPDATE_DONE(1, 0, 0);
184
    return 1;
185
  }
186
1 by brian
clean slate
187
  if (table->timestamp_field)
188
  {
189
    // Don't set timestamp column if this is modified
1009 by Brian Aker
Merge of Monty
190
    if (table->timestamp_field->isWriteSet())
1607 by Brian Aker
Cursor now fully handles the update to timestamp for the engine.
191
    {
1 by brian
clean slate
192
      table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
1607 by Brian Aker
Cursor now fully handles the update to timestamp for the engine.
193
    }
1 by brian
clean slate
194
    else
195
    {
196
      if (table->timestamp_field_type == TIMESTAMP_AUTO_SET_ON_UPDATE ||
197
          table->timestamp_field_type == TIMESTAMP_AUTO_SET_ON_BOTH)
1607 by Brian Aker
Cursor now fully handles the update to timestamp for the engine.
198
      {
1999.4.2 by Brian Aker
Encapsulate the field's position.
199
        table->setWriteSet(table->timestamp_field->position());
1607 by Brian Aker
Cursor now fully handles the update to timestamp for the engine.
200
      }
1 by brian
clean slate
201
    }
202
  }
203
520.1.22 by Brian Aker
Second pass of thd cleanup
204
  if (setup_fields(session, 0, values, MARK_COLUMNS_READ, 0, 0))
1 by brian
clean slate
205
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
206
    free_underlaid_joins(session, select_lex);
1864.3.22 by Brian Aker
Goto removal.
207
    DRIZZLE_UPDATE_DONE(1, 0, 0);
208
209
    return 1;
1 by brian
clean slate
210
  }
211
2183.2.20 by Olaf van der Spek
Use List::size()
212
  if (select_lex->inner_refs_list.size() &&
520.1.22 by Brian Aker
Second pass of thd cleanup
213
    fix_inner_refs(session, all_fields, select_lex, select_lex->ref_pointer_array))
1 by brian
clean slate
214
  {
1126.10.17 by Padraig O'Sullivan
Added calls to the update related dtrace probes.
215
    DRIZZLE_UPDATE_DONE(1, 0, 0);
2062.4.1 by Andrew Hutchings
Backport http://bugs.mysql.com/bug.php?id=40113
216
    return 1;
1 by brian
clean slate
217
  }
218
219
  if (conds)
220
  {
221
    Item::cond_result cond_value;
520.1.22 by Brian Aker
Second pass of thd cleanup
222
    conds= remove_eq_conds(session, conds, &cond_value);
1 by brian
clean slate
223
    if (cond_value == Item::COND_FALSE)
224
      limit= 0;                                   // Impossible WHERE
225
  }
226
227
  /*
228
    If a timestamp field settable on UPDATE is present then to avoid wrong
229
    update force the table handler to retrieve write-only fields to be able
230
    to compare records and detect data change.
231
  */
1233.1.4 by Brian Aker
Added:
232
  if (table->cursor->getEngine()->check_flag(HTON_BIT_PARTIAL_COLUMN_READ) &&
1 by brian
clean slate
233
      table->timestamp_field &&
234
      (table->timestamp_field_type == TIMESTAMP_AUTO_SET_ON_UPDATE ||
235
       table->timestamp_field_type == TIMESTAMP_AUTO_SET_ON_BOTH))
1607 by Brian Aker
Cursor now fully handles the update to timestamp for the engine.
236
  {
1802.16.8 by Padraig O'Sullivan
Removal of all MyBitmap from the code base. Compiles but test failures exist now.
237
    *table->read_set|= *table->write_set;
1607 by Brian Aker
Cursor now fully handles the update to timestamp for the engine.
238
  }
1 by brian
clean slate
239
  // Don't count on usage of 'only index' when calculating which key to use
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
240
  table->covering_keys.reset();
1 by brian
clean slate
241
1208.3.2 by brian
Update for Cursor renaming.
242
  /* Update the table->cursor->stats.records number */
243
  table->cursor->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);
1 by brian
clean slate
244
1237.9.2 by Padraig O'Sullivan
Moved opt_range.[cc,h] into the optimizer directory and namespace and renamed the files to
245
  select= optimizer::make_select(table, 0, 0, conds, 0, &error);
1 by brian
clean slate
246
  if (error || !limit ||
1237.6.1 by Brian Aker
Remove dead bits in parser/whitespace/etc.
247
      (select && select->check_quick(session, false, limit)))
1 by brian
clean slate
248
  {
249
    delete select;
1124.2.14 by Diego Medina
* On certain UPDATE and DELETE statements, drizzled failed an assert() in
250
    /**
251
     * Resetting the Diagnostic area to prevent
252
     * lp bug# 439719
253
     */
2239.1.4 by Olaf van der Spek
Refactor includes
254
    session->main_da().reset_diagnostics_area();
520.1.22 by Brian Aker
Second pass of thd cleanup
255
    free_underlaid_joins(session, select_lex);
2062.4.1 by Andrew Hutchings
Backport http://bugs.mysql.com/bug.php?id=40113
256
    if (error || session->is_error())
1864.3.22 by Brian Aker
Goto removal.
257
    {
258
      DRIZZLE_UPDATE_DONE(1, 0, 0);
259
      return 1;
260
    }
1126.10.17 by Padraig O'Sullivan
Added calls to the update related dtrace probes.
261
    DRIZZLE_UPDATE_DONE(0, 0, 0);
836 by Brian Aker
Fixed session call from function to method.
262
    session->my_ok();				// No matching records
1126.10.17 by Padraig O'Sullivan
Added calls to the update related dtrace probes.
263
    return 0;
1 by brian
clean slate
264
  }
265
  if (!select && limit != HA_POS_ERROR)
266
  {
1237.9.2 by Padraig O'Sullivan
Moved opt_range.[cc,h] into the optimizer directory and namespace and renamed the files to
267
    if ((used_index= optimizer::get_index_for_order(table, order, limit)) != MAX_KEY)
56 by brian
Next pass of true/false update.
268
      need_sort= false;
1 by brian
clean slate
269
  }
270
  /* If running in safe sql mode, don't allow updates without keys */
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
271
  if (table->quick_keys.none())
1 by brian
clean slate
272
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
273
    session->server_status|=SERVER_QUERY_NO_INDEX_USED;
1 by brian
clean slate
274
  }
275
276
  table->mark_columns_needed_for_update();
277
278
  /* Check if we are modifying a key that we are used to search with */
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
279
1 by brian
clean slate
280
  if (select && select->quick)
281
  {
282
    used_index= select->quick->index;
283
    used_key_is_modified= (!select->quick->unique_key_range() &&
1802.16.8 by Padraig O'Sullivan
Removal of all MyBitmap from the code base. Compiles but test failures exist now.
284
                          select->quick->is_keys_used(*table->write_set));
1 by brian
clean slate
285
  }
286
  else
287
  {
288
    used_key_is_modified= 0;
289
    if (used_index == MAX_KEY)                  // no index for sort order
1208.3.2 by brian
Update for Cursor renaming.
290
      used_index= table->cursor->key_used_on_scan;
1 by brian
clean slate
291
    if (used_index != MAX_KEY)
1802.16.8 by Padraig O'Sullivan
Removal of all MyBitmap from the code base. Compiles but test failures exist now.
292
      used_key_is_modified= is_key_used(table, used_index, *table->write_set);
1 by brian
clean slate
293
  }
294
295
296
  if (used_key_is_modified || order)
297
  {
298
    /*
299
      We can't update table directly;  We must first search after all
300
      matching rows before updating the table!
301
    */
1005.2.6 by Monty Taylor
Re-added bitset<> as a replacement for Bitmap<>
302
    if (used_index < MAX_KEY && old_covering_keys.test(used_index))
1 by brian
clean slate
303
    {
304
      table->key_read=1;
305
      table->mark_columns_used_by_index(used_index);
306
    }
307
    else
308
    {
309
      table->use_all_columns();
310
    }
311
312
    /* note: We avoid sorting avoid if we sort on the used index */
313
    if (order && (need_sort || used_key_is_modified))
314
    {
315
      /*
327.2.3 by Brian Aker
Refactoring of class Table
316
	Doing an order_st BY;  Let filesort find and sort the rows we are going
1 by brian
clean slate
317
	to update
318
        NOTE: filesort will call table->prepare_for_position()
319
      */
482 by Brian Aker
Remove uint.
320
      uint32_t         length= 0;
1711.6.1 by Brian Aker
Style on structure cleanup
321
      SortField  *sortorder;
1 by brian
clean slate
322
      ha_rows examined_rows;
1905.1.1 by Brian Aker
Adding FileSort class.
323
      FileSort filesort(*session);
1 by brian
clean slate
324
2296.1.1 by Mark Atwood
Merge in Fixes of Brian's IOCACHE.
325
      table->sort.io_cache= new internal::io_cache_st;
2318.6.36 by Olaf van der Spek
Refactor
326
      sortorder=make_unireg_sortorder(order, &length, NULL);
641.3.8 by Monty Taylor
Removed my_malloc from drizzled.
327
2318.6.36 by Olaf van der Spek
Refactor
328
      if ((table->sort.found_records= filesort.run(table, sortorder, length, select, limit, 1, examined_rows)) == HA_POS_ERROR)
329
        goto err;
1 by brian
clean slate
330
      /*
331
	Filesort has already found and selected the rows we want to update,
332
	so we don't need the where clause
333
      */
2172.3.22 by Brian Aker
This patch adds safe_delete(). All of these locations in the code should be
334
      safe_delete(select);
1 by brian
clean slate
335
    }
336
    else
337
    {
338
      /*
339
	We are doing a search on a key that is updated. In this case
340
	we go trough the matching rows, save a pointer to them and
341
	update these in a separate loop based on the pointer.
342
      */
343
2296.1.1 by Mark Atwood
Merge in Fixes of Brian's IOCACHE.
344
      internal::io_cache_st tempfile;
1909.1.2 by Brian Aker
Additional io_cache encapsulation.
345
      if (tempfile.open_cached_file(drizzle_tmpdir.c_str(),TEMP_PREFIX, DISK_BUFFER_SIZE, MYF(MY_WME)))
346
      {
1 by brian
clean slate
347
	goto err;
1909.1.2 by Brian Aker
Additional io_cache encapsulation.
348
      }
1 by brian
clean slate
349
350
      /* If quick select is used, initialize it before retrieving rows. */
351
      if (select && select->quick && select->quick->reset())
352
        goto err;
1208.3.2 by brian
Update for Cursor renaming.
353
      table->cursor->try_semi_consistent_read(1);
1 by brian
clean slate
354
355
      /*
356
        When we get here, we have one of the following options:
357
        A. used_index == MAX_KEY
358
           This means we should use full table scan, and start it with
359
           init_read_record call
360
        B. used_index != MAX_KEY
361
           B.1 quick select is used, start the scan with init_read_record
362
           B.2 quick select is not used, this is full index scan (with LIMIT)
363
               Full index scan must be started with init_read_record_idx
364
      */
365
366
      if (used_index == MAX_KEY || (select && select->quick))
1538 by Brian Aker
Code shuffle on ReadRecord
367
      {
2049.2.1 by Stewart Smith
doStartTableScan() result not checked.
368
        if ((error= info.init_read_record(session, table, select, 0, true)))
369
          goto err;
1538 by Brian Aker
Code shuffle on ReadRecord
370
      }
1 by brian
clean slate
371
      else
1538 by Brian Aker
Code shuffle on ReadRecord
372
      {
2049.2.8 by Stewart Smith
init_read_record_idx return result should be checked now that it checks startIndexScan result. Fix case in sql_update
373
        if ((error= info.init_read_record_idx(session, table, 1, used_index)))
374
          goto err;
1538 by Brian Aker
Code shuffle on ReadRecord
375
      }
1 by brian
clean slate
376
520.1.22 by Brian Aker
Second pass of thd cleanup
377
      session->set_proc_info("Searching rows for update");
1 by brian
clean slate
378
      ha_rows tmp_limit= limit;
379
1910.2.8 by Brian Aker
Enapsulate Kill.
380
      while (not(error= info.read_record(&info)) && not session->getKilled())
1 by brian
clean slate
381
      {
382
	if (!(select && select->skip_record()))
383
	{
1208.3.2 by brian
Update for Cursor renaming.
384
          if (table->cursor->was_semi_consistent_read())
1 by brian
clean slate
385
	    continue;  /* repeat the read of the same row if it still exists */
386
1672.3.6 by Brian Aker
First pass in encapsulating row
387
	  table->cursor->position(table->getInsertRecord());
2385.3.13 by Olaf van der Spek
Refactor iocache
388
	  if (tempfile.write(table->cursor->ref, table->cursor->ref_length))
1 by brian
clean slate
389
	  {
971.6.11 by Eric Day
Removed purecov messages.
390
	    error=1;
391
	    break;
1 by brian
clean slate
392
	  }
393
	  if (!--limit && using_limit)
394
	  {
395
	    error= -1;
396
	    break;
397
	  }
398
	}
399
	else
1208.3.2 by brian
Update for Cursor renaming.
400
	  table->cursor->unlock_row();
1 by brian
clean slate
401
      }
1910.2.8 by Brian Aker
Enapsulate Kill.
402
      if (session->getKilled() && not error)
1 by brian
clean slate
403
	error= 1;				// Aborted
404
      limit= tmp_limit;
1208.3.2 by brian
Update for Cursor renaming.
405
      table->cursor->try_semi_consistent_read(0);
1538 by Brian Aker
Code shuffle on ReadRecord
406
      info.end_read_record();
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
407
1 by brian
clean slate
408
      /* Change select to use tempfile */
409
      if (select)
410
      {
2172.3.22 by Brian Aker
This patch adds safe_delete(). All of these locations in the code should be
411
	safe_delete(select->quick);
1 by brian
clean slate
412
	if (select->free_cond)
413
	  delete select->cond;
414
	select->cond=0;
415
      }
416
      else
417
      {
2047.1.1 by Andrew Hutchings
Refix using placement new for join code, vector for join cache buffer.
418
	select= new optimizer::SqlSelect();
1 by brian
clean slate
419
	select->head=table;
420
      }
1909.1.1 by Brian Aker
Encapsulation of IO_CACHE.
421
      if (tempfile.reinit_io_cache(internal::READ_CACHE,0L,0,0))
971.6.11 by Eric Day
Removed purecov messages.
422
	error=1;
1241.9.48 by Monty Taylor
Made one of the drizzled instances of IO_CACHE a pointer.
423
      // Read row ptrs from this cursor
424
      memcpy(select->file, &tempfile, sizeof(tempfile));
1 by brian
clean slate
425
      if (error >= 0)
426
	goto err;
427
    }
428
    if (table->key_read)
429
      table->restore_column_maps_after_mark_index();
430
  }
431
432
  if (ignore)
1208.3.2 by brian
Update for Cursor renaming.
433
    table->cursor->extra(HA_EXTRA_IGNORE_DUP_KEY);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
434
1 by brian
clean slate
435
  if (select && select->quick && select->quick->reset())
436
    goto err;
1208.3.2 by brian
Update for Cursor renaming.
437
  table->cursor->try_semi_consistent_read(1);
2049.2.1 by Stewart Smith
doStartTableScan() result not checked.
438
  if ((error= info.init_read_record(session, table, select, 0, true)))
439
  {
440
    goto err;
441
  }
1 by brian
clean slate
442
443
  updated= found= 0;
685.4.1 by Jay Pipes
Enabled the null.test.
444
  /*
445
   * Per the SQL standard, inserting NULL into a NOT NULL
446
   * field requires an error to be thrown.
447
   *
448
   * @NOTE
449
   *
450
   * NULL check and handling occurs in field_conv.cc
451
   */
452
  session->count_cuted_fields= CHECK_FIELD_ERROR_FOR_NULL;
453
  session->cuted_fields= 0L;
520.1.22 by Brian Aker
Second pass of thd cleanup
454
  session->set_proc_info("Updating");
1 by brian
clean slate
455
1208.3.2 by brian
Update for Cursor renaming.
456
  transactional_table= table->cursor->has_transactions();
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
457
  session->setAbortOnWarning(test(!ignore));
1 by brian
clean slate
458
459
  /*
460
    Assure that we can use position()
461
    if we need to create an error message.
462
  */
1233.1.4 by Brian Aker
Added:
463
  if (table->cursor->getEngine()->check_flag(HTON_BIT_PARTIAL_COLUMN_READ))
1 by brian
clean slate
464
    table->prepare_for_position();
465
1910.2.8 by Brian Aker
Enapsulate Kill.
466
  while (not (error=info.read_record(&info)) && not session->getKilled())
1 by brian
clean slate
467
  {
1910.2.8 by Brian Aker
Enapsulate Kill.
468
    if (not (select && select->skip_record()))
1 by brian
clean slate
469
    {
1208.3.2 by brian
Update for Cursor renaming.
470
      if (table->cursor->was_semi_consistent_read())
1 by brian
clean slate
471
        continue;  /* repeat the read of the same row if it still exists */
472
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
473
      table->storeRecord();
1235.1.11 by Brian Aker
Small cleanups, did in MERGE table only engine flag.
474
      if (fill_record(session, fields, values))
971.6.11 by Eric Day
Removed purecov messages.
475
        break;
1 by brian
clean slate
476
477
      found++;
478
1819.9.151 by Martin Hansson, Stewart Smith
Merge Revision revid:martin.hansson@oracle.com-20101007081311-zb72jgqjx2rs831z from MySQL InnoDB
479
      if (! table->records_are_comparable() || table->compare_records())
1 by brian
clean slate
480
      {
1235.1.9 by Brian Aker
Remove code around update batch handler (we have no engines supporting
481
        /* Non-batched update */
1672.3.6 by Brian Aker
First pass in encapsulating row
482
        error= table->cursor->updateRecord(table->getUpdateRecord(),
483
                                            table->getInsertRecord());
1552.1.3 by Brian Aker
Fixes the assertion bug on handling of auto increment (sort of worthless,
484
485
        table->auto_increment_field_not_null= false;
486
1 by brian
clean slate
487
        if (!error || error == HA_ERR_RECORD_IS_THE_SAME)
1861.6.1 by David Shrewsbury
Add method to undo adding records to a Statement message in case of multi-row statement failure.
488
        {
1 by brian
clean slate
489
          if (error != HA_ERR_RECORD_IS_THE_SAME)
490
            updated++;
491
          else
492
            error= 0;
1861.6.1 by David Shrewsbury
Add method to undo adding records to a Statement message in case of multi-row statement failure.
493
        }
494
        else if (! ignore ||
1208.3.2 by brian
Update for Cursor renaming.
495
                 table->cursor->is_fatal_error(error, HA_CHECK_DUP_KEY))
1861.6.1 by David Shrewsbury
Add method to undo adding records to a Statement message in case of multi-row statement failure.
496
        {
1 by brian
clean slate
497
          /*
498
            If (ignore && error is ignorable) we don't have to
499
            do anything; otherwise...
500
          */
501
          myf flags= 0;
502
1208.3.2 by brian
Update for Cursor renaming.
503
          if (table->cursor->is_fatal_error(error, HA_CHECK_DUP_KEY))
1 by brian
clean slate
504
            flags|= ME_FATALERROR; /* Other handler errors are fatal */
505
506
          prepare_record_for_error_message(error, table);
1861.6.1 by David Shrewsbury
Add method to undo adding records to a Statement message in case of multi-row statement failure.
507
          table->print_error(error,MYF(flags));
508
          error= 1;
509
          break;
510
        }
1 by brian
clean slate
511
      }
512
513
      if (!--limit && using_limit)
514
      {
1235.1.9 by Brian Aker
Remove code around update batch handler (we have no engines supporting
515
        error= -1;				// Simulate end of cursor
516
        break;
1 by brian
clean slate
517
      }
518
    }
519
    else
1208.3.2 by brian
Update for Cursor renaming.
520
      table->cursor->unlock_row();
520.1.22 by Brian Aker
Second pass of thd cleanup
521
    session->row_count++;
1 by brian
clean slate
522
  }
523
  dup_key_found= 0;
524
  /*
525
    Caching the killed status to pass as the arg to query event constuctor;
526
    The cached value can not change whereas the killed status can
527
    (externally) since this point and change of the latter won't affect
528
    binlogging.
51.2.2 by Patrick Galbraith
Removed DBUGs from
529
    It's assumed that if an error was set in combination with an effective
1 by brian
clean slate
530
    killed status then the error is due to killing.
531
  */
1910.2.8 by Brian Aker
Enapsulate Kill.
532
  killed_status= session->getKilled(); // get the status of the volatile
1 by brian
clean slate
533
  // simulated killing after the loop must be ineffective for binlogging
520.1.21 by Brian Aker
THD -> Session rename
534
  error= (killed_status == Session::NOT_KILLED)?  error : 1;
51.2.2 by Patrick Galbraith
Removed DBUGs from
535
1235.1.9 by Brian Aker
Remove code around update batch handler (we have no engines supporting
536
  updated-= dup_key_found;
1208.3.2 by brian
Update for Cursor renaming.
537
  table->cursor->try_semi_consistent_read(0);
1 by brian
clean slate
538
539
  if (!transactional_table && updated > 0)
1273.1.13 by Jay Pipes
Style cleanup around TransactionContext::modified_non_trans_table and dead code removal
540
    session->transaction.stmt.markModifiedNonTransData();
1 by brian
clean slate
541
1538 by Brian Aker
Code shuffle on ReadRecord
542
  info.end_read_record();
1 by brian
clean slate
543
  delete select;
520.1.22 by Brian Aker
Second pass of thd cleanup
544
  session->set_proc_info("end");
1208.3.2 by brian
Update for Cursor renaming.
545
  table->cursor->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
1 by brian
clean slate
546
547
  /*
548
    error < 0 means really no error at all: we processed all rows until the
549
    last one without error. error > 0 means an error (e.g. unique key
550
    violation and no IGNORE or REPLACE). error == 0 is also an error (if
551
    preparing the record or invoking before triggers fails). See
1405.3.5 by Jay Pipes
TransactionServices method names now meet code style guidelines.
552
    autocommitOrRollback(error>=0) and return(error>=0) below.
1 by brian
clean slate
553
    Sometimes we want to binlog even if we updated no rows, in case user used
554
    it to be sure master and slave are in same state.
555
  */
1273.1.13 by Jay Pipes
Style cleanup around TransactionContext::modified_non_trans_table and dead code removal
556
  if ((error < 0) || session->transaction.stmt.hasModifiedNonTransData())
1 by brian
clean slate
557
  {
1273.1.13 by Jay Pipes
Style cleanup around TransactionContext::modified_non_trans_table and dead code removal
558
    if (session->transaction.stmt.hasModifiedNonTransData())
559
      session->transaction.all.markModifiedNonTransData();
1 by brian
clean slate
560
  }
1273.1.13 by Jay Pipes
Style cleanup around TransactionContext::modified_non_trans_table and dead code removal
561
  assert(transactional_table || !updated || session->transaction.stmt.hasModifiedNonTransData());
520.1.22 by Brian Aker
Second pass of thd cleanup
562
  free_underlaid_joins(session, select_lex);
1 by brian
clean slate
563
564
  /* If LAST_INSERT_ID(X) was used, report X */
520.1.22 by Brian Aker
Second pass of thd cleanup
565
  id= session->arg_of_last_insert_id_function ?
566
    session->first_successful_insert_id_in_prev_stmt : 0;
1 by brian
clean slate
567
568
  if (error < 0)
569
  {
570
    char buff[STRING_BUFFER_USUAL_SIZE];
1366.1.12 by Siddharth Prakash Singh
more sprintf->snprintf
571
    snprintf(buff, sizeof(buff), ER(ER_UPDATE_INFO), (ulong) found, (ulong) updated,
520.1.22 by Brian Aker
Second pass of thd cleanup
572
	    (ulong) session->cuted_fields);
971.3.59 by Eric Day
Removed client_capabilities from session and pushed functionality into protocol plugin.
573
    session->row_count_func= updated;
1124.2.14 by Diego Medina
* On certain UPDATE and DELETE statements, drizzled failed an assert() in
574
    /**
575
     * Resetting the Diagnostic area to prevent
576
     * lp bug# 439719
577
     */
2239.1.4 by Olaf van der Spek
Refactor includes
578
    session->main_da().reset_diagnostics_area();
2148.5.2 by Brian Aker
Additional remove of current_session.
579
    session->my_ok((ulong) session->rowCount(), found, id, buff);
580
    session->status_var.updated_row_count+= session->rowCount();
1 by brian
clean slate
581
  }
1633.4.8 by Brian Aker
Update for count_cuted_fields.
582
  session->count_cuted_fields= CHECK_FIELD_ERROR_FOR_NULL;		/* calc cuted fields */
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
583
  session->setAbortOnWarning(false);
1126.10.25 by Padraig O'Sullivan
Updated calls to some dtrace probes to cast the parameter to const char *
584
  DRIZZLE_UPDATE_DONE((error >= 0 || session->is_error()), found, updated);
1126.10.17 by Padraig O'Sullivan
Added calls to the update related dtrace probes.
585
  return ((error >= 0 || session->is_error()) ? 1 : 0);
1 by brian
clean slate
586
587
err:
2049.2.1 by Stewart Smith
doStartTableScan() result not checked.
588
  if (error != 0)
589
    table->print_error(error,MYF(0));
590
1 by brian
clean slate
591
  delete select;
520.1.22 by Brian Aker
Second pass of thd cleanup
592
  free_underlaid_joins(session, select_lex);
1 by brian
clean slate
593
  if (table->key_read)
594
  {
595
    table->key_read=0;
1208.3.2 by brian
Update for Cursor renaming.
596
    table->cursor->extra(HA_EXTRA_NO_KEYREAD);
1 by brian
clean slate
597
  }
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
598
  session->setAbortOnWarning(false);
1 by brian
clean slate
599
1126.10.17 by Padraig O'Sullivan
Added calls to the update related dtrace probes.
600
  DRIZZLE_UPDATE_DONE(1, 0, 0);
601
  return 1;
1 by brian
clean slate
602
}
603
604
/*
605
  Prepare items in UPDATE statement
606
607
  SYNOPSIS
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
608
    prepare_update()
520.1.22 by Brian Aker
Second pass of thd cleanup
609
    session			- thread handler
1 by brian
clean slate
610
    table_list		- global/local table list
611
    conds		- conditions
1273.2.8 by Stewart Smith
fix accidental mangling of comment: s/order_st BY/ORDER BY/. in sql_update.cc
612
    order_num		- number of ORDER BY list entries
613
    order		- ORDER BY clause list
1 by brian
clean slate
614
615
  RETURN VALUE
56 by brian
Next pass of true/false update.
616
    false OK
617
    true  error
1 by brian
clean slate
618
*/
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
619
bool prepare_update(Session *session, TableList *table_list,
1892.3.3 by tdavies
struct order_st changed and renamed to c++ class named:Order
620
			 Item **conds, uint32_t order_num, Order *order)
1 by brian
clean slate
621
{
622
  List<Item> all_fields;
2227.4.8 by Olaf van der Spek
Session::lex()
623
  Select_Lex *select_lex= &session->lex().select_lex;
1 by brian
clean slate
624
2227.4.8 by Olaf van der Spek
Session::lex()
625
  session->lex().allow_sum_func= 0;
1 by brian
clean slate
626
2318.6.31 by Olaf van der Spek
Refactor
627
  if (setup_tables_and_check_access(session, &select_lex->context, &select_lex->top_join_list, table_list, &select_lex->leaf_tables, false) ||
628
      session->setup_conds(table_list, conds))
629
      return true;
630
  select_lex->setup_ref_array(session, order_num);
631
  if (setup_order(session, select_lex->ref_pointer_array, table_list, all_fields, all_fields, order))
836 by Brian Aker
Fixed session call from function to method.
632
    return true;
1 by brian
clean slate
633
634
  /* Check that we are not using table that we are updating in a sub select */
2318.8.6 by Olaf van der Spek
Add const
635
  if (unique_table(table_list, table_list->next_global))
1 by brian
clean slate
636
  {
2318.8.6 by Olaf van der Spek
Add const
637
    my_error(ER_UPDATE_TABLE_USED, MYF(0), table_list->getTableName());
638
    return true;
1 by brian
clean slate
639
  }
177.1.1 by brian
Removed dead code around prep.
640
836 by Brian Aker
Fixed session call from function to method.
641
  return false;
1 by brian
clean slate
642
}
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
643
644
} /* namespace drizzled */