~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_insert.cc

  • Committer: Brian Aker
  • Date: 2008-10-06 06:47:29 UTC
  • Revision ID: brian@tangent.org-20081006064729-2i9mhjkzyvow9xsm
RemoveĀ uint.

Show diffs side-by-side

added added

removed removed

Lines of Context:
24
24
*/
25
25
#include <drizzled/server_includes.h>
26
26
#include <drizzled/sql_select.h>
27
 
#include <drizzled/show.h>
28
 
#include <drizzled/error.h>
29
 
#include <drizzled/name_resolution_context_state.h>
30
 
#include <drizzled/probes.h>
31
 
#include <drizzled/sql_base.h>
32
 
#include <drizzled/sql_load.h>
33
 
#include <drizzled/field/timestamp.h>
34
 
#include <drizzled/lock.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) : malloc(size))
 
38
#define my_safe_afree(ptr, size, min_length) if (size > min_length) free(ptr)
 
39
#endif
 
40
 
35
41
 
36
42
 
37
43
/*
39
45
 
40
46
  SYNOPSIS
41
47
    check_insert_fields()
42
 
    session                         The current thread.
 
48
    thd                         The current thread.
43
49
    table                       The table for insert.
44
50
    fields                      The insert fields.
45
51
    values                      The insert values.
55
61
    -1          Error
56
62
*/
57
63
 
58
 
static int check_insert_fields(Session *session, TableList *table_list,
 
64
static int check_insert_fields(THD *thd, TableList *table_list,
59
65
                               List<Item> &fields, List<Item> &values,
60
66
                               bool check_unique,
61
 
                               table_map *)
 
67
                               table_map *map __attribute__((unused)))
62
68
{
63
69
  Table *table= table_list->table;
64
70
 
79
85
  }
80
86
  else
81
87
  {                                             // Part field list
82
 
    Select_Lex *select_lex= &session->lex->select_lex;
 
88
    SELECT_LEX *select_lex= &thd->lex->select_lex;
83
89
    Name_resolution_context *context= &select_lex->context;
84
90
    Name_resolution_context_state ctx_state;
85
91
    int res;
90
96
      return -1;
91
97
    }
92
98
 
93
 
    session->dup_field= 0;
 
99
    thd->dup_field= 0;
94
100
 
95
101
    /* Save the state of the current name resolution context. */
96
102
    ctx_state.save_state(context, table_list);
101
107
    */
102
108
    table_list->next_local= 0;
103
109
    context->resolve_in_table_list_only(table_list);
104
 
    res= setup_fields(session, 0, fields, MARK_COLUMNS_WRITE, 0, 0);
 
110
    res= setup_fields(thd, 0, fields, MARK_COLUMNS_WRITE, 0, 0);
105
111
 
106
112
    /* Restore the current context. */
107
113
    ctx_state.restore_state(context, table_list);
109
115
    if (res)
110
116
      return -1;
111
117
 
112
 
    if (check_unique && session->dup_field)
 
118
    if (check_unique && thd->dup_field)
113
119
    {
114
 
      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);
115
121
      return -1;
116
122
    }
117
123
    if (table->timestamp_field) // Don't automaticly set timestamp if used
126
132
                       table->timestamp_field->field_index);
127
133
      }
128
134
    }
129
 
    /* Mark all virtual columns for write*/
130
 
    if (table->vfield)
131
 
      table->mark_virtual_columns();
132
135
  }
133
136
 
134
137
  return 0;
140
143
 
141
144
  SYNOPSIS
142
145
    check_update_fields()
143
 
    session                         The current thread.
 
146
    thd                         The current thread.
144
147
    insert_table_list           The insert table list.
145
148
    table                       The table for update.
146
149
    update_fields               The update fields.
154
157
    -1          Error
155
158
*/
156
159
 
157
 
static int check_update_fields(Session *session, TableList *insert_table_list,
 
160
static int check_update_fields(THD *thd, TableList *insert_table_list,
158
161
                               List<Item> &update_fields,
159
 
                               table_map *)
 
162
                               table_map *map __attribute__((unused)))
160
163
{
161
164
  Table *table= insert_table_list->table;
162
165
  bool timestamp_mark= false;
172
175
  }
173
176
 
174
177
  /* Check the fields we are going to modify */
175
 
  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))
176
179
    return -1;
177
180
 
178
181
  if (table->timestamp_field)
199
202
*/
200
203
 
201
204
static
202
 
void upgrade_lock_type(Session *,
 
205
void upgrade_lock_type(THD *thd __attribute__((unused)),
203
206
                       thr_lock_type *lock_type,
204
207
                       enum_duplicates duplic,
205
 
                       bool )
 
208
                       bool is_multi_insert __attribute__((unused)))
206
209
{
207
210
  if (duplic == DUP_UPDATE ||
208
211
      (duplic == DUP_REPLACE && *lock_type == TL_WRITE_CONCURRENT_INSERT))
221
224
  end of dispatch_command().
222
225
*/
223
226
 
224
 
bool mysql_insert(Session *session,TableList *table_list,
 
227
bool mysql_insert(THD *thd,TableList *table_list,
225
228
                  List<Item> &fields,
226
229
                  List<List_item> &values_list,
227
230
                  List<Item> &update_fields,
232
235
  int error;
233
236
  bool transactional_table, joins_freed= false;
234
237
  bool changed;
 
238
  bool was_insert_delayed= (table_list->lock_type ==  TL_WRITE_DELAYED);
235
239
  uint32_t value_count;
236
240
  ulong counter = 1;
237
241
  uint64_t id;
243
247
  Name_resolution_context_state ctx_state;
244
248
  thr_lock_type lock_type;
245
249
  Item *unused_conds= 0;
246
 
 
 
250
  
247
251
 
248
252
  /*
249
253
    Upgrade lock type if the requested lock is incompatible with
250
254
    the current connection mode or table operation.
251
255
  */
252
 
  upgrade_lock_type(session, &table_list->lock_type, duplic,
 
256
  upgrade_lock_type(thd, &table_list->lock_type, duplic,
253
257
                    values_list.elements > 1);
254
258
 
255
 
  if (open_and_lock_tables(session, 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))
 
267
  {
 
268
    my_error(ER_DELAYED_INSERT_TABLE_LOCKED, MYF(0),
 
269
             table_list->table_name);
256
270
    return(true);
 
271
  }
257
272
 
 
273
  {
 
274
    if (open_and_lock_tables(thd, table_list))
 
275
      return(true);
 
276
  }
258
277
  lock_type= table_list->lock_type;
259
278
 
260
 
  session->set_proc_info("init");
261
 
  session->used_tables=0;
 
279
  thd_proc_info(thd, "init");
 
280
  thd->used_tables=0;
262
281
  values= its++;
263
282
  value_count= values->elements;
264
283
 
265
 
  if (mysql_prepare_insert(session, table_list, table, fields, values,
 
284
  if (mysql_prepare_insert(thd, table_list, table, fields, values,
266
285
                           update_fields, update_values, duplic, &unused_conds,
267
286
                           false,
268
287
                           (fields.elements || !value_count ||
272
291
  /* mysql_prepare_insert set table_list->table if it was not set */
273
292
  table= table_list->table;
274
293
 
275
 
  context= &session->lex->select_lex.context;
 
294
  context= &thd->lex->select_lex.context;
276
295
  /*
277
296
    These three asserts test the hypothesis that the resetting of the name
278
297
    resolution context below is not necessary at all since the list of local
300
319
      my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), counter);
301
320
      goto abort;
302
321
    }
303
 
    if (setup_fields(session, 0, *values, MARK_COLUMNS_READ, 0, 0))
 
322
    if (setup_fields(thd, 0, *values, MARK_COLUMNS_READ, 0, 0))
304
323
      goto abort;
305
324
  }
306
325
  its.rewind ();
307
 
 
 
326
 
308
327
  /* Restore the current context. */
309
328
  ctx_state.restore_state(context, table_list);
310
329
 
322
341
    For single line insert, generate an error if try to set a NOT NULL field
323
342
    to NULL.
324
343
  */
325
 
  session->count_cuted_fields= ((values_list.elements == 1 &&
 
344
  thd->count_cuted_fields= ((values_list.elements == 1 &&
326
345
                             !ignore) ?
327
346
                            CHECK_FIELD_ERROR_FOR_NULL :
328
347
                            CHECK_FIELD_WARN);
329
 
  session->cuted_fields = 0L;
 
348
  thd->cuted_fields = 0L;
330
349
  table->next_number_field=table->found_next_number_field;
331
350
 
 
351
  if (thd->slave_thread &&
 
352
      (info.handle_duplicates == DUP_UPDATE) &&
 
353
      (table->next_number_field != NULL) &&
 
354
      rpl_master_has_bug(&active_mi->rli, 24432))
 
355
    goto abort;
 
356
 
332
357
  error=0;
333
 
  session->set_proc_info("update");
 
358
  thd_proc_info(thd, "update");
334
359
  if (duplic == DUP_REPLACE)
335
360
    table->file->extra(HA_EXTRA_WRITE_CAN_REPLACE);
336
361
  if (duplic == DUP_UPDATE)
342
367
  }
343
368
 
344
369
 
345
 
  session->abort_on_warning= !ignore;
 
370
  thd->abort_on_warning= !ignore;
346
371
 
347
372
  table->mark_columns_needed_for_insert();
348
373
 
351
376
    if (fields.elements || !value_count)
352
377
    {
353
378
      restore_record(table,s->default_values);  // Get empty record
354
 
      if (fill_record(session, fields, *values, 0))
 
379
      if (fill_record(thd, fields, *values, 0))
355
380
      {
356
 
        if (values_list.elements != 1 && ! session->is_error())
 
381
        if (values_list.elements != 1 && ! thd->is_error())
357
382
        {
358
383
          info.records++;
359
384
          continue;
360
385
        }
361
386
        /*
362
 
          TODO: set session->abort_on_warning if values_list.elements == 1
 
387
          TODO: set thd->abort_on_warning if values_list.elements == 1
363
388
          and check that all items return warning in case of problem with
364
389
          storing field.
365
390
        */
369
394
    }
370
395
    else
371
396
    {
372
 
      if (session->used_tables)                 // Column used in values()
 
397
      if (thd->used_tables)                     // Column used in values()
373
398
        restore_record(table,s->default_values);        // Get empty record
374
399
      else
375
400
      {
380
405
        */
381
406
        table->record[0][0]= table->s->default_values[0];
382
407
      }
383
 
      if (fill_record(session, table->field, *values, 0))
 
408
      if (fill_record(thd, table->field, *values, 0))
384
409
      {
385
 
        if (values_list.elements != 1 && ! session->is_error())
 
410
        if (values_list.elements != 1 && ! thd->is_error())
386
411
        {
387
412
          info.records++;
388
413
          continue;
392
417
      }
393
418
    }
394
419
 
395
 
    // Release latches in case bulk insert takes a long time
396
 
    ha_release_temporary_latches(session);
397
 
 
398
 
    error=write_record(session, table ,&info);
 
420
    error=write_record(thd, table ,&info);
399
421
    if (error)
400
422
      break;
401
 
    session->row_count++;
 
423
    thd->row_count++;
402
424
  }
403
425
 
404
 
  free_underlaid_joins(session, &session->lex->select_lex);
 
426
  free_underlaid_joins(thd, &thd->lex->select_lex);
405
427
  joins_freed= true;
406
428
 
407
429
  /*
424
446
 
425
447
    transactional_table= table->file->has_transactions();
426
448
 
427
 
    changed= (info.copied || info.deleted || info.updated);
428
 
    if ((changed && error <= 0) || session->transaction.stmt.modified_non_trans_table)
429
 
    {
430
 
      if (session->transaction.stmt.modified_non_trans_table)
431
 
        session->transaction.all.modified_non_trans_table= true;
432
 
    }
433
 
    assert(transactional_table || !changed || session->transaction.stmt.modified_non_trans_table);
 
449
    if ((changed= (info.copied || info.deleted || info.updated)))
 
450
    {
 
451
      /*
 
452
        Invalidate the table in the query cache if something changed.
 
453
        For the transactional algorithm to work the invalidation must be
 
454
        before binlog writing and ha_autocommit_or_rollback
 
455
      */
 
456
    }
 
457
    if ((changed && error <= 0) || thd->transaction.stmt.modified_non_trans_table || was_insert_delayed)
 
458
    {
 
459
      if (mysql_bin_log.is_open())
 
460
      {
 
461
        if (error <= 0)
 
462
        {
 
463
          /*
 
464
            [Guilhem wrote] Temporary errors may have filled
 
465
            thd->net.last_error/errno.  For example if there has
 
466
            been a disk full error when writing the row, and it was
 
467
            MyISAM, then thd->net.last_error/errno will be set to
 
468
            "disk full"... and the my_pwrite() will wait until free
 
469
            space appears, and so when it finishes then the
 
470
            write_row() was entirely successful
 
471
          */
 
472
          /* todo: consider removing */
 
473
          thd->clear_error();
 
474
        }
 
475
        /* bug#22725:
 
476
 
 
477
        A query which per-row-loop can not be interrupted with
 
478
        KILLED, like INSERT, and that does not invoke stored
 
479
        routines can be binlogged with neglecting the KILLED error.
 
480
        
 
481
        If there was no error (error == zero) until after the end of
 
482
        inserting loop the KILLED flag that appeared later can be
 
483
        disregarded since previously possible invocation of stored
 
484
        routines did not result in any error due to the KILLED.  In
 
485
        such case the flag is ignored for constructing binlog event.
 
486
        */
 
487
        assert(thd->killed != THD::KILL_BAD_DATA || error > 0);
 
488
        if (thd->binlog_query(THD::ROW_QUERY_TYPE,
 
489
                              thd->query, thd->query_length,
 
490
                              transactional_table, false,
 
491
                              (error>0) ? thd->killed : THD::NOT_KILLED) &&
 
492
            transactional_table)
 
493
        {
 
494
          error=1;
 
495
        }
 
496
      }
 
497
      if (thd->transaction.stmt.modified_non_trans_table)
 
498
        thd->transaction.all.modified_non_trans_table= true;
 
499
    }
 
500
    assert(transactional_table || !changed || 
 
501
                thd->transaction.stmt.modified_non_trans_table);
434
502
 
435
503
  }
436
 
  session->set_proc_info("end");
 
504
  thd_proc_info(thd, "end");
437
505
  /*
438
506
    We'll report to the client this id:
439
507
    - if the table contains an autoincrement column and we successfully
444
512
    inserted, the id of the last "inserted" row (if IGNORE, that value may not
445
513
    have been really inserted but ignored).
446
514
  */
447
 
  id= (session->first_successful_insert_id_in_cur_stmt > 0) ?
448
 
    session->first_successful_insert_id_in_cur_stmt :
449
 
    (session->arg_of_last_insert_id_function ?
450
 
     session->first_successful_insert_id_in_prev_stmt :
 
515
  id= (thd->first_successful_insert_id_in_cur_stmt > 0) ?
 
516
    thd->first_successful_insert_id_in_cur_stmt :
 
517
    (thd->arg_of_last_insert_id_function ?
 
518
     thd->first_successful_insert_id_in_prev_stmt :
451
519
     ((table->next_number_field && info.copied) ?
452
520
     table->next_number_field->val_int() : 0));
453
521
  table->next_number_field=0;
454
 
  session->count_cuted_fields= CHECK_FIELD_IGNORE;
 
522
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;
455
523
  table->auto_increment_field_not_null= false;
456
524
  if (duplic == DUP_REPLACE)
457
525
    table->file->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
458
526
 
459
527
  if (error)
460
528
    goto abort;
461
 
  if (values_list.elements == 1 && (!(session->options & OPTION_WARNINGS) ||
462
 
                                    !session->cuted_fields))
 
529
  if (values_list.elements == 1 && (!(thd->options & OPTION_WARNINGS) ||
 
530
                                    !thd->cuted_fields))
463
531
  {
464
 
    session->row_count_func= info.copied + info.deleted +
465
 
                         ((session->client_capabilities & CLIENT_FOUND_ROWS) ?
 
532
    thd->row_count_func= info.copied + info.deleted +
 
533
                         ((thd->client_capabilities & CLIENT_FOUND_ROWS) ?
466
534
                          info.touched : info.updated);
467
 
    session->my_ok((ulong) session->row_count_func, id);
 
535
    my_ok(thd, (ulong) thd->row_count_func, id);
468
536
  }
469
537
  else
470
538
  {
471
539
    char buff[160];
472
 
    ha_rows updated=((session->client_capabilities & CLIENT_FOUND_ROWS) ?
 
540
    ha_rows updated=((thd->client_capabilities & CLIENT_FOUND_ROWS) ?
473
541
                     info.touched : info.updated);
474
542
    if (ignore)
475
543
      sprintf(buff, ER(ER_INSERT_INFO), (ulong) info.records,
476
 
              (ulong) (info.records - info.copied), (ulong) session->cuted_fields);
 
544
              (ulong) (info.records - info.copied), (ulong) thd->cuted_fields);
477
545
    else
478
546
      sprintf(buff, ER(ER_INSERT_INFO), (ulong) info.records,
479
 
              (ulong) (info.deleted + updated), (ulong) session->cuted_fields);
480
 
    session->row_count_func= info.copied + info.deleted + updated;
481
 
    session->my_ok((ulong) session->row_count_func, id, buff);
 
547
              (ulong) (info.deleted + updated), (ulong) thd->cuted_fields);
 
548
    thd->row_count_func= info.copied + info.deleted + updated;
 
549
    ::my_ok(thd, (ulong) thd->row_count_func, id, buff);
482
550
  }
483
 
  session->abort_on_warning= 0;
 
551
  thd->abort_on_warning= 0;
484
552
  DRIZZLE_INSERT_END();
485
553
  return(false);
486
554
 
488
556
  if (table != NULL)
489
557
    table->file->ha_release_auto_increment();
490
558
  if (!joins_freed)
491
 
    free_underlaid_joins(session, &session->lex->select_lex);
492
 
  session->abort_on_warning= 0;
 
559
    free_underlaid_joins(thd, &thd->lex->select_lex);
 
560
  thd->abort_on_warning= 0;
493
561
  DRIZZLE_INSERT_END();
494
562
  return(true);
495
563
}
500
568
 
501
569
  SYNOPSIS
502
570
     mysql_prepare_insert_check_table()
503
 
     session            Thread handle
 
571
     thd                Thread handle
504
572
     table_list         Table list
505
573
     fields             List of fields to be updated
506
574
     where              Pointer to where clause
511
579
     true  ERROR
512
580
*/
513
581
 
514
 
static bool mysql_prepare_insert_check_table(Session *session, TableList *table_list,
515
 
                                             List<Item> &,
 
582
static bool mysql_prepare_insert_check_table(THD *thd, TableList *table_list,
 
583
                                             List<Item> &fields __attribute__((unused)),
516
584
                                             bool select_insert)
517
585
{
518
 
 
 
586
  
519
587
 
520
588
  /*
521
589
     first table in list is the one we'll INSERT into, requires INSERT_ACL.
524
592
     than INSERT.
525
593
  */
526
594
 
527
 
  if (setup_tables_and_check_access(session, &session->lex->select_lex.context,
528
 
                                    &session->lex->select_lex.top_join_list,
 
595
  if (setup_tables_and_check_access(thd, &thd->lex->select_lex.context,
 
596
                                    &thd->lex->select_lex.top_join_list,
529
597
                                    table_list,
530
 
                                    &session->lex->select_lex.leaf_tables,
 
598
                                    &thd->lex->select_lex.leaf_tables,
531
599
                                    select_insert))
532
600
    return(true);
533
601
 
540
608
 
541
609
  SYNOPSIS
542
610
    mysql_prepare_insert()
543
 
    session                     Thread handler
 
611
    thd                 Thread handler
544
612
    table_list          Global/local table list
545
613
    table               Table to insert into (can be NULL if table should
546
 
                        be taken from table_list->table)
 
614
                        be taken from table_list->table)    
547
615
    where               Where clause (for insert ... select)
548
616
    select_insert       true if INSERT ... SELECT statement
549
 
    check_fields        true if need to check that all INSERT fields are
 
617
    check_fields        true if need to check that all INSERT fields are 
550
618
                        given values.
551
 
    abort_on_warning    whether to report if some INSERT field is not
 
619
    abort_on_warning    whether to report if some INSERT field is not 
552
620
                        assigned as an error (true) or as a warning (false).
553
621
 
554
622
  TODO (in far future)
560
628
  WARNING
561
629
    You MUST set table->insert_values to 0 after calling this function
562
630
    before releasing the table object.
563
 
 
 
631
  
564
632
  RETURN VALUE
565
633
    false OK
566
634
    true  error
567
635
*/
568
636
 
569
 
bool mysql_prepare_insert(Session *session, TableList *table_list,
 
637
bool mysql_prepare_insert(THD *thd, TableList *table_list,
570
638
                          Table *table, List<Item> &fields, List_item *values,
571
639
                          List<Item> &update_fields, List<Item> &update_values,
572
640
                          enum_duplicates duplic,
573
 
                          COND **,
 
641
                          COND **where __attribute__((unused)),
574
642
                          bool select_insert,
575
643
                          bool check_fields, bool abort_on_warning)
576
644
{
577
 
  Select_Lex *select_lex= &session->lex->select_lex;
 
645
  SELECT_LEX *select_lex= &thd->lex->select_lex;
578
646
  Name_resolution_context *context= &select_lex->context;
579
647
  Name_resolution_context_state ctx_state;
580
648
  bool insert_into_view= (0 != 0);
581
649
  bool res= 0;
582
650
  table_map map= 0;
583
 
 
 
651
  
584
652
  /* INSERT should have a SELECT or VALUES clause */
585
653
  assert (!select_insert || !values);
586
654
 
587
655
  /*
588
656
    For subqueries in VALUES() we should not see the table in which we are
589
657
    inserting (for INSERT ... SELECT this is done by changing table_list,
590
 
    because INSERT ... SELECT share Select_Lex it with SELECT.
 
658
    because INSERT ... SELECT share SELECT_LEX it with SELECT.
591
659
  */
592
660
  if (!select_insert)
593
661
  {
594
 
    for (Select_Lex_Unit *un= select_lex->first_inner_unit();
 
662
    for (SELECT_LEX_UNIT *un= select_lex->first_inner_unit();
595
663
         un;
596
664
         un= un->next_unit())
597
665
    {
598
 
      for (Select_Lex *sl= un->first_select();
 
666
      for (SELECT_LEX *sl= un->first_select();
599
667
           sl;
600
668
           sl= sl->next_select())
601
669
      {
607
675
  if (duplic == DUP_UPDATE)
608
676
  {
609
677
    /* it should be allocated before Item::fix_fields() */
610
 
    if (table_list->set_insert_values(session->mem_root))
 
678
    if (table_list->set_insert_values(thd->mem_root))
611
679
      return(true);
612
680
  }
613
681
 
614
 
  if (mysql_prepare_insert_check_table(session, table_list, fields, select_insert))
 
682
  if (mysql_prepare_insert_check_table(thd, table_list, fields, select_insert))
615
683
    return(true);
616
684
 
617
685
 
631
699
    table_list->next_local= 0;
632
700
    context->resolve_in_table_list_only(table_list);
633
701
 
634
 
    res= check_insert_fields(session, context->table_list, fields, *values,
 
702
    res= check_insert_fields(thd, context->table_list, fields, *values,
635
703
                             !insert_into_view, &map) ||
636
 
      setup_fields(session, 0, *values, MARK_COLUMNS_READ, 0, 0);
 
704
      setup_fields(thd, 0, *values, MARK_COLUMNS_READ, 0, 0);
637
705
 
638
706
    if (!res && check_fields)
639
707
    {
640
 
      bool saved_abort_on_warning= session->abort_on_warning;
641
 
      session->abort_on_warning= abort_on_warning;
642
 
      res= check_that_all_fields_are_given_values(session,
643
 
                                                  table ? table :
 
708
      bool saved_abort_on_warning= thd->abort_on_warning;
 
709
      thd->abort_on_warning= abort_on_warning;
 
710
      res= check_that_all_fields_are_given_values(thd, 
 
711
                                                  table ? table : 
644
712
                                                  context->table_list->table,
645
713
                                                  context->table_list);
646
 
      session->abort_on_warning= saved_abort_on_warning;
 
714
      thd->abort_on_warning= saved_abort_on_warning;
647
715
    }
648
716
 
649
717
    if (!res && duplic == DUP_UPDATE)
650
718
    {
651
 
      res= check_update_fields(session, context->table_list, update_fields, &map);
 
719
      res= check_update_fields(thd, context->table_list, update_fields, &map);
652
720
    }
653
721
 
654
722
    /* Restore the current context. */
655
723
    ctx_state.restore_state(context, table_list);
656
724
 
657
725
    if (!res)
658
 
      res= setup_fields(session, 0, update_values, MARK_COLUMNS_READ, 0, 0);
 
726
      res= setup_fields(thd, 0, update_values, MARK_COLUMNS_READ, 0, 0);
659
727
  }
660
728
 
661
729
  if (res)
667
735
  if (!select_insert)
668
736
  {
669
737
    TableList *duplicate;
670
 
    if ((duplicate= unique_table(session, table_list, table_list->next_global, 1)))
 
738
    if ((duplicate= unique_table(thd, table_list, table_list->next_global, 1)))
671
739
    {
672
740
      update_non_unique_table_error(table_list, "INSERT", duplicate);
673
741
      return(true);
696
764
 
697
765
  SYNOPSIS
698
766
     write_record()
699
 
      session   - thread context
 
767
      thd   - thread context
700
768
      table - table to which record should be written
701
769
      info  - COPY_INFO structure describing handling of duplicates
702
770
              and which is used for counting number of records inserted
708
776
    then both on update triggers will work instead. Similarly both on
709
777
    delete triggers will be invoked if we will delete conflicting records.
710
778
 
711
 
    Sets session->transaction.stmt.modified_non_trans_table to true if table which is updated didn't have
 
779
    Sets thd->transaction.stmt.modified_non_trans_table to true if table which is updated didn't have
712
780
    transactions.
713
781
 
714
782
  RETURN VALUE
717
785
*/
718
786
 
719
787
 
720
 
int write_record(Session *session, Table *table,COPY_INFO *info)
 
788
int write_record(THD *thd, Table *table,COPY_INFO *info)
721
789
{
722
790
  int error;
723
791
  char *key=0;
724
792
  MY_BITMAP *save_read_set, *save_write_set;
725
793
  uint64_t prev_insert_id= table->file->next_insert_id;
726
794
  uint64_t insert_id_for_cur_row= 0;
727
 
 
 
795
  
728
796
 
729
797
  info->records++;
730
798
  save_read_set=  table->read_set;
731
799
  save_write_set= table->write_set;
732
800
 
733
 
  if (info->handle_duplicates == DUP_REPLACE || info->handle_duplicates == DUP_UPDATE)
 
801
  if (info->handle_duplicates == DUP_REPLACE ||
 
802
      info->handle_duplicates == DUP_UPDATE)
734
803
  {
735
804
    while ((error=table->file->ha_write_row(table->record[0])))
736
805
    {
739
808
        If we do more than one iteration of this loop, from the second one the
740
809
        row will have an explicit value in the autoinc field, which was set at
741
810
        the first call of handler::update_auto_increment(). So we must save
742
 
        the autogenerated value to avoid session->insert_id_for_cur_row to become
 
811
        the autogenerated value to avoid thd->insert_id_for_cur_row to become
743
812
        0.
744
813
      */
745
814
      if (table->file->insert_id_for_cur_row > 0)
793
862
 
794
863
        if (!key)
795
864
        {
796
 
          if (!(key=(char*) malloc(table->s->max_unique_length)))
 
865
          if (!(key=(char*) my_safe_alloca(table->s->max_unique_length,
 
866
                                           MAX_KEY_LENGTH)))
797
867
          {
798
868
            error=ENOMEM;
799
869
            goto err;
817
887
        restore_record(table,record[1]);
818
888
        assert(info->update_fields->elements ==
819
889
                    info->update_values->elements);
820
 
        if (fill_record(session, *info->update_fields,
 
890
        if (fill_record(thd, *info->update_fields,
821
891
                                                 *info->update_values,
822
892
                                                 info->ignore))
823
893
          goto before_err;
852
922
            like a regular UPDATE statement: it should not affect the value of a
853
923
            next SELECT LAST_INSERT_ID() or mysql_insert_id().
854
924
            Except if LAST_INSERT_ID(#) was in the INSERT query, which is
855
 
            handled separately by Session::arg_of_last_insert_id_function.
 
925
            handled separately by THD::arg_of_last_insert_id_function.
856
926
          */
857
927
          insert_id_for_cur_row= table->file->insert_id_for_cur_row= 0;
858
928
          info->copied++;
872
942
          an INSERT or DELETE(s) + INSERT; FOREIGN KEY checks in
873
943
          InnoDB do not function in the defined way if we allow MySQL
874
944
          to convert the latter operation internally to an UPDATE.
875
 
          We also should not perform this conversion if we have
 
945
          We also should not perform this conversion if we have 
876
946
          timestamp field with ON UPDATE which is different from DEFAULT.
877
947
          Another case when conversion should not be performed is when
878
948
          we have ON DELETE trigger on table so user may notice that
894
964
            info->deleted++;
895
965
          else
896
966
            error= 0;
897
 
          session->record_first_successful_insert_id_in_cur_stmt(table->file->insert_id_for_cur_row);
 
967
          thd->record_first_successful_insert_id_in_cur_stmt(table->file->insert_id_for_cur_row);
898
968
          /*
899
969
            Since we pretend that we have done insert we should call
900
970
            its after triggers.
907
977
            goto err;
908
978
          info->deleted++;
909
979
          if (!table->file->has_transactions())
910
 
            session->transaction.stmt.modified_non_trans_table= true;
 
980
            thd->transaction.stmt.modified_non_trans_table= true;
911
981
          /* Let us attempt do write_row() once more */
912
982
        }
913
983
      }
914
984
    }
915
 
    session->record_first_successful_insert_id_in_cur_stmt(table->file->insert_id_for_cur_row);
 
985
    thd->record_first_successful_insert_id_in_cur_stmt(table->file->insert_id_for_cur_row);
916
986
    /*
917
987
      Restore column maps if they where replaced during an duplicate key
918
988
      problem.
932
1002
 
933
1003
after_n_copied_inc:
934
1004
  info->copied++;
935
 
  session->record_first_successful_insert_id_in_cur_stmt(table->file->insert_id_for_cur_row);
 
1005
  thd->record_first_successful_insert_id_in_cur_stmt(table->file->insert_id_for_cur_row);
936
1006
 
937
1007
gok_or_after_err:
938
1008
  if (key)
939
 
    free(key);
 
1009
    my_safe_afree(key,table->s->max_unique_length,MAX_KEY_LENGTH);
940
1010
  if (!table->file->has_transactions())
941
 
    session->transaction.stmt.modified_non_trans_table= true;
 
1011
    thd->transaction.stmt.modified_non_trans_table= true;
942
1012
  return(0);
943
1013
 
944
1014
err:
945
1015
  info->last_errno= error;
946
1016
  /* current_select is NULL if this is a delayed insert */
947
 
  if (session->lex->current_select)
948
 
    session->lex->current_select->no_error= 0;        // Give error
 
1017
  if (thd->lex->current_select)
 
1018
    thd->lex->current_select->no_error= 0;        // Give error
949
1019
  table->file->print_error(error,MYF(0));
950
 
 
 
1020
  
951
1021
before_err:
952
1022
  table->file->restore_auto_increment(prev_insert_id);
953
1023
  if (key)
954
 
    free(key);
 
1024
    my_safe_afree(key, table->s->max_unique_length, MAX_KEY_LENGTH);
955
1025
  table->column_bitmaps_set(save_read_set, save_write_set);
956
1026
  return(1);
957
1027
}
961
1031
  Check that all fields with arn't null_fields are used
962
1032
******************************************************************************/
963
1033
 
964
 
int check_that_all_fields_are_given_values(Session *session, Table *entry,
965
 
                                           TableList *)
 
1034
int check_that_all_fields_are_given_values(THD *thd, Table *entry,
 
1035
                                           TableList *table_list)
966
1036
{
967
1037
  int err= 0;
968
1038
  MY_BITMAP *write_set= entry->write_set;
969
1039
 
970
1040
  for (Field **field=entry->field ; *field ; field++)
971
1041
  {
972
 
    if (!bitmap_is_set(write_set, (*field)->field_index))
973
 
    {
974
 
      /*
975
 
       * If the field doesn't have any default value
976
 
       * and there is no actual value specified in the
977
 
       * INSERT statement, throw error ER_NO_DEFAULT_FOR_FIELD.
978
 
       */
979
 
      if (((*field)->flags & NO_DEFAULT_VALUE_FLAG) &&
 
1042
    if (!bitmap_is_set(write_set, (*field)->field_index) &&
 
1043
        ((*field)->flags & NO_DEFAULT_VALUE_FLAG) &&
980
1044
        ((*field)->real_type() != DRIZZLE_TYPE_ENUM))
981
 
      {
982
 
        my_error(ER_NO_DEFAULT_FOR_FIELD, MYF(0), (*field)->field_name);
983
 
        err= 1;
984
 
      }
985
 
    }
986
 
    else
987
1045
    {
988
 
      /*
989
 
       * However, if an actual NULL value was specified
990
 
       * for the field and the field is a NOT NULL field, 
991
 
       * throw ER_BAD_NULL_ERROR.
992
 
       *
993
 
       * Per the SQL standard, inserting NULL into a NOT NULL
994
 
       * field requires an error to be thrown.
995
 
       */
996
 
      if (((*field)->flags & NOT_NULL_FLAG) &&
997
 
          (*field)->is_null())
998
 
      {
999
 
        my_error(ER_BAD_NULL_ERROR, MYF(0), (*field)->field_name);
1000
 
        err= 1;
1001
 
      }
 
1046
      bool view= false;
 
1047
      if (table_list)
 
1048
      {
 
1049
        table_list= table_list->top_table();
 
1050
        view= test(0);
 
1051
      }
 
1052
      {
 
1053
        push_warning_printf(thd, DRIZZLE_ERROR::WARN_LEVEL_WARN,
 
1054
                            ER_NO_DEFAULT_FOR_FIELD,
 
1055
                            ER(ER_NO_DEFAULT_FOR_FIELD),
 
1056
                            (*field)->field_name);
 
1057
      }
 
1058
      err= 1;
1002
1059
    }
1003
1060
  }
1004
 
  return session->abort_on_warning ? err : 0;
 
1061
  return thd->abort_on_warning ? err : 0;
1005
1062
}
1006
1063
 
1007
1064
/***************************************************************************
1014
1071
 
1015
1072
  SYNOPSIS
1016
1073
    mysql_insert_select_prepare()
1017
 
    session         thread handler
 
1074
    thd         thread handler
1018
1075
 
1019
1076
  RETURN
1020
1077
    false OK
1021
1078
    true  Error
1022
1079
*/
1023
1080
 
1024
 
bool mysql_insert_select_prepare(Session *session)
 
1081
bool mysql_insert_select_prepare(THD *thd)
1025
1082
{
1026
 
  LEX *lex= session->lex;
1027
 
  Select_Lex *select_lex= &lex->select_lex;
1028
 
 
1029
 
  /*
1030
 
    Select_Lex do not belong to INSERT statement, so we can't add WHERE
 
1083
  LEX *lex= thd->lex;
 
1084
  SELECT_LEX *select_lex= &lex->select_lex;
 
1085
  
 
1086
 
 
1087
  /*
 
1088
    Statement-based replication of INSERT ... SELECT ... LIMIT is not safe
 
1089
    as order of rows is not defined, so in mixed mode we go to row-based.
 
1090
 
 
1091
    Note that we may consider a statement as safe if ORDER BY primary_key
 
1092
    is present or we SELECT a constant. However it may confuse users to
 
1093
    see very similiar statements replicated differently.
 
1094
  */
 
1095
  if (lex->current_select->select_limit)
 
1096
  {
 
1097
    lex->set_stmt_unsafe();
 
1098
    thd->set_current_stmt_binlog_row_based_if_mixed();
 
1099
  }
 
1100
  /*
 
1101
    SELECT_LEX do not belong to INSERT statement, so we can't add WHERE
1031
1102
    clause if table is VIEW
1032
1103
  */
1033
 
 
1034
 
  if (mysql_prepare_insert(session, lex->query_tables,
 
1104
  
 
1105
  if (mysql_prepare_insert(thd, lex->query_tables,
1035
1106
                           lex->query_tables->table, lex->field_list, 0,
1036
1107
                           lex->update_list, lex->value_list,
1037
1108
                           lex->duplicates,
1069
1140
 
1070
1141
 
1071
1142
int
1072
 
select_insert::prepare(List<Item> &values, Select_Lex_Unit *u)
 
1143
select_insert::prepare(List<Item> &values, SELECT_LEX_UNIT *u)
1073
1144
{
1074
 
  LEX *lex= session->lex;
 
1145
  LEX *lex= thd->lex;
1075
1146
  int res;
1076
1147
  table_map map= 0;
1077
 
  Select_Lex *lex_current_select_save= lex->current_select;
1078
 
 
 
1148
  SELECT_LEX *lex_current_select_save= lex->current_select;
 
1149
  
1079
1150
 
1080
1151
  unit= u;
1081
1152
 
1085
1156
    we are fixing fields from insert list.
1086
1157
  */
1087
1158
  lex->current_select= &lex->select_lex;
1088
 
  res= check_insert_fields(session, table_list, *fields, values,
 
1159
  res= check_insert_fields(thd, table_list, *fields, values,
1089
1160
                           !insert_into_view, &map) ||
1090
 
       setup_fields(session, 0, values, MARK_COLUMNS_READ, 0, 0);
 
1161
       setup_fields(thd, 0, values, MARK_COLUMNS_READ, 0, 0);
1091
1162
 
1092
1163
  if (!res && fields->elements)
1093
1164
  {
1094
 
    bool saved_abort_on_warning= session->abort_on_warning;
1095
 
    session->abort_on_warning= !info.ignore;
1096
 
    res= check_that_all_fields_are_given_values(session, table_list->table,
 
1165
    bool saved_abort_on_warning= thd->abort_on_warning;
 
1166
    thd->abort_on_warning= !info.ignore;
 
1167
    res= check_that_all_fields_are_given_values(thd, table_list->table, 
1097
1168
                                                table_list);
1098
 
    session->abort_on_warning= saved_abort_on_warning;
 
1169
    thd->abort_on_warning= saved_abort_on_warning;
1099
1170
  }
1100
1171
 
1101
1172
  if (info.handle_duplicates == DUP_UPDATE && !res)
1110
1181
    table_list->next_local= 0;
1111
1182
    context->resolve_in_table_list_only(table_list);
1112
1183
 
1113
 
    res= res || check_update_fields(session, context->table_list,
 
1184
    res= res || check_update_fields(thd, context->table_list,
1114
1185
                                    *info.update_fields, &map);
1115
1186
    /*
1116
 
      When we are not using GROUP BY and there are no ungrouped aggregate functions
 
1187
      When we are not using GROUP BY and there are no ungrouped aggregate functions 
1117
1188
      we can refer to other tables in the ON DUPLICATE KEY part.
1118
1189
      We use next_name_resolution_table descructively, so check it first (views?)
1119
1190
    */
1124
1195
        We must make a single context out of the two separate name resolution contexts :
1125
1196
        the INSERT table and the tables in the SELECT part of INSERT ... SELECT.
1126
1197
        To do that we must concatenate the two lists
1127
 
      */
1128
 
      table_list->next_name_resolution_table=
 
1198
      */  
 
1199
      table_list->next_name_resolution_table= 
1129
1200
        ctx_state.get_first_name_resolution_table();
1130
1201
 
1131
 
    res= res || setup_fields(session, 0, *info.update_values,
 
1202
    res= res || setup_fields(thd, 0, *info.update_values,
1132
1203
                             MARK_COLUMNS_READ, 0, 0);
1133
1204
    if (!res)
1134
1205
    {
1165
1236
    Is table which we are changing used somewhere in other parts of
1166
1237
    query
1167
1238
  */
1168
 
  if (unique_table(session, table_list, table_list->next_global, 0))
 
1239
  if (unique_table(thd, table_list, table_list->next_global, 0))
1169
1240
  {
1170
1241
    /* Using same table for INSERT and SELECT */
1171
1242
    lex->current_select->options|= OPTION_BUFFER_RESULT;
1174
1245
  else if (!(lex->current_select->options & OPTION_BUFFER_RESULT))
1175
1246
  {
1176
1247
    /*
1177
 
      We must not yet prepare the result table if it is the same as one of the
1178
 
      source tables (INSERT SELECT). The preparation may disable
 
1248
      We must not yet prepare the result table if it is the same as one of the 
 
1249
      source tables (INSERT SELECT). The preparation may disable 
1179
1250
      indexes on the result table, which may be used during the select, if it
1180
1251
      is the same table (Bug #6034). Do the preparation after the select phase
1181
1252
      in select_insert::prepare2().
1187
1258
  restore_record(table,s->default_values);              // Get empty record
1188
1259
  table->next_number_field=table->found_next_number_field;
1189
1260
 
1190
 
  session->cuted_fields=0;
 
1261
  if (thd->slave_thread &&
 
1262
      (info.handle_duplicates == DUP_UPDATE) &&
 
1263
      (table->next_number_field != NULL) &&
 
1264
      rpl_master_has_bug(&active_mi->rli, 24432))
 
1265
    return(1);
 
1266
 
 
1267
  thd->cuted_fields=0;
1191
1268
  if (info.ignore || info.handle_duplicates != DUP_ERROR)
1192
1269
    table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
1193
1270
  if (info.handle_duplicates == DUP_REPLACE)
1194
1271
    table->file->extra(HA_EXTRA_WRITE_CAN_REPLACE);
1195
1272
  if (info.handle_duplicates == DUP_UPDATE)
1196
1273
    table->file->extra(HA_EXTRA_INSERT_WITH_UPDATE);
1197
 
  session->abort_on_warning= !info.ignore;
 
1274
  thd->abort_on_warning= !info.ignore;
1198
1275
  table->mark_columns_needed_for_insert();
1199
1276
 
1200
1277
 
1213
1290
    If the result table is the same as one of the source tables (INSERT SELECT),
1214
1291
    the result table is not finally prepared at the join prepair phase.
1215
1292
    Do the final preparation now.
1216
 
 
 
1293
                       
1217
1294
  RETURN
1218
1295
    0   OK
1219
1296
*/
1220
1297
 
1221
1298
int select_insert::prepare2(void)
1222
1299
{
1223
 
 
1224
 
  if (session->lex->current_select->options & OPTION_BUFFER_RESULT)
 
1300
  
 
1301
  if (thd->lex->current_select->options & OPTION_BUFFER_RESULT)
1225
1302
    table->file->ha_start_bulk_insert((ha_rows) 0);
1226
1303
  return(0);
1227
1304
}
1235
1312
 
1236
1313
select_insert::~select_insert()
1237
1314
{
1238
 
 
 
1315
  
1239
1316
  if (table)
1240
1317
  {
1241
1318
    table->next_number_field=0;
1242
1319
    table->auto_increment_field_not_null= false;
1243
1320
    table->file->ha_reset();
1244
1321
  }
1245
 
  session->count_cuted_fields= CHECK_FIELD_IGNORE;
1246
 
  session->abort_on_warning= 0;
 
1322
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;
 
1323
  thd->abort_on_warning= 0;
1247
1324
  return;
1248
1325
}
1249
1326
 
1250
1327
 
1251
1328
bool select_insert::send_data(List<Item> &values)
1252
1329
{
1253
 
 
 
1330
  
1254
1331
  bool error=0;
1255
1332
 
1256
1333
  if (unit->offset_limit_cnt)
1259
1336
    return(0);
1260
1337
  }
1261
1338
 
1262
 
  session->count_cuted_fields= CHECK_FIELD_WARN;        // Calculate cuted fields
 
1339
  thd->count_cuted_fields= CHECK_FIELD_WARN;    // Calculate cuted fields
1263
1340
  store_values(values);
1264
 
  session->count_cuted_fields= CHECK_FIELD_IGNORE;
1265
 
  if (session->is_error())
 
1341
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;
 
1342
  if (thd->is_error())
1266
1343
    return(1);
1267
1344
 
1268
 
  error= write_record(session, table, &info);
1269
 
 
 
1345
  error= write_record(thd, table, &info);
 
1346
    
1270
1347
  if (!error)
1271
1348
  {
1272
1349
    if (info.handle_duplicates == DUP_UPDATE)
1274
1351
      /*
1275
1352
        Restore fields of the record since it is possible that they were
1276
1353
        changed by ON DUPLICATE KEY UPDATE clause.
1277
 
 
 
1354
    
1278
1355
        If triggers exist then whey can modify some fields which were not
1279
1356
        originally touched by INSERT ... SELECT, so we have to restore
1280
1357
        their original values for the next row.
1287
1364
        If no value has been autogenerated so far, we need to remember the
1288
1365
        value we just saw, we may need to send it to client in the end.
1289
1366
      */
1290
 
      if (session->first_successful_insert_id_in_cur_stmt == 0) // optimization
1291
 
        autoinc_value_of_last_inserted_row=
 
1367
      if (thd->first_successful_insert_id_in_cur_stmt == 0) // optimization
 
1368
        autoinc_value_of_last_inserted_row= 
1292
1369
          table->next_number_field->val_int();
1293
1370
      /*
1294
1371
        Clear auto-increment field for the next record, if triggers are used
1304
1381
void select_insert::store_values(List<Item> &values)
1305
1382
{
1306
1383
  if (fields->elements)
1307
 
    fill_record(session, *fields, values, 1);
 
1384
    fill_record(thd, *fields, values, 1);
1308
1385
  else
1309
 
    fill_record(session, table->field, values, 1);
 
1386
    fill_record(thd, table->field, values, 1);
1310
1387
}
1311
1388
 
1312
1389
void select_insert::send_error(uint32_t errcode,const char *err)
1313
1390
{
1314
 
 
 
1391
  
1315
1392
 
1316
1393
  my_message(errcode, err, MYF(0));
1317
1394
 
1325
1402
  bool const trans_table= table->file->has_transactions();
1326
1403
  uint64_t id;
1327
1404
  bool changed;
1328
 
 
 
1405
  THD::killed_state killed_status= thd->killed;
 
1406
  
1329
1407
  error= table->file->ha_end_bulk_insert();
1330
1408
  table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
1331
1409
  table->file->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
1336
1414
      We must invalidate the table in the query cache before binlog writing
1337
1415
      and ha_autocommit_or_rollback.
1338
1416
    */
1339
 
    if (session->transaction.stmt.modified_non_trans_table)
1340
 
      session->transaction.all.modified_non_trans_table= true;
 
1417
    if (thd->transaction.stmt.modified_non_trans_table)
 
1418
      thd->transaction.all.modified_non_trans_table= true;
1341
1419
  }
1342
 
  assert(trans_table || !changed ||
1343
 
              session->transaction.stmt.modified_non_trans_table);
 
1420
  assert(trans_table || !changed || 
 
1421
              thd->transaction.stmt.modified_non_trans_table);
1344
1422
 
 
1423
  /*
 
1424
    Write to binlog before commiting transaction.  No statement will
 
1425
    be written by the binlog_query() below in RBR mode.  All the
 
1426
    events are in the transaction cache and will be written when
 
1427
    ha_autocommit_or_rollback() is issued below.
 
1428
  */
 
1429
  if (mysql_bin_log.is_open())
 
1430
  {
 
1431
    if (!error)
 
1432
      thd->clear_error();
 
1433
    thd->binlog_query(THD::ROW_QUERY_TYPE,
 
1434
                      thd->query, thd->query_length,
 
1435
                      trans_table, false, killed_status);
 
1436
  }
1345
1437
  table->file->ha_release_auto_increment();
1346
1438
 
1347
1439
  if (error)
1352
1444
  char buff[160];
1353
1445
  if (info.ignore)
1354
1446
    sprintf(buff, ER(ER_INSERT_INFO), (ulong) info.records,
1355
 
            (ulong) (info.records - info.copied), (ulong) session->cuted_fields);
 
1447
            (ulong) (info.records - info.copied), (ulong) thd->cuted_fields);
1356
1448
  else
1357
1449
    sprintf(buff, ER(ER_INSERT_INFO), (ulong) info.records,
1358
 
            (ulong) (info.deleted+info.updated), (ulong) session->cuted_fields);
1359
 
  session->row_count_func= info.copied + info.deleted +
1360
 
                       ((session->client_capabilities & CLIENT_FOUND_ROWS) ?
 
1450
            (ulong) (info.deleted+info.updated), (ulong) thd->cuted_fields);
 
1451
  thd->row_count_func= info.copied + info.deleted +
 
1452
                       ((thd->client_capabilities & CLIENT_FOUND_ROWS) ?
1361
1453
                        info.touched : info.updated);
1362
1454
 
1363
 
  id= (session->first_successful_insert_id_in_cur_stmt > 0) ?
1364
 
    session->first_successful_insert_id_in_cur_stmt :
1365
 
    (session->arg_of_last_insert_id_function ?
1366
 
     session->first_successful_insert_id_in_prev_stmt :
 
1455
  id= (thd->first_successful_insert_id_in_cur_stmt > 0) ?
 
1456
    thd->first_successful_insert_id_in_cur_stmt :
 
1457
    (thd->arg_of_last_insert_id_function ?
 
1458
     thd->first_successful_insert_id_in_prev_stmt :
1367
1459
     (info.copied ? autoinc_value_of_last_inserted_row : 0));
1368
 
  session->my_ok((ulong) session->row_count_func, id, buff);
 
1460
  ::my_ok(thd, (ulong) thd->row_count_func, id, buff);
1369
1461
  return(0);
1370
1462
}
1371
1463
 
1372
1464
void select_insert::abort() {
1373
1465
 
1374
 
 
 
1466
  
1375
1467
  /*
1376
1468
    If the creation of the table failed (due to a syntax error, for
1377
1469
    example), no table will have been opened and therefore 'table'
1400
1492
    */
1401
1493
    changed= (info.copied || info.deleted || info.updated);
1402
1494
    transactional_table= table->file->has_transactions();
 
1495
    if (thd->transaction.stmt.modified_non_trans_table)
 
1496
    {
 
1497
        if (mysql_bin_log.is_open())
 
1498
          thd->binlog_query(THD::ROW_QUERY_TYPE, thd->query, thd->query_length,
 
1499
                            transactional_table, false);
 
1500
        if (!thd->current_stmt_binlog_row_based && !can_rollback_data())
 
1501
          thd->transaction.all.modified_non_trans_table= true;
 
1502
    }
1403
1503
    assert(transactional_table || !changed ||
1404
 
                session->transaction.stmt.modified_non_trans_table);
 
1504
                thd->transaction.stmt.modified_non_trans_table);
1405
1505
    table->file->ha_release_auto_increment();
1406
1506
  }
1407
1507
 
1419
1519
 
1420
1520
  SYNOPSIS
1421
1521
    create_table_from_items()
1422
 
      session          in     Thread object
 
1522
      thd          in     Thread object
1423
1523
      create_info  in     Create information (like MAX_ROWS, ENGINE or
1424
1524
                          temporary table flag)
1425
1525
      create_table in     Pointer to TableList object providing database
1432
1532
      lock         out    Pointer to the DRIZZLE_LOCK object for table created
1433
1533
                          (or open temporary table) will be returned in this
1434
1534
                          parameter. Since this table is not included in
1435
 
                          Session::lock caller is responsible for explicitly
 
1535
                          THD::lock caller is responsible for explicitly
1436
1536
                          unlocking this table.
1437
1537
      hooks
1438
1538
 
1455
1555
    0         Error
1456
1556
*/
1457
1557
 
1458
 
static Table *create_table_from_items(Session *session, HA_CREATE_INFO *create_info,
 
1558
static Table *create_table_from_items(THD *thd, HA_CREATE_INFO *create_info,
1459
1559
                                      TableList *create_table,
1460
1560
                                      Alter_info *alter_info,
1461
1561
                                      List<Item> *items,
1462
 
                                      DRIZZLE_LOCK **lock)
 
1562
                                      DRIZZLE_LOCK **lock,
 
1563
                                      TABLEOP_HOOKS *hooks)
1463
1564
{
1464
1565
  Table tmp_table;              // Used during 'Create_field()'
1465
1566
  TABLE_SHARE share;
1478
1579
    if (create_info->options & HA_LEX_CREATE_IF_NOT_EXISTS)
1479
1580
    {
1480
1581
      create_info->table_existed= 1;            // Mark that table existed
1481
 
      push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
 
1582
      push_warning_printf(thd, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
1482
1583
                          ER_TABLE_EXISTS_ERROR, ER(ER_TABLE_EXISTS_ERROR),
1483
1584
                          create_table->table_name);
1484
1585
      return(create_table->table);
1491
1592
  tmp_table.alias= 0;
1492
1593
  tmp_table.timestamp_field= 0;
1493
1594
  tmp_table.s= &share;
1494
 
  init_tmp_table_share(session, &share, "", 0, "", "");
 
1595
  init_tmp_table_share(thd, &share, "", 0, "", "");
1495
1596
 
1496
1597
  tmp_table.s->db_create_options=0;
1497
1598
  tmp_table.s->blob_ptr_size= portable_sizeof_char_ptr;
1498
 
  tmp_table.s->db_low_byte_first=
 
1599
  tmp_table.s->db_low_byte_first= 
1499
1600
        test(create_info->db_type == myisam_hton ||
1500
1601
             create_info->db_type == heap_hton);
1501
1602
  tmp_table.null_row= false;
1511
1612
      else
1512
1613
        field= item->tmp_table_field_from_field_type(&tmp_table, 0);
1513
1614
    else
1514
 
      field= create_tmp_field(session, &tmp_table, item, item->type(),
 
1615
      field= create_tmp_field(thd, &tmp_table, item, item->type(),
1515
1616
                              (Item ***) 0, &tmp_field, &def_field, 0, 0, 0, 0,
1516
1617
                              0);
1517
1618
    if (!field ||
1541
1642
    open_table().
1542
1643
  */
1543
1644
  {
1544
 
    if (!mysql_create_table_no_lock(session, create_table->db,
 
1645
    tmp_disable_binlog(thd);
 
1646
    if (!mysql_create_table_no_lock(thd, create_table->db,
1545
1647
                                    create_table->table_name,
1546
1648
                                    create_info, alter_info, 0,
1547
 
                                    select_field_count, true))
 
1649
                                    select_field_count))
1548
1650
    {
1549
1651
      if (create_info->table_existed &&
1550
1652
          !(create_info->options & HA_LEX_CREATE_TMP_TABLE))
1561
1663
      if (!(create_info->options & HA_LEX_CREATE_TMP_TABLE))
1562
1664
      {
1563
1665
        pthread_mutex_lock(&LOCK_open);
1564
 
        if (reopen_name_locked_table(session, create_table, false))
 
1666
        if (reopen_name_locked_table(thd, create_table, false))
1565
1667
        {
1566
1668
          quick_rm_table(create_info->db_type, create_table->db,
1567
1669
                         table_case_name(create_info, create_table->table_name),
1573
1675
      }
1574
1676
      else
1575
1677
      {
1576
 
        if (!(table= open_table(session, create_table, (bool*) 0,
 
1678
        if (!(table= open_table(thd, create_table, (bool*) 0,
1577
1679
                                DRIZZLE_OPEN_TEMPORARY_ONLY)) &&
1578
1680
            !create_info->table_existed)
1579
1681
        {
1582
1684
            it preparable for open. But let us do close_temporary_table() here
1583
1685
            just in case.
1584
1686
          */
1585
 
          drop_temporary_table(session, create_table);
 
1687
          drop_temporary_table(thd, create_table);
1586
1688
        }
1587
1689
      }
1588
1690
    }
 
1691
    reenable_binlog(thd);
1589
1692
    if (!table)                                   // open failed
1590
1693
      return(0);
1591
1694
  }
1592
1695
 
1593
1696
  table->reginfo.lock_type=TL_WRITE;
1594
 
  if (! ((*lock)= mysql_lock_tables(session, &table, 1,
1595
 
                                    DRIZZLE_LOCK_IGNORE_FLUSH, &not_used)))
 
1697
  hooks->prelock(&table, 1);                    // Call prelock hooks
 
1698
  if (! ((*lock)= mysql_lock_tables(thd, &table, 1,
 
1699
                                    DRIZZLE_LOCK_IGNORE_FLUSH, &not_used)) ||
 
1700
        hooks->postlock(&table, 1))
1596
1701
  {
1597
1702
    if (*lock)
1598
1703
    {
1599
 
      mysql_unlock_tables(session, *lock);
 
1704
      mysql_unlock_tables(thd, *lock);
1600
1705
      *lock= 0;
1601
1706
    }
1602
1707
 
1603
1708
    if (!create_info->table_existed)
1604
 
      drop_open_table(session, table, create_table->db, create_table->table_name);
 
1709
      drop_open_table(thd, table, create_table->db, create_table->table_name);
1605
1710
    return(0);
1606
1711
  }
1607
1712
  return(table);
1609
1714
 
1610
1715
 
1611
1716
int
1612
 
select_create::prepare(List<Item> &values, Select_Lex_Unit *u)
 
1717
select_create::prepare(List<Item> &values, SELECT_LEX_UNIT *u)
1613
1718
{
1614
1719
  DRIZZLE_LOCK *extra_lock= NULL;
 
1720
  
 
1721
 
 
1722
  TABLEOP_HOOKS *hook_ptr= NULL;
1615
1723
  /*
1616
1724
    For row-based replication, the CREATE-SELECT statement is written
1617
1725
    in two pieces: the first one contain the CREATE TABLE statement
1630
1738
    slave.  Hence, we have to hold on to the CREATE part of the
1631
1739
    statement until the statement has finished.
1632
1740
   */
 
1741
  class MY_HOOKS : public TABLEOP_HOOKS {
 
1742
  public:
 
1743
    MY_HOOKS(select_create *x, TableList *create_table,
 
1744
             TableList *select_tables)
 
1745
      : ptr(x), all_tables(*create_table)
 
1746
      {
 
1747
        all_tables.next_global= select_tables;
 
1748
      }
 
1749
 
 
1750
  private:
 
1751
    virtual int do_postlock(Table **tables, uint32_t count)
 
1752
    {
 
1753
      THD *thd= const_cast<THD*>(ptr->get_thd());
 
1754
      if (int error= decide_logging_format(thd, &all_tables))
 
1755
        return error;
 
1756
 
 
1757
      Table const *const table = *tables;
 
1758
      if (thd->current_stmt_binlog_row_based  &&
 
1759
          !table->s->tmp_table &&
 
1760
          !ptr->get_create_info()->table_existed)
 
1761
      {
 
1762
        ptr->binlog_show_create_table(tables, count);
 
1763
      }
 
1764
      return 0;
 
1765
    }
 
1766
 
 
1767
    select_create *ptr;
 
1768
    TableList all_tables;
 
1769
  };
 
1770
 
 
1771
  MY_HOOKS hooks(this, create_table, select_tables);
 
1772
  hook_ptr= &hooks;
1633
1773
 
1634
1774
  unit= u;
1635
1775
 
1638
1778
    row-based replication for the statement.  If we are creating a
1639
1779
    temporary table, we need to start a statement transaction.
1640
1780
  */
 
1781
  if ((thd->lex->create_info.options & HA_LEX_CREATE_TMP_TABLE) == 0 &&
 
1782
      thd->current_stmt_binlog_row_based)
 
1783
  {
 
1784
    thd->binlog_start_trans_and_stmt();
 
1785
  }
1641
1786
 
1642
 
  if (!(table= create_table_from_items(session, create_info, create_table,
 
1787
  if (!(table= create_table_from_items(thd, create_info, create_table,
1643
1788
                                       alter_info, &values,
1644
 
                                       &extra_lock)))
 
1789
                                       &extra_lock, hook_ptr)))
1645
1790
    return(-1);                         // abort() deletes table
1646
1791
 
1647
1792
  if (extra_lock)
1651
1796
    if (create_info->options & HA_LEX_CREATE_TMP_TABLE)
1652
1797
      m_plock= &m_lock;
1653
1798
    else
1654
 
      m_plock= &session->extra_lock;
 
1799
      m_plock= &thd->extra_lock;
1655
1800
 
1656
1801
    *m_plock= extra_lock;
1657
1802
  }
1674
1819
  table->next_number_field=table->found_next_number_field;
1675
1820
 
1676
1821
  restore_record(table,s->default_values);      // Get empty record
1677
 
  session->cuted_fields=0;
 
1822
  thd->cuted_fields=0;
1678
1823
  if (info.ignore || info.handle_duplicates != DUP_ERROR)
1679
1824
    table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
1680
1825
  if (info.handle_duplicates == DUP_REPLACE)
1682
1827
  if (info.handle_duplicates == DUP_UPDATE)
1683
1828
    table->file->extra(HA_EXTRA_INSERT_WITH_UPDATE);
1684
1829
  table->file->ha_start_bulk_insert((ha_rows) 0);
1685
 
  session->abort_on_warning= !info.ignore;
1686
 
  if (check_that_all_fields_are_given_values(session, table, table_list))
 
1830
  thd->abort_on_warning= !info.ignore;
 
1831
  if (check_that_all_fields_are_given_values(thd, table, table_list))
1687
1832
    return(1);
1688
1833
  table->mark_columns_needed_for_insert();
1689
1834
  table->file->extra(HA_EXTRA_WRITE_CACHE);
1690
1835
  return(0);
1691
1836
}
1692
1837
 
 
1838
void
 
1839
select_create::binlog_show_create_table(Table **tables, uint32_t count)
 
1840
{
 
1841
  /*
 
1842
    Note 1: In RBR mode, we generate a CREATE TABLE statement for the
 
1843
    created table by calling store_create_info() (behaves as SHOW
 
1844
    CREATE TABLE).  In the event of an error, nothing should be
 
1845
    written to the binary log, even if the table is non-transactional;
 
1846
    therefore we pretend that the generated CREATE TABLE statement is
 
1847
    for a transactional table.  The event will then be put in the
 
1848
    transaction cache, and any subsequent events (e.g., table-map
 
1849
    events and binrow events) will also be put there.  We can then use
 
1850
    ha_autocommit_or_rollback() to either throw away the entire
 
1851
    kaboodle of events, or write them to the binary log.
 
1852
 
 
1853
    We write the CREATE TABLE statement here and not in prepare()
 
1854
    since there potentially are sub-selects or accesses to information
 
1855
    schema that will do a close_thread_tables(), destroying the
 
1856
    statement transaction cache.
 
1857
  */
 
1858
  assert(thd->current_stmt_binlog_row_based);
 
1859
  assert(tables && *tables && count > 0);
 
1860
 
 
1861
  char buf[2048];
 
1862
  String query(buf, sizeof(buf), system_charset_info);
 
1863
  int result;
 
1864
  TableList tmp_table_list;
 
1865
 
 
1866
  memset(&tmp_table_list, 0, sizeof(tmp_table_list));
 
1867
  tmp_table_list.table = *tables;
 
1868
  query.length(0);      // Have to zero it since constructor doesn't
 
1869
 
 
1870
  result= store_create_info(thd, &tmp_table_list, &query, create_info);
 
1871
  assert(result == 0); /* store_create_info() always return 0 */
 
1872
 
 
1873
  thd->binlog_query(THD::STMT_QUERY_TYPE,
 
1874
                    query.ptr(), query.length(),
 
1875
                    /* is_trans */ true,
 
1876
                    /* suppress_use */ false);
 
1877
}
 
1878
 
1693
1879
void select_create::store_values(List<Item> &values)
1694
1880
{
1695
 
  fill_record(session, field, values, 1);
 
1881
  fill_record(thd, field, values, 1);
1696
1882
}
1697
1883
 
1698
1884
 
1699
1885
void select_create::send_error(uint32_t errcode,const char *err)
1700
1886
{
1701
 
 
 
1887
  
1702
1888
 
1703
1889
  /*
1704
1890
    This will execute any rollbacks that are necessary before writing
1711
1897
    written to the binary log.
1712
1898
 
1713
1899
  */
 
1900
  tmp_disable_binlog(thd);
1714
1901
  select_insert::send_error(errcode, err);
 
1902
  reenable_binlog(thd);
1715
1903
 
1716
1904
  return;
1717
1905
}
1731
1919
    */
1732
1920
    if (!table->s->tmp_table)
1733
1921
    {
1734
 
      ha_autocommit_or_rollback(session, 0);
1735
 
      (void) session->endActiveTransaction();
 
1922
      ha_autocommit_or_rollback(thd, 0);
 
1923
      end_active_trans(thd);
1736
1924
    }
1737
1925
 
1738
1926
    table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
1739
1927
    table->file->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
1740
1928
    if (m_plock)
1741
1929
    {
1742
 
      mysql_unlock_tables(session, *m_plock);
 
1930
      mysql_unlock_tables(thd, *m_plock);
1743
1931
      *m_plock= NULL;
1744
1932
      m_plock= NULL;
1745
1933
    }
1750
1938
 
1751
1939
void select_create::abort()
1752
1940
{
1753
 
 
 
1941
  
1754
1942
 
1755
1943
  /*
1756
1944
    In select_insert::abort() we roll back the statement, including
1767
1955
    of the table succeeded or not, since we need to reset the binary
1768
1956
    log state.
1769
1957
  */
 
1958
  tmp_disable_binlog(thd);
1770
1959
  select_insert::abort();
1771
 
  session->transaction.stmt.modified_non_trans_table= false;
 
1960
  thd->transaction.stmt.modified_non_trans_table= false;
 
1961
  reenable_binlog(thd);
1772
1962
 
1773
1963
 
1774
1964
  if (m_plock)
1775
1965
  {
1776
 
    mysql_unlock_tables(session, *m_plock);
 
1966
    mysql_unlock_tables(thd, *m_plock);
1777
1967
    *m_plock= NULL;
1778
1968
    m_plock= NULL;
1779
1969
  }
1783
1973
    table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
1784
1974
    table->file->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
1785
1975
    if (!create_info->table_existed)
1786
 
      drop_open_table(session, table, create_table->db, create_table->table_name);
 
1976
      drop_open_table(thd, table, create_table->db, create_table->table_name);
1787
1977
    table=0;                                    // Safety
1788
1978
  }
1789
1979
  return;