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