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