~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_insert.cc

  • Committer: Lee
  • Date: 2008-10-07 17:11:23 UTC
  • mto: (489.1.1 codestyle)
  • mto: This revision was merged to the branch mainline in revision 491.
  • Revision ID: lbieber@lbieber-desktop-20081007171123-s6ex14jq8jfuql8e
breakĀ outĀ Field_longstr

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
 
12
12
   You should have received a copy of the GNU General Public License
13
13
   along with this program; if not, write to the Free Software
14
 
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */
 
14
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
15
15
 
16
16
 
17
17
/* Insert of records */
18
18
 
19
 
#include <config.h>
20
 
#include <cstdio>
 
19
/*
 
20
  INSERT DELAYED
 
21
 
 
22
  Drizzle has a different form of DELAYED then MySQL. DELAYED is just
 
23
  a hint to the the sorage engine (which can then do whatever it likes.
 
24
*/
 
25
#include <drizzled/server_includes.h>
21
26
#include <drizzled/sql_select.h>
22
 
#include <drizzled/show.h>
23
 
#include <drizzled/error.h>
24
 
#include <drizzled/name_resolution_context_state.h>
25
 
#include <drizzled/probes.h>
26
 
#include <drizzled/sql_base.h>
27
 
#include <drizzled/sql_load.h>
28
 
#include <drizzled/field/epoch.h>
29
 
#include <drizzled/lock.h>
30
 
#include <drizzled/sql_table.h>
31
 
#include <drizzled/pthread_globals.h>
32
 
#include <drizzled/transaction_services.h>
33
 
#include <drizzled/plugin/transactional_storage_engine.h>
34
 
#include <drizzled/select_insert.h>
35
 
#include <drizzled/select_create.h>
36
 
 
37
 
#include <drizzled/table/shell.h>
38
 
 
39
 
namespace drizzled
40
 
{
41
 
 
42
 
extern plugin::StorageEngine *heap_engine;
43
 
extern plugin::StorageEngine *myisam_engine;
 
27
#include <drizzled/sql_show.h>
 
28
#include "rpl_mi.h"
 
29
#include <drizzled/drizzled_error_messages.h>
 
30
 
 
31
/* Define to force use of my_malloc() if the allocated memory block is big */
 
32
 
 
33
#ifndef HAVE_ALLOCA
 
34
#define my_safe_alloca(size, min_length) my_alloca(size)
 
35
#define my_safe_afree(ptr, size, min_length) my_afree(ptr)
 
36
#else
 
37
#define my_safe_alloca(size, min_length) ((size <= min_length) ? my_alloca(size) : malloc(size))
 
38
#define my_safe_afree(ptr, size, min_length) if (size > min_length) free(ptr)
 
39
#endif
 
40
 
 
41
 
44
42
 
45
43
/*
46
44
  Check if insert fields are correct.
47
45
 
48
46
  SYNOPSIS
49
47
    check_insert_fields()
50
 
    session                         The current thread.
 
48
    thd                         The current thread.
51
49
    table                       The table for insert.
52
50
    fields                      The insert fields.
53
51
    values                      The insert values.
63
61
    -1          Error
64
62
*/
65
63
 
66
 
static int check_insert_fields(Session *session, TableList *table_list,
 
64
static int check_insert_fields(THD *thd, TableList *table_list,
67
65
                               List<Item> &fields, List<Item> &values,
68
66
                               bool check_unique,
69
 
                               table_map *)
 
67
                               table_map *map __attribute__((unused)))
70
68
{
71
69
  Table *table= table_list->table;
72
70
 
73
71
  if (fields.elements == 0 && values.elements != 0)
74
72
  {
75
 
    if (values.elements != table->getShare()->sizeFields())
 
73
    if (values.elements != table->s->fields)
76
74
    {
77
75
      my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), 1L);
78
76
      return -1;
83
81
      No fields are provided so all fields must be provided in the values.
84
82
      Thus we set all bits in the write set.
85
83
    */
86
 
    table->setWriteSet();
 
84
    bitmap_set_all(table->write_set);
87
85
  }
88
86
  else
89
87
  {                                             // Part field list
90
 
    Select_Lex *select_lex= &session->getLex()->select_lex;
 
88
    SELECT_LEX *select_lex= &thd->lex->select_lex;
91
89
    Name_resolution_context *context= &select_lex->context;
92
90
    Name_resolution_context_state ctx_state;
93
91
    int res;
98
96
      return -1;
99
97
    }
100
98
 
101
 
    session->dup_field= 0;
 
99
    thd->dup_field= 0;
102
100
 
103
101
    /* Save the state of the current name resolution context. */
104
102
    ctx_state.save_state(context, table_list);
109
107
    */
110
108
    table_list->next_local= 0;
111
109
    context->resolve_in_table_list_only(table_list);
112
 
    res= setup_fields(session, 0, fields, MARK_COLUMNS_WRITE, 0, 0);
 
110
    res= setup_fields(thd, 0, fields, MARK_COLUMNS_WRITE, 0, 0);
113
111
 
114
112
    /* Restore the current context. */
115
113
    ctx_state.restore_state(context, table_list);
117
115
    if (res)
118
116
      return -1;
119
117
 
120
 
    if (check_unique && session->dup_field)
 
118
    if (check_unique && thd->dup_field)
121
119
    {
122
 
      my_error(ER_FIELD_SPECIFIED_TWICE, MYF(0), session->dup_field->field_name);
 
120
      my_error(ER_FIELD_SPECIFIED_TWICE, MYF(0), thd->dup_field->field_name);
123
121
      return -1;
124
122
    }
125
123
    if (table->timestamp_field) // Don't automaticly set timestamp if used
126
124
    {
127
 
      if (table->timestamp_field->isWriteSet())
128
 
      {
 
125
      if (bitmap_is_set(table->write_set,
 
126
                        table->timestamp_field->field_index))
129
127
        clear_timestamp_auto_bits(table->timestamp_field_type,
130
128
                                  TIMESTAMP_AUTO_SET_ON_INSERT);
131
 
      }
132
129
      else
133
130
      {
134
 
        table->setWriteSet(table->timestamp_field->position());
 
131
        bitmap_set_bit(table->write_set,
 
132
                       table->timestamp_field->field_index);
135
133
      }
136
134
    }
137
135
  }
145
143
 
146
144
  SYNOPSIS
147
145
    check_update_fields()
148
 
    session                         The current thread.
 
146
    thd                         The current thread.
149
147
    insert_table_list           The insert table list.
150
148
    table                       The table for update.
151
149
    update_fields               The update fields.
159
157
    -1          Error
160
158
*/
161
159
 
162
 
static int check_update_fields(Session *session, TableList *insert_table_list,
 
160
static int check_update_fields(THD *thd, TableList *insert_table_list,
163
161
                               List<Item> &update_fields,
164
 
                               table_map *)
 
162
                               table_map *map __attribute__((unused)))
165
163
{
166
164
  Table *table= insert_table_list->table;
167
165
  bool timestamp_mark= false;
172
170
      Unmark the timestamp field so that we can check if this is modified
173
171
      by update_fields
174
172
    */
175
 
    timestamp_mark= table->write_set->test(table->timestamp_field->position());
176
 
    table->write_set->reset(table->timestamp_field->position());
 
173
    timestamp_mark= bitmap_test_and_clear(table->write_set,
 
174
                                          table->timestamp_field->field_index);
177
175
  }
178
176
 
179
177
  /* Check the fields we are going to modify */
180
 
  if (setup_fields(session, 0, update_fields, MARK_COLUMNS_WRITE, 0, 0))
 
178
  if (setup_fields(thd, 0, update_fields, MARK_COLUMNS_WRITE, 0, 0))
181
179
    return -1;
182
180
 
183
181
  if (table->timestamp_field)
184
182
  {
185
183
    /* Don't set timestamp column if this is modified. */
186
 
    if (table->timestamp_field->isWriteSet())
187
 
    {
 
184
    if (bitmap_is_set(table->write_set,
 
185
                      table->timestamp_field->field_index))
188
186
      clear_timestamp_auto_bits(table->timestamp_field_type,
189
187
                                TIMESTAMP_AUTO_SET_ON_UPDATE);
190
 
    }
191
 
 
192
188
    if (timestamp_mark)
193
 
    {
194
 
      table->setWriteSet(table->timestamp_field->position());
195
 
    }
 
189
      bitmap_set_bit(table->write_set,
 
190
                     table->timestamp_field->field_index);
196
191
  }
197
192
  return 0;
198
193
}
207
202
*/
208
203
 
209
204
static
210
 
void upgrade_lock_type(Session *,
 
205
void upgrade_lock_type(THD *thd __attribute__((unused)),
211
206
                       thr_lock_type *lock_type,
212
207
                       enum_duplicates duplic,
213
 
                       bool )
 
208
                       bool is_multi_insert __attribute__((unused)))
214
209
{
215
210
  if (duplic == DUP_UPDATE ||
216
211
      (duplic == DUP_REPLACE && *lock_type == TL_WRITE_CONCURRENT_INSERT))
229
224
  end of dispatch_command().
230
225
*/
231
226
 
232
 
bool insert_query(Session *session,TableList *table_list,
 
227
bool mysql_insert(THD *thd,TableList *table_list,
233
228
                  List<Item> &fields,
234
229
                  List<List_item> &values_list,
235
230
                  List<Item> &update_fields,
240
235
  int error;
241
236
  bool transactional_table, joins_freed= false;
242
237
  bool changed;
 
238
  bool was_insert_delayed= (table_list->lock_type ==  TL_WRITE_DELAYED);
243
239
  uint32_t value_count;
244
240
  ulong counter = 1;
245
241
  uint64_t id;
246
 
  CopyInfo info;
 
242
  COPY_INFO info;
247
243
  Table *table= 0;
248
 
  List<List_item>::iterator its(values_list.begin());
 
244
  List_iterator_fast<List_item> its(values_list);
249
245
  List_item *values;
250
246
  Name_resolution_context *context;
251
247
  Name_resolution_context_state ctx_state;
252
248
  thr_lock_type lock_type;
253
249
  Item *unused_conds= 0;
254
 
 
 
250
  
255
251
 
256
252
  /*
257
253
    Upgrade lock type if the requested lock is incompatible with
258
254
    the current connection mode or table operation.
259
255
  */
260
 
  upgrade_lock_type(session, &table_list->lock_type, duplic,
 
256
  upgrade_lock_type(thd, &table_list->lock_type, duplic,
261
257
                    values_list.elements > 1);
262
258
 
263
 
  if (session->openTablesLock(table_list))
 
259
  /*
 
260
    We can't write-delayed into a table locked with LOCK TABLES:
 
261
    this will lead to a deadlock, since the delayed thread will
 
262
    never be able to get a lock on the table. QQQ: why not
 
263
    upgrade the lock here instead?
 
264
  */
 
265
  if (table_list->lock_type == TL_WRITE_DELAYED && thd->locked_tables &&
 
266
      find_locked_table(thd, table_list->db, table_list->table_name))
264
267
  {
265
 
    DRIZZLE_INSERT_DONE(1, 0);
266
 
    return true;
 
268
    my_error(ER_DELAYED_INSERT_TABLE_LOCKED, MYF(0),
 
269
             table_list->table_name);
 
270
    return(true);
267
271
  }
268
272
 
 
273
  {
 
274
    if (open_and_lock_tables(thd, table_list))
 
275
      return(true);
 
276
  }
269
277
  lock_type= table_list->lock_type;
270
278
 
271
 
  session->set_proc_info("init");
272
 
  session->used_tables=0;
 
279
  thd_proc_info(thd, "init");
 
280
  thd->used_tables=0;
273
281
  values= its++;
274
282
  value_count= values->elements;
275
283
 
276
 
  if (prepare_insert(session, table_list, table, fields, values,
 
284
  if (mysql_prepare_insert(thd, table_list, table, fields, values,
277
285
                           update_fields, update_values, duplic, &unused_conds,
278
286
                           false,
279
287
                           (fields.elements || !value_count ||
280
288
                            (0) != 0), !ignore))
281
 
  {
282
 
    if (table != NULL)
283
 
      table->cursor->ha_release_auto_increment();
284
 
    if (!joins_freed)
285
 
      free_underlaid_joins(session, &session->getLex()->select_lex);
286
 
    session->setAbortOnWarning(false);
287
 
    DRIZZLE_INSERT_DONE(1, 0);
288
 
    return true;
289
 
  }
 
289
    goto abort;
290
290
 
291
291
  /* mysql_prepare_insert set table_list->table if it was not set */
292
292
  table= table_list->table;
293
293
 
294
 
  context= &session->getLex()->select_lex.context;
 
294
  context= &thd->lex->select_lex.context;
295
295
  /*
296
296
    These three asserts test the hypothesis that the resetting of the name
297
297
    resolution context below is not necessary at all since the list of local
317
317
    if (values->elements != value_count)
318
318
    {
319
319
      my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), counter);
320
 
 
321
 
      if (table != NULL)
322
 
        table->cursor->ha_release_auto_increment();
323
 
      if (!joins_freed)
324
 
        free_underlaid_joins(session, &session->getLex()->select_lex);
325
 
      session->setAbortOnWarning(false);
326
 
      DRIZZLE_INSERT_DONE(1, 0);
327
 
 
328
 
      return true;
329
 
    }
330
 
    if (setup_fields(session, 0, *values, MARK_COLUMNS_READ, 0, 0))
331
 
    {
332
 
      if (table != NULL)
333
 
        table->cursor->ha_release_auto_increment();
334
 
      if (!joins_freed)
335
 
        free_underlaid_joins(session, &session->getLex()->select_lex);
336
 
      session->setAbortOnWarning(false);
337
 
      DRIZZLE_INSERT_DONE(1, 0);
338
 
      return true;
339
 
    }
 
320
      goto abort;
 
321
    }
 
322
    if (setup_fields(thd, 0, *values, MARK_COLUMNS_READ, 0, 0))
 
323
      goto abort;
340
324
  }
341
 
  its= values_list.begin();
342
 
 
 
325
  its.rewind ();
 
326
 
343
327
  /* Restore the current context. */
344
328
  ctx_state.restore_state(context, table_list);
345
329
 
346
330
  /*
347
 
    Fill in the given fields and dump it to the table cursor
 
331
    Fill in the given fields and dump it to the table file
348
332
  */
 
333
  memset(&info, 0, sizeof(info));
349
334
  info.ignore= ignore;
350
335
  info.handle_duplicates=duplic;
351
336
  info.update_fields= &update_fields;
356
341
    For single line insert, generate an error if try to set a NOT NULL field
357
342
    to NULL.
358
343
  */
359
 
  session->count_cuted_fields= ignore ? CHECK_FIELD_WARN : CHECK_FIELD_ERROR_FOR_NULL;
360
 
 
361
 
  session->cuted_fields = 0L;
 
344
  thd->count_cuted_fields= ((values_list.elements == 1 &&
 
345
                             !ignore) ?
 
346
                            CHECK_FIELD_ERROR_FOR_NULL :
 
347
                            CHECK_FIELD_WARN);
 
348
  thd->cuted_fields = 0L;
362
349
  table->next_number_field=table->found_next_number_field;
363
350
 
 
351
  if (thd->slave_thread &&
 
352
      (info.handle_duplicates == DUP_UPDATE) &&
 
353
      (table->next_number_field != NULL) &&
 
354
      rpl_master_has_bug(&active_mi->rli, 24432))
 
355
    goto abort;
 
356
 
364
357
  error=0;
365
 
  session->set_proc_info("update");
 
358
  thd_proc_info(thd, "update");
366
359
  if (duplic == DUP_REPLACE)
367
 
    table->cursor->extra(HA_EXTRA_WRITE_CAN_REPLACE);
 
360
    table->file->extra(HA_EXTRA_WRITE_CAN_REPLACE);
368
361
  if (duplic == DUP_UPDATE)
369
 
    table->cursor->extra(HA_EXTRA_INSERT_WITH_UPDATE);
 
362
    table->file->extra(HA_EXTRA_INSERT_WITH_UPDATE);
370
363
  {
371
364
    if (duplic != DUP_ERROR || ignore)
372
 
      table->cursor->extra(HA_EXTRA_IGNORE_DUP_KEY);
373
 
    table->cursor->ha_start_bulk_insert(values_list.elements);
 
365
      table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
 
366
    table->file->ha_start_bulk_insert(values_list.elements);
374
367
  }
375
368
 
376
369
 
377
 
  session->setAbortOnWarning(not ignore);
 
370
  thd->abort_on_warning= !ignore;
378
371
 
379
372
  table->mark_columns_needed_for_insert();
380
373
 
382
375
  {
383
376
    if (fields.elements || !value_count)
384
377
    {
385
 
      table->restoreRecordAsDefault();  // Get empty record
386
 
      if (fill_record(session, fields, *values))
 
378
      restore_record(table,s->default_values);  // Get empty record
 
379
      if (fill_record(thd, fields, *values, 0))
387
380
      {
388
 
        if (values_list.elements != 1 && ! session->is_error())
 
381
        if (values_list.elements != 1 && ! thd->is_error())
389
382
        {
390
383
          info.records++;
391
384
          continue;
392
385
        }
393
386
        /*
394
 
          TODO: set session->abort_on_warning if values_list.elements == 1
 
387
          TODO: set thd->abort_on_warning if values_list.elements == 1
395
388
          and check that all items return warning in case of problem with
396
389
          storing field.
397
390
        */
401
394
    }
402
395
    else
403
396
    {
404
 
      table->restoreRecordAsDefault();  // Get empty record
405
 
 
406
 
      if (fill_record(session, table->getFields(), *values))
407
 
      {
408
 
        if (values_list.elements != 1 && ! session->is_error())
 
397
      if (thd->used_tables)                     // Column used in values()
 
398
        restore_record(table,s->default_values);        // Get empty record
 
399
      else
 
400
      {
 
401
        /*
 
402
          Fix delete marker. No need to restore rest of record since it will
 
403
          be overwritten by fill_record() anyway (and fill_record() does not
 
404
          use default values in this case).
 
405
        */
 
406
        table->record[0][0]= table->s->default_values[0];
 
407
      }
 
408
      if (fill_record(thd, table->field, *values, 0))
 
409
      {
 
410
        if (values_list.elements != 1 && ! thd->is_error())
409
411
        {
410
412
          info.records++;
411
413
          continue;
415
417
      }
416
418
    }
417
419
 
418
 
    // Release latches in case bulk insert takes a long time
419
 
    plugin::TransactionalStorageEngine::releaseTemporaryLatches(session);
420
 
 
421
 
    error=write_record(session, table ,&info);
 
420
    error=write_record(thd, table ,&info);
422
421
    if (error)
423
422
      break;
424
 
    session->row_count++;
 
423
    thd->row_count++;
425
424
  }
426
425
 
427
 
  free_underlaid_joins(session, &session->getLex()->select_lex);
 
426
  free_underlaid_joins(thd, &thd->lex->select_lex);
428
427
  joins_freed= true;
429
428
 
430
429
  /*
436
435
      Do not do this release if this is a delayed insert, it would steal
437
436
      auto_inc values from the delayed_insert thread as they share Table.
438
437
    */
439
 
    table->cursor->ha_release_auto_increment();
440
 
    if (table->cursor->ha_end_bulk_insert() && !error)
 
438
    table->file->ha_release_auto_increment();
 
439
    if (table->file->ha_end_bulk_insert() && !error)
441
440
    {
442
 
      table->print_error(errno,MYF(0));
 
441
      table->file->print_error(my_errno,MYF(0));
443
442
      error=1;
444
443
    }
445
444
    if (duplic != DUP_ERROR || ignore)
446
 
      table->cursor->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
447
 
 
448
 
    transactional_table= table->cursor->has_transactions();
449
 
 
450
 
    changed= (info.copied || info.deleted || info.updated);
451
 
    if ((changed && error <= 0) || session->transaction.stmt.hasModifiedNonTransData())
452
 
    {
453
 
      if (session->transaction.stmt.hasModifiedNonTransData())
454
 
        session->transaction.all.markModifiedNonTransData();
455
 
    }
456
 
    assert(transactional_table || !changed || session->transaction.stmt.hasModifiedNonTransData());
 
445
      table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
 
446
 
 
447
    transactional_table= table->file->has_transactions();
 
448
 
 
449
    if ((changed= (info.copied || info.deleted || info.updated)))
 
450
    {
 
451
      /*
 
452
        Invalidate the table in the query cache if something changed.
 
453
        For the transactional algorithm to work the invalidation must be
 
454
        before binlog writing and ha_autocommit_or_rollback
 
455
      */
 
456
    }
 
457
    if ((changed && error <= 0) || thd->transaction.stmt.modified_non_trans_table || was_insert_delayed)
 
458
    {
 
459
      if (mysql_bin_log.is_open())
 
460
      {
 
461
        if (error <= 0)
 
462
        {
 
463
          /*
 
464
            [Guilhem wrote] Temporary errors may have filled
 
465
            thd->net.last_error/errno.  For example if there has
 
466
            been a disk full error when writing the row, and it was
 
467
            MyISAM, then thd->net.last_error/errno will be set to
 
468
            "disk full"... and the my_pwrite() will wait until free
 
469
            space appears, and so when it finishes then the
 
470
            write_row() was entirely successful
 
471
          */
 
472
          /* todo: consider removing */
 
473
          thd->clear_error();
 
474
        }
 
475
        /* bug#22725:
 
476
 
 
477
        A query which per-row-loop can not be interrupted with
 
478
        KILLED, like INSERT, and that does not invoke stored
 
479
        routines can be binlogged with neglecting the KILLED error.
 
480
        
 
481
        If there was no error (error == zero) until after the end of
 
482
        inserting loop the KILLED flag that appeared later can be
 
483
        disregarded since previously possible invocation of stored
 
484
        routines did not result in any error due to the KILLED.  In
 
485
        such case the flag is ignored for constructing binlog event.
 
486
        */
 
487
        assert(thd->killed != THD::KILL_BAD_DATA || error > 0);
 
488
        if (thd->binlog_query(THD::ROW_QUERY_TYPE,
 
489
                              thd->query, thd->query_length,
 
490
                              transactional_table, false,
 
491
                              (error>0) ? thd->killed : THD::NOT_KILLED) &&
 
492
            transactional_table)
 
493
        {
 
494
          error=1;
 
495
        }
 
496
      }
 
497
      if (thd->transaction.stmt.modified_non_trans_table)
 
498
        thd->transaction.all.modified_non_trans_table= true;
 
499
    }
 
500
    assert(transactional_table || !changed || 
 
501
                thd->transaction.stmt.modified_non_trans_table);
457
502
 
458
503
  }
459
 
  session->set_proc_info("end");
 
504
  thd_proc_info(thd, "end");
460
505
  /*
461
506
    We'll report to the client this id:
462
507
    - if the table contains an autoincrement column and we successfully
467
512
    inserted, the id of the last "inserted" row (if IGNORE, that value may not
468
513
    have been really inserted but ignored).
469
514
  */
470
 
  id= (session->first_successful_insert_id_in_cur_stmt > 0) ?
471
 
    session->first_successful_insert_id_in_cur_stmt :
472
 
    (session->arg_of_last_insert_id_function ?
473
 
     session->first_successful_insert_id_in_prev_stmt :
 
515
  id= (thd->first_successful_insert_id_in_cur_stmt > 0) ?
 
516
    thd->first_successful_insert_id_in_cur_stmt :
 
517
    (thd->arg_of_last_insert_id_function ?
 
518
     thd->first_successful_insert_id_in_prev_stmt :
474
519
     ((table->next_number_field && info.copied) ?
475
520
     table->next_number_field->val_int() : 0));
476
521
  table->next_number_field=0;
477
 
  session->count_cuted_fields= CHECK_FIELD_IGNORE;
 
522
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;
478
523
  table->auto_increment_field_not_null= false;
479
524
  if (duplic == DUP_REPLACE)
480
 
    table->cursor->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
 
525
    table->file->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
481
526
 
482
527
  if (error)
483
 
  {
484
 
    if (table != NULL)
485
 
      table->cursor->ha_release_auto_increment();
486
 
    if (!joins_freed)
487
 
      free_underlaid_joins(session, &session->getLex()->select_lex);
488
 
    session->setAbortOnWarning(false);
489
 
    DRIZZLE_INSERT_DONE(1, 0);
490
 
    return true;
491
 
  }
492
 
 
493
 
  if (values_list.elements == 1 && (!(session->options & OPTION_WARNINGS) ||
494
 
                                    !session->cuted_fields))
495
 
  {
496
 
    session->row_count_func= info.copied + info.deleted + info.updated;
497
 
    session->my_ok((ulong) session->rowCount(),
498
 
                   info.copied + info.deleted + info.touched, id);
 
528
    goto abort;
 
529
  if (values_list.elements == 1 && (!(thd->options & OPTION_WARNINGS) ||
 
530
                                    !thd->cuted_fields))
 
531
  {
 
532
    thd->row_count_func= info.copied + info.deleted +
 
533
                         ((thd->client_capabilities & CLIENT_FOUND_ROWS) ?
 
534
                          info.touched : info.updated);
 
535
    my_ok(thd, (ulong) thd->row_count_func, id);
499
536
  }
500
537
  else
501
538
  {
502
539
    char buff[160];
 
540
    ha_rows updated=((thd->client_capabilities & CLIENT_FOUND_ROWS) ?
 
541
                     info.touched : info.updated);
503
542
    if (ignore)
504
 
      snprintf(buff, sizeof(buff), ER(ER_INSERT_INFO), (ulong) info.records,
505
 
              (ulong) (info.records - info.copied), (ulong) session->cuted_fields);
 
543
      sprintf(buff, ER(ER_INSERT_INFO), (ulong) info.records,
 
544
              (ulong) (info.records - info.copied), (ulong) thd->cuted_fields);
506
545
    else
507
 
      snprintf(buff, sizeof(buff), ER(ER_INSERT_INFO), (ulong) info.records,
508
 
              (ulong) (info.deleted + info.updated), (ulong) session->cuted_fields);
509
 
    session->row_count_func= info.copied + info.deleted + info.updated;
510
 
    session->my_ok((ulong) session->rowCount(),
511
 
                   info.copied + info.deleted + info.touched, id, buff);
 
546
      sprintf(buff, ER(ER_INSERT_INFO), (ulong) info.records,
 
547
              (ulong) (info.deleted + updated), (ulong) thd->cuted_fields);
 
548
    thd->row_count_func= info.copied + info.deleted + updated;
 
549
    ::my_ok(thd, (ulong) thd->row_count_func, id, buff);
512
550
  }
513
 
  session->status_var.inserted_row_count+= session->rowCount();
514
 
  session->setAbortOnWarning(false);
515
 
  DRIZZLE_INSERT_DONE(0, session->rowCount());
 
551
  thd->abort_on_warning= 0;
 
552
  DRIZZLE_INSERT_END();
 
553
  return(false);
516
554
 
517
 
  return false;
 
555
abort:
 
556
  if (table != NULL)
 
557
    table->file->ha_release_auto_increment();
 
558
  if (!joins_freed)
 
559
    free_underlaid_joins(thd, &thd->lex->select_lex);
 
560
  thd->abort_on_warning= 0;
 
561
  DRIZZLE_INSERT_END();
 
562
  return(true);
518
563
}
519
564
 
520
565
 
522
567
  Check if table can be updated
523
568
 
524
569
  SYNOPSIS
525
 
     prepare_insert_check_table()
526
 
     session            Thread handle
 
570
     mysql_prepare_insert_check_table()
 
571
     thd                Thread handle
527
572
     table_list         Table list
528
573
     fields             List of fields to be updated
529
574
     where              Pointer to where clause
534
579
     true  ERROR
535
580
*/
536
581
 
537
 
static bool prepare_insert_check_table(Session *session, TableList *table_list,
538
 
                                             List<Item> &,
 
582
static bool mysql_prepare_insert_check_table(THD *thd, TableList *table_list,
 
583
                                             List<Item> &fields __attribute__((unused)),
539
584
                                             bool select_insert)
540
585
{
541
 
 
 
586
  
542
587
 
543
588
  /*
544
589
     first table in list is the one we'll INSERT into, requires INSERT_ACL.
547
592
     than INSERT.
548
593
  */
549
594
 
550
 
  if (setup_tables_and_check_access(session, &session->getLex()->select_lex.context,
551
 
                                    &session->getLex()->select_lex.top_join_list,
 
595
  if (setup_tables_and_check_access(thd, &thd->lex->select_lex.context,
 
596
                                    &thd->lex->select_lex.top_join_list,
552
597
                                    table_list,
553
 
                                    &session->getLex()->select_lex.leaf_tables,
 
598
                                    &thd->lex->select_lex.leaf_tables,
554
599
                                    select_insert))
555
600
    return(true);
556
601
 
562
607
  Prepare items in INSERT statement
563
608
 
564
609
  SYNOPSIS
565
 
    prepare_insert()
566
 
    session                     Thread handler
 
610
    mysql_prepare_insert()
 
611
    thd                 Thread handler
567
612
    table_list          Global/local table list
568
613
    table               Table to insert into (can be NULL if table should
569
 
                        be taken from table_list->table)
 
614
                        be taken from table_list->table)    
570
615
    where               Where clause (for insert ... select)
571
616
    select_insert       true if INSERT ... SELECT statement
572
 
    check_fields        true if need to check that all INSERT fields are
 
617
    check_fields        true if need to check that all INSERT fields are 
573
618
                        given values.
574
 
    abort_on_warning    whether to report if some INSERT field is not
 
619
    abort_on_warning    whether to report if some INSERT field is not 
575
620
                        assigned as an error (true) or as a warning (false).
576
621
 
577
622
  TODO (in far future)
583
628
  WARNING
584
629
    You MUST set table->insert_values to 0 after calling this function
585
630
    before releasing the table object.
586
 
 
 
631
  
587
632
  RETURN VALUE
588
633
    false OK
589
634
    true  error
590
635
*/
591
636
 
592
 
bool prepare_insert(Session *session, TableList *table_list,
 
637
bool mysql_prepare_insert(THD *thd, TableList *table_list,
593
638
                          Table *table, List<Item> &fields, List_item *values,
594
639
                          List<Item> &update_fields, List<Item> &update_values,
595
640
                          enum_duplicates duplic,
596
 
                          COND **,
 
641
                          COND **where __attribute__((unused)),
597
642
                          bool select_insert,
598
643
                          bool check_fields, bool abort_on_warning)
599
644
{
600
 
  Select_Lex *select_lex= &session->getLex()->select_lex;
 
645
  SELECT_LEX *select_lex= &thd->lex->select_lex;
601
646
  Name_resolution_context *context= &select_lex->context;
602
647
  Name_resolution_context_state ctx_state;
603
648
  bool insert_into_view= (0 != 0);
604
649
  bool res= 0;
605
650
  table_map map= 0;
606
 
 
 
651
  
607
652
  /* INSERT should have a SELECT or VALUES clause */
608
653
  assert (!select_insert || !values);
609
654
 
610
655
  /*
611
656
    For subqueries in VALUES() we should not see the table in which we are
612
657
    inserting (for INSERT ... SELECT this is done by changing table_list,
613
 
    because INSERT ... SELECT share Select_Lex it with SELECT.
 
658
    because INSERT ... SELECT share SELECT_LEX it with SELECT.
614
659
  */
615
 
  if (not select_insert)
 
660
  if (!select_insert)
616
661
  {
617
 
    for (Select_Lex_Unit *un= select_lex->first_inner_unit();
 
662
    for (SELECT_LEX_UNIT *un= select_lex->first_inner_unit();
618
663
         un;
619
664
         un= un->next_unit())
620
665
    {
621
 
      for (Select_Lex *sl= un->first_select();
 
666
      for (SELECT_LEX *sl= un->first_select();
622
667
           sl;
623
668
           sl= sl->next_select())
624
669
      {
630
675
  if (duplic == DUP_UPDATE)
631
676
  {
632
677
    /* it should be allocated before Item::fix_fields() */
633
 
    if (table_list->set_insert_values(session->mem_root))
 
678
    if (table_list->set_insert_values(thd->mem_root))
634
679
      return(true);
635
680
  }
636
681
 
637
 
  if (prepare_insert_check_table(session, table_list, fields, select_insert))
 
682
  if (mysql_prepare_insert_check_table(thd, table_list, fields, select_insert))
638
683
    return(true);
639
684
 
640
685
 
654
699
    table_list->next_local= 0;
655
700
    context->resolve_in_table_list_only(table_list);
656
701
 
657
 
    res= check_insert_fields(session, context->table_list, fields, *values,
 
702
    res= check_insert_fields(thd, context->table_list, fields, *values,
658
703
                             !insert_into_view, &map) ||
659
 
      setup_fields(session, 0, *values, MARK_COLUMNS_READ, 0, 0);
 
704
      setup_fields(thd, 0, *values, MARK_COLUMNS_READ, 0, 0);
660
705
 
661
706
    if (!res && check_fields)
662
707
    {
663
 
      bool saved_abort_on_warning= session->abortOnWarning();
664
 
 
665
 
      session->setAbortOnWarning(abort_on_warning);
666
 
      res= check_that_all_fields_are_given_values(session,
667
 
                                                  table ? table :
 
708
      bool saved_abort_on_warning= thd->abort_on_warning;
 
709
      thd->abort_on_warning= abort_on_warning;
 
710
      res= check_that_all_fields_are_given_values(thd, 
 
711
                                                  table ? table : 
668
712
                                                  context->table_list->table,
669
713
                                                  context->table_list);
670
 
      session->setAbortOnWarning(saved_abort_on_warning);
 
714
      thd->abort_on_warning= saved_abort_on_warning;
671
715
    }
672
716
 
673
717
    if (!res && duplic == DUP_UPDATE)
674
718
    {
675
 
      res= check_update_fields(session, context->table_list, update_fields, &map);
 
719
      res= check_update_fields(thd, context->table_list, update_fields, &map);
676
720
    }
677
721
 
678
722
    /* Restore the current context. */
679
723
    ctx_state.restore_state(context, table_list);
680
724
 
681
 
    if (not res)
682
 
      res= setup_fields(session, 0, update_values, MARK_COLUMNS_READ, 0, 0);
 
725
    if (!res)
 
726
      res= setup_fields(thd, 0, update_values, MARK_COLUMNS_READ, 0, 0);
683
727
  }
684
728
 
685
729
  if (res)
686
730
    return(res);
687
731
 
688
 
  if (not table)
 
732
  if (!table)
689
733
    table= table_list->table;
690
734
 
691
 
  if (not select_insert)
 
735
  if (!select_insert)
692
736
  {
693
737
    TableList *duplicate;
694
 
    if ((duplicate= unique_table(table_list, table_list->next_global, true)))
 
738
    if ((duplicate= unique_table(thd, table_list, table_list->next_global, 1)))
695
739
    {
696
 
      my_error(ER_UPDATE_TABLE_USED, MYF(0), table_list->alias);
697
 
 
698
 
      return true;
 
740
      update_non_unique_table_error(table_list, "INSERT", duplicate);
 
741
      return(true);
699
742
    }
700
743
  }
701
 
 
702
744
  if (duplic == DUP_UPDATE || duplic == DUP_REPLACE)
703
745
    table->prepare_for_position();
704
 
 
705
 
  return false;
 
746
  return(false);
706
747
}
707
748
 
708
749
 
710
751
 
711
752
static int last_uniq_key(Table *table,uint32_t keynr)
712
753
{
713
 
  while (++keynr < table->getShare()->sizeKeys())
 
754
  while (++keynr < table->s->keys)
714
755
    if (table->key_info[keynr].flags & HA_NOSAME)
715
756
      return 0;
716
757
  return 1;
723
764
 
724
765
  SYNOPSIS
725
766
     write_record()
726
 
      session   - thread context
 
767
      thd   - thread context
727
768
      table - table to which record should be written
728
 
      info  - CopyInfo structure describing handling of duplicates
 
769
      info  - COPY_INFO structure describing handling of duplicates
729
770
              and which is used for counting number of records inserted
730
771
              and deleted.
731
772
 
735
776
    then both on update triggers will work instead. Similarly both on
736
777
    delete triggers will be invoked if we will delete conflicting records.
737
778
 
738
 
    Sets session->transaction.stmt.modified_non_trans_data to true if table which is updated didn't have
 
779
    Sets thd->transaction.stmt.modified_non_trans_table to true if table which is updated didn't have
739
780
    transactions.
740
781
 
741
782
  RETURN VALUE
744
785
*/
745
786
 
746
787
 
747
 
int write_record(Session *session, Table *table,CopyInfo *info)
 
788
int write_record(THD *thd, Table *table,COPY_INFO *info)
748
789
{
749
790
  int error;
750
 
  std::vector<unsigned char> key;
751
 
  boost::dynamic_bitset<> *save_read_set, *save_write_set;
752
 
  uint64_t prev_insert_id= table->cursor->next_insert_id;
 
791
  char *key=0;
 
792
  MY_BITMAP *save_read_set, *save_write_set;
 
793
  uint64_t prev_insert_id= table->file->next_insert_id;
753
794
  uint64_t insert_id_for_cur_row= 0;
754
 
 
 
795
  
755
796
 
756
797
  info->records++;
757
798
  save_read_set=  table->read_set;
758
799
  save_write_set= table->write_set;
759
800
 
760
 
  if (info->handle_duplicates == DUP_REPLACE || info->handle_duplicates == DUP_UPDATE)
 
801
  if (info->handle_duplicates == DUP_REPLACE ||
 
802
      info->handle_duplicates == DUP_UPDATE)
761
803
  {
762
 
    while ((error=table->cursor->insertRecord(table->getInsertRecord())))
 
804
    while ((error=table->file->ha_write_row(table->record[0])))
763
805
    {
764
806
      uint32_t key_nr;
765
807
      /*
766
808
        If we do more than one iteration of this loop, from the second one the
767
809
        row will have an explicit value in the autoinc field, which was set at
768
810
        the first call of handler::update_auto_increment(). So we must save
769
 
        the autogenerated value to avoid session->insert_id_for_cur_row to become
 
811
        the autogenerated value to avoid thd->insert_id_for_cur_row to become
770
812
        0.
771
813
      */
772
 
      if (table->cursor->insert_id_for_cur_row > 0)
773
 
        insert_id_for_cur_row= table->cursor->insert_id_for_cur_row;
 
814
      if (table->file->insert_id_for_cur_row > 0)
 
815
        insert_id_for_cur_row= table->file->insert_id_for_cur_row;
774
816
      else
775
 
        table->cursor->insert_id_for_cur_row= insert_id_for_cur_row;
 
817
        table->file->insert_id_for_cur_row= insert_id_for_cur_row;
776
818
      bool is_duplicate_key_error;
777
 
      if (table->cursor->is_fatal_error(error, HA_CHECK_DUP))
 
819
      if (table->file->is_fatal_error(error, HA_CHECK_DUP))
778
820
        goto err;
779
 
      is_duplicate_key_error= table->cursor->is_fatal_error(error, 0);
 
821
      is_duplicate_key_error= table->file->is_fatal_error(error, 0);
780
822
      if (!is_duplicate_key_error)
781
823
      {
782
824
        /*
788
830
          goto gok_or_after_err; /* Ignoring a not fatal error, return 0 */
789
831
        goto err;
790
832
      }
791
 
      if ((int) (key_nr = table->get_dup_key(error)) < 0)
 
833
      if ((int) (key_nr = table->file->get_dup_key(error)) < 0)
792
834
      {
793
835
        error= HA_ERR_FOUND_DUPP_KEY;         /* Database can't find key */
794
836
        goto err;
802
844
      */
803
845
      if (info->handle_duplicates == DUP_REPLACE &&
804
846
          table->next_number_field &&
805
 
          key_nr == table->getShare()->next_number_index &&
 
847
          key_nr == table->s->next_number_index &&
806
848
          (insert_id_for_cur_row > 0))
807
849
        goto err;
808
 
      if (table->cursor->getEngine()->check_flag(HTON_BIT_DUPLICATE_POS))
 
850
      if (table->file->ha_table_flags() & HA_DUPLICATE_POS)
809
851
      {
810
 
        if (table->cursor->rnd_pos(table->getUpdateRecord(),table->cursor->dup_ref))
 
852
        if (table->file->rnd_pos(table->record[1],table->file->dup_ref))
811
853
          goto err;
812
854
      }
813
855
      else
814
856
      {
815
 
        if (table->cursor->extra(HA_EXTRA_FLUSH_CACHE)) /* Not needed with NISAM */
 
857
        if (table->file->extra(HA_EXTRA_FLUSH_CACHE)) /* Not needed with NISAM */
816
858
        {
817
 
          error=errno;
 
859
          error=my_errno;
818
860
          goto err;
819
861
        }
820
862
 
821
 
        if (not key.size())
 
863
        if (!key)
822
864
        {
823
 
          key.resize(table->getShare()->max_unique_length);
 
865
          if (!(key=(char*) my_safe_alloca(table->s->max_unique_length,
 
866
                                           MAX_KEY_LENGTH)))
 
867
          {
 
868
            error=ENOMEM;
 
869
            goto err;
 
870
          }
824
871
        }
825
 
        key_copy(&key[0], table->getInsertRecord(), table->key_info+key_nr, 0);
826
 
        if ((error=(table->cursor->index_read_idx_map(table->getUpdateRecord(),key_nr,
827
 
                                                    &key[0], HA_WHOLE_KEY,
 
872
        key_copy((unsigned char*) key,table->record[0],table->key_info+key_nr,0);
 
873
        if ((error=(table->file->index_read_idx_map(table->record[1],key_nr,
 
874
                                                    (unsigned char*) key, HA_WHOLE_KEY,
828
875
                                                    HA_READ_KEY_EXACT))))
829
876
          goto err;
830
877
      }
835
882
          that matches, is updated. If update causes a conflict again,
836
883
          an error is returned
837
884
        */
838
 
        assert(table->insert_values.size());
839
 
        table->storeRecordAsInsert();
840
 
        table->restoreRecord();
 
885
        assert(table->insert_values != NULL);
 
886
        store_record(table,insert_values);
 
887
        restore_record(table,record[1]);
841
888
        assert(info->update_fields->elements ==
842
889
                    info->update_values->elements);
843
 
        if (fill_record(session, *info->update_fields,
 
890
        if (fill_record(thd, *info->update_fields,
844
891
                                                 *info->update_values,
845
892
                                                 info->ignore))
846
893
          goto before_err;
847
894
 
848
 
        table->cursor->restore_auto_increment(prev_insert_id);
 
895
        table->file->restore_auto_increment(prev_insert_id);
849
896
        if (table->next_number_field)
850
 
          table->cursor->adjust_next_insert_id_after_explicit_value(
 
897
          table->file->adjust_next_insert_id_after_explicit_value(
851
898
            table->next_number_field->val_int());
852
899
        info->touched++;
853
 
 
854
 
        if (! table->records_are_comparable() || table->compare_records())
 
900
        if ((table->file->ha_table_flags() & HA_PARTIAL_COLUMN_READ &&
 
901
             !bitmap_is_subset(table->write_set, table->read_set)) ||
 
902
            table->compare_record())
855
903
        {
856
 
          if ((error=table->cursor->updateRecord(table->getUpdateRecord(),
857
 
                                                table->getInsertRecord())) &&
 
904
          if ((error=table->file->ha_update_row(table->record[1],
 
905
                                                table->record[0])) &&
858
906
              error != HA_ERR_RECORD_IS_THE_SAME)
859
907
          {
860
908
            if (info->ignore &&
861
 
                !table->cursor->is_fatal_error(error, HA_CHECK_DUP_KEY))
 
909
                !table->file->is_fatal_error(error, HA_CHECK_DUP_KEY))
862
910
            {
863
911
              goto gok_or_after_err;
864
912
            }
872
920
          /*
873
921
            If ON DUP KEY UPDATE updates a row instead of inserting one, it's
874
922
            like a regular UPDATE statement: it should not affect the value of a
875
 
            next SELECT LAST_INSERT_ID() or insert_id().
 
923
            next SELECT LAST_INSERT_ID() or mysql_insert_id().
876
924
            Except if LAST_INSERT_ID(#) was in the INSERT query, which is
877
 
            handled separately by Session::arg_of_last_insert_id_function.
 
925
            handled separately by THD::arg_of_last_insert_id_function.
878
926
          */
879
 
          insert_id_for_cur_row= table->cursor->insert_id_for_cur_row= 0;
 
927
          insert_id_for_cur_row= table->file->insert_id_for_cur_row= 0;
880
928
          info->copied++;
881
929
        }
882
930
 
883
931
        if (table->next_number_field)
884
 
          table->cursor->adjust_next_insert_id_after_explicit_value(
 
932
          table->file->adjust_next_insert_id_after_explicit_value(
885
933
            table->next_number_field->val_int());
886
934
        info->touched++;
887
935
 
894
942
          an INSERT or DELETE(s) + INSERT; FOREIGN KEY checks in
895
943
          InnoDB do not function in the defined way if we allow MySQL
896
944
          to convert the latter operation internally to an UPDATE.
897
 
          We also should not perform this conversion if we have
 
945
          We also should not perform this conversion if we have 
898
946
          timestamp field with ON UPDATE which is different from DEFAULT.
899
947
          Another case when conversion should not be performed is when
900
948
          we have ON DELETE trigger on table so user may notice that
904
952
          ON UPDATE triggers.
905
953
        */
906
954
        if (last_uniq_key(table,key_nr) &&
907
 
            !table->cursor->referenced_by_foreign_key() &&
 
955
            !table->file->referenced_by_foreign_key() &&
908
956
            (table->timestamp_field_type == TIMESTAMP_NO_AUTO_SET ||
909
957
             table->timestamp_field_type == TIMESTAMP_AUTO_SET_ON_BOTH))
910
958
        {
911
 
          if ((error=table->cursor->updateRecord(table->getUpdateRecord(),
912
 
                                                table->getInsertRecord())) &&
 
959
          if ((error=table->file->ha_update_row(table->record[1],
 
960
                                                table->record[0])) &&
913
961
              error != HA_ERR_RECORD_IS_THE_SAME)
914
962
            goto err;
915
963
          if (error != HA_ERR_RECORD_IS_THE_SAME)
916
964
            info->deleted++;
917
965
          else
918
966
            error= 0;
919
 
          session->record_first_successful_insert_id_in_cur_stmt(table->cursor->insert_id_for_cur_row);
 
967
          thd->record_first_successful_insert_id_in_cur_stmt(table->file->insert_id_for_cur_row);
920
968
          /*
921
969
            Since we pretend that we have done insert we should call
922
970
            its after triggers.
925
973
        }
926
974
        else
927
975
        {
928
 
          if ((error=table->cursor->deleteRecord(table->getUpdateRecord())))
 
976
          if ((error=table->file->ha_delete_row(table->record[1])))
929
977
            goto err;
930
978
          info->deleted++;
931
 
          if (!table->cursor->has_transactions())
932
 
            session->transaction.stmt.markModifiedNonTransData();
 
979
          if (!table->file->has_transactions())
 
980
            thd->transaction.stmt.modified_non_trans_table= true;
933
981
          /* Let us attempt do write_row() once more */
934
982
        }
935
983
      }
936
984
    }
937
 
    session->record_first_successful_insert_id_in_cur_stmt(table->cursor->insert_id_for_cur_row);
 
985
    thd->record_first_successful_insert_id_in_cur_stmt(table->file->insert_id_for_cur_row);
938
986
    /*
939
987
      Restore column maps if they where replaced during an duplicate key
940
988
      problem.
941
989
    */
942
990
    if (table->read_set != save_read_set ||
943
991
        table->write_set != save_write_set)
944
 
      table->column_bitmaps_set(*save_read_set, *save_write_set);
 
992
      table->column_bitmaps_set(save_read_set, save_write_set);
945
993
  }
946
 
  else if ((error=table->cursor->insertRecord(table->getInsertRecord())))
 
994
  else if ((error=table->file->ha_write_row(table->record[0])))
947
995
  {
948
996
    if (!info->ignore ||
949
 
        table->cursor->is_fatal_error(error, HA_CHECK_DUP))
 
997
        table->file->is_fatal_error(error, HA_CHECK_DUP))
950
998
      goto err;
951
 
    table->cursor->restore_auto_increment(prev_insert_id);
 
999
    table->file->restore_auto_increment(prev_insert_id);
952
1000
    goto gok_or_after_err;
953
1001
  }
954
1002
 
955
1003
after_n_copied_inc:
956
1004
  info->copied++;
957
 
  session->record_first_successful_insert_id_in_cur_stmt(table->cursor->insert_id_for_cur_row);
 
1005
  thd->record_first_successful_insert_id_in_cur_stmt(table->file->insert_id_for_cur_row);
958
1006
 
959
1007
gok_or_after_err:
960
 
  if (!table->cursor->has_transactions())
961
 
    session->transaction.stmt.markModifiedNonTransData();
 
1008
  if (key)
 
1009
    my_safe_afree(key,table->s->max_unique_length,MAX_KEY_LENGTH);
 
1010
  if (!table->file->has_transactions())
 
1011
    thd->transaction.stmt.modified_non_trans_table= true;
962
1012
  return(0);
963
1013
 
964
1014
err:
965
1015
  info->last_errno= error;
966
1016
  /* current_select is NULL if this is a delayed insert */
967
 
  if (session->getLex()->current_select)
968
 
    session->getLex()->current_select->no_error= 0;        // Give error
969
 
  table->print_error(error,MYF(0));
970
 
 
 
1017
  if (thd->lex->current_select)
 
1018
    thd->lex->current_select->no_error= 0;        // Give error
 
1019
  table->file->print_error(error,MYF(0));
 
1020
  
971
1021
before_err:
972
 
  table->cursor->restore_auto_increment(prev_insert_id);
973
 
  table->column_bitmaps_set(*save_read_set, *save_write_set);
974
 
  return 1;
 
1022
  table->file->restore_auto_increment(prev_insert_id);
 
1023
  if (key)
 
1024
    my_safe_afree(key, table->s->max_unique_length, MAX_KEY_LENGTH);
 
1025
  table->column_bitmaps_set(save_read_set, save_write_set);
 
1026
  return(1);
975
1027
}
976
1028
 
977
1029
 
979
1031
  Check that all fields with arn't null_fields are used
980
1032
******************************************************************************/
981
1033
 
982
 
int check_that_all_fields_are_given_values(Session *session, Table *entry,
983
 
                                           TableList *)
 
1034
int check_that_all_fields_are_given_values(THD *thd, Table *entry,
 
1035
                                           TableList *table_list)
984
1036
{
985
1037
  int err= 0;
 
1038
  MY_BITMAP *write_set= entry->write_set;
986
1039
 
987
 
  for (Field **field=entry->getFields() ; *field ; field++)
 
1040
  for (Field **field=entry->field ; *field ; field++)
988
1041
  {
989
 
    if (((*field)->isWriteSet()) == false)
990
 
    {
991
 
      /*
992
 
       * If the field doesn't have any default value
993
 
       * and there is no actual value specified in the
994
 
       * INSERT statement, throw error ER_NO_DEFAULT_FOR_FIELD.
995
 
       */
996
 
      if (((*field)->flags & NO_DEFAULT_VALUE_FLAG) &&
 
1042
    if (!bitmap_is_set(write_set, (*field)->field_index) &&
 
1043
        ((*field)->flags & NO_DEFAULT_VALUE_FLAG) &&
997
1044
        ((*field)->real_type() != DRIZZLE_TYPE_ENUM))
998
 
      {
999
 
        my_error(ER_NO_DEFAULT_FOR_FIELD, MYF(0), (*field)->field_name);
1000
 
        err= 1;
1001
 
      }
1002
 
    }
1003
 
    else
1004
1045
    {
1005
 
      /*
1006
 
       * However, if an actual NULL value was specified
1007
 
       * for the field and the field is a NOT NULL field, 
1008
 
       * throw ER_BAD_NULL_ERROR.
1009
 
       *
1010
 
       * Per the SQL standard, inserting NULL into a NOT NULL
1011
 
       * field requires an error to be thrown.
1012
 
       */
1013
 
      if (((*field)->flags & NOT_NULL_FLAG) &&
1014
 
          (*field)->is_null())
1015
 
      {
1016
 
        my_error(ER_BAD_NULL_ERROR, MYF(0), (*field)->field_name);
1017
 
        err= 1;
1018
 
      }
 
1046
      bool view= false;
 
1047
      if (table_list)
 
1048
      {
 
1049
        table_list= table_list->top_table();
 
1050
        view= test(0);
 
1051
      }
 
1052
      {
 
1053
        push_warning_printf(thd, DRIZZLE_ERROR::WARN_LEVEL_WARN,
 
1054
                            ER_NO_DEFAULT_FOR_FIELD,
 
1055
                            ER(ER_NO_DEFAULT_FOR_FIELD),
 
1056
                            (*field)->field_name);
 
1057
      }
 
1058
      err= 1;
1019
1059
    }
1020
1060
  }
1021
 
  return session->abortOnWarning() ? err : 0;
 
1061
  return thd->abort_on_warning ? err : 0;
1022
1062
}
1023
1063
 
1024
1064
/***************************************************************************
1030
1070
  make insert specific preparation and checks after opening tables
1031
1071
 
1032
1072
  SYNOPSIS
1033
 
    insert_select_prepare()
1034
 
    session         thread handler
 
1073
    mysql_insert_select_prepare()
 
1074
    thd         thread handler
1035
1075
 
1036
1076
  RETURN
1037
1077
    false OK
1038
1078
    true  Error
1039
1079
*/
1040
1080
 
1041
 
bool insert_select_prepare(Session *session)
 
1081
bool mysql_insert_select_prepare(THD *thd)
1042
1082
{
1043
 
  LEX *lex= session->getLex();
1044
 
  Select_Lex *select_lex= &lex->select_lex;
1045
 
 
1046
 
  /*
1047
 
    Select_Lex do not belong to INSERT statement, so we can't add WHERE
 
1083
  LEX *lex= thd->lex;
 
1084
  SELECT_LEX *select_lex= &lex->select_lex;
 
1085
  
 
1086
 
 
1087
  /*
 
1088
    Statement-based replication of INSERT ... SELECT ... LIMIT is not safe
 
1089
    as order of rows is not defined, so in mixed mode we go to row-based.
 
1090
 
 
1091
    Note that we may consider a statement as safe if ORDER BY primary_key
 
1092
    is present or we SELECT a constant. However it may confuse users to
 
1093
    see very similiar statements replicated differently.
 
1094
  */
 
1095
  if (lex->current_select->select_limit)
 
1096
  {
 
1097
    lex->set_stmt_unsafe();
 
1098
    thd->set_current_stmt_binlog_row_based_if_mixed();
 
1099
  }
 
1100
  /*
 
1101
    SELECT_LEX do not belong to INSERT statement, so we can't add WHERE
1048
1102
    clause if table is VIEW
1049
1103
  */
1050
 
 
1051
 
  if (prepare_insert(session, lex->query_tables,
 
1104
  
 
1105
  if (mysql_prepare_insert(thd, lex->query_tables,
1052
1106
                           lex->query_tables->table, lex->field_list, 0,
1053
1107
                           lex->update_list, lex->value_list,
1054
1108
                           lex->duplicates,
1072
1126
                             List<Item> *update_fields,
1073
1127
                             List<Item> *update_values,
1074
1128
                             enum_duplicates duplic,
1075
 
                             bool ignore_check_option_errors) :
1076
 
  table_list(table_list_par), table(table_par), fields(fields_par),
1077
 
  autoinc_value_of_last_inserted_row(0),
1078
 
  insert_into_view(table_list_par && 0 != 0)
 
1129
                             bool ignore_check_option_errors)
 
1130
  :table_list(table_list_par), table(table_par), fields(fields_par),
 
1131
   autoinc_value_of_last_inserted_row(0),
 
1132
   insert_into_view(table_list_par && 0 != 0)
1079
1133
{
 
1134
  memset(&info, 0, sizeof(info));
1080
1135
  info.handle_duplicates= duplic;
1081
1136
  info.ignore= ignore_check_option_errors;
1082
1137
  info.update_fields= update_fields;
1085
1140
 
1086
1141
 
1087
1142
int
1088
 
select_insert::prepare(List<Item> &values, Select_Lex_Unit *u)
 
1143
select_insert::prepare(List<Item> &values, SELECT_LEX_UNIT *u)
1089
1144
{
 
1145
  LEX *lex= thd->lex;
1090
1146
  int res;
1091
1147
  table_map map= 0;
1092
 
  Select_Lex *lex_current_select_save= session->getLex()->current_select;
1093
 
 
 
1148
  SELECT_LEX *lex_current_select_save= lex->current_select;
 
1149
  
1094
1150
 
1095
1151
  unit= u;
1096
1152
 
1099
1155
    select, LEX::current_select should point to the first select while
1100
1156
    we are fixing fields from insert list.
1101
1157
  */
1102
 
  session->getLex()->current_select= &session->getLex()->select_lex;
1103
 
  res= check_insert_fields(session, table_list, *fields, values,
 
1158
  lex->current_select= &lex->select_lex;
 
1159
  res= check_insert_fields(thd, table_list, *fields, values,
1104
1160
                           !insert_into_view, &map) ||
1105
 
       setup_fields(session, 0, values, MARK_COLUMNS_READ, 0, 0);
 
1161
       setup_fields(thd, 0, values, MARK_COLUMNS_READ, 0, 0);
1106
1162
 
1107
1163
  if (!res && fields->elements)
1108
1164
  {
1109
 
    bool saved_abort_on_warning= session->abortOnWarning();
1110
 
    session->setAbortOnWarning(not info.ignore);
1111
 
    res= check_that_all_fields_are_given_values(session, table_list->table,
 
1165
    bool saved_abort_on_warning= thd->abort_on_warning;
 
1166
    thd->abort_on_warning= !info.ignore;
 
1167
    res= check_that_all_fields_are_given_values(thd, table_list->table, 
1112
1168
                                                table_list);
1113
 
    session->setAbortOnWarning(saved_abort_on_warning);
 
1169
    thd->abort_on_warning= saved_abort_on_warning;
1114
1170
  }
1115
1171
 
1116
1172
  if (info.handle_duplicates == DUP_UPDATE && !res)
1117
1173
  {
1118
 
    Name_resolution_context *context= &session->getLex()->select_lex.context;
 
1174
    Name_resolution_context *context= &lex->select_lex.context;
1119
1175
    Name_resolution_context_state ctx_state;
1120
1176
 
1121
1177
    /* Save the state of the current name resolution context. */
1125
1181
    table_list->next_local= 0;
1126
1182
    context->resolve_in_table_list_only(table_list);
1127
1183
 
1128
 
    res= res || check_update_fields(session, context->table_list,
 
1184
    res= res || check_update_fields(thd, context->table_list,
1129
1185
                                    *info.update_fields, &map);
1130
1186
    /*
1131
 
      When we are not using GROUP BY and there are no ungrouped aggregate functions
 
1187
      When we are not using GROUP BY and there are no ungrouped aggregate functions 
1132
1188
      we can refer to other tables in the ON DUPLICATE KEY part.
1133
1189
      We use next_name_resolution_table descructively, so check it first (views?)
1134
1190
    */
1135
1191
    assert (!table_list->next_name_resolution_table);
1136
 
    if (session->getLex()->select_lex.group_list.elements == 0 and
1137
 
        not session->getLex()->select_lex.with_sum_func)
 
1192
    if (lex->select_lex.group_list.elements == 0 &&
 
1193
        !lex->select_lex.with_sum_func)
1138
1194
      /*
1139
1195
        We must make a single context out of the two separate name resolution contexts :
1140
1196
        the INSERT table and the tables in the SELECT part of INSERT ... SELECT.
1141
1197
        To do that we must concatenate the two lists
1142
 
      */
1143
 
      table_list->next_name_resolution_table=
 
1198
      */  
 
1199
      table_list->next_name_resolution_table= 
1144
1200
        ctx_state.get_first_name_resolution_table();
1145
1201
 
1146
 
    res= res || setup_fields(session, 0, *info.update_values,
 
1202
    res= res || setup_fields(thd, 0, *info.update_values,
1147
1203
                             MARK_COLUMNS_READ, 0, 0);
1148
1204
    if (!res)
1149
1205
    {
1153
1209
        order to get correct values from those fields when the select
1154
1210
        employs a temporary table.
1155
1211
      */
1156
 
      List<Item>::iterator li(info.update_values->begin());
 
1212
      List_iterator<Item> li(*info.update_values);
1157
1213
      Item *item;
1158
1214
 
1159
1215
      while ((item= li++))
1160
1216
      {
1161
1217
        item->transform(&Item::update_value_transformer,
1162
 
                        (unsigned char*)session->getLex()->current_select);
 
1218
                        (unsigned char*)lex->current_select);
1163
1219
      }
1164
1220
    }
1165
1221
 
1167
1223
    ctx_state.restore_state(context, table_list);
1168
1224
  }
1169
1225
 
1170
 
  session->getLex()->current_select= lex_current_select_save;
 
1226
  lex->current_select= lex_current_select_save;
1171
1227
  if (res)
1172
1228
    return(1);
1173
1229
  /*
1180
1236
    Is table which we are changing used somewhere in other parts of
1181
1237
    query
1182
1238
  */
1183
 
  if (unique_table(table_list, table_list->next_global))
 
1239
  if (unique_table(thd, table_list, table_list->next_global, 0))
1184
1240
  {
1185
1241
    /* Using same table for INSERT and SELECT */
1186
 
    session->getLex()->current_select->options|= OPTION_BUFFER_RESULT;
1187
 
    session->getLex()->current_select->join->select_options|= OPTION_BUFFER_RESULT;
 
1242
    lex->current_select->options|= OPTION_BUFFER_RESULT;
 
1243
    lex->current_select->join->select_options|= OPTION_BUFFER_RESULT;
1188
1244
  }
1189
 
  else if (not (session->getLex()->current_select->options & OPTION_BUFFER_RESULT))
 
1245
  else if (!(lex->current_select->options & OPTION_BUFFER_RESULT))
1190
1246
  {
1191
1247
    /*
1192
 
      We must not yet prepare the result table if it is the same as one of the
1193
 
      source tables (INSERT SELECT). The preparation may disable
 
1248
      We must not yet prepare the result table if it is the same as one of the 
 
1249
      source tables (INSERT SELECT). The preparation may disable 
1194
1250
      indexes on the result table, which may be used during the select, if it
1195
1251
      is the same table (Bug #6034). Do the preparation after the select phase
1196
1252
      in select_insert::prepare2().
1197
1253
      We won't start bulk inserts at all if this statement uses functions or
1198
1254
      should invoke triggers since they may access to the same table too.
1199
1255
    */
1200
 
    table->cursor->ha_start_bulk_insert((ha_rows) 0);
 
1256
    table->file->ha_start_bulk_insert((ha_rows) 0);
1201
1257
  }
1202
 
  table->restoreRecordAsDefault();              // Get empty record
 
1258
  restore_record(table,s->default_values);              // Get empty record
1203
1259
  table->next_number_field=table->found_next_number_field;
1204
1260
 
1205
 
  session->cuted_fields=0;
 
1261
  if (thd->slave_thread &&
 
1262
      (info.handle_duplicates == DUP_UPDATE) &&
 
1263
      (table->next_number_field != NULL) &&
 
1264
      rpl_master_has_bug(&active_mi->rli, 24432))
 
1265
    return(1);
1206
1266
 
 
1267
  thd->cuted_fields=0;
1207
1268
  if (info.ignore || info.handle_duplicates != DUP_ERROR)
1208
 
    table->cursor->extra(HA_EXTRA_IGNORE_DUP_KEY);
1209
 
 
 
1269
    table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
1210
1270
  if (info.handle_duplicates == DUP_REPLACE)
1211
 
    table->cursor->extra(HA_EXTRA_WRITE_CAN_REPLACE);
1212
 
 
 
1271
    table->file->extra(HA_EXTRA_WRITE_CAN_REPLACE);
1213
1272
  if (info.handle_duplicates == DUP_UPDATE)
1214
 
    table->cursor->extra(HA_EXTRA_INSERT_WITH_UPDATE);
1215
 
 
1216
 
  session->setAbortOnWarning(not info.ignore);
 
1273
    table->file->extra(HA_EXTRA_INSERT_WITH_UPDATE);
 
1274
  thd->abort_on_warning= !info.ignore;
1217
1275
  table->mark_columns_needed_for_insert();
1218
1276
 
1219
1277
 
1232
1290
    If the result table is the same as one of the source tables (INSERT SELECT),
1233
1291
    the result table is not finally prepared at the join prepair phase.
1234
1292
    Do the final preparation now.
1235
 
 
 
1293
                       
1236
1294
  RETURN
1237
1295
    0   OK
1238
1296
*/
1239
1297
 
1240
1298
int select_insert::prepare2(void)
1241
1299
{
1242
 
  if (session->getLex()->current_select->options & OPTION_BUFFER_RESULT)
1243
 
    table->cursor->ha_start_bulk_insert((ha_rows) 0);
1244
 
 
 
1300
  
 
1301
  if (thd->lex->current_select->options & OPTION_BUFFER_RESULT)
 
1302
    table->file->ha_start_bulk_insert((ha_rows) 0);
1245
1303
  return(0);
1246
1304
}
1247
1305
 
1254
1312
 
1255
1313
select_insert::~select_insert()
1256
1314
{
1257
 
 
 
1315
  
1258
1316
  if (table)
1259
1317
  {
1260
1318
    table->next_number_field=0;
1261
1319
    table->auto_increment_field_not_null= false;
1262
 
    table->cursor->ha_reset();
 
1320
    table->file->ha_reset();
1263
1321
  }
1264
 
  session->count_cuted_fields= CHECK_FIELD_IGNORE;
1265
 
  session->setAbortOnWarning(false);
 
1322
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;
 
1323
  thd->abort_on_warning= 0;
1266
1324
  return;
1267
1325
}
1268
1326
 
1269
1327
 
1270
1328
bool select_insert::send_data(List<Item> &values)
1271
1329
{
1272
 
 
1273
 
  bool error= false;
 
1330
  
 
1331
  bool error=0;
1274
1332
 
1275
1333
  if (unit->offset_limit_cnt)
1276
1334
  {                                             // using limit offset,count
1277
1335
    unit->offset_limit_cnt--;
1278
 
    return false;
 
1336
    return(0);
1279
1337
  }
1280
1338
 
1281
 
  session->count_cuted_fields= CHECK_FIELD_WARN;        // Calculate cuted fields
 
1339
  thd->count_cuted_fields= CHECK_FIELD_WARN;    // Calculate cuted fields
1282
1340
  store_values(values);
1283
 
  session->count_cuted_fields= CHECK_FIELD_IGNORE;
1284
 
  if (session->is_error())
1285
 
    return true;
1286
 
 
1287
 
  // Release latches in case bulk insert takes a long time
1288
 
  plugin::TransactionalStorageEngine::releaseTemporaryLatches(session);
1289
 
 
1290
 
  error= write_record(session, table, &info);
1291
 
  table->auto_increment_field_not_null= false;
1292
 
 
 
1341
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;
 
1342
  if (thd->is_error())
 
1343
    return(1);
 
1344
 
 
1345
  error= write_record(thd, table, &info);
 
1346
    
1293
1347
  if (!error)
1294
1348
  {
1295
1349
    if (info.handle_duplicates == DUP_UPDATE)
1297
1351
      /*
1298
1352
        Restore fields of the record since it is possible that they were
1299
1353
        changed by ON DUPLICATE KEY UPDATE clause.
1300
 
 
 
1354
    
1301
1355
        If triggers exist then whey can modify some fields which were not
1302
1356
        originally touched by INSERT ... SELECT, so we have to restore
1303
1357
        their original values for the next row.
1304
1358
      */
1305
 
      table->restoreRecordAsDefault();
 
1359
      restore_record(table, s->default_values);
1306
1360
    }
1307
1361
    if (table->next_number_field)
1308
1362
    {
1310
1364
        If no value has been autogenerated so far, we need to remember the
1311
1365
        value we just saw, we may need to send it to client in the end.
1312
1366
      */
1313
 
      if (session->first_successful_insert_id_in_cur_stmt == 0) // optimization
1314
 
        autoinc_value_of_last_inserted_row=
 
1367
      if (thd->first_successful_insert_id_in_cur_stmt == 0) // optimization
 
1368
        autoinc_value_of_last_inserted_row= 
1315
1369
          table->next_number_field->val_int();
1316
1370
      /*
1317
1371
        Clear auto-increment field for the next record, if triggers are used
1327
1381
void select_insert::store_values(List<Item> &values)
1328
1382
{
1329
1383
  if (fields->elements)
1330
 
    fill_record(session, *fields, values, true);
 
1384
    fill_record(thd, *fields, values, 1);
1331
1385
  else
1332
 
    fill_record(session, table->getFields(), values, true);
 
1386
    fill_record(thd, table->field, values, 1);
1333
1387
}
1334
1388
 
1335
 
void select_insert::send_error(drizzled::error_t errcode,const char *err)
 
1389
void select_insert::send_error(uint32_t errcode,const char *err)
1336
1390
{
 
1391
  
 
1392
 
1337
1393
  my_message(errcode, err, MYF(0));
 
1394
 
 
1395
  return;
1338
1396
}
1339
1397
 
1340
1398
 
1341
1399
bool select_insert::send_eof()
1342
1400
{
1343
1401
  int error;
1344
 
  bool const trans_table= table->cursor->has_transactions();
 
1402
  bool const trans_table= table->file->has_transactions();
1345
1403
  uint64_t id;
1346
1404
  bool changed;
1347
 
 
1348
 
  error= table->cursor->ha_end_bulk_insert();
1349
 
  table->cursor->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
1350
 
  table->cursor->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
 
1405
  THD::killed_state killed_status= thd->killed;
 
1406
  
 
1407
  error= table->file->ha_end_bulk_insert();
 
1408
  table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
 
1409
  table->file->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
1351
1410
 
1352
1411
  if ((changed= (info.copied || info.deleted || info.updated)))
1353
1412
  {
1354
1413
    /*
1355
1414
      We must invalidate the table in the query cache before binlog writing
1356
 
      and autocommitOrRollback.
 
1415
      and ha_autocommit_or_rollback.
1357
1416
    */
1358
 
    if (session->transaction.stmt.hasModifiedNonTransData())
1359
 
      session->transaction.all.markModifiedNonTransData();
 
1417
    if (thd->transaction.stmt.modified_non_trans_table)
 
1418
      thd->transaction.all.modified_non_trans_table= true;
1360
1419
  }
1361
 
  assert(trans_table || !changed ||
1362
 
              session->transaction.stmt.hasModifiedNonTransData());
 
1420
  assert(trans_table || !changed || 
 
1421
              thd->transaction.stmt.modified_non_trans_table);
1363
1422
 
1364
 
  table->cursor->ha_release_auto_increment();
 
1423
  /*
 
1424
    Write to binlog before commiting transaction.  No statement will
 
1425
    be written by the binlog_query() below in RBR mode.  All the
 
1426
    events are in the transaction cache and will be written when
 
1427
    ha_autocommit_or_rollback() is issued below.
 
1428
  */
 
1429
  if (mysql_bin_log.is_open())
 
1430
  {
 
1431
    if (!error)
 
1432
      thd->clear_error();
 
1433
    thd->binlog_query(THD::ROW_QUERY_TYPE,
 
1434
                      thd->query, thd->query_length,
 
1435
                      trans_table, false, killed_status);
 
1436
  }
 
1437
  table->file->ha_release_auto_increment();
1365
1438
 
1366
1439
  if (error)
1367
1440
  {
1368
 
    table->print_error(error,MYF(0));
1369
 
    DRIZZLE_INSERT_SELECT_DONE(error, 0);
1370
 
    return 1;
 
1441
    table->file->print_error(error,MYF(0));
 
1442
    return(1);
1371
1443
  }
1372
1444
  char buff[160];
1373
1445
  if (info.ignore)
1374
 
    snprintf(buff, sizeof(buff), ER(ER_INSERT_INFO), (ulong) info.records,
1375
 
            (ulong) (info.records - info.copied), (ulong) session->cuted_fields);
 
1446
    sprintf(buff, ER(ER_INSERT_INFO), (ulong) info.records,
 
1447
            (ulong) (info.records - info.copied), (ulong) thd->cuted_fields);
1376
1448
  else
1377
 
    snprintf(buff, sizeof(buff), ER(ER_INSERT_INFO), (ulong) info.records,
1378
 
            (ulong) (info.deleted+info.updated), (ulong) session->cuted_fields);
1379
 
  session->row_count_func= info.copied + info.deleted + info.updated;
 
1449
    sprintf(buff, ER(ER_INSERT_INFO), (ulong) info.records,
 
1450
            (ulong) (info.deleted+info.updated), (ulong) thd->cuted_fields);
 
1451
  thd->row_count_func= info.copied + info.deleted +
 
1452
                       ((thd->client_capabilities & CLIENT_FOUND_ROWS) ?
 
1453
                        info.touched : info.updated);
1380
1454
 
1381
 
  id= (session->first_successful_insert_id_in_cur_stmt > 0) ?
1382
 
    session->first_successful_insert_id_in_cur_stmt :
1383
 
    (session->arg_of_last_insert_id_function ?
1384
 
     session->first_successful_insert_id_in_prev_stmt :
 
1455
  id= (thd->first_successful_insert_id_in_cur_stmt > 0) ?
 
1456
    thd->first_successful_insert_id_in_cur_stmt :
 
1457
    (thd->arg_of_last_insert_id_function ?
 
1458
     thd->first_successful_insert_id_in_prev_stmt :
1385
1459
     (info.copied ? autoinc_value_of_last_inserted_row : 0));
1386
 
  session->my_ok((ulong) session->rowCount(),
1387
 
                 info.copied + info.deleted + info.touched, id, buff);
1388
 
  session->status_var.inserted_row_count+= session->rowCount(); 
1389
 
  DRIZZLE_INSERT_SELECT_DONE(0, session->rowCount());
1390
 
  return 0;
 
1460
  ::my_ok(thd, (ulong) thd->row_count_func, id, buff);
 
1461
  return(0);
1391
1462
}
1392
1463
 
1393
1464
void select_insert::abort() {
1394
1465
 
1395
 
 
 
1466
  
1396
1467
  /*
1397
1468
    If the creation of the table failed (due to a syntax error, for
1398
1469
    example), no table will have been opened and therefore 'table'
1403
1474
  {
1404
1475
    bool changed, transactional_table;
1405
1476
 
1406
 
    table->cursor->ha_end_bulk_insert();
 
1477
    table->file->ha_end_bulk_insert();
1407
1478
 
1408
1479
    /*
1409
1480
      If at least one row has been inserted/modified and will stay in
1420
1491
      zero, so no check for that is made.
1421
1492
    */
1422
1493
    changed= (info.copied || info.deleted || info.updated);
1423
 
    transactional_table= table->cursor->has_transactions();
 
1494
    transactional_table= table->file->has_transactions();
 
1495
    if (thd->transaction.stmt.modified_non_trans_table)
 
1496
    {
 
1497
        if (mysql_bin_log.is_open())
 
1498
          thd->binlog_query(THD::ROW_QUERY_TYPE, thd->query, thd->query_length,
 
1499
                            transactional_table, false);
 
1500
        if (!thd->current_stmt_binlog_row_based && !can_rollback_data())
 
1501
          thd->transaction.all.modified_non_trans_table= true;
 
1502
    }
1424
1503
    assert(transactional_table || !changed ||
1425
 
                session->transaction.stmt.hasModifiedNonTransData());
1426
 
    table->cursor->ha_release_auto_increment();
1427
 
  }
1428
 
 
1429
 
  if (DRIZZLE_INSERT_SELECT_DONE_ENABLED())
1430
 
  {
1431
 
    DRIZZLE_INSERT_SELECT_DONE(0, info.copied + info.deleted + info.updated);
 
1504
                thd->transaction.stmt.modified_non_trans_table);
 
1505
    table->file->ha_release_auto_increment();
1432
1506
  }
1433
1507
 
1434
1508
  return;
1445
1519
 
1446
1520
  SYNOPSIS
1447
1521
    create_table_from_items()
1448
 
      session          in     Thread object
 
1522
      thd          in     Thread object
1449
1523
      create_info  in     Create information (like MAX_ROWS, ENGINE or
1450
1524
                          temporary table flag)
1451
1525
      create_table in     Pointer to TableList object providing database
1455
1529
      items        in     List of items which should be used to produce rest
1456
1530
                          of fields for the table (corresponding fields will
1457
1531
                          be added to the end of alter_info->create_list)
1458
 
      lock         out    Pointer to the DrizzleLock object for table created
 
1532
      lock         out    Pointer to the DRIZZLE_LOCK object for table created
1459
1533
                          (or open temporary table) will be returned in this
1460
1534
                          parameter. Since this table is not included in
1461
 
                          Session::lock caller is responsible for explicitly
 
1535
                          THD::lock caller is responsible for explicitly
1462
1536
                          unlocking this table.
1463
1537
      hooks
1464
1538
 
1465
1539
  NOTES
1466
1540
    This function behaves differently for base and temporary tables:
1467
1541
    - For base table we assume that either table exists and was pre-opened
1468
 
      and locked at openTablesLock() stage (and in this case we just
 
1542
      and locked at open_and_lock_tables() stage (and in this case we just
1469
1543
      emit error or warning and return pre-opened Table object) or special
1470
1544
      placeholder was put in table cache that guarantees that this table
1471
1545
      won't be created or opened until the placeholder will be removed
1481
1555
    0         Error
1482
1556
*/
1483
1557
 
1484
 
static Table *create_table_from_items(Session *session, HA_CREATE_INFO *create_info,
 
1558
static Table *create_table_from_items(THD *thd, HA_CREATE_INFO *create_info,
1485
1559
                                      TableList *create_table,
1486
 
                                      message::Table &table_proto,
1487
 
                                      AlterInfo *alter_info,
 
1560
                                      Alter_info *alter_info,
1488
1561
                                      List<Item> *items,
1489
 
                                      bool is_if_not_exists,
1490
 
                                      DrizzleLock **lock,
1491
 
                                      identifier::Table::const_reference identifier)
 
1562
                                      DRIZZLE_LOCK **lock,
 
1563
                                      TABLEOP_HOOKS *hooks)
1492
1564
{
1493
 
  TableShare share(message::Table::INTERNAL);
 
1565
  Table tmp_table;              // Used during 'Create_field()'
 
1566
  TABLE_SHARE share;
 
1567
  Table *table= 0;
1494
1568
  uint32_t select_field_count= items->elements;
1495
1569
  /* Add selected items to field list */
1496
 
  List<Item>::iterator it(items->begin());
 
1570
  List_iterator_fast<Item> it(*items);
1497
1571
  Item *item;
1498
1572
  Field *tmp_field;
 
1573
  bool not_used;
1499
1574
 
1500
 
  if (not (identifier.isTmp()) && create_table->table->db_stat)
 
1575
  if (!(create_info->options & HA_LEX_CREATE_TMP_TABLE) &&
 
1576
      create_table->table->db_stat)
1501
1577
  {
1502
 
    /* Table already exists and was open at openTablesLock() stage. */
1503
 
    if (is_if_not_exists)
 
1578
    /* Table already exists and was open at open_and_lock_tables() stage. */
 
1579
    if (create_info->options & HA_LEX_CREATE_IF_NOT_EXISTS)
1504
1580
    {
1505
1581
      create_info->table_existed= 1;            // Mark that table existed
1506
 
      push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
 
1582
      push_warning_printf(thd, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
1507
1583
                          ER_TABLE_EXISTS_ERROR, ER(ER_TABLE_EXISTS_ERROR),
1508
 
                          create_table->getTableName());
1509
 
      return create_table->table;
 
1584
                          create_table->table_name);
 
1585
      return(create_table->table);
1510
1586
    }
1511
1587
 
1512
 
    my_error(ER_TABLE_EXISTS_ERROR, MYF(0), create_table->getTableName());
1513
 
    return NULL;
 
1588
    my_error(ER_TABLE_EXISTS_ERROR, MYF(0), create_table->table_name);
 
1589
    return(0);
1514
1590
  }
1515
1591
 
 
1592
  tmp_table.alias= 0;
 
1593
  tmp_table.timestamp_field= 0;
 
1594
  tmp_table.s= &share;
 
1595
  init_tmp_table_share(thd, &share, "", 0, "", "");
 
1596
 
 
1597
  tmp_table.s->db_create_options=0;
 
1598
  tmp_table.s->blob_ptr_size= portable_sizeof_char_ptr;
 
1599
  tmp_table.s->db_low_byte_first= 
 
1600
        test(create_info->db_type == myisam_hton ||
 
1601
             create_info->db_type == heap_hton);
 
1602
  tmp_table.null_row= false;
 
1603
  tmp_table.maybe_null= false;
 
1604
 
 
1605
  while ((item=it++))
1516
1606
  {
1517
 
    table::Shell tmp_table(share);              // Used during 'CreateField()'
1518
 
 
1519
 
    if (not table_proto.engine().name().compare("MyISAM"))
1520
 
      tmp_table.getMutableShare()->db_low_byte_first= true;
1521
 
    else if (not table_proto.engine().name().compare("MEMORY"))
1522
 
      tmp_table.getMutableShare()->db_low_byte_first= true;
1523
 
 
1524
 
    tmp_table.in_use= session;
1525
 
 
1526
 
    while ((item=it++))
1527
 
    {
1528
 
      CreateField *cr_field;
1529
 
      Field *field, *def_field;
1530
 
      if (item->type() == Item::FUNC_ITEM)
1531
 
      {
1532
 
        if (item->result_type() != STRING_RESULT)
1533
 
        {
1534
 
          field= item->tmp_table_field(&tmp_table);
1535
 
        }
1536
 
        else
1537
 
        {
1538
 
          field= item->tmp_table_field_from_field_type(&tmp_table, 0);
1539
 
        }
1540
 
      }
 
1607
    Create_field *cr_field;
 
1608
    Field *field, *def_field;
 
1609
    if (item->type() == Item::FUNC_ITEM)
 
1610
      if (item->result_type() != STRING_RESULT)
 
1611
        field= item->tmp_table_field(&tmp_table);
1541
1612
      else
1542
 
      {
1543
 
        field= create_tmp_field(session, &tmp_table, item, item->type(),
1544
 
                                (Item ***) 0, &tmp_field, &def_field, false,
1545
 
                                false, false, 0);
1546
 
      }
1547
 
 
1548
 
      if (!field ||
1549
 
          !(cr_field=new CreateField(field,(item->type() == Item::FIELD_ITEM ?
1550
 
                                            ((Item_field *)item)->field :
1551
 
                                            (Field*) 0))))
1552
 
      {
1553
 
        return NULL;
1554
 
      }
1555
 
 
1556
 
      if (item->maybe_null)
1557
 
      {
1558
 
        cr_field->flags &= ~NOT_NULL_FLAG;
1559
 
      }
1560
 
 
1561
 
      alter_info->create_list.push_back(cr_field);
1562
 
    }
 
1613
        field= item->tmp_table_field_from_field_type(&tmp_table, 0);
 
1614
    else
 
1615
      field= create_tmp_field(thd, &tmp_table, item, item->type(),
 
1616
                              (Item ***) 0, &tmp_field, &def_field, 0, 0, 0, 0,
 
1617
                              0);
 
1618
    if (!field ||
 
1619
        !(cr_field=new Create_field(field,(item->type() == Item::FIELD_ITEM ?
 
1620
                                           ((Item_field *)item)->field :
 
1621
                                           (Field*) 0))))
 
1622
      return(0);
 
1623
    if (item->maybe_null)
 
1624
      cr_field->flags &= ~NOT_NULL_FLAG;
 
1625
    alter_info->create_list.push_back(cr_field);
1563
1626
  }
1564
1627
 
1565
1628
  /*
1568
1631
    Note that we either creating (or opening existing) temporary table or
1569
1632
    creating base table on which name we have exclusive lock. So code below
1570
1633
    should not cause deadlocks or races.
 
1634
 
 
1635
    We don't log the statement, it will be logged later.
 
1636
 
 
1637
    If this is a HEAP table, the automatic DELETE FROM which is written to the
 
1638
    binlog when a HEAP table is opened for the first time since startup, must
 
1639
    not be written: 1) it would be wrong (imagine we're in CREATE SELECT: we
 
1640
    don't want to delete from it) 2) it would be written before the CREATE
 
1641
    Table, which is a wrong order. So we keep binary logging disabled when we
 
1642
    open_table().
1571
1643
  */
1572
 
  Table *table= 0;
1573
1644
  {
1574
 
    if (not create_table_no_lock(session,
1575
 
                                 identifier,
1576
 
                                 create_info,
1577
 
                                 table_proto,
1578
 
                                 alter_info,
1579
 
                                 false,
1580
 
                                 select_field_count,
1581
 
                                 is_if_not_exists))
 
1645
    tmp_disable_binlog(thd);
 
1646
    if (!mysql_create_table_no_lock(thd, create_table->db,
 
1647
                                    create_table->table_name,
 
1648
                                    create_info, alter_info, 0,
 
1649
                                    select_field_count))
1582
1650
    {
1583
 
      if (create_info->table_existed && not identifier.isTmp())
 
1651
      if (create_info->table_existed &&
 
1652
          !(create_info->options & HA_LEX_CREATE_TMP_TABLE))
1584
1653
      {
1585
1654
        /*
1586
1655
          This means that someone created table underneath server
1587
1656
          or it was created via different mysqld front-end to the
1588
1657
          cluster. We don't have much options but throw an error.
1589
1658
        */
1590
 
        my_error(ER_TABLE_EXISTS_ERROR, MYF(0), create_table->getTableName());
1591
 
        return NULL;
 
1659
        my_error(ER_TABLE_EXISTS_ERROR, MYF(0), create_table->table_name);
 
1660
        return(0);
1592
1661
      }
1593
1662
 
1594
 
      if (not identifier.isTmp())
 
1663
      if (!(create_info->options & HA_LEX_CREATE_TMP_TABLE))
1595
1664
      {
1596
 
        /* CREATE TABLE... has found that the table already exists for insert and is adapting to use it */
1597
 
        boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex());
1598
 
 
1599
 
        if (create_table->table)
 
1665
        pthread_mutex_lock(&LOCK_open);
 
1666
        if (reopen_name_locked_table(thd, create_table, false))
1600
1667
        {
1601
 
          table::Concurrent *concurrent_table= static_cast<table::Concurrent *>(create_table->table);
1602
 
 
1603
 
          if (concurrent_table->reopen_name_locked_table(create_table, session))
1604
 
          {
1605
 
            (void)plugin::StorageEngine::dropTable(*session, identifier);
1606
 
          }
1607
 
          else
1608
 
          {
1609
 
            table= create_table->table;
1610
 
          }
 
1668
          quick_rm_table(create_info->db_type, create_table->db,
 
1669
                         table_case_name(create_info, create_table->table_name),
 
1670
                         0);
1611
1671
        }
1612
1672
        else
1613
 
        {
1614
 
          (void)plugin::StorageEngine::dropTable(*session, identifier);
1615
 
        }
 
1673
          table= create_table->table;
 
1674
        pthread_mutex_unlock(&LOCK_open);
1616
1675
      }
1617
1676
      else
1618
1677
      {
1619
 
        if (not (table= session->openTable(create_table, (bool*) 0,
1620
 
                                           DRIZZLE_OPEN_TEMPORARY_ONLY)) &&
1621
 
            not create_info->table_existed)
 
1678
        if (!(table= open_table(thd, create_table, (bool*) 0,
 
1679
                                DRIZZLE_OPEN_TEMPORARY_ONLY)) &&
 
1680
            !create_info->table_existed)
1622
1681
        {
1623
1682
          /*
1624
1683
            This shouldn't happen as creation of temporary table should make
1625
1684
            it preparable for open. But let us do close_temporary_table() here
1626
1685
            just in case.
1627
1686
          */
1628
 
          session->drop_temporary_table(identifier);
 
1687
          drop_temporary_table(thd, create_table);
1629
1688
        }
1630
1689
      }
1631
1690
    }
1632
 
    if (not table)                                   // open failed
1633
 
      return NULL;
 
1691
    reenable_binlog(thd);
 
1692
    if (!table)                                   // open failed
 
1693
      return(0);
1634
1694
  }
1635
1695
 
1636
1696
  table->reginfo.lock_type=TL_WRITE;
1637
 
  if (not ((*lock)= session->lockTables(&table, 1, DRIZZLE_LOCK_IGNORE_FLUSH)))
 
1697
  hooks->prelock(&table, 1);                    // Call prelock hooks
 
1698
  if (! ((*lock)= mysql_lock_tables(thd, &table, 1,
 
1699
                                    DRIZZLE_LOCK_IGNORE_FLUSH, &not_used)) ||
 
1700
        hooks->postlock(&table, 1))
1638
1701
  {
1639
1702
    if (*lock)
1640
1703
    {
1641
 
      session->unlockTables(*lock);
 
1704
      mysql_unlock_tables(thd, *lock);
1642
1705
      *lock= 0;
1643
1706
    }
1644
1707
 
1645
 
    if (not create_info->table_existed)
1646
 
      session->drop_open_table(table, identifier);
1647
 
 
1648
 
    return NULL;
 
1708
    if (!create_info->table_existed)
 
1709
      drop_open_table(thd, table, create_table->db, create_table->table_name);
 
1710
    return(0);
1649
1711
  }
1650
 
 
1651
 
  return table;
 
1712
  return(table);
1652
1713
}
1653
1714
 
1654
1715
 
1655
1716
int
1656
 
select_create::prepare(List<Item> &values, Select_Lex_Unit *u)
 
1717
select_create::prepare(List<Item> &values, SELECT_LEX_UNIT *u)
1657
1718
{
1658
 
  DrizzleLock *extra_lock= NULL;
 
1719
  DRIZZLE_LOCK *extra_lock= NULL;
 
1720
  
 
1721
 
 
1722
  TABLEOP_HOOKS *hook_ptr= NULL;
1659
1723
  /*
1660
 
    For replication, the CREATE-SELECT statement is written
1661
 
    in two pieces: the first transaction messsage contains 
1662
 
    the CREATE TABLE statement as a CreateTableStatement message
1663
 
    necessary to create the table.
1664
 
    
1665
 
    The second transaction message contains all the InsertStatement
1666
 
    and associated InsertRecords that should go into the table.
 
1724
    For row-based replication, the CREATE-SELECT statement is written
 
1725
    in two pieces: the first one contain the CREATE TABLE statement
 
1726
    necessary to create the table and the second part contain the rows
 
1727
    that should go into the table.
 
1728
 
 
1729
    For non-temporary tables, the start of the CREATE-SELECT
 
1730
    implicitly commits the previous transaction, and all events
 
1731
    forming the statement will be stored the transaction cache. At end
 
1732
    of the statement, the entire statement is committed as a
 
1733
    transaction, and all events are written to the binary log.
 
1734
 
 
1735
    On the master, the table is locked for the duration of the
 
1736
    statement, but since the CREATE part is replicated as a simple
 
1737
    statement, there is no way to lock the table for accesses on the
 
1738
    slave.  Hence, we have to hold on to the CREATE part of the
 
1739
    statement until the statement has finished.
1667
1740
   */
 
1741
  class MY_HOOKS : public TABLEOP_HOOKS {
 
1742
  public:
 
1743
    MY_HOOKS(select_create *x, TableList *create_table,
 
1744
             TableList *select_tables)
 
1745
      : ptr(x), all_tables(*create_table)
 
1746
      {
 
1747
        all_tables.next_global= select_tables;
 
1748
      }
 
1749
 
 
1750
  private:
 
1751
    virtual int do_postlock(Table **tables, uint32_t count)
 
1752
    {
 
1753
      THD *thd= const_cast<THD*>(ptr->get_thd());
 
1754
      if (int error= decide_logging_format(thd, &all_tables))
 
1755
        return error;
 
1756
 
 
1757
      Table const *const table = *tables;
 
1758
      if (thd->current_stmt_binlog_row_based  &&
 
1759
          !table->s->tmp_table &&
 
1760
          !ptr->get_create_info()->table_existed)
 
1761
      {
 
1762
        ptr->binlog_show_create_table(tables, count);
 
1763
      }
 
1764
      return 0;
 
1765
    }
 
1766
 
 
1767
    select_create *ptr;
 
1768
    TableList all_tables;
 
1769
  };
 
1770
 
 
1771
  MY_HOOKS hooks(this, create_table, select_tables);
 
1772
  hook_ptr= &hooks;
1668
1773
 
1669
1774
  unit= u;
1670
1775
 
1671
 
  if (not (table= create_table_from_items(session, create_info, create_table,
1672
 
                                          table_proto,
1673
 
                                          alter_info, &values,
1674
 
                                          is_if_not_exists,
1675
 
                                          &extra_lock, identifier)))
 
1776
  /*
 
1777
    Start a statement transaction before the create if we are using
 
1778
    row-based replication for the statement.  If we are creating a
 
1779
    temporary table, we need to start a statement transaction.
 
1780
  */
 
1781
  if ((thd->lex->create_info.options & HA_LEX_CREATE_TMP_TABLE) == 0 &&
 
1782
      thd->current_stmt_binlog_row_based)
1676
1783
  {
 
1784
    thd->binlog_start_trans_and_stmt();
 
1785
  }
 
1786
 
 
1787
  if (!(table= create_table_from_items(thd, create_info, create_table,
 
1788
                                       alter_info, &values,
 
1789
                                       &extra_lock, hook_ptr)))
1677
1790
    return(-1);                         // abort() deletes table
1678
 
  }
1679
1791
 
1680
1792
  if (extra_lock)
1681
1793
  {
1682
1794
    assert(m_plock == NULL);
1683
1795
 
1684
 
    if (identifier.isTmp())
 
1796
    if (create_info->options & HA_LEX_CREATE_TMP_TABLE)
1685
1797
      m_plock= &m_lock;
1686
1798
    else
1687
 
      m_plock= &session->extra_lock;
 
1799
      m_plock= &thd->extra_lock;
1688
1800
 
1689
1801
    *m_plock= extra_lock;
1690
1802
  }
1691
1803
 
1692
 
  if (table->getShare()->sizeFields() < values.elements)
 
1804
  if (table->s->fields < values.elements)
1693
1805
  {
1694
1806
    my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), 1);
1695
1807
    return(-1);
1696
1808
  }
1697
1809
 
1698
1810
 /* First field to copy */
1699
 
  field= table->getFields() + table->getShare()->sizeFields() - values.elements;
 
1811
  field= table->field+table->s->fields - values.elements;
1700
1812
 
1701
1813
  /* Mark all fields that are given values */
1702
1814
  for (Field **f= field ; *f ; f++)
1703
 
  {
1704
 
    table->setWriteSet((*f)->position());
1705
 
  }
 
1815
    bitmap_set_bit(table->write_set, (*f)->field_index);
1706
1816
 
1707
1817
  /* Don't set timestamp if used */
1708
1818
  table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
1709
1819
  table->next_number_field=table->found_next_number_field;
1710
1820
 
1711
 
  table->restoreRecordAsDefault();      // Get empty record
1712
 
  session->cuted_fields=0;
 
1821
  restore_record(table,s->default_values);      // Get empty record
 
1822
  thd->cuted_fields=0;
1713
1823
  if (info.ignore || info.handle_duplicates != DUP_ERROR)
1714
 
    table->cursor->extra(HA_EXTRA_IGNORE_DUP_KEY);
1715
 
 
 
1824
    table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
1716
1825
  if (info.handle_duplicates == DUP_REPLACE)
1717
 
    table->cursor->extra(HA_EXTRA_WRITE_CAN_REPLACE);
1718
 
 
 
1826
    table->file->extra(HA_EXTRA_WRITE_CAN_REPLACE);
1719
1827
  if (info.handle_duplicates == DUP_UPDATE)
1720
 
    table->cursor->extra(HA_EXTRA_INSERT_WITH_UPDATE);
1721
 
 
1722
 
  table->cursor->ha_start_bulk_insert((ha_rows) 0);
1723
 
  session->setAbortOnWarning(not info.ignore);
1724
 
  if (check_that_all_fields_are_given_values(session, table, table_list))
 
1828
    table->file->extra(HA_EXTRA_INSERT_WITH_UPDATE);
 
1829
  table->file->ha_start_bulk_insert((ha_rows) 0);
 
1830
  thd->abort_on_warning= !info.ignore;
 
1831
  if (check_that_all_fields_are_given_values(thd, table, table_list))
1725
1832
    return(1);
1726
 
 
1727
1833
  table->mark_columns_needed_for_insert();
1728
 
  table->cursor->extra(HA_EXTRA_WRITE_CACHE);
 
1834
  table->file->extra(HA_EXTRA_WRITE_CACHE);
1729
1835
  return(0);
1730
1836
}
1731
1837
 
 
1838
void
 
1839
select_create::binlog_show_create_table(Table **tables, uint32_t count)
 
1840
{
 
1841
  /*
 
1842
    Note 1: In RBR mode, we generate a CREATE TABLE statement for the
 
1843
    created table by calling store_create_info() (behaves as SHOW
 
1844
    CREATE TABLE).  In the event of an error, nothing should be
 
1845
    written to the binary log, even if the table is non-transactional;
 
1846
    therefore we pretend that the generated CREATE TABLE statement is
 
1847
    for a transactional table.  The event will then be put in the
 
1848
    transaction cache, and any subsequent events (e.g., table-map
 
1849
    events and binrow events) will also be put there.  We can then use
 
1850
    ha_autocommit_or_rollback() to either throw away the entire
 
1851
    kaboodle of events, or write them to the binary log.
 
1852
 
 
1853
    We write the CREATE TABLE statement here and not in prepare()
 
1854
    since there potentially are sub-selects or accesses to information
 
1855
    schema that will do a close_thread_tables(), destroying the
 
1856
    statement transaction cache.
 
1857
  */
 
1858
  assert(thd->current_stmt_binlog_row_based);
 
1859
  assert(tables && *tables && count > 0);
 
1860
 
 
1861
  char buf[2048];
 
1862
  String query(buf, sizeof(buf), system_charset_info);
 
1863
  int result;
 
1864
  TableList tmp_table_list;
 
1865
 
 
1866
  memset(&tmp_table_list, 0, sizeof(tmp_table_list));
 
1867
  tmp_table_list.table = *tables;
 
1868
  query.length(0);      // Have to zero it since constructor doesn't
 
1869
 
 
1870
  result= store_create_info(thd, &tmp_table_list, &query, create_info);
 
1871
  assert(result == 0); /* store_create_info() always return 0 */
 
1872
 
 
1873
  thd->binlog_query(THD::STMT_QUERY_TYPE,
 
1874
                    query.ptr(), query.length(),
 
1875
                    /* is_trans */ true,
 
1876
                    /* suppress_use */ false);
 
1877
}
 
1878
 
1732
1879
void select_create::store_values(List<Item> &values)
1733
1880
{
1734
 
  fill_record(session, field, values, true);
 
1881
  fill_record(thd, field, values, 1);
1735
1882
}
1736
1883
 
1737
1884
 
1738
 
void select_create::send_error(drizzled::error_t errcode,const char *err)
 
1885
void select_create::send_error(uint32_t errcode,const char *err)
1739
1886
{
 
1887
  
 
1888
 
1740
1889
  /*
1741
1890
    This will execute any rollbacks that are necessary before writing
1742
1891
    the transcation cache.
1748
1897
    written to the binary log.
1749
1898
 
1750
1899
  */
 
1900
  tmp_disable_binlog(thd);
1751
1901
  select_insert::send_error(errcode, err);
 
1902
  reenable_binlog(thd);
 
1903
 
 
1904
  return;
1752
1905
}
1753
1906
 
1754
1907
 
1764
1917
      tables.  This can fail, but we should unlock the table
1765
1918
      nevertheless.
1766
1919
    */
1767
 
    if (!table->getShare()->getType())
 
1920
    if (!table->s->tmp_table)
1768
1921
    {
1769
 
      TransactionServices &transaction_services= TransactionServices::singleton();
1770
 
      transaction_services.autocommitOrRollback(*session, 0);
1771
 
      (void) session->endActiveTransaction();
 
1922
      ha_autocommit_or_rollback(thd, 0);
 
1923
      end_active_trans(thd);
1772
1924
    }
1773
1925
 
1774
 
    table->cursor->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
1775
 
    table->cursor->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
 
1926
    table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
 
1927
    table->file->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
1776
1928
    if (m_plock)
1777
1929
    {
1778
 
      session->unlockTables(*m_plock);
 
1930
      mysql_unlock_tables(thd, *m_plock);
1779
1931
      *m_plock= NULL;
1780
1932
      m_plock= NULL;
1781
1933
    }
1786
1938
 
1787
1939
void select_create::abort()
1788
1940
{
 
1941
  
 
1942
 
1789
1943
  /*
1790
1944
    In select_insert::abort() we roll back the statement, including
1791
1945
    truncating the transaction cache of the binary log. To do this, we
1801
1955
    of the table succeeded or not, since we need to reset the binary
1802
1956
    log state.
1803
1957
  */
 
1958
  tmp_disable_binlog(thd);
1804
1959
  select_insert::abort();
 
1960
  thd->transaction.stmt.modified_non_trans_table= false;
 
1961
  reenable_binlog(thd);
 
1962
 
1805
1963
 
1806
1964
  if (m_plock)
1807
1965
  {
1808
 
    session->unlockTables(*m_plock);
 
1966
    mysql_unlock_tables(thd, *m_plock);
1809
1967
    *m_plock= NULL;
1810
1968
    m_plock= NULL;
1811
1969
  }
1812
1970
 
1813
1971
  if (table)
1814
1972
  {
1815
 
    table->cursor->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
1816
 
    table->cursor->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
1817
 
    if (not create_info->table_existed)
1818
 
      session->drop_open_table(table, identifier);
1819
 
    table= NULL;                                    // Safety
 
1973
    table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
 
1974
    table->file->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
 
1975
    if (!create_info->table_existed)
 
1976
      drop_open_table(thd, table, create_table->db, create_table->table_name);
 
1977
    table=0;                                    // Safety
1820
1978
  }
 
1979
  return;
1821
1980
}
1822
1981
 
1823
 
} /* namespace drizzled */
 
1982
 
 
1983
/*****************************************************************************
 
1984
  Instansiate templates
 
1985
*****************************************************************************/
 
1986
 
 
1987
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
 
1988
template class List_iterator_fast<List_item>;
 
1989
#endif /* HAVE_EXPLICIT_TEMPLATE_INSTANTIATION */