drizzle
C++ MySQL-protocol-compatible database server
Loading...
Searching...
No Matches
alter_table.cc
1/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
2 * vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
3 *
4 * Copyright (C) 2009 Sun Microsystems, Inc.
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
21#include <config.h>
22
23#include <fcntl.h>
24
25#include <sstream>
26
27#include <drizzled/show.h>
28#include <drizzled/lock.h>
29#include <drizzled/session.h>
30#include <drizzled/statement/alter_table.h>
31#include <drizzled/charset.h>
32#include <drizzled/gettext.h>
33#include <drizzled/data_home.h>
34#include <drizzled/sql_table.h>
35#include <drizzled/table_proto.h>
36#include <drizzled/optimizer/range.h>
37#include <drizzled/time_functions.h>
38#include <drizzled/records.h>
39#include <drizzled/pthread_globals.h>
40#include <drizzled/internal/my_sys.h>
41#include <drizzled/internal/iocache.h>
42#include <drizzled/plugin/storage_engine.h>
43#include <drizzled/copy_field.h>
44#include <drizzled/transaction_services.h>
45#include <drizzled/filesort.h>
46#include <drizzled/message.h>
47#include <drizzled/message/alter_table.pb.h>
48#include <drizzled/alter_column.h>
49#include <drizzled/alter_info.h>
50#include <drizzled/util/test.h>
51#include <drizzled/open_tables_state.h>
52#include <drizzled/table/cache.h>
53#include <drizzled/create_field.h>
54#include <drizzled/catalog/instance.h>
55#include <drizzled/key_part_info.h>
56
57using namespace std;
58
59namespace drizzled {
60
61extern pid_t current_pid;
62
63static int copy_data_between_tables(Session *session,
64 Table *from,Table *to,
65 List<CreateField> &create,
66 bool ignore,
67 uint32_t order_num,
68 Order *order,
69 ha_rows *copied,
70 ha_rows *deleted,
71 message::AlterTable &alter_table_message,
72 bool error_if_not_empty);
73
74static bool prepare_alter_table(Session *session,
75 Table *table,
76 HA_CREATE_INFO *create_info,
77 const message::Table &original_proto,
78 message::Table &table_message,
79 message::AlterTable &alter_table_message,
80 AlterInfo *alter_info);
81
82static Table *open_alter_table(Session *session, Table *table, identifier::Table &identifier);
83
84static int apply_online_alter_keys_onoff(Session *session,
85 Table* table,
86 const message::AlterTable::AlterKeysOnOff &op);
87
88static int apply_online_rename_table(Session *session,
89 Table *table,
90 plugin::StorageEngine *original_engine,
91 identifier::Table &original_table_identifier,
92 identifier::Table &new_table_identifier,
93 const message::AlterTable::RenameTable &alter_operation);
94
95namespace statement {
96
97AlterTable::AlterTable(Session *in_session, Table_ident *) :
98 CreateTable(in_session)
99{
100 set_command(SQLCOM_ALTER_TABLE);
101}
102
103} // namespace statement
104
106{
107 TableList *first_table= (TableList *) lex().select_lex.table_list.first;
108 TableList *all_tables= lex().query_tables;
109 assert(first_table == all_tables && first_table != 0);
110 Select_Lex *select_lex= &lex().select_lex;
111
112 is_engine_set= not createTableMessage().engine().name().empty();
113
114 if (is_engine_set)
115 {
116 create_info().db_type=
117 plugin::StorageEngine::findByName(session(), createTableMessage().engine().name());
118
119 if (create_info().db_type == NULL)
120 {
121 my_error(createTableMessage().engine().name(), ER_UNKNOWN_STORAGE_ENGINE, MYF(0));
122
123 return true;
124 }
125 }
126
127 /* Must be set in the parser */
128 assert(select_lex->db);
129
130 /* Chicken/Egg... we need to search for the table, to know if the table exists, so we can build a full identifier from it */
131 message::table::shared_ptr original_table_message;
132 {
133 identifier::Table identifier(session().catalog().identifier(),
134 first_table->getSchemaName(),
135 first_table->getTableName());
136 if (not (original_table_message= plugin::StorageEngine::getTableMessage(session(), identifier)))
137 {
138 my_error(ER_BAD_TABLE_ERROR, identifier);
139 return true;
140 }
141
142 if (not create_info().db_type)
143 {
144 create_info().db_type=
145 plugin::StorageEngine::findByName(session(), original_table_message->engine().name());
146
147 if (not create_info().db_type)
148 {
149 my_error(ER_BAD_TABLE_ERROR, identifier);
150 return true;
151 }
152 }
153 }
154
155 if (not validateCreateTableOption())
156 return true;
157
158 if (session().inTransaction())
159 {
160 my_error(ER_TRANSACTIONAL_DDL_NOT_SUPPORTED, MYF(0));
161 return true;
162 }
163
164 if (session().wait_if_global_read_lock(0, 1))
165 return true;
166
167 bool res;
168 if (original_table_message->type() == message::Table::STANDARD )
169 {
170 identifier::Table identifier(session().catalog().identifier(),
171 first_table->getSchemaName(),
172 first_table->getTableName());
173 identifier::Table new_identifier(session().catalog().identifier(),
174 select_lex->db ? select_lex->db : first_table->getSchemaName(),
175 lex().name.data() ? lex().name.data() : first_table->getTableName());
176
177 res= alter_table(&session(),
178 identifier,
179 new_identifier,
180 &create_info(),
181 *original_table_message,
182 createTableMessage(),
183 first_table,
184 &alter_info,
185 select_lex->order_list.size(),
186 (Order *) select_lex->order_list.first,
187 lex().ignore);
188 }
189 else
190 {
191 identifier::Table catch22(session().catalog().identifier(),
192 first_table->getSchemaName(),
193 first_table->getTableName());
194 Table *table= session().open_tables.find_temporary_table(catch22);
195 assert(table);
196 {
197 identifier::Table identifier(session().catalog().identifier(),
198 first_table->getSchemaName(),
199 first_table->getTableName(),
200 table->getMutableShare()->getPath());
201
202 identifier::Table new_identifier(session().catalog().identifier(),
203 select_lex->db ? select_lex->db : first_table->getSchemaName(),
204 lex().name.data() ? lex().name.data() : first_table->getTableName(),
205 table->getMutableShare()->getPath());
206
207 res= alter_table(&session(),
208 identifier,
209 new_identifier,
210 &create_info(),
211 *original_table_message,
212 createTableMessage(),
213 first_table,
214 &alter_info,
215 select_lex->order_list.size(),
216 (Order *) select_lex->order_list.first,
217 lex().ignore);
218 }
219 }
220
221 /*
222 Release the protection against the global read lock and wake
223 everyone, who might want to set a global read lock.
224 */
225 session().startWaitingGlobalReadLock();
226
227 return res;
228}
229
230
271static bool prepare_alter_table(Session *session,
272 Table *table,
273 HA_CREATE_INFO *create_info,
274 const message::Table &original_proto,
275 message::Table &table_message,
276 message::AlterTable &alter_table_message,
277 AlterInfo *alter_info)
278{
279 uint32_t used_fields= create_info->used_fields;
280 vector<string> drop_keys;
281 vector<string> drop_columns;
282 vector<string> drop_fkeys;
283 vector<const message::AlterTable::RenameKey *> rename_keys;
284
285 for (const message::AlterTable::RenameKey &rename_key : alter_table_message.rename_keys())
286 {
287 if (not system_charset_info->strcasecmp(rename_key.old_name().c_str(), "PRIMARY"))
288 {
289 my_error(ER_WRONG_NAME_FOR_INDEX, MYF(0), rename_key.old_name().c_str());
290 return true;
291 }
292 if (not system_charset_info->strcasecmp(rename_key.new_name().c_str(), "PRIMARY"))
293 {
294 my_error(ER_WRONG_NAME_FOR_INDEX, MYF(0), rename_key.new_name().c_str());
295 return true;
296 }
297 rename_keys.push_back(&rename_key);
298 }
299
300 /* we use drop_(keys|columns|fkey) below to check that we can do all
301 operations we've been asked to do */
302 for (int operationnr= 0; operationnr < alter_table_message.operations_size();
303 operationnr++)
304 {
305 const message::AlterTable::AlterTableOperation &operation=
306 alter_table_message.operations(operationnr);
307
308 switch (operation.operation())
309 {
310 case message::AlterTable::AlterTableOperation::DROP_KEY:
311 drop_keys.push_back(operation.drop_name());
312 break;
313 case message::AlterTable::AlterTableOperation::DROP_COLUMN:
314 drop_columns.push_back(operation.drop_name());
315 break;
316 case message::AlterTable::AlterTableOperation::DROP_FOREIGN_KEY:
317 drop_fkeys.push_back(operation.drop_name());
318 break;
319 default:
320 break;
321 }
322 }
323
324 /* Let new create options override the old ones */
325 message::Table::TableOptions *table_options= table_message.mutable_options();
326
327 if (not (used_fields & HA_CREATE_USED_DEFAULT_CHARSET))
328 create_info->default_table_charset= table->getShare()->table_charset;
329
330 if (not (used_fields & HA_CREATE_USED_AUTO) && table->found_next_number_field)
331 {
332 /* Table has an autoincrement, copy value to new table */
333 table->cursor->info(HA_STATUS_AUTO);
334 create_info->auto_increment_value= table->cursor->stats.auto_increment_value;
335 if (create_info->auto_increment_value != original_proto.options().auto_increment_value())
336 table_options->set_has_user_set_auto_increment_value(false);
337 }
338
339 table->restoreRecordAsDefault(); /* Empty record for DEFAULT */
340
341 List<CreateField> new_create_list;
342 List<Key> new_key_list;
343 /* First collect all fields from table which isn't in drop_list */
344 Field *field;
345 for (Field **f_ptr= table->getFields(); (field= *f_ptr); f_ptr++)
346 {
347 /* Check if field should be dropped */
348 vector<string>::iterator it= drop_columns.begin();
349 while (it != drop_columns.end())
350 {
351 if (not system_charset_info->strcasecmp(field->field_name, it->c_str()))
352 {
353 /* Reset auto_increment value if it was dropped */
354 if (MTYP_TYPENR(field->unireg_check) == Field::NEXT_NUMBER &&
355 not (used_fields & HA_CREATE_USED_AUTO))
356 {
357 create_info->auto_increment_value= 0;
358 create_info->used_fields|= HA_CREATE_USED_AUTO;
359 }
360 break;
361 }
362 it++;
363 }
364
365 if (it != drop_columns.end())
366 {
367 drop_columns.erase(it);
368 continue;
369 }
370
371 /* Mark that we will read the field */
372 field->setReadSet();
373
374 CreateField *def;
375 /* Check if field is changed */
376 List<CreateField>::iterator def_it= alter_info->create_list.begin();
377 while ((def= def_it++))
378 {
379 if (def->change &&
380 ! system_charset_info->strcasecmp(field->field_name, def->change))
381 break;
382 }
383
384 if (def)
385 {
386 /* Field is changed */
387 def->field= field;
388 if (! def->after)
389 {
390 new_create_list.push_back(def);
391 def_it.remove();
392 }
393 }
394 else
395 {
396 /*
397 This field was not dropped and not changed, add it to the list
398 for the new table.
399 */
400 def= new CreateField(field, field);
401 new_create_list.push_back(def);
402 AlterInfo::alter_list_t::iterator alter(alter_info->alter_list.begin());
403
404 for (; alter != alter_info->alter_list.end(); alter++)
405 {
406 if (not system_charset_info->strcasecmp(field->field_name, alter->name))
407 break;
408 }
409
410 if (alter != alter_info->alter_list.end())
411 {
412 def->setDefaultValue(alter->def, NULL);
413
414 alter_info->alter_list.erase(alter);
415 }
416 }
417 }
418
419 CreateField *def;
420 List<CreateField>::iterator def_it= alter_info->create_list.begin();
421 while ((def= def_it++)) /* Add new columns */
422 {
423 if (def->change && ! def->field)
424 {
425 my_error(ER_BAD_FIELD_ERROR, MYF(0), def->change, table->getMutableShare()->getTableName());
426 return true;
427 }
428 /*
429 If we have been given a field which has no default value, and is not null then we need to bail.
430 */
431 if (not (~def->flags & (NO_DEFAULT_VALUE_FLAG | NOT_NULL_FLAG)) and not def->change)
432 {
433 alter_info->error_if_not_empty= true;
434 }
435 if (! def->after)
436 {
437 new_create_list.push_back(def);
438 }
439 else if (def->after == first_keyword)
440 {
441 new_create_list.push_front(def);
442 }
443 else
444 {
445 CreateField *find;
446 List<CreateField>::iterator find_it= new_create_list.begin();
447
448 while ((find= find_it++)) /* Add new columns */
449 {
450 if (not system_charset_info->strcasecmp(def->after, find->field_name))
451 break;
452 }
453
454 if (not find)
455 {
456 my_error(ER_BAD_FIELD_ERROR, MYF(0), def->after, table->getMutableShare()->getTableName());
457 return true;
458 }
459
460 find_it.after(def); /* Put element after this */
461
462 /*
463 XXX: hack for Bug#28427.
464 If column order has changed, force OFFLINE ALTER Table
465 without querying engine capabilities. If we ever have an
466 engine that supports online ALTER Table CHANGE COLUMN
467 <name> AFTER <name1> (Falcon?), this fix will effectively
468 disable the capability.
469 TODO: detect the situation in compare_tables, behave based
470 on engine capabilities.
471 */
472 if (alter_table_message.build_method() == message::AlterTable::BUILD_ONLINE)
473 {
474 my_error(*session->getQueryString(), ER_NOT_SUPPORTED_YET);
475 return true;
476 }
477 }
478 }
479
480 if (not alter_info->alter_list.empty())
481 {
482 my_error(ER_BAD_FIELD_ERROR, MYF(0), alter_info->alter_list.front().name, table->getMutableShare()->getTableName());
483 return true;
484 }
485
486 if (new_create_list.is_empty())
487 {
488 my_message(ER_CANT_REMOVE_ALL_FIELDS, ER(ER_CANT_REMOVE_ALL_FIELDS), MYF(0));
489 return true;
490 }
491
492 /*
493 Collect all keys which isn't in drop list. Add only those
494 for which some fields exists.
495 */
496 KeyInfo *key_info= table->key_info;
497 for (uint32_t i= 0; i < table->getShare()->sizeKeys(); i++, key_info++)
498 {
499 const char *key_name= key_info->name;
500
501 vector<string>::iterator it= drop_keys.begin();
502 while (it != drop_keys.end())
503 {
504 if (not system_charset_info->strcasecmp(key_name, it->c_str()))
505 break;
506 it++;
507 }
508
509 if (it != drop_keys.end())
510 {
511 drop_keys.erase(it);
512 continue;
513 }
514
515 const char *new_key_name= key_name;
516 bool generated= key_info->flags & HA_GENERATED_KEY;
517 for (auto rename_it= rename_keys.begin(); rename_it != rename_keys.end(); ++rename_it)
518 {
519 if (not system_charset_info->strcasecmp(key_name, (*rename_it)->old_name().c_str()))
520 {
521 new_key_name= (*rename_it)->new_name().c_str();
522 /*
523 A key the user named is no longer one the server generated, so
524 mysql_prepare_create_table() must not fold it away.
525 */
526 generated= false;
527 rename_keys.erase(rename_it);
528 break;
529 }
530 }
531
532 KeyPartInfo *key_part= key_info->key_part;
533 List<Key_part_spec> key_parts;
534 for (uint32_t j= 0; j < key_info->key_parts; j++, key_part++)
535 {
536 if (not key_part->field)
537 continue; /* Wrong field (from UNIREG) */
538
539 const char *key_part_name= key_part->field->field_name;
540 CreateField *cfield;
541 List<CreateField>::iterator field_it= new_create_list.begin();
542 while ((cfield= field_it++))
543 {
544 if (cfield->change)
545 {
546 if (not system_charset_info->strcasecmp(key_part_name, cfield->change))
547 break;
548 }
549 else if (not system_charset_info->strcasecmp(key_part_name, cfield->field_name))
550 break;
551 }
552
553 if (not cfield)
554 continue; /* Field is removed */
555
556 uint32_t key_part_length= key_part->length;
557 if (cfield->field) /* Not new field */
558 {
559 /*
560 If the field can't have only a part used in a key according to its
561 new type, or should not be used partially according to its
562 previous type, or the field length is less than the key part
563 length, unset the key part length.
564
565 We also unset the key part length if it is the same as the
566 old field's length, so the whole new field will be used.
567
568 BLOBs may have cfield->length == 0, which is why we test it before
569 checking whether cfield->length < key_part_length (in chars).
570 */
571 if (! Field::type_can_have_key_part(cfield->field->type()) ||
573 (cfield->field->field_length == key_part_length) ||
574 (cfield->length &&
575 (cfield->length < key_part_length / key_part->field->charset()->mbmaxlen)))
576 key_part_length= 0; /* Use whole field */
577 }
578 key_part_length/= key_part->field->charset()->mbmaxlen;
579 key_parts.push_back(new Key_part_spec(str_ref(cfield->field_name), key_part_length));
580 }
581 if (key_parts.size())
582 {
583 KEY_CREATE_INFO key_create_info= default_key_create_info;
584 key_create_info.algorithm= key_info->algorithm;
585
586 if (key_info->flags & HA_USES_BLOCK_SIZE)
587 key_create_info.block_size= key_info->block_size;
588
589 if (key_info->flags & HA_USES_COMMENT)
590 key_create_info.comment= key_info->comment;
591
592 Key::Keytype key_type= key_info->flags & HA_NOSAME
593 ? (is_primary_key(key_name) ? Key::PRIMARY : Key::UNIQUE)
594 : Key::MULTIPLE;
595 new_key_list.push_back(new Key(key_type, str_ref(new_key_name), &key_create_info, generated, key_parts));
596 }
597 }
598
599 for (const message::AlterTable::RenameKey *rename_key : rename_keys)
600 {
601 if (not rename_key->if_exists())
602 {
603 my_error(ER_KEY_DOES_NOT_EXITS, MYF(0),
604 rename_key->old_name().c_str(),
605 table->getShare()->getTableName());
606 return true;
607 }
608 push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
609 ER_KEY_DOES_NOT_EXITS, ER(ER_KEY_DOES_NOT_EXITS),
610 rename_key->old_name().c_str(),
611 table->getShare()->getTableName());
612 }
613
614 /* Copy over existing foreign keys */
615 for (int32_t j= 0; j < original_proto.fk_constraint_size(); j++)
616 {
617 vector<string>::iterator it= drop_fkeys.begin();
618 while (it != drop_fkeys.end())
619 {
620 if (! system_charset_info->strcasecmp(original_proto.fk_constraint(j).name().c_str(), it->c_str()))
621 {
622 break;
623 }
624 it++;
625 }
626
627 if (it != drop_fkeys.end())
628 {
629 drop_fkeys.erase(it);
630 continue;
631 }
632
633 message::Table::ForeignKeyConstraint *pfkey= table_message.add_fk_constraint();
634 *pfkey= original_proto.fk_constraint(j);
635 }
636
637 {
638 Key *key;
639 List<Key>::iterator key_it(alter_info->key_list.begin());
640 while ((key= key_it++)) /* Add new keys */
641 {
642 if (key->type == Key::FOREIGN_KEY)
643 {
644 if (((Foreign_key *)key)->validate(new_create_list))
645 {
646 return true;
647 }
648
649 Foreign_key *fkey= (Foreign_key*)key;
650 add_foreign_key_to_table_message(&table_message,
651 fkey->name.data(),
652 fkey->columns,
653 fkey->ref_table,
654 fkey->ref_columns,
655 fkey->delete_opt,
656 fkey->update_opt,
657 fkey->match_opt);
658 }
659
660 if (key->type != Key::FOREIGN_KEY)
661 new_key_list.push_back(key);
662
663 if (key->name.data() && is_primary_key(key->name.data()))
664 {
665 my_error(ER_WRONG_NAME_FOR_INDEX, MYF(0), key->name.data());
666 return true;
667 }
668 }
669 }
670
671 /* Fix names of foreign keys being added */
672 for (int j= 0; j < table_message.fk_constraint_size(); j++)
673 {
674 if (! table_message.fk_constraint(j).has_name())
675 {
676 std::string name(table->getMutableShare()->getTableName());
677 char number[20];
678
679 name.append("_ibfk_");
680 snprintf(number, sizeof(number), "%d", j+1);
681 name.append(number);
682
683 message::Table::ForeignKeyConstraint *pfkey= table_message.mutable_fk_constraint(j);
684 pfkey->set_name(name);
685 }
686 }
687
688 if (drop_keys.size())
689 {
690 my_error(ER_CANT_DROP_FIELD_OR_KEY,
691 MYF(0),
692 drop_keys.front().c_str());
693 return true;
694 }
695
696 if (drop_columns.size())
697 {
698 my_error(ER_CANT_DROP_FIELD_OR_KEY,
699 MYF(0),
700 drop_columns.front().c_str());
701 return true;
702 }
703
704 if (drop_fkeys.size())
705 {
706 my_error(ER_CANT_DROP_FIELD_OR_KEY,
707 MYF(0),
708 drop_fkeys.front().c_str());
709 return true;
710 }
711
712 if (not alter_info->alter_list.empty())
713 {
714 my_error(ER_CANT_DROP_FIELD_OR_KEY,
715 MYF(0),
716 alter_info->alter_list.front().name);
717 return true;
718 }
719
720 if (not table_message.options().has_comment()
721 && table->getMutableShare()->hasComment())
722 {
723 table_options->set_comment(table->getMutableShare()->getComment());
724 }
725
726 if (table->getShare()->getType())
727 {
728 table_message.set_type(message::Table::TEMPORARY);
729 }
730
731 table_message.set_creation_timestamp(table->getShare()->getTableMessage()->creation_timestamp());
732 table_message.set_version(table->getShare()->getTableMessage()->version());
733 table_message.set_uuid(table->getShare()->getTableMessage()->uuid());
734
735 alter_info->create_list.swap(new_create_list);
736 alter_info->key_list.swap(new_key_list);
737
738 size_t num_engine_options= table_message.engine().options_size();
739 size_t original_num_engine_options= original_proto.engine().options_size();
740 for (size_t x= 0; x < original_num_engine_options; ++x)
741 {
742 bool found= false;
743
744 for (size_t y= 0; y < num_engine_options; ++y)
745 {
746 found= not table_message.engine().options(y).name().compare(original_proto.engine().options(x).name());
747
748 if (found)
749 break;
750 }
751
752 if (not found)
753 {
754 message::Engine::Option *opt= table_message.mutable_engine()->add_options();
755
756 opt->set_name(original_proto.engine().options(x).name());
757 opt->set_state(original_proto.engine().options(x).state());
758 }
759 }
760
761 drizzled::message::update(table_message);
762
763 return false;
764}
765
766/* table_list should contain just one table */
767static int discard_or_import_tablespace(Session *session,
768 TableList *table_list,
769 bool discard)
770{
771 /*
772 Note that DISCARD/IMPORT TABLESPACE always is the only operation in an
773 ALTER Table
774 */
775 session->set_proc_info("discard_or_import_tablespace");
776
777 /*
778 We set this flag so that ha_innobase::open and ::external_lock() do
779 not complain when we lock the table
780 */
781 session->setDoingTablespaceOperation(true);
782 Table* table= session->openTableLock(table_list, TL_WRITE);
783 if (not table)
784 {
785 session->setDoingTablespaceOperation(false);
786 return -1;
787 }
788
789 int error;
790 do {
791 error= table->cursor->ha_discard_or_import_tablespace(discard);
792
793 session->set_proc_info("end");
794
795 if (error)
796 break;
797
798 /* The ALTER Table is always in its own transaction */
799 error= TransactionServices::autocommitOrRollback(*session, false);
800 if (not session->endActiveTransaction())
801 error= 1;
802
803 if (error)
804 break;
805
806 TransactionServices::rawStatement(*session,
807 *session->getQueryString(),
808 *session->schema());
809
810 } while(0);
811
812 (void) TransactionServices::autocommitOrRollback(*session, error);
813 session->setDoingTablespaceOperation(false);
814
815 if (error == 0)
816 {
817 session->my_ok();
818 return 0;
819 }
820
821 table->print_error(error, MYF(0));
822
823 return -1;
824}
825
840static bool alter_table_manage_keys(Session *session,
841 Table *table, int indexes_were_disabled,
842 const message::AlterTable &alter_table_message)
843{
844 int error= 0;
845 if (alter_table_message.has_alter_keys_onoff()
846 && alter_table_message.alter_keys_onoff().enable())
847 {
848 error= table->cursor->ha_enable_indexes(HA_KEY_SWITCH_NONUNIQ_SAVE);
849 }
850
851 if ((! alter_table_message.has_alter_keys_onoff() && indexes_were_disabled)
852 || (alter_table_message.has_alter_keys_onoff()
853 && ! alter_table_message.alter_keys_onoff().enable()))
854 {
855 error= table->cursor->ha_disable_indexes(HA_KEY_SWITCH_NONUNIQ_SAVE);
856 }
857
858 if (error == HA_ERR_WRONG_COMMAND)
859 {
860 push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
861 ER_ILLEGAL_HA, ER(ER_ILLEGAL_HA),
862 table->getMutableShare()->getTableName());
863 error= 0;
864 }
865 else if (error)
866 {
867 table->print_error(error, MYF(0));
868 }
869
870 return(error);
871}
872
873static bool lockTableIfDifferent(Session &session,
874 identifier::Table &original_table_identifier,
875 identifier::Table &new_table_identifier,
876 Table *name_lock)
877{
878 /* Check that we are not trying to rename to an existing table */
879 if (not (original_table_identifier == new_table_identifier))
880 {
881 if (original_table_identifier.isTmp())
882 {
883 if (session.open_tables.find_temporary_table(new_table_identifier))
884 {
885 my_error(ER_TABLE_EXISTS_ERROR, new_table_identifier);
886 return false;
887 }
888 }
889 else
890 {
891 name_lock= session.lock_table_name_if_not_cached(new_table_identifier);
892 if (not name_lock)
893 {
894 my_error(ER_TABLE_EXISTS_ERROR, new_table_identifier);
895 return false;
896 }
897
898 if (plugin::StorageEngine::doesTableExist(session, new_table_identifier))
899 {
900 /* Table will be closed by Session::executeCommand() */
901 my_error(ER_TABLE_EXISTS_ERROR, new_table_identifier);
902
903 {
904 boost::mutex::scoped_lock scopedLock(table::Cache::mutex());
905 session.unlink_open_table(name_lock);
906 }
907
908 return false;
909 }
910 }
911 }
912
913 return true;
914}
915
957
958static bool internal_alter_table(Session *session,
959 Table *table,
960 identifier::Table &original_table_identifier,
961 identifier::Table &new_table_identifier,
962 HA_CREATE_INFO *create_info,
963 const message::Table &original_proto,
964 message::Table &create_proto,
965 message::AlterTable &alter_table_message,
966 TableList *table_list,
967 AlterInfo *alter_info,
968 uint32_t order_num,
969 Order *order,
970 bool ignore)
971{
972 int error= 0;
973 char tmp_name[80];
974 char old_name[32];
975 ha_rows copied= 0;
976 ha_rows deleted= 0;
977
978 if (not original_table_identifier.isValid())
979 return true;
980
981 if (not new_table_identifier.isValid())
982 return true;
983
984 session->set_proc_info("init");
985
986 table->use_all_columns();
987
988 plugin::StorageEngine *new_engine;
989 plugin::StorageEngine *original_engine;
990
991 original_engine= table->getMutableShare()->getEngine();
992
993 if (not create_info->db_type)
994 {
995 create_info->db_type= original_engine;
996 }
997 new_engine= create_info->db_type;
998
999
1000 create_proto.set_schema(new_table_identifier.getSchemaName());
1001 create_proto.set_type(new_table_identifier.getType());
1002
1007 if (new_engine != original_engine &&
1008 not table->cursor->can_switch_engines())
1009 {
1010 assert(0);
1011 my_error(ER_ROW_IS_REFERENCED, MYF(0));
1012
1013 return true;
1014 }
1015
1016 if (original_engine->check_flag(HTON_BIT_ALTER_NOT_SUPPORTED) ||
1017 new_engine->check_flag(HTON_BIT_ALTER_NOT_SUPPORTED))
1018 {
1019 my_error(ER_ILLEGAL_HA, new_table_identifier);
1020
1021 return true;
1022 }
1023
1024 session->set_proc_info("setup");
1025
1026 /* First we try for operations that do not require a copying
1027 ALTER TABLE.
1028
1029 In future there should be more operations, currently it's just a couple.
1030 */
1031
1032 if ((alter_table_message.has_rename()
1033 || alter_table_message.has_alter_keys_onoff())
1034 && alter_table_message.operations_size() == 0)
1035 {
1036 /*
1037 * test if no other bits except ALTER_RENAME and ALTER_KEYS_ONOFF are set
1038 */
1039 bitset<32> tmp;
1040
1041 tmp.set();
1042 tmp.reset(ALTER_RENAME);
1043 tmp.reset(ALTER_KEYS_ONOFF);
1044 tmp&= alter_info->flags;
1045
1046 if((not (tmp.any()) && not table->getShare()->getType())) // no need to touch frm
1047 {
1048 if (alter_table_message.has_alter_keys_onoff())
1049 {
1050 error= apply_online_alter_keys_onoff(session, table,
1051 alter_table_message.alter_keys_onoff());
1052
1053 if (error == HA_ERR_WRONG_COMMAND)
1054 {
1055 error= EE_OK;
1056 push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
1057 ER_ILLEGAL_HA, ER(ER_ILLEGAL_HA),
1058 table->getAlias());
1059 }
1060 }
1061
1062 if (alter_table_message.has_rename())
1063 {
1064 error= apply_online_rename_table(session,
1065 table,
1066 original_engine,
1067 original_table_identifier,
1068 new_table_identifier,
1069 alter_table_message.rename());
1070
1071 if (error == HA_ERR_WRONG_COMMAND)
1072 {
1073 error= EE_OK;
1074 push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
1075 ER_ILLEGAL_HA, ER(ER_ILLEGAL_HA),
1076 table->getAlias());
1077 }
1078 }
1079
1080 if (not error)
1081 {
1082 TransactionServices::allocateNewTransactionId();
1084 *session->getQueryString(),
1085 *session->schema());
1086 session->my_ok();
1087 }
1088 else if (error > EE_OK) // If we have already set the error, we pass along -1
1089 {
1090 table->print_error(error, MYF(0));
1091 }
1092
1093 table_list->table= NULL;
1094
1095 return error;
1096 }
1097 }
1098
1099 if (alter_table_message.build_method() == message::AlterTable::BUILD_ONLINE)
1100 {
1101 my_error(*session->getQueryString(), ER_NOT_SUPPORTED_YET);
1102 return true;
1103 }
1104
1105 /* We have to do full alter table. */
1106 new_engine= create_info->db_type;
1107
1108 if (prepare_alter_table(session, table, create_info, original_proto, create_proto, alter_table_message, alter_info))
1109 {
1110 return true;
1111 }
1112
1113 set_table_default_charset(session->catalog().identifier(), create_info, new_table_identifier.getSchemaName().c_str());
1114
1115 snprintf(tmp_name, sizeof(tmp_name), "%s-%lx_%" PRIx64, TMP_FILE_PREFIX, (unsigned long) current_pid, session->thread_id);
1116
1117 /* Create a temporary table with the new format */
1123 identifier::Table new_table_as_temporary(session->catalog().identifier(),
1124 original_table_identifier.getSchemaName(),
1125 tmp_name,
1126 create_proto.type() != message::Table::TEMPORARY ? message::Table::INTERNAL :
1127 message::Table::TEMPORARY);
1128
1129 /*
1130 Create a table with a temporary name.
1131 We don't log the statement, it will be logged later.
1132 */
1133 create_proto.set_name(new_table_as_temporary.getTableName());
1134 create_proto.mutable_engine()->set_name(create_info->db_type->getName());
1135
1136 error= create_table(session,
1137 new_table_as_temporary,
1138 create_info, create_proto, alter_info, true, 0, false);
1139
1140 if (error != 0)
1141 {
1142 return true;
1143 }
1144
1145 /* Open the table so we need to copy the data to it. */
1146 Table *new_table= open_alter_table(session, table, new_table_as_temporary);
1147
1148
1149 if (not new_table)
1150 {
1151 plugin::StorageEngine::dropTable(*session, new_table_as_temporary);
1152 return true;
1153 }
1154
1155 /* Copy the data if necessary. */
1156 {
1157 /* We must not ignore bad input! */
1158 session->count_cuted_fields= CHECK_FIELD_ERROR_FOR_NULL; // calc cuted fields
1159 session->cuted_fields= 0L;
1160 session->set_proc_info("copy to tmp table");
1161 copied= deleted= 0;
1162
1163 /* We don't want update TIMESTAMP fields during ALTER Table. */
1164 new_table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
1165 new_table->next_number_field= new_table->found_next_number_field;
1166 error= copy_data_between_tables(session,
1167 table,
1168 new_table,
1169 alter_info->create_list,
1170 ignore,
1171 order_num,
1172 order,
1173 &copied,
1174 &deleted,
1175 alter_table_message,
1176 alter_info->error_if_not_empty);
1177
1178 /* We must not ignore bad input! */
1179 assert(session->count_cuted_fields == CHECK_FIELD_ERROR_FOR_NULL);
1180 }
1181
1182 /* Now we need to resolve what just happened with the data copy. */
1183
1184 if (error)
1185 {
1186
1187 /*
1188 No default value was provided for new fields.
1189 */
1190 if (alter_info->error_if_not_empty && session->row_count)
1191 {
1192 my_error(ER_INVALID_ALTER_TABLE_FOR_NOT_NULL, MYF(0));
1193 }
1194
1195 if (original_table_identifier.isTmp())
1196 {
1197 if (new_table)
1198 {
1199 /* close_temporary_table() frees the new_table pointer. */
1200 session->open_tables.close_temporary_table(new_table);
1201 }
1202 else
1203 {
1204 plugin::StorageEngine::dropTable(*session, new_table_as_temporary);
1205 }
1206
1207 return true;
1208 }
1209 else
1210 {
1211 if (new_table)
1212 {
1213 /*
1214 Close the intermediate table that will be the new table.
1215 Note that MERGE tables do not have their children attached here.
1216 */
1217 new_table->intern_close_table();
1218 if (new_table->hasShare())
1219 {
1220 delete new_table->getMutableShare();
1221 }
1222
1223 delete new_table;
1224 }
1225
1226 boost::mutex::scoped_lock scopedLock(table::Cache::mutex());
1227
1228 plugin::StorageEngine::dropTable(*session, new_table_as_temporary);
1229
1230 return true;
1231 }
1232 }
1233 // Temporary table and success
1234 else if (original_table_identifier.isTmp())
1235 {
1236 /* Close lock if this is a transactional table */
1237 if (session->open_tables.lock)
1238 {
1239 session->unlockTables(session->open_tables.lock);
1240 session->open_tables.lock= 0;
1241 }
1242
1243 /* Remove link to old table and rename the new one */
1244 session->open_tables.close_temporary_table(table);
1245
1246 /* Should pass the 'new_name' as we store table name in the cache */
1247 new_table->getMutableShare()->setIdentifier(new_table_identifier);
1248
1249 new_table_identifier.setPath(new_table_as_temporary.getPath());
1250
1251 if (rename_table(*session, new_engine, new_table_as_temporary, new_table_identifier) != 0)
1252 {
1253 return true;
1254 }
1255 }
1256 // Normal table success
1257 else
1258 {
1259 if (new_table)
1260 {
1261 /*
1262 Close the intermediate table that will be the new table.
1263 Note that MERGE tables do not have their children attached here.
1264 */
1265 new_table->intern_close_table();
1266
1267 if (new_table->hasShare())
1268 {
1269 delete new_table->getMutableShare();
1270 }
1271
1272 delete new_table;
1273 }
1274
1275 {
1276 boost::mutex::scoped_lock scopedLock(table::Cache::mutex()); /* ALTER TABLE */
1277 /*
1278 Data is copied. Now we:
1279 1) Wait until all other threads close old version of table.
1280 2) Close instances of table open by this thread and replace them
1281 with exclusive name-locks.
1282 3) Rename the old table to a temp name, rename the new one to the
1283 old name.
1284 4) If we are under LOCK TABLES and don't do ALTER Table ... RENAME
1285 we reopen new version of table.
1286 5) Write statement to the binary log.
1287 6) If we are under LOCK TABLES and do ALTER Table ... RENAME we
1288 remove name-locks from list of open tables and table cache.
1289 7) If we are not not under LOCK TABLES we rely on close_thread_tables()
1290 call to remove name-locks from table cache and list of open table.
1291 */
1292
1293 session->set_proc_info("rename result table");
1294
1295 snprintf(old_name, sizeof(old_name), "%s2-%lx-%" PRIx64, TMP_FILE_PREFIX, (unsigned long) current_pid, session->thread_id);
1296
1297 files_charset_info->casedn_str(old_name);
1298
1299 wait_while_table_is_used(session, table, HA_EXTRA_PREPARE_FOR_RENAME);
1300 session->close_data_files_and_morph_locks(original_table_identifier);
1301
1302 assert(not error);
1303
1304 /*
1305 This leads to the storage engine (SE) not being notified for renames in
1306 rename_table(), because we just juggle with the FRM and nothing
1307 more. If we have an intermediate table, then we notify the SE that
1308 it should become the actual table. Later, we will recycle the old table.
1309 However, in case of ALTER Table RENAME there might be no intermediate
1310 table. This is when the old and new tables are compatible, according to
1311 compare_table(). Then, we need one additional call to
1312 */
1313 identifier::Table original_table_to_drop(session->catalog().identifier(),
1314 original_table_identifier.getSchemaName(),
1315 old_name, create_proto.type() != message::Table::TEMPORARY ? message::Table::INTERNAL :
1316 message::Table::TEMPORARY);
1317
1318 drizzled::error_t rename_error= EE_OK;
1319 if (rename_table(*session, original_engine, original_table_identifier, original_table_to_drop))
1320 {
1321 error= ER_ERROR_ON_RENAME;
1322 plugin::StorageEngine::dropTable(*session, new_table_as_temporary);
1323 }
1324 else
1325 {
1326 if (rename_table(*session, new_engine, new_table_as_temporary, new_table_identifier) != 0)
1327 {
1328 /* Try to get everything back. */
1329 rename_error= ER_ERROR_ON_RENAME;
1330
1331 plugin::StorageEngine::dropTable(*session, new_table_identifier);
1332
1333 plugin::StorageEngine::dropTable(*session, new_table_as_temporary);
1334
1335 rename_table(*session, original_engine, original_table_to_drop, original_table_identifier);
1336 }
1337 else
1338 {
1339 plugin::StorageEngine::dropTable(*session, original_table_to_drop);
1340 }
1341 }
1342
1343 if (rename_error)
1344 {
1345 /*
1346 An error happened while we were holding exclusive name-lock on table
1347 being altered. To be safe under LOCK TABLES we should remove placeholders
1348 from list of open tables list and table cache.
1349 */
1350 session->unlink_open_table(table);
1351
1352 return true;
1353 }
1354 }
1355
1356 session->set_proc_info("end");
1357
1359 *session->getQueryString(),
1360 *session->schema());
1361 table_list->table= NULL;
1362 }
1363
1364 /*
1365 * Field::store() may have called my_error(). If this is
1366 * the case, we must not send an ok packet, since
1367 * Diagnostics_area::is_set() will fail an assert.
1368 */
1369 if (session->is_error())
1370 {
1371 /* my_error() was called. Return true (which means error...) */
1372 return true;
1373 }
1374
1375 snprintf(tmp_name, sizeof(tmp_name), ER(ER_INSERT_INFO),
1376 (ulong) (copied + deleted), (ulong) deleted,
1377 (ulong) session->cuted_fields);
1378 session->my_ok(copied + deleted, 0, 0L, tmp_name);
1379 return false;
1380}
1381
1382static int apply_online_alter_keys_onoff(Session *session,
1383 Table* table,
1384 const message::AlterTable::AlterKeysOnOff &op)
1385{
1386 int error= 0;
1387
1388 if (op.enable())
1389 {
1390 /*
1391 wait_while_table_is_used() ensures that table being altered is
1392 opened only by this thread and that Table::TableShare::version
1393 of Table object corresponding to this table is 0.
1394 The latter guarantees that no DML statement will open this table
1395 until ALTER Table finishes (i.e. until close_thread_tables())
1396 while the fact that the table is still open gives us protection
1397 from concurrent DDL statements.
1398 */
1399 {
1400 boost::mutex::scoped_lock scopedLock(table::Cache::mutex()); /* DDL wait for/blocker */
1401 wait_while_table_is_used(session, table, HA_EXTRA_FORCE_REOPEN);
1402 }
1403 error= table->cursor->ha_enable_indexes(HA_KEY_SWITCH_NONUNIQ_SAVE);
1404
1405 /* COND_refresh will be signaled in close_thread_tables() */
1406 }
1407 else
1408 {
1409 {
1410 boost::mutex::scoped_lock scopedLock(table::Cache::mutex()); /* DDL wait for/blocker */
1411 wait_while_table_is_used(session, table, HA_EXTRA_FORCE_REOPEN);
1412 }
1413 error= table->cursor->ha_disable_indexes(HA_KEY_SWITCH_NONUNIQ_SAVE);
1414
1415 /* COND_refresh will be signaled in close_thread_tables() */
1416 }
1417
1418 return error;
1419}
1420
1421static int apply_online_rename_table(Session *session,
1422 Table *table,
1423 plugin::StorageEngine *original_engine,
1424 identifier::Table &original_table_identifier,
1425 identifier::Table &new_table_identifier,
1426 const message::AlterTable::RenameTable &alter_operation)
1427{
1428 int error= 0;
1429
1430 boost::mutex::scoped_lock scopedLock(table::Cache::mutex()); /* Lock to remove all instances of table from table cache before ALTER */
1431 /*
1432 Unlike to the above case close_cached_table() below will remove ALL
1433 instances of Table from table cache (it will also remove table lock
1434 held by this thread).
1435 */
1436
1437 if (not (original_table_identifier == new_table_identifier))
1438 {
1439 assert(alter_operation.to_name() == new_table_identifier.getTableName());
1440 assert(alter_operation.to_schema() == new_table_identifier.getSchemaName());
1441
1442 session->set_proc_info("rename");
1443 /*
1444 Then do a 'simple' rename of the table. First we need to close all
1445 instances of 'source' table.
1446 */
1447 session->close_cached_table(table);
1448 /*
1449 Then, we want check once again that target table does not exist.
1450 Actually the order of these two steps does not matter since
1451 earlier we took name-lock on the target table, so we do them
1452 in this particular order only to be consistent with 5.0, in which
1453 we don't take this name-lock and where this order really matters.
1454 @todo Investigate if we need this access() check at all.
1455 */
1456 if (plugin::StorageEngine::doesTableExist(*session, new_table_identifier))
1457 {
1458 my_error(ER_TABLE_EXISTS_ERROR, new_table_identifier);
1459 error= -1;
1460 }
1461 else
1462 {
1463 if (rename_table(*session, original_engine, original_table_identifier, new_table_identifier))
1464 {
1465 error= -1;
1466 }
1467 }
1468 }
1469 return error;
1470}
1471
1472bool alter_table(Session *session,
1473 identifier::Table &original_table_identifier,
1474 identifier::Table &new_table_identifier,
1475 HA_CREATE_INFO *create_info,
1476 const message::Table &original_proto,
1477 message::Table &create_proto,
1478 TableList *table_list,
1479 AlterInfo *alter_info,
1480 uint32_t order_num,
1481 Order *order,
1482 bool ignore)
1483{
1484 bool error;
1485 Table *table;
1486 message::AlterTable *alter_table_message= session->lex().alter_table();
1487
1488 alter_table_message->set_catalog(original_table_identifier.getCatalogName());
1489 alter_table_message->set_schema(original_table_identifier.getSchemaName());
1490 alter_table_message->set_name(original_table_identifier.getTableName());
1491
1492 if (alter_table_message->operations_size()
1493 && (alter_table_message->operations(0).operation()
1494 == message::AlterTable::AlterTableOperation::DISCARD_TABLESPACE
1495 || alter_table_message->operations(0).operation()
1496 == message::AlterTable::AlterTableOperation::IMPORT_TABLESPACE))
1497 {
1498 bool discard= (alter_table_message->operations(0).operation() ==
1499 message::AlterTable::AlterTableOperation::DISCARD_TABLESPACE);
1500 /* DISCARD/IMPORT TABLESPACE is always alone in an ALTER Table */
1501 return discard_or_import_tablespace(session, table_list, discard);
1502 }
1503
1504 session->set_proc_info("init");
1505
1506 if (not (table= session->openTableLock(table_list, TL_WRITE_ALLOW_READ)))
1507 return true;
1508
1509 session->set_proc_info("gained write lock on table");
1510
1511 /*
1512 Check that we are not trying to rename to an existing table,
1513 if one existed we get a lock, if we can't we error.
1514 */
1515 {
1516 Table *name_lock= NULL;
1517
1518 if (not lockTableIfDifferent(*session, original_table_identifier, new_table_identifier, name_lock))
1519 {
1520 return true;
1521 }
1522
1523 error= internal_alter_table(session,
1524 table,
1525 original_table_identifier,
1526 new_table_identifier,
1527 create_info,
1528 original_proto,
1529 create_proto,
1530 *alter_table_message,
1531 table_list,
1532 alter_info,
1533 order_num,
1534 order,
1535 ignore);
1536
1537 if (name_lock)
1538 {
1539 boost::mutex::scoped_lock scopedLock(table::Cache::mutex());
1540 session->unlink_open_table(name_lock);
1541 }
1542 }
1543
1544 return error;
1545}
1546/* alter_table */
1547
1548static int
1549copy_data_between_tables(Session *session,
1550 Table *from, Table *to,
1551 List<CreateField> &create,
1552 bool ignore,
1553 uint32_t order_num, Order *order,
1554 ha_rows *copied,
1555 ha_rows *deleted,
1556 message::AlterTable &alter_table_message,
1557 bool error_if_not_empty)
1558{
1559 int error= 0;
1560 CopyField *copy,*copy_end;
1561 ulong found_count,delete_count;
1562 uint32_t length= 0;
1563 SortField *sortorder;
1564 ReadRecord info;
1565 TableList tables;
1566 List<Item> fields;
1567 List<Item> all_fields;
1568 ha_rows examined_rows;
1569 bool auto_increment_field_copied= 0;
1570 uint64_t prev_insert_id;
1571
1572 /*
1573 Turn off recovery logging since rollback of an alter table is to
1574 delete the new table so there is no need to log the changes to it.
1575
1576 This needs to be done before external_lock
1577 */
1578
1579 /*
1580 * LP Bug #552420
1581 *
1582 * Since open_temporary_table() doesn't invoke lockTables(), we
1583 * don't get the usual automatic call to StorageEngine::startStatement(), so
1584 * we manually call it here...
1585 */
1586 to->getMutableShare()->getEngine()->startStatement(session);
1587
1588 copy= new CopyField[to->getShare()->sizeFields()];
1589
1590 if (to->cursor->ha_external_lock(session, F_WRLCK))
1591 return -1;
1592
1593 /* We need external lock before we can disable/enable keys */
1594 alter_table_manage_keys(session, to, from->cursor->indexes_are_disabled(),
1595 alter_table_message);
1596
1597 /* We can abort alter table for any table type */
1598 session->setAbortOnWarning(not ignore);
1599
1600 from->cursor->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);
1601 to->cursor->ha_start_bulk_insert(from->cursor->stats.records);
1602
1603 List<CreateField>::iterator it(create.begin());
1604 copy_end= copy;
1605 for (Field **ptr= to->getFields(); *ptr ; ptr++)
1606 {
1607 CreateField* def=it++;
1608 if (def->field)
1609 {
1610 if (*ptr == to->next_number_field)
1611 auto_increment_field_copied= true;
1612
1613 (copy_end++)->set(*ptr,def->field,0);
1614 }
1615
1616 }
1617
1618 found_count=delete_count=0;
1619
1620 do
1621 {
1622 if (order)
1623 {
1624 if (to->getShare()->hasPrimaryKey() && to->cursor->primary_key_is_clustered())
1625 {
1626 char warn_buff[DRIZZLE_ERRMSG_SIZE];
1627 snprintf(warn_buff, sizeof(warn_buff),
1628 _("order_st BY ignored because there is a user-defined clustered "
1629 "index in the table '%-.192s'"),
1630 from->getMutableShare()->getTableName());
1631 push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_WARN, ER_UNKNOWN_ERROR,
1632 warn_buff);
1633 }
1634 else
1635 {
1636 FileSort filesort(*session);
1637 from->sort.io_cache= new internal::io_cache_st;
1638
1639 tables.table= from;
1640 tables.setTableName(from->getMutableShare()->getTableName());
1641 tables.alias= tables.getTableName();
1642 tables.setSchemaName(from->getMutableShare()->getSchemaName());
1643 error= 1;
1644
1645 session->lex().select_lex.setup_ref_array(session, order_num);
1646 if (setup_order(session, session->lex().select_lex.ref_pointer_array, &tables, fields, all_fields, order))
1647 break;
1648 sortorder= make_unireg_sortorder(order, &length, NULL);
1649 if ((from->sort.found_records= filesort.run(from, sortorder, length, (optimizer::SqlSelect *) 0, HA_POS_ERROR, 1, examined_rows)) == HA_POS_ERROR)
1650 break;
1651 }
1652 }
1653
1654 /* Tell handler that we have values for all columns in the to table */
1655 to->use_all_columns();
1656
1657 error= info.init_read_record(session, from, NULL, 1, true);
1658 if (error)
1659 {
1660 to->print_error(errno, MYF(0));
1661
1662 break;
1663 }
1664
1665 if (ignore)
1666 {
1667 to->cursor->extra(HA_EXTRA_IGNORE_DUP_KEY);
1668 }
1669
1670 session->row_count= 0;
1671 to->restoreRecordAsDefault(); // Create empty record
1672 while (not (error=info.read_record(&info)))
1673 {
1674 if (session->getKilled())
1675 {
1676 session->send_kill_message();
1677 error= 1;
1678 break;
1679 }
1680 session->row_count++;
1681 /* Return error if source table isn't empty. */
1682 if (error_if_not_empty)
1683 {
1684 error= 1;
1685 break;
1686 }
1687 if (to->next_number_field)
1688 {
1689 if (auto_increment_field_copied)
1690 to->auto_increment_field_not_null= true;
1691 else
1692 to->next_number_field->reset();
1693 }
1694
1695 for (CopyField *copy_ptr= copy; copy_ptr != copy_end ; copy_ptr++)
1696 {
1697 if (not copy->to_field->hasDefault() and copy->from_null_ptr and *copy->from_null_ptr & copy->from_bit)
1698 {
1699 copy->to_field->set_warning(DRIZZLE_ERROR::WARN_LEVEL_WARN,
1700 ER_WARN_DATA_TRUNCATED, 1);
1701 copy->to_field->reset();
1702 error= 1;
1703 break;
1704 }
1705
1706 copy_ptr->do_copy(copy_ptr);
1707 }
1708
1709 if (error)
1710 {
1711 break;
1712 }
1713
1714 prev_insert_id= to->cursor->next_insert_id;
1715 error= to->cursor->insertRecord(to->record[0]);
1716 to->auto_increment_field_not_null= false;
1717
1718 if (error)
1719 {
1720 if (!ignore || to->cursor->is_fatal_error(error, HA_CHECK_DUP))
1721 {
1722 to->print_error(error, MYF(0));
1723 break;
1724 }
1725 to->cursor->restore_auto_increment(prev_insert_id);
1726 delete_count++;
1727 }
1728 else
1729 {
1730 found_count++;
1731 }
1732 }
1733
1734 info.end_read_record();
1735 from->free_io_cache();
1736 delete[] copy;
1737
1738 if (to->cursor->ha_end_bulk_insert() && error <= 0)
1739 {
1740 to->print_error(errno, MYF(0));
1741 error= 1;
1742 }
1743 to->cursor->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
1744
1745 /*
1746 Ensure that the new table is saved properly to disk so that we
1747 can do a rename
1748 */
1749 if (TransactionServices::autocommitOrRollback(*session, false))
1750 error= 1;
1751
1752 if (not session->endActiveTransaction())
1753 error= 1;
1754
1755 } while (0);
1756
1757 session->setAbortOnWarning(false);
1758 from->free_io_cache();
1759 *copied= found_count;
1760 *deleted=delete_count;
1761 to->cursor->ha_release_auto_increment();
1762
1763 if (to->cursor->ha_external_lock(session, F_UNLCK))
1764 {
1765 error= 1;
1766 }
1767
1768 return error > 0 ? -1 : 0;
1769}
1770
1771static Table *open_alter_table(Session *session, Table *table, identifier::Table &identifier)
1772{
1773 /* Open the table so we need to copy the data to it. */
1774 if (table->getShare()->getType())
1775 {
1776 TableList tbl;
1777 tbl.setSchemaName(identifier.getSchemaName().c_str());
1778 tbl.alias= identifier.getTableName().c_str();
1779 tbl.setTableName(identifier.getTableName().c_str());
1780
1781 /* Table is in session->temporary_tables */
1782 return session->openTable(&tbl, NULL, DRIZZLE_LOCK_IGNORE_FLUSH);
1783 }
1784 else
1785 {
1786 /* Open our intermediate table */
1787 return session->open_temporary_table(identifier, false);
1788 }
1789}
1790
1791} /* namespace drizzled */
const char * field_name
enum_field_types sql_type
static bool type_can_have_key_part(enum_field_types)
Definition field.cc:859
uint32_t field_length
Definition field.h:131
const char * field_name
Definition field.h:104
Table * table
opened table
Definition table_list.h:145
Select_Lex * select_lex
Definition table_list.h:208
static void rawStatement(Session &, const std::string &query, const std::string &schema)
#define TMP_FILE_PREFIX
int setup_order(Session *session, Item **ref_pointer_array, TableList *tables, List< Item > &fields, List< Item > &all_fields, Order *order)
TODO: Rename this file - func.h is stupid.
uint64_t prev_insert_id(uint64_t nr, drizzle_system_variables *variables)
static bool internal_alter_table(Session *session, Table *table, identifier::Table &original_table_identifier, identifier::Table &new_table_identifier, HA_CREATE_INFO *create_info, const message::Table &original_proto, message::Table &create_proto, message::AlterTable &alter_table_message, TableList *table_list, AlterInfo *alter_info, uint32_t order_num, Order *order, bool ignore)
static bool alter_table_manage_keys(Session *session, Table *table, int indexes_were_disabled, const message::AlterTable &alter_table_message)
static bool prepare_alter_table(Session *session, Table *table, HA_CREATE_INFO *create_info, const message::Table &original_proto, message::Table &table_message, message::AlterTable &alter_table_message, AlterInfo *alter_info)
STL namespace.