~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
/* Insert of records */
18
2173.2.1 by Monty Taylor
Fixes incorrect usage of include
19
#include <config.h>
1502.3.1 by iwamatsu at nigauri
Add cstdio include to files needing it. Fixes the build on some debian
20
#include <cstdio>
243.1.17 by Jay Pipes
FINAL PHASE removal of mysql_priv.h (Bye, bye my friend.)
21
#include <drizzled/sql_select.h>
575.4.7 by Monty Taylor
More header cleanup.
22
#include <drizzled/show.h>
549 by Monty Taylor
Took gettext.h out of header files.
23
#include <drizzled/error.h>
584.4.4 by Monty Taylor
Split out Name_resolution_context.
24
#include <drizzled/name_resolution_context_state.h>
520.7.1 by Monty Taylor
Moved hash.c to drizzled.
25
#include <drizzled/probes.h>
584.1.15 by Monty Taylor
The mega-patch from hell. Renamed sql_class to session (since that's what it is) and removed it and field and table from common_includes.
26
#include <drizzled/sql_base.h>
27
#include <drizzled/sql_load.h>
1999.4.9 by Brian Aker
Created EPOCH
28
#include <drizzled/field/epoch.h>
670.2.4 by Monty Taylor
Removed more stuff from the headers.
29
#include <drizzled/lock.h>
2173.2.1 by Monty Taylor
Fixes incorrect usage of include
30
#include <drizzled/sql_table.h>
31
#include <drizzled/pthread_globals.h>
32
#include <drizzled/transaction_services.h>
33
#include <drizzled/plugin/transactional_storage_engine.h>
2154.2.17 by Brian Aker
Additional removal of session
34
#include <drizzled/select_insert.h>
35
#include <drizzled/select_create.h>
2173.2.1 by Monty Taylor
Fixes incorrect usage of include
36
#include <drizzled/table/shell.h>
2198.1.1 by Olaf van der Spek
Remove unnecessary alter* includes
37
#include <drizzled/alter_info.h>
2227.4.3 by Olaf van der Spek
Remove unnecessary statement.h include
38
#include <drizzled/sql_parse.h>
1859.2.9 by Brian Aker
We add a "shell" table type, used only during field creation.
39
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
40
namespace drizzled
41
{
1 by brian
clean slate
42
1241.9.32 by Monty Taylor
Moved global myisam and heap pointers out of server_includes.
43
extern plugin::StorageEngine *heap_engine;
44
extern plugin::StorageEngine *myisam_engine;
45
1 by brian
clean slate
46
/*
47
  Check if insert fields are correct.
48
49
  SYNOPSIS
50
    check_insert_fields()
520.1.22 by Brian Aker
Second pass of thd cleanup
51
    session                         The current thread.
1 by brian
clean slate
52
    table                       The table for insert.
53
    fields                      The insert fields.
54
    values                      The insert values.
55
    check_unique                If duplicate values should be rejected.
56
57
  NOTE
58
    Clears TIMESTAMP_AUTO_SET_ON_INSERT from table->timestamp_field_type
59
    or leaves it as is, depending on if timestamp should be updated or
60
    not.
61
62
  RETURN
63
    0           OK
64
    -1          Error
65
*/
66
520.1.22 by Brian Aker
Second pass of thd cleanup
67
static int check_insert_fields(Session *session, TableList *table_list,
1 by brian
clean slate
68
                               List<Item> &fields, List<Item> &values,
77.1.45 by Monty Taylor
Warning fixes.
69
                               bool check_unique,
779.1.27 by Monty Taylor
Got rid of __attribute__((unused)) and the like from the .cc files.
70
                               table_map *)
1 by brian
clean slate
71
{
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
72
  Table *table= table_list->table;
1 by brian
clean slate
73
2183.2.19 by Olaf van der Spek
Use List::size()
74
  if (fields.size() == 0 && values.size() != 0)
1 by brian
clean slate
75
  {
2183.2.19 by Olaf van der Spek
Use List::size()
76
    if (values.size() != table->getShare()->sizeFields())
1 by brian
clean slate
77
    {
78
      my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), 1L);
79
      return -1;
80
    }
81
    clear_timestamp_auto_bits(table->timestamp_field_type,
82
                              TIMESTAMP_AUTO_SET_ON_INSERT);
83
    /*
84
      No fields are provided so all fields must be provided in the values.
85
      Thus we set all bits in the write set.
86
    */
1005.2.12 by Monty Taylor
Moved some things to the API.
87
    table->setWriteSet();
1 by brian
clean slate
88
  }
89
  else
90
  {						// Part field list
2227.4.8 by Olaf van der Spek
Session::lex()
91
    Select_Lex *select_lex= &session->lex().select_lex;
1 by brian
clean slate
92
    Name_resolution_context *context= &select_lex->context;
93
    Name_resolution_context_state ctx_state;
94
    int res;
95
2183.2.19 by Olaf van der Spek
Use List::size()
96
    if (fields.size() != values.size())
1 by brian
clean slate
97
    {
98
      my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), 1L);
99
      return -1;
100
    }
101
520.1.22 by Brian Aker
Second pass of thd cleanup
102
    session->dup_field= 0;
1 by brian
clean slate
103
104
    /* Save the state of the current name resolution context. */
105
    ctx_state.save_state(context, table_list);
106
107
    /*
108
      Perform name resolution only in the first table - 'table_list',
109
      which is the table that is inserted into.
110
    */
111
    table_list->next_local= 0;
112
    context->resolve_in_table_list_only(table_list);
520.1.22 by Brian Aker
Second pass of thd cleanup
113
    res= setup_fields(session, 0, fields, MARK_COLUMNS_WRITE, 0, 0);
1 by brian
clean slate
114
115
    /* Restore the current context. */
116
    ctx_state.restore_state(context, table_list);
117
118
    if (res)
119
      return -1;
120
520.1.22 by Brian Aker
Second pass of thd cleanup
121
    if (check_unique && session->dup_field)
1 by brian
clean slate
122
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
123
      my_error(ER_FIELD_SPECIFIED_TWICE, MYF(0), session->dup_field->field_name);
1 by brian
clean slate
124
      return -1;
125
    }
126
    if (table->timestamp_field)	// Don't automaticly set timestamp if used
127
    {
1009 by Brian Aker
Merge of Monty
128
      if (table->timestamp_field->isWriteSet())
1607 by Brian Aker
Cursor now fully handles the update to timestamp for the engine.
129
      {
1 by brian
clean slate
130
        clear_timestamp_auto_bits(table->timestamp_field_type,
131
                                  TIMESTAMP_AUTO_SET_ON_INSERT);
1607 by Brian Aker
Cursor now fully handles the update to timestamp for the engine.
132
      }
1 by brian
clean slate
133
      else
134
      {
1999.4.2 by Brian Aker
Encapsulate the field's position.
135
        table->setWriteSet(table->timestamp_field->position());
1 by brian
clean slate
136
      }
137
    }
138
  }
139
140
  return 0;
141
}
142
143
144
/*
145
  Check update fields for the timestamp field.
146
147
  SYNOPSIS
148
    check_update_fields()
520.1.22 by Brian Aker
Second pass of thd cleanup
149
    session                         The current thread.
1 by brian
clean slate
150
    insert_table_list           The insert table list.
151
    table                       The table for update.
152
    update_fields               The update fields.
153
154
  NOTE
155
    If the update fields include the timestamp field,
156
    remove TIMESTAMP_AUTO_SET_ON_UPDATE from table->timestamp_field_type.
157
158
  RETURN
159
    0           OK
160
    -1          Error
161
*/
162
520.1.22 by Brian Aker
Second pass of thd cleanup
163
static int check_update_fields(Session *session, TableList *insert_table_list,
77.1.45 by Monty Taylor
Warning fixes.
164
                               List<Item> &update_fields,
779.1.27 by Monty Taylor
Got rid of __attribute__((unused)) and the like from the .cc files.
165
                               table_map *)
1 by brian
clean slate
166
{
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
167
  Table *table= insert_table_list->table;
199 by Brian Aker
my_bool...
168
  bool timestamp_mark= false;
1 by brian
clean slate
169
170
  if (table->timestamp_field)
171
  {
172
    /*
173
      Unmark the timestamp field so that we can check if this is modified
174
      by update_fields
175
    */
1999.4.2 by Brian Aker
Encapsulate the field's position.
176
    timestamp_mark= table->write_set->test(table->timestamp_field->position());
177
    table->write_set->reset(table->timestamp_field->position());
1 by brian
clean slate
178
  }
179
180
  /* Check the fields we are going to modify */
520.1.22 by Brian Aker
Second pass of thd cleanup
181
  if (setup_fields(session, 0, update_fields, MARK_COLUMNS_WRITE, 0, 0))
1 by brian
clean slate
182
    return -1;
183
184
  if (table->timestamp_field)
185
  {
186
    /* Don't set timestamp column if this is modified. */
1009 by Brian Aker
Merge of Monty
187
    if (table->timestamp_field->isWriteSet())
1607 by Brian Aker
Cursor now fully handles the update to timestamp for the engine.
188
    {
1 by brian
clean slate
189
      clear_timestamp_auto_bits(table->timestamp_field_type,
190
                                TIMESTAMP_AUTO_SET_ON_UPDATE);
1607 by Brian Aker
Cursor now fully handles the update to timestamp for the engine.
191
    }
192
1 by brian
clean slate
193
    if (timestamp_mark)
1607 by Brian Aker
Cursor now fully handles the update to timestamp for the engine.
194
    {
1999.4.2 by Brian Aker
Encapsulate the field's position.
195
      table->setWriteSet(table->timestamp_field->position());
1607 by Brian Aker
Cursor now fully handles the update to timestamp for the engine.
196
    }
1 by brian
clean slate
197
  }
198
  return 0;
199
}
200
201
202
/**
203
  Upgrade table-level lock of INSERT statement to TL_WRITE if
204
  a more concurrent lock is infeasible for some reason. This is
205
  necessary for engines without internal locking support (MyISAM).
206
  An engine with internal locking implementation might later
207
  downgrade the lock in handler::store_lock() method.
208
*/
209
210
static
779.1.27 by Monty Taylor
Got rid of __attribute__((unused)) and the like from the .cc files.
211
void upgrade_lock_type(Session *,
77.1.45 by Monty Taylor
Warning fixes.
212
                       thr_lock_type *lock_type,
1 by brian
clean slate
213
                       enum_duplicates duplic,
779.1.27 by Monty Taylor
Got rid of __attribute__((unused)) and the like from the .cc files.
214
                       bool )
1 by brian
clean slate
215
{
216
  if (duplic == DUP_UPDATE ||
217
      (duplic == DUP_REPLACE && *lock_type == TL_WRITE_CONCURRENT_INSERT))
218
  {
219
    *lock_type= TL_WRITE_DEFAULT;
220
    return;
221
  }
222
}
223
224
225
/**
226
  INSERT statement implementation
227
228
  @note Like implementations of other DDL/DML in MySQL, this function
229
  relies on the caller to close the thread tables. This is done in the
230
  end of dispatch_command().
231
*/
232
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
233
bool insert_query(Session *session,TableList *table_list,
1 by brian
clean slate
234
                  List<Item> &fields,
235
                  List<List_item> &values_list,
236
                  List<Item> &update_fields,
237
                  List<Item> &update_values,
238
                  enum_duplicates duplic,
239
		  bool ignore)
240
{
241
  int error;
163 by Brian Aker
Merge Monty's code.
242
  bool transactional_table, joins_freed= false;
1 by brian
clean slate
243
  bool changed;
482 by Brian Aker
Remove uint.
244
  uint32_t value_count;
1 by brian
clean slate
245
  ulong counter = 1;
151 by Brian Aker
Ulonglong to uint64_t
246
  uint64_t id;
1711.6.1 by Brian Aker
Style on structure cleanup
247
  CopyInfo info;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
248
  Table *table= 0;
2183.2.12 by Olaf van der Spek
Use List::begin()
249
  List<List_item>::iterator its(values_list.begin());
1 by brian
clean slate
250
  List_item *values;
251
  Name_resolution_context *context;
252
  Name_resolution_context_state ctx_state;
253
  thr_lock_type lock_type;
254
  Item *unused_conds= 0;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
255
1 by brian
clean slate
256
257
  /*
258
    Upgrade lock type if the requested lock is incompatible with
259
    the current connection mode or table operation.
260
  */
520.1.22 by Brian Aker
Second pass of thd cleanup
261
  upgrade_lock_type(session, &table_list->lock_type, duplic,
2183.2.19 by Olaf van der Spek
Use List::size()
262
                    values_list.size() > 1);
1 by brian
clean slate
263
1109.1.3 by Brian Aker
Move names around a bit (to align similar methods)
264
  if (session->openTablesLock(table_list))
1126.10.12 by Padraig O'Sullivan
Added calls to the dtrace probes related to insertion.
265
  {
266
    DRIZZLE_INSERT_DONE(1, 0);
1109.1.2 by Brian Aker
More from the table patch
267
    return true;
1126.10.12 by Padraig O'Sullivan
Added calls to the dtrace probes related to insertion.
268
  }
1 by brian
clean slate
269
270
  lock_type= table_list->lock_type;
271
520.1.22 by Brian Aker
Second pass of thd cleanup
272
  session->set_proc_info("init");
273
  session->used_tables=0;
1 by brian
clean slate
274
  values= its++;
2183.2.19 by Olaf van der Spek
Use List::size()
275
  value_count= values->size();
1 by brian
clean slate
276
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
277
  if (prepare_insert(session, table_list, table, fields, values,
1 by brian
clean slate
278
			   update_fields, update_values, duplic, &unused_conds,
163 by Brian Aker
Merge Monty's code.
279
                           false,
2183.2.19 by Olaf van der Spek
Use List::size()
280
                           (fields.size() || !value_count ||
1 by brian
clean slate
281
                            (0) != 0), !ignore))
1864.3.19 by Brian Aker
Update to remove additional goto.
282
  {
283
    if (table != NULL)
284
      table->cursor->ha_release_auto_increment();
285
    if (!joins_freed)
2227.4.8 by Olaf van der Spek
Session::lex()
286
      free_underlaid_joins(session, &session->lex().select_lex);
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
287
    session->setAbortOnWarning(false);
1864.3.19 by Brian Aker
Update to remove additional goto.
288
    DRIZZLE_INSERT_DONE(1, 0);
289
    return true;
290
  }
1 by brian
clean slate
291
292
  /* mysql_prepare_insert set table_list->table if it was not set */
293
  table= table_list->table;
294
2227.4.8 by Olaf van der Spek
Session::lex()
295
  context= &session->lex().select_lex.context;
1 by brian
clean slate
296
  /*
297
    These three asserts test the hypothesis that the resetting of the name
298
    resolution context below is not necessary at all since the list of local
299
    tables for INSERT always consists of one table.
300
  */
51.2.2 by Patrick Galbraith
Removed DBUGs from
301
  assert(!table_list->next_local);
302
  assert(!context->table_list->next_local);
303
  assert(!context->first_name_resolution_table->next_name_resolution_table);
1 by brian
clean slate
304
305
  /* Save the state of the current name resolution context. */
306
  ctx_state.save_state(context, table_list);
307
308
  /*
309
    Perform name resolution only in the first table - 'table_list',
310
    which is the table that is inserted into.
311
  */
312
  table_list->next_local= 0;
313
  context->resolve_in_table_list_only(table_list);
314
315
  while ((values= its++))
316
  {
317
    counter++;
2183.2.19 by Olaf van der Spek
Use List::size()
318
    if (values->size() != value_count)
1 by brian
clean slate
319
    {
320
      my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), counter);
1864.3.19 by Brian Aker
Update to remove additional goto.
321
322
      if (table != NULL)
323
        table->cursor->ha_release_auto_increment();
324
      if (!joins_freed)
2227.4.8 by Olaf van der Spek
Session::lex()
325
        free_underlaid_joins(session, &session->lex().select_lex);
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
326
      session->setAbortOnWarning(false);
1864.3.19 by Brian Aker
Update to remove additional goto.
327
      DRIZZLE_INSERT_DONE(1, 0);
328
329
      return true;
1 by brian
clean slate
330
    }
520.1.22 by Brian Aker
Second pass of thd cleanup
331
    if (setup_fields(session, 0, *values, MARK_COLUMNS_READ, 0, 0))
1864.3.19 by Brian Aker
Update to remove additional goto.
332
    {
333
      if (table != NULL)
334
        table->cursor->ha_release_auto_increment();
335
      if (!joins_freed)
2227.4.8 by Olaf van der Spek
Session::lex()
336
        free_underlaid_joins(session, &session->lex().select_lex);
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
337
      session->setAbortOnWarning(false);
1864.3.19 by Brian Aker
Update to remove additional goto.
338
      DRIZZLE_INSERT_DONE(1, 0);
339
      return true;
340
    }
1 by brian
clean slate
341
  }
2183.2.7 by Olaf van der Spek
x
342
  its= values_list.begin();
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
343
1 by brian
clean slate
344
  /* Restore the current context. */
345
  ctx_state.restore_state(context, table_list);
346
347
  /*
1208.3.2 by brian
Update for Cursor renaming.
348
    Fill in the given fields and dump it to the table cursor
1 by brian
clean slate
349
  */
350
  info.ignore= ignore;
351
  info.handle_duplicates=duplic;
352
  info.update_fields= &update_fields;
353
  info.update_values= &update_values;
354
355
  /*
356
    Count warnings for all inserts.
357
    For single line insert, generate an error if try to set a NOT NULL field
358
    to NULL.
359
  */
1637 by Brian Aker
Merge in changes to call error on bad data input.
360
  session->count_cuted_fields= ignore ? CHECK_FIELD_WARN : CHECK_FIELD_ERROR_FOR_NULL;
361
520.1.22 by Brian Aker
Second pass of thd cleanup
362
  session->cuted_fields = 0L;
1 by brian
clean slate
363
  table->next_number_field=table->found_next_number_field;
364
365
  error=0;
520.1.22 by Brian Aker
Second pass of thd cleanup
366
  session->set_proc_info("update");
1 by brian
clean slate
367
  if (duplic == DUP_REPLACE)
1208.3.2 by brian
Update for Cursor renaming.
368
    table->cursor->extra(HA_EXTRA_WRITE_CAN_REPLACE);
1 by brian
clean slate
369
  if (duplic == DUP_UPDATE)
1208.3.2 by brian
Update for Cursor renaming.
370
    table->cursor->extra(HA_EXTRA_INSERT_WITH_UPDATE);
1 by brian
clean slate
371
  {
372
    if (duplic != DUP_ERROR || ignore)
1208.3.2 by brian
Update for Cursor renaming.
373
      table->cursor->extra(HA_EXTRA_IGNORE_DUP_KEY);
2183.2.19 by Olaf van der Spek
Use List::size()
374
    table->cursor->ha_start_bulk_insert(values_list.size());
1 by brian
clean slate
375
  }
376
377
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
378
  session->setAbortOnWarning(not ignore);
1 by brian
clean slate
379
380
  table->mark_columns_needed_for_insert();
381
382
  while ((values= its++))
383
  {
2183.2.19 by Olaf van der Spek
Use List::size()
384
    if (fields.size() || !value_count)
1 by brian
clean slate
385
    {
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
386
      table->restoreRecordAsDefault();	// Get empty record
1235.1.11 by Brian Aker
Small cleanups, did in MERGE table only engine flag.
387
      if (fill_record(session, fields, *values))
1 by brian
clean slate
388
      {
2183.2.19 by Olaf van der Spek
Use List::size()
389
	if (values_list.size() != 1 && ! session->is_error())
1 by brian
clean slate
390
	{
391
	  info.records++;
392
	  continue;
393
	}
394
	/*
520.1.22 by Brian Aker
Second pass of thd cleanup
395
	  TODO: set session->abort_on_warning if values_list.elements == 1
1 by brian
clean slate
396
	  and check that all items return warning in case of problem with
397
	  storing field.
398
        */
399
	error=1;
400
	break;
401
      }
402
    }
403
    else
404
    {
1222.3.1 by Stewart Smith
mi_write valgrind warning in alias test
405
      table->restoreRecordAsDefault();	// Get empty record
406
1578.2.16 by Brian Aker
Merge in change to getTable() to private the field objects.
407
      if (fill_record(session, table->getFields(), *values))
1 by brian
clean slate
408
      {
2183.2.19 by Olaf van der Spek
Use List::size()
409
	if (values_list.size() != 1 && ! session->is_error())
1 by brian
clean slate
410
	{
411
	  info.records++;
412
	  continue;
413
	}
414
	error=1;
415
	break;
416
      }
417
    }
418
873.2.11 by Monty Taylor
call ha_release_temporary_latches
419
    // Release latches in case bulk insert takes a long time
1273.1.15 by Jay Pipes
This patch completes the first step in the splitting of
420
    plugin::TransactionalStorageEngine::releaseTemporaryLatches(session);
873.2.11 by Monty Taylor
call ha_release_temporary_latches
421
520.1.22 by Brian Aker
Second pass of thd cleanup
422
    error=write_record(session, table ,&info);
1 by brian
clean slate
423
    if (error)
424
      break;
520.1.22 by Brian Aker
Second pass of thd cleanup
425
    session->row_count++;
1 by brian
clean slate
426
  }
427
2227.4.8 by Olaf van der Spek
Session::lex()
428
  free_underlaid_joins(session, &session->lex().select_lex);
163 by Brian Aker
Merge Monty's code.
429
  joins_freed= true;
1 by brian
clean slate
430
431
  /*
432
    Now all rows are inserted.  Time to update logs and sends response to
433
    user
434
  */
435
  {
436
    /*
437
      Do not do this release if this is a delayed insert, it would steal
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
438
      auto_inc values from the delayed_insert thread as they share Table.
1 by brian
clean slate
439
    */
1208.3.2 by brian
Update for Cursor renaming.
440
    table->cursor->ha_release_auto_increment();
441
    if (table->cursor->ha_end_bulk_insert() && !error)
1 by brian
clean slate
442
    {
1241.9.57 by Monty Taylor
Oy. Bigger change than I normally like - but this stuff is all intertwined.
443
      table->print_error(errno,MYF(0));
1 by brian
clean slate
444
      error=1;
445
    }
446
    if (duplic != DUP_ERROR || ignore)
1208.3.2 by brian
Update for Cursor renaming.
447
      table->cursor->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
1 by brian
clean slate
448
1208.3.2 by brian
Update for Cursor renaming.
449
    transactional_table= table->cursor->has_transactions();
1 by brian
clean slate
450
831.1.1 by Brian Aker
Cleanup of DELAYED INSERT bits (aka... it is just now a hint to the engine).
451
    changed= (info.copied || info.deleted || info.updated);
1273.1.13 by Jay Pipes
Style cleanup around TransactionContext::modified_non_trans_table and dead code removal
452
    if ((changed && error <= 0) || session->transaction.stmt.hasModifiedNonTransData())
1 by brian
clean slate
453
    {
1273.1.13 by Jay Pipes
Style cleanup around TransactionContext::modified_non_trans_table and dead code removal
454
      if (session->transaction.stmt.hasModifiedNonTransData())
455
	session->transaction.all.markModifiedNonTransData();
1 by brian
clean slate
456
    }
1273.1.13 by Jay Pipes
Style cleanup around TransactionContext::modified_non_trans_table and dead code removal
457
    assert(transactional_table || !changed || session->transaction.stmt.hasModifiedNonTransData());
1 by brian
clean slate
458
459
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
460
  session->set_proc_info("end");
1 by brian
clean slate
461
  /*
462
    We'll report to the client this id:
463
    - if the table contains an autoincrement column and we successfully
464
    inserted an autogenerated value, the autogenerated value.
465
    - if the table contains no autoincrement column and LAST_INSERT_ID(X) was
466
    called, X.
467
    - if the table contains an autoincrement column, and some rows were
468
    inserted, the id of the last "inserted" row (if IGNORE, that value may not
469
    have been really inserted but ignored).
470
  */
520.1.22 by Brian Aker
Second pass of thd cleanup
471
  id= (session->first_successful_insert_id_in_cur_stmt > 0) ?
472
    session->first_successful_insert_id_in_cur_stmt :
473
    (session->arg_of_last_insert_id_function ?
474
     session->first_successful_insert_id_in_prev_stmt :
1 by brian
clean slate
475
     ((table->next_number_field && info.copied) ?
476
     table->next_number_field->val_int() : 0));
477
  table->next_number_field=0;
520.1.22 by Brian Aker
Second pass of thd cleanup
478
  session->count_cuted_fields= CHECK_FIELD_IGNORE;
163 by Brian Aker
Merge Monty's code.
479
  table->auto_increment_field_not_null= false;
1 by brian
clean slate
480
  if (duplic == DUP_REPLACE)
1208.3.2 by brian
Update for Cursor renaming.
481
    table->cursor->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
1 by brian
clean slate
482
483
  if (error)
1864.3.19 by Brian Aker
Update to remove additional goto.
484
  {
485
    if (table != NULL)
486
      table->cursor->ha_release_auto_increment();
487
    if (!joins_freed)
2227.4.8 by Olaf van der Spek
Session::lex()
488
      free_underlaid_joins(session, &session->lex().select_lex);
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
489
    session->setAbortOnWarning(false);
1864.3.19 by Brian Aker
Update to remove additional goto.
490
    DRIZZLE_INSERT_DONE(1, 0);
491
    return true;
492
  }
493
2183.2.19 by Olaf van der Spek
Use List::size()
494
  if (values_list.size() == 1 && (!(session->options & OPTION_WARNINGS) ||
520.1.22 by Brian Aker
Second pass of thd cleanup
495
				    !session->cuted_fields))
1 by brian
clean slate
496
  {
971.3.59 by Eric Day
Removed client_capabilities from session and pushed functionality into protocol plugin.
497
    session->row_count_func= info.copied + info.deleted + info.updated;
2148.5.2 by Brian Aker
Additional remove of current_session.
498
    session->my_ok((ulong) session->rowCount(),
971.3.59 by Eric Day
Removed client_capabilities from session and pushed functionality into protocol plugin.
499
                   info.copied + info.deleted + info.touched, id);
1 by brian
clean slate
500
  }
501
  else
502
  {
503
    char buff[160];
504
    if (ignore)
1366.1.11 by Siddharth Prakash Singh
sprintf->snprintf continued
505
      snprintf(buff, sizeof(buff), ER(ER_INSERT_INFO), (ulong) info.records,
520.1.22 by Brian Aker
Second pass of thd cleanup
506
              (ulong) (info.records - info.copied), (ulong) session->cuted_fields);
1 by brian
clean slate
507
    else
1366.1.11 by Siddharth Prakash Singh
sprintf->snprintf continued
508
      snprintf(buff, sizeof(buff), ER(ER_INSERT_INFO), (ulong) info.records,
971.3.59 by Eric Day
Removed client_capabilities from session and pushed functionality into protocol plugin.
509
	      (ulong) (info.deleted + info.updated), (ulong) session->cuted_fields);
510
    session->row_count_func= info.copied + info.deleted + info.updated;
2148.5.2 by Brian Aker
Additional remove of current_session.
511
    session->my_ok((ulong) session->rowCount(),
971.3.59 by Eric Day
Removed client_capabilities from session and pushed functionality into protocol plugin.
512
                   info.copied + info.deleted + info.touched, id, buff);
1 by brian
clean slate
513
  }
2148.5.2 by Brian Aker
Additional remove of current_session.
514
  session->status_var.inserted_row_count+= session->rowCount();
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
515
  session->setAbortOnWarning(false);
2148.5.2 by Brian Aker
Additional remove of current_session.
516
  DRIZZLE_INSERT_DONE(0, session->rowCount());
1864.3.19 by Brian Aker
Update to remove additional goto.
517
1126.10.12 by Padraig O'Sullivan
Added calls to the dtrace probes related to insertion.
518
  return false;
1 by brian
clean slate
519
}
520
521
522
/*
523
  Check if table can be updated
524
525
  SYNOPSIS
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
526
     prepare_insert_check_table()
520.1.22 by Brian Aker
Second pass of thd cleanup
527
     session		Thread handle
1 by brian
clean slate
528
     table_list		Table list
529
     fields		List of fields to be updated
530
     where		Pointer to where clause
531
     select_insert      Check is making for SELECT ... INSERT
532
533
   RETURN
163 by Brian Aker
Merge Monty's code.
534
     false ok
535
     true  ERROR
1 by brian
clean slate
536
*/
537
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
538
static bool prepare_insert_check_table(Session *session, TableList *table_list,
779.1.27 by Monty Taylor
Got rid of __attribute__((unused)) and the like from the .cc files.
539
                                             List<Item> &,
1 by brian
clean slate
540
                                             bool select_insert)
541
{
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
542
1 by brian
clean slate
543
544
  /*
545
     first table in list is the one we'll INSERT into, requires INSERT_ACL.
546
     all others require SELECT_ACL only. the ACL requirement below is for
547
     new leaves only anyway (view-constituents), so check for SELECT rather
548
     than INSERT.
549
  */
550
2227.4.8 by Olaf van der Spek
Session::lex()
551
  if (setup_tables_and_check_access(session, &session->lex().select_lex.context,
552
                                    &session->lex().select_lex.top_join_list,
1 by brian
clean slate
553
                                    table_list,
2227.4.8 by Olaf van der Spek
Session::lex()
554
                                    &session->lex().select_lex.leaf_tables,
1 by brian
clean slate
555
                                    select_insert))
163 by Brian Aker
Merge Monty's code.
556
    return(true);
1 by brian
clean slate
557
163 by Brian Aker
Merge Monty's code.
558
  return(false);
1 by brian
clean slate
559
}
560
561
562
/*
563
  Prepare items in INSERT statement
564
565
  SYNOPSIS
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
566
    prepare_insert()
520.1.22 by Brian Aker
Second pass of thd cleanup
567
    session			Thread handler
1 by brian
clean slate
568
    table_list	        Global/local table list
569
    table		Table to insert into (can be NULL if table should
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
570
			be taken from table_list->table)
1 by brian
clean slate
571
    where		Where clause (for insert ... select)
163 by Brian Aker
Merge Monty's code.
572
    select_insert	true if INSERT ... SELECT statement
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
573
    check_fields        true if need to check that all INSERT fields are
1 by brian
clean slate
574
                        given values.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
575
    abort_on_warning    whether to report if some INSERT field is not
163 by Brian Aker
Merge Monty's code.
576
                        assigned as an error (true) or as a warning (false).
1 by brian
clean slate
577
578
  TODO (in far future)
579
    In cases of:
580
    INSERT INTO t1 SELECT a, sum(a) as sum1 from t2 GROUP BY a
581
    ON DUPLICATE KEY ...
582
    we should be able to refer to sum1 in the ON DUPLICATE KEY part
583
584
  WARNING
585
    You MUST set table->insert_values to 0 after calling this function
586
    before releasing the table object.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
587
1 by brian
clean slate
588
  RETURN VALUE
163 by Brian Aker
Merge Monty's code.
589
    false OK
590
    true  error
1 by brian
clean slate
591
*/
592
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
593
bool prepare_insert(Session *session, TableList *table_list,
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
594
                          Table *table, List<Item> &fields, List_item *values,
1 by brian
clean slate
595
                          List<Item> &update_fields, List<Item> &update_values,
596
                          enum_duplicates duplic,
779.1.27 by Monty Taylor
Got rid of __attribute__((unused)) and the like from the .cc files.
597
                          COND **,
77.1.45 by Monty Taylor
Warning fixes.
598
                          bool select_insert,
1 by brian
clean slate
599
                          bool check_fields, bool abort_on_warning)
600
{
2227.4.8 by Olaf van der Spek
Session::lex()
601
  Select_Lex *select_lex= &session->lex().select_lex;
1 by brian
clean slate
602
  Name_resolution_context *context= &select_lex->context;
603
  Name_resolution_context_state ctx_state;
604
  bool insert_into_view= (0 != 0);
605
  bool res= 0;
606
  table_map map= 0;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
607
1 by brian
clean slate
608
  /* INSERT should have a SELECT or VALUES clause */
51.2.2 by Patrick Galbraith
Removed DBUGs from
609
  assert (!select_insert || !values);
1 by brian
clean slate
610
611
  /*
612
    For subqueries in VALUES() we should not see the table in which we are
613
    inserting (for INSERT ... SELECT this is done by changing table_list,
846 by Brian Aker
Removing on typedeffed class.
614
    because INSERT ... SELECT share Select_Lex it with SELECT.
1 by brian
clean slate
615
  */
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
616
  if (not select_insert)
1 by brian
clean slate
617
  {
848 by Brian Aker
typdef class removal (just... use the name of the class).
618
    for (Select_Lex_Unit *un= select_lex->first_inner_unit();
1 by brian
clean slate
619
         un;
620
         un= un->next_unit())
621
    {
846 by Brian Aker
Removing on typedeffed class.
622
      for (Select_Lex *sl= un->first_select();
1 by brian
clean slate
623
           sl;
624
           sl= sl->next_select())
625
      {
626
        sl->context.outer_context= 0;
627
      }
628
    }
629
  }
630
631
  if (duplic == DUP_UPDATE)
632
  {
633
    /* it should be allocated before Item::fix_fields() */
520.1.22 by Brian Aker
Second pass of thd cleanup
634
    if (table_list->set_insert_values(session->mem_root))
163 by Brian Aker
Merge Monty's code.
635
      return(true);
1 by brian
clean slate
636
  }
637
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
638
  if (prepare_insert_check_table(session, table_list, fields, select_insert))
163 by Brian Aker
Merge Monty's code.
639
    return(true);
1 by brian
clean slate
640
641
642
  /* Prepare the fields in the statement. */
643
  if (values)
644
  {
645
    /* if we have INSERT ... VALUES () we cannot have a GROUP BY clause */
51.2.2 by Patrick Galbraith
Removed DBUGs from
646
    assert (!select_lex->group_list.elements);
1 by brian
clean slate
647
648
    /* Save the state of the current name resolution context. */
649
    ctx_state.save_state(context, table_list);
650
651
    /*
652
      Perform name resolution only in the first table - 'table_list',
653
      which is the table that is inserted into.
654
     */
655
    table_list->next_local= 0;
656
    context->resolve_in_table_list_only(table_list);
657
520.1.22 by Brian Aker
Second pass of thd cleanup
658
    res= check_insert_fields(session, context->table_list, fields, *values,
1 by brian
clean slate
659
                             !insert_into_view, &map) ||
520.1.22 by Brian Aker
Second pass of thd cleanup
660
      setup_fields(session, 0, *values, MARK_COLUMNS_READ, 0, 0);
1 by brian
clean slate
661
662
    if (!res && check_fields)
663
    {
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
664
      bool saved_abort_on_warning= session->abortOnWarning();
665
666
      session->setAbortOnWarning(abort_on_warning);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
667
      res= check_that_all_fields_are_given_values(session,
668
                                                  table ? table :
1 by brian
clean slate
669
                                                  context->table_list->table,
670
                                                  context->table_list);
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
671
      session->setAbortOnWarning(saved_abort_on_warning);
1 by brian
clean slate
672
    }
673
674
    if (!res && duplic == DUP_UPDATE)
675
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
676
      res= check_update_fields(session, context->table_list, update_fields, &map);
1 by brian
clean slate
677
    }
678
679
    /* Restore the current context. */
680
    ctx_state.restore_state(context, table_list);
681
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
682
    if (not res)
520.1.22 by Brian Aker
Second pass of thd cleanup
683
      res= setup_fields(session, 0, update_values, MARK_COLUMNS_READ, 0, 0);
1 by brian
clean slate
684
  }
685
686
  if (res)
51.2.2 by Patrick Galbraith
Removed DBUGs from
687
    return(res);
1 by brian
clean slate
688
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
689
  if (not table)
1 by brian
clean slate
690
    table= table_list->table;
691
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
692
  if (not select_insert)
1 by brian
clean slate
693
  {
327.2.4 by Brian Aker
Refactoring table.h
694
    TableList *duplicate;
1220.1.13 by Brian Aker
Remove mysql_lock_have_duplicate() (we don't have merge, and our partition
695
    if ((duplicate= unique_table(table_list, table_list->next_global, true)))
1 by brian
clean slate
696
    {
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
697
      my_error(ER_UPDATE_TABLE_USED, MYF(0), table_list->alias);
698
699
      return true;
1 by brian
clean slate
700
    }
701
  }
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
702
1 by brian
clean slate
703
  if (duplic == DUP_UPDATE || duplic == DUP_REPLACE)
704
    table->prepare_for_position();
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
705
706
  return false;
1 by brian
clean slate
707
}
708
709
710
	/* Check if there is more uniq keys after field */
711
482 by Brian Aker
Remove uint.
712
static int last_uniq_key(Table *table,uint32_t keynr)
1 by brian
clean slate
713
{
1578.2.10 by Brian Aker
keys and fields partial encapsulation.
714
  while (++keynr < table->getShare()->sizeKeys())
1 by brian
clean slate
715
    if (table->key_info[keynr].flags & HA_NOSAME)
716
      return 0;
717
  return 1;
718
}
719
720
721
/*
722
  Write a record to table with optional deleting of conflicting records,
723
  invoke proper triggers if needed.
724
725
  SYNOPSIS
726
     write_record()
520.1.22 by Brian Aker
Second pass of thd cleanup
727
      session   - thread context
1 by brian
clean slate
728
      table - table to which record should be written
1711.6.1 by Brian Aker
Style on structure cleanup
729
      info  - CopyInfo structure describing handling of duplicates
1 by brian
clean slate
730
              and which is used for counting number of records inserted
731
              and deleted.
732
733
  NOTE
734
    Once this record will be written to table after insert trigger will
735
    be invoked. If instead of inserting new record we will update old one
736
    then both on update triggers will work instead. Similarly both on
737
    delete triggers will be invoked if we will delete conflicting records.
738
1273.1.13 by Jay Pipes
Style cleanup around TransactionContext::modified_non_trans_table and dead code removal
739
    Sets session->transaction.stmt.modified_non_trans_data to true if table which is updated didn't have
1 by brian
clean slate
740
    transactions.
741
742
  RETURN VALUE
743
    0     - success
744
    non-0 - error
745
*/
746
747
1711.6.1 by Brian Aker
Style on structure cleanup
748
int write_record(Session *session, Table *table,CopyInfo *info)
1 by brian
clean slate
749
{
750
  int error;
1749.3.10 by Brian Aker
Remove malloc call in favor of using a vector in key usage in sql_insert
751
  std::vector<unsigned char> key;
1802.16.8 by Padraig O'Sullivan
Removal of all MyBitmap from the code base. Compiles but test failures exist now.
752
  boost::dynamic_bitset<> *save_read_set, *save_write_set;
1208.3.2 by brian
Update for Cursor renaming.
753
  uint64_t prev_insert_id= table->cursor->next_insert_id;
151 by Brian Aker
Ulonglong to uint64_t
754
  uint64_t insert_id_for_cur_row= 0;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
755
1 by brian
clean slate
756
757
  info->records++;
758
  save_read_set=  table->read_set;
759
  save_write_set= table->write_set;
760
831.1.1 by Brian Aker
Cleanup of DELAYED INSERT bits (aka... it is just now a hint to the engine).
761
  if (info->handle_duplicates == DUP_REPLACE || info->handle_duplicates == DUP_UPDATE)
1 by brian
clean slate
762
  {
1672.3.6 by Brian Aker
First pass in encapsulating row
763
    while ((error=table->cursor->insertRecord(table->getInsertRecord())))
1 by brian
clean slate
764
    {
482 by Brian Aker
Remove uint.
765
      uint32_t key_nr;
1 by brian
clean slate
766
      /*
767
        If we do more than one iteration of this loop, from the second one the
768
        row will have an explicit value in the autoinc field, which was set at
769
        the first call of handler::update_auto_increment(). So we must save
520.1.22 by Brian Aker
Second pass of thd cleanup
770
        the autogenerated value to avoid session->insert_id_for_cur_row to become
1 by brian
clean slate
771
        0.
772
      */
1208.3.2 by brian
Update for Cursor renaming.
773
      if (table->cursor->insert_id_for_cur_row > 0)
774
        insert_id_for_cur_row= table->cursor->insert_id_for_cur_row;
1 by brian
clean slate
775
      else
1208.3.2 by brian
Update for Cursor renaming.
776
        table->cursor->insert_id_for_cur_row= insert_id_for_cur_row;
1 by brian
clean slate
777
      bool is_duplicate_key_error;
1208.3.2 by brian
Update for Cursor renaming.
778
      if (table->cursor->is_fatal_error(error, HA_CHECK_DUP))
1 by brian
clean slate
779
	goto err;
1208.3.2 by brian
Update for Cursor renaming.
780
      is_duplicate_key_error= table->cursor->is_fatal_error(error, 0);
1 by brian
clean slate
781
      if (!is_duplicate_key_error)
782
      {
783
        /*
784
          We come here when we had an ignorable error which is not a duplicate
785
          key error. In this we ignore error if ignore flag is set, otherwise
786
          report error as usual. We will not do any duplicate key processing.
787
        */
788
        if (info->ignore)
789
          goto gok_or_after_err; /* Ignoring a not fatal error, return 0 */
790
        goto err;
791
      }
1216.1.1 by Brian Aker
Move print_error up to Engine.
792
      if ((int) (key_nr = table->get_dup_key(error)) < 0)
1 by brian
clean slate
793
      {
794
	error= HA_ERR_FOUND_DUPP_KEY;         /* Database can't find key */
795
	goto err;
796
      }
797
      /* Read all columns for the row we are going to replace */
798
      table->use_all_columns();
799
      /*
800
	Don't allow REPLACE to replace a row when a auto_increment column
801
	was used.  This ensures that we don't get a problem when the
802
	whole range of the key has been used.
803
      */
804
      if (info->handle_duplicates == DUP_REPLACE &&
805
          table->next_number_field &&
1574 by Brian Aker
Rollup patch for hiding tableshare.
806
          key_nr == table->getShare()->next_number_index &&
1 by brian
clean slate
807
	  (insert_id_for_cur_row > 0))
808
	goto err;
1233.1.6 by Brian Aker
Remove table_flags from MyISAM.
809
      if (table->cursor->getEngine()->check_flag(HTON_BIT_DUPLICATE_POS))
1 by brian
clean slate
810
      {
1672.3.6 by Brian Aker
First pass in encapsulating row
811
	if (table->cursor->rnd_pos(table->getUpdateRecord(),table->cursor->dup_ref))
1 by brian
clean slate
812
	  goto err;
813
      }
814
      else
815
      {
1208.3.2 by brian
Update for Cursor renaming.
816
	if (table->cursor->extra(HA_EXTRA_FLUSH_CACHE)) /* Not needed with NISAM */
1 by brian
clean slate
817
	{
1241.9.57 by Monty Taylor
Oy. Bigger change than I normally like - but this stuff is all intertwined.
818
	  error=errno;
1 by brian
clean slate
819
	  goto err;
820
	}
821
1749.3.10 by Brian Aker
Remove malloc call in favor of using a vector in key usage in sql_insert
822
	if (not key.size())
1 by brian
clean slate
823
	{
1749.3.10 by Brian Aker
Remove malloc call in favor of using a vector in key usage in sql_insert
824
          key.resize(table->getShare()->max_unique_length);
1 by brian
clean slate
825
	}
1749.3.10 by Brian Aker
Remove malloc call in favor of using a vector in key usage in sql_insert
826
	key_copy(&key[0], table->getInsertRecord(), table->key_info+key_nr, 0);
1672.3.6 by Brian Aker
First pass in encapsulating row
827
	if ((error=(table->cursor->index_read_idx_map(table->getUpdateRecord(),key_nr,
1749.3.10 by Brian Aker
Remove malloc call in favor of using a vector in key usage in sql_insert
828
                                                    &key[0], HA_WHOLE_KEY,
1 by brian
clean slate
829
                                                    HA_READ_KEY_EXACT))))
830
	  goto err;
831
      }
832
      if (info->handle_duplicates == DUP_UPDATE)
833
      {
834
        /*
835
          We don't check for other UNIQUE keys - the first row
836
          that matches, is updated. If update causes a conflict again,
837
          an error is returned
838
        */
1672.3.5 by Brian Aker
This replaces the allocation we do for insert/update.
839
	assert(table->insert_values.size());
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
840
        table->storeRecordAsInsert();
841
        table->restoreRecord();
2183.2.19 by Olaf van der Spek
Use List::size()
842
        assert(info->update_fields->size() ==
843
                    info->update_values->size());
520.1.22 by Brian Aker
Second pass of thd cleanup
844
        if (fill_record(session, *info->update_fields,
1 by brian
clean slate
845
                                                 *info->update_values,
846
                                                 info->ignore))
847
          goto before_err;
848
1208.3.2 by brian
Update for Cursor renaming.
849
        table->cursor->restore_auto_increment(prev_insert_id);
1 by brian
clean slate
850
        if (table->next_number_field)
1208.3.2 by brian
Update for Cursor renaming.
851
          table->cursor->adjust_next_insert_id_after_explicit_value(
1 by brian
clean slate
852
            table->next_number_field->val_int());
853
        info->touched++;
1819.9.151 by Martin Hansson, Stewart Smith
Merge Revision revid:martin.hansson@oracle.com-20101007081311-zb72jgqjx2rs831z from MySQL InnoDB
854
855
        if (! table->records_are_comparable() || table->compare_records())
1 by brian
clean slate
856
        {
1672.3.6 by Brian Aker
First pass in encapsulating row
857
          if ((error=table->cursor->updateRecord(table->getUpdateRecord(),
858
                                                table->getInsertRecord())) &&
1 by brian
clean slate
859
              error != HA_ERR_RECORD_IS_THE_SAME)
860
          {
861
            if (info->ignore &&
1208.3.2 by brian
Update for Cursor renaming.
862
                !table->cursor->is_fatal_error(error, HA_CHECK_DUP_KEY))
1 by brian
clean slate
863
            {
864
              goto gok_or_after_err;
865
            }
866
            goto err;
867
          }
868
869
          if (error != HA_ERR_RECORD_IS_THE_SAME)
870
            info->updated++;
871
          else
872
            error= 0;
873
          /*
874
            If ON DUP KEY UPDATE updates a row instead of inserting one, it's
875
            like a regular UPDATE statement: it should not affect the value of a
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
876
            next SELECT LAST_INSERT_ID() or insert_id().
1 by brian
clean slate
877
            Except if LAST_INSERT_ID(#) was in the INSERT query, which is
520.1.21 by Brian Aker
THD -> Session rename
878
            handled separately by Session::arg_of_last_insert_id_function.
1 by brian
clean slate
879
          */
1208.3.2 by brian
Update for Cursor renaming.
880
          insert_id_for_cur_row= table->cursor->insert_id_for_cur_row= 0;
1 by brian
clean slate
881
          info->copied++;
882
        }
883
884
        if (table->next_number_field)
1208.3.2 by brian
Update for Cursor renaming.
885
          table->cursor->adjust_next_insert_id_after_explicit_value(
1 by brian
clean slate
886
            table->next_number_field->val_int());
887
        info->touched++;
888
889
        goto gok_or_after_err;
890
      }
891
      else /* DUP_REPLACE */
892
      {
893
	/*
894
	  The manual defines the REPLACE semantics that it is either
895
	  an INSERT or DELETE(s) + INSERT; FOREIGN KEY checks in
896
	  InnoDB do not function in the defined way if we allow MySQL
897
	  to convert the latter operation internally to an UPDATE.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
898
          We also should not perform this conversion if we have
1 by brian
clean slate
899
          timestamp field with ON UPDATE which is different from DEFAULT.
900
          Another case when conversion should not be performed is when
901
          we have ON DELETE trigger on table so user may notice that
902
          we cheat here. Note that it is ok to do such conversion for
903
          tables which have ON UPDATE but have no ON DELETE triggers,
904
          we just should not expose this fact to users by invoking
905
          ON UPDATE triggers.
906
	*/
907
	if (last_uniq_key(table,key_nr) &&
1208.3.2 by brian
Update for Cursor renaming.
908
	    !table->cursor->referenced_by_foreign_key() &&
1 by brian
clean slate
909
            (table->timestamp_field_type == TIMESTAMP_NO_AUTO_SET ||
910
             table->timestamp_field_type == TIMESTAMP_AUTO_SET_ON_BOTH))
911
        {
1672.3.6 by Brian Aker
First pass in encapsulating row
912
          if ((error=table->cursor->updateRecord(table->getUpdateRecord(),
913
					        table->getInsertRecord())) &&
1 by brian
clean slate
914
              error != HA_ERR_RECORD_IS_THE_SAME)
915
            goto err;
916
          if (error != HA_ERR_RECORD_IS_THE_SAME)
917
            info->deleted++;
918
          else
919
            error= 0;
1208.3.2 by brian
Update for Cursor renaming.
920
          session->record_first_successful_insert_id_in_cur_stmt(table->cursor->insert_id_for_cur_row);
1 by brian
clean slate
921
          /*
922
            Since we pretend that we have done insert we should call
923
            its after triggers.
924
          */
925
          goto after_n_copied_inc;
926
        }
927
        else
928
        {
1672.3.6 by Brian Aker
First pass in encapsulating row
929
          if ((error=table->cursor->deleteRecord(table->getUpdateRecord())))
1 by brian
clean slate
930
            goto err;
931
          info->deleted++;
1208.3.2 by brian
Update for Cursor renaming.
932
          if (!table->cursor->has_transactions())
1273.1.13 by Jay Pipes
Style cleanup around TransactionContext::modified_non_trans_table and dead code removal
933
            session->transaction.stmt.markModifiedNonTransData();
1 by brian
clean slate
934
          /* Let us attempt do write_row() once more */
935
        }
936
      }
937
    }
1208.3.2 by brian
Update for Cursor renaming.
938
    session->record_first_successful_insert_id_in_cur_stmt(table->cursor->insert_id_for_cur_row);
1 by brian
clean slate
939
    /*
940
      Restore column maps if they where replaced during an duplicate key
941
      problem.
942
    */
943
    if (table->read_set != save_read_set ||
944
        table->write_set != save_write_set)
1802.16.8 by Padraig O'Sullivan
Removal of all MyBitmap from the code base. Compiles but test failures exist now.
945
      table->column_bitmaps_set(*save_read_set, *save_write_set);
1 by brian
clean slate
946
  }
1672.3.6 by Brian Aker
First pass in encapsulating row
947
  else if ((error=table->cursor->insertRecord(table->getInsertRecord())))
1 by brian
clean slate
948
  {
949
    if (!info->ignore ||
1208.3.2 by brian
Update for Cursor renaming.
950
        table->cursor->is_fatal_error(error, HA_CHECK_DUP))
1 by brian
clean slate
951
      goto err;
1208.3.2 by brian
Update for Cursor renaming.
952
    table->cursor->restore_auto_increment(prev_insert_id);
1 by brian
clean slate
953
    goto gok_or_after_err;
954
  }
955
956
after_n_copied_inc:
957
  info->copied++;
1208.3.2 by brian
Update for Cursor renaming.
958
  session->record_first_successful_insert_id_in_cur_stmt(table->cursor->insert_id_for_cur_row);
1 by brian
clean slate
959
960
gok_or_after_err:
1208.3.2 by brian
Update for Cursor renaming.
961
  if (!table->cursor->has_transactions())
1273.1.13 by Jay Pipes
Style cleanup around TransactionContext::modified_non_trans_table and dead code removal
962
    session->transaction.stmt.markModifiedNonTransData();
51.2.2 by Patrick Galbraith
Removed DBUGs from
963
  return(0);
1 by brian
clean slate
964
965
err:
966
  info->last_errno= error;
967
  /* current_select is NULL if this is a delayed insert */
2227.4.8 by Olaf van der Spek
Session::lex()
968
  if (session->lex().current_select)
969
    session->lex().current_select->no_error= 0;        // Give error
1216.1.1 by Brian Aker
Move print_error up to Engine.
970
  table->print_error(error,MYF(0));
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
971
1 by brian
clean slate
972
before_err:
1208.3.2 by brian
Update for Cursor renaming.
973
  table->cursor->restore_auto_increment(prev_insert_id);
1802.16.8 by Padraig O'Sullivan
Removal of all MyBitmap from the code base. Compiles but test failures exist now.
974
  table->column_bitmaps_set(*save_read_set, *save_write_set);
975
  return 1;
1 by brian
clean slate
976
}
977
978
979
/******************************************************************************
980
  Check that all fields with arn't null_fields are used
981
******************************************************************************/
982
520.1.22 by Brian Aker
Second pass of thd cleanup
983
int check_that_all_fields_are_given_values(Session *session, Table *entry,
685.4.10 by Jay Pipes
Fixed bug where error 1364 was not being thrown in an appropriate place. Now, check_that_all_fields_have_given_values() method does two separate checks, one for not being in the write_set() and not having a default value (raise 1364) and another for being in the write_set() but having a NULL value set
984
                                           TableList *)
1 by brian
clean slate
985
{
986
  int err= 0;
987
1578.2.16 by Brian Aker
Merge in change to getTable() to private the field objects.
988
  for (Field **field=entry->getFields() ; *field ; field++)
1 by brian
clean slate
989
  {
1009 by Brian Aker
Merge of Monty
990
    if (((*field)->isWriteSet()) == false)
685.4.10 by Jay Pipes
Fixed bug where error 1364 was not being thrown in an appropriate place. Now, check_that_all_fields_have_given_values() method does two separate checks, one for not being in the write_set() and not having a default value (raise 1364) and another for being in the write_set() but having a NULL value set
991
    {
992
      /*
993
       * If the field doesn't have any default value
994
       * and there is no actual value specified in the
995
       * INSERT statement, throw error ER_NO_DEFAULT_FOR_FIELD.
996
       */
997
      if (((*field)->flags & NO_DEFAULT_VALUE_FLAG) &&
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
998
        ((*field)->real_type() != DRIZZLE_TYPE_ENUM))
1 by brian
clean slate
999
      {
685.4.10 by Jay Pipes
Fixed bug where error 1364 was not being thrown in an appropriate place. Now, check_that_all_fields_have_given_values() method does two separate checks, one for not being in the write_set() and not having a default value (raise 1364) and another for being in the write_set() but having a NULL value set
1000
        my_error(ER_NO_DEFAULT_FOR_FIELD, MYF(0), (*field)->field_name);
1001
        err= 1;
1 by brian
clean slate
1002
      }
685.4.10 by Jay Pipes
Fixed bug where error 1364 was not being thrown in an appropriate place. Now, check_that_all_fields_have_given_values() method does two separate checks, one for not being in the write_set() and not having a default value (raise 1364) and another for being in the write_set() but having a NULL value set
1003
    }
1004
    else
1005
    {
685.4.1 by Jay Pipes
Enabled the null.test.
1006
      /*
685.4.10 by Jay Pipes
Fixed bug where error 1364 was not being thrown in an appropriate place. Now, check_that_all_fields_have_given_values() method does two separate checks, one for not being in the write_set() and not having a default value (raise 1364) and another for being in the write_set() but having a NULL value set
1007
       * However, if an actual NULL value was specified
2227.4.3 by Olaf van der Spek
Remove unnecessary statement.h include
1008
       * for the field and the field is a NOT NULL field,
685.4.10 by Jay Pipes
Fixed bug where error 1364 was not being thrown in an appropriate place. Now, check_that_all_fields_have_given_values() method does two separate checks, one for not being in the write_set() and not having a default value (raise 1364) and another for being in the write_set() but having a NULL value set
1009
       * throw ER_BAD_NULL_ERROR.
1010
       *
685.4.1 by Jay Pipes
Enabled the null.test.
1011
       * Per the SQL standard, inserting NULL into a NOT NULL
1012
       * field requires an error to be thrown.
1013
       */
685.4.10 by Jay Pipes
Fixed bug where error 1364 was not being thrown in an appropriate place. Now, check_that_all_fields_have_given_values() method does two separate checks, one for not being in the write_set() and not having a default value (raise 1364) and another for being in the write_set() but having a NULL value set
1014
      if (((*field)->flags & NOT_NULL_FLAG) &&
1015
          (*field)->is_null())
1016
      {
1017
        my_error(ER_BAD_NULL_ERROR, MYF(0), (*field)->field_name);
1018
        err= 1;
1019
      }
1 by brian
clean slate
1020
    }
1021
  }
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
1022
  return session->abortOnWarning() ? err : 0;
1 by brian
clean slate
1023
}
1024
1025
/***************************************************************************
1026
  Store records in INSERT ... SELECT *
1027
***************************************************************************/
1028
1029
1030
/*
1031
  make insert specific preparation and checks after opening tables
1032
1033
  SYNOPSIS
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
1034
    insert_select_prepare()
520.1.22 by Brian Aker
Second pass of thd cleanup
1035
    session         thread handler
1 by brian
clean slate
1036
1037
  RETURN
163 by Brian Aker
Merge Monty's code.
1038
    false OK
1039
    true  Error
1 by brian
clean slate
1040
*/
1041
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
1042
bool insert_select_prepare(Session *session)
1 by brian
clean slate
1043
{
2227.4.10 by Olaf van der Spek
Session::lex()
1044
  LEX *lex= &session->lex();
846 by Brian Aker
Removing on typedeffed class.
1045
  Select_Lex *select_lex= &lex->select_lex;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1046
1 by brian
clean slate
1047
  /*
846 by Brian Aker
Removing on typedeffed class.
1048
    Select_Lex do not belong to INSERT statement, so we can't add WHERE
1 by brian
clean slate
1049
    clause if table is VIEW
1050
  */
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1051
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
1052
  if (prepare_insert(session, lex->query_tables,
1 by brian
clean slate
1053
                           lex->query_tables->table, lex->field_list, 0,
1054
                           lex->update_list, lex->value_list,
1055
                           lex->duplicates,
163 by Brian Aker
Merge Monty's code.
1056
                           &select_lex->where, true, false, false))
1057
    return(true);
1 by brian
clean slate
1058
1059
  /*
1060
    exclude first table from leaf tables list, because it belong to
1061
    INSERT
1062
  */
51.2.2 by Patrick Galbraith
Removed DBUGs from
1063
  assert(select_lex->leaf_tables != 0);
1 by brian
clean slate
1064
  lex->leaf_tables_insert= select_lex->leaf_tables;
1065
  /* skip all leaf tables belonged to view where we are insert */
327.1.7 by Brian Aker
Removed belong_to_view variable
1066
  select_lex->leaf_tables= select_lex->leaf_tables->next_leaf;
163 by Brian Aker
Merge Monty's code.
1067
  return(false);
1 by brian
clean slate
1068
}
1069
1070
327.2.4 by Brian Aker
Refactoring table.h
1071
select_insert::select_insert(TableList *table_list_par, Table *table_par,
1 by brian
clean slate
1072
                             List<Item> *fields_par,
1073
                             List<Item> *update_fields,
1074
                             List<Item> *update_values,
1075
                             enum_duplicates duplic,
1755.2.1 by Brian Aker
Remove dead memset call.
1076
                             bool ignore_check_option_errors) :
1077
  table_list(table_list_par), table(table_par), fields(fields_par),
1078
  autoinc_value_of_last_inserted_row(0),
1079
  insert_into_view(table_list_par && 0 != 0)
1 by brian
clean slate
1080
{
1081
  info.handle_duplicates= duplic;
1082
  info.ignore= ignore_check_option_errors;
1083
  info.update_fields= update_fields;
1084
  info.update_values= update_values;
1085
}
1086
1087
1088
int
848 by Brian Aker
typdef class removal (just... use the name of the class).
1089
select_insert::prepare(List<Item> &values, Select_Lex_Unit *u)
1 by brian
clean slate
1090
{
1091
  int res;
1092
  table_map map= 0;
2227.4.8 by Olaf van der Spek
Session::lex()
1093
  Select_Lex *lex_current_select_save= session->lex().current_select;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1094
1 by brian
clean slate
1095
1096
  unit= u;
1097
1098
  /*
1099
    Since table in which we are going to insert is added to the first
1100
    select, LEX::current_select should point to the first select while
1101
    we are fixing fields from insert list.
1102
  */
2227.4.8 by Olaf van der Spek
Session::lex()
1103
  session->lex().current_select= &session->lex().select_lex;
520.1.22 by Brian Aker
Second pass of thd cleanup
1104
  res= check_insert_fields(session, table_list, *fields, values,
1 by brian
clean slate
1105
                           !insert_into_view, &map) ||
520.1.22 by Brian Aker
Second pass of thd cleanup
1106
       setup_fields(session, 0, values, MARK_COLUMNS_READ, 0, 0);
1 by brian
clean slate
1107
2183.2.19 by Olaf van der Spek
Use List::size()
1108
  if (!res && fields->size())
1 by brian
clean slate
1109
  {
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
1110
    bool saved_abort_on_warning= session->abortOnWarning();
1111
    session->setAbortOnWarning(not info.ignore);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1112
    res= check_that_all_fields_are_given_values(session, table_list->table,
1 by brian
clean slate
1113
                                                table_list);
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
1114
    session->setAbortOnWarning(saved_abort_on_warning);
1 by brian
clean slate
1115
  }
1116
1117
  if (info.handle_duplicates == DUP_UPDATE && !res)
1118
  {
2227.4.8 by Olaf van der Spek
Session::lex()
1119
    Name_resolution_context *context= &session->lex().select_lex.context;
1 by brian
clean slate
1120
    Name_resolution_context_state ctx_state;
1121
1122
    /* Save the state of the current name resolution context. */
1123
    ctx_state.save_state(context, table_list);
1124
1125
    /* Perform name resolution only in the first table - 'table_list'. */
1126
    table_list->next_local= 0;
1127
    context->resolve_in_table_list_only(table_list);
1128
520.1.22 by Brian Aker
Second pass of thd cleanup
1129
    res= res || check_update_fields(session, context->table_list,
1 by brian
clean slate
1130
                                    *info.update_fields, &map);
1131
    /*
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1132
      When we are not using GROUP BY and there are no ungrouped aggregate functions
1 by brian
clean slate
1133
      we can refer to other tables in the ON DUPLICATE KEY part.
1134
      We use next_name_resolution_table descructively, so check it first (views?)
1135
    */
51.2.2 by Patrick Galbraith
Removed DBUGs from
1136
    assert (!table_list->next_name_resolution_table);
2227.4.8 by Olaf van der Spek
Session::lex()
1137
    if (session->lex().select_lex.group_list.elements == 0 and
1138
        not session->lex().select_lex.with_sum_func)
1 by brian
clean slate
1139
      /*
1140
        We must make a single context out of the two separate name resolution contexts :
1141
        the INSERT table and the tables in the SELECT part of INSERT ... SELECT.
1142
        To do that we must concatenate the two lists
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1143
      */
1144
      table_list->next_name_resolution_table=
1 by brian
clean slate
1145
        ctx_state.get_first_name_resolution_table();
1146
520.1.22 by Brian Aker
Second pass of thd cleanup
1147
    res= res || setup_fields(session, 0, *info.update_values,
1 by brian
clean slate
1148
                             MARK_COLUMNS_READ, 0, 0);
1149
    if (!res)
1150
    {
1151
      /*
1152
        Traverse the update values list and substitute fields from the
1153
        select for references (Item_ref objects) to them. This is done in
1154
        order to get correct values from those fields when the select
1155
        employs a temporary table.
1156
      */
2183.2.12 by Olaf van der Spek
Use List::begin()
1157
      List<Item>::iterator li(info.update_values->begin());
1 by brian
clean slate
1158
      Item *item;
1159
1160
      while ((item= li++))
1161
      {
1162
        item->transform(&Item::update_value_transformer,
2227.4.8 by Olaf van der Spek
Session::lex()
1163
                        (unsigned char*)session->lex().current_select);
1 by brian
clean slate
1164
      }
1165
    }
1166
1167
    /* Restore the current context. */
1168
    ctx_state.restore_state(context, table_list);
1169
  }
1170
2227.4.8 by Olaf van der Spek
Session::lex()
1171
  session->lex().current_select= lex_current_select_save;
1 by brian
clean slate
1172
  if (res)
51.2.2 by Patrick Galbraith
Removed DBUGs from
1173
    return(1);
1 by brian
clean slate
1174
  /*
1175
    if it is INSERT into join view then check_insert_fields already found
1176
    real table for insert
1177
  */
1178
  table= table_list->table;
1179
1180
  /*
1181
    Is table which we are changing used somewhere in other parts of
1182
    query
1183
  */
1220.1.13 by Brian Aker
Remove mysql_lock_have_duplicate() (we don't have merge, and our partition
1184
  if (unique_table(table_list, table_list->next_global))
1 by brian
clean slate
1185
  {
1186
    /* Using same table for INSERT and SELECT */
2227.4.8 by Olaf van der Spek
Session::lex()
1187
    session->lex().current_select->options|= OPTION_BUFFER_RESULT;
1188
    session->lex().current_select->join->select_options|= OPTION_BUFFER_RESULT;
1 by brian
clean slate
1189
  }
2227.4.8 by Olaf van der Spek
Session::lex()
1190
  else if (not (session->lex().current_select->options & OPTION_BUFFER_RESULT))
1 by brian
clean slate
1191
  {
1192
    /*
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1193
      We must not yet prepare the result table if it is the same as one of the
1194
      source tables (INSERT SELECT). The preparation may disable
1 by brian
clean slate
1195
      indexes on the result table, which may be used during the select, if it
1196
      is the same table (Bug #6034). Do the preparation after the select phase
1197
      in select_insert::prepare2().
1198
      We won't start bulk inserts at all if this statement uses functions or
1199
      should invoke triggers since they may access to the same table too.
1200
    */
1208.3.2 by brian
Update for Cursor renaming.
1201
    table->cursor->ha_start_bulk_insert((ha_rows) 0);
1 by brian
clean slate
1202
  }
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
1203
  table->restoreRecordAsDefault();		// Get empty record
1 by brian
clean slate
1204
  table->next_number_field=table->found_next_number_field;
1205
520.1.22 by Brian Aker
Second pass of thd cleanup
1206
  session->cuted_fields=0;
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
1207
1 by brian
clean slate
1208
  if (info.ignore || info.handle_duplicates != DUP_ERROR)
1208.3.2 by brian
Update for Cursor renaming.
1209
    table->cursor->extra(HA_EXTRA_IGNORE_DUP_KEY);
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
1210
1 by brian
clean slate
1211
  if (info.handle_duplicates == DUP_REPLACE)
1208.3.2 by brian
Update for Cursor renaming.
1212
    table->cursor->extra(HA_EXTRA_WRITE_CAN_REPLACE);
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
1213
1 by brian
clean slate
1214
  if (info.handle_duplicates == DUP_UPDATE)
1208.3.2 by brian
Update for Cursor renaming.
1215
    table->cursor->extra(HA_EXTRA_INSERT_WITH_UPDATE);
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
1216
1217
  session->setAbortOnWarning(not info.ignore);
1 by brian
clean slate
1218
  table->mark_columns_needed_for_insert();
1219
1220
51.2.2 by Patrick Galbraith
Removed DBUGs from
1221
  return(res);
1 by brian
clean slate
1222
}
1223
1224
1225
/*
1226
  Finish the preparation of the result table.
1227
1228
  SYNOPSIS
1229
    select_insert::prepare2()
1230
    void
1231
1232
  DESCRIPTION
1233
    If the result table is the same as one of the source tables (INSERT SELECT),
1234
    the result table is not finally prepared at the join prepair phase.
1235
    Do the final preparation now.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1236
1 by brian
clean slate
1237
  RETURN
1238
    0   OK
1239
*/
1240
1241
int select_insert::prepare2(void)
1242
{
2227.4.8 by Olaf van der Spek
Session::lex()
1243
  if (session->lex().current_select->options & OPTION_BUFFER_RESULT)
1208.3.2 by brian
Update for Cursor renaming.
1244
    table->cursor->ha_start_bulk_insert((ha_rows) 0);
2187.2.2 by Brian Aker
getLex() usage and fix for table_name creation during admin commands.
1245
51.2.2 by Patrick Galbraith
Removed DBUGs from
1246
  return(0);
1 by brian
clean slate
1247
}
1248
1249
1250
void select_insert::cleanup()
1251
{
1252
  /* select_insert/select_create are never re-used in prepared statement */
51.2.2 by Patrick Galbraith
Removed DBUGs from
1253
  assert(0);
1 by brian
clean slate
1254
}
1255
1256
select_insert::~select_insert()
1257
{
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1258
1 by brian
clean slate
1259
  if (table)
1260
  {
1261
    table->next_number_field=0;
163 by Brian Aker
Merge Monty's code.
1262
    table->auto_increment_field_not_null= false;
1208.3.2 by brian
Update for Cursor renaming.
1263
    table->cursor->ha_reset();
1 by brian
clean slate
1264
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
1265
  session->count_cuted_fields= CHECK_FIELD_IGNORE;
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
1266
  session->setAbortOnWarning(false);
51.2.2 by Patrick Galbraith
Removed DBUGs from
1267
  return;
1 by brian
clean slate
1268
}
1269
1270
1271
bool select_insert::send_data(List<Item> &values)
1272
{
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1273
2187.2.2 by Brian Aker
getLex() usage and fix for table_name creation during admin commands.
1274
  bool error= false;
1 by brian
clean slate
1275
1276
  if (unit->offset_limit_cnt)
1277
  {						// using limit offset,count
1278
    unit->offset_limit_cnt--;
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
1279
    return false;
1 by brian
clean slate
1280
  }
1281
520.1.22 by Brian Aker
Second pass of thd cleanup
1282
  session->count_cuted_fields= CHECK_FIELD_WARN;	// Calculate cuted fields
1 by brian
clean slate
1283
  store_values(values);
520.1.22 by Brian Aker
Second pass of thd cleanup
1284
  session->count_cuted_fields= CHECK_FIELD_IGNORE;
1285
  if (session->is_error())
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
1286
    return true;
1 by brian
clean slate
1287
991.1.1 by Stewart Smith
Release latches in case bulk insert takes a long time
1288
  // Release latches in case bulk insert takes a long time
1273.1.15 by Jay Pipes
This patch completes the first step in the splitting of
1289
  plugin::TransactionalStorageEngine::releaseTemporaryLatches(session);
991.1.1 by Stewart Smith
Release latches in case bulk insert takes a long time
1290
520.1.22 by Brian Aker
Second pass of thd cleanup
1291
  error= write_record(session, table, &info);
1552.1.3 by Brian Aker
Fixes the assertion bug on handling of auto increment (sort of worthless,
1292
  table->auto_increment_field_not_null= false;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1293
1 by brian
clean slate
1294
  if (!error)
1295
  {
1296
    if (info.handle_duplicates == DUP_UPDATE)
1297
    {
1298
      /*
1299
        Restore fields of the record since it is possible that they were
1300
        changed by ON DUPLICATE KEY UPDATE clause.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1301
1 by brian
clean slate
1302
        If triggers exist then whey can modify some fields which were not
1303
        originally touched by INSERT ... SELECT, so we have to restore
1304
        their original values for the next row.
1305
      */
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
1306
      table->restoreRecordAsDefault();
1 by brian
clean slate
1307
    }
1308
    if (table->next_number_field)
1309
    {
1310
      /*
1311
        If no value has been autogenerated so far, we need to remember the
1312
        value we just saw, we may need to send it to client in the end.
1313
      */
520.1.22 by Brian Aker
Second pass of thd cleanup
1314
      if (session->first_successful_insert_id_in_cur_stmt == 0) // optimization
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1315
        autoinc_value_of_last_inserted_row=
1 by brian
clean slate
1316
          table->next_number_field->val_int();
1317
      /*
1318
        Clear auto-increment field for the next record, if triggers are used
1319
        we will clear it twice, but this should be cheap.
1320
      */
1321
      table->next_number_field->reset();
1322
    }
1323
  }
51.2.2 by Patrick Galbraith
Removed DBUGs from
1324
  return(error);
1 by brian
clean slate
1325
}
1326
1327
1328
void select_insert::store_values(List<Item> &values)
1329
{
2183.2.19 by Olaf van der Spek
Use List::size()
1330
  if (fields->size())
1235.1.11 by Brian Aker
Small cleanups, did in MERGE table only engine flag.
1331
    fill_record(session, *fields, values, true);
1 by brian
clean slate
1332
  else
1578.2.16 by Brian Aker
Merge in change to getTable() to private the field objects.
1333
    fill_record(session, table->getFields(), values, true);
1 by brian
clean slate
1334
}
1335
2087.3.1 by Brian Aker
Entire convert over to time_t.
1336
void select_insert::send_error(drizzled::error_t errcode,const char *err)
1 by brian
clean slate
1337
{
1338
  my_message(errcode, err, MYF(0));
1339
}
1340
1341
1342
bool select_insert::send_eof()
1343
{
1344
  int error;
1208.3.2 by brian
Update for Cursor renaming.
1345
  bool const trans_table= table->cursor->has_transactions();
151 by Brian Aker
Ulonglong to uint64_t
1346
  uint64_t id;
1 by brian
clean slate
1347
  bool changed;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1348
1208.3.2 by brian
Update for Cursor renaming.
1349
  error= table->cursor->ha_end_bulk_insert();
1350
  table->cursor->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
1351
  table->cursor->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
1 by brian
clean slate
1352
1353
  if ((changed= (info.copied || info.deleted || info.updated)))
1354
  {
1355
    /*
1356
      We must invalidate the table in the query cache before binlog writing
1405.3.5 by Jay Pipes
TransactionServices method names now meet code style guidelines.
1357
      and autocommitOrRollback.
1 by brian
clean slate
1358
    */
1273.1.13 by Jay Pipes
Style cleanup around TransactionContext::modified_non_trans_table and dead code removal
1359
    if (session->transaction.stmt.hasModifiedNonTransData())
1360
      session->transaction.all.markModifiedNonTransData();
1 by brian
clean slate
1361
  }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1362
  assert(trans_table || !changed ||
1273.1.13 by Jay Pipes
Style cleanup around TransactionContext::modified_non_trans_table and dead code removal
1363
              session->transaction.stmt.hasModifiedNonTransData());
1 by brian
clean slate
1364
1208.3.2 by brian
Update for Cursor renaming.
1365
  table->cursor->ha_release_auto_increment();
1 by brian
clean slate
1366
1367
  if (error)
1368
  {
1216.1.1 by Brian Aker
Move print_error up to Engine.
1369
    table->print_error(error,MYF(0));
1126.10.12 by Padraig O'Sullivan
Added calls to the dtrace probes related to insertion.
1370
    DRIZZLE_INSERT_SELECT_DONE(error, 0);
1371
    return 1;
1 by brian
clean slate
1372
  }
1373
  char buff[160];
1374
  if (info.ignore)
1366.1.11 by Siddharth Prakash Singh
sprintf->snprintf continued
1375
    snprintf(buff, sizeof(buff), ER(ER_INSERT_INFO), (ulong) info.records,
520.1.22 by Brian Aker
Second pass of thd cleanup
1376
	    (ulong) (info.records - info.copied), (ulong) session->cuted_fields);
1 by brian
clean slate
1377
  else
1366.1.11 by Siddharth Prakash Singh
sprintf->snprintf continued
1378
    snprintf(buff, sizeof(buff), ER(ER_INSERT_INFO), (ulong) info.records,
520.1.22 by Brian Aker
Second pass of thd cleanup
1379
	    (ulong) (info.deleted+info.updated), (ulong) session->cuted_fields);
971.3.59 by Eric Day
Removed client_capabilities from session and pushed functionality into protocol plugin.
1380
  session->row_count_func= info.copied + info.deleted + info.updated;
1 by brian
clean slate
1381
520.1.22 by Brian Aker
Second pass of thd cleanup
1382
  id= (session->first_successful_insert_id_in_cur_stmt > 0) ?
1383
    session->first_successful_insert_id_in_cur_stmt :
1384
    (session->arg_of_last_insert_id_function ?
1385
     session->first_successful_insert_id_in_prev_stmt :
1 by brian
clean slate
1386
     (info.copied ? autoinc_value_of_last_inserted_row : 0));
2148.5.2 by Brian Aker
Additional remove of current_session.
1387
  session->my_ok((ulong) session->rowCount(),
971.3.59 by Eric Day
Removed client_capabilities from session and pushed functionality into protocol plugin.
1388
                 info.copied + info.deleted + info.touched, id, buff);
2227.4.3 by Olaf van der Spek
Remove unnecessary statement.h include
1389
  session->status_var.inserted_row_count+= session->rowCount();
2148.5.2 by Brian Aker
Additional remove of current_session.
1390
  DRIZZLE_INSERT_SELECT_DONE(0, session->rowCount());
1126.10.12 by Padraig O'Sullivan
Added calls to the dtrace probes related to insertion.
1391
  return 0;
1 by brian
clean slate
1392
}
1393
1394
void select_insert::abort() {
1395
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1396
1 by brian
clean slate
1397
  /*
1398
    If the creation of the table failed (due to a syntax error, for
1399
    example), no table will have been opened and therefore 'table'
1400
    will be NULL. In that case, we still need to execute the rollback
1401
    and the end of the function.
1402
   */
1403
  if (table)
1404
  {
1405
    bool changed, transactional_table;
1406
1208.3.2 by brian
Update for Cursor renaming.
1407
    table->cursor->ha_end_bulk_insert();
1 by brian
clean slate
1408
1409
    /*
1410
      If at least one row has been inserted/modified and will stay in
1411
      the table (the table doesn't have transactions) we must write to
1412
      the binlog (and the error code will make the slave stop).
1413
1414
      For many errors (example: we got a duplicate key error while
1415
      inserting into a MyISAM table), no row will be added to the table,
1416
      so passing the error to the slave will not help since there will
1417
      be an error code mismatch (the inserts will succeed on the slave
1418
      with no error).
1419
1420
      If table creation failed, the number of rows modified will also be
1421
      zero, so no check for that is made.
1422
    */
1423
    changed= (info.copied || info.deleted || info.updated);
1208.3.2 by brian
Update for Cursor renaming.
1424
    transactional_table= table->cursor->has_transactions();
51.2.2 by Patrick Galbraith
Removed DBUGs from
1425
    assert(transactional_table || !changed ||
1273.1.13 by Jay Pipes
Style cleanup around TransactionContext::modified_non_trans_table and dead code removal
1426
		session->transaction.stmt.hasModifiedNonTransData());
1208.3.2 by brian
Update for Cursor renaming.
1427
    table->cursor->ha_release_auto_increment();
1 by brian
clean slate
1428
  }
1429
1126.10.12 by Padraig O'Sullivan
Added calls to the dtrace probes related to insertion.
1430
  if (DRIZZLE_INSERT_SELECT_DONE_ENABLED())
1431
  {
1432
    DRIZZLE_INSERT_SELECT_DONE(0, info.copied + info.deleted + info.updated);
1433
  }
1434
51.2.2 by Patrick Galbraith
Removed DBUGs from
1435
  return;
1 by brian
clean slate
1436
}
1437
1438
1439
/***************************************************************************
1440
  CREATE TABLE (SELECT) ...
1441
***************************************************************************/
1442
1443
/*
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1444
  Create table from lists of fields and items (or just return Table
1 by brian
clean slate
1445
  object for pre-opened existing table).
1446
1447
  SYNOPSIS
1448
    create_table_from_items()
520.1.22 by Brian Aker
Second pass of thd cleanup
1449
      session          in     Thread object
1 by brian
clean slate
1450
      create_info  in     Create information (like MAX_ROWS, ENGINE or
1451
                          temporary table flag)
327.2.4 by Brian Aker
Refactoring table.h
1452
      create_table in     Pointer to TableList object providing database
1 by brian
clean slate
1453
                          and name for table to be created or to be open
1454
      alter_info   in/out Initial list of columns and indexes for the table
1455
                          to be created
1456
      items        in     List of items which should be used to produce rest
1457
                          of fields for the table (corresponding fields will
1458
                          be added to the end of alter_info->create_list)
1711.6.1 by Brian Aker
Style on structure cleanup
1459
      lock         out    Pointer to the DrizzleLock object for table created
1 by brian
clean slate
1460
                          (or open temporary table) will be returned in this
1461
                          parameter. Since this table is not included in
520.1.21 by Brian Aker
THD -> Session rename
1462
                          Session::lock caller is responsible for explicitly
1 by brian
clean slate
1463
                          unlocking this table.
1464
      hooks
1465
1466
  NOTES
1467
    This function behaves differently for base and temporary tables:
1468
    - For base table we assume that either table exists and was pre-opened
1109.1.3 by Brian Aker
Move names around a bit (to align similar methods)
1469
      and locked at openTablesLock() stage (and in this case we just
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1470
      emit error or warning and return pre-opened Table object) or special
1 by brian
clean slate
1471
      placeholder was put in table cache that guarantees that this table
1472
      won't be created or opened until the placeholder will be removed
1473
      (so there is an exclusive lock on this table).
1474
    - We don't pre-open existing temporary table, instead we either open
1475
      or create and then open table in this function.
1476
1477
    Since this function contains some logic specific to CREATE TABLE ...
1478
    SELECT it should be changed before it can be used in other contexts.
1479
1480
  RETURN VALUES
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1481
    non-zero  Pointer to Table object for table created or opened
1 by brian
clean slate
1482
    0         Error
1483
*/
1484
520.1.22 by Brian Aker
Second pass of thd cleanup
1485
static Table *create_table_from_items(Session *session, HA_CREATE_INFO *create_info,
327.2.4 by Brian Aker
Refactoring table.h
1486
                                      TableList *create_table,
1320.1.2 by Brian Aker
More reference counting.
1487
				      message::Table &table_proto,
1126.3.3 by Jay Pipes
Moves Alter_info out into its own header and source file, cleans up some related include mess in sql_lex.h, and renames Alter_info to AlterInfo.
1488
                                      AlterInfo *alter_info,
1 by brian
clean slate
1489
                                      List<Item> *items,
1222.2.3 by Brian Aker
Remove a few more options, from options in HA_CREATE_INFO.
1490
                                      bool is_if_not_exists,
1711.6.1 by Brian Aker
Style on structure cleanup
1491
                                      DrizzleLock **lock,
2087.4.2 by Brian Aker
Modify TableIdentifier to fit with the rest of the identifiers.
1492
				      identifier::Table::const_reference identifier)
1 by brian
clean slate
1493
{
1608.2.4 by Brian Aker
Update for having share declared type.
1494
  TableShare share(message::Table::INTERNAL);
2183.2.19 by Olaf van der Spek
Use List::size()
1495
  uint32_t select_field_count= items->size();
1 by brian
clean slate
1496
  /* Add selected items to field list */
2183.2.12 by Olaf van der Spek
Use List::begin()
1497
  List<Item>::iterator it(items->begin());
1 by brian
clean slate
1498
  Item *item;
1499
  Field *tmp_field;
1500
1395.1.10 by Brian Aker
Trying to be consistent through interface on state of tmp.
1501
  if (not (identifier.isTmp()) && create_table->table->db_stat)
1 by brian
clean slate
1502
  {
1109.1.3 by Brian Aker
Move names around a bit (to align similar methods)
1503
    /* Table already exists and was open at openTablesLock() stage. */
1222.2.3 by Brian Aker
Remove a few more options, from options in HA_CREATE_INFO.
1504
    if (is_if_not_exists)
1 by brian
clean slate
1505
    {
1506
      create_info->table_existed= 1;		// Mark that table existed
520.1.22 by Brian Aker
Second pass of thd cleanup
1507
      push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
1 by brian
clean slate
1508
                          ER_TABLE_EXISTS_ERROR, ER(ER_TABLE_EXISTS_ERROR),
1874.1.2 by Brian Aker
Encapsulate table_name from table_list.
1509
                          create_table->getTableName());
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1510
      return create_table->table;
1 by brian
clean slate
1511
    }
1512
1874.1.2 by Brian Aker
Encapsulate table_name from table_list.
1513
    my_error(ER_TABLE_EXISTS_ERROR, MYF(0), create_table->getTableName());
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1514
    return NULL;
1 by brian
clean slate
1515
  }
1516
1517
  {
1859.2.11 by Brian Aker
Merge in so that shell requires a share to construct.
1518
    table::Shell tmp_table(share);		// Used during 'CreateField()'
1859.2.9 by Brian Aker
We add a "shell" table type, used only during field creation.
1519
1520
    if (not table_proto.engine().name().compare("MyISAM"))
1521
      tmp_table.getMutableShare()->db_low_byte_first= true;
1522
    else if (not table_proto.engine().name().compare("MEMORY"))
1523
      tmp_table.getMutableShare()->db_low_byte_first= true;
1524
1525
    tmp_table.in_use= session;
1526
1527
    while ((item=it++))
1835.1.3 by Brian Aker
Fix variable such that we no longer pass share to varstring on creation.
1528
    {
1859.2.9 by Brian Aker
We add a "shell" table type, used only during field creation.
1529
      CreateField *cr_field;
1530
      Field *field, *def_field;
1531
      if (item->type() == Item::FUNC_ITEM)
1835.1.3 by Brian Aker
Fix variable such that we no longer pass share to varstring on creation.
1532
      {
1859.2.9 by Brian Aker
We add a "shell" table type, used only during field creation.
1533
        if (item->result_type() != STRING_RESULT)
1534
        {
1535
          field= item->tmp_table_field(&tmp_table);
1536
        }
1537
        else
1538
        {
1539
          field= item->tmp_table_field_from_field_type(&tmp_table, 0);
1540
        }
1835.1.3 by Brian Aker
Fix variable such that we no longer pass share to varstring on creation.
1541
      }
1 by brian
clean slate
1542
      else
1835.1.3 by Brian Aker
Fix variable such that we no longer pass share to varstring on creation.
1543
      {
1859.2.9 by Brian Aker
We add a "shell" table type, used only during field creation.
1544
        field= create_tmp_field(session, &tmp_table, item, item->type(),
1545
                                (Item ***) 0, &tmp_field, &def_field, false,
1546
                                false, false, 0);
1547
      }
1548
1549
      if (!field ||
1550
          !(cr_field=new CreateField(field,(item->type() == Item::FIELD_ITEM ?
1551
                                            ((Item_field *)item)->field :
1552
                                            (Field*) 0))))
1553
      {
1554
        return NULL;
1555
      }
1556
1557
      if (item->maybe_null)
1558
      {
1559
        cr_field->flags &= ~NOT_NULL_FLAG;
1560
      }
1561
1562
      alter_info->create_list.push_back(cr_field);
1563
    }
1 by brian
clean slate
1564
  }
1565
1566
  /*
1567
    Create and lock table.
1568
1569
    Note that we either creating (or opening existing) temporary table or
1570
    creating base table on which name we have exclusive lock. So code below
1571
    should not cause deadlocks or races.
1572
  */
1859.2.9 by Brian Aker
We add a "shell" table type, used only during field creation.
1573
  Table *table= 0;
1 by brian
clean slate
1574
  {
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
1575
    if (not create_table_no_lock(session,
2029.1.1 by Brian Aker
Merge in first pass.
1576
				 identifier,
1577
				 create_info,
1578
				 table_proto,
1579
				 alter_info,
1580
				 false,
1581
				 select_field_count,
1582
				 is_if_not_exists))
1 by brian
clean slate
1583
    {
1395.1.10 by Brian Aker
Trying to be consistent through interface on state of tmp.
1584
      if (create_info->table_existed && not identifier.isTmp())
1 by brian
clean slate
1585
      {
1586
        /*
1587
          This means that someone created table underneath server
1588
          or it was created via different mysqld front-end to the
1589
          cluster. We don't have much options but throw an error.
1590
        */
1874.1.2 by Brian Aker
Encapsulate table_name from table_list.
1591
        my_error(ER_TABLE_EXISTS_ERROR, MYF(0), create_table->getTableName());
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1592
        return NULL;
1 by brian
clean slate
1593
      }
1594
1395.1.10 by Brian Aker
Trying to be consistent through interface on state of tmp.
1595
      if (not identifier.isTmp())
1 by brian
clean slate
1596
      {
1938.4.12 by Brian Aker
Merge in lock refactor, this just encapsulates.
1597
        /* CREATE TABLE... has found that the table already exists for insert and is adapting to use it */
1598
        boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex());
1874.3.2 by Brian Aker
Updating a few bits of the interface to be specific to table::Concurrent
1599
1600
        if (create_table->table)
1601
        {
1878.1.1 by Brian Aker
Stick to static cast.
1602
          table::Concurrent *concurrent_table= static_cast<table::Concurrent *>(create_table->table);
1874.3.2 by Brian Aker
Updating a few bits of the interface to be specific to table::Concurrent
1603
1604
          if (concurrent_table->reopen_name_locked_table(create_table, session))
1605
          {
2068.7.1 by Brian Aker
First pass through error correction in SE interface for drop table.
1606
            (void)plugin::StorageEngine::dropTable(*session, identifier);
1874.3.2 by Brian Aker
Updating a few bits of the interface to be specific to table::Concurrent
1607
          }
1608
          else
1609
          {
1610
            table= create_table->table;
1611
          }
1612
        }
1613
        else
1 by brian
clean slate
1614
        {
2068.7.1 by Brian Aker
First pass through error correction in SE interface for drop table.
1615
          (void)plugin::StorageEngine::dropTable(*session, identifier);
1 by brian
clean slate
1616
        }
1617
      }
1618
      else
1619
      {
1320.1.2 by Brian Aker
More reference counting.
1620
        if (not (table= session->openTable(create_table, (bool*) 0,
1621
                                           DRIZZLE_OPEN_TEMPORARY_ONLY)) &&
1622
            not create_info->table_existed)
1 by brian
clean slate
1623
        {
1624
          /*
1625
            This shouldn't happen as creation of temporary table should make
1626
            it preparable for open. But let us do close_temporary_table() here
1627
            just in case.
1628
          */
1864.3.13 by Brian Aker
Usage of find_temporary_table() to identifier.
1629
          session->drop_temporary_table(identifier);
1 by brian
clean slate
1630
        }
1631
      }
1632
    }
1859.2.9 by Brian Aker
We add a "shell" table type, used only during field creation.
1633
    if (not table)                                   // open failed
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1634
      return NULL;
1 by brian
clean slate
1635
  }
1636
1637
  table->reginfo.lock_type=TL_WRITE;
2064.1.2 by Brian Aker
Remove not_used bit for lock.
1638
  if (not ((*lock)= session->lockTables(&table, 1, DRIZZLE_LOCK_IGNORE_FLUSH)))
1 by brian
clean slate
1639
  {
1640
    if (*lock)
1641
    {
1910.2.7 by Brian Aker
Rename lock methods to be style + well make sense.
1642
      session->unlockTables(*lock);
1 by brian
clean slate
1643
      *lock= 0;
1644
    }
1645
1372.1.1 by Brian Aker
Removed/rewrite to remove goto in alter table.
1646
    if (not create_info->table_existed)
1647
      session->drop_open_table(table, identifier);
2168.3.3 by Brian Aker
Merge in using std::string for creating the list of bad tables.
1648
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1649
    return NULL;
1 by brian
clean slate
1650
  }
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1651
1652
  return table;
1 by brian
clean slate
1653
}
1654
1655
1656
int
848 by Brian Aker
typdef class removal (just... use the name of the class).
1657
select_create::prepare(List<Item> &values, Select_Lex_Unit *u)
1 by brian
clean slate
1658
{
1711.6.1 by Brian Aker
Style on structure cleanup
1659
  DrizzleLock *extra_lock= NULL;
1 by brian
clean slate
1660
  /*
1308.2.11 by Jay Pipes
* Adds CREATE TABLE as a specific CreateTableStatement message in the
1661
    For replication, the CREATE-SELECT statement is written
2227.4.3 by Olaf van der Spek
Remove unnecessary statement.h include
1662
    in two pieces: the first transaction messsage contains
1308.2.11 by Jay Pipes
* Adds CREATE TABLE as a specific CreateTableStatement message in the
1663
    the CREATE TABLE statement as a CreateTableStatement message
1664
    necessary to create the table.
2227.4.3 by Olaf van der Spek
Remove unnecessary statement.h include
1665
1308.2.11 by Jay Pipes
* Adds CREATE TABLE as a specific CreateTableStatement message in the
1666
    The second transaction message contains all the InsertStatement
1667
    and associated InsertRecords that should go into the table.
1 by brian
clean slate
1668
   */
1669
1670
  unit= u;
1671
1340.1.1 by Brian Aker
Length usage of identifier down the tree.
1672
  if (not (table= create_table_from_items(session, create_info, create_table,
1673
					  table_proto,
1674
					  alter_info, &values,
1675
					  is_if_not_exists,
1676
					  &extra_lock, identifier)))
1608.2.4 by Brian Aker
Update for having share declared type.
1677
  {
51.2.2 by Patrick Galbraith
Removed DBUGs from
1678
    return(-1);				// abort() deletes table
1608.2.4 by Brian Aker
Update for having share declared type.
1679
  }
1 by brian
clean slate
1680
1681
  if (extra_lock)
1682
  {
51.2.2 by Patrick Galbraith
Removed DBUGs from
1683
    assert(m_plock == NULL);
1 by brian
clean slate
1684
1395.1.10 by Brian Aker
Trying to be consistent through interface on state of tmp.
1685
    if (identifier.isTmp())
1 by brian
clean slate
1686
      m_plock= &m_lock;
1687
    else
520.1.22 by Brian Aker
Second pass of thd cleanup
1688
      m_plock= &session->extra_lock;
1 by brian
clean slate
1689
1690
    *m_plock= extra_lock;
1691
  }
1692
2183.2.19 by Olaf van der Spek
Use List::size()
1693
  if (table->getShare()->sizeFields() < values.size())
1 by brian
clean slate
1694
  {
1695
    my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), 1);
51.2.2 by Patrick Galbraith
Removed DBUGs from
1696
    return(-1);
1 by brian
clean slate
1697
  }
1698
1699
 /* First field to copy */
2183.2.19 by Olaf van der Spek
Use List::size()
1700
  field= table->getFields() + table->getShare()->sizeFields() - values.size();
1 by brian
clean slate
1701
1702
  /* Mark all fields that are given values */
1703
  for (Field **f= field ; *f ; f++)
1999.4.2 by Brian Aker
Encapsulate the field's position.
1704
  {
1705
    table->setWriteSet((*f)->position());
1706
  }
1 by brian
clean slate
1707
1708
  /* Don't set timestamp if used */
1709
  table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
1710
  table->next_number_field=table->found_next_number_field;
1711
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
1712
  table->restoreRecordAsDefault();      // Get empty record
520.1.22 by Brian Aker
Second pass of thd cleanup
1713
  session->cuted_fields=0;
1 by brian
clean slate
1714
  if (info.ignore || info.handle_duplicates != DUP_ERROR)
1208.3.2 by brian
Update for Cursor renaming.
1715
    table->cursor->extra(HA_EXTRA_IGNORE_DUP_KEY);
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
1716
1 by brian
clean slate
1717
  if (info.handle_duplicates == DUP_REPLACE)
1208.3.2 by brian
Update for Cursor renaming.
1718
    table->cursor->extra(HA_EXTRA_WRITE_CAN_REPLACE);
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
1719
1 by brian
clean slate
1720
  if (info.handle_duplicates == DUP_UPDATE)
1208.3.2 by brian
Update for Cursor renaming.
1721
    table->cursor->extra(HA_EXTRA_INSERT_WITH_UPDATE);
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
1722
1208.3.2 by brian
Update for Cursor renaming.
1723
  table->cursor->ha_start_bulk_insert((ha_rows) 0);
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
1724
  session->setAbortOnWarning(not info.ignore);
520.1.22 by Brian Aker
Second pass of thd cleanup
1725
  if (check_that_all_fields_are_given_values(session, table, table_list))
51.2.2 by Patrick Galbraith
Removed DBUGs from
1726
    return(1);
2114.5.1 by Brian Aker
Additional abstract around time (this also makes the abort_on_warnings in
1727
1 by brian
clean slate
1728
  table->mark_columns_needed_for_insert();
1208.3.2 by brian
Update for Cursor renaming.
1729
  table->cursor->extra(HA_EXTRA_WRITE_CACHE);
51.2.2 by Patrick Galbraith
Removed DBUGs from
1730
  return(0);
1 by brian
clean slate
1731
}
1732
1733
void select_create::store_values(List<Item> &values)
1734
{
1235.1.11 by Brian Aker
Small cleanups, did in MERGE table only engine flag.
1735
  fill_record(session, field, values, true);
1 by brian
clean slate
1736
}
1737
1738
2087.3.1 by Brian Aker
Entire convert over to time_t.
1739
void select_create::send_error(drizzled::error_t errcode,const char *err)
1 by brian
clean slate
1740
{
1741
  /*
1742
    This will execute any rollbacks that are necessary before writing
1743
    the transcation cache.
1744
1745
    We disable the binary log since nothing should be written to the
1746
    binary log.  This disabling is important, since we potentially do
1747
    a "roll back" of non-transactional tables by removing the table,
1748
    and the actual rollback might generate events that should not be
1749
    written to the binary log.
1750
1751
  */
1752
  select_insert::send_error(errcode, err);
1753
}
1754
1755
1756
bool select_create::send_eof()
1757
{
1758
  bool tmp=select_insert::send_eof();
1759
  if (tmp)
1760
    abort();
1761
  else
1762
  {
1763
    /*
1764
      Do an implicit commit at end of statement for non-temporary
1765
      tables.  This can fail, but we should unlock the table
1766
      nevertheless.
1767
    */
1608.2.3 by Brian Aker
Encapsulate type for TableShare.
1768
    if (!table->getShare()->getType())
1 by brian
clean slate
1769
    {
1273.1.2 by Jay Pipes
This patch does not change any algorithms or code paths,
1770
      TransactionServices &transaction_services= TransactionServices::singleton();
2096.2.1 by David Shrewsbury
Initial change to use references to Session in TransactionServices methods rather than pointers.
1771
      transaction_services.autocommitOrRollback(*session, 0);
934.2.11 by Jay Pipes
Moves end_trans(), begin_trans(), end_active_trans() out of the parser module and adds startTransaction(), endTransaction(), and endActiveTransaction() member methods of Session object.
1772
      (void) session->endActiveTransaction();
1 by brian
clean slate
1773
    }
1774
1208.3.2 by brian
Update for Cursor renaming.
1775
    table->cursor->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
1776
    table->cursor->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
1 by brian
clean slate
1777
    if (m_plock)
1778
    {
1910.2.7 by Brian Aker
Rename lock methods to be style + well make sense.
1779
      session->unlockTables(*m_plock);
1 by brian
clean slate
1780
      *m_plock= NULL;
1781
      m_plock= NULL;
1782
    }
1783
  }
1784
  return tmp;
1785
}
1786
1787
1788
void select_create::abort()
1789
{
1790
  /*
1791
    In select_insert::abort() we roll back the statement, including
1792
    truncating the transaction cache of the binary log. To do this, we
1793
    pretend that the statement is transactional, even though it might
1794
    be the case that it was not.
1795
1796
    We roll back the statement prior to deleting the table and prior
1797
    to releasing the lock on the table, since there might be potential
1798
    for failure if the rollback is executed after the drop or after
1799
    unlocking the table.
1800
1801
    We also roll back the statement regardless of whether the creation
1802
    of the table succeeded or not, since we need to reset the binary
1803
    log state.
1804
  */
1805
  select_insert::abort();
1806
1807
  if (m_plock)
1808
  {
1910.2.7 by Brian Aker
Rename lock methods to be style + well make sense.
1809
    session->unlockTables(*m_plock);
1 by brian
clean slate
1810
    *m_plock= NULL;
1811
    m_plock= NULL;
1812
  }
1813
1814
  if (table)
1815
  {
1208.3.2 by brian
Update for Cursor renaming.
1816
    table->cursor->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
1817
    table->cursor->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
1372.1.1 by Brian Aker
Removed/rewrite to remove goto in alter table.
1818
    if (not create_info->table_existed)
1819
      session->drop_open_table(table, identifier);
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1820
    table= NULL;                                    // Safety
1 by brian
clean slate
1821
  }
1822
}
1823
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
1824
} /* namespace drizzled */