~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_insert.cc

pandora-build v0.100 - Fixes several bugs found by cb1kenobi. Add several thoughts from folks at LCA.

Show diffs side-by-side

added added

removed removed

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