~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/statement/alter_table.cc

  • Committer: Brian Aker
  • Date: 2010-06-28 16:17:36 UTC
  • mfrom: (1637.4.1 drizzle)
  • Revision ID: brian@gaz-20100628161736-eormhb2mnd551i2h
MergeĀ unused

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
2
2
 *  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
3
3
 *
4
 
 *  Copyright (C) 2009 Sun Microsystems, Inc.
 
4
 *  Copyright (C) 2009 Sun Microsystems
5
5
 *
6
6
 *  This program is free software; you can redistribute it and/or modify
7
7
 *  it under the terms of the GNU General Public License as published by
41
41
#include "drizzled/pthread_globals.h"
42
42
#include "drizzled/internal/my_sys.h"
43
43
#include "drizzled/internal/iocache.h"
44
 
#include "drizzled/plugin/storage_engine.h"
45
 
#include <drizzled/copy_field.h>
46
44
 
47
45
#include "drizzled/transaction_services.h"
48
46
 
49
 
#include "drizzled/filesort.h"
50
 
 
51
 
#include "drizzled/message.h"
52
 
 
53
47
using namespace std;
54
48
 
55
49
namespace drizzled
62
56
                                    List<CreateField> &create,
63
57
                                    bool ignore,
64
58
                                    uint32_t order_num,
65
 
                                    Order *order,
 
59
                                    order_st *order,
66
60
                                    ha_rows *copied,
67
61
                                    ha_rows *deleted,
68
62
                                    enum enum_enable_or_disable keys_onoff,
69
63
                                    bool error_if_not_empty);
70
64
 
71
 
static bool prepare_alter_table(Session *session,
 
65
static bool mysql_prepare_alter_table(Session *session,
72
66
                                      Table *table,
73
67
                                      HA_CREATE_INFO *create_info,
74
68
                                      const message::Table &original_proto,
75
69
                                      message::Table &table_message,
76
70
                                      AlterInfo *alter_info);
77
71
 
78
 
static Table *open_alter_table(Session *session, Table *table, identifier::Table &identifier);
79
 
 
80
 
namespace statement {
81
 
 
82
 
AlterTable::AlterTable(Session *in_session, Table_ident *ident, drizzled::ha_build_method build_arg) :
83
 
  CreateTable(in_session)
84
 
85
 
  in_session->lex->sql_command= SQLCOM_ALTER_TABLE;
86
 
  (void)ident;
87
 
  alter_info.build_method= build_arg;
88
 
}
89
 
 
90
 
} // namespace statement
 
72
static int create_temporary_table(Session *session,
 
73
                                  TableIdentifier &identifier,
 
74
                                  HA_CREATE_INFO *create_info,
 
75
                                  message::Table &create_message,
 
76
                                  AlterInfo *alter_info);
 
77
 
 
78
static Table *open_alter_table(Session *session, Table *table, TableIdentifier &identifier);
91
79
 
92
80
bool statement::AlterTable::execute()
93
81
{
94
 
  TableList *first_table= (TableList *) getSession()->lex->select_lex.table_list.first;
95
 
  TableList *all_tables= getSession()->lex->query_tables;
 
82
  TableList *first_table= (TableList *) session->lex->select_lex.table_list.first;
 
83
  TableList *all_tables= session->lex->query_tables;
96
84
  assert(first_table == all_tables && first_table != 0);
97
 
  Select_Lex *select_lex= &getSession()->lex->select_lex;
 
85
  Select_Lex *select_lex= &session->lex->select_lex;
98
86
  bool need_start_waiting= false;
99
87
 
100
 
  is_engine_set= not createTableMessage().engine().name().empty();
101
 
 
102
88
  if (is_engine_set)
103
89
  {
104
 
    create_info().db_type= 
105
 
      plugin::StorageEngine::findByName(*getSession(), createTableMessage().engine().name());
 
90
    create_info.db_type= 
 
91
      plugin::StorageEngine::findByName(*session, create_table_message.engine().name());
106
92
 
107
 
    if (create_info().db_type == NULL)
 
93
    if (create_info.db_type == NULL)
108
94
    {
109
 
      my_error(createTableMessage().engine().name(), ER_UNKNOWN_STORAGE_ENGINE, MYF(0));
 
95
      my_error(ER_UNKNOWN_STORAGE_ENGINE, MYF(0), 
 
96
               create_table_message.engine().name().c_str());
110
97
 
111
98
      return true;
112
99
    }
116
103
  assert(select_lex->db);
117
104
 
118
105
  /* Chicken/Egg... we need to search for the table, to know if the table exists, so we can build a full identifier from it */
119
 
  message::table::shared_ptr original_table_message;
 
106
  message::Table original_table_message;
120
107
  {
121
 
    identifier::Table identifier(first_table->getSchemaName(), first_table->getTableName());
122
 
    if (plugin::StorageEngine::getTableDefinition(*getSession(), identifier, original_table_message) != EEXIST)
 
108
    TableIdentifier identifier(first_table->db, first_table->table_name);
 
109
    if (plugin::StorageEngine::getTableDefinition(*session, identifier, original_table_message) != EEXIST)
123
110
    {
124
 
      my_error(ER_BAD_TABLE_ERROR, identifier);
 
111
      my_error(ER_BAD_TABLE_ERROR, MYF(0), identifier.getSQLPath().c_str());
125
112
      return true;
126
113
    }
127
114
 
128
 
    if (not  create_info().db_type)
 
115
    if (not  create_info.db_type)
129
116
    {
130
 
      create_info().db_type= 
131
 
        plugin::StorageEngine::findByName(*getSession(), original_table_message->engine().name());
 
117
      create_info.db_type= 
 
118
        plugin::StorageEngine::findByName(*session, original_table_message.engine().name());
132
119
 
133
 
      if (not create_info().db_type)
 
120
      if (not create_info.db_type)
134
121
      {
135
 
        my_error(ER_BAD_TABLE_ERROR, identifier);
 
122
        my_error(ER_BAD_TABLE_ERROR, MYF(0), identifier.getSQLPath().c_str());
136
123
        return true;
137
124
      }
138
125
    }
139
126
  }
140
127
 
141
128
  if (not validateCreateTableOption())
142
 
    return true;
143
 
 
144
 
  if (getSession()->inTransaction())
145
 
  {
146
 
    my_error(ER_TRANSACTIONAL_DDL_NOT_SUPPORTED, MYF(0));
147
 
    return true;
148
 
  }
149
 
 
150
 
  if (not (need_start_waiting= not getSession()->wait_if_global_read_lock(0, 1)))
151
 
    return true;
 
129
  {
 
130
    return true;
 
131
  }
 
132
 
 
133
  /* ALTER TABLE ends previous transaction */
 
134
  if (not session->endActiveTransaction())
 
135
  {
 
136
    return true;
 
137
  }
 
138
 
 
139
  if (not (need_start_waiting= ! wait_if_global_read_lock(session, 0, 1)))
 
140
  {
 
141
    return true;
 
142
  }
152
143
 
153
144
  bool res;
154
 
  if (original_table_message->type() == message::Table::STANDARD )
 
145
  if (original_table_message.type() == message::Table::STANDARD )
155
146
  {
156
 
    identifier::Table identifier(first_table->getSchemaName(), first_table->getTableName());
157
 
    identifier::Table new_identifier(select_lex->db ? select_lex->db : first_table->getSchemaName(),
158
 
                                   getSession()->lex->name.str ? getSession()->lex->name.str : first_table->getTableName());
 
147
    TableIdentifier identifier(first_table->db, first_table->table_name);
 
148
    TableIdentifier new_identifier(select_lex->db ? select_lex->db : first_table->db,
 
149
                                   session->lex->name.str ? session->lex->name.str : first_table->table_name);
159
150
 
160
 
    res= alter_table(getSession(), 
 
151
    res= alter_table(session, 
161
152
                     identifier,
162
153
                     new_identifier,
163
 
                     &create_info(),
164
 
                     *original_table_message,
165
 
                     createTableMessage(),
 
154
                     &create_info,
 
155
                     original_table_message,
 
156
                     create_table_message,
166
157
                     first_table,
167
158
                     &alter_info,
168
159
                     select_lex->order_list.elements,
169
 
                     (Order *) select_lex->order_list.first,
170
 
                     getSession()->lex->ignore);
 
160
                     (order_st *) select_lex->order_list.first,
 
161
                     session->lex->ignore);
171
162
  }
172
163
  else
173
164
  {
174
 
    identifier::Table catch22(first_table->getSchemaName(), first_table->getTableName());
175
 
    Table *table= getSession()->find_temporary_table(catch22);
 
165
    Table *table= session->find_temporary_table(first_table);
176
166
    assert(table);
177
167
    {
178
 
      identifier::Table identifier(first_table->getSchemaName(), first_table->getTableName(), table->getMutableShare()->getPath());
179
 
      identifier::Table new_identifier(select_lex->db ? select_lex->db : first_table->getSchemaName(),
180
 
                                       getSession()->lex->name.str ? getSession()->lex->name.str : first_table->getTableName(),
181
 
                                       table->getMutableShare()->getPath());
 
168
      TableIdentifier identifier(first_table->db, first_table->table_name, table->getMutableShare()->getPath());
 
169
      TableIdentifier new_identifier(select_lex->db ? select_lex->db : first_table->db,
 
170
                                     session->lex->name.str ? session->lex->name.str : first_table->table_name,
 
171
                                     table->getMutableShare()->getPath());
182
172
 
183
 
      res= alter_table(getSession(), 
 
173
      res= alter_table(session, 
184
174
                       identifier,
185
175
                       new_identifier,
186
 
                       &create_info(),
187
 
                       *original_table_message,
188
 
                       createTableMessage(),
 
176
                       &create_info,
 
177
                       original_table_message,
 
178
                       create_table_message,
189
179
                       first_table,
190
180
                       &alter_info,
191
181
                       select_lex->order_list.elements,
192
 
                       (Order *) select_lex->order_list.first,
193
 
                       getSession()->lex->ignore);
 
182
                       (order_st *) select_lex->order_list.first,
 
183
                       session->lex->ignore);
194
184
    }
195
185
  }
196
186
 
198
188
     Release the protection against the global read lock and wake
199
189
     everyone, who might want to set a global read lock.
200
190
   */
201
 
  getSession()->startWaitingGlobalReadLock();
202
 
 
 
191
  start_waiting_global_read_lock(session);
203
192
  return res;
204
193
}
205
194
 
244
233
                 Table instructions
245
234
  @retval false  success
246
235
*/
247
 
static bool prepare_alter_table(Session *session,
248
 
                                Table *table,
249
 
                                HA_CREATE_INFO *create_info,
250
 
                                const message::Table &original_proto,
251
 
                                message::Table &table_message,
252
 
                                AlterInfo *alter_info)
 
236
static bool mysql_prepare_alter_table(Session *session,
 
237
                                      Table *table,
 
238
                                      HA_CREATE_INFO *create_info,
 
239
                                      const message::Table &original_proto,
 
240
                                      message::Table &table_message,
 
241
                                      AlterInfo *alter_info)
253
242
{
254
243
  /* New column definitions are added here */
255
244
  List<CreateField> new_create_list;
270
259
  message::Table::TableOptions *table_options;
271
260
  table_options= table_message.mutable_options();
272
261
 
273
 
  if (not (used_fields & HA_CREATE_USED_DEFAULT_CHARSET))
 
262
  if (! (used_fields & HA_CREATE_USED_DEFAULT_CHARSET))
274
263
    create_info->default_table_charset= table->getShare()->table_charset;
275
 
 
276
 
  if (not (used_fields & HA_CREATE_USED_AUTO) && table->found_next_number_field)
 
264
  if (! (used_fields & HA_CREATE_USED_AUTO) &&
 
265
      table->found_next_number_field)
277
266
  {
278
267
    /* Table has an autoincrement, copy value to new table */
279
268
    table->cursor->info(HA_STATUS_AUTO);
280
269
    create_info->auto_increment_value= table->cursor->stats.auto_increment_value;
281
 
    if (create_info->auto_increment_value != original_proto.options().auto_increment_value())
282
 
      table_options->set_has_user_set_auto_increment_value(false);
283
270
  }
284
 
 
285
271
  table->restoreRecordAsDefault(); /* Empty record for DEFAULT */
286
272
  CreateField *def;
287
273
 
288
274
  /* First collect all fields from table which isn't in drop_list */
 
275
  Field **f_ptr;
289
276
  Field *field;
290
 
  for (Field **f_ptr= table->getFields(); (field= *f_ptr); f_ptr++)
 
277
  for (f_ptr= table->getFields(); (field= *f_ptr); f_ptr++)
291
278
  {
292
279
    /* Check if field should be dropped */
293
280
    AlterDrop *drop;
307
294
        break;
308
295
      }
309
296
    }
310
 
 
311
297
    if (drop)
312
298
    {
313
299
      drop_it.remove();
325
311
          ! my_strcasecmp(system_charset_info, field->field_name, def->change))
326
312
              break;
327
313
    }
328
 
 
329
314
    if (def)
330
315
    {
331
316
      /* Field is changed */
346
331
      new_create_list.push_back(def);
347
332
      alter_it.rewind(); /* Change default if ALTER */
348
333
      AlterColumn *alter;
349
 
 
350
334
      while ((alter= alter_it++))
351
335
      {
352
336
        if (! my_strcasecmp(system_charset_info,field->field_name, alter->name))
353
337
          break;
354
338
      }
355
 
 
356
339
      if (alter)
357
340
      {
358
341
        if (def->sql_type == DRIZZLE_TYPE_BLOB)
359
342
        {
360
343
          my_error(ER_BLOB_CANT_HAVE_DEFAULT, MYF(0), def->change);
361
 
          return true;
 
344
                goto err;
362
345
        }
363
 
 
364
346
        if ((def->def= alter->def))
365
347
        {
366
348
          /* Use new default */
367
349
          def->flags&= ~NO_DEFAULT_VALUE_FLAG;
368
350
        }
369
351
        else
370
 
        {
371
352
          def->flags|= NO_DEFAULT_VALUE_FLAG;
372
 
        }
373
353
        alter_it.remove();
374
354
      }
375
355
    }
376
356
  }
377
 
 
378
357
  def_it.rewind();
379
358
  while ((def= def_it++)) /* Add new columns */
380
359
  {
381
360
    if (def->change && ! def->field)
382
361
    {
383
362
      my_error(ER_BAD_FIELD_ERROR, MYF(0), def->change, table->getMutableShare()->getTableName());
384
 
      return true;
 
363
      goto err;
385
364
    }
386
365
    /*
387
 
      If we have been given a field which has no default value, and is not null then we need to bail.
 
366
      Check that the DATE/DATETIME not null field we are going to add is
 
367
      either has a default value or the '0000-00-00' is allowed by the
 
368
      set sql mode.
 
369
      If the '0000-00-00' value isn't allowed then raise the error_if_not_empty
 
370
      flag to allow ALTER Table only if the table to be altered is empty.
388
371
    */
389
 
    if (not (~def->flags & (NO_DEFAULT_VALUE_FLAG | NOT_NULL_FLAG)) and not def->change)
 
372
    if ((def->sql_type == DRIZZLE_TYPE_DATE ||
 
373
         def->sql_type == DRIZZLE_TYPE_DATETIME) &&
 
374
        ! alter_info->datetime_field &&
 
375
        ! (~def->flags & (NO_DEFAULT_VALUE_FLAG | NOT_NULL_FLAG)))
390
376
    {
 
377
      alter_info->datetime_field= def;
391
378
      alter_info->error_if_not_empty= true;
392
379
    }
393
380
    if (! def->after)
394
 
    {
395
381
      new_create_list.push_back(def);
396
 
    }
397
382
    else if (def->after == first_keyword)
398
 
    {
399
383
      new_create_list.push_front(def);
400
 
    }
401
384
    else
402
385
    {
403
386
      CreateField *find;
404
387
      find_it.rewind();
405
 
 
406
388
      while ((find= find_it++)) /* Add new columns */
407
389
      {
408
 
        if (not my_strcasecmp(system_charset_info,def->after, find->field_name))
 
390
        if (! my_strcasecmp(system_charset_info,def->after, find->field_name))
409
391
          break;
410
392
      }
411
 
 
412
 
      if (not find)
 
393
      if (! find)
413
394
      {
414
395
        my_error(ER_BAD_FIELD_ERROR, MYF(0), def->after, table->getMutableShare()->getTableName());
415
 
        return true;
 
396
        goto err;
416
397
      }
417
 
 
418
398
      find_it.after(def); /* Put element after this */
419
 
 
420
399
      /*
421
400
        XXX: hack for Bug#28427.
422
401
        If column order has changed, force OFFLINE ALTER Table
429
408
      */
430
409
      if (alter_info->build_method == HA_BUILD_ONLINE)
431
410
      {
432
 
        my_error(*session->getQueryString(), ER_NOT_SUPPORTED_YET);
433
 
        return true;
 
411
        my_error(ER_NOT_SUPPORTED_YET, MYF(0), session->query.c_str());
 
412
        goto err;
434
413
      }
435
 
 
436
414
      alter_info->build_method= HA_BUILD_OFFLINE;
437
415
    }
438
416
  }
439
 
 
440
417
  if (alter_info->alter_list.elements)
441
418
  {
442
419
    my_error(ER_BAD_FIELD_ERROR,
443
420
             MYF(0),
444
421
             alter_info->alter_list.head()->name,
445
422
             table->getMutableShare()->getTableName());
446
 
    return true;
 
423
    goto err;
447
424
  }
448
 
 
449
 
  if (not new_create_list.elements)
 
425
  if (! new_create_list.elements)
450
426
  {
451
427
    my_message(ER_CANT_REMOVE_ALL_FIELDS,
452
428
               ER(ER_CANT_REMOVE_ALL_FIELDS),
453
429
               MYF(0));
454
 
    return true;
 
430
    goto err;
455
431
  }
456
432
 
457
433
  /*
462
438
  {
463
439
    char *key_name= key_info->name;
464
440
    AlterDrop *drop;
465
 
 
466
441
    drop_it.rewind();
467
442
    while ((drop= drop_it++))
468
443
    {
470
445
          ! my_strcasecmp(system_charset_info, key_name, drop->name))
471
446
        break;
472
447
    }
473
 
 
474
448
    if (drop)
475
449
    {
476
450
      drop_it.remove();
491
465
      {
492
466
        if (cfield->change)
493
467
        {
494
 
          if (not my_strcasecmp(system_charset_info, key_part_name, cfield->change))
 
468
          if (! my_strcasecmp(system_charset_info, key_part_name, cfield->change))
495
469
            break;
496
470
        }
497
 
        else if (not my_strcasecmp(system_charset_info, key_part_name, cfield->field_name))
 
471
        else if (! my_strcasecmp(system_charset_info, key_part_name, cfield->field_name))
498
472
          break;
499
473
      }
500
 
 
501
 
      if (not cfield)
 
474
      if (! cfield)
502
475
              continue; /* Field is removed */
503
476
      
504
477
      uint32_t key_part_length= key_part->length;
530
503
    }
531
504
    if (key_parts.elements)
532
505
    {
533
 
      key_create_information_st key_create_info= default_key_create_info;
 
506
      KEY_CREATE_INFO key_create_info;
534
507
      Key *key;
535
 
      Key::Keytype key_type;
 
508
      enum Key::Keytype key_type;
 
509
      memset(&key_create_info, 0, sizeof(key_create_info));
536
510
 
537
511
      key_create_info.algorithm= key_info->algorithm;
538
 
 
539
512
      if (key_info->flags & HA_USES_BLOCK_SIZE)
540
513
        key_create_info.block_size= key_info->block_size;
541
 
 
542
514
      if (key_info->flags & HA_USES_COMMENT)
543
515
        key_create_info.comment= key_info->comment;
544
516
 
550
522
          key_type= Key::UNIQUE;
551
523
      }
552
524
      else
553
 
      {
554
525
        key_type= Key::MULTIPLE;
555
 
      }
556
526
 
557
527
      key= new Key(key_type,
558
528
                   key_name,
563
533
      new_key_list.push_back(key);
564
534
    }
565
535
  }
566
 
 
567
 
  /* Copy over existing foreign keys */
568
 
  for (int32_t j= 0; j < original_proto.fk_constraint_size(); j++)
569
 
  {
570
 
    AlterDrop *drop;
571
 
    drop_it.rewind();
572
 
    while ((drop= drop_it++))
573
 
    {
574
 
      if (drop->type == AlterDrop::FOREIGN_KEY &&
575
 
          ! my_strcasecmp(system_charset_info, original_proto.fk_constraint(j).name().c_str(), drop->name))
576
 
      {
577
 
        break;
578
 
      }
579
 
    }
580
 
    if (drop)
581
 
    {
582
 
      drop_it.remove();
583
 
      continue;
584
 
    }
585
 
 
586
 
    message::Table::ForeignKeyConstraint *pfkey= table_message.add_fk_constraint();
587
 
    *pfkey= original_proto.fk_constraint(j);
588
 
  }
589
 
 
590
536
  {
591
537
    Key *key;
592
538
    while ((key= key_it++)) /* Add new keys */
593
539
    {
594
 
      if (key->type == Key::FOREIGN_KEY)
595
 
      {
596
 
        if (((Foreign_key *)key)->validate(new_create_list))
597
 
        {
598
 
          return true;
599
 
        }
600
 
 
601
 
        Foreign_key *fkey= (Foreign_key*)key;
602
 
        add_foreign_key_to_table_message(&table_message,
603
 
                                         fkey->name.str,
604
 
                                         fkey->columns,
605
 
                                         fkey->ref_table,
606
 
                                         fkey->ref_columns,
607
 
                                         fkey->delete_opt,
608
 
                                         fkey->update_opt,
609
 
                                         fkey->match_opt);
610
 
      }
611
 
 
 
540
      if (key->type == Key::FOREIGN_KEY &&
 
541
          ((Foreign_key *)key)->validate(new_create_list))
 
542
        goto err;
612
543
      if (key->type != Key::FOREIGN_KEY)
613
544
        new_key_list.push_back(key);
614
 
 
615
545
      if (key->name.str && is_primary_key_name(key->name.str))
616
546
      {
617
547
        my_error(ER_WRONG_NAME_FOR_INDEX,
618
548
                 MYF(0),
619
549
                 key->name.str);
620
 
        return true;
 
550
        goto err;
621
551
      }
622
552
    }
623
553
  }
624
554
 
625
 
  /* Fix names of foreign keys being added */
626
 
  for (int j= 0; j < table_message.fk_constraint_size(); j++)
627
 
  {
628
 
    if (! table_message.fk_constraint(j).has_name())
629
 
    {
630
 
      std::string name(table->getMutableShare()->getTableName());
631
 
      char number[20];
632
 
 
633
 
      name.append("_ibfk_");
634
 
      snprintf(number, sizeof(number), "%d", j+1);
635
 
      name.append(number);
636
 
 
637
 
      message::Table::ForeignKeyConstraint *pfkey= table_message.mutable_fk_constraint(j);
638
 
      pfkey->set_name(name);
639
 
    }
640
 
  }
641
 
 
642
555
  if (alter_info->drop_list.elements)
643
556
  {
644
557
    my_error(ER_CANT_DROP_FIELD_OR_KEY,
645
558
             MYF(0),
646
559
             alter_info->drop_list.head()->name);
647
 
    return true;
 
560
    goto err;
648
561
  }
649
 
 
650
562
  if (alter_info->alter_list.elements)
651
563
  {
652
564
    my_error(ER_CANT_DROP_FIELD_OR_KEY,
653
565
             MYF(0),
654
566
             alter_info->alter_list.head()->name);
655
 
    return true;
 
567
    goto err;
656
568
  }
657
569
 
658
570
  if (not table_message.options().has_comment()
659
571
      && table->getMutableShare()->hasComment())
660
 
  {
661
572
    table_options->set_comment(table->getMutableShare()->getComment());
662
 
  }
663
573
 
664
574
  if (table->getShare()->getType())
665
575
  {
666
576
    table_message.set_type(message::Table::TEMPORARY);
667
577
  }
668
578
 
669
 
  table_message.set_creation_timestamp(table->getShare()->getTableMessage()->creation_timestamp());
670
 
  table_message.set_version(table->getShare()->getTableMessage()->version());
671
 
  table_message.set_uuid(table->getShare()->getTableMessage()->uuid());
 
579
  table_message.set_creation_timestamp(table->getShare()->getTableProto()->creation_timestamp());
 
580
 
 
581
  table_message.set_update_timestamp(time(NULL));
672
582
 
673
583
  rc= false;
674
584
  alter_info->create_list.swap(new_create_list);
675
585
  alter_info->key_list.swap(new_key_list);
 
586
err:
676
587
 
677
588
  size_t num_engine_options= table_message.engine().options_size();
678
589
  size_t original_num_engine_options= original_proto.engine().options_size();
697
608
    }
698
609
  }
699
610
 
700
 
  drizzled::message::update(table_message);
701
 
 
702
 
  return false;
 
611
  return rc;
703
612
}
704
613
 
705
614
/* table_list should contain just one table */
706
 
static int discard_or_import_tablespace(Session *session,
 
615
static int mysql_discard_or_import_tablespace(Session *session,
707
616
                                              TableList *table_list,
708
617
                                              enum tablespace_op_type tablespace_op)
709
618
{
710
619
  Table *table;
711
620
  bool discard;
 
621
  int error;
712
622
 
713
623
  /*
714
624
    Note that DISCARD/IMPORT TABLESPACE always is the only operation in an
715
625
    ALTER Table
716
626
  */
 
627
 
717
628
  TransactionServices &transaction_services= TransactionServices::singleton();
718
629
  session->set_proc_info("discard_or_import_tablespace");
719
630
 
723
634
   We set this flag so that ha_innobase::open and ::external_lock() do
724
635
   not complain when we lock the table
725
636
 */
726
 
  session->setDoingTablespaceOperation(true);
727
 
  if (not (table= session->openTableLock(table_list, TL_WRITE)))
 
637
  session->tablespace_op= true;
 
638
  if (!(table= session->openTableLock(table_list, TL_WRITE)))
728
639
  {
729
 
    session->setDoingTablespaceOperation(false);
 
640
    session->tablespace_op= false;
730
641
    return -1;
731
642
  }
732
643
 
733
 
  int error;
734
 
  do {
735
 
    error= table->cursor->ha_discard_or_import_tablespace(discard);
736
 
 
737
 
    session->set_proc_info("end");
738
 
 
739
 
    if (error)
740
 
      break;
741
 
 
742
 
    /* The ALTER Table is always in its own transaction */
743
 
    error= transaction_services.autocommitOrRollback(*session, false);
744
 
    if (not session->endActiveTransaction())
745
 
      error= 1;
746
 
 
747
 
    if (error)
748
 
      break;
749
 
 
750
 
    write_bin_log(session, *session->getQueryString());
751
 
 
752
 
  } while(0);
753
 
 
754
 
  (void) transaction_services.autocommitOrRollback(*session, error);
755
 
  session->setDoingTablespaceOperation(false);
 
644
  error= table->cursor->ha_discard_or_import_tablespace(discard);
 
645
 
 
646
  session->set_proc_info("end");
 
647
 
 
648
  if (error)
 
649
    goto err;
 
650
 
 
651
  /* The ALTER Table is always in its own transaction */
 
652
  error= transaction_services.autocommitOrRollback(session, false);
 
653
  if (! session->endActiveTransaction())
 
654
    error=1;
 
655
  if (error)
 
656
    goto err;
 
657
  write_bin_log(session, session->query.c_str());
 
658
 
 
659
err:
 
660
  (void) transaction_services.autocommitOrRollback(session, error);
 
661
  session->tablespace_op=false;
756
662
 
757
663
  if (error == 0)
758
664
  {
802
708
                        ER_ILLEGAL_HA, ER(ER_ILLEGAL_HA),
803
709
                        table->getMutableShare()->getTableName());
804
710
    error= 0;
805
 
  }
806
 
  else if (error)
807
 
  {
 
711
  } else if (error)
808
712
    table->print_error(error, MYF(0));
809
 
  }
810
713
 
811
714
  return(error);
812
715
}
813
716
 
814
717
static bool lockTableIfDifferent(Session &session,
815
 
                                 identifier::Table &original_table_identifier,
816
 
                                 identifier::Table &new_table_identifier,
 
718
                                 TableIdentifier &original_table_identifier,
 
719
                                 TableIdentifier &new_table_identifier,
817
720
                                 Table *name_lock)
818
721
{
819
722
  /* Check that we are not trying to rename to an existing table */
824
727
 
825
728
      if (session.find_temporary_table(new_table_identifier))
826
729
      {
827
 
        my_error(ER_TABLE_EXISTS_ERROR, new_table_identifier);
 
730
        my_error(ER_TABLE_EXISTS_ERROR, MYF(0), new_table_identifier.getSQLPath().c_str());
828
731
        return false;
829
732
      }
830
733
    }
837
740
 
838
741
      if (not name_lock)
839
742
      {
840
 
        my_error(ER_TABLE_EXISTS_ERROR, new_table_identifier);
 
743
        my_error(ER_TABLE_EXISTS_ERROR, MYF(0), new_table_identifier.getSQLPath().c_str());
841
744
        return false;
842
745
      }
843
746
 
844
747
      if (plugin::StorageEngine::doesTableExist(session, new_table_identifier))
845
748
      {
846
749
        /* Table will be closed by Session::executeCommand() */
847
 
        my_error(ER_TABLE_EXISTS_ERROR, new_table_identifier);
 
750
        my_error(ER_TABLE_EXISTS_ERROR, MYF(0), new_table_identifier.getSQLPath().c_str());
848
751
 
849
 
        {
850
 
          boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex());
851
 
          session.unlink_open_table(name_lock);
852
 
        }
 
752
        pthread_mutex_lock(&LOCK_open); /* ALTER TABLe */
 
753
        session.unlink_open_table(name_lock);
 
754
        pthread_mutex_unlock(&LOCK_open);
853
755
 
854
756
        return false;
855
757
      }
903
805
 
904
806
static bool internal_alter_table(Session *session,
905
807
                                 Table *table,
906
 
                                 identifier::Table &original_table_identifier,
907
 
                                 identifier::Table &new_table_identifier,
 
808
                                 TableIdentifier &original_table_identifier,
 
809
                                 TableIdentifier &new_table_identifier,
908
810
                                 HA_CREATE_INFO *create_info,
909
811
                                 const message::Table &original_proto,
910
812
                                 message::Table &create_proto,
911
813
                                 TableList *table_list,
912
814
                                 AlterInfo *alter_info,
913
815
                                 uint32_t order_num,
914
 
                                 Order *order,
 
816
                                 order_st *order,
915
817
                                 bool ignore)
916
818
{
 
819
  Table *new_table= NULL;
917
820
  int error= 0;
918
821
  char tmp_name[80];
919
822
  char old_name[32];
920
823
  ha_rows copied= 0;
921
824
  ha_rows deleted= 0;
922
825
 
923
 
  if (not original_table_identifier.isValid())
924
 
    return true;
925
 
 
926
 
  if (not new_table_identifier.isValid())
927
 
    return true;
 
826
  message::Table *original_table_definition= table->getMutableShare()->getTableProto();
928
827
 
929
828
  session->set_proc_info("init");
930
829
 
961
860
  if (original_engine->check_flag(HTON_BIT_ALTER_NOT_SUPPORTED) ||
962
861
      new_engine->check_flag(HTON_BIT_ALTER_NOT_SUPPORTED))
963
862
  {
964
 
    my_error(ER_ILLEGAL_HA, new_table_identifier);
 
863
    my_error(ER_ILLEGAL_HA, MYF(0), new_table_identifier.getSQLPath().c_str());
965
864
 
966
865
    return true;
967
866
  }
968
867
 
 
868
  if (create_info->row_type == ROW_TYPE_NOT_USED)
 
869
  {
 
870
    message::Table::TableOptions *table_options;
 
871
    table_options= create_proto.mutable_options();
 
872
 
 
873
    create_info->row_type= table->getShare()->row_type;
 
874
    table_options->set_row_type(original_table_definition->options().row_type());
 
875
  }
 
876
 
969
877
  session->set_proc_info("setup");
970
878
 
971
879
  /*
979
887
    tmp.reset(ALTER_KEYS_ONOFF);
980
888
    tmp&= alter_info->flags;
981
889
 
982
 
    if (not (tmp.any()) && not table->getShare()->getType()) // no need to touch frm
 
890
    if (! (tmp.any()) && ! table->getShare()->getType()) // no need to touch frm
983
891
    {
984
892
      switch (alter_info->keys_onoff)
985
893
      {
986
894
      case LEAVE_AS_IS:
987
895
        break;
988
 
 
989
896
      case ENABLE:
990
897
        /*
991
898
          wait_while_table_is_used() ensures that table being altered is
996
903
          while the fact that the table is still open gives us protection
997
904
          from concurrent DDL statements.
998
905
        */
999
 
        {
1000
 
          boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex()); /* DDL wait for/blocker */
1001
 
          wait_while_table_is_used(session, table, HA_EXTRA_FORCE_REOPEN);
1002
 
        }
 
906
        pthread_mutex_lock(&LOCK_open); /* DDL wait for/blocker */
 
907
        wait_while_table_is_used(session, table, HA_EXTRA_FORCE_REOPEN);
 
908
        pthread_mutex_unlock(&LOCK_open);
1003
909
        error= table->cursor->ha_enable_indexes(HA_KEY_SWITCH_NONUNIQ_SAVE);
1004
 
 
1005
910
        /* COND_refresh will be signaled in close_thread_tables() */
1006
911
        break;
1007
 
 
1008
912
      case DISABLE:
1009
 
        {
1010
 
          boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex()); /* DDL wait for/blocker */
1011
 
          wait_while_table_is_used(session, table, HA_EXTRA_FORCE_REOPEN);
1012
 
        }
1013
 
        error= table->cursor->ha_disable_indexes(HA_KEY_SWITCH_NONUNIQ_SAVE);
1014
 
 
 
913
        pthread_mutex_lock(&LOCK_open); /* DDL wait for/blocker */
 
914
        wait_while_table_is_used(session, table, HA_EXTRA_FORCE_REOPEN);
 
915
        pthread_mutex_unlock(&LOCK_open);
 
916
        error=table->cursor->ha_disable_indexes(HA_KEY_SWITCH_NONUNIQ_SAVE);
1015
917
        /* COND_refresh will be signaled in close_thread_tables() */
1016
918
        break;
 
919
      default:
 
920
        assert(false);
 
921
        error= 0;
 
922
        break;
1017
923
      }
1018
924
 
1019
925
      if (error == HA_ERR_WRONG_COMMAND)
1020
926
      {
1021
 
        error= EE_OK;
 
927
        error= 0;
1022
928
        push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
1023
929
                            ER_ILLEGAL_HA, ER(ER_ILLEGAL_HA),
1024
 
                            table->getAlias());
 
930
                            table->alias);
1025
931
      }
1026
932
 
1027
 
      boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex()); /* Lock to remove all instances of table from table cache before ALTER */
 
933
      pthread_mutex_lock(&LOCK_open); /* Lock to remove all instances of table from table cache before ALTER */
1028
934
      /*
1029
935
        Unlike to the above case close_cached_table() below will remove ALL
1030
936
        instances of Table from table cache (it will also remove table lock
1031
937
        held by this thread). So to make actual table renaming and writing
1032
938
        to binlog atomic we have to put them into the same critical section
1033
 
        protected by table::Cache::singleton().mutex() mutex. This also removes gap for races between
1034
 
        access() and rename_table() calls.
 
939
        protected by LOCK_open mutex. This also removes gap for races between
 
940
        access() and mysql_rename_table() calls.
1035
941
      */
1036
942
 
1037
 
      if (not error &&  not (original_table_identifier == new_table_identifier))
 
943
      if (error == 0 &&  not (original_table_identifier == new_table_identifier))
1038
944
      {
1039
945
        session->set_proc_info("rename");
1040
946
        /*
1052
958
        */
1053
959
        if (plugin::StorageEngine::doesTableExist(*session, new_table_identifier))
1054
960
        {
1055
 
          my_error(ER_TABLE_EXISTS_ERROR, new_table_identifier);
 
961
          my_error(ER_TABLE_EXISTS_ERROR, MYF(0), new_table_identifier.getSQLPath().c_str());
1056
962
          error= -1;
1057
963
        }
1058
964
        else
1059
965
        {
1060
 
          if (rename_table(*session, original_engine, original_table_identifier, new_table_identifier))
 
966
          if (mysql_rename_table(*session, original_engine, original_table_identifier, new_table_identifier))
1061
967
          {
1062
968
            error= -1;
1063
969
          }
1066
972
 
1067
973
      if (error == HA_ERR_WRONG_COMMAND)
1068
974
      {
1069
 
        error= EE_OK;
 
975
        error= 0;
1070
976
        push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
1071
977
                            ER_ILLEGAL_HA, ER(ER_ILLEGAL_HA),
1072
 
                            table->getAlias());
 
978
                            table->alias);
1073
979
      }
1074
980
 
1075
 
      if (not error)
 
981
      if (error == 0)
1076
982
      {
1077
 
        TransactionServices &transaction_services= TransactionServices::singleton();
1078
 
        transaction_services.allocateNewTransactionId();
1079
 
        write_bin_log(session, *session->getQueryString());
 
983
        write_bin_log(session, session->query.c_str());
1080
984
        session->my_ok();
1081
985
      }
1082
 
      else if (error > EE_OK) // If we have already set the error, we pass along -1
 
986
      else if (error > 0)
1083
987
      {
1084
988
        table->print_error(error, MYF(0));
 
989
        error= -1;
1085
990
      }
1086
991
 
 
992
      pthread_mutex_unlock(&LOCK_open);
1087
993
      table_list->table= NULL;
1088
994
 
1089
995
      return error;
1093
999
  /* We have to do full alter table. */
1094
1000
  new_engine= create_info->db_type;
1095
1001
 
1096
 
  if (prepare_alter_table(session, table, create_info, original_proto, create_proto, alter_info))
 
1002
  if (mysql_prepare_alter_table(session, table, create_info, original_proto, create_proto, alter_info))
1097
1003
  {
1098
1004
    return true;
1099
1005
  }
1110
1016
    case we just use it as is. Neither of these tables require locks in order to  be
1111
1017
    filled.
1112
1018
  */
1113
 
  identifier::Table new_table_as_temporary(original_table_identifier.getSchemaName(),
 
1019
  TableIdentifier new_table_as_temporary(original_table_identifier.getSchemaName(),
1114
1020
                                         tmp_name,
1115
1021
                                         create_proto.type() != message::Table::TEMPORARY ? message::Table::INTERNAL :
1116
1022
                                         message::Table::TEMPORARY);
1117
1023
 
1118
 
  /*
1119
 
    Create a table with a temporary name.
1120
 
    We don't log the statement, it will be logged later.
1121
 
  */
1122
 
  create_proto.set_name(new_table_as_temporary.getTableName());
1123
 
  create_proto.mutable_engine()->set_name(create_info->db_type->getName());
1124
 
 
1125
 
  error= create_table(session,
1126
 
                      new_table_as_temporary,
1127
 
                      create_info, create_proto, alter_info, true, 0, false);
 
1024
  error= create_temporary_table(session, new_table_as_temporary, create_info, create_proto, alter_info);
1128
1025
 
1129
1026
  if (error != 0)
1130
1027
  {
1132
1029
  }
1133
1030
 
1134
1031
  /* Open the table so we need to copy the data to it. */
1135
 
  Table *new_table= open_alter_table(session, table, new_table_as_temporary);
1136
 
 
 
1032
  new_table= open_alter_table(session, table, new_table_as_temporary);
1137
1033
 
1138
1034
  if (not new_table)
1139
1035
  {
1140
 
    plugin::StorageEngine::dropTable(*session, new_table_as_temporary);
 
1036
    quick_rm_table(*session, new_table_as_temporary);
1141
1037
    return true;
1142
1038
  }
1143
1039
 
1174
1070
  {
1175
1071
 
1176
1072
    /*
1177
 
      No default value was provided for new fields.
 
1073
      No default value was provided for a DATE/DATETIME field, the
 
1074
      current sql_mode doesn't allow the '0000-00-00' value and
 
1075
      the table to be altered isn't empty.
 
1076
      Report error here.
1178
1077
    */
1179
1078
    if (alter_info->error_if_not_empty && session->row_count)
1180
1079
    {
1181
 
      my_error(ER_INVALID_ALTER_TABLE_FOR_NOT_NULL, MYF(0));
 
1080
      const char *f_val= 0;
 
1081
      enum enum_drizzle_timestamp_type t_type= DRIZZLE_TIMESTAMP_DATE;
 
1082
 
 
1083
      switch (alter_info->datetime_field->sql_type)
 
1084
      {
 
1085
      case DRIZZLE_TYPE_DATE:
 
1086
        f_val= "0000-00-00";
 
1087
        t_type= DRIZZLE_TIMESTAMP_DATE;
 
1088
        break;
 
1089
      case DRIZZLE_TYPE_DATETIME:
 
1090
        f_val= "0000-00-00 00:00:00";
 
1091
        t_type= DRIZZLE_TIMESTAMP_DATETIME;
 
1092
        break;
 
1093
      default:
 
1094
        /* Shouldn't get here. */
 
1095
        assert(0);
 
1096
      }
 
1097
      bool save_abort_on_warning= session->abort_on_warning;
 
1098
      session->abort_on_warning= true;
 
1099
      make_truncated_value_warning(session, DRIZZLE_ERROR::WARN_LEVEL_ERROR,
 
1100
                                   f_val, internal::strlength(f_val), t_type,
 
1101
                                   alter_info->datetime_field->field_name);
 
1102
      session->abort_on_warning= save_abort_on_warning;
1182
1103
    }
1183
1104
 
1184
1105
    if (original_table_identifier.isTmp())
1190
1111
      }
1191
1112
      else
1192
1113
      {
1193
 
        plugin::StorageEngine::dropTable(*session, new_table_as_temporary);
 
1114
        quick_rm_table(*session, new_table_as_temporary);
1194
1115
      }
1195
1116
 
1196
1117
      return true;
1206
1127
        new_table->intern_close_table();
1207
1128
        if (new_table->hasShare())
1208
1129
        {
1209
 
          delete new_table->getMutableShare();
 
1130
          assert(new_table->getShare()->newed);
 
1131
          delete new_table->s;
 
1132
          new_table->s= NULL;
1210
1133
        }
1211
1134
 
1212
 
        delete new_table;
 
1135
        free(new_table);
1213
1136
      }
1214
1137
 
1215
 
      boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex());
 
1138
      pthread_mutex_lock(&LOCK_open); /* ALTER TABLE */
1216
1139
 
1217
 
      plugin::StorageEngine::dropTable(*session, new_table_as_temporary);
 
1140
      quick_rm_table(*session, new_table_as_temporary);
 
1141
      pthread_mutex_unlock(&LOCK_open);
1218
1142
 
1219
1143
      return true;
1220
1144
    }
1225
1149
    /* Close lock if this is a transactional table */
1226
1150
    if (session->lock)
1227
1151
    {
1228
 
      session->unlockTables(session->lock);
 
1152
      mysql_unlock_tables(session, session->lock);
1229
1153
      session->lock= 0;
1230
1154
    }
1231
1155
 
1237
1161
 
1238
1162
    new_table_identifier.setPath(new_table_as_temporary.getPath());
1239
1163
 
1240
 
    if (rename_table(*session, new_engine, new_table_as_temporary, new_table_identifier) != 0)
 
1164
    if (mysql_rename_table(*session, new_engine, new_table_as_temporary, new_table_identifier) != 0)
1241
1165
    {
1242
1166
      return true;
1243
1167
    }
1255
1179
 
1256
1180
      if (new_table->hasShare())
1257
1181
      {
1258
 
        delete new_table->getMutableShare();
 
1182
        assert(new_table->getShare()->newed);
 
1183
        delete new_table->s;
 
1184
        new_table->s= NULL;
1259
1185
      }
1260
1186
 
1261
 
      delete new_table;
1262
 
    }
1263
 
 
1264
 
    {
1265
 
      boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex()); /* ALTER TABLE */
1266
 
      /*
1267
 
        Data is copied. Now we:
1268
 
        1) Wait until all other threads close old version of table.
1269
 
        2) Close instances of table open by this thread and replace them
1270
 
        with exclusive name-locks.
1271
 
        3) Rename the old table to a temp name, rename the new one to the
1272
 
        old name.
1273
 
        4) If we are under LOCK TABLES and don't do ALTER Table ... RENAME
1274
 
        we reopen new version of table.
1275
 
        5) Write statement to the binary log.
1276
 
        6) If we are under LOCK TABLES and do ALTER Table ... RENAME we
1277
 
        remove name-locks from list of open tables and table cache.
1278
 
        7) If we are not not under LOCK TABLES we rely on close_thread_tables()
1279
 
        call to remove name-locks from table cache and list of open table.
1280
 
      */
1281
 
 
1282
 
      session->set_proc_info("rename result table");
1283
 
 
1284
 
      snprintf(old_name, sizeof(old_name), "%s2-%lx-%"PRIx64, TMP_FILE_PREFIX, (unsigned long) current_pid, session->thread_id);
1285
 
 
1286
 
      my_casedn_str(files_charset_info, old_name);
1287
 
 
1288
 
      wait_while_table_is_used(session, table, HA_EXTRA_PREPARE_FOR_RENAME);
1289
 
      session->close_data_files_and_morph_locks(original_table_identifier);
1290
 
 
1291
 
      assert(not error);
1292
 
 
1293
 
      /*
1294
 
        This leads to the storage engine (SE) not being notified for renames in
1295
 
        rename_table(), because we just juggle with the FRM and nothing
1296
 
        more. If we have an intermediate table, then we notify the SE that
1297
 
        it should become the actual table. Later, we will recycle the old table.
1298
 
        However, in case of ALTER Table RENAME there might be no intermediate
1299
 
        table. This is when the old and new tables are compatible, according to
1300
 
        compare_table(). Then, we need one additional call to
1301
 
      */
1302
 
      identifier::Table original_table_to_drop(original_table_identifier.getSchemaName(),
1303
 
                                             old_name, create_proto.type() != message::Table::TEMPORARY ? message::Table::INTERNAL :
1304
 
                                             message::Table::TEMPORARY);
1305
 
 
1306
 
      drizzled::error_t rename_error= EE_OK;
1307
 
      if (rename_table(*session, original_engine, original_table_identifier, original_table_to_drop))
 
1187
      free(new_table);
 
1188
    }
 
1189
 
 
1190
    pthread_mutex_lock(&LOCK_open); /* ALTER TABLE */
 
1191
 
 
1192
    /*
 
1193
      Data is copied. Now we:
 
1194
      1) Wait until all other threads close old version of table.
 
1195
      2) Close instances of table open by this thread and replace them
 
1196
      with exclusive name-locks.
 
1197
      3) Rename the old table to a temp name, rename the new one to the
 
1198
      old name.
 
1199
      4) If we are under LOCK TABLES and don't do ALTER Table ... RENAME
 
1200
      we reopen new version of table.
 
1201
      5) Write statement to the binary log.
 
1202
      6) If we are under LOCK TABLES and do ALTER Table ... RENAME we
 
1203
      remove name-locks from list of open tables and table cache.
 
1204
      7) If we are not not under LOCK TABLES we rely on close_thread_tables()
 
1205
      call to remove name-locks from table cache and list of open table.
 
1206
    */
 
1207
 
 
1208
    session->set_proc_info("rename result table");
 
1209
 
 
1210
    snprintf(old_name, sizeof(old_name), "%s2-%lx-%"PRIx64, TMP_FILE_PREFIX, (unsigned long) current_pid, session->thread_id);
 
1211
 
 
1212
    my_casedn_str(files_charset_info, old_name);
 
1213
 
 
1214
    wait_while_table_is_used(session, table, HA_EXTRA_PREPARE_FOR_RENAME);
 
1215
    session->close_data_files_and_morph_locks(original_table_identifier);
 
1216
 
 
1217
    error= 0;
 
1218
 
 
1219
    /*
 
1220
      This leads to the storage engine (SE) not being notified for renames in
 
1221
      mysql_rename_table(), because we just juggle with the FRM and nothing
 
1222
      more. If we have an intermediate table, then we notify the SE that
 
1223
      it should become the actual table. Later, we will recycle the old table.
 
1224
      However, in case of ALTER Table RENAME there might be no intermediate
 
1225
      table. This is when the old and new tables are compatible, according to
 
1226
      compare_table(). Then, we need one additional call to
 
1227
    */
 
1228
    TableIdentifier original_table_to_drop(original_table_identifier.getSchemaName(),
 
1229
                                           old_name, message::Table::TEMPORARY);
 
1230
 
 
1231
    if (mysql_rename_table(*session, original_engine, original_table_identifier, original_table_to_drop))
 
1232
    {
 
1233
      error= 1;
 
1234
      quick_rm_table(*session, new_table_as_temporary);
 
1235
    }
 
1236
    else
 
1237
    {
 
1238
      if (mysql_rename_table(*session, new_engine, new_table_as_temporary, new_table_identifier) != 0)
1308
1239
      {
1309
 
        error= ER_ERROR_ON_RENAME;
1310
 
        plugin::StorageEngine::dropTable(*session, new_table_as_temporary);
 
1240
        /* Try to get everything back. */
 
1241
        error= 1;
 
1242
 
 
1243
        quick_rm_table(*session, new_table_identifier);
 
1244
 
 
1245
        quick_rm_table(*session, new_table_as_temporary);
 
1246
 
 
1247
        mysql_rename_table(*session, original_engine, original_table_to_drop, original_table_identifier);
1311
1248
      }
1312
1249
      else
1313
1250
      {
1314
 
        if (rename_table(*session, new_engine, new_table_as_temporary, new_table_identifier) != 0)
1315
 
        {
1316
 
          /* Try to get everything back. */
1317
 
          rename_error= ER_ERROR_ON_RENAME;
1318
 
 
1319
 
          plugin::StorageEngine::dropTable(*session, new_table_identifier);
1320
 
 
1321
 
          plugin::StorageEngine::dropTable(*session, new_table_as_temporary);
1322
 
 
1323
 
          rename_table(*session, original_engine, original_table_to_drop, original_table_identifier);
1324
 
        }
1325
 
        else
1326
 
        {
1327
 
          plugin::StorageEngine::dropTable(*session, original_table_to_drop);
1328
 
        }
1329
 
      }
1330
 
 
1331
 
      if (rename_error)
1332
 
      {
1333
 
        /*
1334
 
          An error happened while we were holding exclusive name-lock on table
1335
 
          being altered. To be safe under LOCK TABLES we should remove placeholders
1336
 
          from list of open tables list and table cache.
1337
 
        */
1338
 
        session->unlink_open_table(table);
1339
 
 
1340
 
        return true;
1341
 
      }
1342
 
    }
 
1251
        quick_rm_table(*session, original_table_to_drop);
 
1252
      }
 
1253
    }
 
1254
 
 
1255
    if (error)
 
1256
    {
 
1257
      /*
 
1258
        An error happened while we were holding exclusive name-lock on table
 
1259
        being altered. To be safe under LOCK TABLES we should remove placeholders
 
1260
        from list of open tables list and table cache.
 
1261
      */
 
1262
      session->unlink_open_table(table);
 
1263
      pthread_mutex_unlock(&LOCK_open);
 
1264
 
 
1265
      return true;
 
1266
    }
 
1267
 
 
1268
    pthread_mutex_unlock(&LOCK_open);
1343
1269
 
1344
1270
    session->set_proc_info("end");
1345
1271
 
1346
 
    write_bin_log(session, *session->getQueryString());
 
1272
    write_bin_log(session, session->query.c_str());
1347
1273
    table_list->table= NULL;
1348
1274
  }
1349
1275
 
1362
1288
           (ulong) (copied + deleted), (ulong) deleted,
1363
1289
           (ulong) session->cuted_fields);
1364
1290
  session->my_ok(copied + deleted, 0, 0L, tmp_name);
1365
 
  session->some_tables_deleted= false;
 
1291
  session->some_tables_deleted= 0;
1366
1292
 
1367
1293
  return false;
1368
1294
}
1369
1295
 
1370
1296
bool alter_table(Session *session,
1371
 
                 identifier::Table &original_table_identifier,
1372
 
                 identifier::Table &new_table_identifier,
 
1297
                 TableIdentifier &original_table_identifier,
 
1298
                 TableIdentifier &new_table_identifier,
1373
1299
                 HA_CREATE_INFO *create_info,
1374
1300
                 const message::Table &original_proto,
1375
1301
                 message::Table &create_proto,
1376
1302
                 TableList *table_list,
1377
1303
                 AlterInfo *alter_info,
1378
1304
                 uint32_t order_num,
1379
 
                 Order *order,
 
1305
                 order_st *order,
1380
1306
                 bool ignore)
1381
1307
{
1382
1308
  bool error;
1385
1311
  if (alter_info->tablespace_op != NO_TABLESPACE_OP)
1386
1312
  {
1387
1313
    /* DISCARD/IMPORT TABLESPACE is always alone in an ALTER Table */
1388
 
    return discard_or_import_tablespace(session, table_list, alter_info->tablespace_op);
 
1314
    return mysql_discard_or_import_tablespace(session, table_list, alter_info->tablespace_op);
1389
1315
  }
1390
1316
 
1391
1317
  session->set_proc_info("init");
1422
1348
 
1423
1349
    if (name_lock)
1424
1350
    {
1425
 
      boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex());
 
1351
      pthread_mutex_lock(&LOCK_open); /* ALTER TABLe */
1426
1352
      session->unlink_open_table(name_lock);
 
1353
      pthread_mutex_unlock(&LOCK_open);
1427
1354
    }
1428
1355
  }
1429
1356
 
1436
1363
                         Table *from, Table *to,
1437
1364
                         List<CreateField> &create,
1438
1365
                         bool ignore,
1439
 
                         uint32_t order_num, Order *order,
 
1366
                         uint32_t order_num, order_st *order,
1440
1367
                         ha_rows *copied,
1441
1368
                         ha_rows *deleted,
1442
1369
                         enum enum_enable_or_disable keys_onoff,
1446
1373
  CopyField *copy,*copy_end;
1447
1374
  ulong found_count,delete_count;
1448
1375
  uint32_t length= 0;
1449
 
  SortField *sortorder;
 
1376
  SORT_FIELD *sortorder;
1450
1377
  ReadRecord info;
1451
1378
  TableList   tables;
1452
1379
  List<Item>   fields;
1466
1393
  /* 
1467
1394
   * LP Bug #552420 
1468
1395
   *
1469
 
   * Since open_temporary_table() doesn't invoke lockTables(), we
 
1396
   * Since open_temporary_table() doesn't invoke mysql_lock_tables(), we
1470
1397
   * don't get the usual automatic call to StorageEngine::startStatement(), so
1471
1398
   * we manually call it here...
1472
1399
   */
1473
 
  to->getMutableShare()->getEngine()->startStatement(session);
 
1400
  to->s->getEngine()->startStatement(session);
1474
1401
 
1475
1402
  if (!(copy= new CopyField[to->getShare()->sizeFields()]))
1476
1403
    return -1;
1482
1409
  alter_table_manage_keys(session, to, from->cursor->indexes_are_disabled(), keys_onoff);
1483
1410
 
1484
1411
  /* We can abort alter table for any table type */
1485
 
  session->setAbortOnWarning(not ignore);
 
1412
  session->abort_on_warning= !ignore;
1486
1413
 
1487
1414
  from->cursor->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);
1488
1415
  to->cursor->ha_start_bulk_insert(from->cursor->stats.records);
1489
1416
 
1490
1417
  List_iterator<CreateField> it(create);
1491
1418
  CreateField *def;
1492
 
  copy_end= copy;
 
1419
  copy_end=copy;
1493
1420
  for (Field **ptr= to->getFields(); *ptr ; ptr++)
1494
1421
  {
1495
1422
    def=it++;
1505
1432
 
1506
1433
  found_count=delete_count=0;
1507
1434
 
1508
 
  do
 
1435
  if (order)
1509
1436
  {
1510
 
    if (order)
1511
 
    {
1512
 
      if (to->getShare()->hasPrimaryKey() && to->cursor->primary_key_is_clustered())
 
1437
    if (to->getShare()->hasPrimaryKey() && to->cursor->primary_key_is_clustered())
 
1438
    {
 
1439
      char warn_buff[DRIZZLE_ERRMSG_SIZE];
 
1440
      snprintf(warn_buff, sizeof(warn_buff),
 
1441
               _("order_st BY ignored because there is a user-defined clustered "
 
1442
                 "index in the table '%-.192s'"),
 
1443
               from->getMutableShare()->getTableName());
 
1444
      push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_WARN, ER_UNKNOWN_ERROR,
 
1445
                   warn_buff);
 
1446
    }
 
1447
    else
 
1448
    {
 
1449
      from->sort.io_cache= new internal::IO_CACHE;
 
1450
 
 
1451
      memset(&tables, 0, sizeof(tables));
 
1452
      tables.table= from;
 
1453
      tables.alias= tables.table_name= const_cast<char *>(from->getMutableShare()->getTableName());
 
1454
      tables.db= const_cast<char *>(from->getMutableShare()->getSchemaName());
 
1455
      error= 1;
 
1456
 
 
1457
      if (session->lex->select_lex.setup_ref_array(session, order_num) ||
 
1458
          setup_order(session, session->lex->select_lex.ref_pointer_array,
 
1459
                      &tables, fields, all_fields, order) ||
 
1460
          !(sortorder= make_unireg_sortorder(order, &length, NULL)) ||
 
1461
          (from->sort.found_records= filesort(session, from, sortorder, length,
 
1462
                                              (optimizer::SqlSelect *) 0, HA_POS_ERROR,
 
1463
                                              1, &examined_rows)) ==
 
1464
          HA_POS_ERROR)
1513
1465
      {
1514
 
        char warn_buff[DRIZZLE_ERRMSG_SIZE];
1515
 
        snprintf(warn_buff, sizeof(warn_buff),
1516
 
                 _("order_st BY ignored because there is a user-defined clustered "
1517
 
                   "index in the table '%-.192s'"),
1518
 
                 from->getMutableShare()->getTableName());
1519
 
        push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_WARN, ER_UNKNOWN_ERROR,
1520
 
                     warn_buff);
 
1466
        goto err;
1521
1467
      }
 
1468
    }
 
1469
  }
 
1470
 
 
1471
  /* Tell handler that we have values for all columns in the to table */
 
1472
  to->use_all_columns();
 
1473
  info.init_read_record(session, from, (optimizer::SqlSelect *) 0, 1, true);
 
1474
  if (ignore)
 
1475
    to->cursor->extra(HA_EXTRA_IGNORE_DUP_KEY);
 
1476
  session->row_count= 0;
 
1477
  to->restoreRecordAsDefault();        // Create empty record
 
1478
  while (!(error=info.read_record(&info)))
 
1479
  {
 
1480
    if (session->killed)
 
1481
    {
 
1482
      session->send_kill_message();
 
1483
      error= 1;
 
1484
      break;
 
1485
    }
 
1486
    session->row_count++;
 
1487
    /* Return error if source table isn't empty. */
 
1488
    if (error_if_not_empty)
 
1489
    {
 
1490
      error= 1;
 
1491
      break;
 
1492
    }
 
1493
    if (to->next_number_field)
 
1494
    {
 
1495
      if (auto_increment_field_copied)
 
1496
        to->auto_increment_field_not_null= true;
1522
1497
      else
1523
 
      {
1524
 
        FileSort filesort(*session);
1525
 
        from->sort.io_cache= new internal::IO_CACHE;
1526
 
 
1527
 
        tables.table= from;
1528
 
        tables.setTableName(const_cast<char *>(from->getMutableShare()->getTableName()));
1529
 
        tables.alias= const_cast<char *>(tables.getTableName());
1530
 
        tables.setSchemaName(const_cast<char *>(from->getMutableShare()->getSchemaName()));
1531
 
        error= 1;
1532
 
 
1533
 
        if (session->lex->select_lex.setup_ref_array(session, order_num) ||
1534
 
            setup_order(session, session->lex->select_lex.ref_pointer_array,
1535
 
                        &tables, fields, all_fields, order) ||
1536
 
            !(sortorder= make_unireg_sortorder(order, &length, NULL)) ||
1537
 
            (from->sort.found_records= filesort.run(from, sortorder, length,
1538
 
                                                    (optimizer::SqlSelect *) 0, HA_POS_ERROR,
1539
 
                                                    1, examined_rows)) == HA_POS_ERROR)
1540
 
        {
1541
 
          break;
1542
 
        }
1543
 
      }
1544
 
    }
1545
 
 
1546
 
    /* Tell handler that we have values for all columns in the to table */
1547
 
    to->use_all_columns();
1548
 
 
1549
 
    error= info.init_read_record(session, from, (optimizer::SqlSelect *) 0, 1, true);
 
1498
        to->next_number_field->reset();
 
1499
    }
 
1500
 
 
1501
    for (CopyField *copy_ptr=copy ; copy_ptr != copy_end ; copy_ptr++)
 
1502
    {
 
1503
      copy_ptr->do_copy(copy_ptr);
 
1504
    }
 
1505
    prev_insert_id= to->cursor->next_insert_id;
 
1506
    error= to->cursor->insertRecord(to->record[0]);
 
1507
    to->auto_increment_field_not_null= false;
 
1508
 
1550
1509
    if (error)
1551
 
    {
1552
 
      to->print_error(errno, MYF(0));
1553
 
 
1554
 
      break;
1555
 
    }
1556
 
 
1557
 
    if (ignore)
1558
 
    {
1559
 
      to->cursor->extra(HA_EXTRA_IGNORE_DUP_KEY);
1560
 
    }
1561
 
 
1562
 
    session->row_count= 0;
1563
 
    to->restoreRecordAsDefault();        // Create empty record
1564
 
    while (not (error=info.read_record(&info)))
1565
 
    {
1566
 
      if (session->getKilled())
1567
 
      {
1568
 
        session->send_kill_message();
1569
 
        error= 1;
1570
 
        break;
1571
 
      }
1572
 
      session->row_count++;
1573
 
      /* Return error if source table isn't empty. */
1574
 
      if (error_if_not_empty)
1575
 
      {
1576
 
        error= 1;
1577
 
        break;
1578
 
      }
1579
 
      if (to->next_number_field)
1580
 
      {
1581
 
        if (auto_increment_field_copied)
1582
 
          to->auto_increment_field_not_null= true;
1583
 
        else
1584
 
          to->next_number_field->reset();
1585
 
      }
1586
 
 
1587
 
      for (CopyField *copy_ptr= copy; copy_ptr != copy_end ; copy_ptr++)
1588
 
      {
1589
 
        if (not copy->to_field->hasDefault() and copy->from_null_ptr and  *copy->from_null_ptr & copy->from_bit)
1590
 
        {
1591
 
          copy->to_field->set_warning(DRIZZLE_ERROR::WARN_LEVEL_WARN,
1592
 
                                      ER_WARN_DATA_TRUNCATED, 1);
1593
 
          copy->to_field->reset();
1594
 
          error= 1;
1595
 
          break;
1596
 
        }
1597
 
 
1598
 
        copy_ptr->do_copy(copy_ptr);
1599
 
      }
1600
 
 
1601
 
      if (error)
1602
 
      {
1603
 
        break;
1604
 
      }
1605
 
 
1606
 
      prev_insert_id= to->cursor->next_insert_id;
1607
 
      error= to->cursor->insertRecord(to->record[0]);
1608
 
      to->auto_increment_field_not_null= false;
1609
 
 
1610
 
      if (error)
 
1510
    { 
 
1511
      if (!ignore ||
 
1512
          to->cursor->is_fatal_error(error, HA_CHECK_DUP))
1611
1513
      { 
1612
 
        if (!ignore || to->cursor->is_fatal_error(error, HA_CHECK_DUP))
1613
 
        { 
1614
 
          to->print_error(error, MYF(0));
1615
 
          break;
1616
 
        }
1617
 
        to->cursor->restore_auto_increment(prev_insert_id);
1618
 
        delete_count++;
1619
 
      }
1620
 
      else
1621
 
      {
1622
 
        found_count++;
1623
 
      }
 
1514
        to->print_error(error, MYF(0));
 
1515
        break;
 
1516
      }
 
1517
      to->cursor->restore_auto_increment(prev_insert_id);
 
1518
      delete_count++;
1624
1519
    }
1625
 
 
1626
 
    info.end_read_record();
1627
 
    from->free_io_cache();
1628
 
    delete [] copy;                             // This is never 0
1629
 
 
1630
 
    if (to->cursor->ha_end_bulk_insert() && error <= 0)
 
1520
    else
1631
1521
    {
1632
 
      to->print_error(errno, MYF(0));
1633
 
      error= 1;
 
1522
      found_count++;
1634
1523
    }
1635
 
    to->cursor->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
1636
 
 
1637
 
    /*
1638
 
      Ensure that the new table is saved properly to disk so that we
1639
 
      can do a rename
1640
 
    */
1641
 
    if (transaction_services.autocommitOrRollback(*session, false))
1642
 
      error= 1;
1643
 
 
1644
 
    if (not session->endActiveTransaction())
1645
 
      error= 1;
1646
 
 
1647
 
  } while (0);
1648
 
 
1649
 
  session->setAbortOnWarning(false);
 
1524
  }
 
1525
 
 
1526
  info.end_read_record();
 
1527
  from->free_io_cache();
 
1528
  delete [] copy;                               // This is never 0
 
1529
 
 
1530
  if (to->cursor->ha_end_bulk_insert() && error <= 0)
 
1531
  {
 
1532
    to->print_error(errno, MYF(0));
 
1533
    error=1;
 
1534
  }
 
1535
  to->cursor->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
 
1536
 
 
1537
  /*
 
1538
    Ensure that the new table is saved properly to disk so that we
 
1539
    can do a rename
 
1540
  */
 
1541
  if (transaction_services.autocommitOrRollback(session, false))
 
1542
    error=1;
 
1543
  if (! session->endActiveTransaction())
 
1544
    error=1;
 
1545
 
 
1546
 err:
 
1547
  session->abort_on_warning= 0;
1650
1548
  from->free_io_cache();
1651
1549
  *copied= found_count;
1652
1550
  *deleted=delete_count;
1653
1551
  to->cursor->ha_release_auto_increment();
1654
 
 
1655
 
  if (to->cursor->ha_external_lock(session, F_UNLCK))
1656
 
  {
 
1552
  if (to->cursor->ha_external_lock(session,F_UNLCK))
1657
1553
    error=1;
1658
 
  }
1659
1554
 
1660
1555
  return(error > 0 ? -1 : 0);
1661
1556
}
1662
1557
 
1663
 
static Table *open_alter_table(Session *session, Table *table, identifier::Table &identifier)
 
1558
static int
 
1559
create_temporary_table(Session *session,
 
1560
                       TableIdentifier &identifier,
 
1561
                       HA_CREATE_INFO *create_info,
 
1562
                       message::Table &create_proto,
 
1563
                       AlterInfo *alter_info)
 
1564
{
 
1565
  int error;
 
1566
 
 
1567
  /*
 
1568
    Create a table with a temporary name.
 
1569
    We don't log the statement, it will be logged later.
 
1570
  */
 
1571
  create_proto.set_name(identifier.getTableName());
 
1572
 
 
1573
  create_proto.mutable_engine()->set_name(create_info->db_type->getName());
 
1574
 
 
1575
  error= mysql_create_table(session,
 
1576
                            identifier,
 
1577
                            create_info, create_proto, alter_info, true, 0, false);
 
1578
 
 
1579
  return error;
 
1580
}
 
1581
 
 
1582
static Table *open_alter_table(Session *session, Table *table, TableIdentifier &identifier)
1664
1583
{
1665
1584
  Table *new_table;
1666
1585
 
1668
1587
  if (table->getShare()->getType())
1669
1588
  {
1670
1589
    TableList tbl;
1671
 
    tbl.setSchemaName(const_cast<char *>(identifier.getSchemaName().c_str()));
 
1590
    tbl.db= const_cast<char *>(identifier.getSchemaName().c_str());
1672
1591
    tbl.alias= const_cast<char *>(identifier.getTableName().c_str());
1673
 
    tbl.setTableName(const_cast<char *>(identifier.getTableName().c_str()));
 
1592
    tbl.table_name= const_cast<char *>(identifier.getTableName().c_str());
1674
1593
 
1675
1594
    /* Table is in session->temporary_tables */
1676
1595
    new_table= session->openTable(&tbl, (bool*) 0, DRIZZLE_LOCK_IGNORE_FLUSH);