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