~drizzle-trunk/drizzle/development

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