~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/statement/alter_table.cc

pandora-build v0.71. Added check for avahi.

Show diffs side-by-side

added added

removed removed

Lines of Context:
18
18
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19
19
 */
20
20
 
21
 
#include "config.h"
22
 
 
23
 
#include <fcntl.h>
24
 
 
25
 
#include <sstream>
26
 
 
27
 
#include "drizzled/show.h"
28
 
#include "drizzled/lock.h"
29
 
#include "drizzled/session.h"
30
 
#include "drizzled/statement/alter_table.h"
31
 
#include "drizzled/global_charset_info.h"
32
 
 
 
21
#include <drizzled/server_includes.h>
 
22
#include <drizzled/show.h>
 
23
#include <drizzled/lock.h>
 
24
#include <drizzled/session.h>
 
25
#include <drizzled/statement/alter_table.h>
33
26
 
34
27
#include "drizzled/gettext.h"
35
28
#include "drizzled/data_home.h"
36
29
#include "drizzled/sql_table.h"
37
30
#include "drizzled/table_proto.h"
38
 
#include "drizzled/optimizer/range.h"
39
 
#include "drizzled/time_functions.h"
40
 
#include "drizzled/records.h"
41
 
#include "drizzled/pthread_globals.h"
42
 
#include "drizzled/internal/my_sys.h"
43
 
#include "drizzled/internal/iocache.h"
44
 
 
45
 
#include "drizzled/transaction_services.h"
46
 
 
47
 
#include "drizzled/filesort.h"
48
 
 
49
 
#include "drizzled/message.h"
50
31
 
51
32
using namespace std;
52
33
 
53
34
namespace drizzled
54
35
{
55
36
 
56
 
extern pid_t current_pid;
57
 
 
58
 
static int copy_data_between_tables(Session *session,
59
 
                                    Table *from,Table *to,
 
37
static int copy_data_between_tables(Table *from,Table *to,
60
38
                                    List<CreateField> &create,
61
39
                                    bool ignore,
62
40
                                    uint32_t order_num,
63
 
                                    Order *order,
 
41
                                    order_st *order,
64
42
                                    ha_rows *copied,
65
43
                                    ha_rows *deleted,
66
44
                                    enum enum_enable_or_disable keys_onoff,
67
45
                                    bool error_if_not_empty);
68
 
 
69
46
static bool mysql_prepare_alter_table(Session *session,
70
47
                                      Table *table,
71
48
                                      HA_CREATE_INFO *create_info,
72
 
                                      const message::Table &original_proto,
73
 
                                      message::Table &table_message,
 
49
                                      message::Table *table_proto,
74
50
                                      AlterInfo *alter_info);
75
 
 
76
51
static int create_temporary_table(Session *session,
77
 
                                  TableIdentifier &identifier,
 
52
                                  Table *table,
 
53
                                  char *new_db,
 
54
                                  char *tmp_name,
78
55
                                  HA_CREATE_INFO *create_info,
79
 
                                  message::Table &create_message,
 
56
                                  message::Table *create_proto,
80
57
                                  AlterInfo *alter_info);
81
58
 
82
 
static Table *open_alter_table(Session *session, Table *table, TableIdentifier &identifier);
83
 
 
84
59
bool statement::AlterTable::execute()
85
60
{
86
61
  TableList *first_table= (TableList *) session->lex->select_lex.table_list.first;
89
64
  Select_Lex *select_lex= &session->lex->select_lex;
90
65
  bool need_start_waiting= false;
91
66
 
92
 
  if (is_engine_set)
 
67
  if (create_info.used_fields & HA_CREATE_USED_ENGINE)
93
68
  {
 
69
 
94
70
    create_info.db_type= 
95
 
      plugin::StorageEngine::findByName(*session, create_table_message.engine().name());
 
71
      plugin::StorageEngine::findByName(*session, create_table_proto.engine().name());
96
72
 
97
73
    if (create_info.db_type == NULL)
98
74
    {
99
75
      my_error(ER_UNKNOWN_STORAGE_ENGINE, MYF(0), 
100
 
               create_table_message.engine().name().c_str());
 
76
               create_table_proto.name().c_str());
101
77
 
102
78
      return true;
103
79
    }
106
82
  /* Must be set in the parser */
107
83
  assert(select_lex->db);
108
84
 
109
 
  /* Chicken/Egg... we need to search for the table, to know if the table exists, so we can build a full identifier from it */
110
 
  message::table::shared_ptr original_table_message;
111
 
  {
112
 
    TableIdentifier identifier(first_table->getSchemaName(), first_table->getTableName());
113
 
    if (plugin::StorageEngine::getTableDefinition(*session, identifier, original_table_message) != EEXIST)
114
 
    {
115
 
      std::string path;
116
 
      identifier.getSQLPath(path);
117
 
      my_error(ER_BAD_TABLE_ERROR, MYF(0), path.c_str());
118
 
      return true;
119
 
    }
120
 
 
121
 
    if (not  create_info.db_type)
122
 
    {
123
 
      create_info.db_type= 
124
 
        plugin::StorageEngine::findByName(*session, original_table_message->engine().name());
125
 
 
126
 
      if (not create_info.db_type)
127
 
      {
128
 
        std::string path;
129
 
        identifier.getSQLPath(path);
130
 
        my_error(ER_BAD_TABLE_ERROR, MYF(0), path.c_str());
131
 
        return true;
132
 
      }
133
 
    }
134
 
  }
135
 
 
136
 
  if (not validateCreateTableOption())
137
 
    return true;
138
 
 
139
85
  /* ALTER TABLE ends previous transaction */
140
 
  if (not session->endActiveTransaction())
141
 
    return true;
142
 
 
143
 
  if (not (need_start_waiting= not session->wait_if_global_read_lock(0, 1)))
144
 
    return true;
145
 
 
146
 
  bool res;
147
 
  if (original_table_message->type() == message::Table::STANDARD )
148
 
  {
149
 
    TableIdentifier identifier(first_table->getSchemaName(), first_table->getTableName());
150
 
    TableIdentifier new_identifier(select_lex->db ? select_lex->db : first_table->getSchemaName(),
151
 
                                   session->lex->name.str ? session->lex->name.str : first_table->getTableName());
152
 
 
153
 
    res= alter_table(session, 
154
 
                     identifier,
155
 
                     new_identifier,
156
 
                     &create_info,
157
 
                     *original_table_message,
158
 
                     create_table_message,
159
 
                     first_table,
160
 
                     &alter_info,
161
 
                     select_lex->order_list.elements,
162
 
                     (Order *) select_lex->order_list.first,
163
 
                     session->lex->ignore);
164
 
  }
165
 
  else
166
 
  {
167
 
    TableIdentifier catch22(first_table->getSchemaName(), first_table->getTableName());
168
 
    Table *table= session->find_temporary_table(catch22);
169
 
    assert(table);
170
 
    {
171
 
      TableIdentifier identifier(first_table->getSchemaName(), first_table->getTableName(), table->getMutableShare()->getPath());
172
 
      TableIdentifier new_identifier(select_lex->db ? select_lex->db : first_table->getSchemaName(),
173
 
                                     session->lex->name.str ? session->lex->name.str : first_table->getTableName(),
174
 
                                     table->getMutableShare()->getPath());
175
 
 
176
 
      res= alter_table(session, 
177
 
                       identifier,
178
 
                       new_identifier,
179
 
                       &create_info,
180
 
                       *original_table_message,
181
 
                       create_table_message,
182
 
                       first_table,
183
 
                       &alter_info,
184
 
                       select_lex->order_list.elements,
185
 
                       (Order *) select_lex->order_list.first,
186
 
                       session->lex->ignore);
187
 
    }
188
 
  }
189
 
 
 
86
  if (! session->endActiveTransaction())
 
87
  {
 
88
    return true;
 
89
  }
 
90
 
 
91
  if (! (need_start_waiting= ! wait_if_global_read_lock(session, 0, 1)))
 
92
  {
 
93
    return true;
 
94
  }
 
95
 
 
96
  bool res= alter_table(session, 
 
97
                        select_lex->db, 
 
98
                        session->lex->name.str,
 
99
                        &create_info,
 
100
                        &create_table_proto,
 
101
                        first_table,
 
102
                        &alter_info,
 
103
                        select_lex->order_list.elements,
 
104
                        (order_st *) select_lex->order_list.first,
 
105
                        session->lex->ignore);
190
106
  /*
191
107
     Release the protection against the global read lock and wake
192
108
     everyone, who might want to set a global read lock.
193
109
   */
194
 
  session->startWaitingGlobalReadLock();
195
 
 
 
110
  start_waiting_global_read_lock(session);
196
111
  return res;
197
112
}
198
113
 
240
155
static bool mysql_prepare_alter_table(Session *session,
241
156
                                      Table *table,
242
157
                                      HA_CREATE_INFO *create_info,
243
 
                                      const message::Table &original_proto,
244
 
                                      message::Table &table_message,
 
158
                                      message::Table *table_proto,
245
159
                                      AlterInfo *alter_info)
246
160
{
247
161
  /* New column definitions are added here */
256
170
  List_iterator<CreateField> field_it(new_create_list);
257
171
  List<Key_part_spec> key_parts;
258
172
  uint32_t used_fields= create_info->used_fields;
259
 
  KeyInfo *key_info= table->key_info;
 
173
  KEY *key_info= table->key_info;
260
174
  bool rc= true;
261
175
 
262
176
  /* Let new create options override the old ones */
263
177
  message::Table::TableOptions *table_options;
264
 
  table_options= table_message.mutable_options();
 
178
  table_options= table_proto->mutable_options();
265
179
 
 
180
  if (! (used_fields & HA_CREATE_USED_BLOCK_SIZE))
 
181
    table_options->set_block_size(table->s->block_size);
266
182
  if (! (used_fields & HA_CREATE_USED_DEFAULT_CHARSET))
267
 
    create_info->default_table_charset= table->getShare()->table_charset;
 
183
    create_info->default_table_charset= table->s->table_charset;
268
184
  if (! (used_fields & HA_CREATE_USED_AUTO) &&
269
185
      table->found_next_number_field)
270
186
  {
271
187
    /* Table has an autoincrement, copy value to new table */
272
188
    table->cursor->info(HA_STATUS_AUTO);
273
189
    create_info->auto_increment_value= table->cursor->stats.auto_increment_value;
274
 
    if (create_info->auto_increment_value != original_proto.options().auto_increment_value())
275
 
      table_options->set_has_user_set_auto_increment_value(false);
276
190
  }
 
191
  if (! (used_fields & HA_CREATE_USED_KEY_BLOCK_SIZE)
 
192
      && table->s->hasKeyBlockSize())
 
193
    table_options->set_key_block_size(table->s->getKeyBlockSize());
 
194
 
 
195
  if ((used_fields & HA_CREATE_USED_KEY_BLOCK_SIZE)
 
196
      && table_options->key_block_size() == 0)
 
197
    table_options->clear_key_block_size();
 
198
 
277
199
  table->restoreRecordAsDefault(); /* Empty record for DEFAULT */
278
200
  CreateField *def;
279
201
 
280
202
  /* First collect all fields from table which isn't in drop_list */
281
203
  Field **f_ptr;
282
204
  Field *field;
283
 
  for (f_ptr= table->getFields(); (field= *f_ptr); f_ptr++)
 
205
  for (f_ptr= table->field; (field= *f_ptr); f_ptr++)
284
206
  {
285
207
    /* Check if field should be dropped */
286
208
    AlterDrop *drop;
347
269
        if (def->sql_type == DRIZZLE_TYPE_BLOB)
348
270
        {
349
271
          my_error(ER_BLOB_CANT_HAVE_DEFAULT, MYF(0), def->change);
350
 
          return true;
 
272
                goto err;
351
273
        }
352
274
        if ((def->def= alter->def))
353
275
        {
355
277
          def->flags&= ~NO_DEFAULT_VALUE_FLAG;
356
278
        }
357
279
        else
358
 
        {
359
280
          def->flags|= NO_DEFAULT_VALUE_FLAG;
360
 
        }
361
281
        alter_it.remove();
362
282
      }
363
283
    }
367
287
  {
368
288
    if (def->change && ! def->field)
369
289
    {
370
 
      my_error(ER_BAD_FIELD_ERROR, MYF(0), def->change, table->getMutableShare()->getTableName());
371
 
      return true;
 
290
      my_error(ER_BAD_FIELD_ERROR, MYF(0), def->change, table->s->table_name.str);
 
291
      goto err;
372
292
    }
373
293
    /*
374
 
      If we have been given a field which has no default value, and is not null then we need to bail.
 
294
      Check that the DATE/DATETIME not null field we are going to add is
 
295
      either has a default value or the '0000-00-00' is allowed by the
 
296
      set sql mode.
 
297
      If the '0000-00-00' value isn't allowed then raise the error_if_not_empty
 
298
      flag to allow ALTER Table only if the table to be altered is empty.
375
299
    */
376
 
    if (not (~def->flags & (NO_DEFAULT_VALUE_FLAG | NOT_NULL_FLAG)) and not def->change)
 
300
    if ((def->sql_type == DRIZZLE_TYPE_DATE ||
 
301
         def->sql_type == DRIZZLE_TYPE_DATETIME) &&
 
302
        ! alter_info->datetime_field &&
 
303
        ! (~def->flags & (NO_DEFAULT_VALUE_FLAG | NOT_NULL_FLAG)) &&
 
304
        session->variables.sql_mode & MODE_NO_ZERO_DATE)
377
305
    {
 
306
      alter_info->datetime_field= def;
378
307
      alter_info->error_if_not_empty= true;
379
308
    }
380
309
    if (! def->after)
381
 
    {
382
310
      new_create_list.push_back(def);
383
 
    }
384
311
    else if (def->after == first_keyword)
385
 
    {
386
312
      new_create_list.push_front(def);
387
 
    }
388
313
    else
389
314
    {
390
315
      CreateField *find;
396
321
      }
397
322
      if (! find)
398
323
      {
399
 
        my_error(ER_BAD_FIELD_ERROR, MYF(0), def->after, table->getMutableShare()->getTableName());
400
 
        return true;
 
324
        my_error(ER_BAD_FIELD_ERROR, MYF(0), def->after, table->s->table_name.str);
 
325
        goto err;
401
326
      }
402
327
      find_it.after(def); /* Put element after this */
403
328
      /*
412
337
      */
413
338
      if (alter_info->build_method == HA_BUILD_ONLINE)
414
339
      {
415
 
        my_error(ER_NOT_SUPPORTED_YET, MYF(0), session->getQueryString()->c_str());
416
 
        return true;
 
340
        my_error(ER_NOT_SUPPORTED_YET, MYF(0), session->query);
 
341
        goto err;
417
342
      }
418
343
      alter_info->build_method= HA_BUILD_OFFLINE;
419
344
    }
423
348
    my_error(ER_BAD_FIELD_ERROR,
424
349
             MYF(0),
425
350
             alter_info->alter_list.head()->name,
426
 
             table->getMutableShare()->getTableName());
427
 
    return true;
 
351
             table->s->table_name.str);
 
352
    goto err;
428
353
  }
429
354
  if (! new_create_list.elements)
430
355
  {
431
356
    my_message(ER_CANT_REMOVE_ALL_FIELDS,
432
357
               ER(ER_CANT_REMOVE_ALL_FIELDS),
433
358
               MYF(0));
434
 
    return true;
 
359
    goto err;
435
360
  }
436
361
 
437
362
  /*
438
363
    Collect all keys which isn't in drop list. Add only those
439
364
    for which some fields exists.
440
365
  */
441
 
  for (uint32_t i= 0; i < table->getShare()->sizeKeys(); i++, key_info++)
 
366
  for (uint32_t i= 0; i < table->s->keys; i++, key_info++)
442
367
  {
443
368
    char *key_name= key_info->name;
444
369
    AlterDrop *drop;
455
380
      continue;
456
381
    }
457
382
 
458
 
    KeyPartInfo *key_part= key_info->key_part;
 
383
    KEY_PART_INFO *key_part= key_info->key_part;
459
384
    key_parts.empty();
460
385
    for (uint32_t j= 0; j < key_info->key_parts; j++, key_part++)
461
386
    {
537
462
      new_key_list.push_back(key);
538
463
    }
539
464
  }
540
 
 
541
 
  /* Copy over existing foreign keys */
542
 
  for (int j= 0; j < original_proto.fk_constraint_size(); j++)
543
 
  {
544
 
    AlterDrop *drop;
545
 
    drop_it.rewind();
546
 
    while ((drop= drop_it++))
547
 
    {
548
 
      if (drop->type == AlterDrop::FOREIGN_KEY &&
549
 
          ! my_strcasecmp(system_charset_info, original_proto.fk_constraint(j).name().c_str(), drop->name))
550
 
      {
551
 
        break;
552
 
      }
553
 
    }
554
 
    if (drop)
555
 
    {
556
 
      drop_it.remove();
557
 
      continue;
558
 
    }
559
 
 
560
 
    message::Table::ForeignKeyConstraint *pfkey= table_message.add_fk_constraint();
561
 
    *pfkey= original_proto.fk_constraint(j);
562
 
  }
563
 
 
564
465
  {
565
466
    Key *key;
566
467
    while ((key= key_it++)) /* Add new keys */
567
468
    {
568
 
      if (key->type == Key::FOREIGN_KEY)
569
 
      {
570
 
        if (((Foreign_key *)key)->validate(new_create_list))
571
 
        {
572
 
          return true;
573
 
        }
574
 
 
575
 
        Foreign_key *fkey= (Foreign_key*)key;
576
 
        add_foreign_key_to_table_message(&table_message,
577
 
                                         fkey->name.str,
578
 
                                         fkey->columns,
579
 
                                         fkey->ref_table,
580
 
                                         fkey->ref_columns,
581
 
                                         fkey->delete_opt,
582
 
                                         fkey->update_opt,
583
 
                                         fkey->match_opt);
584
 
      }
585
 
 
 
469
      if (key->type == Key::FOREIGN_KEY &&
 
470
          ((Foreign_key *)key)->validate(new_create_list))
 
471
        goto err;
586
472
      if (key->type != Key::FOREIGN_KEY)
587
473
        new_key_list.push_back(key);
588
 
 
589
474
      if (key->name.str && is_primary_key_name(key->name.str))
590
475
      {
591
476
        my_error(ER_WRONG_NAME_FOR_INDEX,
592
477
                 MYF(0),
593
478
                 key->name.str);
594
 
        return true;
 
479
        goto err;
595
480
      }
596
481
    }
597
482
  }
598
483
 
599
 
  /* Fix names of foreign keys being added */
600
 
  for (int j= 0; j < table_message.fk_constraint_size(); j++)
601
 
  {
602
 
    if (! table_message.fk_constraint(j).has_name())
603
 
    {
604
 
      std::string name(table->getMutableShare()->getTableName());
605
 
      char number[20];
606
 
 
607
 
      name.append("_ibfk_");
608
 
      snprintf(number, sizeof(number), "%d", j+1);
609
 
      name.append(number);
610
 
 
611
 
      message::Table::ForeignKeyConstraint *pfkey= table_message.mutable_fk_constraint(j);
612
 
      pfkey->set_name(name);
613
 
    }
614
 
  }
615
 
 
616
484
  if (alter_info->drop_list.elements)
617
485
  {
618
486
    my_error(ER_CANT_DROP_FIELD_OR_KEY,
619
487
             MYF(0),
620
488
             alter_info->drop_list.head()->name);
621
 
    return true;
 
489
    goto err;
622
490
  }
623
491
  if (alter_info->alter_list.elements)
624
492
  {
625
493
    my_error(ER_CANT_DROP_FIELD_OR_KEY,
626
494
             MYF(0),
627
495
             alter_info->alter_list.head()->name);
628
 
    return true;
629
 
  }
630
 
 
631
 
  if (not table_message.options().has_comment()
632
 
      && table->getMutableShare()->hasComment())
633
 
    table_options->set_comment(table->getMutableShare()->getComment());
634
 
 
635
 
  if (table->getShare()->getType())
636
 
  {
637
 
    table_message.set_type(message::Table::TEMPORARY);
638
 
  }
639
 
 
640
 
  table_message.set_creation_timestamp(table->getShare()->getTableProto()->creation_timestamp());
641
 
  table_message.set_version(table->getShare()->getTableProto()->version());
642
 
  table_message.set_uuid(table->getShare()->getTableProto()->uuid());
 
496
    goto err;
 
497
  }
 
498
 
 
499
  if (! table_proto->options().has_comment()
 
500
      && table->s->hasComment())
 
501
    table_options->set_comment(table->s->getComment());
 
502
 
 
503
  if (table->s->tmp_table)
 
504
    create_info->options|= HA_LEX_CREATE_TMP_TABLE;
643
505
 
644
506
  rc= false;
645
507
  alter_info->create_list.swap(new_create_list);
646
508
  alter_info->key_list.swap(new_key_list);
647
 
 
648
 
  size_t num_engine_options= table_message.engine().options_size();
649
 
  size_t original_num_engine_options= original_proto.engine().options_size();
650
 
  for (size_t x= 0; x < original_num_engine_options; ++x)
651
 
  {
652
 
    bool found= false;
653
 
 
654
 
    for (size_t y= 0; y < num_engine_options; ++y)
655
 
    {
656
 
      found= not table_message.engine().options(y).name().compare(original_proto.engine().options(x).name());
657
 
      
658
 
      if (found)
659
 
        break;
660
 
    }
661
 
 
662
 
    if (not found)
663
 
    {
664
 
      message::Engine::Option *opt= table_message.mutable_engine()->add_options();
665
 
 
666
 
      opt->set_name(original_proto.engine().options(x).name());
667
 
      opt->set_state(original_proto.engine().options(x).state());
668
 
    }
669
 
  }
670
 
 
671
 
  drizzled::message::update(table_message);
672
 
 
673
 
  return false;
 
509
err:
 
510
  return rc;
674
511
}
675
512
 
676
513
/* table_list should contain just one table */
687
524
    ALTER Table
688
525
  */
689
526
 
690
 
  TransactionServices &transaction_services= TransactionServices::singleton();
691
527
  session->set_proc_info("discard_or_import_tablespace");
692
528
 
693
529
  discard= test(tablespace_op == DISCARD_TABLESPACE);
711
547
    goto err;
712
548
 
713
549
  /* The ALTER Table is always in its own transaction */
714
 
  error= transaction_services.autocommitOrRollback(session, false);
715
 
  if (not session->endActiveTransaction())
 
550
  error = ha_autocommit_or_rollback(session, 0);
 
551
  if (! session->endActiveTransaction())
716
552
    error=1;
717
 
 
718
553
  if (error)
719
554
    goto err;
720
 
 
721
 
  write_bin_log(session, *session->getQueryString());
 
555
  write_bin_log(session, session->query, session->query_length);
722
556
 
723
557
err:
724
 
  (void) transaction_services.autocommitOrRollback(session, error);
 
558
  ha_autocommit_or_rollback(session, error);
725
559
  session->tablespace_op=false;
726
560
 
727
561
  if (error == 0)
730
564
    return 0;
731
565
  }
732
566
 
733
 
  table->print_error(error, MYF(0));
 
567
  table->cursor->print_error(error, MYF(0));
734
568
 
735
569
  return -1;
736
570
}
749
583
    false  OK
750
584
    true   Error
751
585
*/
752
 
static bool alter_table_manage_keys(Session *session,
753
 
                                    Table *table, int indexes_were_disabled,
754
 
                                    enum enum_enable_or_disable keys_onoff)
 
586
static bool alter_table_manage_keys(Table *table, int indexes_were_disabled,
 
587
                             enum enum_enable_or_disable keys_onoff)
755
588
{
756
589
  int error= 0;
757
590
  switch (keys_onoff) {
759
592
    error= table->cursor->ha_enable_indexes(HA_KEY_SWITCH_NONUNIQ_SAVE);
760
593
    break;
761
594
  case LEAVE_AS_IS:
762
 
    if (not indexes_were_disabled)
 
595
    if (!indexes_were_disabled)
763
596
      break;
764
597
    /* fall-through: disabled indexes */
765
598
  case DISABLE:
768
601
 
769
602
  if (error == HA_ERR_WRONG_COMMAND)
770
603
  {
771
 
    push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
 
604
    push_warning_printf(current_session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
772
605
                        ER_ILLEGAL_HA, ER(ER_ILLEGAL_HA),
773
 
                        table->getMutableShare()->getTableName());
 
606
                        table->s->table_name.str);
774
607
    error= 0;
775
608
  } else if (error)
776
 
    table->print_error(error, MYF(0));
 
609
    table->cursor->print_error(error, MYF(0));
777
610
 
778
611
  return(error);
779
612
}
780
613
 
781
 
static bool lockTableIfDifferent(Session &session,
782
 
                                 TableIdentifier &original_table_identifier,
783
 
                                 TableIdentifier &new_table_identifier,
784
 
                                 Table *name_lock)
785
 
{
786
 
  /* Check that we are not trying to rename to an existing table */
787
 
  if (not (original_table_identifier == new_table_identifier))
788
 
  {
789
 
    if (original_table_identifier.isTmp())
790
 
    {
791
 
 
792
 
      if (session.find_temporary_table(new_table_identifier))
793
 
      {
794
 
        std::string path;
795
 
        new_table_identifier.getSQLPath(path);
796
 
        my_error(ER_TABLE_EXISTS_ERROR, MYF(0), path.c_str());
797
 
        return false;
798
 
      }
799
 
    }
800
 
    else
801
 
    {
802
 
      if (session.lock_table_name_if_not_cached(new_table_identifier, &name_lock))
803
 
      {
804
 
        return false;
805
 
      }
806
 
 
807
 
      if (not name_lock)
808
 
      {
809
 
        std::string path;
810
 
        new_table_identifier.getSQLPath(path);
811
 
        my_error(ER_TABLE_EXISTS_ERROR, MYF(0), path.c_str());
812
 
        return false;
813
 
      }
814
 
 
815
 
      if (plugin::StorageEngine::doesTableExist(session, new_table_identifier))
816
 
      {
817
 
        std::string path;
818
 
        new_table_identifier.getSQLPath(path);
819
 
 
820
 
        /* Table will be closed by Session::executeCommand() */
821
 
        my_error(ER_TABLE_EXISTS_ERROR, MYF(0), path.c_str());
822
 
 
823
 
        table::Cache::singleton().mutex().lock(); /* ALTER TABLe */
824
 
        session.unlink_open_table(name_lock);
825
 
        table::Cache::singleton().mutex().unlock();
826
 
 
827
 
        return false;
828
 
      }
829
 
    }
830
 
  }
831
 
 
832
 
  return true;
833
 
}
834
 
 
835
614
/**
836
615
  Alter table
837
616
 
845
624
      table_list       The table to change.
846
625
      alter_info       Lists of fields, keys to be changed, added
847
626
                       or dropped.
848
 
      order_num        How many ORDER BY fields has been specified.
 
627
      order_num        How many order_st BY fields has been specified.
849
628
      order            List of fields to order_st BY.
850
629
      ignore           Whether we have ALTER IGNORE Table
851
630
 
873
652
    false  OK
874
653
    true   Error
875
654
*/
876
 
 
877
 
static bool internal_alter_table(Session *session,
878
 
                                 Table *table,
879
 
                                 TableIdentifier &original_table_identifier,
880
 
                                 TableIdentifier &new_table_identifier,
881
 
                                 HA_CREATE_INFO *create_info,
882
 
                                 const message::Table &original_proto,
883
 
                                 message::Table &create_proto,
884
 
                                 TableList *table_list,
885
 
                                 AlterInfo *alter_info,
886
 
                                 uint32_t order_num,
887
 
                                 Order *order,
888
 
                                 bool ignore)
 
655
bool alter_table(Session *session,
 
656
                 char *new_db,
 
657
                 char *new_name,
 
658
                 HA_CREATE_INFO *create_info,
 
659
                 message::Table *create_proto,
 
660
                 TableList *table_list,
 
661
                 AlterInfo *alter_info,
 
662
                 uint32_t order_num,
 
663
                 order_st *order,
 
664
                 bool ignore)
889
665
{
 
666
  Table *table;
 
667
  Table *new_table= NULL;
 
668
  Table *name_lock= NULL;
 
669
  string new_name_str;
890
670
  int error= 0;
891
671
  char tmp_name[80];
892
672
  char old_name[32];
 
673
  char new_name_buff[FN_REFLEN];
 
674
  char new_alias_buff[FN_REFLEN];
 
675
  char *table_name;
 
676
  char *db;
 
677
  const char *new_alias;
 
678
  char path[FN_REFLEN];
893
679
  ha_rows copied= 0;
894
680
  ha_rows deleted= 0;
895
 
 
896
 
  if (not original_table_identifier.isValid())
897
 
    return true;
898
 
 
899
 
  if (not new_table_identifier.isValid())
900
 
    return true;
 
681
  plugin::StorageEngine *old_db_type;
 
682
  plugin::StorageEngine *new_db_type;
 
683
  plugin::StorageEngine *save_old_db_type;
 
684
  bitset<32> tmp;
 
685
 
 
686
  new_name_buff[0]= '\0';
 
687
 
 
688
  if (table_list && table_list->schema_table)
 
689
  {
 
690
    my_error(ER_DBACCESS_DENIED_ERROR, MYF(0), "", "", INFORMATION_SCHEMA_NAME.c_str());
 
691
    return true;
 
692
  }
901
693
 
902
694
  session->set_proc_info("init");
903
695
 
 
696
  /*
 
697
    Assign variables table_name, new_name, db, new_db, path
 
698
    to simplify further comparisons: we want to see if it's a RENAME
 
699
    later just by comparing the pointers, avoiding the need for strcmp.
 
700
  */
 
701
  table_name= table_list->table_name;
 
702
  db= table_list->db;
 
703
  if (! new_db || ! my_strcasecmp(table_alias_charset, new_db, db))
 
704
    new_db= db;
 
705
 
 
706
  if (alter_info->tablespace_op != NO_TABLESPACE_OP)
 
707
  {
 
708
    /* DISCARD/IMPORT TABLESPACE is always alone in an ALTER Table */
 
709
    return mysql_discard_or_import_tablespace(session, table_list, alter_info->tablespace_op);
 
710
  }
 
711
 
 
712
  build_table_filename(path, sizeof(path), db, table_name, false);
 
713
 
 
714
  ostringstream oss;
 
715
  oss << drizzle_data_home << "/" << db << "/" << table_name;
 
716
 
 
717
  (void) unpack_filename(new_name_buff, oss.str().c_str());
 
718
 
 
719
  /*
 
720
    If this is just a rename of a view, short cut to the
 
721
    following scenario: 1) lock LOCK_open 2) do a RENAME
 
722
    2) unlock LOCK_open.
 
723
    This is a copy-paste added to make sure
 
724
    ALTER (sic:) Table .. RENAME works for views. ALTER VIEW is handled
 
725
    as an independent branch in mysql_execute_command. The need
 
726
    for a copy-paste arose because the main code flow of ALTER Table
 
727
    ... RENAME tries to use openTableLock, which does not work for views
 
728
    (openTableLock was never modified to merge table lists of child tables
 
729
    into the main table list, like open_tables does).
 
730
    This code is wrong and will be removed, please do not copy.
 
731
  */
 
732
 
 
733
  if (!(table= session->openTableLock(table_list, TL_WRITE_ALLOW_READ)))
 
734
    return true;
 
735
  
904
736
  table->use_all_columns();
905
737
 
906
 
  plugin::StorageEngine *new_engine;
907
 
  plugin::StorageEngine *original_engine;
908
 
 
909
 
  original_engine= table->getMutableShare()->getEngine();
910
 
 
911
 
  if (not create_info->db_type)
912
 
  {
913
 
    create_info->db_type= original_engine;
914
 
  }
915
 
  new_engine= create_info->db_type;
916
 
 
917
 
 
918
 
  create_proto.set_schema(new_table_identifier.getSchemaName());
919
 
  create_proto.set_type(new_table_identifier.getType());
920
 
 
921
 
  /**
922
 
    @todo Have a check on the table definition for FK in the future 
923
 
    to remove the need for the cursor. (aka can_switch_engines())
924
 
  */
925
 
  if (new_engine != original_engine &&
926
 
      not table->cursor->can_switch_engines())
 
738
  /* Check that we are not trying to rename to an existing table */
 
739
  if (new_name)
 
740
  {
 
741
    strcpy(new_name_buff, new_name);
 
742
    strcpy(new_alias_buff, new_name);
 
743
    new_alias= new_alias_buff;
 
744
 
 
745
    my_casedn_str(files_charset_info, new_name_buff);
 
746
    new_alias= new_name; // Create lower case table name
 
747
    my_casedn_str(files_charset_info, new_name);
 
748
 
 
749
    if (new_db == db &&
 
750
        ! my_strcasecmp(table_alias_charset, new_name_buff, table_name))
 
751
    {
 
752
      /*
 
753
        Source and destination table names are equal: make later check
 
754
        easier.
 
755
      */
 
756
      new_alias= new_name= table_name;
 
757
    }
 
758
    else
 
759
    {
 
760
      if (table->s->tmp_table != NO_TMP_TABLE)
 
761
      {
 
762
        if (session->find_temporary_table(new_db, new_name_buff))
 
763
        {
 
764
          my_error(ER_TABLE_EXISTS_ERROR, MYF(0), new_name_buff);
 
765
          return true;
 
766
        }
 
767
      }
 
768
      else
 
769
      {
 
770
        if (session->lock_table_name_if_not_cached(new_db, new_name, &name_lock))
 
771
          return true;
 
772
 
 
773
        if (! name_lock)
 
774
        {
 
775
          my_error(ER_TABLE_EXISTS_ERROR, MYF(0), new_alias);
 
776
          return true;
 
777
        }
 
778
 
 
779
        build_table_filename(new_name_buff, sizeof(new_name_buff), new_db, new_name_buff, false);
 
780
 
 
781
        if (plugin::StorageEngine::getTableDefinition(*session, new_name_buff, new_db, new_name_buff, false) == EEXIST)
 
782
        {
 
783
          /* Table will be closed by Session::executeCommand() */
 
784
          my_error(ER_TABLE_EXISTS_ERROR, MYF(0), new_alias);
 
785
          goto err;
 
786
        }
 
787
      }
 
788
    }
 
789
  }
 
790
  else
 
791
  {
 
792
    new_alias= table_name;
 
793
    new_name= table_name;
 
794
  }
 
795
 
 
796
  old_db_type= table->s->db_type();
 
797
  if (! create_info->db_type)
 
798
  {
 
799
    create_info->db_type= old_db_type;
 
800
  }
 
801
 
 
802
  if (table->s->tmp_table != NO_TMP_TABLE)
 
803
    create_info->options|= HA_LEX_CREATE_TMP_TABLE;
 
804
 
 
805
  if (check_engine(session, new_name, create_info))
 
806
    goto err;
 
807
 
 
808
  new_db_type= create_info->db_type;
 
809
 
 
810
  if (new_db_type != old_db_type &&
 
811
      !table->cursor->can_switch_engines())
927
812
  {
928
813
    assert(0);
929
814
    my_error(ER_ROW_IS_REFERENCED, MYF(0));
930
 
 
931
 
    return true;
 
815
    goto err;
932
816
  }
933
817
 
934
 
  if (original_engine->check_flag(HTON_BIT_ALTER_NOT_SUPPORTED) ||
935
 
      new_engine->check_flag(HTON_BIT_ALTER_NOT_SUPPORTED))
 
818
  if (create_info->row_type == ROW_TYPE_NOT_USED)
 
819
    create_info->row_type= table->s->row_type;
 
820
 
 
821
  if (old_db_type->check_flag(HTON_BIT_ALTER_NOT_SUPPORTED) ||
 
822
      new_db_type->check_flag(HTON_BIT_ALTER_NOT_SUPPORTED))
936
823
  {
937
 
    std::string path;
938
 
    new_table_identifier.getSQLPath(path);
939
 
    my_error(ER_ILLEGAL_HA, MYF(0), path.c_str());
940
 
 
941
 
    return true;
 
824
    my_error(ER_ILLEGAL_HA, MYF(0), table_name);
 
825
    goto err;
942
826
  }
943
827
 
944
828
  session->set_proc_info("setup");
945
 
 
 
829
  
946
830
  /*
947
831
   * test if no other bits except ALTER_RENAME and ALTER_KEYS_ONOFF are set
948
 
 */
 
832
   */
 
833
  tmp.set();
 
834
  tmp.reset(ALTER_RENAME);
 
835
  tmp.reset(ALTER_KEYS_ONOFF);
 
836
  tmp&= alter_info->flags;
 
837
  if (! (tmp.any()) &&
 
838
      ! table->s->tmp_table) // no need to touch frm
949
839
  {
950
 
    bitset<32> tmp;
951
 
 
952
 
    tmp.set();
953
 
    tmp.reset(ALTER_RENAME);
954
 
    tmp.reset(ALTER_KEYS_ONOFF);
955
 
    tmp&= alter_info->flags;
956
 
 
957
 
    if (! (tmp.any()) && ! table->getShare()->getType()) // no need to touch frm
958
 
    {
959
 
      switch (alter_info->keys_onoff)
960
 
      {
961
 
      case LEAVE_AS_IS:
962
 
        break;
963
 
      case ENABLE:
964
 
        /*
965
 
          wait_while_table_is_used() ensures that table being altered is
966
 
          opened only by this thread and that Table::TableShare::version
967
 
          of Table object corresponding to this table is 0.
968
 
          The latter guarantees that no DML statement will open this table
969
 
          until ALTER Table finishes (i.e. until close_thread_tables())
970
 
          while the fact that the table is still open gives us protection
971
 
          from concurrent DDL statements.
972
 
        */
973
 
        table::Cache::singleton().mutex().lock(); /* DDL wait for/blocker */
974
 
        wait_while_table_is_used(session, table, HA_EXTRA_FORCE_REOPEN);
975
 
        table::Cache::singleton().mutex().unlock();
976
 
        error= table->cursor->ha_enable_indexes(HA_KEY_SWITCH_NONUNIQ_SAVE);
977
 
        /* COND_refresh will be signaled in close_thread_tables() */
978
 
        break;
979
 
      case DISABLE:
980
 
        table::Cache::singleton().mutex().lock(); /* DDL wait for/blocker */
981
 
        wait_while_table_is_used(session, table, HA_EXTRA_FORCE_REOPEN);
982
 
        table::Cache::singleton().mutex().unlock();
983
 
        error=table->cursor->ha_disable_indexes(HA_KEY_SWITCH_NONUNIQ_SAVE);
984
 
        /* COND_refresh will be signaled in close_thread_tables() */
985
 
        break;
986
 
      default:
987
 
        assert(false);
988
 
        error= 0;
989
 
        break;
990
 
      }
991
 
 
992
 
      if (error == HA_ERR_WRONG_COMMAND)
993
 
      {
994
 
        error= 0;
995
 
        push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
996
 
                            ER_ILLEGAL_HA, ER(ER_ILLEGAL_HA),
997
 
                            table->getAlias());
998
 
      }
999
 
 
1000
 
      table::Cache::singleton().mutex().lock(); /* Lock to remove all instances of table from table cache before ALTER */
1001
 
      /*
1002
 
        Unlike to the above case close_cached_table() below will remove ALL
1003
 
        instances of Table from table cache (it will also remove table lock
1004
 
        held by this thread). So to make actual table renaming and writing
1005
 
        to binlog atomic we have to put them into the same critical section
1006
 
        protected by table::Cache::singleton().mutex() mutex. This also removes gap for races between
1007
 
        access() and mysql_rename_table() calls.
1008
 
      */
1009
 
 
1010
 
      if (error == 0 &&  not (original_table_identifier == new_table_identifier))
1011
 
      {
1012
 
        session->set_proc_info("rename");
1013
 
        /*
1014
 
          Then do a 'simple' rename of the table. First we need to close all
1015
 
          instances of 'source' table.
1016
 
        */
1017
 
        session->close_cached_table(table);
1018
 
        /*
1019
 
          Then, we want check once again that target table does not exist.
1020
 
          Actually the order of these two steps does not matter since
1021
 
          earlier we took name-lock on the target table, so we do them
1022
 
          in this particular order only to be consistent with 5.0, in which
1023
 
          we don't take this name-lock and where this order really matters.
1024
 
          @todo Investigate if we need this access() check at all.
1025
 
        */
1026
 
        if (plugin::StorageEngine::doesTableExist(*session, new_table_identifier))
1027
 
        {
1028
 
          std::string path;
1029
 
          new_table_identifier.getSQLPath(path);
1030
 
          my_error(ER_TABLE_EXISTS_ERROR, MYF(0), path.c_str());
 
840
    switch (alter_info->keys_onoff)
 
841
    {
 
842
    case LEAVE_AS_IS:
 
843
      break;
 
844
    case ENABLE:
 
845
      /*
 
846
        wait_while_table_is_used() ensures that table being altered is
 
847
        opened only by this thread and that Table::TableShare::version
 
848
        of Table object corresponding to this table is 0.
 
849
        The latter guarantees that no DML statement will open this table
 
850
        until ALTER Table finishes (i.e. until close_thread_tables())
 
851
        while the fact that the table is still open gives us protection
 
852
        from concurrent DDL statements.
 
853
      */
 
854
      pthread_mutex_lock(&LOCK_open); /* DDL wait for/blocker */
 
855
      wait_while_table_is_used(session, table, HA_EXTRA_FORCE_REOPEN);
 
856
      pthread_mutex_unlock(&LOCK_open);
 
857
      error= table->cursor->ha_enable_indexes(HA_KEY_SWITCH_NONUNIQ_SAVE);
 
858
      /* COND_refresh will be signaled in close_thread_tables() */
 
859
      break;
 
860
    case DISABLE:
 
861
      pthread_mutex_lock(&LOCK_open); /* DDL wait for/blocker */
 
862
      wait_while_table_is_used(session, table, HA_EXTRA_FORCE_REOPEN);
 
863
      pthread_mutex_unlock(&LOCK_open);
 
864
      error=table->cursor->ha_disable_indexes(HA_KEY_SWITCH_NONUNIQ_SAVE);
 
865
      /* COND_refresh will be signaled in close_thread_tables() */
 
866
      break;
 
867
    default:
 
868
      assert(false);
 
869
      error= 0;
 
870
      break;
 
871
    }
 
872
 
 
873
    if (error == HA_ERR_WRONG_COMMAND)
 
874
    {
 
875
      error= 0;
 
876
      push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
 
877
                          ER_ILLEGAL_HA, ER(ER_ILLEGAL_HA),
 
878
                          table->alias);
 
879
    }
 
880
 
 
881
    pthread_mutex_lock(&LOCK_open); /* Lock to remove all instances of table from table cache before ALTER */
 
882
    /*
 
883
      Unlike to the above case close_cached_table() below will remove ALL
 
884
      instances of Table from table cache (it will also remove table lock
 
885
      held by this thread). So to make actual table renaming and writing
 
886
      to binlog atomic we have to put them into the same critical section
 
887
      protected by LOCK_open mutex. This also removes gap for races between
 
888
      access() and mysql_rename_table() calls.
 
889
    */
 
890
 
 
891
    if (error == 0 && 
 
892
        (new_name != table_name || new_db != db))
 
893
    {
 
894
      session->set_proc_info("rename");
 
895
      /*
 
896
        Then do a 'simple' rename of the table. First we need to close all
 
897
        instances of 'source' table.
 
898
      */
 
899
      session->close_cached_table(table);
 
900
      /*
 
901
        Then, we want check once again that target table does not exist.
 
902
        Actually the order of these two steps does not matter since
 
903
        earlier we took name-lock on the target table, so we do them
 
904
        in this particular order only to be consistent with 5.0, in which
 
905
        we don't take this name-lock and where this order really matters.
 
906
        TODO: Investigate if we need this access() check at all.
 
907
      */
 
908
      if (plugin::StorageEngine::getTableDefinition(*session, new_name, db, table_name, false) == EEXIST)
 
909
      {
 
910
        my_error(ER_TABLE_EXISTS_ERROR, MYF(0), new_name);
 
911
        error= -1;
 
912
      }
 
913
      else
 
914
      {
 
915
        *fn_ext(new_name)= 0;
 
916
        if (mysql_rename_table(old_db_type, db, table_name, new_db, new_alias, 0))
1031
917
          error= -1;
1032
 
        }
1033
 
        else
1034
 
        {
1035
 
          if (mysql_rename_table(*session, original_engine, original_table_identifier, new_table_identifier))
1036
 
          {
1037
 
            error= -1;
1038
 
          }
1039
 
        }
1040
 
      }
1041
 
 
1042
 
      if (error == HA_ERR_WRONG_COMMAND)
1043
 
      {
1044
 
        error= 0;
1045
 
        push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
1046
 
                            ER_ILLEGAL_HA, ER(ER_ILLEGAL_HA),
1047
 
                            table->getAlias());
1048
 
      }
1049
 
 
1050
 
      if (error == 0)
1051
 
      {
1052
 
        TransactionServices &transaction_services= TransactionServices::singleton();
1053
 
        transaction_services.allocateNewTransactionId();
1054
 
        write_bin_log(session, *session->getQueryString());
1055
 
        session->my_ok();
1056
 
      }
1057
 
      else if (error > 0)
1058
 
      {
1059
 
        table->print_error(error, MYF(0));
1060
 
        error= -1;
1061
 
      }
1062
 
 
1063
 
      table::Cache::singleton().mutex().unlock();
1064
 
      table_list->table= NULL;
1065
 
 
1066
 
      return error;
1067
 
    }
 
918
      }
 
919
    }
 
920
 
 
921
    if (error == HA_ERR_WRONG_COMMAND)
 
922
    {
 
923
      error= 0;
 
924
      push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
 
925
                          ER_ILLEGAL_HA, ER(ER_ILLEGAL_HA),
 
926
                          table->alias);
 
927
    }
 
928
 
 
929
    if (error == 0)
 
930
    {
 
931
      write_bin_log(session, session->query, session->query_length);
 
932
      session->my_ok();
 
933
    }
 
934
    else if (error > 0)
 
935
    {
 
936
      table->cursor->print_error(error, MYF(0));
 
937
      error= -1;
 
938
    }
 
939
 
 
940
    if (name_lock)
 
941
      session->unlink_open_table(name_lock);
 
942
 
 
943
    pthread_mutex_unlock(&LOCK_open);
 
944
    table_list->table= NULL;
 
945
    return error;
1068
946
  }
1069
947
 
1070
948
  /* We have to do full alter table. */
1071
 
  new_engine= create_info->db_type;
1072
 
 
1073
 
  if (mysql_prepare_alter_table(session, table, create_info, original_proto, create_proto, alter_info))
1074
 
  {
1075
 
    return true;
1076
 
  }
1077
 
 
1078
 
  set_table_default_charset(create_info, new_table_identifier.getSchemaName().c_str());
 
949
 
 
950
  /*
 
951
    If the old table had partitions and we are doing ALTER Table ...
 
952
    engine= <new_engine>, the new table must preserve the original
 
953
    partitioning. That means that the new engine is still the
 
954
    partitioning engine, not the engine specified in the parser.
 
955
    This is discovered  in prep_alter_part_table, which in such case
 
956
    updates create_info->db_type.
 
957
    Now we need to update the stack copy of create_info->db_type,
 
958
    as otherwise we won't be able to correctly move the files of the
 
959
    temporary table to the result table files.
 
960
  */
 
961
  new_db_type= create_info->db_type;
 
962
 
 
963
  if (mysql_prepare_alter_table(session, table, create_info, create_proto,
 
964
                                alter_info))
 
965
      goto err;
 
966
 
 
967
  set_table_default_charset(create_info, db);
1079
968
 
1080
969
  alter_info->build_method= HA_BUILD_OFFLINE;
1081
970
 
1082
971
  snprintf(tmp_name, sizeof(tmp_name), "%s-%lx_%"PRIx64, TMP_FILE_PREFIX, (unsigned long) current_pid, session->thread_id);
 
972
  
 
973
  /* Safety fix for innodb */
 
974
  my_casedn_str(files_charset_info, tmp_name);
1083
975
 
1084
976
  /* Create a temporary table with the new format */
1085
 
  /**
1086
 
    @note we make an internal temporary table unless the table is a temporary table. In last
1087
 
    case we just use it as is. Neither of these tables require locks in order to  be
1088
 
    filled.
1089
 
  */
1090
 
  TableIdentifier new_table_as_temporary(original_table_identifier.getSchemaName(),
1091
 
                                         tmp_name,
1092
 
                                         create_proto.type() != message::Table::TEMPORARY ? message::Table::INTERNAL :
1093
 
                                         message::Table::TEMPORARY);
1094
 
 
1095
 
  error= create_temporary_table(session, new_table_as_temporary, create_info, create_proto, alter_info);
1096
 
 
 
977
  error= create_temporary_table(session, table, new_db, tmp_name, create_info, create_proto, alter_info);
1097
978
  if (error != 0)
1098
 
  {
1099
 
    return true;
1100
 
  }
 
979
    goto err;
1101
980
 
1102
981
  /* Open the table so we need to copy the data to it. */
1103
 
  Table *new_table= open_alter_table(session, table, new_table_as_temporary);
1104
 
 
1105
 
 
1106
 
  if (not new_table)
1107
 
  {
1108
 
    plugin::StorageEngine::dropTable(*session, new_table_as_temporary);
1109
 
    return true;
1110
 
  }
 
982
  if (table->s->tmp_table)
 
983
  {
 
984
    TableList tbl;
 
985
    tbl.db= new_db;
 
986
    tbl.alias= tmp_name;
 
987
    tbl.table_name= tmp_name;
 
988
 
 
989
    /* Table is in session->temporary_tables */
 
990
    new_table= session->openTable(&tbl, (bool*) 0, DRIZZLE_LOCK_IGNORE_FLUSH);
 
991
  }
 
992
  else
 
993
  {
 
994
    char tmp_path[FN_REFLEN];
 
995
    /* table is a normal table: Create temporary table in same directory */
 
996
    build_table_filename(tmp_path, sizeof(tmp_path), new_db, tmp_name, true);
 
997
    /* Open our intermediate table */
 
998
    new_table= session->open_temporary_table(tmp_path, new_db, tmp_name, false);
 
999
  }
 
1000
 
 
1001
  if (new_table == NULL)
 
1002
    goto err1;
1111
1003
 
1112
1004
  /* Copy the data if necessary. */
1113
 
  {
1114
 
    /* We must not ignore bad input! */
1115
 
    session->count_cuted_fields= CHECK_FIELD_ERROR_FOR_NULL;    // calc cuted fields
1116
 
    session->cuted_fields= 0L;
1117
 
    session->set_proc_info("copy to tmp table");
1118
 
    copied= deleted= 0;
1119
 
 
1120
 
    /* We don't want update TIMESTAMP fields during ALTER Table. */
1121
 
    new_table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
1122
 
    new_table->next_number_field= new_table->found_next_number_field;
1123
 
    error= copy_data_between_tables(session,
1124
 
                                    table,
1125
 
                                    new_table,
1126
 
                                    alter_info->create_list,
1127
 
                                    ignore,
1128
 
                                    order_num,
1129
 
                                    order,
1130
 
                                    &copied,
1131
 
                                    &deleted,
1132
 
                                    alter_info->keys_onoff,
1133
 
                                    alter_info->error_if_not_empty);
1134
 
 
1135
 
    /* We must not ignore bad input! */
1136
 
    assert(session->count_cuted_fields == CHECK_FIELD_ERROR_FOR_NULL);
1137
 
  }
1138
 
 
1139
 
  /* Now we need to resolve what just happened with the data copy. */
1140
 
 
1141
 
  if (error)
1142
 
  {
1143
 
 
1144
 
    /*
1145
 
      No default value was provided for a DATE/DATETIME field, the
1146
 
      current sql_mode doesn't allow the '0000-00-00' value and
1147
 
      the table to be altered isn't empty.
1148
 
      Report error here.
1149
 
    */
1150
 
    if (alter_info->error_if_not_empty && session->row_count)
1151
 
    {
1152
 
      my_error(ER_INVALID_ALTER_TABLE_FOR_NOT_NULL, MYF(0));
1153
 
    }
1154
 
 
1155
 
    if (original_table_identifier.isTmp())
1156
 
    {
1157
 
      if (new_table)
1158
 
      {
1159
 
        /* close_temporary_table() frees the new_table pointer. */
1160
 
        session->close_temporary_table(new_table);
1161
 
      }
1162
 
      else
1163
 
      {
1164
 
        plugin::StorageEngine::dropTable(*session, new_table_as_temporary);
1165
 
      }
1166
 
 
1167
 
      return true;
1168
 
    }
1169
 
    else
1170
 
    {
1171
 
      if (new_table)
1172
 
      {
1173
 
        /*
1174
 
          Close the intermediate table that will be the new table.
1175
 
          Note that MERGE tables do not have their children attached here.
1176
 
        */
1177
 
        new_table->intern_close_table();
1178
 
        if (new_table->hasShare())
1179
 
        {
1180
 
          delete new_table->getMutableShare();
1181
 
        }
1182
 
 
1183
 
        delete new_table;
1184
 
      }
1185
 
 
1186
 
      table::Cache::singleton().mutex().lock(); /* ALTER TABLE */
1187
 
 
1188
 
      plugin::StorageEngine::dropTable(*session, new_table_as_temporary);
1189
 
      table::Cache::singleton().mutex().unlock();
1190
 
 
1191
 
      return true;
1192
 
    }
1193
 
  }
1194
 
  // Temporary table and success
1195
 
  else if (original_table_identifier.isTmp())
1196
 
  {
 
1005
  session->count_cuted_fields= CHECK_FIELD_WARN;        // calc cuted fields
 
1006
  session->cuted_fields= 0L;
 
1007
  session->set_proc_info("copy to tmp table");
 
1008
  copied= deleted= 0;
 
1009
 
 
1010
  assert(new_table);
 
1011
 
 
1012
  /* We don't want update TIMESTAMP fields during ALTER Table. */
 
1013
  new_table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
 
1014
  new_table->next_number_field= new_table->found_next_number_field;
 
1015
  error= copy_data_between_tables(table, 
 
1016
                                  new_table,
 
1017
                                  alter_info->create_list, 
 
1018
                                  ignore,
 
1019
                                  order_num, 
 
1020
                                  order, 
 
1021
                                  &copied, 
 
1022
                                  &deleted,
 
1023
                                  alter_info->keys_onoff,
 
1024
                                  alter_info->error_if_not_empty);
 
1025
 
 
1026
  /* We must not ignore bad input! */
 
1027
  session->count_cuted_fields= CHECK_FIELD_ERROR_FOR_NULL;
 
1028
 
 
1029
  if (table->s->tmp_table != NO_TMP_TABLE)
 
1030
  {
 
1031
    /* We changed a temporary table */
 
1032
    if (error)
 
1033
      goto err1;
 
1034
 
1197
1035
    /* Close lock if this is a transactional table */
1198
1036
    if (session->lock)
1199
1037
    {
1200
 
      session->unlockTables(session->lock);
 
1038
      mysql_unlock_tables(session, session->lock);
1201
1039
      session->lock= 0;
1202
1040
    }
1203
1041
 
1204
1042
    /* Remove link to old table and rename the new one */
1205
 
    session->close_temporary_table(table);
 
1043
    session->close_temporary_table(table, true, true);
1206
1044
 
1207
1045
    /* Should pass the 'new_name' as we store table name in the cache */
1208
 
    new_table->getMutableShare()->setIdentifier(new_table_identifier);
1209
 
 
1210
 
    new_table_identifier.setPath(new_table_as_temporary.getPath());
1211
 
 
1212
 
    if (mysql_rename_table(*session, new_engine, new_table_as_temporary, new_table_identifier) != 0)
1213
 
    {
1214
 
      return true;
1215
 
    }
1216
 
  }
1217
 
  // Normal table success
 
1046
    if (new_table->rename_temporary_table(new_db, new_name))
 
1047
      goto err1;
 
1048
    
 
1049
    goto end_temporary;
 
1050
  }
 
1051
 
 
1052
  if (new_table)
 
1053
  {
 
1054
    /*
 
1055
      Close the intermediate table that will be the new table.
 
1056
      Note that MERGE tables do not have their children attached here.
 
1057
    */
 
1058
    new_table->intern_close_table();
 
1059
    free(new_table);
 
1060
  }
 
1061
 
 
1062
  pthread_mutex_lock(&LOCK_open); /* ALTER TABLE */
 
1063
  
 
1064
  if (error)
 
1065
  {
 
1066
    quick_rm_table(*session, new_db, tmp_name, true);
 
1067
    pthread_mutex_unlock(&LOCK_open);
 
1068
    goto err;
 
1069
  }
 
1070
 
 
1071
  /*
 
1072
    Data is copied. Now we:
 
1073
    1) Wait until all other threads close old version of table.
 
1074
    2) Close instances of table open by this thread and replace them
 
1075
       with exclusive name-locks.
 
1076
    3) Rename the old table to a temp name, rename the new one to the
 
1077
       old name.
 
1078
    4) If we are under LOCK TABLES and don't do ALTER Table ... RENAME
 
1079
       we reopen new version of table.
 
1080
    5) Write statement to the binary log.
 
1081
    6) If we are under LOCK TABLES and do ALTER Table ... RENAME we
 
1082
       remove name-locks from list of open tables and table cache.
 
1083
    7) If we are not not under LOCK TABLES we rely on close_thread_tables()
 
1084
       call to remove name-locks from table cache and list of open table.
 
1085
  */
 
1086
 
 
1087
  session->set_proc_info("rename result table");
 
1088
 
 
1089
  snprintf(old_name, sizeof(old_name), "%s2-%lx-%"PRIx64, TMP_FILE_PREFIX, (unsigned long) current_pid, session->thread_id);
 
1090
 
 
1091
  my_casedn_str(files_charset_info, old_name);
 
1092
 
 
1093
  wait_while_table_is_used(session, table, HA_EXTRA_PREPARE_FOR_RENAME);
 
1094
  session->close_data_files_and_morph_locks(db, table_name);
 
1095
 
 
1096
  error= 0;
 
1097
  save_old_db_type= old_db_type;
 
1098
 
 
1099
  /*
 
1100
    This leads to the storage engine (SE) not being notified for renames in
 
1101
    mysql_rename_table(), because we just juggle with the FRM and nothing
 
1102
    more. If we have an intermediate table, then we notify the SE that
 
1103
    it should become the actual table. Later, we will recycle the old table.
 
1104
    However, in case of ALTER Table RENAME there might be no intermediate
 
1105
    table. This is when the old and new tables are compatible, according to
 
1106
    compare_table(). Then, we need one additional call to
 
1107
    mysql_rename_table() with flag NO_FRM_RENAME, which does nothing else but
 
1108
    actual rename in the SE and the FRM is not touched. Note that, if the
 
1109
    table is renamed and the SE is also changed, then an intermediate table
 
1110
    is created and the additional call will not take place.
 
1111
  */
 
1112
  if (mysql_rename_table(old_db_type, db, table_name, db, old_name, FN_TO_IS_TMP))
 
1113
  {
 
1114
    error= 1;
 
1115
    quick_rm_table(*session, new_db, tmp_name, true);
 
1116
  }
1218
1117
  else
1219
1118
  {
1220
 
    if (new_table)
1221
 
    {
1222
 
      /*
1223
 
        Close the intermediate table that will be the new table.
1224
 
        Note that MERGE tables do not have their children attached here.
1225
 
      */
1226
 
      new_table->intern_close_table();
1227
 
 
1228
 
      if (new_table->hasShare())
1229
 
      {
1230
 
        delete new_table->getMutableShare();
1231
 
      }
1232
 
 
1233
 
      delete new_table;
1234
 
    }
1235
 
 
1236
 
    table::Cache::singleton().mutex().lock(); /* ALTER TABLE */
1237
 
 
1238
 
    /*
1239
 
      Data is copied. Now we:
1240
 
      1) Wait until all other threads close old version of table.
1241
 
      2) Close instances of table open by this thread and replace them
1242
 
      with exclusive name-locks.
1243
 
      3) Rename the old table to a temp name, rename the new one to the
1244
 
      old name.
1245
 
      4) If we are under LOCK TABLES and don't do ALTER Table ... RENAME
1246
 
      we reopen new version of table.
1247
 
      5) Write statement to the binary log.
1248
 
      6) If we are under LOCK TABLES and do ALTER Table ... RENAME we
1249
 
      remove name-locks from list of open tables and table cache.
1250
 
      7) If we are not not under LOCK TABLES we rely on close_thread_tables()
1251
 
      call to remove name-locks from table cache and list of open table.
1252
 
    */
1253
 
 
1254
 
    session->set_proc_info("rename result table");
1255
 
 
1256
 
    snprintf(old_name, sizeof(old_name), "%s2-%lx-%"PRIx64, TMP_FILE_PREFIX, (unsigned long) current_pid, session->thread_id);
1257
 
 
1258
 
    my_casedn_str(files_charset_info, old_name);
1259
 
 
1260
 
    wait_while_table_is_used(session, table, HA_EXTRA_PREPARE_FOR_RENAME);
1261
 
    session->close_data_files_and_morph_locks(original_table_identifier);
1262
 
 
1263
 
    error= 0;
1264
 
 
1265
 
    /*
1266
 
      This leads to the storage engine (SE) not being notified for renames in
1267
 
      mysql_rename_table(), because we just juggle with the FRM and nothing
1268
 
      more. If we have an intermediate table, then we notify the SE that
1269
 
      it should become the actual table. Later, we will recycle the old table.
1270
 
      However, in case of ALTER Table RENAME there might be no intermediate
1271
 
      table. This is when the old and new tables are compatible, according to
1272
 
      compare_table(). Then, we need one additional call to
1273
 
    */
1274
 
    TableIdentifier original_table_to_drop(original_table_identifier.getSchemaName(),
1275
 
                                           old_name, create_proto.type() != message::Table::TEMPORARY ? message::Table::INTERNAL :
1276
 
                                         message::Table::TEMPORARY);
1277
 
 
1278
 
    if (mysql_rename_table(*session, original_engine, original_table_identifier, original_table_to_drop))
1279
 
    {
 
1119
    if (mysql_rename_table(new_db_type, new_db, tmp_name, new_db, new_alias, FN_FROM_IS_TMP) != 0)
 
1120
    {
 
1121
      /* Try to get everything back. */
1280
1122
      error= 1;
1281
 
      plugin::StorageEngine::dropTable(*session, new_table_as_temporary);
 
1123
      quick_rm_table(*session, new_db, new_alias, false);
 
1124
      quick_rm_table(*session, new_db, tmp_name, true);
 
1125
      mysql_rename_table(old_db_type, db, old_name, db, table_name, FN_FROM_IS_TMP);
 
1126
    }
 
1127
  }
 
1128
 
 
1129
  if (error)
 
1130
  {
 
1131
    /* This shouldn't happen. But let us play it safe. */
 
1132
    goto err_with_placeholders;
 
1133
  }
 
1134
 
 
1135
  quick_rm_table(*session, db, old_name, true);
 
1136
 
 
1137
  pthread_mutex_unlock(&LOCK_open);
 
1138
 
 
1139
  session->set_proc_info("end");
 
1140
 
 
1141
  write_bin_log(session, session->query, session->query_length);
 
1142
 
 
1143
  if (old_db_type->check_flag(HTON_BIT_FLUSH_AFTER_RENAME))
 
1144
  {
 
1145
    /*
 
1146
      For the alter table to be properly flushed to the logs, we
 
1147
      have to open the new table.  If not, we get a problem on server
 
1148
      shutdown. But we do not need to attach MERGE children.
 
1149
    */
 
1150
    char table_path[FN_REFLEN];
 
1151
    Table *t_table;
 
1152
    build_table_filename(table_path, sizeof(table_path), new_db, table_name, false);
 
1153
    t_table= session->open_temporary_table(table_path, new_db, tmp_name, false);
 
1154
    if (t_table)
 
1155
    {
 
1156
      t_table->intern_close_table();
 
1157
      free(t_table);
1282
1158
    }
1283
1159
    else
1284
 
    {
1285
 
      if (mysql_rename_table(*session, new_engine, new_table_as_temporary, new_table_identifier) != 0)
1286
 
      {
1287
 
        /* Try to get everything back. */
1288
 
        error= 1;
1289
 
 
1290
 
        plugin::StorageEngine::dropTable(*session, new_table_identifier);
1291
 
 
1292
 
        plugin::StorageEngine::dropTable(*session, new_table_as_temporary);
1293
 
 
1294
 
        mysql_rename_table(*session, original_engine, original_table_to_drop, original_table_identifier);
1295
 
      }
1296
 
      else
1297
 
      {
1298
 
        plugin::StorageEngine::dropTable(*session, original_table_to_drop);
1299
 
      }
1300
 
    }
1301
 
 
1302
 
    if (error)
1303
 
    {
1304
 
      /*
1305
 
        An error happened while we were holding exclusive name-lock on table
1306
 
        being altered. To be safe under LOCK TABLES we should remove placeholders
1307
 
        from list of open tables list and table cache.
1308
 
      */
1309
 
      session->unlink_open_table(table);
1310
 
      table::Cache::singleton().mutex().unlock();
1311
 
 
1312
 
      return true;
1313
 
    }
1314
 
 
1315
 
    table::Cache::singleton().mutex().unlock();
1316
 
 
1317
 
    session->set_proc_info("end");
1318
 
 
1319
 
    write_bin_log(session, *session->getQueryString());
1320
 
    table_list->table= NULL;
 
1160
      errmsg_printf(ERRMSG_LVL_WARN, _("Could not open table %s.%s after rename\n"), new_db, table_name);
 
1161
 
 
1162
    plugin::StorageEngine::flushLogs(old_db_type);
1321
1163
  }
 
1164
  table_list->table= NULL;
1322
1165
 
 
1166
end_temporary:
1323
1167
  /*
1324
1168
   * Field::store() may have called my_error().  If this is 
1325
1169
   * the case, we must not send an ok packet, since 
1326
1170
   * Diagnostics_area::is_set() will fail an assert.
1327
 
 */
1328
 
  if (session->is_error())
 
1171
   */
 
1172
  if (! session->is_error())
 
1173
  {
 
1174
    snprintf(tmp_name, sizeof(tmp_name), ER(ER_INSERT_INFO),
 
1175
            (ulong) (copied + deleted), (ulong) deleted,
 
1176
            (ulong) session->cuted_fields);
 
1177
    session->my_ok(copied + deleted, 0, 0L, tmp_name);
 
1178
    session->some_tables_deleted=0;
 
1179
    return false;
 
1180
  }
 
1181
  else
1329
1182
  {
1330
1183
    /* my_error() was called.  Return true (which means error...) */
1331
1184
    return true;
1332
1185
  }
1333
1186
 
1334
 
  snprintf(tmp_name, sizeof(tmp_name), ER(ER_INSERT_INFO),
1335
 
           (ulong) (copied + deleted), (ulong) deleted,
1336
 
           (ulong) session->cuted_fields);
1337
 
  session->my_ok(copied + deleted, 0, 0L, tmp_name);
1338
 
  session->some_tables_deleted= 0;
1339
 
 
1340
 
  return false;
1341
 
}
1342
 
 
1343
 
bool alter_table(Session *session,
1344
 
                 TableIdentifier &original_table_identifier,
1345
 
                 TableIdentifier &new_table_identifier,
1346
 
                 HA_CREATE_INFO *create_info,
1347
 
                 const message::Table &original_proto,
1348
 
                 message::Table &create_proto,
1349
 
                 TableList *table_list,
1350
 
                 AlterInfo *alter_info,
1351
 
                 uint32_t order_num,
1352
 
                 Order *order,
1353
 
                 bool ignore)
1354
 
{
1355
 
  bool error;
1356
 
  Table *table;
1357
 
 
1358
 
  if (alter_info->tablespace_op != NO_TABLESPACE_OP)
1359
 
  {
1360
 
    /* DISCARD/IMPORT TABLESPACE is always alone in an ALTER Table */
1361
 
    return mysql_discard_or_import_tablespace(session, table_list, alter_info->tablespace_op);
1362
 
  }
1363
 
 
1364
 
  session->set_proc_info("init");
1365
 
 
1366
 
  if (not (table= session->openTableLock(table_list, TL_WRITE_ALLOW_READ)))
1367
 
    return true;
1368
 
 
1369
 
  session->set_proc_info("gained write lock on table");
1370
 
 
1371
 
  /* 
1372
 
    Check that we are not trying to rename to an existing table,
1373
 
    if one existed we get a lock, if we can't we error.
1374
 
  */
1375
 
  {
1376
 
    Table *name_lock= NULL;
1377
 
 
1378
 
    if (not lockTableIfDifferent(*session, original_table_identifier, new_table_identifier, name_lock))
1379
 
    {
1380
 
      return true;
1381
 
    }
1382
 
 
1383
 
    error= internal_alter_table(session,
1384
 
                                table,
1385
 
                                original_table_identifier,
1386
 
                                new_table_identifier,
1387
 
                                create_info,
1388
 
                                original_proto,
1389
 
                                create_proto,
1390
 
                                table_list,
1391
 
                                alter_info,
1392
 
                                order_num,
1393
 
                                order,
1394
 
                                ignore);
1395
 
 
1396
 
    if (name_lock)
1397
 
    {
1398
 
      table::Cache::singleton().mutex().lock(); /* ALTER TABLe */
1399
 
      session->unlink_open_table(name_lock);
1400
 
      table::Cache::singleton().mutex().unlock();
1401
 
    }
1402
 
  }
1403
 
 
1404
 
  return error;
 
1187
err1:
 
1188
  if (new_table)
 
1189
  {
 
1190
    /* close_temporary_table() frees the new_table pointer. */
 
1191
    session->close_temporary_table(new_table, true, true);
 
1192
  }
 
1193
  else
 
1194
    quick_rm_table(*session, new_db, tmp_name, true);
 
1195
 
 
1196
err:
 
1197
  /*
 
1198
    No default value was provided for a DATE/DATETIME field, the
 
1199
    current sql_mode doesn't allow the '0000-00-00' value and
 
1200
    the table to be altered isn't empty.
 
1201
    Report error here.
 
1202
  */
 
1203
  if (alter_info->error_if_not_empty && session->row_count)
 
1204
  {
 
1205
    const char *f_val= 0;
 
1206
    enum enum_drizzle_timestamp_type t_type= DRIZZLE_TIMESTAMP_DATE;
 
1207
    switch (alter_info->datetime_field->sql_type)
 
1208
    {
 
1209
      case DRIZZLE_TYPE_DATE:
 
1210
        f_val= "0000-00-00";
 
1211
        t_type= DRIZZLE_TIMESTAMP_DATE;
 
1212
        break;
 
1213
      case DRIZZLE_TYPE_DATETIME:
 
1214
        f_val= "0000-00-00 00:00:00";
 
1215
        t_type= DRIZZLE_TIMESTAMP_DATETIME;
 
1216
        break;
 
1217
      default:
 
1218
        /* Shouldn't get here. */
 
1219
        assert(0);
 
1220
    }
 
1221
    bool save_abort_on_warning= session->abort_on_warning;
 
1222
    session->abort_on_warning= true;
 
1223
    make_truncated_value_warning(session, DRIZZLE_ERROR::WARN_LEVEL_ERROR,
 
1224
                                 f_val, strlength(f_val), t_type,
 
1225
                                 alter_info->datetime_field->field_name);
 
1226
    session->abort_on_warning= save_abort_on_warning;
 
1227
  }
 
1228
  if (name_lock)
 
1229
  {
 
1230
    pthread_mutex_lock(&LOCK_open); /* ALTER TABLe */
 
1231
    session->unlink_open_table(name_lock);
 
1232
    pthread_mutex_unlock(&LOCK_open);
 
1233
  }
 
1234
  return true;
 
1235
 
 
1236
err_with_placeholders:
 
1237
  /*
 
1238
    An error happened while we were holding exclusive name-lock on table
 
1239
    being altered. To be safe under LOCK TABLES we should remove placeholders
 
1240
    from list of open tables list and table cache.
 
1241
  */
 
1242
  session->unlink_open_table(table);
 
1243
  if (name_lock)
 
1244
    session->unlink_open_table(name_lock);
 
1245
  pthread_mutex_unlock(&LOCK_open);
 
1246
  return true;
1405
1247
}
1406
1248
/* alter_table */
1407
1249
 
1408
1250
static int
1409
 
copy_data_between_tables(Session *session,
1410
 
                         Table *from, Table *to,
1411
 
                         List<CreateField> &create,
 
1251
copy_data_between_tables(Table *from,Table *to,
 
1252
                         List<CreateField> &create,
1412
1253
                         bool ignore,
1413
 
                         uint32_t order_num, Order *order,
1414
 
                         ha_rows *copied,
1415
 
                         ha_rows *deleted,
 
1254
                         uint32_t order_num, order_st *order,
 
1255
                         ha_rows *copied,
 
1256
                         ha_rows *deleted,
1416
1257
                         enum enum_enable_or_disable keys_onoff,
1417
1258
                         bool error_if_not_empty)
1418
1259
{
1419
 
  int error= 0;
 
1260
  int error;
1420
1261
  CopyField *copy,*copy_end;
1421
1262
  ulong found_count,delete_count;
 
1263
  Session *session= current_session;
1422
1264
  uint32_t length= 0;
1423
 
  SortField *sortorder;
1424
 
  ReadRecord info;
 
1265
  SORT_FIELD *sortorder;
 
1266
  READ_RECORD info;
1425
1267
  TableList   tables;
1426
1268
  List<Item>   fields;
1427
1269
  List<Item>   all_fields;
1435
1277
 
1436
1278
    This needs to be done before external_lock
1437
1279
  */
1438
 
  TransactionServices &transaction_services= TransactionServices::singleton();
1439
 
 
1440
 
  /* 
1441
 
   * LP Bug #552420 
1442
 
   *
1443
 
   * Since open_temporary_table() doesn't invoke lockTables(), we
1444
 
   * don't get the usual automatic call to StorageEngine::startStatement(), so
1445
 
   * we manually call it here...
1446
 
   */
1447
 
  to->getMutableShare()->getEngine()->startStatement(session);
1448
 
 
1449
 
  if (!(copy= new CopyField[to->getShare()->sizeFields()]))
 
1280
  error= ha_enable_transaction(session, false);
 
1281
  if (error)
 
1282
    return -1;
 
1283
 
 
1284
  if (!(copy= new CopyField[to->s->fields]))
1450
1285
    return -1;
1451
1286
 
1452
1287
  if (to->cursor->ha_external_lock(session, F_WRLCK))
1453
1288
    return -1;
1454
1289
 
1455
1290
  /* We need external lock before we can disable/enable keys */
1456
 
  alter_table_manage_keys(session, to, from->cursor->indexes_are_disabled(), keys_onoff);
 
1291
  alter_table_manage_keys(to, from->cursor->indexes_are_disabled(), keys_onoff);
1457
1292
 
1458
1293
  /* We can abort alter table for any table type */
1459
1294
  session->abort_on_warning= !ignore;
1464
1299
  List_iterator<CreateField> it(create);
1465
1300
  CreateField *def;
1466
1301
  copy_end=copy;
1467
 
  for (Field **ptr= to->getFields(); *ptr ; ptr++)
 
1302
  for (Field **ptr=to->field ; *ptr ; ptr++)
1468
1303
  {
1469
1304
    def=it++;
1470
1305
    if (def->field)
1481
1316
 
1482
1317
  if (order)
1483
1318
  {
1484
 
    if (to->getShare()->hasPrimaryKey() && to->cursor->primary_key_is_clustered())
 
1319
    if (to->s->primary_key != MAX_KEY && to->cursor->primary_key_is_clustered())
1485
1320
    {
1486
1321
      char warn_buff[DRIZZLE_ERRMSG_SIZE];
1487
1322
      snprintf(warn_buff, sizeof(warn_buff),
1488
1323
               _("order_st BY ignored because there is a user-defined clustered "
1489
1324
                 "index in the table '%-.192s'"),
1490
 
               from->getMutableShare()->getTableName());
 
1325
               from->s->table_name.str);
1491
1326
      push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_WARN, ER_UNKNOWN_ERROR,
1492
1327
                   warn_buff);
1493
1328
    }
1494
1329
    else
1495
1330
    {
1496
 
      FileSort filesort(*session);
1497
 
      from->sort.io_cache= new internal::IO_CACHE;
 
1331
      from->sort.io_cache= new IO_CACHE;
 
1332
      memset(from->sort.io_cache, 0, sizeof(IO_CACHE));
1498
1333
 
1499
1334
      memset(&tables, 0, sizeof(tables));
1500
1335
      tables.table= from;
1501
 
      tables.setTableName(const_cast<char *>(from->getMutableShare()->getTableName()));
1502
 
      tables.alias= const_cast<char *>(tables.getTableName());
1503
 
      tables.setSchemaName(const_cast<char *>(from->getMutableShare()->getSchemaName()));
 
1336
      tables.alias= tables.table_name= from->s->table_name.str;
 
1337
      tables.db= from->s->db.str;
1504
1338
      error= 1;
1505
1339
 
1506
1340
      if (session->lex->select_lex.setup_ref_array(session, order_num) ||
1507
1341
          setup_order(session, session->lex->select_lex.ref_pointer_array,
1508
1342
                      &tables, fields, all_fields, order) ||
1509
1343
          !(sortorder= make_unireg_sortorder(order, &length, NULL)) ||
1510
 
          (from->sort.found_records= filesort.run(from, sortorder, length,
1511
 
                                                  (optimizer::SqlSelect *) 0, HA_POS_ERROR,
1512
 
                                                  1, examined_rows)) == HA_POS_ERROR)
1513
 
      {
 
1344
          (from->sort.found_records= filesort(session, from, sortorder, length,
 
1345
                                              (SQL_SELECT *) 0, HA_POS_ERROR,
 
1346
                                              1, &examined_rows)) ==
 
1347
          HA_POS_ERROR)
1514
1348
        goto err;
1515
 
      }
1516
1349
    }
1517
 
  }
 
1350
  };
1518
1351
 
1519
1352
  /* Tell handler that we have values for all columns in the to table */
1520
1353
  to->use_all_columns();
1521
 
  info.init_read_record(session, from, (optimizer::SqlSelect *) 0, 1, true);
 
1354
  init_read_record(&info, session, from, (SQL_SELECT *) 0, 1,1);
1522
1355
  if (ignore)
1523
1356
    to->cursor->extra(HA_EXTRA_IGNORE_DUP_KEY);
1524
1357
  session->row_count= 0;
1525
1358
  to->restoreRecordAsDefault();        // Create empty record
1526
1359
  while (!(error=info.read_record(&info)))
1527
1360
  {
1528
 
    if (session->getKilled())
 
1361
    if (session->killed)
1529
1362
    {
1530
1363
      session->send_kill_message();
1531
1364
      error= 1;
1546
1379
        to->next_number_field->reset();
1547
1380
    }
1548
1381
 
1549
 
    for (CopyField *copy_ptr= copy; copy_ptr != copy_end ; copy_ptr++)
 
1382
    for (CopyField *copy_ptr=copy ; copy_ptr != copy_end ; copy_ptr++)
1550
1383
    {
1551
 
      if (not copy->to_field->hasDefault() and copy->from_null_ptr and  *copy->from_null_ptr & copy->from_bit)
1552
 
      {
1553
 
        copy->to_field->set_warning(DRIZZLE_ERROR::WARN_LEVEL_WARN,
1554
 
                                    ER_WARN_DATA_TRUNCATED, 1);
1555
 
        copy->to_field->reset();
1556
 
        error= 1;
1557
 
        break;
1558
 
      }
1559
 
 
1560
1384
      copy_ptr->do_copy(copy_ptr);
1561
1385
    }
1562
 
 
1563
 
    if (error)
1564
 
    {
1565
 
      break;
1566
 
    }
1567
 
 
1568
1386
    prev_insert_id= to->cursor->next_insert_id;
1569
 
    error= to->cursor->insertRecord(to->record[0]);
 
1387
    error= to->cursor->ha_write_row(to->record[0]);
1570
1388
    to->auto_increment_field_not_null= false;
 
1389
    if (error)
 
1390
    {
 
1391
      if (!ignore ||
 
1392
          to->cursor->is_fatal_error(error, HA_CHECK_DUP))
 
1393
      {
 
1394
        if (!to->cursor->is_fatal_error(error, HA_CHECK_DUP))
 
1395
        {
 
1396
          uint32_t key_nr= to->cursor->get_dup_key(error);
 
1397
          if ((int) key_nr >= 0)
 
1398
          {
 
1399
            const char *err_msg= ER(ER_DUP_ENTRY_WITH_KEY_NAME);
 
1400
            if (key_nr == 0 &&
 
1401
                (to->key_info[0].key_part[0].field->flags &
 
1402
                 AUTO_INCREMENT_FLAG))
 
1403
              err_msg= ER(ER_DUP_ENTRY_AUTOINCREMENT_CASE);
 
1404
            to->cursor->print_keydup_error(key_nr, err_msg);
 
1405
            break;
 
1406
          }
 
1407
        }
1571
1408
 
1572
 
    if (error)
1573
 
    { 
1574
 
      if (!ignore || to->cursor->is_fatal_error(error, HA_CHECK_DUP))
1575
 
      { 
1576
 
        to->print_error(error, MYF(0));
 
1409
        to->cursor->print_error(error,MYF(0));
1577
1410
        break;
1578
1411
      }
1579
1412
      to->cursor->restore_auto_increment(prev_insert_id);
1580
1413
      delete_count++;
1581
1414
    }
1582
1415
    else
1583
 
    {
1584
1416
      found_count++;
1585
 
    }
1586
1417
  }
1587
 
 
1588
 
  info.end_read_record();
 
1418
  end_read_record(&info);
1589
1419
  from->free_io_cache();
1590
1420
  delete [] copy;                               // This is never 0
1591
1421
 
1592
1422
  if (to->cursor->ha_end_bulk_insert() && error <= 0)
1593
1423
  {
1594
 
    to->print_error(errno, MYF(0));
 
1424
    to->cursor->print_error(my_errno,MYF(0));
1595
1425
    error=1;
1596
1426
  }
1597
1427
  to->cursor->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
1598
1428
 
 
1429
  if (ha_enable_transaction(session, true))
 
1430
  {
 
1431
    error= 1;
 
1432
    goto err;
 
1433
  }
 
1434
 
1599
1435
  /*
1600
1436
    Ensure that the new table is saved properly to disk so that we
1601
1437
    can do a rename
1602
1438
  */
1603
 
  if (transaction_services.autocommitOrRollback(session, false))
 
1439
  if (ha_autocommit_or_rollback(session, 0))
1604
1440
    error=1;
1605
1441
  if (! session->endActiveTransaction())
1606
1442
    error=1;
1613
1449
  to->cursor->ha_release_auto_increment();
1614
1450
  if (to->cursor->ha_external_lock(session,F_UNLCK))
1615
1451
    error=1;
1616
 
 
1617
1452
  return(error > 0 ? -1 : 0);
1618
1453
}
1619
1454
 
1620
1455
static int
1621
1456
create_temporary_table(Session *session,
1622
 
                       TableIdentifier &identifier,
 
1457
                       Table *table,
 
1458
                       char *new_db,
 
1459
                       char *tmp_name,
1623
1460
                       HA_CREATE_INFO *create_info,
1624
 
                       message::Table &create_proto,
 
1461
                       message::Table *create_proto,
1625
1462
                       AlterInfo *alter_info)
1626
1463
{
1627
1464
  int error;
1628
 
 
 
1465
  plugin::StorageEngine *old_db_type, *new_db_type;
 
1466
  old_db_type= table->s->db_type();
 
1467
  new_db_type= create_info->db_type;
1629
1468
  /*
1630
1469
    Create a table with a temporary name.
1631
1470
    We don't log the statement, it will be logged later.
1632
1471
  */
1633
 
  create_proto.set_name(identifier.getTableName());
1634
 
 
1635
 
  create_proto.mutable_engine()->set_name(create_info->db_type->getName());
1636
 
 
1637
 
  error= mysql_create_table(session,
1638
 
                            identifier,
1639
 
                            create_info, create_proto, alter_info, true, 0, false);
1640
 
 
1641
 
  return error;
 
1472
  create_proto->set_name(tmp_name);
 
1473
  create_proto->set_type(message::Table::TEMPORARY);
 
1474
 
 
1475
  message::Table::StorageEngine *protoengine;
 
1476
  protoengine= create_proto->mutable_engine();
 
1477
  protoengine->set_name(new_db_type->getName());
 
1478
 
 
1479
  error= mysql_create_table(session, new_db, tmp_name,
 
1480
                            create_info, create_proto, alter_info, true, 0);
 
1481
 
 
1482
  return(error);
1642
1483
}
1643
1484
 
1644
 
static Table *open_alter_table(Session *session, Table *table, TableIdentifier &identifier)
 
1485
/** @TODO This will soon die. */
 
1486
bool create_like_schema_frm(Session* session,
 
1487
                            TableList* schema_table,
 
1488
                            HA_CREATE_INFO *create_info,
 
1489
                            message::Table* table_proto)
1645
1490
{
1646
 
  Table *new_table;
1647
 
 
1648
 
  /* Open the table so we need to copy the data to it. */
1649
 
  if (table->getShare()->getType())
1650
 
  {
1651
 
    TableList tbl;
1652
 
    tbl.setSchemaName(const_cast<char *>(identifier.getSchemaName().c_str()));
1653
 
    tbl.alias= const_cast<char *>(identifier.getTableName().c_str());
1654
 
    tbl.setTableName(const_cast<char *>(identifier.getTableName().c_str()));
1655
 
 
1656
 
    /* Table is in session->temporary_tables */
1657
 
    new_table= session->openTable(&tbl, (bool*) 0, DRIZZLE_LOCK_IGNORE_FLUSH);
1658
 
  }
 
1491
  HA_CREATE_INFO local_create_info;
 
1492
  AlterInfo alter_info;
 
1493
  bool tmp_table= (create_info->options & HA_LEX_CREATE_TMP_TABLE);
 
1494
  uint32_t keys= schema_table->table->s->keys;
 
1495
  uint32_t db_options= 0;
 
1496
 
 
1497
  memset(&local_create_info, 0, sizeof(local_create_info));
 
1498
  local_create_info.db_type= schema_table->table->s->db_type();
 
1499
  local_create_info.row_type= schema_table->table->s->row_type;
 
1500
  local_create_info.default_table_charset=default_charset_info;
 
1501
  alter_info.flags.set(ALTER_CHANGE_COLUMN);
 
1502
  alter_info.flags.set(ALTER_RECREATE);
 
1503
  schema_table->table->use_all_columns();
 
1504
  if (mysql_prepare_alter_table(session, schema_table->table,
 
1505
                                &local_create_info, table_proto, &alter_info))
 
1506
    return true;
 
1507
 
 
1508
  /* I_S tables are created with MAX_ROWS for some efficiency drive.
 
1509
     When CREATE LIKE, we don't want to keep it coming across */
 
1510
  message::Table::TableOptions *table_options;
 
1511
  table_options= table_proto->mutable_options();
 
1512
  table_options->clear_max_rows();
 
1513
 
 
1514
  if (mysql_prepare_create_table(session, &local_create_info, table_proto,
 
1515
                                 &alter_info,
 
1516
                                 tmp_table, &db_options,
 
1517
                                 schema_table->table->cursor,
 
1518
                                 &schema_table->table->s->key_info, &keys, 0))
 
1519
    return true;
 
1520
 
 
1521
  table_proto->set_name("system_stupid_i_s_fix_nonsense");
 
1522
  if(tmp_table)
 
1523
    table_proto->set_type(message::Table::TEMPORARY);
1659
1524
  else
 
1525
    table_proto->set_type(message::Table::STANDARD);
 
1526
 
1660
1527
  {
1661
 
    /* Open our intermediate table */
1662
 
    new_table= session->open_temporary_table(identifier, false);
 
1528
    message::Table::StorageEngine *protoengine;
 
1529
    protoengine= table_proto->mutable_engine();
 
1530
 
 
1531
    plugin::StorageEngine *engine= local_create_info.db_type;
 
1532
 
 
1533
    protoengine->set_name(engine->getName());
1663
1534
  }
1664
1535
 
1665
 
  return new_table;
 
1536
  if (fill_table_proto(table_proto, "system_stupid_i_s_fix_nonsense",
 
1537
                       alter_info.create_list, &local_create_info,
 
1538
                       keys, schema_table->table->s->key_info))
 
1539
    return true;
 
1540
 
 
1541
  return false;
1666
1542
}
1667
1543
 
1668
1544
} /* namespace drizzled */