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