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