~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_insert.cc

  • Committer: Brian Aker
  • Date: 2008-08-16 15:41:14 UTC
  • mto: This revision was merged to the branch mainline in revision 346.
  • Revision ID: brian@tangent.org-20080816154114-eufmwf31p6ie1nd6
Cleaned up depend in Proto utils. Modified int to bool. Put TmpTable class
into play.

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