~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
      }
1014
      {
520.1.22 by Brian Aker
Second pass of thd cleanup
1015
        push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_WARN,
1 by brian
clean slate
1016
                            ER_NO_DEFAULT_FOR_FIELD,
1017
                            ER(ER_NO_DEFAULT_FOR_FIELD),
1018
                            (*field)->field_name);
1019
      }
1020
      err= 1;
1021
    }
1022
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
1023
  return session->abort_on_warning ? err : 0;
1 by brian
clean slate
1024
}
1025
1026
/***************************************************************************
1027
  Store records in INSERT ... SELECT *
1028
***************************************************************************/
1029
1030
1031
/*
1032
  make insert specific preparation and checks after opening tables
1033
1034
  SYNOPSIS
1035
    mysql_insert_select_prepare()
520.1.22 by Brian Aker
Second pass of thd cleanup
1036
    session         thread handler
1 by brian
clean slate
1037
1038
  RETURN
163 by Brian Aker
Merge Monty's code.
1039
    false OK
1040
    true  Error
1 by brian
clean slate
1041
*/
1042
520.1.22 by Brian Aker
Second pass of thd cleanup
1043
bool mysql_insert_select_prepare(Session *session)
1 by brian
clean slate
1044
{
520.1.22 by Brian Aker
Second pass of thd cleanup
1045
  LEX *lex= session->lex;
1 by brian
clean slate
1046
  SELECT_LEX *select_lex= &lex->select_lex;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1047
1 by brian
clean slate
1048
  /*
1049
    SELECT_LEX do not belong to INSERT statement, so we can't add WHERE
1050
    clause if table is VIEW
1051
  */
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1052
520.1.22 by Brian Aker
Second pass of thd cleanup
1053
  if (mysql_prepare_insert(session, lex->query_tables,
1 by brian
clean slate
1054
                           lex->query_tables->table, lex->field_list, 0,
1055
                           lex->update_list, lex->value_list,
1056
                           lex->duplicates,
163 by Brian Aker
Merge Monty's code.
1057
                           &select_lex->where, true, false, false))
1058
    return(true);
1 by brian
clean slate
1059
1060
  /*
1061
    exclude first table from leaf tables list, because it belong to
1062
    INSERT
1063
  */
51.2.2 by Patrick Galbraith
Removed DBUGs from
1064
  assert(select_lex->leaf_tables != 0);
1 by brian
clean slate
1065
  lex->leaf_tables_insert= select_lex->leaf_tables;
1066
  /* skip all leaf tables belonged to view where we are insert */
327.1.7 by Brian Aker
Removed belong_to_view variable
1067
  select_lex->leaf_tables= select_lex->leaf_tables->next_leaf;
163 by Brian Aker
Merge Monty's code.
1068
  return(false);
1 by brian
clean slate
1069
}
1070
1071
327.2.4 by Brian Aker
Refactoring table.h
1072
select_insert::select_insert(TableList *table_list_par, Table *table_par,
1 by brian
clean slate
1073
                             List<Item> *fields_par,
1074
                             List<Item> *update_fields,
1075
                             List<Item> *update_values,
1076
                             enum_duplicates duplic,
1077
                             bool ignore_check_option_errors)
1078
  :table_list(table_list_par), table(table_par), fields(fields_par),
1079
   autoinc_value_of_last_inserted_row(0),
1080
   insert_into_view(table_list_par && 0 != 0)
1081
{
212.6.6 by Mats Kindahl
Removing redundant use of casts in drizzled/ for memcmp(), memcpy(), memset(), and memmove().
1082
  memset(&info, 0, sizeof(info));
1 by brian
clean slate
1083
  info.handle_duplicates= duplic;
1084
  info.ignore= ignore_check_option_errors;
1085
  info.update_fields= update_fields;
1086
  info.update_values= update_values;
1087
}
1088
1089
1090
int
1091
select_insert::prepare(List<Item> &values, SELECT_LEX_UNIT *u)
1092
{
520.1.22 by Brian Aker
Second pass of thd cleanup
1093
  LEX *lex= session->lex;
1 by brian
clean slate
1094
  int res;
1095
  table_map map= 0;
1096
  SELECT_LEX *lex_current_select_save= lex->current_select;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1097
1 by brian
clean slate
1098
1099
  unit= u;
1100
1101
  /*
1102
    Since table in which we are going to insert is added to the first
1103
    select, LEX::current_select should point to the first select while
1104
    we are fixing fields from insert list.
1105
  */
1106
  lex->current_select= &lex->select_lex;
520.1.22 by Brian Aker
Second pass of thd cleanup
1107
  res= check_insert_fields(session, table_list, *fields, values,
1 by brian
clean slate
1108
                           !insert_into_view, &map) ||
520.1.22 by Brian Aker
Second pass of thd cleanup
1109
       setup_fields(session, 0, values, MARK_COLUMNS_READ, 0, 0);
1 by brian
clean slate
1110
1111
  if (!res && fields->elements)
1112
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
1113
    bool saved_abort_on_warning= session->abort_on_warning;
1114
    session->abort_on_warning= !info.ignore;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1115
    res= check_that_all_fields_are_given_values(session, table_list->table,
1 by brian
clean slate
1116
                                                table_list);
520.1.22 by Brian Aker
Second pass of thd cleanup
1117
    session->abort_on_warning= saved_abort_on_warning;
1 by brian
clean slate
1118
  }
1119
1120
  if (info.handle_duplicates == DUP_UPDATE && !res)
1121
  {
1122
    Name_resolution_context *context= &lex->select_lex.context;
1123
    Name_resolution_context_state ctx_state;
1124
1125
    /* Save the state of the current name resolution context. */
1126
    ctx_state.save_state(context, table_list);
1127
1128
    /* Perform name resolution only in the first table - 'table_list'. */
1129
    table_list->next_local= 0;
1130
    context->resolve_in_table_list_only(table_list);
1131
520.1.22 by Brian Aker
Second pass of thd cleanup
1132
    res= res || check_update_fields(session, context->table_list,
1 by brian
clean slate
1133
                                    *info.update_fields, &map);
1134
    /*
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1135
      When we are not using GROUP BY and there are no ungrouped aggregate functions
1 by brian
clean slate
1136
      we can refer to other tables in the ON DUPLICATE KEY part.
1137
      We use next_name_resolution_table descructively, so check it first (views?)
1138
    */
51.2.2 by Patrick Galbraith
Removed DBUGs from
1139
    assert (!table_list->next_name_resolution_table);
1 by brian
clean slate
1140
    if (lex->select_lex.group_list.elements == 0 &&
1141
        !lex->select_lex.with_sum_func)
1142
      /*
1143
        We must make a single context out of the two separate name resolution contexts :
1144
        the INSERT table and the tables in the SELECT part of INSERT ... SELECT.
1145
        To do that we must concatenate the two lists
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1146
      */
1147
      table_list->next_name_resolution_table=
1 by brian
clean slate
1148
        ctx_state.get_first_name_resolution_table();
1149
520.1.22 by Brian Aker
Second pass of thd cleanup
1150
    res= res || setup_fields(session, 0, *info.update_values,
1 by brian
clean slate
1151
                             MARK_COLUMNS_READ, 0, 0);
1152
    if (!res)
1153
    {
1154
      /*
1155
        Traverse the update values list and substitute fields from the
1156
        select for references (Item_ref objects) to them. This is done in
1157
        order to get correct values from those fields when the select
1158
        employs a temporary table.
1159
      */
1160
      List_iterator<Item> li(*info.update_values);
1161
      Item *item;
1162
1163
      while ((item= li++))
1164
      {
1165
        item->transform(&Item::update_value_transformer,
481 by Brian Aker
Remove all of uchar.
1166
                        (unsigned char*)lex->current_select);
1 by brian
clean slate
1167
      }
1168
    }
1169
1170
    /* Restore the current context. */
1171
    ctx_state.restore_state(context, table_list);
1172
  }
1173
1174
  lex->current_select= lex_current_select_save;
1175
  if (res)
51.2.2 by Patrick Galbraith
Removed DBUGs from
1176
    return(1);
1 by brian
clean slate
1177
  /*
1178
    if it is INSERT into join view then check_insert_fields already found
1179
    real table for insert
1180
  */
1181
  table= table_list->table;
1182
1183
  /*
1184
    Is table which we are changing used somewhere in other parts of
1185
    query
1186
  */
520.1.22 by Brian Aker
Second pass of thd cleanup
1187
  if (unique_table(session, table_list, table_list->next_global, 0))
1 by brian
clean slate
1188
  {
1189
    /* Using same table for INSERT and SELECT */
1190
    lex->current_select->options|= OPTION_BUFFER_RESULT;
1191
    lex->current_select->join->select_options|= OPTION_BUFFER_RESULT;
1192
  }
1193
  else if (!(lex->current_select->options & OPTION_BUFFER_RESULT))
1194
  {
1195
    /*
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1196
      We must not yet prepare the result table if it is the same as one of the
1197
      source tables (INSERT SELECT). The preparation may disable
1 by brian
clean slate
1198
      indexes on the result table, which may be used during the select, if it
1199
      is the same table (Bug #6034). Do the preparation after the select phase
1200
      in select_insert::prepare2().
1201
      We won't start bulk inserts at all if this statement uses functions or
1202
      should invoke triggers since they may access to the same table too.
1203
    */
1204
    table->file->ha_start_bulk_insert((ha_rows) 0);
1205
  }
1206
  restore_record(table,s->default_values);		// Get empty record
1207
  table->next_number_field=table->found_next_number_field;
1208
520.1.22 by Brian Aker
Second pass of thd cleanup
1209
  if (session->slave_thread &&
1 by brian
clean slate
1210
      (info.handle_duplicates == DUP_UPDATE) &&
1211
      (table->next_number_field != NULL) &&
1212
      rpl_master_has_bug(&active_mi->rli, 24432))
51.2.2 by Patrick Galbraith
Removed DBUGs from
1213
    return(1);
1 by brian
clean slate
1214
520.1.22 by Brian Aker
Second pass of thd cleanup
1215
  session->cuted_fields=0;
1 by brian
clean slate
1216
  if (info.ignore || info.handle_duplicates != DUP_ERROR)
1217
    table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
1218
  if (info.handle_duplicates == DUP_REPLACE)
1219
    table->file->extra(HA_EXTRA_WRITE_CAN_REPLACE);
1220
  if (info.handle_duplicates == DUP_UPDATE)
1221
    table->file->extra(HA_EXTRA_INSERT_WITH_UPDATE);
520.1.22 by Brian Aker
Second pass of thd cleanup
1222
  session->abort_on_warning= !info.ignore;
1 by brian
clean slate
1223
  table->mark_columns_needed_for_insert();
1224
1225
51.2.2 by Patrick Galbraith
Removed DBUGs from
1226
  return(res);
1 by brian
clean slate
1227
}
1228
1229
1230
/*
1231
  Finish the preparation of the result table.
1232
1233
  SYNOPSIS
1234
    select_insert::prepare2()
1235
    void
1236
1237
  DESCRIPTION
1238
    If the result table is the same as one of the source tables (INSERT SELECT),
1239
    the result table is not finally prepared at the join prepair phase.
1240
    Do the final preparation now.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1241
1 by brian
clean slate
1242
  RETURN
1243
    0   OK
1244
*/
1245
1246
int select_insert::prepare2(void)
1247
{
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1248
520.1.22 by Brian Aker
Second pass of thd cleanup
1249
  if (session->lex->current_select->options & OPTION_BUFFER_RESULT)
1 by brian
clean slate
1250
    table->file->ha_start_bulk_insert((ha_rows) 0);
51.2.2 by Patrick Galbraith
Removed DBUGs from
1251
  return(0);
1 by brian
clean slate
1252
}
1253
1254
1255
void select_insert::cleanup()
1256
{
1257
  /* select_insert/select_create are never re-used in prepared statement */
51.2.2 by Patrick Galbraith
Removed DBUGs from
1258
  assert(0);
1 by brian
clean slate
1259
}
1260
1261
select_insert::~select_insert()
1262
{
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1263
1 by brian
clean slate
1264
  if (table)
1265
  {
1266
    table->next_number_field=0;
163 by Brian Aker
Merge Monty's code.
1267
    table->auto_increment_field_not_null= false;
1 by brian
clean slate
1268
    table->file->ha_reset();
1269
  }
520.1.22 by Brian Aker
Second pass of thd cleanup
1270
  session->count_cuted_fields= CHECK_FIELD_IGNORE;
1271
  session->abort_on_warning= 0;
51.2.2 by Patrick Galbraith
Removed DBUGs from
1272
  return;
1 by brian
clean slate
1273
}
1274
1275
1276
bool select_insert::send_data(List<Item> &values)
1277
{
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1278
1 by brian
clean slate
1279
  bool error=0;
1280
1281
  if (unit->offset_limit_cnt)
1282
  {						// using limit offset,count
1283
    unit->offset_limit_cnt--;
51.2.2 by Patrick Galbraith
Removed DBUGs from
1284
    return(0);
1 by brian
clean slate
1285
  }
1286
520.1.22 by Brian Aker
Second pass of thd cleanup
1287
  session->count_cuted_fields= CHECK_FIELD_WARN;	// Calculate cuted fields
1 by brian
clean slate
1288
  store_values(values);
520.1.22 by Brian Aker
Second pass of thd cleanup
1289
  session->count_cuted_fields= CHECK_FIELD_IGNORE;
1290
  if (session->is_error())
51.2.2 by Patrick Galbraith
Removed DBUGs from
1291
    return(1);
1 by brian
clean slate
1292
520.1.22 by Brian Aker
Second pass of thd cleanup
1293
  error= write_record(session, table, &info);
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1294
1 by brian
clean slate
1295
  if (!error)
1296
  {
1297
    if (info.handle_duplicates == DUP_UPDATE)
1298
    {
1299
      /*
1300
        Restore fields of the record since it is possible that they were
1301
        changed by ON DUPLICATE KEY UPDATE clause.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1302
1 by brian
clean slate
1303
        If triggers exist then whey can modify some fields which were not
1304
        originally touched by INSERT ... SELECT, so we have to restore
1305
        their original values for the next row.
1306
      */
1307
      restore_record(table, s->default_values);
1308
    }
1309
    if (table->next_number_field)
1310
    {
1311
      /*
1312
        If no value has been autogenerated so far, we need to remember the
1313
        value we just saw, we may need to send it to client in the end.
1314
      */
520.1.22 by Brian Aker
Second pass of thd cleanup
1315
      if (session->first_successful_insert_id_in_cur_stmt == 0) // optimization
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1316
        autoinc_value_of_last_inserted_row=
1 by brian
clean slate
1317
          table->next_number_field->val_int();
1318
      /*
1319
        Clear auto-increment field for the next record, if triggers are used
1320
        we will clear it twice, but this should be cheap.
1321
      */
1322
      table->next_number_field->reset();
1323
    }
1324
  }
51.2.2 by Patrick Galbraith
Removed DBUGs from
1325
  return(error);
1 by brian
clean slate
1326
}
1327
1328
1329
void select_insert::store_values(List<Item> &values)
1330
{
1331
  if (fields->elements)
520.1.22 by Brian Aker
Second pass of thd cleanup
1332
    fill_record(session, *fields, values, 1);
1 by brian
clean slate
1333
  else
520.1.22 by Brian Aker
Second pass of thd cleanup
1334
    fill_record(session, table->field, values, 1);
1 by brian
clean slate
1335
}
1336
482 by Brian Aker
Remove uint.
1337
void select_insert::send_error(uint32_t errcode,const char *err)
1 by brian
clean slate
1338
{
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1339
1 by brian
clean slate
1340
1341
  my_message(errcode, err, MYF(0));
1342
51.2.2 by Patrick Galbraith
Removed DBUGs from
1343
  return;
1 by brian
clean slate
1344
}
1345
1346
1347
bool select_insert::send_eof()
1348
{
1349
  int error;
1350
  bool const trans_table= table->file->has_transactions();
151 by Brian Aker
Ulonglong to uint64_t
1351
  uint64_t id;
1 by brian
clean slate
1352
  bool changed;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1353
1 by brian
clean slate
1354
  error= table->file->ha_end_bulk_insert();
1355
  table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
1356
  table->file->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
1357
1358
  if ((changed= (info.copied || info.deleted || info.updated)))
1359
  {
1360
    /*
1361
      We must invalidate the table in the query cache before binlog writing
1362
      and ha_autocommit_or_rollback.
1363
    */
520.1.22 by Brian Aker
Second pass of thd cleanup
1364
    if (session->transaction.stmt.modified_non_trans_table)
1365
      session->transaction.all.modified_non_trans_table= true;
1 by brian
clean slate
1366
  }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1367
  assert(trans_table || !changed ||
520.1.22 by Brian Aker
Second pass of thd cleanup
1368
              session->transaction.stmt.modified_non_trans_table);
1 by brian
clean slate
1369
1370
  table->file->ha_release_auto_increment();
1371
1372
  if (error)
1373
  {
1374
    table->file->print_error(error,MYF(0));
51.2.2 by Patrick Galbraith
Removed DBUGs from
1375
    return(1);
1 by brian
clean slate
1376
  }
1377
  char buff[160];
1378
  if (info.ignore)
1379
    sprintf(buff, ER(ER_INSERT_INFO), (ulong) info.records,
520.1.22 by Brian Aker
Second pass of thd cleanup
1380
	    (ulong) (info.records - info.copied), (ulong) session->cuted_fields);
1 by brian
clean slate
1381
  else
1382
    sprintf(buff, ER(ER_INSERT_INFO), (ulong) info.records,
520.1.22 by Brian Aker
Second pass of thd cleanup
1383
	    (ulong) (info.deleted+info.updated), (ulong) session->cuted_fields);
1384
  session->row_count_func= info.copied + info.deleted +
1385
                       ((session->client_capabilities & CLIENT_FOUND_ROWS) ?
1 by brian
clean slate
1386
                        info.touched : info.updated);
1387
520.1.22 by Brian Aker
Second pass of thd cleanup
1388
  id= (session->first_successful_insert_id_in_cur_stmt > 0) ?
1389
    session->first_successful_insert_id_in_cur_stmt :
1390
    (session->arg_of_last_insert_id_function ?
1391
     session->first_successful_insert_id_in_prev_stmt :
1 by brian
clean slate
1392
     (info.copied ? autoinc_value_of_last_inserted_row : 0));
520.1.22 by Brian Aker
Second pass of thd cleanup
1393
  ::my_ok(session, (ulong) session->row_count_func, id, buff);
51.2.2 by Patrick Galbraith
Removed DBUGs from
1394
  return(0);
1 by brian
clean slate
1395
}
1396
1397
void select_insert::abort() {
1398
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1399
1 by brian
clean slate
1400
  /*
1401
    If the creation of the table failed (due to a syntax error, for
1402
    example), no table will have been opened and therefore 'table'
1403
    will be NULL. In that case, we still need to execute the rollback
1404
    and the end of the function.
1405
   */
1406
  if (table)
1407
  {
1408
    bool changed, transactional_table;
1409
1410
    table->file->ha_end_bulk_insert();
1411
1412
    /*
1413
      If at least one row has been inserted/modified and will stay in
1414
      the table (the table doesn't have transactions) we must write to
1415
      the binlog (and the error code will make the slave stop).
1416
1417
      For many errors (example: we got a duplicate key error while
1418
      inserting into a MyISAM table), no row will be added to the table,
1419
      so passing the error to the slave will not help since there will
1420
      be an error code mismatch (the inserts will succeed on the slave
1421
      with no error).
1422
1423
      If table creation failed, the number of rows modified will also be
1424
      zero, so no check for that is made.
1425
    */
1426
    changed= (info.copied || info.deleted || info.updated);
1427
    transactional_table= table->file->has_transactions();
51.2.2 by Patrick Galbraith
Removed DBUGs from
1428
    assert(transactional_table || !changed ||
520.1.22 by Brian Aker
Second pass of thd cleanup
1429
		session->transaction.stmt.modified_non_trans_table);
1 by brian
clean slate
1430
    table->file->ha_release_auto_increment();
1431
  }
1432
51.2.2 by Patrick Galbraith
Removed DBUGs from
1433
  return;
1 by brian
clean slate
1434
}
1435
1436
1437
/***************************************************************************
1438
  CREATE TABLE (SELECT) ...
1439
***************************************************************************/
1440
1441
/*
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1442
  Create table from lists of fields and items (or just return Table
1 by brian
clean slate
1443
  object for pre-opened existing table).
1444
1445
  SYNOPSIS
1446
    create_table_from_items()
520.1.22 by Brian Aker
Second pass of thd cleanup
1447
      session          in     Thread object
1 by brian
clean slate
1448
      create_info  in     Create information (like MAX_ROWS, ENGINE or
1449
                          temporary table flag)
327.2.4 by Brian Aker
Refactoring table.h
1450
      create_table in     Pointer to TableList object providing database
1 by brian
clean slate
1451
                          and name for table to be created or to be open
1452
      alter_info   in/out Initial list of columns and indexes for the table
1453
                          to be created
1454
      items        in     List of items which should be used to produce rest
1455
                          of fields for the table (corresponding fields will
1456
                          be added to the end of alter_info->create_list)
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
1457
      lock         out    Pointer to the DRIZZLE_LOCK object for table created
1 by brian
clean slate
1458
                          (or open temporary table) will be returned in this
1459
                          parameter. Since this table is not included in
520.1.21 by Brian Aker
THD -> Session rename
1460
                          Session::lock caller is responsible for explicitly
1 by brian
clean slate
1461
                          unlocking this table.
1462
      hooks
1463
1464
  NOTES
1465
    This function behaves differently for base and temporary tables:
1466
    - For base table we assume that either table exists and was pre-opened
1467
      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
1468
      emit error or warning and return pre-opened Table object) or special
1 by brian
clean slate
1469
      placeholder was put in table cache that guarantees that this table
1470
      won't be created or opened until the placeholder will be removed
1471
      (so there is an exclusive lock on this table).
1472
    - We don't pre-open existing temporary table, instead we either open
1473
      or create and then open table in this function.
1474
1475
    Since this function contains some logic specific to CREATE TABLE ...
1476
    SELECT it should be changed before it can be used in other contexts.
1477
1478
  RETURN VALUES
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1479
    non-zero  Pointer to Table object for table created or opened
1 by brian
clean slate
1480
    0         Error
1481
*/
1482
520.1.22 by Brian Aker
Second pass of thd cleanup
1483
static Table *create_table_from_items(Session *session, HA_CREATE_INFO *create_info,
327.2.4 by Brian Aker
Refactoring table.h
1484
                                      TableList *create_table,
1 by brian
clean slate
1485
                                      Alter_info *alter_info,
1486
                                      List<Item> *items,
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
1487
                                      DRIZZLE_LOCK **lock,
575.1.3 by Monty Taylor
Moved some stuff out of handler.h.
1488
                                      Tableop_hooks *hooks)
1 by brian
clean slate
1489
{
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1490
  Table tmp_table;		// Used during 'Create_field()'
1 by brian
clean slate
1491
  TABLE_SHARE share;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1492
  Table *table= 0;
482 by Brian Aker
Remove uint.
1493
  uint32_t select_field_count= items->elements;
1 by brian
clean slate
1494
  /* Add selected items to field list */
1495
  List_iterator_fast<Item> it(*items);
1496
  Item *item;
1497
  Field *tmp_field;
1498
  bool not_used;
1499
1500
  if (!(create_info->options & HA_LEX_CREATE_TMP_TABLE) &&
1501
      create_table->table->db_stat)
1502
  {
1503
    /* Table already exists and was open at open_and_lock_tables() stage. */
1504
    if (create_info->options & HA_LEX_CREATE_IF_NOT_EXISTS)
1505
    {
1506
      create_info->table_existed= 1;		// Mark that table existed
520.1.22 by Brian Aker
Second pass of thd cleanup
1507
      push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
1 by brian
clean slate
1508
                          ER_TABLE_EXISTS_ERROR, ER(ER_TABLE_EXISTS_ERROR),
1509
                          create_table->table_name);
51.2.2 by Patrick Galbraith
Removed DBUGs from
1510
      return(create_table->table);
1 by brian
clean slate
1511
    }
1512
1513
    my_error(ER_TABLE_EXISTS_ERROR, MYF(0), create_table->table_name);
51.2.2 by Patrick Galbraith
Removed DBUGs from
1514
    return(0);
1 by brian
clean slate
1515
  }
1516
1517
  tmp_table.alias= 0;
1518
  tmp_table.timestamp_field= 0;
1519
  tmp_table.s= &share;
520.1.22 by Brian Aker
Second pass of thd cleanup
1520
  init_tmp_table_share(session, &share, "", 0, "", "");
1 by brian
clean slate
1521
1522
  tmp_table.s->db_create_options=0;
1523
  tmp_table.s->blob_ptr_size= portable_sizeof_char_ptr;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1524
  tmp_table.s->db_low_byte_first=
1 by brian
clean slate
1525
        test(create_info->db_type == myisam_hton ||
1526
             create_info->db_type == heap_hton);
274 by Brian Aker
my_bool conversion in Table
1527
  tmp_table.null_row= false;
1528
  tmp_table.maybe_null= false;
1 by brian
clean slate
1529
1530
  while ((item=it++))
1531
  {
1532
    Create_field *cr_field;
1533
    Field *field, *def_field;
1534
    if (item->type() == Item::FUNC_ITEM)
1535
      if (item->result_type() != STRING_RESULT)
1536
        field= item->tmp_table_field(&tmp_table);
1537
      else
1538
        field= item->tmp_table_field_from_field_type(&tmp_table, 0);
1539
    else
520.1.22 by Brian Aker
Second pass of thd cleanup
1540
      field= create_tmp_field(session, &tmp_table, item, item->type(),
1 by brian
clean slate
1541
                              (Item ***) 0, &tmp_field, &def_field, 0, 0, 0, 0,
1542
                              0);
1543
    if (!field ||
1544
	!(cr_field=new Create_field(field,(item->type() == Item::FIELD_ITEM ?
1545
					   ((Item_field *)item)->field :
1546
					   (Field*) 0))))
51.2.2 by Patrick Galbraith
Removed DBUGs from
1547
      return(0);
1 by brian
clean slate
1548
    if (item->maybe_null)
1549
      cr_field->flags &= ~NOT_NULL_FLAG;
1550
    alter_info->create_list.push_back(cr_field);
1551
  }
1552
1553
  /*
1554
    Create and lock table.
1555
1556
    Note that we either creating (or opening existing) temporary table or
1557
    creating base table on which name we have exclusive lock. So code below
1558
    should not cause deadlocks or races.
1559
1560
    We don't log the statement, it will be logged later.
1561
1562
    If this is a HEAP table, the automatic DELETE FROM which is written to the
1563
    binlog when a HEAP table is opened for the first time since startup, must
1564
    not be written: 1) it would be wrong (imagine we're in CREATE SELECT: we
1565
    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
1566
    Table, which is a wrong order. So we keep binary logging disabled when we
1 by brian
clean slate
1567
    open_table().
1568
  */
1569
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
1570
    tmp_disable_binlog(session);
1571
    if (!mysql_create_table_no_lock(session, create_table->db,
1 by brian
clean slate
1572
                                    create_table->table_name,
1573
                                    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
1574
                                    select_field_count, true))
1 by brian
clean slate
1575
    {
1576
      if (create_info->table_existed &&
1577
          !(create_info->options & HA_LEX_CREATE_TMP_TABLE))
1578
      {
1579
        /*
1580
          This means that someone created table underneath server
1581
          or it was created via different mysqld front-end to the
1582
          cluster. We don't have much options but throw an error.
1583
        */
1584
        my_error(ER_TABLE_EXISTS_ERROR, MYF(0), create_table->table_name);
51.2.2 by Patrick Galbraith
Removed DBUGs from
1585
        return(0);
1 by brian
clean slate
1586
      }
1587
1588
      if (!(create_info->options & HA_LEX_CREATE_TMP_TABLE))
1589
      {
398.1.10 by Monty Taylor
Actually removed VOID() this time.
1590
        pthread_mutex_lock(&LOCK_open);
520.1.22 by Brian Aker
Second pass of thd cleanup
1591
        if (reopen_name_locked_table(session, create_table, false))
1 by brian
clean slate
1592
        {
1593
          quick_rm_table(create_info->db_type, create_table->db,
1594
                         table_case_name(create_info, create_table->table_name),
1595
                         0);
1596
        }
1597
        else
1598
          table= create_table->table;
398.1.10 by Monty Taylor
Actually removed VOID() this time.
1599
        pthread_mutex_unlock(&LOCK_open);
1 by brian
clean slate
1600
      }
1601
      else
1602
      {
520.1.22 by Brian Aker
Second pass of thd cleanup
1603
        if (!(table= open_table(session, create_table, (bool*) 0,
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
1604
                                DRIZZLE_OPEN_TEMPORARY_ONLY)) &&
1 by brian
clean slate
1605
            !create_info->table_existed)
1606
        {
1607
          /*
1608
            This shouldn't happen as creation of temporary table should make
1609
            it preparable for open. But let us do close_temporary_table() here
1610
            just in case.
1611
          */
520.1.22 by Brian Aker
Second pass of thd cleanup
1612
          drop_temporary_table(session, create_table);
1 by brian
clean slate
1613
        }
1614
      }
1615
    }
520.1.22 by Brian Aker
Second pass of thd cleanup
1616
    reenable_binlog(session);
1 by brian
clean slate
1617
    if (!table)                                   // open failed
51.2.2 by Patrick Galbraith
Removed DBUGs from
1618
      return(0);
1 by brian
clean slate
1619
  }
1620
1621
  table->reginfo.lock_type=TL_WRITE;
1622
  hooks->prelock(&table, 1);                    // Call prelock hooks
520.1.22 by Brian Aker
Second pass of thd cleanup
1623
  if (! ((*lock)= mysql_lock_tables(session, &table, 1,
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
1624
                                    DRIZZLE_LOCK_IGNORE_FLUSH, &not_used)) ||
1 by brian
clean slate
1625
        hooks->postlock(&table, 1))
1626
  {
1627
    if (*lock)
1628
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
1629
      mysql_unlock_tables(session, *lock);
1 by brian
clean slate
1630
      *lock= 0;
1631
    }
1632
1633
    if (!create_info->table_existed)
520.1.22 by Brian Aker
Second pass of thd cleanup
1634
      drop_open_table(session, table, create_table->db, create_table->table_name);
51.2.2 by Patrick Galbraith
Removed DBUGs from
1635
    return(0);
1 by brian
clean slate
1636
  }
51.2.2 by Patrick Galbraith
Removed DBUGs from
1637
  return(table);
1 by brian
clean slate
1638
}
1639
1640
1641
int
1642
select_create::prepare(List<Item> &values, SELECT_LEX_UNIT *u)
1643
{
319.1.1 by Grant Limberg
renamed all instances of MYSQL_ to DRIZZLE_
1644
  DRIZZLE_LOCK *extra_lock= NULL;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1645
1 by brian
clean slate
1646
575.1.3 by Monty Taylor
Moved some stuff out of handler.h.
1647
  Tableop_hooks *hook_ptr= NULL;
1 by brian
clean slate
1648
  /*
1649
    For row-based replication, the CREATE-SELECT statement is written
1650
    in two pieces: the first one contain the CREATE TABLE statement
1651
    necessary to create the table and the second part contain the rows
1652
    that should go into the table.
1653
1654
    For non-temporary tables, the start of the CREATE-SELECT
1655
    implicitly commits the previous transaction, and all events
1656
    forming the statement will be stored the transaction cache. At end
1657
    of the statement, the entire statement is committed as a
1658
    transaction, and all events are written to the binary log.
1659
1660
    On the master, the table is locked for the duration of the
1661
    statement, but since the CREATE part is replicated as a simple
1662
    statement, there is no way to lock the table for accesses on the
1663
    slave.  Hence, we have to hold on to the CREATE part of the
1664
    statement until the statement has finished.
1665
   */
575.1.3 by Monty Taylor
Moved some stuff out of handler.h.
1666
  class MY_HOOKS : public Tableop_hooks {
1 by brian
clean slate
1667
  public:
327.2.4 by Brian Aker
Refactoring table.h
1668
    MY_HOOKS(select_create *x, TableList *create_table,
1669
             TableList *select_tables)
1 by brian
clean slate
1670
      : ptr(x), all_tables(*create_table)
1671
      {
1672
        all_tables.next_global= select_tables;
1673
      }
1674
1675
  private:
482 by Brian Aker
Remove uint.
1676
    virtual int do_postlock(Table **tables, uint32_t count)
1 by brian
clean slate
1677
    {
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1678
      Table const *const table = *tables;
600 by Brian Aker
Removing more options around changing replication
1679
      if (drizzle_bin_log.is_open()
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1680
          && !table->s->tmp_table
599 by Brian Aker
Change default option. Also, fixed failure on doing so...
1681
          && !ptr->get_create_info()->table_existed)
1 by brian
clean slate
1682
      {
1683
        ptr->binlog_show_create_table(tables, count);
1684
      }
1685
      return 0;
1686
    }
1687
1688
    select_create *ptr;
327.2.4 by Brian Aker
Refactoring table.h
1689
    TableList all_tables;
1 by brian
clean slate
1690
  };
1691
1692
  MY_HOOKS hooks(this, create_table, select_tables);
1693
  hook_ptr= &hooks;
1694
1695
  unit= u;
1696
1697
  /*
1698
    Start a statement transaction before the create if we are using
1699
    row-based replication for the statement.  If we are creating a
1700
    temporary table, we need to start a statement transaction.
1701
  */
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1702
  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...
1703
      && drizzle_bin_log.is_open())
1 by brian
clean slate
1704
  {
1705
  }
1706
520.1.22 by Brian Aker
Second pass of thd cleanup
1707
  if (!(table= create_table_from_items(session, create_info, create_table,
1 by brian
clean slate
1708
                                       alter_info, &values,
1709
                                       &extra_lock, hook_ptr)))
51.2.2 by Patrick Galbraith
Removed DBUGs from
1710
    return(-1);				// abort() deletes table
1 by brian
clean slate
1711
1712
  if (extra_lock)
1713
  {
51.2.2 by Patrick Galbraith
Removed DBUGs from
1714
    assert(m_plock == NULL);
1 by brian
clean slate
1715
1716
    if (create_info->options & HA_LEX_CREATE_TMP_TABLE)
1717
      m_plock= &m_lock;
1718
    else
520.1.22 by Brian Aker
Second pass of thd cleanup
1719
      m_plock= &session->extra_lock;
1 by brian
clean slate
1720
1721
    *m_plock= extra_lock;
1722
  }
1723
1724
  if (table->s->fields < values.elements)
1725
  {
1726
    my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), 1);
51.2.2 by Patrick Galbraith
Removed DBUGs from
1727
    return(-1);
1 by brian
clean slate
1728
  }
1729
1730
 /* First field to copy */
1731
  field= table->field+table->s->fields - values.elements;
1732
1733
  /* Mark all fields that are given values */
1734
  for (Field **f= field ; *f ; f++)
1735
    bitmap_set_bit(table->write_set, (*f)->field_index);
1736
1737
  /* Don't set timestamp if used */
1738
  table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
1739
  table->next_number_field=table->found_next_number_field;
1740
1741
  restore_record(table,s->default_values);      // Get empty record
520.1.22 by Brian Aker
Second pass of thd cleanup
1742
  session->cuted_fields=0;
1 by brian
clean slate
1743
  if (info.ignore || info.handle_duplicates != DUP_ERROR)
1744
    table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
1745
  if (info.handle_duplicates == DUP_REPLACE)
1746
    table->file->extra(HA_EXTRA_WRITE_CAN_REPLACE);
1747
  if (info.handle_duplicates == DUP_UPDATE)
1748
    table->file->extra(HA_EXTRA_INSERT_WITH_UPDATE);
1749
  table->file->ha_start_bulk_insert((ha_rows) 0);
520.1.22 by Brian Aker
Second pass of thd cleanup
1750
  session->abort_on_warning= !info.ignore;
1751
  if (check_that_all_fields_are_given_values(session, table, table_list))
51.2.2 by Patrick Galbraith
Removed DBUGs from
1752
    return(1);
1 by brian
clean slate
1753
  table->mark_columns_needed_for_insert();
1754
  table->file->extra(HA_EXTRA_WRITE_CACHE);
51.2.2 by Patrick Galbraith
Removed DBUGs from
1755
  return(0);
1 by brian
clean slate
1756
}
1757
1758
void
482 by Brian Aker
Remove uint.
1759
select_create::binlog_show_create_table(Table **tables, uint32_t count)
1 by brian
clean slate
1760
{
1761
  /*
1762
    Note 1: In RBR mode, we generate a CREATE TABLE statement for the
1763
    created table by calling store_create_info() (behaves as SHOW
1764
    CREATE TABLE).  In the event of an error, nothing should be
1765
    written to the binary log, even if the table is non-transactional;
1766
    therefore we pretend that the generated CREATE TABLE statement is
1767
    for a transactional table.  The event will then be put in the
1768
    transaction cache, and any subsequent events (e.g., table-map
1769
    events and binrow events) will also be put there.  We can then use
1770
    ha_autocommit_or_rollback() to either throw away the entire
1771
    kaboodle of events, or write them to the binary log.
1772
1773
    We write the CREATE TABLE statement here and not in prepare()
1774
    since there potentially are sub-selects or accesses to information
1775
    schema that will do a close_thread_tables(), destroying the
1776
    statement transaction cache.
1777
  */
51.2.2 by Patrick Galbraith
Removed DBUGs from
1778
  assert(tables && *tables && count > 0);
1 by brian
clean slate
1779
1780
  char buf[2048];
1781
  String query(buf, sizeof(buf), system_charset_info);
1782
  int result;
327.2.4 by Brian Aker
Refactoring table.h
1783
  TableList tmp_table_list;
1 by brian
clean slate
1784
1785
  memset(&tmp_table_list, 0, sizeof(tmp_table_list));
1786
  tmp_table_list.table = *tables;
1787
  query.length(0);      // Have to zero it since constructor doesn't
1788
520.1.22 by Brian Aker
Second pass of thd cleanup
1789
  result= store_create_info(session, &tmp_table_list, &query, create_info);
51.2.2 by Patrick Galbraith
Removed DBUGs from
1790
  assert(result == 0); /* store_create_info() always return 0 */
1 by brian
clean slate
1791
}
1792
1793
void select_create::store_values(List<Item> &values)
1794
{
520.1.22 by Brian Aker
Second pass of thd cleanup
1795
  fill_record(session, field, values, 1);
1 by brian
clean slate
1796
}
1797
1798
482 by Brian Aker
Remove uint.
1799
void select_create::send_error(uint32_t errcode,const char *err)
1 by brian
clean slate
1800
{
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1801
1 by brian
clean slate
1802
1803
  /*
1804
    This will execute any rollbacks that are necessary before writing
1805
    the transcation cache.
1806
1807
    We disable the binary log since nothing should be written to the
1808
    binary log.  This disabling is important, since we potentially do
1809
    a "roll back" of non-transactional tables by removing the table,
1810
    and the actual rollback might generate events that should not be
1811
    written to the binary log.
1812
1813
  */
520.1.22 by Brian Aker
Second pass of thd cleanup
1814
  tmp_disable_binlog(session);
1 by brian
clean slate
1815
  select_insert::send_error(errcode, err);
520.1.22 by Brian Aker
Second pass of thd cleanup
1816
  reenable_binlog(session);
1 by brian
clean slate
1817
51.2.2 by Patrick Galbraith
Removed DBUGs from
1818
  return;
1 by brian
clean slate
1819
}
1820
1821
1822
bool select_create::send_eof()
1823
{
1824
  bool tmp=select_insert::send_eof();
1825
  if (tmp)
1826
    abort();
1827
  else
1828
  {
1829
    /*
1830
      Do an implicit commit at end of statement for non-temporary
1831
      tables.  This can fail, but we should unlock the table
1832
      nevertheless.
1833
    */
1834
    if (!table->s->tmp_table)
1835
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
1836
      ha_autocommit_or_rollback(session, 0);
1837
      end_active_trans(session);
1 by brian
clean slate
1838
    }
1839
1840
    table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
1841
    table->file->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
1842
    if (m_plock)
1843
    {
520.1.22 by Brian Aker
Second pass of thd cleanup
1844
      mysql_unlock_tables(session, *m_plock);
1 by brian
clean slate
1845
      *m_plock= NULL;
1846
      m_plock= NULL;
1847
    }
1848
  }
1849
  return tmp;
1850
}
1851
1852
1853
void select_create::abort()
1854
{
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1855
1 by brian
clean slate
1856
1857
  /*
1858
    In select_insert::abort() we roll back the statement, including
1859
    truncating the transaction cache of the binary log. To do this, we
1860
    pretend that the statement is transactional, even though it might
1861
    be the case that it was not.
1862
1863
    We roll back the statement prior to deleting the table and prior
1864
    to releasing the lock on the table, since there might be potential
1865
    for failure if the rollback is executed after the drop or after
1866
    unlocking the table.
1867
1868
    We also roll back the statement regardless of whether the creation
1869
    of the table succeeded or not, since we need to reset the binary
1870
    log state.
1871
  */
520.1.22 by Brian Aker
Second pass of thd cleanup
1872
  tmp_disable_binlog(session);
1 by brian
clean slate
1873
  select_insert::abort();
520.1.22 by Brian Aker
Second pass of thd cleanup
1874
  session->transaction.stmt.modified_non_trans_table= false;
1875
  reenable_binlog(session);
1 by brian
clean slate
1876
1877
1878
  if (m_plock)
1879
  {
520.1.22 by Brian Aker
Second pass of thd cleanup
1880
    mysql_unlock_tables(session, *m_plock);
1 by brian
clean slate
1881
    *m_plock= NULL;
1882
    m_plock= NULL;
1883
  }
1884
1885
  if (table)
1886
  {
1887
    table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
1888
    table->file->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
1889
    if (!create_info->table_existed)
520.1.22 by Brian Aker
Second pass of thd cleanup
1890
      drop_open_table(session, table, create_table->db, create_table->table_name);
1 by brian
clean slate
1891
    table=0;                                    // Safety
1892
  }
51.2.2 by Patrick Galbraith
Removed DBUGs from
1893
  return;
1 by brian
clean slate
1894
}
1895
1896
1897
/*****************************************************************************
1898
  Instansiate templates
1899
*****************************************************************************/
1900
1901
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
1902
template class List_iterator_fast<List_item>;
1903
#endif /* HAVE_EXPLICIT_TEMPLATE_INSTANTIATION */