~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++;
1819.9.151 by Martin Hansson, Stewart Smith
Merge Revision revid:martin.hansson@oracle.com-20101007081311-zb72jgqjx2rs831z from MySQL InnoDB
849
850
        if (! table->records_are_comparable() || table->compare_records())
1 by brian
clean slate
851
        {
1672.3.6 by Brian Aker
First pass in encapsulating row
852
          if ((error=table->cursor->updateRecord(table->getUpdateRecord(),
853
                                                table->getInsertRecord())) &&
1 by brian
clean slate
854
              error != HA_ERR_RECORD_IS_THE_SAME)
855
          {
856
            if (info->ignore &&
1208.3.2 by brian
Update for Cursor renaming.
857
                !table->cursor->is_fatal_error(error, HA_CHECK_DUP_KEY))
1 by brian
clean slate
858
            {
859
              goto gok_or_after_err;
860
            }
861
            goto err;
862
          }
863
864
          if (error != HA_ERR_RECORD_IS_THE_SAME)
865
            info->updated++;
866
          else
867
            error= 0;
868
          /*
869
            If ON DUP KEY UPDATE updates a row instead of inserting one, it's
870
            like a regular UPDATE statement: it should not affect the value of a
871
            next SELECT LAST_INSERT_ID() or mysql_insert_id().
872
            Except if LAST_INSERT_ID(#) was in the INSERT query, which is
520.1.21 by Brian Aker
THD -> Session rename
873
            handled separately by Session::arg_of_last_insert_id_function.
1 by brian
clean slate
874
          */
1208.3.2 by brian
Update for Cursor renaming.
875
          insert_id_for_cur_row= table->cursor->insert_id_for_cur_row= 0;
1 by brian
clean slate
876
          info->copied++;
877
        }
878
879
        if (table->next_number_field)
1208.3.2 by brian
Update for Cursor renaming.
880
          table->cursor->adjust_next_insert_id_after_explicit_value(
1 by brian
clean slate
881
            table->next_number_field->val_int());
882
        info->touched++;
883
884
        goto gok_or_after_err;
885
      }
886
      else /* DUP_REPLACE */
887
      {
888
	/*
889
	  The manual defines the REPLACE semantics that it is either
890
	  an INSERT or DELETE(s) + INSERT; FOREIGN KEY checks in
891
	  InnoDB do not function in the defined way if we allow MySQL
892
	  to convert the latter operation internally to an UPDATE.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
893
          We also should not perform this conversion if we have
1 by brian
clean slate
894
          timestamp field with ON UPDATE which is different from DEFAULT.
895
          Another case when conversion should not be performed is when
896
          we have ON DELETE trigger on table so user may notice that
897
          we cheat here. Note that it is ok to do such conversion for
898
          tables which have ON UPDATE but have no ON DELETE triggers,
899
          we just should not expose this fact to users by invoking
900
          ON UPDATE triggers.
901
	*/
902
	if (last_uniq_key(table,key_nr) &&
1208.3.2 by brian
Update for Cursor renaming.
903
	    !table->cursor->referenced_by_foreign_key() &&
1 by brian
clean slate
904
            (table->timestamp_field_type == TIMESTAMP_NO_AUTO_SET ||
905
             table->timestamp_field_type == TIMESTAMP_AUTO_SET_ON_BOTH))
906
        {
1672.3.6 by Brian Aker
First pass in encapsulating row
907
          if ((error=table->cursor->updateRecord(table->getUpdateRecord(),
908
					        table->getInsertRecord())) &&
1 by brian
clean slate
909
              error != HA_ERR_RECORD_IS_THE_SAME)
910
            goto err;
911
          if (error != HA_ERR_RECORD_IS_THE_SAME)
912
            info->deleted++;
913
          else
914
            error= 0;
1208.3.2 by brian
Update for Cursor renaming.
915
          session->record_first_successful_insert_id_in_cur_stmt(table->cursor->insert_id_for_cur_row);
1 by brian
clean slate
916
          /*
917
            Since we pretend that we have done insert we should call
918
            its after triggers.
919
          */
920
          goto after_n_copied_inc;
921
        }
922
        else
923
        {
1672.3.6 by Brian Aker
First pass in encapsulating row
924
          if ((error=table->cursor->deleteRecord(table->getUpdateRecord())))
1 by brian
clean slate
925
            goto err;
926
          info->deleted++;
1208.3.2 by brian
Update for Cursor renaming.
927
          if (!table->cursor->has_transactions())
1273.1.13 by Jay Pipes
Style cleanup around TransactionContext::modified_non_trans_table and dead code removal
928
            session->transaction.stmt.markModifiedNonTransData();
1 by brian
clean slate
929
          /* Let us attempt do write_row() once more */
930
        }
931
      }
932
    }
1208.3.2 by brian
Update for Cursor renaming.
933
    session->record_first_successful_insert_id_in_cur_stmt(table->cursor->insert_id_for_cur_row);
1 by brian
clean slate
934
    /*
935
      Restore column maps if they where replaced during an duplicate key
936
      problem.
937
    */
938
    if (table->read_set != save_read_set ||
939
        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.
940
      table->column_bitmaps_set(*save_read_set, *save_write_set);
1 by brian
clean slate
941
  }
1672.3.6 by Brian Aker
First pass in encapsulating row
942
  else if ((error=table->cursor->insertRecord(table->getInsertRecord())))
1 by brian
clean slate
943
  {
944
    if (!info->ignore ||
1208.3.2 by brian
Update for Cursor renaming.
945
        table->cursor->is_fatal_error(error, HA_CHECK_DUP))
1 by brian
clean slate
946
      goto err;
1208.3.2 by brian
Update for Cursor renaming.
947
    table->cursor->restore_auto_increment(prev_insert_id);
1 by brian
clean slate
948
    goto gok_or_after_err;
949
  }
950
951
after_n_copied_inc:
952
  info->copied++;
1208.3.2 by brian
Update for Cursor renaming.
953
  session->record_first_successful_insert_id_in_cur_stmt(table->cursor->insert_id_for_cur_row);
1 by brian
clean slate
954
955
gok_or_after_err:
1208.3.2 by brian
Update for Cursor renaming.
956
  if (!table->cursor->has_transactions())
1273.1.13 by Jay Pipes
Style cleanup around TransactionContext::modified_non_trans_table and dead code removal
957
    session->transaction.stmt.markModifiedNonTransData();
51.2.2 by Patrick Galbraith
Removed DBUGs from
958
  return(0);
1 by brian
clean slate
959
960
err:
961
  info->last_errno= error;
962
  /* current_select is NULL if this is a delayed insert */
520.1.22 by Brian Aker
Second pass of thd cleanup
963
  if (session->lex->current_select)
964
    session->lex->current_select->no_error= 0;        // Give error
1216.1.1 by Brian Aker
Move print_error up to Engine.
965
  table->print_error(error,MYF(0));
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
966
1 by brian
clean slate
967
before_err:
1208.3.2 by brian
Update for Cursor renaming.
968
  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.
969
  table->column_bitmaps_set(*save_read_set, *save_write_set);
970
  return 1;
1 by brian
clean slate
971
}
972
973
974
/******************************************************************************
975
  Check that all fields with arn't null_fields are used
976
******************************************************************************/
977
520.1.22 by Brian Aker
Second pass of thd cleanup
978
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
979
                                           TableList *)
1 by brian
clean slate
980
{
981
  int err= 0;
982
1578.2.16 by Brian Aker
Merge in change to getTable() to private the field objects.
983
  for (Field **field=entry->getFields() ; *field ; field++)
1 by brian
clean slate
984
  {
1009 by Brian Aker
Merge of Monty
985
    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
986
    {
987
      /*
988
       * If the field doesn't have any default value
989
       * and there is no actual value specified in the
990
       * INSERT statement, throw error ER_NO_DEFAULT_FOR_FIELD.
991
       */
992
      if (((*field)->flags & NO_DEFAULT_VALUE_FLAG) &&
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
993
        ((*field)->real_type() != DRIZZLE_TYPE_ENUM))
1 by brian
clean slate
994
      {
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
995
        my_error(ER_NO_DEFAULT_FOR_FIELD, MYF(0), (*field)->field_name);
996
        err= 1;
1 by brian
clean slate
997
      }
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
998
    }
999
    else
1000
    {
685.4.1 by Jay Pipes
Enabled the null.test.
1001
      /*
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
1002
       * However, if an actual NULL value was specified
1003
       * for the field and the field is a NOT NULL field, 
1004
       * throw ER_BAD_NULL_ERROR.
1005
       *
685.4.1 by Jay Pipes
Enabled the null.test.
1006
       * Per the SQL standard, inserting NULL into a NOT NULL
1007
       * field requires an error to be thrown.
1008
       */
685.4.10 by Jay Pipes
Fixed bug where error 1364 was not being thrown in an appropriate place. Now, check_that_all_fields_have_given_values() method does two separate checks, one for not being in the write_set() and not having a default value (raise 1364) and another for being in the write_set() but having a NULL value set
1009
      if (((*field)->flags & NOT_NULL_FLAG) &&
1010
          (*field)->is_null())
1011
      {
1012
        my_error(ER_BAD_NULL_ERROR, MYF(0), (*field)->field_name);
1013
        err= 1;
1014
      }
1 by brian
clean slate
1015
    }
1016
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
1017
  return session->abort_on_warning ? err : 0;
1 by brian
clean slate
1018
}
1019
1020
/***************************************************************************
1021
  Store records in INSERT ... SELECT *
1022
***************************************************************************/
1023
1024
1025
/*
1026
  make insert specific preparation and checks after opening tables
1027
1028
  SYNOPSIS
1029
    mysql_insert_select_prepare()
520.1.22 by Brian Aker
Second pass of thd cleanup
1030
    session         thread handler
1 by brian
clean slate
1031
1032
  RETURN
163 by Brian Aker
Merge Monty's code.
1033
    false OK
1034
    true  Error
1 by brian
clean slate
1035
*/
1036
520.1.22 by Brian Aker
Second pass of thd cleanup
1037
bool mysql_insert_select_prepare(Session *session)
1 by brian
clean slate
1038
{
520.1.22 by Brian Aker
Second pass of thd cleanup
1039
  LEX *lex= session->lex;
846 by Brian Aker
Removing on typedeffed class.
1040
  Select_Lex *select_lex= &lex->select_lex;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1041
1 by brian
clean slate
1042
  /*
846 by Brian Aker
Removing on typedeffed class.
1043
    Select_Lex do not belong to INSERT statement, so we can't add WHERE
1 by brian
clean slate
1044
    clause if table is VIEW
1045
  */
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1046
520.1.22 by Brian Aker
Second pass of thd cleanup
1047
  if (mysql_prepare_insert(session, lex->query_tables,
1 by brian
clean slate
1048
                           lex->query_tables->table, lex->field_list, 0,
1049
                           lex->update_list, lex->value_list,
1050
                           lex->duplicates,
163 by Brian Aker
Merge Monty's code.
1051
                           &select_lex->where, true, false, false))
1052
    return(true);
1 by brian
clean slate
1053
1054
  /*
1055
    exclude first table from leaf tables list, because it belong to
1056
    INSERT
1057
  */
51.2.2 by Patrick Galbraith
Removed DBUGs from
1058
  assert(select_lex->leaf_tables != 0);
1 by brian
clean slate
1059
  lex->leaf_tables_insert= select_lex->leaf_tables;
1060
  /* skip all leaf tables belonged to view where we are insert */
327.1.7 by Brian Aker
Removed belong_to_view variable
1061
  select_lex->leaf_tables= select_lex->leaf_tables->next_leaf;
163 by Brian Aker
Merge Monty's code.
1062
  return(false);
1 by brian
clean slate
1063
}
1064
1065
327.2.4 by Brian Aker
Refactoring table.h
1066
select_insert::select_insert(TableList *table_list_par, Table *table_par,
1 by brian
clean slate
1067
                             List<Item> *fields_par,
1068
                             List<Item> *update_fields,
1069
                             List<Item> *update_values,
1070
                             enum_duplicates duplic,
1755.2.1 by Brian Aker
Remove dead memset call.
1071
                             bool ignore_check_option_errors) :
1072
  table_list(table_list_par), table(table_par), fields(fields_par),
1073
  autoinc_value_of_last_inserted_row(0),
1074
  insert_into_view(table_list_par && 0 != 0)
1 by brian
clean slate
1075
{
1076
  info.handle_duplicates= duplic;
1077
  info.ignore= ignore_check_option_errors;
1078
  info.update_fields= update_fields;
1079
  info.update_values= update_values;
1080
}
1081
1082
1083
int
848 by Brian Aker
typdef class removal (just... use the name of the class).
1084
select_insert::prepare(List<Item> &values, Select_Lex_Unit *u)
1 by brian
clean slate
1085
{
520.1.22 by Brian Aker
Second pass of thd cleanup
1086
  LEX *lex= session->lex;
1 by brian
clean slate
1087
  int res;
1088
  table_map map= 0;
846 by Brian Aker
Removing on typedeffed class.
1089
  Select_Lex *lex_current_select_save= lex->current_select;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1090
1 by brian
clean slate
1091
1092
  unit= u;
1093
1094
  /*
1095
    Since table in which we are going to insert is added to the first
1096
    select, LEX::current_select should point to the first select while
1097
    we are fixing fields from insert list.
1098
  */
1099
  lex->current_select= &lex->select_lex;
520.1.22 by Brian Aker
Second pass of thd cleanup
1100
  res= check_insert_fields(session, table_list, *fields, values,
1 by brian
clean slate
1101
                           !insert_into_view, &map) ||
520.1.22 by Brian Aker
Second pass of thd cleanup
1102
       setup_fields(session, 0, values, MARK_COLUMNS_READ, 0, 0);
1 by brian
clean slate
1103
1104
  if (!res && fields->elements)
1105
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
1106
    bool saved_abort_on_warning= session->abort_on_warning;
1107
    session->abort_on_warning= !info.ignore;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1108
    res= check_that_all_fields_are_given_values(session, table_list->table,
1 by brian
clean slate
1109
                                                table_list);
520.1.22 by Brian Aker
Second pass of thd cleanup
1110
    session->abort_on_warning= saved_abort_on_warning;
1 by brian
clean slate
1111
  }
1112
1113
  if (info.handle_duplicates == DUP_UPDATE && !res)
1114
  {
1115
    Name_resolution_context *context= &lex->select_lex.context;
1116
    Name_resolution_context_state ctx_state;
1117
1118
    /* Save the state of the current name resolution context. */
1119
    ctx_state.save_state(context, table_list);
1120
1121
    /* Perform name resolution only in the first table - 'table_list'. */
1122
    table_list->next_local= 0;
1123
    context->resolve_in_table_list_only(table_list);
1124
520.1.22 by Brian Aker
Second pass of thd cleanup
1125
    res= res || check_update_fields(session, context->table_list,
1 by brian
clean slate
1126
                                    *info.update_fields, &map);
1127
    /*
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1128
      When we are not using GROUP BY and there are no ungrouped aggregate functions
1 by brian
clean slate
1129
      we can refer to other tables in the ON DUPLICATE KEY part.
1130
      We use next_name_resolution_table descructively, so check it first (views?)
1131
    */
51.2.2 by Patrick Galbraith
Removed DBUGs from
1132
    assert (!table_list->next_name_resolution_table);
1 by brian
clean slate
1133
    if (lex->select_lex.group_list.elements == 0 &&
1134
        !lex->select_lex.with_sum_func)
1135
      /*
1136
        We must make a single context out of the two separate name resolution contexts :
1137
        the INSERT table and the tables in the SELECT part of INSERT ... SELECT.
1138
        To do that we must concatenate the two lists
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1139
      */
1140
      table_list->next_name_resolution_table=
1 by brian
clean slate
1141
        ctx_state.get_first_name_resolution_table();
1142
520.1.22 by Brian Aker
Second pass of thd cleanup
1143
    res= res || setup_fields(session, 0, *info.update_values,
1 by brian
clean slate
1144
                             MARK_COLUMNS_READ, 0, 0);
1145
    if (!res)
1146
    {
1147
      /*
1148
        Traverse the update values list and substitute fields from the
1149
        select for references (Item_ref objects) to them. This is done in
1150
        order to get correct values from those fields when the select
1151
        employs a temporary table.
1152
      */
1153
      List_iterator<Item> li(*info.update_values);
1154
      Item *item;
1155
1156
      while ((item= li++))
1157
      {
1158
        item->transform(&Item::update_value_transformer,
481 by Brian Aker
Remove all of uchar.
1159
                        (unsigned char*)lex->current_select);
1 by brian
clean slate
1160
      }
1161
    }
1162
1163
    /* Restore the current context. */
1164
    ctx_state.restore_state(context, table_list);
1165
  }
1166
1167
  lex->current_select= lex_current_select_save;
1168
  if (res)
51.2.2 by Patrick Galbraith
Removed DBUGs from
1169
    return(1);
1 by brian
clean slate
1170
  /*
1171
    if it is INSERT into join view then check_insert_fields already found
1172
    real table for insert
1173
  */
1174
  table= table_list->table;
1175
1176
  /*
1177
    Is table which we are changing used somewhere in other parts of
1178
    query
1179
  */
1220.1.13 by Brian Aker
Remove mysql_lock_have_duplicate() (we don't have merge, and our partition
1180
  if (unique_table(table_list, table_list->next_global))
1 by brian
clean slate
1181
  {
1182
    /* Using same table for INSERT and SELECT */
1183
    lex->current_select->options|= OPTION_BUFFER_RESULT;
1184
    lex->current_select->join->select_options|= OPTION_BUFFER_RESULT;
1185
  }
1186
  else if (!(lex->current_select->options & OPTION_BUFFER_RESULT))
1187
  {
1188
    /*
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1189
      We must not yet prepare the result table if it is the same as one of the
1190
      source tables (INSERT SELECT). The preparation may disable
1 by brian
clean slate
1191
      indexes on the result table, which may be used during the select, if it
1192
      is the same table (Bug #6034). Do the preparation after the select phase
1193
      in select_insert::prepare2().
1194
      We won't start bulk inserts at all if this statement uses functions or
1195
      should invoke triggers since they may access to the same table too.
1196
    */
1208.3.2 by brian
Update for Cursor renaming.
1197
    table->cursor->ha_start_bulk_insert((ha_rows) 0);
1 by brian
clean slate
1198
  }
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
1199
  table->restoreRecordAsDefault();		// Get empty record
1 by brian
clean slate
1200
  table->next_number_field=table->found_next_number_field;
1201
520.1.22 by Brian Aker
Second pass of thd cleanup
1202
  session->cuted_fields=0;
1 by brian
clean slate
1203
  if (info.ignore || info.handle_duplicates != DUP_ERROR)
1208.3.2 by brian
Update for Cursor renaming.
1204
    table->cursor->extra(HA_EXTRA_IGNORE_DUP_KEY);
1 by brian
clean slate
1205
  if (info.handle_duplicates == DUP_REPLACE)
1208.3.2 by brian
Update for Cursor renaming.
1206
    table->cursor->extra(HA_EXTRA_WRITE_CAN_REPLACE);
1 by brian
clean slate
1207
  if (info.handle_duplicates == DUP_UPDATE)
1208.3.2 by brian
Update for Cursor renaming.
1208
    table->cursor->extra(HA_EXTRA_INSERT_WITH_UPDATE);
520.1.22 by Brian Aker
Second pass of thd cleanup
1209
  session->abort_on_warning= !info.ignore;
1 by brian
clean slate
1210
  table->mark_columns_needed_for_insert();
1211
1212
51.2.2 by Patrick Galbraith
Removed DBUGs from
1213
  return(res);
1 by brian
clean slate
1214
}
1215
1216
1217
/*
1218
  Finish the preparation of the result table.
1219
1220
  SYNOPSIS
1221
    select_insert::prepare2()
1222
    void
1223
1224
  DESCRIPTION
1225
    If the result table is the same as one of the source tables (INSERT SELECT),
1226
    the result table is not finally prepared at the join prepair phase.
1227
    Do the final preparation now.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1228
1 by brian
clean slate
1229
  RETURN
1230
    0   OK
1231
*/
1232
1233
int select_insert::prepare2(void)
1234
{
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1235
520.1.22 by Brian Aker
Second pass of thd cleanup
1236
  if (session->lex->current_select->options & OPTION_BUFFER_RESULT)
1208.3.2 by brian
Update for Cursor renaming.
1237
    table->cursor->ha_start_bulk_insert((ha_rows) 0);
51.2.2 by Patrick Galbraith
Removed DBUGs from
1238
  return(0);
1 by brian
clean slate
1239
}
1240
1241
1242
void select_insert::cleanup()
1243
{
1244
  /* select_insert/select_create are never re-used in prepared statement */
51.2.2 by Patrick Galbraith
Removed DBUGs from
1245
  assert(0);
1 by brian
clean slate
1246
}
1247
1248
select_insert::~select_insert()
1249
{
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1250
1 by brian
clean slate
1251
  if (table)
1252
  {
1253
    table->next_number_field=0;
163 by Brian Aker
Merge Monty's code.
1254
    table->auto_increment_field_not_null= false;
1208.3.2 by brian
Update for Cursor renaming.
1255
    table->cursor->ha_reset();
1 by brian
clean slate
1256
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
1257
  session->count_cuted_fields= CHECK_FIELD_IGNORE;
1258
  session->abort_on_warning= 0;
51.2.2 by Patrick Galbraith
Removed DBUGs from
1259
  return;
1 by brian
clean slate
1260
}
1261
1262
1263
bool select_insert::send_data(List<Item> &values)
1264
{
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1265
1 by brian
clean slate
1266
  bool error=0;
1267
1268
  if (unit->offset_limit_cnt)
1269
  {						// using limit offset,count
1270
    unit->offset_limit_cnt--;
51.2.2 by Patrick Galbraith
Removed DBUGs from
1271
    return(0);
1 by brian
clean slate
1272
  }
1273
520.1.22 by Brian Aker
Second pass of thd cleanup
1274
  session->count_cuted_fields= CHECK_FIELD_WARN;	// Calculate cuted fields
1 by brian
clean slate
1275
  store_values(values);
520.1.22 by Brian Aker
Second pass of thd cleanup
1276
  session->count_cuted_fields= CHECK_FIELD_IGNORE;
1277
  if (session->is_error())
51.2.2 by Patrick Galbraith
Removed DBUGs from
1278
    return(1);
1 by brian
clean slate
1279
991.1.1 by Stewart Smith
Release latches in case bulk insert takes a long time
1280
  // 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
1281
  plugin::TransactionalStorageEngine::releaseTemporaryLatches(session);
991.1.1 by Stewart Smith
Release latches in case bulk insert takes a long time
1282
520.1.22 by Brian Aker
Second pass of thd cleanup
1283
  error= write_record(session, table, &info);
1552.1.3 by Brian Aker
Fixes the assertion bug on handling of auto increment (sort of worthless,
1284
  table->auto_increment_field_not_null= false;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1285
1 by brian
clean slate
1286
  if (!error)
1287
  {
1288
    if (info.handle_duplicates == DUP_UPDATE)
1289
    {
1290
      /*
1291
        Restore fields of the record since it is possible that they were
1292
        changed by ON DUPLICATE KEY UPDATE clause.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1293
1 by brian
clean slate
1294
        If triggers exist then whey can modify some fields which were not
1295
        originally touched by INSERT ... SELECT, so we have to restore
1296
        their original values for the next row.
1297
      */
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
1298
      table->restoreRecordAsDefault();
1 by brian
clean slate
1299
    }
1300
    if (table->next_number_field)
1301
    {
1302
      /*
1303
        If no value has been autogenerated so far, we need to remember the
1304
        value we just saw, we may need to send it to client in the end.
1305
      */
520.1.22 by Brian Aker
Second pass of thd cleanup
1306
      if (session->first_successful_insert_id_in_cur_stmt == 0) // optimization
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1307
        autoinc_value_of_last_inserted_row=
1 by brian
clean slate
1308
          table->next_number_field->val_int();
1309
      /*
1310
        Clear auto-increment field for the next record, if triggers are used
1311
        we will clear it twice, but this should be cheap.
1312
      */
1313
      table->next_number_field->reset();
1314
    }
1315
  }
51.2.2 by Patrick Galbraith
Removed DBUGs from
1316
  return(error);
1 by brian
clean slate
1317
}
1318
1319
1320
void select_insert::store_values(List<Item> &values)
1321
{
1322
  if (fields->elements)
1235.1.11 by Brian Aker
Small cleanups, did in MERGE table only engine flag.
1323
    fill_record(session, *fields, values, true);
1 by brian
clean slate
1324
  else
1578.2.16 by Brian Aker
Merge in change to getTable() to private the field objects.
1325
    fill_record(session, table->getFields(), values, true);
1 by brian
clean slate
1326
}
1327
482 by Brian Aker
Remove uint.
1328
void select_insert::send_error(uint32_t errcode,const char *err)
1 by brian
clean slate
1329
{
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1330
1 by brian
clean slate
1331
1332
  my_message(errcode, err, MYF(0));
1333
51.2.2 by Patrick Galbraith
Removed DBUGs from
1334
  return;
1 by brian
clean slate
1335
}
1336
1337
1338
bool select_insert::send_eof()
1339
{
1340
  int error;
1208.3.2 by brian
Update for Cursor renaming.
1341
  bool const trans_table= table->cursor->has_transactions();
151 by Brian Aker
Ulonglong to uint64_t
1342
  uint64_t id;
1 by brian
clean slate
1343
  bool changed;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1344
1208.3.2 by brian
Update for Cursor renaming.
1345
  error= table->cursor->ha_end_bulk_insert();
1346
  table->cursor->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
1347
  table->cursor->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
1 by brian
clean slate
1348
1349
  if ((changed= (info.copied || info.deleted || info.updated)))
1350
  {
1351
    /*
1352
      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.
1353
      and autocommitOrRollback.
1 by brian
clean slate
1354
    */
1273.1.13 by Jay Pipes
Style cleanup around TransactionContext::modified_non_trans_table and dead code removal
1355
    if (session->transaction.stmt.hasModifiedNonTransData())
1356
      session->transaction.all.markModifiedNonTransData();
1 by brian
clean slate
1357
  }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1358
  assert(trans_table || !changed ||
1273.1.13 by Jay Pipes
Style cleanup around TransactionContext::modified_non_trans_table and dead code removal
1359
              session->transaction.stmt.hasModifiedNonTransData());
1 by brian
clean slate
1360
1208.3.2 by brian
Update for Cursor renaming.
1361
  table->cursor->ha_release_auto_increment();
1 by brian
clean slate
1362
1363
  if (error)
1364
  {
1216.1.1 by Brian Aker
Move print_error up to Engine.
1365
    table->print_error(error,MYF(0));
1126.10.12 by Padraig O'Sullivan
Added calls to the dtrace probes related to insertion.
1366
    DRIZZLE_INSERT_SELECT_DONE(error, 0);
1367
    return 1;
1 by brian
clean slate
1368
  }
1369
  char buff[160];
1370
  if (info.ignore)
1366.1.11 by Siddharth Prakash Singh
sprintf->snprintf continued
1371
    snprintf(buff, sizeof(buff), ER(ER_INSERT_INFO), (ulong) info.records,
520.1.22 by Brian Aker
Second pass of thd cleanup
1372
	    (ulong) (info.records - info.copied), (ulong) session->cuted_fields);
1 by brian
clean slate
1373
  else
1366.1.11 by Siddharth Prakash Singh
sprintf->snprintf continued
1374
    snprintf(buff, sizeof(buff), ER(ER_INSERT_INFO), (ulong) info.records,
520.1.22 by Brian Aker
Second pass of thd cleanup
1375
	    (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.
1376
  session->row_count_func= info.copied + info.deleted + info.updated;
1 by brian
clean slate
1377
520.1.22 by Brian Aker
Second pass of thd cleanup
1378
  id= (session->first_successful_insert_id_in_cur_stmt > 0) ?
1379
    session->first_successful_insert_id_in_cur_stmt :
1380
    (session->arg_of_last_insert_id_function ?
1381
     session->first_successful_insert_id_in_prev_stmt :
1 by brian
clean slate
1382
     (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.
1383
  session->my_ok((ulong) session->row_count_func,
1384
                 info.copied + info.deleted + info.touched, id, buff);
1625.2.2 by Joe Daly
add counter logic for rows sent/received/inserted/updated
1385
  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.
1386
  DRIZZLE_INSERT_SELECT_DONE(0, session->row_count_func);
1387
  return 0;
1 by brian
clean slate
1388
}
1389
1390
void select_insert::abort() {
1391
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1392
1 by brian
clean slate
1393
  /*
1394
    If the creation of the table failed (due to a syntax error, for
1395
    example), no table will have been opened and therefore 'table'
1396
    will be NULL. In that case, we still need to execute the rollback
1397
    and the end of the function.
1398
   */
1399
  if (table)
1400
  {
1401
    bool changed, transactional_table;
1402
1208.3.2 by brian
Update for Cursor renaming.
1403
    table->cursor->ha_end_bulk_insert();
1 by brian
clean slate
1404
1405
    /*
1406
      If at least one row has been inserted/modified and will stay in
1407
      the table (the table doesn't have transactions) we must write to
1408
      the binlog (and the error code will make the slave stop).
1409
1410
      For many errors (example: we got a duplicate key error while
1411
      inserting into a MyISAM table), no row will be added to the table,
1412
      so passing the error to the slave will not help since there will
1413
      be an error code mismatch (the inserts will succeed on the slave
1414
      with no error).
1415
1416
      If table creation failed, the number of rows modified will also be
1417
      zero, so no check for that is made.
1418
    */
1419
    changed= (info.copied || info.deleted || info.updated);
1208.3.2 by brian
Update for Cursor renaming.
1420
    transactional_table= table->cursor->has_transactions();
51.2.2 by Patrick Galbraith
Removed DBUGs from
1421
    assert(transactional_table || !changed ||
1273.1.13 by Jay Pipes
Style cleanup around TransactionContext::modified_non_trans_table and dead code removal
1422
		session->transaction.stmt.hasModifiedNonTransData());
1208.3.2 by brian
Update for Cursor renaming.
1423
    table->cursor->ha_release_auto_increment();
1 by brian
clean slate
1424
  }
1425
1126.10.12 by Padraig O'Sullivan
Added calls to the dtrace probes related to insertion.
1426
  if (DRIZZLE_INSERT_SELECT_DONE_ENABLED())
1427
  {
1428
    DRIZZLE_INSERT_SELECT_DONE(0, info.copied + info.deleted + info.updated);
1429
  }
1430
51.2.2 by Patrick Galbraith
Removed DBUGs from
1431
  return;
1 by brian
clean slate
1432
}
1433
1434
1435
/***************************************************************************
1436
  CREATE TABLE (SELECT) ...
1437
***************************************************************************/
1438
1439
/*
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1440
  Create table from lists of fields and items (or just return Table
1 by brian
clean slate
1441
  object for pre-opened existing table).
1442
1443
  SYNOPSIS
1444
    create_table_from_items()
520.1.22 by Brian Aker
Second pass of thd cleanup
1445
      session          in     Thread object
1 by brian
clean slate
1446
      create_info  in     Create information (like MAX_ROWS, ENGINE or
1447
                          temporary table flag)
327.2.4 by Brian Aker
Refactoring table.h
1448
      create_table in     Pointer to TableList object providing database
1 by brian
clean slate
1449
                          and name for table to be created or to be open
1450
      alter_info   in/out Initial list of columns and indexes for the table
1451
                          to be created
1452
      items        in     List of items which should be used to produce rest
1453
                          of fields for the table (corresponding fields will
1454
                          be added to the end of alter_info->create_list)
1711.6.1 by Brian Aker
Style on structure cleanup
1455
      lock         out    Pointer to the DrizzleLock object for table created
1 by brian
clean slate
1456
                          (or open temporary table) will be returned in this
1457
                          parameter. Since this table is not included in
520.1.21 by Brian Aker
THD -> Session rename
1458
                          Session::lock caller is responsible for explicitly
1 by brian
clean slate
1459
                          unlocking this table.
1460
      hooks
1461
1462
  NOTES
1463
    This function behaves differently for base and temporary tables:
1464
    - 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)
1465
      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
1466
      emit error or warning and return pre-opened Table object) or special
1 by brian
clean slate
1467
      placeholder was put in table cache that guarantees that this table
1468
      won't be created or opened until the placeholder will be removed
1469
      (so there is an exclusive lock on this table).
1470
    - We don't pre-open existing temporary table, instead we either open
1471
      or create and then open table in this function.
1472
1473
    Since this function contains some logic specific to CREATE TABLE ...
1474
    SELECT it should be changed before it can be used in other contexts.
1475
1476
  RETURN VALUES
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1477
    non-zero  Pointer to Table object for table created or opened
1 by brian
clean slate
1478
    0         Error
1479
*/
1480
520.1.22 by Brian Aker
Second pass of thd cleanup
1481
static Table *create_table_from_items(Session *session, HA_CREATE_INFO *create_info,
327.2.4 by Brian Aker
Refactoring table.h
1482
                                      TableList *create_table,
1320.1.2 by Brian Aker
More reference counting.
1483
				      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.
1484
                                      AlterInfo *alter_info,
1 by brian
clean slate
1485
                                      List<Item> *items,
1222.2.3 by Brian Aker
Remove a few more options, from options in HA_CREATE_INFO.
1486
                                      bool is_if_not_exists,
1711.6.1 by Brian Aker
Style on structure cleanup
1487
                                      DrizzleLock **lock,
1340.1.1 by Brian Aker
Length usage of identifier down the tree.
1488
				      TableIdentifier &identifier)
1 by brian
clean slate
1489
{
1608.2.4 by Brian Aker
Update for having share declared type.
1490
  TableShare share(message::Table::INTERNAL);
482 by Brian Aker
Remove uint.
1491
  uint32_t select_field_count= items->elements;
1 by brian
clean slate
1492
  /* Add selected items to field list */
1493
  List_iterator_fast<Item> it(*items);
1494
  Item *item;
1495
  Field *tmp_field;
1496
  bool not_used;
1497
1395.1.10 by Brian Aker
Trying to be consistent through interface on state of tmp.
1498
  if (not (identifier.isTmp()) && create_table->table->db_stat)
1 by brian
clean slate
1499
  {
1109.1.3 by Brian Aker
Move names around a bit (to align similar methods)
1500
    /* 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.
1501
    if (is_if_not_exists)
1 by brian
clean slate
1502
    {
1503
      create_info->table_existed= 1;		// Mark that table existed
520.1.22 by Brian Aker
Second pass of thd cleanup
1504
      push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
1 by brian
clean slate
1505
                          ER_TABLE_EXISTS_ERROR, ER(ER_TABLE_EXISTS_ERROR),
1874.1.2 by Brian Aker
Encapsulate table_name from table_list.
1506
                          create_table->getTableName());
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1507
      return create_table->table;
1 by brian
clean slate
1508
    }
1509
1874.1.2 by Brian Aker
Encapsulate table_name from table_list.
1510
    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
1511
    return NULL;
1 by brian
clean slate
1512
  }
1513
1514
  {
1859.2.11 by Brian Aker
Merge in so that shell requires a share to construct.
1515
    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.
1516
    tmp_table.timestamp_field= 0;
1517
1518
    tmp_table.getMutableShare()->db_create_options= 0;
1519
    tmp_table.getMutableShare()->blob_ptr_size= portable_sizeof_char_ptr;
1520
1521
    if (not table_proto.engine().name().compare("MyISAM"))
1522
      tmp_table.getMutableShare()->db_low_byte_first= true;
1523
    else if (not table_proto.engine().name().compare("MEMORY"))
1524
      tmp_table.getMutableShare()->db_low_byte_first= true;
1525
1526
    tmp_table.null_row= false;
1527
    tmp_table.maybe_null= false;
1528
1529
    tmp_table.in_use= session;
1530
1531
    while ((item=it++))
1835.1.3 by Brian Aker
Fix variable such that we no longer pass share to varstring on creation.
1532
    {
1859.2.9 by Brian Aker
We add a "shell" table type, used only during field creation.
1533
      CreateField *cr_field;
1534
      Field *field, *def_field;
1535
      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.
1536
      {
1859.2.9 by Brian Aker
We add a "shell" table type, used only during field creation.
1537
        if (item->result_type() != STRING_RESULT)
1538
        {
1539
          field= item->tmp_table_field(&tmp_table);
1540
        }
1541
        else
1542
        {
1543
          field= item->tmp_table_field_from_field_type(&tmp_table, 0);
1544
        }
1835.1.3 by Brian Aker
Fix variable such that we no longer pass share to varstring on creation.
1545
      }
1 by brian
clean slate
1546
      else
1835.1.3 by Brian Aker
Fix variable such that we no longer pass share to varstring on creation.
1547
      {
1859.2.9 by Brian Aker
We add a "shell" table type, used only during field creation.
1548
        field= create_tmp_field(session, &tmp_table, item, item->type(),
1549
                                (Item ***) 0, &tmp_field, &def_field, false,
1550
                                false, false, 0);
1551
      }
1552
1553
      if (!field ||
1554
          !(cr_field=new CreateField(field,(item->type() == Item::FIELD_ITEM ?
1555
                                            ((Item_field *)item)->field :
1556
                                            (Field*) 0))))
1557
      {
1558
        return NULL;
1559
      }
1560
1561
      if (item->maybe_null)
1562
      {
1563
        cr_field->flags &= ~NOT_NULL_FLAG;
1564
      }
1565
1566
      alter_info->create_list.push_back(cr_field);
1567
    }
1 by brian
clean slate
1568
  }
1569
1570
  /*
1571
    Create and lock table.
1572
1573
    Note that we either creating (or opening existing) temporary table or
1574
    creating base table on which name we have exclusive lock. So code below
1575
    should not cause deadlocks or races.
1576
  */
1859.2.9 by Brian Aker
We add a "shell" table type, used only during field creation.
1577
  Table *table= 0;
1 by brian
clean slate
1578
  {
1320.1.2 by Brian Aker
More reference counting.
1579
    if (not mysql_create_table_no_lock(session,
1340.1.1 by Brian Aker
Length usage of identifier down the tree.
1580
				       identifier,
1581
				       create_info,
1582
				       table_proto,
1583
				       alter_info,
1584
				       false,
1585
				       select_field_count,
1586
				       is_if_not_exists))
1 by brian
clean slate
1587
    {
1395.1.10 by Brian Aker
Trying to be consistent through interface on state of tmp.
1588
      if (create_info->table_existed && not identifier.isTmp())
1 by brian
clean slate
1589
      {
1590
        /*
1591
          This means that someone created table underneath server
1592
          or it was created via different mysqld front-end to the
1593
          cluster. We don't have much options but throw an error.
1594
        */
1874.1.2 by Brian Aker
Encapsulate table_name from table_list.
1595
        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
1596
        return NULL;
1 by brian
clean slate
1597
      }
1598
1395.1.10 by Brian Aker
Trying to be consistent through interface on state of tmp.
1599
      if (not identifier.isTmp())
1 by brian
clean slate
1600
      {
1938.4.12 by Brian Aker
Merge in lock refactor, this just encapsulates.
1601
        /* CREATE TABLE... has found that the table already exists for insert and is adapting to use it */
1602
        boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex());
1874.3.2 by Brian Aker
Updating a few bits of the interface to be specific to table::Concurrent
1603
1604
        if (create_table->table)
1605
        {
1878.1.1 by Brian Aker
Stick to static cast.
1606
          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
1607
1608
          if (concurrent_table->reopen_name_locked_table(create_table, session))
1609
          {
1954.2.4 by Brian Aker
Remove quick_rm_table().
1610
            plugin::StorageEngine::dropTable(*session, identifier);
1874.3.2 by Brian Aker
Updating a few bits of the interface to be specific to table::Concurrent
1611
          }
1612
          else
1613
          {
1614
            table= create_table->table;
1615
          }
1616
        }
1617
        else
1 by brian
clean slate
1618
        {
1954.2.4 by Brian Aker
Remove quick_rm_table().
1619
          plugin::StorageEngine::dropTable(*session, identifier);
1 by brian
clean slate
1620
        }
1621
      }
1622
      else
1623
      {
1320.1.2 by Brian Aker
More reference counting.
1624
        if (not (table= session->openTable(create_table, (bool*) 0,
1625
                                           DRIZZLE_OPEN_TEMPORARY_ONLY)) &&
1626
            not create_info->table_existed)
1 by brian
clean slate
1627
        {
1628
          /*
1629
            This shouldn't happen as creation of temporary table should make
1630
            it preparable for open. But let us do close_temporary_table() here
1631
            just in case.
1632
          */
1864.3.13 by Brian Aker
Usage of find_temporary_table() to identifier.
1633
          session->drop_temporary_table(identifier);
1 by brian
clean slate
1634
        }
1635
      }
1636
    }
1859.2.9 by Brian Aker
We add a "shell" table type, used only during field creation.
1637
    if (not table)                                   // open failed
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1638
      return NULL;
1 by brian
clean slate
1639
  }
1640
1641
  table->reginfo.lock_type=TL_WRITE;
1910.2.7 by Brian Aker
Rename lock methods to be style + well make sense.
1642
  if (! ((*lock)= session->lockTables(&table, 1, DRIZZLE_LOCK_IGNORE_FLUSH, &not_used)))
1 by brian
clean slate
1643
  {
1644
    if (*lock)
1645
    {
1910.2.7 by Brian Aker
Rename lock methods to be style + well make sense.
1646
      session->unlockTables(*lock);
1 by brian
clean slate
1647
      *lock= 0;
1648
    }
1649
1372.1.1 by Brian Aker
Removed/rewrite to remove goto in alter table.
1650
    if (not create_info->table_existed)
1651
      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
1652
    return NULL;
1 by brian
clean slate
1653
  }
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1654
1655
  return table;
1 by brian
clean slate
1656
}
1657
1658
1659
int
848 by Brian Aker
typdef class removal (just... use the name of the class).
1660
select_create::prepare(List<Item> &values, Select_Lex_Unit *u)
1 by brian
clean slate
1661
{
1711.6.1 by Brian Aker
Style on structure cleanup
1662
  DrizzleLock *extra_lock= NULL;
1 by brian
clean slate
1663
  /*
1308.2.11 by Jay Pipes
* Adds CREATE TABLE as a specific CreateTableStatement message in the
1664
    For replication, the CREATE-SELECT statement is written
1665
    in two pieces: the first transaction messsage contains 
1666
    the CREATE TABLE statement as a CreateTableStatement message
1667
    necessary to create the table.
1668
    
1669
    The second transaction message contains all the InsertStatement
1670
    and associated InsertRecords that should go into the table.
1 by brian
clean slate
1671
   */
1672
1673
  unit= u;
1674
1340.1.1 by Brian Aker
Length usage of identifier down the tree.
1675
  if (not (table= create_table_from_items(session, create_info, create_table,
1676
					  table_proto,
1677
					  alter_info, &values,
1678
					  is_if_not_exists,
1679
					  &extra_lock, identifier)))
1608.2.4 by Brian Aker
Update for having share declared type.
1680
  {
51.2.2 by Patrick Galbraith
Removed DBUGs from
1681
    return(-1);				// abort() deletes table
1608.2.4 by Brian Aker
Update for having share declared type.
1682
  }
1 by brian
clean slate
1683
1684
  if (extra_lock)
1685
  {
51.2.2 by Patrick Galbraith
Removed DBUGs from
1686
    assert(m_plock == NULL);
1 by brian
clean slate
1687
1395.1.10 by Brian Aker
Trying to be consistent through interface on state of tmp.
1688
    if (identifier.isTmp())
1 by brian
clean slate
1689
      m_plock= &m_lock;
1690
    else
520.1.22 by Brian Aker
Second pass of thd cleanup
1691
      m_plock= &session->extra_lock;
1 by brian
clean slate
1692
1693
    *m_plock= extra_lock;
1694
  }
1695
1578.2.10 by Brian Aker
keys and fields partial encapsulation.
1696
  if (table->getShare()->sizeFields() < values.elements)
1 by brian
clean slate
1697
  {
1698
    my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), 1);
51.2.2 by Patrick Galbraith
Removed DBUGs from
1699
    return(-1);
1 by brian
clean slate
1700
  }
1701
1702
 /* First field to copy */
1578.2.16 by Brian Aker
Merge in change to getTable() to private the field objects.
1703
  field= table->getFields() + table->getShare()->sizeFields() - values.elements;
1 by brian
clean slate
1704
1705
  /* Mark all fields that are given values */
1706
  for (Field **f= field ; *f ; f++)
1005.2.12 by Monty Taylor
Moved some things to the API.
1707
    table->setWriteSet((*f)->field_index);
1 by brian
clean slate
1708
1709
  /* Don't set timestamp if used */
1710
  table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
1711
  table->next_number_field=table->found_next_number_field;
1712
997.5.1 by chris
Replace macros around unireg.h, store_record,restore_record,cmp_record,empty_record
1713
  table->restoreRecordAsDefault();      // Get empty record
520.1.22 by Brian Aker
Second pass of thd cleanup
1714
  session->cuted_fields=0;
1 by brian
clean slate
1715
  if (info.ignore || info.handle_duplicates != DUP_ERROR)
1208.3.2 by brian
Update for Cursor renaming.
1716
    table->cursor->extra(HA_EXTRA_IGNORE_DUP_KEY);
1 by brian
clean slate
1717
  if (info.handle_duplicates == DUP_REPLACE)
1208.3.2 by brian
Update for Cursor renaming.
1718
    table->cursor->extra(HA_EXTRA_WRITE_CAN_REPLACE);
1 by brian
clean slate
1719
  if (info.handle_duplicates == DUP_UPDATE)
1208.3.2 by brian
Update for Cursor renaming.
1720
    table->cursor->extra(HA_EXTRA_INSERT_WITH_UPDATE);
1721
  table->cursor->ha_start_bulk_insert((ha_rows) 0);
520.1.22 by Brian Aker
Second pass of thd cleanup
1722
  session->abort_on_warning= !info.ignore;
1723
  if (check_that_all_fields_are_given_values(session, table, table_list))
51.2.2 by Patrick Galbraith
Removed DBUGs from
1724
    return(1);
1 by brian
clean slate
1725
  table->mark_columns_needed_for_insert();
1208.3.2 by brian
Update for Cursor renaming.
1726
  table->cursor->extra(HA_EXTRA_WRITE_CACHE);
51.2.2 by Patrick Galbraith
Removed DBUGs from
1727
  return(0);
1 by brian
clean slate
1728
}
1729
1730
void select_create::store_values(List<Item> &values)
1731
{
1235.1.11 by Brian Aker
Small cleanups, did in MERGE table only engine flag.
1732
  fill_record(session, field, values, true);
1 by brian
clean slate
1733
}
1734
1735
482 by Brian Aker
Remove uint.
1736
void select_create::send_error(uint32_t errcode,const char *err)
1 by brian
clean slate
1737
{
1738
  /*
1739
    This will execute any rollbacks that are necessary before writing
1740
    the transcation cache.
1741
1742
    We disable the binary log since nothing should be written to the
1743
    binary log.  This disabling is important, since we potentially do
1744
    a "roll back" of non-transactional tables by removing the table,
1745
    and the actual rollback might generate events that should not be
1746
    written to the binary log.
1747
1748
  */
1749
  select_insert::send_error(errcode, err);
1750
51.2.2 by Patrick Galbraith
Removed DBUGs from
1751
  return;
1 by brian
clean slate
1752
}
1753
1754
1755
bool select_create::send_eof()
1756
{
1757
  bool tmp=select_insert::send_eof();
1758
  if (tmp)
1759
    abort();
1760
  else
1761
  {
1762
    /*
1763
      Do an implicit commit at end of statement for non-temporary
1764
      tables.  This can fail, but we should unlock the table
1765
      nevertheless.
1766
    */
1608.2.3 by Brian Aker
Encapsulate type for TableShare.
1767
    if (!table->getShare()->getType())
1 by brian
clean slate
1768
    {
1273.1.2 by Jay Pipes
This patch does not change any algorithms or code paths,
1769
      TransactionServices &transaction_services= TransactionServices::singleton();
1405.3.5 by Jay Pipes
TransactionServices method names now meet code style guidelines.
1770
      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.
1771
      (void) session->endActiveTransaction();
1 by brian
clean slate
1772
    }
1773
1208.3.2 by brian
Update for Cursor renaming.
1774
    table->cursor->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
1775
    table->cursor->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
1 by brian
clean slate
1776
    if (m_plock)
1777
    {
1910.2.7 by Brian Aker
Rename lock methods to be style + well make sense.
1778
      session->unlockTables(*m_plock);
1 by brian
clean slate
1779
      *m_plock= NULL;
1780
      m_plock= NULL;
1781
    }
1782
  }
1783
  return tmp;
1784
}
1785
1786
1787
void select_create::abort()
1788
{
1789
  /*
1790
    In select_insert::abort() we roll back the statement, including
1791
    truncating the transaction cache of the binary log. To do this, we
1792
    pretend that the statement is transactional, even though it might
1793
    be the case that it was not.
1794
1795
    We roll back the statement prior to deleting the table and prior
1796
    to releasing the lock on the table, since there might be potential
1797
    for failure if the rollback is executed after the drop or after
1798
    unlocking the table.
1799
1800
    We also roll back the statement regardless of whether the creation
1801
    of the table succeeded or not, since we need to reset the binary
1802
    log state.
1803
  */
1804
  select_insert::abort();
1805
1806
  if (m_plock)
1807
  {
1910.2.7 by Brian Aker
Rename lock methods to be style + well make sense.
1808
    session->unlockTables(*m_plock);
1 by brian
clean slate
1809
    *m_plock= NULL;
1810
    m_plock= NULL;
1811
  }
1812
1813
  if (table)
1814
  {
1208.3.2 by brian
Update for Cursor renaming.
1815
    table->cursor->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
1816
    table->cursor->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
1372.1.1 by Brian Aker
Removed/rewrite to remove goto in alter table.
1817
    if (not create_info->table_existed)
1818
      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
1819
    table= NULL;                                    // Safety
1 by brian
clean slate
1820
  }
1821
}
1822
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
1823
} /* namespace drizzled */