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