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