~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_insert.cc

Does not work (compile issue in plugin).

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
 
12
12
   You should have received a copy of the GNU General Public License
13
13
   along with this program; if not, write to the Free Software
14
 
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */
 
14
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
15
15
 
16
16
 
17
17
/* Insert of records */
18
18
 
19
 
#include <config.h>
20
 
#include <cstdio>
 
19
#include "config.h"
21
20
#include <drizzled/sql_select.h>
22
21
#include <drizzled/show.h>
23
22
#include <drizzled/error.h>
25
24
#include <drizzled/probes.h>
26
25
#include <drizzled/sql_base.h>
27
26
#include <drizzled/sql_load.h>
28
 
#include <drizzled/field/epoch.h>
 
27
#include <drizzled/field/timestamp.h>
29
28
#include <drizzled/lock.h>
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>
34
 
#include <drizzled/select_insert.h>
35
 
#include <drizzled/select_create.h>
36
 
#include <drizzled/table/shell.h>
37
 
#include <drizzled/alter_info.h>
38
 
#include <drizzled/sql_parse.h>
39
 
#include <drizzled/sql_lex.h>
40
 
#include <drizzled/statistics_variables.h>
41
 
#include <drizzled/session/transactions.h>
42
 
#include <drizzled/open_tables_state.h>
43
 
#include <drizzled/table/cache.h>
 
29
#include "drizzled/sql_table.h"
 
30
#include "drizzled/pthread_globals.h"
 
31
#include "drizzled/transaction_services.h"
44
32
 
45
 
namespace drizzled {
 
33
namespace drizzled
 
34
{
46
35
 
47
36
extern plugin::StorageEngine *heap_engine;
48
37
extern plugin::StorageEngine *myisam_engine;
75
64
{
76
65
  Table *table= table_list->table;
77
66
 
78
 
  if (fields.size() == 0 && values.size() != 0)
 
67
  if (fields.elements == 0 && values.elements != 0)
79
68
  {
80
 
    if (values.size() != table->getShare()->sizeFields())
 
69
    if (values.elements != table->s->fields)
81
70
    {
82
71
      my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), 1L);
83
72
      return -1;
92
81
  }
93
82
  else
94
83
  {                                             // Part field list
95
 
    Select_Lex *select_lex= &session->lex().select_lex;
 
84
    Select_Lex *select_lex= &session->lex->select_lex;
96
85
    Name_resolution_context *context= &select_lex->context;
97
86
    Name_resolution_context_state ctx_state;
98
87
    int res;
99
88
 
100
 
    if (fields.size() != values.size())
 
89
    if (fields.elements != values.elements)
101
90
    {
102
91
      my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), 1L);
103
92
      return -1;
130
119
    if (table->timestamp_field) // Don't automaticly set timestamp if used
131
120
    {
132
121
      if (table->timestamp_field->isWriteSet())
133
 
      {
134
122
        clear_timestamp_auto_bits(table->timestamp_field_type,
135
123
                                  TIMESTAMP_AUTO_SET_ON_INSERT);
136
 
      }
137
124
      else
138
125
      {
139
 
        table->setWriteSet(table->timestamp_field->position());
 
126
        table->setWriteSet(table->timestamp_field->field_index);
140
127
      }
141
128
    }
142
129
  }
177
164
      Unmark the timestamp field so that we can check if this is modified
178
165
      by update_fields
179
166
    */
180
 
    timestamp_mark= table->write_set->test(table->timestamp_field->position());
181
 
    table->write_set->reset(table->timestamp_field->position());
 
167
    timestamp_mark= table->write_set->testAndClear(table->timestamp_field->field_index);
182
168
  }
183
169
 
184
170
  /* Check the fields we are going to modify */
189
175
  {
190
176
    /* Don't set timestamp column if this is modified. */
191
177
    if (table->timestamp_field->isWriteSet())
192
 
    {
193
178
      clear_timestamp_auto_bits(table->timestamp_field_type,
194
179
                                TIMESTAMP_AUTO_SET_ON_UPDATE);
195
 
    }
196
 
 
197
180
    if (timestamp_mark)
198
 
    {
199
 
      table->setWriteSet(table->timestamp_field->position());
200
 
    }
 
181
      table->setWriteSet(table->timestamp_field->field_index);
201
182
  }
202
183
  return 0;
203
184
}
234
215
  end of dispatch_command().
235
216
*/
236
217
 
237
 
bool insert_query(Session *session,TableList *table_list,
 
218
bool mysql_insert(Session *session,TableList *table_list,
238
219
                  List<Item> &fields,
239
220
                  List<List_item> &values_list,
240
221
                  List<Item> &update_fields,
248
229
  uint32_t value_count;
249
230
  ulong counter = 1;
250
231
  uint64_t id;
251
 
  CopyInfo info;
 
232
  COPY_INFO info;
252
233
  Table *table= 0;
253
 
  List<List_item>::iterator its(values_list.begin());
 
234
  List_iterator_fast<List_item> its(values_list);
254
235
  List_item *values;
255
236
  Name_resolution_context *context;
256
237
  Name_resolution_context_state ctx_state;
 
238
  thr_lock_type lock_type;
257
239
  Item *unused_conds= 0;
258
240
 
259
241
 
262
244
    the current connection mode or table operation.
263
245
  */
264
246
  upgrade_lock_type(session, &table_list->lock_type, duplic,
265
 
                    values_list.size() > 1);
 
247
                    values_list.elements > 1);
266
248
 
267
249
  if (session->openTablesLock(table_list))
268
250
  {
270
252
    return true;
271
253
  }
272
254
 
 
255
  lock_type= table_list->lock_type;
 
256
 
273
257
  session->set_proc_info("init");
274
258
  session->used_tables=0;
275
259
  values= its++;
276
 
  value_count= values->size();
 
260
  value_count= values->elements;
277
261
 
278
 
  if (prepare_insert(session, table_list, table, fields, values,
 
262
  if (mysql_prepare_insert(session, table_list, table, fields, values,
279
263
                           update_fields, update_values, duplic, &unused_conds,
280
264
                           false,
281
 
                           (fields.size() || !value_count ||
 
265
                           (fields.elements || !value_count ||
282
266
                            (0) != 0), !ignore))
283
 
  {
284
 
    if (table != NULL)
285
 
      table->cursor->ha_release_auto_increment();
286
 
    if (!joins_freed)
287
 
      free_underlaid_joins(session, &session->lex().select_lex);
288
 
    session->setAbortOnWarning(false);
289
 
    DRIZZLE_INSERT_DONE(1, 0);
290
 
    return true;
291
 
  }
 
267
    goto abort;
292
268
 
293
269
  /* mysql_prepare_insert set table_list->table if it was not set */
294
270
  table= table_list->table;
295
271
 
296
 
  context= &session->lex().select_lex.context;
 
272
  context= &session->lex->select_lex.context;
297
273
  /*
298
274
    These three asserts test the hypothesis that the resetting of the name
299
275
    resolution context below is not necessary at all since the list of local
316
292
  while ((values= its++))
317
293
  {
318
294
    counter++;
319
 
    if (values->size() != value_count)
 
295
    if (values->elements != value_count)
320
296
    {
321
297
      my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), counter);
322
 
 
323
 
      if (table != NULL)
324
 
        table->cursor->ha_release_auto_increment();
325
 
      if (!joins_freed)
326
 
        free_underlaid_joins(session, &session->lex().select_lex);
327
 
      session->setAbortOnWarning(false);
328
 
      DRIZZLE_INSERT_DONE(1, 0);
329
 
 
330
 
      return true;
 
298
      goto abort;
331
299
    }
332
300
    if (setup_fields(session, 0, *values, MARK_COLUMNS_READ, 0, 0))
333
 
    {
334
 
      if (table != NULL)
335
 
        table->cursor->ha_release_auto_increment();
336
 
      if (!joins_freed)
337
 
        free_underlaid_joins(session, &session->lex().select_lex);
338
 
      session->setAbortOnWarning(false);
339
 
      DRIZZLE_INSERT_DONE(1, 0);
340
 
      return true;
341
 
    }
 
301
      goto abort;
342
302
  }
343
 
  its= values_list.begin();
 
303
  its.rewind ();
344
304
 
345
305
  /* Restore the current context. */
346
306
  ctx_state.restore_state(context, table_list);
348
308
  /*
349
309
    Fill in the given fields and dump it to the table cursor
350
310
  */
 
311
  memset(&info, 0, sizeof(info));
351
312
  info.ignore= ignore;
352
313
  info.handle_duplicates=duplic;
353
314
  info.update_fields= &update_fields;
358
319
    For single line insert, generate an error if try to set a NOT NULL field
359
320
    to NULL.
360
321
  */
361
 
  session->count_cuted_fields= ignore ? CHECK_FIELD_WARN : CHECK_FIELD_ERROR_FOR_NULL;
362
 
 
 
322
  session->count_cuted_fields= ((values_list.elements == 1 &&
 
323
                                 !ignore) ?
 
324
                                CHECK_FIELD_ERROR_FOR_NULL :
 
325
                                CHECK_FIELD_WARN);
363
326
  session->cuted_fields = 0L;
364
327
  table->next_number_field=table->found_next_number_field;
365
328
 
372
335
  {
373
336
    if (duplic != DUP_ERROR || ignore)
374
337
      table->cursor->extra(HA_EXTRA_IGNORE_DUP_KEY);
375
 
    table->cursor->ha_start_bulk_insert(values_list.size());
 
338
    table->cursor->ha_start_bulk_insert(values_list.elements);
376
339
  }
377
340
 
378
341
 
379
 
  session->setAbortOnWarning(not ignore);
 
342
  session->abort_on_warning= !ignore;
380
343
 
381
344
  table->mark_columns_needed_for_insert();
382
345
 
383
346
  while ((values= its++))
384
347
  {
385
 
    if (fields.size() || !value_count)
 
348
    if (fields.elements || !value_count)
386
349
    {
387
350
      table->restoreRecordAsDefault();  // Get empty record
388
351
      if (fill_record(session, fields, *values))
389
352
      {
390
 
        if (values_list.size() != 1 && ! session->is_error())
 
353
        if (values_list.elements != 1 && ! session->is_error())
391
354
        {
392
355
          info.records++;
393
356
          continue;
405
368
    {
406
369
      table->restoreRecordAsDefault();  // Get empty record
407
370
 
408
 
      if (fill_record(session, table->getFields(), *values))
 
371
      if (fill_record(session, table->field, *values))
409
372
      {
410
 
        if (values_list.size() != 1 && ! session->is_error())
 
373
        if (values_list.elements != 1 && ! session->is_error())
411
374
        {
412
375
          info.records++;
413
376
          continue;
418
381
    }
419
382
 
420
383
    // Release latches in case bulk insert takes a long time
421
 
    plugin::TransactionalStorageEngine::releaseTemporaryLatches(session);
 
384
    plugin::StorageEngine::releaseTemporaryLatches(session);
422
385
 
423
386
    error=write_record(session, table ,&info);
424
387
    if (error)
426
389
    session->row_count++;
427
390
  }
428
391
 
429
 
  free_underlaid_joins(session, &session->lex().select_lex);
 
392
  free_underlaid_joins(session, &session->lex->select_lex);
430
393
  joins_freed= true;
431
394
 
432
395
  /*
450
413
    transactional_table= table->cursor->has_transactions();
451
414
 
452
415
    changed= (info.copied || info.deleted || info.updated);
453
 
    if ((changed && error <= 0) || session->transaction.stmt.hasModifiedNonTransData())
 
416
    if ((changed && error <= 0) || session->transaction.stmt.modified_non_trans_table)
454
417
    {
455
 
      if (session->transaction.stmt.hasModifiedNonTransData())
456
 
        session->transaction.all.markModifiedNonTransData();
 
418
      if (session->transaction.stmt.modified_non_trans_table)
 
419
        session->transaction.all.modified_non_trans_table= true;
457
420
    }
458
 
    assert(transactional_table || !changed || session->transaction.stmt.hasModifiedNonTransData());
 
421
    assert(transactional_table || !changed || session->transaction.stmt.modified_non_trans_table);
459
422
 
460
423
  }
461
424
  session->set_proc_info("end");
482
445
    table->cursor->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
483
446
 
484
447
  if (error)
485
 
  {
486
 
    if (table != NULL)
487
 
      table->cursor->ha_release_auto_increment();
488
 
    if (!joins_freed)
489
 
      free_underlaid_joins(session, &session->lex().select_lex);
490
 
    session->setAbortOnWarning(false);
491
 
    DRIZZLE_INSERT_DONE(1, 0);
492
 
    return true;
493
 
  }
494
 
 
495
 
  if (values_list.size() == 1 && (!(session->options & OPTION_WARNINGS) ||
 
448
    goto abort;
 
449
  if (values_list.elements == 1 && (!(session->options & OPTION_WARNINGS) ||
496
450
                                    !session->cuted_fields))
497
451
  {
498
452
    session->row_count_func= info.copied + info.deleted + info.updated;
499
 
    session->my_ok((ulong) session->rowCount(),
 
453
    session->my_ok((ulong) session->row_count_func,
500
454
                   info.copied + info.deleted + info.touched, id);
501
455
  }
502
456
  else
503
457
  {
504
458
    char buff[160];
505
459
    if (ignore)
506
 
      snprintf(buff, sizeof(buff), ER(ER_INSERT_INFO), (ulong) info.records,
 
460
      sprintf(buff, ER(ER_INSERT_INFO), (ulong) info.records,
507
461
              (ulong) (info.records - info.copied), (ulong) session->cuted_fields);
508
462
    else
509
 
      snprintf(buff, sizeof(buff), ER(ER_INSERT_INFO), (ulong) info.records,
 
463
      sprintf(buff, ER(ER_INSERT_INFO), (ulong) info.records,
510
464
              (ulong) (info.deleted + info.updated), (ulong) session->cuted_fields);
511
465
    session->row_count_func= info.copied + info.deleted + info.updated;
512
 
    session->my_ok((ulong) session->rowCount(),
 
466
    session->my_ok((ulong) session->row_count_func,
513
467
                   info.copied + info.deleted + info.touched, id, buff);
514
468
  }
515
 
  session->status_var.inserted_row_count+= session->rowCount();
516
 
  session->setAbortOnWarning(false);
517
 
  DRIZZLE_INSERT_DONE(0, session->rowCount());
518
 
 
 
469
  session->abort_on_warning= 0;
 
470
  DRIZZLE_INSERT_DONE(0, session->row_count_func);
519
471
  return false;
 
472
 
 
473
abort:
 
474
  if (table != NULL)
 
475
    table->cursor->ha_release_auto_increment();
 
476
  if (!joins_freed)
 
477
    free_underlaid_joins(session, &session->lex->select_lex);
 
478
  session->abort_on_warning= 0;
 
479
  DRIZZLE_INSERT_DONE(1, 0);
 
480
  return true;
520
481
}
521
482
 
522
483
 
524
485
  Check if table can be updated
525
486
 
526
487
  SYNOPSIS
527
 
     prepare_insert_check_table()
 
488
     mysql_prepare_insert_check_table()
528
489
     session            Thread handle
529
490
     table_list         Table list
530
491
     fields             List of fields to be updated
536
497
     true  ERROR
537
498
*/
538
499
 
539
 
static bool prepare_insert_check_table(Session *session, TableList *table_list,
 
500
static bool mysql_prepare_insert_check_table(Session *session, TableList *table_list,
540
501
                                             List<Item> &,
541
502
                                             bool select_insert)
542
503
{
549
510
     than INSERT.
550
511
  */
551
512
 
552
 
  if (setup_tables_and_check_access(session, &session->lex().select_lex.context,
553
 
                                    &session->lex().select_lex.top_join_list,
 
513
  if (setup_tables_and_check_access(session, &session->lex->select_lex.context,
 
514
                                    &session->lex->select_lex.top_join_list,
554
515
                                    table_list,
555
 
                                    &session->lex().select_lex.leaf_tables,
 
516
                                    &session->lex->select_lex.leaf_tables,
556
517
                                    select_insert))
557
518
    return(true);
558
519
 
564
525
  Prepare items in INSERT statement
565
526
 
566
527
  SYNOPSIS
567
 
    prepare_insert()
 
528
    mysql_prepare_insert()
568
529
    session                     Thread handler
569
530
    table_list          Global/local table list
570
531
    table               Table to insert into (can be NULL if table should
591
552
    true  error
592
553
*/
593
554
 
594
 
bool prepare_insert(Session *session, TableList *table_list,
 
555
bool mysql_prepare_insert(Session *session, TableList *table_list,
595
556
                          Table *table, List<Item> &fields, List_item *values,
596
557
                          List<Item> &update_fields, List<Item> &update_values,
597
558
                          enum_duplicates duplic,
599
560
                          bool select_insert,
600
561
                          bool check_fields, bool abort_on_warning)
601
562
{
602
 
  Select_Lex *select_lex= &session->lex().select_lex;
 
563
  Select_Lex *select_lex= &session->lex->select_lex;
603
564
  Name_resolution_context *context= &select_lex->context;
604
565
  Name_resolution_context_state ctx_state;
605
566
  bool insert_into_view= (0 != 0);
614
575
    inserting (for INSERT ... SELECT this is done by changing table_list,
615
576
    because INSERT ... SELECT share Select_Lex it with SELECT.
616
577
  */
617
 
  if (not select_insert)
 
578
  if (!select_insert)
618
579
  {
619
580
    for (Select_Lex_Unit *un= select_lex->first_inner_unit();
620
581
         un;
636
597
      return(true);
637
598
  }
638
599
 
639
 
  if (prepare_insert_check_table(session, table_list, fields, select_insert))
 
600
  if (mysql_prepare_insert_check_table(session, table_list, fields, select_insert))
640
601
    return(true);
641
602
 
642
603
 
662
623
 
663
624
    if (!res && check_fields)
664
625
    {
665
 
      bool saved_abort_on_warning= session->abortOnWarning();
666
 
 
667
 
      session->setAbortOnWarning(abort_on_warning);
 
626
      bool saved_abort_on_warning= session->abort_on_warning;
 
627
      session->abort_on_warning= abort_on_warning;
668
628
      res= check_that_all_fields_are_given_values(session,
669
629
                                                  table ? table :
670
630
                                                  context->table_list->table,
671
631
                                                  context->table_list);
672
 
      session->setAbortOnWarning(saved_abort_on_warning);
 
632
      session->abort_on_warning= saved_abort_on_warning;
673
633
    }
674
634
 
675
635
    if (!res && duplic == DUP_UPDATE)
680
640
    /* Restore the current context. */
681
641
    ctx_state.restore_state(context, table_list);
682
642
 
683
 
    if (not res)
 
643
    if (!res)
684
644
      res= setup_fields(session, 0, update_values, MARK_COLUMNS_READ, 0, 0);
685
645
  }
686
646
 
687
647
  if (res)
688
648
    return(res);
689
649
 
690
 
  if (not table)
 
650
  if (!table)
691
651
    table= table_list->table;
692
652
 
693
 
  if (not select_insert)
 
653
  if (!select_insert)
694
654
  {
695
655
    TableList *duplicate;
696
656
    if ((duplicate= unique_table(table_list, table_list->next_global, true)))
700
660
      return true;
701
661
    }
702
662
  }
703
 
 
704
663
  if (duplic == DUP_UPDATE || duplic == DUP_REPLACE)
705
664
    table->prepare_for_position();
706
665
 
712
671
 
713
672
static int last_uniq_key(Table *table,uint32_t keynr)
714
673
{
715
 
  while (++keynr < table->getShare()->sizeKeys())
 
674
  while (++keynr < table->s->keys)
716
675
    if (table->key_info[keynr].flags & HA_NOSAME)
717
676
      return 0;
718
677
  return 1;
727
686
     write_record()
728
687
      session   - thread context
729
688
      table - table to which record should be written
730
 
      info  - CopyInfo structure describing handling of duplicates
 
689
      info  - COPY_INFO structure describing handling of duplicates
731
690
              and which is used for counting number of records inserted
732
691
              and deleted.
733
692
 
737
696
    then both on update triggers will work instead. Similarly both on
738
697
    delete triggers will be invoked if we will delete conflicting records.
739
698
 
740
 
    Sets session->transaction.stmt.modified_non_trans_data to true if table which is updated didn't have
 
699
    Sets session->transaction.stmt.modified_non_trans_table to true if table which is updated didn't have
741
700
    transactions.
742
701
 
743
702
  RETURN VALUE
746
705
*/
747
706
 
748
707
 
749
 
int write_record(Session *session, Table *table,CopyInfo *info)
 
708
int write_record(Session *session, Table *table,COPY_INFO *info)
750
709
{
751
710
  int error;
752
 
  std::vector<unsigned char> key;
753
 
  boost::dynamic_bitset<> *save_read_set, *save_write_set;
 
711
  char *key=0;
 
712
  MyBitmap *save_read_set, *save_write_set;
754
713
  uint64_t prev_insert_id= table->cursor->next_insert_id;
755
714
  uint64_t insert_id_for_cur_row= 0;
756
715
 
761
720
 
762
721
  if (info->handle_duplicates == DUP_REPLACE || info->handle_duplicates == DUP_UPDATE)
763
722
  {
764
 
    while ((error=table->cursor->insertRecord(table->getInsertRecord())))
 
723
    while ((error=table->cursor->ha_write_row(table->record[0])))
765
724
    {
766
725
      uint32_t key_nr;
767
726
      /*
804
763
      */
805
764
      if (info->handle_duplicates == DUP_REPLACE &&
806
765
          table->next_number_field &&
807
 
          key_nr == table->getShare()->next_number_index &&
 
766
          key_nr == table->s->next_number_index &&
808
767
          (insert_id_for_cur_row > 0))
809
768
        goto err;
810
769
      if (table->cursor->getEngine()->check_flag(HTON_BIT_DUPLICATE_POS))
811
770
      {
812
 
        if (table->cursor->rnd_pos(table->getUpdateRecord(),table->cursor->dup_ref))
 
771
        if (table->cursor->rnd_pos(table->record[1],table->cursor->dup_ref))
813
772
          goto err;
814
773
      }
815
774
      else
820
779
          goto err;
821
780
        }
822
781
 
823
 
        if (not key.size())
 
782
        if (!key)
824
783
        {
825
 
          key.resize(table->getShare()->max_unique_length);
 
784
          if (!(key=(char*) malloc(table->s->max_unique_length)))
 
785
          {
 
786
            error=ENOMEM;
 
787
            goto err;
 
788
          }
826
789
        }
827
 
        key_copy(&key[0], table->getInsertRecord(), table->key_info+key_nr, 0);
828
 
        if ((error=(table->cursor->index_read_idx_map(table->getUpdateRecord(),key_nr,
829
 
                                                    &key[0], HA_WHOLE_KEY,
 
790
        key_copy((unsigned char*) key,table->record[0],table->key_info+key_nr,0);
 
791
        if ((error=(table->cursor->index_read_idx_map(table->record[1],key_nr,
 
792
                                                    (unsigned char*) key, HA_WHOLE_KEY,
830
793
                                                    HA_READ_KEY_EXACT))))
831
794
          goto err;
832
795
      }
837
800
          that matches, is updated. If update causes a conflict again,
838
801
          an error is returned
839
802
        */
840
 
        assert(table->insert_values.size());
 
803
        assert(table->insert_values != NULL);
841
804
        table->storeRecordAsInsert();
842
805
        table->restoreRecord();
843
 
        assert(info->update_fields->size() ==
844
 
                    info->update_values->size());
 
806
        assert(info->update_fields->elements ==
 
807
                    info->update_values->elements);
845
808
        if (fill_record(session, *info->update_fields,
846
809
                                                 *info->update_values,
847
810
                                                 info->ignore))
852
815
          table->cursor->adjust_next_insert_id_after_explicit_value(
853
816
            table->next_number_field->val_int());
854
817
        info->touched++;
855
 
 
856
 
        if (! table->records_are_comparable() || table->compare_records())
 
818
        if ((table->cursor->getEngine()->check_flag(HTON_BIT_PARTIAL_COLUMN_READ) &&
 
819
             !bitmap_is_subset(table->write_set, table->read_set)) ||
 
820
            table->compare_record())
857
821
        {
858
 
          if ((error=table->cursor->updateRecord(table->getUpdateRecord(),
859
 
                                                table->getInsertRecord())) &&
 
822
          if ((error=table->cursor->ha_update_row(table->record[1],
 
823
                                                table->record[0])) &&
860
824
              error != HA_ERR_RECORD_IS_THE_SAME)
861
825
          {
862
826
            if (info->ignore &&
874
838
          /*
875
839
            If ON DUP KEY UPDATE updates a row instead of inserting one, it's
876
840
            like a regular UPDATE statement: it should not affect the value of a
877
 
            next SELECT LAST_INSERT_ID() or insert_id().
 
841
            next SELECT LAST_INSERT_ID() or mysql_insert_id().
878
842
            Except if LAST_INSERT_ID(#) was in the INSERT query, which is
879
843
            handled separately by Session::arg_of_last_insert_id_function.
880
844
          */
910
874
            (table->timestamp_field_type == TIMESTAMP_NO_AUTO_SET ||
911
875
             table->timestamp_field_type == TIMESTAMP_AUTO_SET_ON_BOTH))
912
876
        {
913
 
          if ((error=table->cursor->updateRecord(table->getUpdateRecord(),
914
 
                                                table->getInsertRecord())) &&
 
877
          if ((error=table->cursor->ha_update_row(table->record[1],
 
878
                                                table->record[0])) &&
915
879
              error != HA_ERR_RECORD_IS_THE_SAME)
916
880
            goto err;
917
881
          if (error != HA_ERR_RECORD_IS_THE_SAME)
927
891
        }
928
892
        else
929
893
        {
930
 
          if ((error=table->cursor->deleteRecord(table->getUpdateRecord())))
 
894
          if ((error=table->cursor->ha_delete_row(table->record[1])))
931
895
            goto err;
932
896
          info->deleted++;
933
897
          if (!table->cursor->has_transactions())
934
 
            session->transaction.stmt.markModifiedNonTransData();
 
898
            session->transaction.stmt.modified_non_trans_table= true;
935
899
          /* Let us attempt do write_row() once more */
936
900
        }
937
901
      }
943
907
    */
944
908
    if (table->read_set != save_read_set ||
945
909
        table->write_set != save_write_set)
946
 
      table->column_bitmaps_set(*save_read_set, *save_write_set);
 
910
      table->column_bitmaps_set(save_read_set, save_write_set);
947
911
  }
948
 
  else if ((error=table->cursor->insertRecord(table->getInsertRecord())))
 
912
  else if ((error=table->cursor->ha_write_row(table->record[0])))
949
913
  {
950
914
    if (!info->ignore ||
951
915
        table->cursor->is_fatal_error(error, HA_CHECK_DUP))
959
923
  session->record_first_successful_insert_id_in_cur_stmt(table->cursor->insert_id_for_cur_row);
960
924
 
961
925
gok_or_after_err:
 
926
  if (key)
 
927
    free(key);
962
928
  if (!table->cursor->has_transactions())
963
 
    session->transaction.stmt.markModifiedNonTransData();
 
929
    session->transaction.stmt.modified_non_trans_table= true;
964
930
  return(0);
965
931
 
966
932
err:
967
933
  info->last_errno= error;
968
934
  /* current_select is NULL if this is a delayed insert */
969
 
  if (session->lex().current_select)
970
 
    session->lex().current_select->no_error= 0;        // Give error
 
935
  if (session->lex->current_select)
 
936
    session->lex->current_select->no_error= 0;        // Give error
971
937
  table->print_error(error,MYF(0));
972
938
 
973
939
before_err:
974
940
  table->cursor->restore_auto_increment(prev_insert_id);
975
 
  table->column_bitmaps_set(*save_read_set, *save_write_set);
976
 
  return 1;
 
941
  if (key)
 
942
    free(key);
 
943
  table->column_bitmaps_set(save_read_set, save_write_set);
 
944
  return(1);
977
945
}
978
946
 
979
947
 
986
954
{
987
955
  int err= 0;
988
956
 
989
 
  for (Field **field=entry->getFields() ; *field ; field++)
 
957
  for (Field **field=entry->field ; *field ; field++)
990
958
  {
991
959
    if (((*field)->isWriteSet()) == false)
992
960
    {
1006
974
    {
1007
975
      /*
1008
976
       * However, if an actual NULL value was specified
1009
 
       * for the field and the field is a NOT NULL field,
 
977
       * for the field and the field is a NOT NULL field, 
1010
978
       * throw ER_BAD_NULL_ERROR.
1011
979
       *
1012
980
       * Per the SQL standard, inserting NULL into a NOT NULL
1020
988
      }
1021
989
    }
1022
990
  }
1023
 
  return session->abortOnWarning() ? err : 0;
 
991
  return session->abort_on_warning ? err : 0;
1024
992
}
1025
993
 
1026
994
/***************************************************************************
1032
1000
  make insert specific preparation and checks after opening tables
1033
1001
 
1034
1002
  SYNOPSIS
1035
 
    insert_select_prepare()
 
1003
    mysql_insert_select_prepare()
1036
1004
    session         thread handler
1037
1005
 
1038
1006
  RETURN
1040
1008
    true  Error
1041
1009
*/
1042
1010
 
1043
 
bool insert_select_prepare(Session *session)
 
1011
bool mysql_insert_select_prepare(Session *session)
1044
1012
{
1045
 
  LEX *lex= &session->lex();
 
1013
  LEX *lex= session->lex;
1046
1014
  Select_Lex *select_lex= &lex->select_lex;
1047
1015
 
1048
1016
  /*
1050
1018
    clause if table is VIEW
1051
1019
  */
1052
1020
 
1053
 
  if (prepare_insert(session, lex->query_tables,
 
1021
  if (mysql_prepare_insert(session, lex->query_tables,
1054
1022
                           lex->query_tables->table, lex->field_list, 0,
1055
1023
                           lex->update_list, lex->value_list,
1056
1024
                           lex->duplicates,
1074
1042
                             List<Item> *update_fields,
1075
1043
                             List<Item> *update_values,
1076
1044
                             enum_duplicates duplic,
1077
 
                             bool ignore_check_option_errors) :
1078
 
  table_list(table_list_par), table(table_par), fields(fields_par),
1079
 
  autoinc_value_of_last_inserted_row(0),
1080
 
  insert_into_view(table_list_par && 0 != 0)
 
1045
                             bool ignore_check_option_errors)
 
1046
  :table_list(table_list_par), table(table_par), fields(fields_par),
 
1047
   autoinc_value_of_last_inserted_row(0),
 
1048
   insert_into_view(table_list_par && 0 != 0)
1081
1049
{
 
1050
  memset(&info, 0, sizeof(info));
1082
1051
  info.handle_duplicates= duplic;
1083
1052
  info.ignore= ignore_check_option_errors;
1084
1053
  info.update_fields= update_fields;
1089
1058
int
1090
1059
select_insert::prepare(List<Item> &values, Select_Lex_Unit *u)
1091
1060
{
 
1061
  LEX *lex= session->lex;
1092
1062
  int res;
1093
1063
  table_map map= 0;
1094
 
  Select_Lex *lex_current_select_save= session->lex().current_select;
 
1064
  Select_Lex *lex_current_select_save= lex->current_select;
1095
1065
 
1096
1066
 
1097
1067
  unit= u;
1101
1071
    select, LEX::current_select should point to the first select while
1102
1072
    we are fixing fields from insert list.
1103
1073
  */
1104
 
  session->lex().current_select= &session->lex().select_lex;
 
1074
  lex->current_select= &lex->select_lex;
1105
1075
  res= check_insert_fields(session, table_list, *fields, values,
1106
1076
                           !insert_into_view, &map) ||
1107
1077
       setup_fields(session, 0, values, MARK_COLUMNS_READ, 0, 0);
1108
1078
 
1109
 
  if (!res && fields->size())
 
1079
  if (!res && fields->elements)
1110
1080
  {
1111
 
    bool saved_abort_on_warning= session->abortOnWarning();
1112
 
    session->setAbortOnWarning(not info.ignore);
 
1081
    bool saved_abort_on_warning= session->abort_on_warning;
 
1082
    session->abort_on_warning= !info.ignore;
1113
1083
    res= check_that_all_fields_are_given_values(session, table_list->table,
1114
1084
                                                table_list);
1115
 
    session->setAbortOnWarning(saved_abort_on_warning);
 
1085
    session->abort_on_warning= saved_abort_on_warning;
1116
1086
  }
1117
1087
 
1118
1088
  if (info.handle_duplicates == DUP_UPDATE && !res)
1119
1089
  {
1120
 
    Name_resolution_context *context= &session->lex().select_lex.context;
 
1090
    Name_resolution_context *context= &lex->select_lex.context;
1121
1091
    Name_resolution_context_state ctx_state;
1122
1092
 
1123
1093
    /* Save the state of the current name resolution context. */
1135
1105
      We use next_name_resolution_table descructively, so check it first (views?)
1136
1106
    */
1137
1107
    assert (!table_list->next_name_resolution_table);
1138
 
    if (session->lex().select_lex.group_list.elements == 0 and
1139
 
        not session->lex().select_lex.with_sum_func)
 
1108
    if (lex->select_lex.group_list.elements == 0 &&
 
1109
        !lex->select_lex.with_sum_func)
1140
1110
      /*
1141
1111
        We must make a single context out of the two separate name resolution contexts :
1142
1112
        the INSERT table and the tables in the SELECT part of INSERT ... SELECT.
1155
1125
        order to get correct values from those fields when the select
1156
1126
        employs a temporary table.
1157
1127
      */
1158
 
      List<Item>::iterator li(info.update_values->begin());
 
1128
      List_iterator<Item> li(*info.update_values);
1159
1129
      Item *item;
1160
1130
 
1161
1131
      while ((item= li++))
1162
1132
      {
1163
1133
        item->transform(&Item::update_value_transformer,
1164
 
                        (unsigned char*)session->lex().current_select);
 
1134
                        (unsigned char*)lex->current_select);
1165
1135
      }
1166
1136
    }
1167
1137
 
1169
1139
    ctx_state.restore_state(context, table_list);
1170
1140
  }
1171
1141
 
1172
 
  session->lex().current_select= lex_current_select_save;
 
1142
  lex->current_select= lex_current_select_save;
1173
1143
  if (res)
1174
1144
    return(1);
1175
1145
  /*
1185
1155
  if (unique_table(table_list, table_list->next_global))
1186
1156
  {
1187
1157
    /* Using same table for INSERT and SELECT */
1188
 
    session->lex().current_select->options|= OPTION_BUFFER_RESULT;
1189
 
    session->lex().current_select->join->select_options|= OPTION_BUFFER_RESULT;
 
1158
    lex->current_select->options|= OPTION_BUFFER_RESULT;
 
1159
    lex->current_select->join->select_options|= OPTION_BUFFER_RESULT;
1190
1160
  }
1191
 
  else if (not (session->lex().current_select->options & OPTION_BUFFER_RESULT))
 
1161
  else if (!(lex->current_select->options & OPTION_BUFFER_RESULT))
1192
1162
  {
1193
1163
    /*
1194
1164
      We must not yet prepare the result table if it is the same as one of the
1205
1175
  table->next_number_field=table->found_next_number_field;
1206
1176
 
1207
1177
  session->cuted_fields=0;
1208
 
 
1209
1178
  if (info.ignore || info.handle_duplicates != DUP_ERROR)
1210
1179
    table->cursor->extra(HA_EXTRA_IGNORE_DUP_KEY);
1211
 
 
1212
1180
  if (info.handle_duplicates == DUP_REPLACE)
1213
1181
    table->cursor->extra(HA_EXTRA_WRITE_CAN_REPLACE);
1214
 
 
1215
1182
  if (info.handle_duplicates == DUP_UPDATE)
1216
1183
    table->cursor->extra(HA_EXTRA_INSERT_WITH_UPDATE);
1217
 
 
1218
 
  session->setAbortOnWarning(not info.ignore);
 
1184
  session->abort_on_warning= !info.ignore;
1219
1185
  table->mark_columns_needed_for_insert();
1220
1186
 
1221
1187
 
1241
1207
 
1242
1208
int select_insert::prepare2(void)
1243
1209
{
1244
 
  if (session->lex().current_select->options & OPTION_BUFFER_RESULT)
 
1210
 
 
1211
  if (session->lex->current_select->options & OPTION_BUFFER_RESULT)
1245
1212
    table->cursor->ha_start_bulk_insert((ha_rows) 0);
1246
 
 
1247
1213
  return(0);
1248
1214
}
1249
1215
 
1264
1230
    table->cursor->ha_reset();
1265
1231
  }
1266
1232
  session->count_cuted_fields= CHECK_FIELD_IGNORE;
1267
 
  session->setAbortOnWarning(false);
 
1233
  session->abort_on_warning= 0;
1268
1234
  return;
1269
1235
}
1270
1236
 
1272
1238
bool select_insert::send_data(List<Item> &values)
1273
1239
{
1274
1240
 
1275
 
  bool error= false;
 
1241
  bool error=0;
1276
1242
 
1277
1243
  if (unit->offset_limit_cnt)
1278
1244
  {                                             // using limit offset,count
1279
1245
    unit->offset_limit_cnt--;
1280
 
    return false;
 
1246
    return(0);
1281
1247
  }
1282
1248
 
1283
1249
  session->count_cuted_fields= CHECK_FIELD_WARN;        // Calculate cuted fields
1284
1250
  store_values(values);
1285
1251
  session->count_cuted_fields= CHECK_FIELD_IGNORE;
1286
1252
  if (session->is_error())
1287
 
    return true;
 
1253
    return(1);
1288
1254
 
1289
1255
  // Release latches in case bulk insert takes a long time
1290
 
  plugin::TransactionalStorageEngine::releaseTemporaryLatches(session);
 
1256
  plugin::StorageEngine::releaseTemporaryLatches(session);
1291
1257
 
1292
1258
  error= write_record(session, table, &info);
1293
 
  table->auto_increment_field_not_null= false;
1294
1259
 
1295
1260
  if (!error)
1296
1261
  {
1328
1293
 
1329
1294
void select_insert::store_values(List<Item> &values)
1330
1295
{
1331
 
  if (fields->size())
 
1296
  if (fields->elements)
1332
1297
    fill_record(session, *fields, values, true);
1333
1298
  else
1334
 
    fill_record(session, table->getFields(), values, true);
 
1299
    fill_record(session, table->field, values, true);
1335
1300
}
1336
1301
 
1337
 
void select_insert::send_error(drizzled::error_t errcode,const char *err)
 
1302
void select_insert::send_error(uint32_t errcode,const char *err)
1338
1303
{
 
1304
 
 
1305
 
1339
1306
  my_message(errcode, err, MYF(0));
 
1307
 
 
1308
  return;
1340
1309
}
1341
1310
 
1342
1311
 
1355
1324
  {
1356
1325
    /*
1357
1326
      We must invalidate the table in the query cache before binlog writing
1358
 
      and autocommitOrRollback.
 
1327
      and ha_autocommit_or_rollback.
1359
1328
    */
1360
 
    if (session->transaction.stmt.hasModifiedNonTransData())
1361
 
      session->transaction.all.markModifiedNonTransData();
 
1329
    if (session->transaction.stmt.modified_non_trans_table)
 
1330
      session->transaction.all.modified_non_trans_table= true;
1362
1331
  }
1363
1332
  assert(trans_table || !changed ||
1364
 
              session->transaction.stmt.hasModifiedNonTransData());
 
1333
              session->transaction.stmt.modified_non_trans_table);
1365
1334
 
1366
1335
  table->cursor->ha_release_auto_increment();
1367
1336
 
1373
1342
  }
1374
1343
  char buff[160];
1375
1344
  if (info.ignore)
1376
 
    snprintf(buff, sizeof(buff), ER(ER_INSERT_INFO), (ulong) info.records,
 
1345
    sprintf(buff, ER(ER_INSERT_INFO), (ulong) info.records,
1377
1346
            (ulong) (info.records - info.copied), (ulong) session->cuted_fields);
1378
1347
  else
1379
 
    snprintf(buff, sizeof(buff), ER(ER_INSERT_INFO), (ulong) info.records,
 
1348
    sprintf(buff, ER(ER_INSERT_INFO), (ulong) info.records,
1380
1349
            (ulong) (info.deleted+info.updated), (ulong) session->cuted_fields);
1381
1350
  session->row_count_func= info.copied + info.deleted + info.updated;
1382
1351
 
1385
1354
    (session->arg_of_last_insert_id_function ?
1386
1355
     session->first_successful_insert_id_in_prev_stmt :
1387
1356
     (info.copied ? autoinc_value_of_last_inserted_row : 0));
1388
 
  session->my_ok((ulong) session->rowCount(),
 
1357
  session->my_ok((ulong) session->row_count_func,
1389
1358
                 info.copied + info.deleted + info.touched, id, buff);
1390
 
  session->status_var.inserted_row_count+= session->rowCount();
1391
 
  DRIZZLE_INSERT_SELECT_DONE(0, session->rowCount());
 
1359
  DRIZZLE_INSERT_SELECT_DONE(0, session->row_count_func);
1392
1360
  return 0;
1393
1361
}
1394
1362
 
1424
1392
    changed= (info.copied || info.deleted || info.updated);
1425
1393
    transactional_table= table->cursor->has_transactions();
1426
1394
    assert(transactional_table || !changed ||
1427
 
                session->transaction.stmt.hasModifiedNonTransData());
 
1395
                session->transaction.stmt.modified_non_trans_table);
1428
1396
    table->cursor->ha_release_auto_increment();
1429
1397
  }
1430
1398
 
1457
1425
      items        in     List of items which should be used to produce rest
1458
1426
                          of fields for the table (corresponding fields will
1459
1427
                          be added to the end of alter_info->create_list)
1460
 
      lock         out    Pointer to the DrizzleLock object for table created
 
1428
      lock         out    Pointer to the DRIZZLE_LOCK object for table created
1461
1429
                          (or open temporary table) will be returned in this
1462
1430
                          parameter. Since this table is not included in
1463
1431
                          Session::lock caller is responsible for explicitly
1485
1453
 
1486
1454
static Table *create_table_from_items(Session *session, HA_CREATE_INFO *create_info,
1487
1455
                                      TableList *create_table,
1488
 
                                      message::Table &table_proto,
 
1456
                                      message::Table *table_proto,
1489
1457
                                      AlterInfo *alter_info,
1490
1458
                                      List<Item> *items,
1491
1459
                                      bool is_if_not_exists,
1492
 
                                      DrizzleLock **lock,
1493
 
                                      const identifier::Table& identifier)
 
1460
                                      DRIZZLE_LOCK **lock)
1494
1461
{
1495
 
  TableShare share(message::Table::INTERNAL);
1496
 
  uint32_t select_field_count= items->size();
 
1462
  Table tmp_table;              // Used during 'CreateField()'
 
1463
  TableShare share;
 
1464
  Table *table= 0;
 
1465
  uint32_t select_field_count= items->elements;
1497
1466
  /* Add selected items to field list */
1498
 
  List<Item>::iterator it(items->begin());
 
1467
  List_iterator_fast<Item> it(*items);
1499
1468
  Item *item;
1500
1469
  Field *tmp_field;
1501
 
 
1502
 
  if (not (identifier.isTmp()) && create_table->table->db_stat)
 
1470
  bool not_used;
 
1471
 
 
1472
  bool lex_identified_temp_table= (table_proto->type() == message::Table::TEMPORARY);
 
1473
 
 
1474
  if (!(lex_identified_temp_table) &&
 
1475
      create_table->table->db_stat)
1503
1476
  {
1504
1477
    /* Table already exists and was open at openTablesLock() stage. */
1505
1478
    if (is_if_not_exists)
1507
1480
      create_info->table_existed= 1;            // Mark that table existed
1508
1481
      push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
1509
1482
                          ER_TABLE_EXISTS_ERROR, ER(ER_TABLE_EXISTS_ERROR),
1510
 
                          create_table->getTableName());
 
1483
                          create_table->table_name);
1511
1484
      return create_table->table;
1512
1485
    }
1513
1486
 
1514
 
    my_error(ER_TABLE_EXISTS_ERROR, MYF(0), create_table->getTableName());
 
1487
    my_error(ER_TABLE_EXISTS_ERROR, MYF(0), create_table->table_name);
1515
1488
    return NULL;
1516
1489
  }
1517
1490
 
 
1491
  tmp_table.alias= 0;
 
1492
  tmp_table.timestamp_field= 0;
 
1493
  tmp_table.s= &share;
 
1494
 
 
1495
  tmp_table.s->db_create_options=0;
 
1496
  tmp_table.s->blob_ptr_size= portable_sizeof_char_ptr;
 
1497
  tmp_table.s->db_low_byte_first=
 
1498
        test(create_info->db_type == myisam_engine ||
 
1499
             create_info->db_type == heap_engine);
 
1500
  tmp_table.null_row= false;
 
1501
  tmp_table.maybe_null= false;
 
1502
 
 
1503
  while ((item=it++))
1518
1504
  {
1519
 
    table::Shell tmp_table(share);              // Used during 'CreateField()'
1520
 
 
1521
 
    if (not table_proto.engine().name().compare("MyISAM"))
1522
 
      tmp_table.getMutableShare()->db_low_byte_first= true;
1523
 
    else if (not table_proto.engine().name().compare("MEMORY"))
1524
 
      tmp_table.getMutableShare()->db_low_byte_first= true;
1525
 
 
1526
 
    tmp_table.in_use= session;
1527
 
 
1528
 
    while ((item=it++))
1529
 
    {
1530
 
      CreateField *cr_field;
1531
 
      Field *field, *def_field;
1532
 
      if (item->type() == Item::FUNC_ITEM)
1533
 
      {
1534
 
        if (item->result_type() != STRING_RESULT)
1535
 
        {
1536
 
          field= item->tmp_table_field(&tmp_table);
1537
 
        }
1538
 
        else
1539
 
        {
1540
 
          field= item->tmp_table_field_from_field_type(&tmp_table, 0);
1541
 
        }
1542
 
      }
 
1505
    CreateField *cr_field;
 
1506
    Field *field, *def_field;
 
1507
    if (item->type() == Item::FUNC_ITEM)
 
1508
      if (item->result_type() != STRING_RESULT)
 
1509
        field= item->tmp_table_field(&tmp_table);
1543
1510
      else
1544
 
      {
1545
 
        field= create_tmp_field(session, &tmp_table, item, item->type(),
1546
 
                                (Item ***) 0, &tmp_field, &def_field, false,
1547
 
                                false, false, 0);
1548
 
      }
1549
 
 
1550
 
      if (!field ||
1551
 
          !(cr_field=new CreateField(field,(item->type() == Item::FIELD_ITEM ?
1552
 
                                            ((Item_field *)item)->field :
1553
 
                                            (Field*) 0))))
1554
 
      {
1555
 
        return NULL;
1556
 
      }
1557
 
 
1558
 
      if (item->maybe_null)
1559
 
      {
1560
 
        cr_field->flags &= ~NOT_NULL_FLAG;
1561
 
      }
1562
 
 
1563
 
      alter_info->create_list.push_back(cr_field);
1564
 
    }
 
1511
        field= item->tmp_table_field_from_field_type(&tmp_table, 0);
 
1512
    else
 
1513
      field= create_tmp_field(session, &tmp_table, item, item->type(),
 
1514
                              (Item ***) 0, &tmp_field, &def_field, 0, 0, 0, 0,
 
1515
                              0);
 
1516
    if (!field ||
 
1517
        !(cr_field=new CreateField(field,(item->type() == Item::FIELD_ITEM ?
 
1518
                                           ((Item_field *)item)->field :
 
1519
                                           (Field*) 0))))
 
1520
      return NULL;
 
1521
    if (item->maybe_null)
 
1522
      cr_field->flags &= ~NOT_NULL_FLAG;
 
1523
    alter_info->create_list.push_back(cr_field);
1565
1524
  }
1566
1525
 
 
1526
  TableIdentifier identifier(create_table->db,
 
1527
                             create_table->table_name,
 
1528
                             lex_identified_temp_table ?  TEMP_TABLE :
 
1529
                             NO_TMP_TABLE);
 
1530
 
 
1531
 
1567
1532
  /*
1568
1533
    Create and lock table.
1569
1534
 
1571
1536
    creating base table on which name we have exclusive lock. So code below
1572
1537
    should not cause deadlocks or races.
1573
1538
  */
1574
 
  Table *table= 0;
1575
1539
  {
1576
 
    if (not create_table_no_lock(session,
1577
 
                                 identifier,
1578
 
                                 create_info,
1579
 
                                 table_proto,
1580
 
                                 alter_info,
1581
 
                                 false,
1582
 
                                 select_field_count,
1583
 
                                 is_if_not_exists))
 
1540
    if (!mysql_create_table_no_lock(session,
 
1541
                                    identifier,
 
1542
                                    create_info,
 
1543
                                    table_proto,
 
1544
                                    alter_info,
 
1545
                                    false,
 
1546
                                    select_field_count,
 
1547
                                    is_if_not_exists))
1584
1548
    {
1585
 
      if (create_info->table_existed && not identifier.isTmp())
 
1549
      if (create_info->table_existed &&
 
1550
          !(lex_identified_temp_table))
1586
1551
      {
1587
1552
        /*
1588
1553
          This means that someone created table underneath server
1589
1554
          or it was created via different mysqld front-end to the
1590
1555
          cluster. We don't have much options but throw an error.
1591
1556
        */
1592
 
        my_error(ER_TABLE_EXISTS_ERROR, MYF(0), create_table->getTableName());
 
1557
        my_error(ER_TABLE_EXISTS_ERROR, MYF(0), create_table->table_name);
1593
1558
        return NULL;
1594
1559
      }
1595
1560
 
1596
 
      if (not identifier.isTmp())
 
1561
      if (!(lex_identified_temp_table))
1597
1562
      {
1598
 
        /* CREATE TABLE... has found that the table already exists for insert and is adapting to use it */
1599
 
        boost::mutex::scoped_lock scopedLock(table::Cache::mutex());
1600
 
 
1601
 
        if (create_table->table)
 
1563
        pthread_mutex_lock(&LOCK_open); /* CREATE TABLE... has found that the table already exists for insert and is adapting to use it */
 
1564
        if (session->reopen_name_locked_table(create_table, false))
1602
1565
        {
1603
 
          table::Concurrent *concurrent_table= static_cast<table::Concurrent *>(create_table->table);
1604
 
 
1605
 
          if (concurrent_table->reopen_name_locked_table(create_table, session))
1606
 
          {
1607
 
            (void)plugin::StorageEngine::dropTable(*session, identifier);
1608
 
          }
1609
 
          else
1610
 
          {
1611
 
            table= create_table->table;
1612
 
          }
 
1566
          quick_rm_table(*session, identifier);
1613
1567
        }
1614
1568
        else
1615
 
        {
1616
 
          (void)plugin::StorageEngine::dropTable(*session, identifier);
1617
 
        }
 
1569
          table= create_table->table;
 
1570
        pthread_mutex_unlock(&LOCK_open);
1618
1571
      }
1619
1572
      else
1620
1573
      {
1621
 
        if (not (table= session->openTable(create_table, (bool*) 0,
1622
 
                                           DRIZZLE_OPEN_TEMPORARY_ONLY)) &&
1623
 
            not create_info->table_existed)
 
1574
        if (!(table= session->openTable(create_table, (bool*) 0,
 
1575
                                         DRIZZLE_OPEN_TEMPORARY_ONLY)) &&
 
1576
            !create_info->table_existed)
1624
1577
        {
1625
1578
          /*
1626
1579
            This shouldn't happen as creation of temporary table should make
1627
1580
            it preparable for open. But let us do close_temporary_table() here
1628
1581
            just in case.
1629
1582
          */
1630
 
          session->open_tables.drop_temporary_table(identifier);
 
1583
          session->drop_temporary_table(create_table);
1631
1584
        }
1632
1585
      }
1633
1586
    }
1634
 
    if (not table)                                   // open failed
 
1587
    if (!table)                                   // open failed
1635
1588
      return NULL;
1636
1589
  }
1637
1590
 
1638
1591
  table->reginfo.lock_type=TL_WRITE;
1639
 
  if (not ((*lock)= session->lockTables(&table, 1, DRIZZLE_LOCK_IGNORE_FLUSH)))
 
1592
  if (! ((*lock)= mysql_lock_tables(session, &table, 1,
 
1593
                                    DRIZZLE_LOCK_IGNORE_FLUSH, &not_used)))
1640
1594
  {
1641
1595
    if (*lock)
1642
1596
    {
1643
 
      session->unlockTables(*lock);
 
1597
      mysql_unlock_tables(session, *lock);
1644
1598
      *lock= 0;
1645
1599
    }
1646
1600
 
1647
 
    if (not create_info->table_existed)
1648
 
      session->drop_open_table(table, identifier);
1649
 
 
 
1601
    if (!create_info->table_existed)
 
1602
      session->drop_open_table(table, create_table->db, create_table->table_name);
1650
1603
    return NULL;
1651
1604
  }
1652
1605
 
1657
1610
int
1658
1611
select_create::prepare(List<Item> &values, Select_Lex_Unit *u)
1659
1612
{
1660
 
  DrizzleLock *extra_lock= NULL;
 
1613
  bool lex_identified_temp_table= (table_proto->type() == message::Table::TEMPORARY);
 
1614
 
 
1615
  DRIZZLE_LOCK *extra_lock= NULL;
1661
1616
  /*
1662
 
    For replication, the CREATE-SELECT statement is written
1663
 
    in two pieces: the first transaction messsage contains
1664
 
    the CREATE TABLE statement as a CreateTableStatement message
1665
 
    necessary to create the table.
1666
 
 
1667
 
    The second transaction message contains all the InsertStatement
1668
 
    and associated InsertRecords that should go into the table.
 
1617
    For row-based replication, the CREATE-SELECT statement is written
 
1618
    in two pieces: the first one contain the CREATE TABLE statement
 
1619
    necessary to create the table and the second part contain the rows
 
1620
    that should go into the table.
 
1621
 
 
1622
    For non-temporary tables, the start of the CREATE-SELECT
 
1623
    implicitly commits the previous transaction, and all events
 
1624
    forming the statement will be stored the transaction cache. At end
 
1625
    of the statement, the entire statement is committed as a
 
1626
    transaction, and all events are written to the binary log.
 
1627
 
 
1628
    On the master, the table is locked for the duration of the
 
1629
    statement, but since the CREATE part is replicated as a simple
 
1630
    statement, there is no way to lock the table for accesses on the
 
1631
    slave.  Hence, we have to hold on to the CREATE part of the
 
1632
    statement until the statement has finished.
1669
1633
   */
1670
1634
 
1671
1635
  unit= u;
1672
1636
 
1673
 
  if (not (table= create_table_from_items(session, create_info, create_table,
1674
 
                                          table_proto,
1675
 
                                          alter_info, &values,
1676
 
                                          is_if_not_exists,
1677
 
                                          &extra_lock, identifier)))
1678
 
  {
 
1637
  /*
 
1638
    Start a statement transaction before the create if we are using
 
1639
    row-based replication for the statement.  If we are creating a
 
1640
    temporary table, we need to start a statement transaction.
 
1641
  */
 
1642
 
 
1643
  if (!(table= create_table_from_items(session, create_info, create_table,
 
1644
                                       table_proto,
 
1645
                                       alter_info, &values,
 
1646
                                       is_if_not_exists,
 
1647
                                       &extra_lock)))
1679
1648
    return(-1);                         // abort() deletes table
1680
 
  }
1681
1649
 
1682
1650
  if (extra_lock)
1683
1651
  {
1684
1652
    assert(m_plock == NULL);
1685
1653
 
1686
 
    if (identifier.isTmp())
 
1654
    if (lex_identified_temp_table)
1687
1655
      m_plock= &m_lock;
1688
1656
    else
1689
 
      m_plock= &session->open_tables.extra_lock;
 
1657
      m_plock= &session->extra_lock;
1690
1658
 
1691
1659
    *m_plock= extra_lock;
1692
1660
  }
1693
1661
 
1694
 
  if (table->getShare()->sizeFields() < values.size())
 
1662
  if (table->s->fields < values.elements)
1695
1663
  {
1696
1664
    my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), 1);
1697
1665
    return(-1);
1698
1666
  }
1699
1667
 
1700
1668
 /* First field to copy */
1701
 
  field= table->getFields() + table->getShare()->sizeFields() - values.size();
 
1669
  field= table->field+table->s->fields - values.elements;
1702
1670
 
1703
1671
  /* Mark all fields that are given values */
1704
1672
  for (Field **f= field ; *f ; f++)
1705
 
  {
1706
 
    table->setWriteSet((*f)->position());
1707
 
  }
 
1673
    table->setWriteSet((*f)->field_index);
1708
1674
 
1709
1675
  /* Don't set timestamp if used */
1710
1676
  table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
1714
1680
  session->cuted_fields=0;
1715
1681
  if (info.ignore || info.handle_duplicates != DUP_ERROR)
1716
1682
    table->cursor->extra(HA_EXTRA_IGNORE_DUP_KEY);
1717
 
 
1718
1683
  if (info.handle_duplicates == DUP_REPLACE)
1719
1684
    table->cursor->extra(HA_EXTRA_WRITE_CAN_REPLACE);
1720
 
 
1721
1685
  if (info.handle_duplicates == DUP_UPDATE)
1722
1686
    table->cursor->extra(HA_EXTRA_INSERT_WITH_UPDATE);
1723
 
 
1724
1687
  table->cursor->ha_start_bulk_insert((ha_rows) 0);
1725
 
  session->setAbortOnWarning(not info.ignore);
 
1688
  session->abort_on_warning= !info.ignore;
1726
1689
  if (check_that_all_fields_are_given_values(session, table, table_list))
1727
1690
    return(1);
1728
 
 
1729
1691
  table->mark_columns_needed_for_insert();
1730
1692
  table->cursor->extra(HA_EXTRA_WRITE_CACHE);
1731
1693
  return(0);
1737
1699
}
1738
1700
 
1739
1701
 
1740
 
void select_create::send_error(drizzled::error_t errcode,const char *err)
 
1702
void select_create::send_error(uint32_t errcode,const char *err)
1741
1703
{
 
1704
 
 
1705
 
1742
1706
  /*
1743
1707
    This will execute any rollbacks that are necessary before writing
1744
1708
    the transcation cache.
1751
1715
 
1752
1716
  */
1753
1717
  select_insert::send_error(errcode, err);
 
1718
 
 
1719
  return;
1754
1720
}
1755
1721
 
1756
1722
 
1766
1732
      tables.  This can fail, but we should unlock the table
1767
1733
      nevertheless.
1768
1734
    */
1769
 
    if (!table->getShare()->getType())
 
1735
    if (!table->s->tmp_table)
1770
1736
    {
1771
1737
      TransactionServices &transaction_services= TransactionServices::singleton();
1772
 
      transaction_services.autocommitOrRollback(*session, 0);
 
1738
      transaction_services.ha_autocommit_or_rollback(session, 0);
1773
1739
      (void) session->endActiveTransaction();
1774
1740
    }
1775
1741
 
1777
1743
    table->cursor->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
1778
1744
    if (m_plock)
1779
1745
    {
1780
 
      session->unlockTables(*m_plock);
 
1746
      mysql_unlock_tables(session, *m_plock);
1781
1747
      *m_plock= NULL;
1782
1748
      m_plock= NULL;
1783
1749
    }
1788
1754
 
1789
1755
void select_create::abort()
1790
1756
{
 
1757
 
 
1758
 
1791
1759
  /*
1792
1760
    In select_insert::abort() we roll back the statement, including
1793
1761
    truncating the transaction cache of the binary log. To do this, we
1804
1772
    log state.
1805
1773
  */
1806
1774
  select_insert::abort();
 
1775
  session->transaction.stmt.modified_non_trans_table= false;
 
1776
 
1807
1777
 
1808
1778
  if (m_plock)
1809
1779
  {
1810
 
    session->unlockTables(*m_plock);
 
1780
    mysql_unlock_tables(session, *m_plock);
1811
1781
    *m_plock= NULL;
1812
1782
    m_plock= NULL;
1813
1783
  }
1816
1786
  {
1817
1787
    table->cursor->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
1818
1788
    table->cursor->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
1819
 
    if (not create_info->table_existed)
1820
 
      session->drop_open_table(table, identifier);
 
1789
    if (!create_info->table_existed)
 
1790
      session->drop_open_table(table, create_table->db, create_table->table_name);
1821
1791
    table= NULL;                                    // Safety
1822
1792
  }
1823
1793
}