~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/statement/alter_table.cc

  • Committer: Brian Aker
  • Date: 2010-08-09 18:04:12 UTC
  • mfrom: (1689.3.7 staging)
  • Revision ID: brian@gaz-20100809180412-olurwh51ojllev6p
Merge in heap conversion, and case insensitive patch, and remove need for
M_HASH in session.

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
18
18
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19
19
 */
20
20
 
21
 
#include <config.h>
 
21
#include "config.h"
22
22
 
23
23
#include <fcntl.h>
24
24
 
25
25
#include <sstream>
26
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
 
 
33
 
 
34
 
#include <drizzled/gettext.h>
35
 
#include <drizzled/data_home.h>
36
 
#include <drizzled/sql_table.h>
37
 
#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
 
#include <drizzled/plugin/storage_engine.h>
45
 
#include <drizzled/copy_field.h>
46
 
 
47
 
#include <drizzled/transaction_services.h>
48
 
 
49
 
#include <drizzled/filesort.h>
50
 
 
51
 
#include <drizzled/message.h>
 
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
 
 
33
 
 
34
#include "drizzled/gettext.h"
 
35
#include "drizzled/data_home.h"
 
36
#include "drizzled/sql_table.h"
 
37
#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"
52
46
 
53
47
using namespace std;
54
48
 
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->getLex()->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()->getLex()->select_lex.table_list.first;
95
 
  TableList *all_tables= getSession()->getLex()->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()->getLex()->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 (not (original_table_message= plugin::StorageEngine::getTableMessage(*getSession(), identifier)))
 
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()->getLex()->name.str ? getSession()->getLex()->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()->getLex()->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()->getLex()->name.str ? getSession()->getLex()->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()->getLex()->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;
256
245
  /* New key definitions are added here */
257
246
  List<Key> new_key_list;
258
 
  List<AlterDrop>::iterator drop_it(alter_info->drop_list.begin());
259
 
  List<CreateField>::iterator def_it(alter_info->create_list.begin());
260
 
  List<AlterColumn>::iterator alter_it(alter_info->alter_list.begin());
261
 
  List<Key>::iterator key_it(alter_info->key_list.begin());
262
 
  List<CreateField>::iterator find_it(new_create_list.begin());
263
 
  List<CreateField>::iterator field_it(new_create_list.begin());
 
247
  List_iterator<AlterDrop> drop_it(alter_info->drop_list);
 
248
  List_iterator<CreateField> def_it(alter_info->create_list);
 
249
  List_iterator<AlterColumn> alter_it(alter_info->alter_list);
 
250
  List_iterator<Key> key_it(alter_info->key_list);
 
251
  List_iterator<CreateField> find_it(new_create_list);
 
252
  List_iterator<CreateField> field_it(new_create_list);
264
253
  List<Key_part_spec> key_parts;
265
254
  uint32_t used_fields= create_info->used_fields;
266
255
  KeyInfo *key_info= table->key_info;
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;
294
 
    drop_it= alter_info->drop_list.begin();
 
281
    drop_it.rewind();
295
282
    while ((drop= drop_it++))
296
283
    {
297
284
      if (drop->type == AlterDrop::COLUMN &&
307
294
        break;
308
295
      }
309
296
    }
310
 
 
311
297
    if (drop)
312
298
    {
313
299
      drop_it.remove();
318
304
    field->setReadSet();
319
305
 
320
306
    /* Check if field is changed */
321
 
    def_it= alter_info->create_list.begin();
 
307
    def_it.rewind();
322
308
    while ((def= def_it++))
323
309
    {
324
310
      if (def->change &&
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 */
344
329
      */
345
330
      def= new CreateField(field, field);
346
331
      new_create_list.push_back(def);
347
 
      alter_it= alter_info->alter_list.begin(); /* Change default if ALTER */
 
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
 
  def_it= alter_info->create_list.begin();
 
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
 
      find_it= new_create_list.begin();
405
 
 
 
387
      find_it.rewind();
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
 
    drop_it= alter_info->drop_list.begin();
 
441
    drop_it.rewind();
467
442
    while ((drop= drop_it++))
468
443
    {
469
444
      if (drop->type == AlterDrop::KEY &&
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();
478
452
    }
479
453
 
480
454
    KeyPartInfo *key_part= key_info->key_part;
481
 
    key_parts.clear();
 
455
    key_parts.empty();
482
456
    for (uint32_t j= 0; j < key_info->key_parts; j++, key_part++)
483
457
    {
484
458
      if (! key_part->field)
486
460
 
487
461
      const char *key_part_name= key_part->field->field_name;
488
462
      CreateField *cfield;
489
 
      field_it= new_create_list.begin();
 
463
      field_it.rewind();
490
464
      while ((cfield= field_it++))
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= alter_info->drop_list.begin();
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
        LOCK_open.lock(); /* ALTER TABLe */
 
753
        session.unlink_open_table(name_lock);
 
754
        LOCK_open.unlock();
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
{
917
819
  int error= 0;
920
822
  ha_rows copied= 0;
921
823
  ha_rows deleted= 0;
922
824
 
923
 
  if (not original_table_identifier.isValid())
924
 
    return true;
925
 
 
926
 
  if (not new_table_identifier.isValid())
927
 
    return true;
928
 
 
929
825
  session->set_proc_info("init");
930
826
 
931
827
  table->use_all_columns();
961
857
  if (original_engine->check_flag(HTON_BIT_ALTER_NOT_SUPPORTED) ||
962
858
      new_engine->check_flag(HTON_BIT_ALTER_NOT_SUPPORTED))
963
859
  {
964
 
    my_error(ER_ILLEGAL_HA, new_table_identifier);
 
860
    my_error(ER_ILLEGAL_HA, MYF(0), new_table_identifier.getSQLPath().c_str());
965
861
 
966
862
    return true;
967
863
  }
979
875
    tmp.reset(ALTER_KEYS_ONOFF);
980
876
    tmp&= alter_info->flags;
981
877
 
982
 
    if (not (tmp.any()) && not table->getShare()->getType()) // no need to touch frm
 
878
    if (! (tmp.any()) && ! table->getShare()->getType()) // no need to touch frm
983
879
    {
984
880
      switch (alter_info->keys_onoff)
985
881
      {
986
882
      case LEAVE_AS_IS:
987
883
        break;
988
 
 
989
884
      case ENABLE:
990
885
        /*
991
886
          wait_while_table_is_used() ensures that table being altered is
996
891
          while the fact that the table is still open gives us protection
997
892
          from concurrent DDL statements.
998
893
        */
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
 
        }
 
894
        LOCK_open.lock(); /* DDL wait for/blocker */
 
895
        wait_while_table_is_used(session, table, HA_EXTRA_FORCE_REOPEN);
 
896
        LOCK_open.unlock();
1003
897
        error= table->cursor->ha_enable_indexes(HA_KEY_SWITCH_NONUNIQ_SAVE);
1004
 
 
1005
898
        /* COND_refresh will be signaled in close_thread_tables() */
1006
899
        break;
1007
 
 
1008
900
      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
 
 
 
901
        LOCK_open.lock(); /* DDL wait for/blocker */
 
902
        wait_while_table_is_used(session, table, HA_EXTRA_FORCE_REOPEN);
 
903
        LOCK_open.unlock();
 
904
        error=table->cursor->ha_disable_indexes(HA_KEY_SWITCH_NONUNIQ_SAVE);
1015
905
        /* COND_refresh will be signaled in close_thread_tables() */
1016
906
        break;
 
907
      default:
 
908
        assert(false);
 
909
        error= 0;
 
910
        break;
1017
911
      }
1018
912
 
1019
913
      if (error == HA_ERR_WRONG_COMMAND)
1020
914
      {
1021
 
        error= EE_OK;
 
915
        error= 0;
1022
916
        push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
1023
917
                            ER_ILLEGAL_HA, ER(ER_ILLEGAL_HA),
1024
918
                            table->getAlias());
1025
919
      }
1026
920
 
1027
 
      boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex()); /* Lock to remove all instances of table from table cache before ALTER */
 
921
      LOCK_open.lock(); /* Lock to remove all instances of table from table cache before ALTER */
1028
922
      /*
1029
923
        Unlike to the above case close_cached_table() below will remove ALL
1030
924
        instances of Table from table cache (it will also remove table lock
1031
925
        held by this thread). So to make actual table renaming and writing
1032
926
        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.
 
927
        protected by LOCK_open mutex. This also removes gap for races between
 
928
        access() and mysql_rename_table() calls.
1035
929
      */
1036
930
 
1037
 
      if (not error &&  not (original_table_identifier == new_table_identifier))
 
931
      if (error == 0 &&  not (original_table_identifier == new_table_identifier))
1038
932
      {
1039
933
        session->set_proc_info("rename");
1040
934
        /*
1052
946
        */
1053
947
        if (plugin::StorageEngine::doesTableExist(*session, new_table_identifier))
1054
948
        {
1055
 
          my_error(ER_TABLE_EXISTS_ERROR, new_table_identifier);
 
949
          my_error(ER_TABLE_EXISTS_ERROR, MYF(0), new_table_identifier.getSQLPath().c_str());
1056
950
          error= -1;
1057
951
        }
1058
952
        else
1059
953
        {
1060
 
          if (rename_table(*session, original_engine, original_table_identifier, new_table_identifier))
 
954
          if (mysql_rename_table(*session, original_engine, original_table_identifier, new_table_identifier))
1061
955
          {
1062
956
            error= -1;
1063
957
          }
1066
960
 
1067
961
      if (error == HA_ERR_WRONG_COMMAND)
1068
962
      {
1069
 
        error= EE_OK;
 
963
        error= 0;
1070
964
        push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
1071
965
                            ER_ILLEGAL_HA, ER(ER_ILLEGAL_HA),
1072
966
                            table->getAlias());
1073
967
      }
1074
968
 
1075
 
      if (not error)
 
969
      if (error == 0)
1076
970
      {
1077
 
        TransactionServices &transaction_services= TransactionServices::singleton();
1078
 
        transaction_services.allocateNewTransactionId();
1079
 
        write_bin_log(session, *session->getQueryString());
 
971
        write_bin_log(session, session->query.c_str());
1080
972
        session->my_ok();
1081
973
      }
1082
 
      else if (error > EE_OK) // If we have already set the error, we pass along -1
 
974
      else if (error > 0)
1083
975
      {
1084
976
        table->print_error(error, MYF(0));
 
977
        error= -1;
1085
978
      }
1086
979
 
 
980
      LOCK_open.unlock();
1087
981
      table_list->table= NULL;
1088
982
 
1089
983
      return error;
1093
987
  /* We have to do full alter table. */
1094
988
  new_engine= create_info->db_type;
1095
989
 
1096
 
  if (prepare_alter_table(session, table, create_info, original_proto, create_proto, alter_info))
 
990
  if (mysql_prepare_alter_table(session, table, create_info, original_proto, create_proto, alter_info))
1097
991
  {
1098
992
    return true;
1099
993
  }
1110
1004
    case we just use it as is. Neither of these tables require locks in order to  be
1111
1005
    filled.
1112
1006
  */
1113
 
  identifier::Table new_table_as_temporary(original_table_identifier.getSchemaName(),
 
1007
  TableIdentifier new_table_as_temporary(original_table_identifier.getSchemaName(),
1114
1008
                                         tmp_name,
1115
1009
                                         create_proto.type() != message::Table::TEMPORARY ? message::Table::INTERNAL :
1116
1010
                                         message::Table::TEMPORARY);
1117
1011
 
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);
 
1012
  error= create_temporary_table(session, new_table_as_temporary, create_info, create_proto, alter_info);
1128
1013
 
1129
1014
  if (error != 0)
1130
1015
  {
1137
1022
 
1138
1023
  if (not new_table)
1139
1024
  {
1140
 
    plugin::StorageEngine::dropTable(*session, new_table_as_temporary);
 
1025
    quick_rm_table(*session, new_table_as_temporary);
1141
1026
    return true;
1142
1027
  }
1143
1028
 
1174
1059
  {
1175
1060
 
1176
1061
    /*
1177
 
      No default value was provided for new fields.
 
1062
      No default value was provided for a DATE/DATETIME field, the
 
1063
      current sql_mode doesn't allow the '0000-00-00' value and
 
1064
      the table to be altered isn't empty.
 
1065
      Report error here.
1178
1066
    */
1179
1067
    if (alter_info->error_if_not_empty && session->row_count)
1180
1068
    {
1181
 
      my_error(ER_INVALID_ALTER_TABLE_FOR_NOT_NULL, MYF(0));
 
1069
      const char *f_val= 0;
 
1070
      enum enum_drizzle_timestamp_type t_type= DRIZZLE_TIMESTAMP_DATE;
 
1071
 
 
1072
      switch (alter_info->datetime_field->sql_type)
 
1073
      {
 
1074
      case DRIZZLE_TYPE_DATE:
 
1075
        f_val= "0000-00-00";
 
1076
        t_type= DRIZZLE_TIMESTAMP_DATE;
 
1077
        break;
 
1078
      case DRIZZLE_TYPE_DATETIME:
 
1079
        f_val= "0000-00-00 00:00:00";
 
1080
        t_type= DRIZZLE_TIMESTAMP_DATETIME;
 
1081
        break;
 
1082
      default:
 
1083
        /* Shouldn't get here. */
 
1084
        assert(0);
 
1085
      }
 
1086
      bool save_abort_on_warning= session->abort_on_warning;
 
1087
      session->abort_on_warning= true;
 
1088
      make_truncated_value_warning(session, DRIZZLE_ERROR::WARN_LEVEL_ERROR,
 
1089
                                   f_val, internal::strlength(f_val), t_type,
 
1090
                                   alter_info->datetime_field->field_name);
 
1091
      session->abort_on_warning= save_abort_on_warning;
1182
1092
    }
1183
1093
 
1184
1094
    if (original_table_identifier.isTmp())
1190
1100
      }
1191
1101
      else
1192
1102
      {
1193
 
        plugin::StorageEngine::dropTable(*session, new_table_as_temporary);
 
1103
        quick_rm_table(*session, new_table_as_temporary);
1194
1104
      }
1195
1105
 
1196
1106
      return true;
1206
1116
        new_table->intern_close_table();
1207
1117
        if (new_table->hasShare())
1208
1118
        {
1209
 
          delete new_table->getMutableShare();
 
1119
          delete new_table->s;
 
1120
          new_table->s= NULL;
1210
1121
        }
1211
1122
 
1212
1123
        delete new_table;
1213
1124
      }
1214
1125
 
1215
 
      boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex());
 
1126
      LOCK_open.lock(); /* ALTER TABLE */
1216
1127
 
1217
 
      plugin::StorageEngine::dropTable(*session, new_table_as_temporary);
 
1128
      quick_rm_table(*session, new_table_as_temporary);
 
1129
      LOCK_open.unlock();
1218
1130
 
1219
1131
      return true;
1220
1132
    }
1225
1137
    /* Close lock if this is a transactional table */
1226
1138
    if (session->lock)
1227
1139
    {
1228
 
      session->unlockTables(session->lock);
 
1140
      mysql_unlock_tables(session, session->lock);
1229
1141
      session->lock= 0;
1230
1142
    }
1231
1143
 
1237
1149
 
1238
1150
    new_table_identifier.setPath(new_table_as_temporary.getPath());
1239
1151
 
1240
 
    if (rename_table(*session, new_engine, new_table_as_temporary, new_table_identifier) != 0)
 
1152
    if (mysql_rename_table(*session, new_engine, new_table_as_temporary, new_table_identifier) != 0)
1241
1153
    {
1242
1154
      return true;
1243
1155
    }
1255
1167
 
1256
1168
      if (new_table->hasShare())
1257
1169
      {
1258
 
        delete new_table->getMutableShare();
 
1170
        delete new_table->s;
 
1171
        new_table->s= NULL;
1259
1172
      }
1260
1173
 
1261
1174
      delete new_table;
1262
1175
    }
1263
1176
 
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))
 
1177
    LOCK_open.lock(); /* ALTER TABLE */
 
1178
 
 
1179
    /*
 
1180
      Data is copied. Now we:
 
1181
      1) Wait until all other threads close old version of table.
 
1182
      2) Close instances of table open by this thread and replace them
 
1183
      with exclusive name-locks.
 
1184
      3) Rename the old table to a temp name, rename the new one to the
 
1185
      old name.
 
1186
      4) If we are under LOCK TABLES and don't do ALTER Table ... RENAME
 
1187
      we reopen new version of table.
 
1188
      5) Write statement to the binary log.
 
1189
      6) If we are under LOCK TABLES and do ALTER Table ... RENAME we
 
1190
      remove name-locks from list of open tables and table cache.
 
1191
      7) If we are not not under LOCK TABLES we rely on close_thread_tables()
 
1192
      call to remove name-locks from table cache and list of open table.
 
1193
    */
 
1194
 
 
1195
    session->set_proc_info("rename result table");
 
1196
 
 
1197
    snprintf(old_name, sizeof(old_name), "%s2-%lx-%"PRIx64, TMP_FILE_PREFIX, (unsigned long) current_pid, session->thread_id);
 
1198
 
 
1199
    my_casedn_str(files_charset_info, old_name);
 
1200
 
 
1201
    wait_while_table_is_used(session, table, HA_EXTRA_PREPARE_FOR_RENAME);
 
1202
    session->close_data_files_and_morph_locks(original_table_identifier);
 
1203
 
 
1204
    error= 0;
 
1205
 
 
1206
    /*
 
1207
      This leads to the storage engine (SE) not being notified for renames in
 
1208
      mysql_rename_table(), because we just juggle with the FRM and nothing
 
1209
      more. If we have an intermediate table, then we notify the SE that
 
1210
      it should become the actual table. Later, we will recycle the old table.
 
1211
      However, in case of ALTER Table RENAME there might be no intermediate
 
1212
      table. This is when the old and new tables are compatible, according to
 
1213
      compare_table(). Then, we need one additional call to
 
1214
    */
 
1215
    TableIdentifier original_table_to_drop(original_table_identifier.getSchemaName(),
 
1216
                                           old_name, message::Table::TEMPORARY);
 
1217
 
 
1218
    if (mysql_rename_table(*session, original_engine, original_table_identifier, original_table_to_drop))
 
1219
    {
 
1220
      error= 1;
 
1221
      quick_rm_table(*session, new_table_as_temporary);
 
1222
    }
 
1223
    else
 
1224
    {
 
1225
      if (mysql_rename_table(*session, new_engine, new_table_as_temporary, new_table_identifier) != 0)
1308
1226
      {
1309
 
        error= ER_ERROR_ON_RENAME;
1310
 
        plugin::StorageEngine::dropTable(*session, new_table_as_temporary);
 
1227
        /* Try to get everything back. */
 
1228
        error= 1;
 
1229
 
 
1230
        quick_rm_table(*session, new_table_identifier);
 
1231
 
 
1232
        quick_rm_table(*session, new_table_as_temporary);
 
1233
 
 
1234
        mysql_rename_table(*session, original_engine, original_table_to_drop, original_table_identifier);
1311
1235
      }
1312
1236
      else
1313
1237
      {
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
 
    }
 
1238
        quick_rm_table(*session, original_table_to_drop);
 
1239
      }
 
1240
    }
 
1241
 
 
1242
    if (error)
 
1243
    {
 
1244
      /*
 
1245
        An error happened while we were holding exclusive name-lock on table
 
1246
        being altered. To be safe under LOCK TABLES we should remove placeholders
 
1247
        from list of open tables list and table cache.
 
1248
      */
 
1249
      session->unlink_open_table(table);
 
1250
      LOCK_open.unlock();
 
1251
 
 
1252
      return true;
 
1253
    }
 
1254
 
 
1255
    LOCK_open.unlock();
1343
1256
 
1344
1257
    session->set_proc_info("end");
1345
1258
 
1346
 
    write_bin_log(session, *session->getQueryString());
 
1259
    write_bin_log(session, session->query.c_str());
1347
1260
    table_list->table= NULL;
1348
1261
  }
1349
1262
 
1362
1275
           (ulong) (copied + deleted), (ulong) deleted,
1363
1276
           (ulong) session->cuted_fields);
1364
1277
  session->my_ok(copied + deleted, 0, 0L, tmp_name);
1365
 
  session->some_tables_deleted= false;
 
1278
  session->some_tables_deleted= 0;
1366
1279
 
1367
1280
  return false;
1368
1281
}
1369
1282
 
1370
1283
bool alter_table(Session *session,
1371
 
                 identifier::Table &original_table_identifier,
1372
 
                 identifier::Table &new_table_identifier,
 
1284
                 TableIdentifier &original_table_identifier,
 
1285
                 TableIdentifier &new_table_identifier,
1373
1286
                 HA_CREATE_INFO *create_info,
1374
1287
                 const message::Table &original_proto,
1375
1288
                 message::Table &create_proto,
1376
1289
                 TableList *table_list,
1377
1290
                 AlterInfo *alter_info,
1378
1291
                 uint32_t order_num,
1379
 
                 Order *order,
 
1292
                 order_st *order,
1380
1293
                 bool ignore)
1381
1294
{
1382
1295
  bool error;
1385
1298
  if (alter_info->tablespace_op != NO_TABLESPACE_OP)
1386
1299
  {
1387
1300
    /* DISCARD/IMPORT TABLESPACE is always alone in an ALTER Table */
1388
 
    return discard_or_import_tablespace(session, table_list, alter_info->tablespace_op);
 
1301
    return mysql_discard_or_import_tablespace(session, table_list, alter_info->tablespace_op);
1389
1302
  }
1390
1303
 
1391
1304
  session->set_proc_info("init");
1422
1335
 
1423
1336
    if (name_lock)
1424
1337
    {
1425
 
      boost::mutex::scoped_lock scopedLock(table::Cache::singleton().mutex());
 
1338
      LOCK_open.lock(); /* ALTER TABLe */
1426
1339
      session->unlink_open_table(name_lock);
 
1340
      LOCK_open.unlock();
1427
1341
    }
1428
1342
  }
1429
1343
 
1436
1350
                         Table *from, Table *to,
1437
1351
                         List<CreateField> &create,
1438
1352
                         bool ignore,
1439
 
                         uint32_t order_num, Order *order,
 
1353
                         uint32_t order_num, order_st *order,
1440
1354
                         ha_rows *copied,
1441
1355
                         ha_rows *deleted,
1442
1356
                         enum enum_enable_or_disable keys_onoff,
1446
1360
  CopyField *copy,*copy_end;
1447
1361
  ulong found_count,delete_count;
1448
1362
  uint32_t length= 0;
1449
 
  SortField *sortorder;
 
1363
  SORT_FIELD *sortorder;
1450
1364
  ReadRecord info;
1451
1365
  TableList   tables;
1452
1366
  List<Item>   fields;
1466
1380
  /* 
1467
1381
   * LP Bug #552420 
1468
1382
   *
1469
 
   * Since open_temporary_table() doesn't invoke lockTables(), we
 
1383
   * Since open_temporary_table() doesn't invoke mysql_lock_tables(), we
1470
1384
   * don't get the usual automatic call to StorageEngine::startStatement(), so
1471
1385
   * we manually call it here...
1472
1386
   */
1473
 
  to->getMutableShare()->getEngine()->startStatement(session);
 
1387
  to->s->getEngine()->startStatement(session);
1474
1388
 
1475
1389
  if (!(copy= new CopyField[to->getShare()->sizeFields()]))
1476
1390
    return -1;
1482
1396
  alter_table_manage_keys(session, to, from->cursor->indexes_are_disabled(), keys_onoff);
1483
1397
 
1484
1398
  /* We can abort alter table for any table type */
1485
 
  session->setAbortOnWarning(not ignore);
 
1399
  session->abort_on_warning= !ignore;
1486
1400
 
1487
1401
  from->cursor->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);
1488
1402
  to->cursor->ha_start_bulk_insert(from->cursor->stats.records);
1489
1403
 
1490
 
  List<CreateField>::iterator it(create.begin());
 
1404
  List_iterator<CreateField> it(create);
1491
1405
  CreateField *def;
1492
 
  copy_end= copy;
 
1406
  copy_end=copy;
1493
1407
  for (Field **ptr= to->getFields(); *ptr ; ptr++)
1494
1408
  {
1495
1409
    def=it++;
1505
1419
 
1506
1420
  found_count=delete_count=0;
1507
1421
 
1508
 
  do
 
1422
  if (order)
1509
1423
  {
1510
 
    if (order)
1511
 
    {
1512
 
      if (to->getShare()->hasPrimaryKey() && to->cursor->primary_key_is_clustered())
 
1424
    if (to->getShare()->hasPrimaryKey() && to->cursor->primary_key_is_clustered())
 
1425
    {
 
1426
      char warn_buff[DRIZZLE_ERRMSG_SIZE];
 
1427
      snprintf(warn_buff, sizeof(warn_buff),
 
1428
               _("order_st BY ignored because there is a user-defined clustered "
 
1429
                 "index in the table '%-.192s'"),
 
1430
               from->getMutableShare()->getTableName());
 
1431
      push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_WARN, ER_UNKNOWN_ERROR,
 
1432
                   warn_buff);
 
1433
    }
 
1434
    else
 
1435
    {
 
1436
      from->sort.io_cache= new internal::IO_CACHE;
 
1437
 
 
1438
      memset(&tables, 0, sizeof(tables));
 
1439
      tables.table= from;
 
1440
      tables.alias= tables.table_name= const_cast<char *>(from->getMutableShare()->getTableName());
 
1441
      tables.db= const_cast<char *>(from->getMutableShare()->getSchemaName());
 
1442
      error= 1;
 
1443
 
 
1444
      if (session->lex->select_lex.setup_ref_array(session, order_num) ||
 
1445
          setup_order(session, session->lex->select_lex.ref_pointer_array,
 
1446
                      &tables, fields, all_fields, order) ||
 
1447
          !(sortorder= make_unireg_sortorder(order, &length, NULL)) ||
 
1448
          (from->sort.found_records= filesort(session, from, sortorder, length,
 
1449
                                              (optimizer::SqlSelect *) 0, HA_POS_ERROR,
 
1450
                                              1, &examined_rows)) ==
 
1451
          HA_POS_ERROR)
1513
1452
      {
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);
 
1453
        goto err;
1521
1454
      }
 
1455
    }
 
1456
  }
 
1457
 
 
1458
  /* Tell handler that we have values for all columns in the to table */
 
1459
  to->use_all_columns();
 
1460
  info.init_read_record(session, from, (optimizer::SqlSelect *) 0, 1, true);
 
1461
  if (ignore)
 
1462
    to->cursor->extra(HA_EXTRA_IGNORE_DUP_KEY);
 
1463
  session->row_count= 0;
 
1464
  to->restoreRecordAsDefault();        // Create empty record
 
1465
  while (!(error=info.read_record(&info)))
 
1466
  {
 
1467
    if (session->killed)
 
1468
    {
 
1469
      session->send_kill_message();
 
1470
      error= 1;
 
1471
      break;
 
1472
    }
 
1473
    session->row_count++;
 
1474
    /* Return error if source table isn't empty. */
 
1475
    if (error_if_not_empty)
 
1476
    {
 
1477
      error= 1;
 
1478
      break;
 
1479
    }
 
1480
    if (to->next_number_field)
 
1481
    {
 
1482
      if (auto_increment_field_copied)
 
1483
        to->auto_increment_field_not_null= true;
1522
1484
      else
1523
 
      {
1524
 
        FileSort filesort(*session);
1525
 
        from->sort.io_cache= new internal::IO_CACHE;
1526
 
 
1527
 
        tables.table= from;
1528
 
        tables.setTableName(from->getMutableShare()->getTableName());
1529
 
        tables.alias= tables.getTableName();
1530
 
        tables.setSchemaName(const_cast<char *>(from->getMutableShare()->getSchemaName()));
1531
 
        error= 1;
1532
 
 
1533
 
        if (session->getLex()->select_lex.setup_ref_array(session, order_num) ||
1534
 
            setup_order(session, session->getLex()->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);
 
1485
        to->next_number_field->reset();
 
1486
    }
 
1487
 
 
1488
    for (CopyField *copy_ptr=copy ; copy_ptr != copy_end ; copy_ptr++)
 
1489
    {
 
1490
      copy_ptr->do_copy(copy_ptr);
 
1491
    }
 
1492
    prev_insert_id= to->cursor->next_insert_id;
 
1493
    error= to->cursor->insertRecord(to->record[0]);
 
1494
    to->auto_increment_field_not_null= false;
 
1495
 
1550
1496
    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)
 
1497
    { 
 
1498
      if (!ignore ||
 
1499
          to->cursor->is_fatal_error(error, HA_CHECK_DUP))
1611
1500
      { 
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
 
      }
 
1501
        to->print_error(error, MYF(0));
 
1502
        break;
 
1503
      }
 
1504
      to->cursor->restore_auto_increment(prev_insert_id);
 
1505
      delete_count++;
1624
1506
    }
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)
 
1507
    else
1631
1508
    {
1632
 
      to->print_error(errno, MYF(0));
1633
 
      error= 1;
 
1509
      found_count++;
1634
1510
    }
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);
 
1511
  }
 
1512
 
 
1513
  info.end_read_record();
 
1514
  from->free_io_cache();
 
1515
  delete [] copy;                               // This is never 0
 
1516
 
 
1517
  if (to->cursor->ha_end_bulk_insert() && error <= 0)
 
1518
  {
 
1519
    to->print_error(errno, MYF(0));
 
1520
    error=1;
 
1521
  }
 
1522
  to->cursor->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
 
1523
 
 
1524
  /*
 
1525
    Ensure that the new table is saved properly to disk so that we
 
1526
    can do a rename
 
1527
  */
 
1528
  if (transaction_services.autocommitOrRollback(session, false))
 
1529
    error=1;
 
1530
  if (! session->endActiveTransaction())
 
1531
    error=1;
 
1532
 
 
1533
 err:
 
1534
  session->abort_on_warning= 0;
1650
1535
  from->free_io_cache();
1651
1536
  *copied= found_count;
1652
1537
  *deleted=delete_count;
1653
1538
  to->cursor->ha_release_auto_increment();
1654
 
 
1655
 
  if (to->cursor->ha_external_lock(session, F_UNLCK))
1656
 
  {
 
1539
  if (to->cursor->ha_external_lock(session,F_UNLCK))
1657
1540
    error=1;
1658
 
  }
1659
1541
 
1660
1542
  return(error > 0 ? -1 : 0);
1661
1543
}
1662
1544
 
1663
 
static Table *open_alter_table(Session *session, Table *table, identifier::Table &identifier)
 
1545
static int
 
1546
create_temporary_table(Session *session,
 
1547
                       TableIdentifier &identifier,
 
1548
                       HA_CREATE_INFO *create_info,
 
1549
                       message::Table &create_proto,
 
1550
                       AlterInfo *alter_info)
 
1551
{
 
1552
  int error;
 
1553
 
 
1554
  /*
 
1555
    Create a table with a temporary name.
 
1556
    We don't log the statement, it will be logged later.
 
1557
  */
 
1558
  create_proto.set_name(identifier.getTableName());
 
1559
 
 
1560
  create_proto.mutable_engine()->set_name(create_info->db_type->getName());
 
1561
 
 
1562
  error= mysql_create_table(session,
 
1563
                            identifier,
 
1564
                            create_info, create_proto, alter_info, true, 0, false);
 
1565
 
 
1566
  return error;
 
1567
}
 
1568
 
 
1569
static Table *open_alter_table(Session *session, Table *table, TableIdentifier &identifier)
1664
1570
{
1665
1571
  Table *new_table;
1666
1572
 
1668
1574
  if (table->getShare()->getType())
1669
1575
  {
1670
1576
    TableList tbl;
1671
 
    tbl.setSchemaName(const_cast<char *>(identifier.getSchemaName().c_str()));
 
1577
    tbl.db= const_cast<char *>(identifier.getSchemaName().c_str());
1672
1578
    tbl.alias= const_cast<char *>(identifier.getTableName().c_str());
1673
 
    tbl.setTableName(const_cast<char *>(identifier.getTableName().c_str()));
 
1579
    tbl.table_name= const_cast<char *>(identifier.getTableName().c_str());
1674
1580
 
1675
1581
    /* Table is in session->temporary_tables */
1676
1582
    new_table= session->openTable(&tbl, (bool*) 0, DRIZZLE_LOCK_IGNORE_FLUSH);