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