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