~drizzle-trunk/drizzle/development

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