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