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