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