~drizzle-trunk/drizzle/development

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