~drizzle-trunk/drizzle/development

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