drizzle
C++ MySQL-protocol-compatible database server
Loading...
Searching...
No Matches
sql_table.cc
1/* Copyright (C) 2000-2004 MySQL AB
2
3 This program is free software; you can redistribute it and/or modify
4 it under the terms of the GNU General Public License as published by
5 the Free Software Foundation; version 2 of the License.
6
7 This program is distributed in the hope that it will be useful,
8 but WITHOUT ANY WARRANTY; without even the implied warranty of
9 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 GNU General Public License for more details.
11
12 You should have received a copy of the GNU General Public License
13 along with this program; if not, write to the Free Software
14 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
15
16/* drop and alter of tables */
17
18#include <config.h>
19#include <plugin/myisam/myisam.h>
20#include <drizzled/show.h>
21#include <drizzled/error.h>
22#include <drizzled/gettext.h>
23#include <drizzled/data_home.h>
24#include <drizzled/sql_parse.h>
25#include <drizzled/sql_lex.h>
26#include <drizzled/session.h>
27#include <drizzled/sql_base.h>
28#include <drizzled/lock.h>
29#include <drizzled/item/int.h>
30#include <drizzled/item/empty_string.h>
31#include <drizzled/transaction_services.h>
32#include <drizzled/transaction_services.h>
33#include <drizzled/table_proto.h>
34#include <drizzled/plugin/client.h>
35#include <drizzled/identifier.h>
36#include <drizzled/internal/m_string.h>
37#include <drizzled/charset.h>
38#include <drizzled/definition/cache.h>
39#include <drizzled/system_variables.h>
40#include <drizzled/statement/alter_table.h>
41#include <drizzled/sql_table.h>
42#include <drizzled/pthread_globals.h>
43#include <drizzled/typelib.h>
44#include <drizzled/plugin/storage_engine.h>
45#include <drizzled/diagnostics_area.h>
46#include <drizzled/open_tables_state.h>
47#include <drizzled/table/cache.h>
48#include <drizzled/create_field.h>
49#include <drizzled/key_part_info.h>
50
51#include <algorithm>
52#include <sstream>
53
54#include <unordered_set>
55
56using namespace std;
57
58namespace drizzled {
59
60bool is_primary_key(const char* name)
61{
62 return strcmp(name, "PRIMARY") == 0;
63}
64
65static bool check_if_keyname_exists(const char *name,KeyInfo *start, KeyInfo *end);
66static const char *make_unique_key_name(const char *field_name,KeyInfo *start,KeyInfo *end);
67static bool prepare_blob_field(Session *session, CreateField *sql_field);
68
69void set_table_default_charset(const identifier::Catalog &catalog, HA_CREATE_INFO *create_info, const char *db)
70{
71 /*
72 If the table character set was not given explicitly,
73 let's fetch the database default character set and
74 apply it to the table.
75 */
76 if (not create_info->default_table_charset)
77 create_info->default_table_charset= plugin::StorageEngine::getSchemaCollation(identifier::Schema(catalog, str_ref(db)));
78}
79
80/*
81 Execute the drop of a normal or temporary table
82
83 SYNOPSIS
84 rm_table_part2()
85 session Thread Cursor
86 tables Tables to drop
87 if_exists If set, don't give an error if table doesn't exists.
88 In this case we give an warning of level 'NOTE'
89 drop_temporary Only drop temporary tables
90
91 @todo
92 When logging to the binary log, we should log
93 tmp_tables and transactional tables as separate statements if we
94 are in a transaction; This is needed to get these tables into the
95 cached binary log that is only written on COMMIT.
96
97 The current code only writes DROP statements that only uses temporary
98 tables to the cache binary log. This should be ok on most cases, but
99 not all.
100
101 RETURN
102 0 ok
103 1 Error
104 -1 Thread was killed
105*/
106
107int rm_table_part2(Session *session, TableList *tables, bool if_exists,
108 bool drop_temporary)
109{
110 TableList *table;
111 util::string::vector wrong_tables;
112 int error= 0;
113 bool foreign_key_error= false;
114
115 do
116 {
117 boost::mutex::scoped_lock scopedLock(table::Cache::mutex());
118
119 if (not drop_temporary && session->lock_table_names_exclusively(tables))
120 {
121 return 1;
122 }
123
124 /* Don't give warnings for not found errors, as we already generate notes */
125 session->no_warnings_for_error= 1;
126
127 for (table= tables; table; table= table->next_local)
128 {
129 identifier::Table tmp_identifier(session->catalog().identifier(),
130 table->getSchemaName(),
131 table->getTableName());
132
133 error= session->open_tables.drop_temporary_table(tmp_identifier);
134
135 switch (error) {
136 case 0:
137 // removed temporary table
138 continue;
139 case -1:
140 error= 1;
141 break;
142 default:
143 // temporary table not found
144 error= 0;
145 }
146
147 if (drop_temporary == false)
148 {
149 abort_locked_tables(session, tmp_identifier);
150 table::Cache::removeTable(*session, tmp_identifier, RTFC_WAIT_OTHER_THREAD_FLAG | RTFC_CHECK_KILLED_FLAG);
151 /*
152 If the table was used in lock tables, remember it so that
153 unlock_table_names can free it
154 */
155 Table *locked_table= drop_locked_tables(session, tmp_identifier);
156 if (locked_table)
157 table->table= locked_table;
158
159 if (session->getKilled())
160 {
161 error= -1;
162 break;
163 }
164 }
165 identifier::Table identifier(session->catalog().identifier(),
166 table->getSchemaName(),
167 table->getTableName(),
168 table->getInternalTmpTable() ? message::Table::INTERNAL : message::Table::STANDARD);
169
170 message::table::shared_ptr message= plugin::StorageEngine::getTableMessage(*session, identifier, true);
171
172 if (drop_temporary || not plugin::StorageEngine::doesTableExist(*session, identifier))
173 {
174 // Table was not found on disk and table can't be created from engine
175 if (if_exists)
176 {
177 push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
178 ER_BAD_TABLE_ERROR, ER(ER_BAD_TABLE_ERROR),
179 table->getTableName());
180 }
181 else
182 {
183 error= 1;
184 }
185 }
186 else
187 {
188 drizzled::error_t local_error;
189
190 /* Generate transaction event ONLY when we successfully drop */
191 if (plugin::StorageEngine::dropTable(*session, identifier, local_error))
192 {
193 if (message) // If we have no definition, we don't know if the table should have been replicated
194 {
195 TransactionServices::dropTable(*session, identifier, *message, if_exists);
196 }
197 }
198 else
199 {
200 if (local_error == HA_ERR_NO_SUCH_TABLE and if_exists)
201 {
202 error= 0;
203 session->clear_error();
204 }
205
206 if (local_error == HA_ERR_ROW_IS_REFERENCED)
207 {
208 /* the table is referenced by a foreign key constraint */
209 foreign_key_error= true;
210 }
211 error= local_error;
212 }
213 }
214
215 if (error)
216 {
217 wrong_tables.push_back(table->getTableName());
218 }
219 }
220
221 tables->unlock_table_names();
222
223 } while (0);
224
225 if (wrong_tables.size())
226 {
227 if (not foreign_key_error)
228 {
229 std::string table_error;
230
231 for (util::string::vector::reference iter : wrong_tables)
232 {
233 table_error+= iter;
234 table_error+= ',';
235 }
236 table_error.resize(table_error.size() -1);
237
238 my_printf_error(ER_BAD_TABLE_ERROR, ER(ER_BAD_TABLE_ERROR), MYF(0),
239 table_error.c_str());
240 }
241 else
242 {
243 my_message(ER_ROW_IS_REFERENCED, ER(ER_ROW_IS_REFERENCED), MYF(0));
244 }
245 error= 1;
246 }
247
248 session->no_warnings_for_error= 0;
249
250 return error;
251}
252
253/*
254 Sort keys in the following order:
255 - PRIMARY KEY
256 - UNIQUE keys where all column are NOT NULL
257 - UNIQUE keys that don't contain partial segments
258 - Other UNIQUE keys
259 - Normal keys
260 - Fulltext keys
261
262 This will make checking for duplicated keys faster and ensure that
263 PRIMARY keys are prioritized.
264*/
265
266static int sort_keys(KeyInfo *a, KeyInfo *b)
267{
268 ulong a_flags= a->flags, b_flags= b->flags;
269
270 if (a_flags & HA_NOSAME)
271 {
272 if (!(b_flags & HA_NOSAME))
273 return -1;
274 if ((a_flags ^ b_flags) & (HA_NULL_PART_KEY))
275 {
276 /* Sort NOT NULL keys before other keys */
277 return (a_flags & (HA_NULL_PART_KEY)) ? 1 : -1;
278 }
279 if (is_primary_key(a->name))
280 return -1;
281 if (is_primary_key(b->name))
282 return 1;
283 /* Sort keys don't containing partial segments before others */
284 if ((a_flags ^ b_flags) & HA_KEY_HAS_PART_KEY_SEG)
285 return (a_flags & HA_KEY_HAS_PART_KEY_SEG) ? 1 : -1;
286 }
287 else if (b_flags & HA_NOSAME)
288 return 1; // Prefer b
289
290 /*
291 Prefer original key order. usable_key_parts contains here
292 the original key position.
293 */
294 return ((a->usable_key_parts < b->usable_key_parts) ? -1 :
295 (a->usable_key_parts > b->usable_key_parts) ? 1 :
296 0);
297}
298
299/*
300 Check TYPELIB (set or enum) for duplicates
301
302 SYNOPSIS
303 check_duplicates_in_interval()
304 set_or_name "SET" or "ENUM" string for warning message
305 name name of the checked column
306 typelib list of values for the column
307 dup_val_count returns count of duplicate elements
308
309 DESCRIPTION
310 This function prints an warning for each value in list
311 which has some duplicates on its right
312
313 RETURN VALUES
314 0 ok
315 1 Error
316*/
317
318class typelib_set_member
319{
320public:
321 string s;
322 const charset_info_st * const cs;
323
324 typelib_set_member(const char* value, unsigned int length,
325 const charset_info_st * const charset)
326 : s(value, length),
327 cs(charset)
328 {}
329};
330
331static bool operator==(typelib_set_member const& a, typelib_set_member const& b)
332{
333 return (my_strnncoll(a.cs,
334 (const unsigned char*)a.s.c_str(), a.s.length(),
335 (const unsigned char*)b.s.c_str(), b.s.length())==0);
336}
337
338
339namespace
340{
341class typelib_set_member_hasher
342{
343 boost::hash<string> hasher;
344public:
345 std::size_t operator()(const typelib_set_member& t) const
346 {
347 return hasher(t.s);
348 }
349};
350}
351
352static bool check_duplicates_in_interval(const char *set_or_name,
353 const char *name, TYPELIB *typelib,
354 const charset_info_st * const cs,
355 unsigned int *dup_val_count)
356{
357 TYPELIB tmp= *typelib;
358 const char **cur_value= typelib->type_names;
359 unsigned int *cur_length= typelib->type_lengths;
360 *dup_val_count= 0;
361
362 std::unordered_set<typelib_set_member, typelib_set_member_hasher> interval_set;
363
364 for ( ; tmp.count > 0; cur_value++, cur_length++)
365 {
366 tmp.type_names++;
367 tmp.type_lengths++;
368 tmp.count--;
369 if (interval_set.count(typelib_set_member(*cur_value, *cur_length, cs)))
370 {
371 my_error(ER_DUPLICATED_VALUE_IN_TYPE, MYF(0),
372 name,*cur_value,set_or_name);
373 return 1;
374 }
375 else
376 interval_set.insert(typelib_set_member(*cur_value, *cur_length, cs));
377 }
378 return 0;
379}
380
381
382/*
383 Check TYPELIB (set or enum) max and total lengths
384
385 SYNOPSIS
386 calculate_interval_lengths()
387 cs charset+collation pair of the interval
388 typelib list of values for the column
389 max_length length of the longest item
390 tot_length sum of the item lengths
391
392 DESCRIPTION
393 After this function call:
394 - ENUM uses max_length
395 - SET uses tot_length.
396
397 RETURN VALUES
398 void
399*/
400static void calculate_interval_lengths(const charset_info_st * const cs,
401 TYPELIB *interval,
402 uint32_t *max_length,
403 uint32_t *tot_length)
404{
405 const char **pos;
406 uint32_t *len;
407 *max_length= *tot_length= 0;
408 for (pos= interval->type_names, len= interval->type_lengths;
409 *pos ; pos++, len++)
410 {
411 uint32_t length= cs->cset->numchars(cs, *pos, *pos + *len);
412 *tot_length+= length;
413 set_if_bigger(*max_length, (uint32_t)length);
414 }
415}
416
417/*
418 Prepare a create_table instance for packing
419
420 SYNOPSIS
421 prepare_create_field()
422 sql_field field to prepare for packing
423 blob_columns count for BLOBs
424 timestamps count for timestamps
425
426 DESCRIPTION
427 This function prepares a CreateField instance.
428 Fields such as pack_flag are valid after this call.
429
430 RETURN VALUES
431 0 ok
432 1 Error
433*/
434int prepare_create_field(CreateField *sql_field,
435 uint32_t *blob_columns,
436 int *timestamps,
437 int *timestamps_with_niladic)
438{
439 unsigned int dup_val_count;
440
441 /*
442 This code came from mysql_prepare_create_table.
443 Indent preserved to make patching easier
444 */
445 assert(sql_field->charset);
446
447 switch (sql_field->sql_type) {
448 case DRIZZLE_TYPE_BLOB:
449 sql_field->length= 8; // Unireg field length
450 (*blob_columns)++;
451 break;
452
453 case DRIZZLE_TYPE_ENUM:
454 {
455 if (check_duplicates_in_interval("ENUM",
456 sql_field->field_name,
457 sql_field->interval,
458 sql_field->charset,
459 &dup_val_count))
460 {
461 return 1;
462 }
463 }
464 break;
465
466 case DRIZZLE_TYPE_MICROTIME:
467 case DRIZZLE_TYPE_TIMESTAMP:
468 /* We should replace old TIMESTAMP fields with their newer analogs */
469 if (sql_field->unireg_check == Field::TIMESTAMP_OLD_FIELD)
470 {
471 if (!*timestamps)
472 {
473 sql_field->unireg_check= Field::TIMESTAMP_DNUN_FIELD;
474 (*timestamps_with_niladic)++;
475 }
476 else
477 {
478 sql_field->unireg_check= Field::NONE;
479 }
480 }
481 else if (sql_field->unireg_check != Field::NONE)
482 {
483 (*timestamps_with_niladic)++;
484 }
485
486 (*timestamps)++;
487
488 break;
489
490 case DRIZZLE_TYPE_BOOLEAN:
491 case DRIZZLE_TYPE_DATE: // Rest of string types
492 case DRIZZLE_TYPE_DATETIME:
493 case DRIZZLE_TYPE_DECIMAL:
494 case DRIZZLE_TYPE_DOUBLE:
495 case DRIZZLE_TYPE_LONG:
496 case DRIZZLE_TYPE_LONGLONG:
497 case DRIZZLE_TYPE_NULL:
498 case DRIZZLE_TYPE_TIME:
499 case DRIZZLE_TYPE_UUID:
500 case DRIZZLE_TYPE_IPV6:
501 case DRIZZLE_TYPE_VARCHAR:
502 break;
503 }
504
505 return 0;
506}
507
508static int prepare_create_table(Session *session,
509 HA_CREATE_INFO *create_info,
510 message::Table &create_proto,
511 AlterInfo *alter_info,
512 bool tmp_table,
513 uint32_t *db_options,
514 KeyInfo **key_info_buffer,
515 uint32_t *key_count,
516 int select_field_count)
517{
518 const char *key_name;
519 CreateField *sql_field,*dup_field;
520 uint field,blob_columns,max_key_length;
521 ulong record_offset= 0;
522 KeyInfo *key_info;
523 KeyPartInfo *key_part_info;
524 int timestamps= 0, timestamps_with_niladic= 0;
525 int dup_no;
526 int select_field_pos,auto_increment=0;
527 List<CreateField>::iterator it(alter_info->create_list.begin());
528 List<CreateField>::iterator it2(alter_info->create_list.begin());
529
530 plugin::StorageEngine *engine= plugin::StorageEngine::findByName(create_proto.engine().name());
531
532 select_field_pos= alter_info->create_list.size() - select_field_count;
533 blob_columns=0;
534 max_key_length= engine->max_key_length();
535
536 for (int32_t field_no=0; (sql_field=it++) ; field_no++)
537 {
538 const charset_info_st *save_cs;
539
540 /*
541 Initialize length from its original value (number of characters),
542 which was set in the parser. This is necessary if we're
543 executing a prepared statement for the second time.
544 */
545 sql_field->length= sql_field->char_length;
546
547 if (!sql_field->charset)
548 sql_field->charset= create_info->default_table_charset;
549
550 /*
551 table_charset is set in ALTER Table if we want change character set
552 for all varchar/char columns.
553 But the table charset must not affect the BLOB fields, so don't
554 allow to change my_charset_bin to somethig else.
555 */
556 if (create_info->table_charset && sql_field->charset != &my_charset_bin)
557 sql_field->charset= create_info->table_charset;
558
559 save_cs= sql_field->charset;
560 if ((sql_field->flags & BINCMP_FLAG) &&
561 !(sql_field->charset= get_charset_by_csname(sql_field->charset->csname, MY_CS_BINSORT)))
562 {
563 char tmp[64];
564 snprintf(tmp, sizeof(tmp), "%.*s_bin", (int)sizeof(tmp)-5,
565 save_cs->csname);
566 my_error(ER_UNKNOWN_COLLATION, MYF(0), tmp);
567 return true;
568 }
569
570 /*
571 Convert the default value from client character
572 set into the column character set if necessary.
573 */
574 if (sql_field->def &&
575 save_cs != sql_field->def->collation.collation &&
576 (sql_field->sql_type == DRIZZLE_TYPE_ENUM))
577 {
578 /*
579 Starting from 5.1 we work here with a copy of CreateField
580 created by the caller, not with the instance that was
581 originally created during parsing. It's OK to create
582 a temporary item and initialize with it a member of the
583 copy -- this item will be thrown away along with the copy
584 at the end of execution, and thus not introduce a dangling
585 pointer in the parsed tree of a prepared statement or a
586 stored procedure statement.
587 */
588 sql_field->def= sql_field->def->safe_charset_converter(save_cs);
589
590 if (sql_field->def == NULL)
591 {
592 /* Could not convert */
593 my_error(ER_INVALID_DEFAULT, MYF(0), sql_field->field_name);
594 return true;
595 }
596 }
597
598 if (sql_field->sql_type == DRIZZLE_TYPE_ENUM)
599 {
600 const charset_info_st * const cs= sql_field->charset;
601 TYPELIB *interval= sql_field->interval;
602
603 /*
604 Create typelib from interval_list, and if necessary
605 convert strings from client character set to the
606 column character set.
607 */
608 if (!interval)
609 {
610 /*
611 Create the typelib in runtime memory - we will free the
612 occupied memory at the same time when we free this
613 sql_field -- at the end of execution.
614 */
615 interval= sql_field->interval= typelib(*session->mem_root, sql_field->interval_list);
616
617 List<String>::iterator int_it(sql_field->interval_list.begin());
618 String conv, *tmp;
619 char comma_buf[4];
620 int comma_length= cs->cset->wc_mb(cs, ',', (unsigned char*) comma_buf, (unsigned char*) comma_buf + sizeof(comma_buf));
621 assert(comma_length > 0);
622
623 for (uint32_t i= 0; (tmp= int_it++); i++)
624 {
625 uint32_t lengthsp;
626 if (String::needs_conversion(tmp->length(), tmp->charset(), cs))
627 {
628 conv.copy(tmp->ptr(), tmp->length(), cs);
629 interval->type_names[i]= session->mem.strdup(conv);
630 interval->type_lengths[i]= conv.length();
631 }
632
633 // Strip trailing spaces.
634 lengthsp= cs->cset->lengthsp(cs, interval->type_names[i], interval->type_lengths[i]);
635 interval->type_lengths[i]= lengthsp;
636 ((unsigned char *)interval->type_names[i])[lengthsp]= '\0';
637 }
638 sql_field->interval_list.clear(); // Don't need interval_list anymore
639 }
640
641 /* DRIZZLE_TYPE_ENUM */
642 {
643 uint32_t field_length;
644 assert(sql_field->sql_type == DRIZZLE_TYPE_ENUM);
645 if (sql_field->def != NULL)
646 {
647 String str, *def= sql_field->def->val_str(&str);
648 if (def == NULL) /* SQL "NULL" maps to NULL */
649 {
650 if (sql_field->flags & NOT_NULL_FLAG)
651 {
652 my_error(ER_INVALID_DEFAULT, MYF(0), sql_field->field_name);
653 return true;
654 }
655
656 /* else, the defaults yield the correct length for NULLs. */
657 }
658 else /* not NULL */
659 {
660 def->length(cs->cset->lengthsp(cs, def->ptr(), def->length()));
661 if (interval->find_type2(def->ptr(), def->length(), cs) == 0) /* not found */
662 {
663 my_error(ER_INVALID_DEFAULT, MYF(0), sql_field->field_name);
664 return true;
665 }
666 }
667 }
668 uint32_t new_dummy;
669 calculate_interval_lengths(cs, interval, &field_length, &new_dummy);
670 sql_field->length= field_length;
671 }
672 set_if_smaller(sql_field->length, (uint32_t)MAX_FIELD_WIDTH-1);
673 }
674
676 if (prepare_blob_field(session, sql_field))
677 return true;
678
679 if (check_column_name(sql_field->field_name))
680 {
681 my_error(ER_WRONG_COLUMN_NAME, MYF(0), sql_field->field_name);
682 return true;
683 }
684
685 /* Check if we have used the same field name before */
686 for (dup_no=0; (dup_field=it2++) != sql_field; dup_no++)
687 {
688 if (system_charset_info->strcasecmp(sql_field->field_name, dup_field->field_name) == 0)
689 {
690 /*
691 If this was a CREATE ... SELECT statement, accept a field
692 redefinition if we are changing a field in the SELECT part
693 */
694 if (field_no < select_field_pos || dup_no >= select_field_pos)
695 {
696 my_error(ER_DUP_FIELDNAME, MYF(0), sql_field->field_name);
697 return true;
698 }
699 else
700 {
701 /* Field redefined */
702 sql_field->def= dup_field->def;
703 sql_field->sql_type= dup_field->sql_type;
704 sql_field->charset= (dup_field->charset ?
705 dup_field->charset :
706 create_info->default_table_charset);
707 sql_field->length= dup_field->char_length;
708 sql_field->pack_length= dup_field->pack_length;
709 sql_field->key_length= dup_field->key_length;
710 sql_field->decimals= dup_field->decimals;
712 sql_field->unireg_check= dup_field->unireg_check;
713 sql_field->flags= dup_field->flags;
714 sql_field->interval= dup_field->interval;
715 it2.remove(); // Remove first (create) definition
716 select_field_pos--;
717 break;
718 }
719 }
720 }
721
723 if (not create_proto.engine().name().compare("MyISAM") &&
724 ((sql_field->flags & BLOB_FLAG) ||
725 (sql_field->sql_type == DRIZZLE_TYPE_VARCHAR)))
726 {
727 (*db_options)|= HA_OPTION_PACK_RECORD;
728 }
729
730 it2= alter_info->create_list.begin();
731 }
732
733 record_offset= 0;
734 it= alter_info->create_list.begin();
735 while ((sql_field=it++))
736 {
737 assert(sql_field->charset != 0);
738
739 if (prepare_create_field(sql_field, &blob_columns,
740 &timestamps, &timestamps_with_niladic))
741 return true;
742 sql_field->offset= record_offset;
743 if (MTYP_TYPENR(sql_field->unireg_check) == Field::NEXT_NUMBER)
744 auto_increment++;
745 }
746 if (timestamps_with_niladic > 1)
747 {
748 my_message(ER_TOO_MUCH_AUTO_TIMESTAMP_COLS,
749 ER(ER_TOO_MUCH_AUTO_TIMESTAMP_COLS), MYF(0));
750 return true;
751 }
752 if (auto_increment > 1)
753 {
754 my_message(ER_WRONG_AUTO_KEY, ER(ER_WRONG_AUTO_KEY), MYF(0));
755 return true;
756 }
757 if (auto_increment &&
758 (engine->check_flag(HTON_BIT_NO_AUTO_INCREMENT)))
759 {
760 my_message(ER_TABLE_CANT_HANDLE_AUTO_INCREMENT,
761 ER(ER_TABLE_CANT_HANDLE_AUTO_INCREMENT), MYF(0));
762 return true;
763 }
764
765 if (blob_columns && (engine->check_flag(HTON_BIT_NO_BLOBS)))
766 {
767 my_message(ER_TABLE_CANT_HANDLE_BLOB, ER(ER_TABLE_CANT_HANDLE_BLOB),
768 MYF(0));
769 return true;
770 }
771
772 /* Create keys */
773
774 List<Key>::iterator key_iterator(alter_info->key_list.begin());
775 List<Key>::iterator key_iterator2(alter_info->key_list.begin());
776 uint32_t key_parts=0;
777 bool primary_key=0,unique_key=0;
778 Key *key, *key2;
779 uint32_t tmp, key_number;
780 /* special marker for keys to be ignored */
781 static char ignore_key[1];
782
783 /* Calculate number of key segements */
784 *key_count= 0;
785
786 while ((key=key_iterator++))
787 {
788 if (key->type == Key::FOREIGN_KEY)
789 {
790 if (((Foreign_key *)key)->validate(alter_info->create_list))
791 return true;
792
793 Foreign_key *fk_key= (Foreign_key*) key;
794
795 add_foreign_key_to_table_message(&create_proto,
796 fk_key->name.data(),
797 fk_key->columns,
798 fk_key->ref_table,
799 fk_key->ref_columns,
800 fk_key->delete_opt,
801 fk_key->update_opt,
802 fk_key->match_opt);
803
804 if (fk_key->ref_columns.size() &&
805 fk_key->ref_columns.size() != fk_key->columns.size())
806 {
807 my_error(ER_WRONG_FK_DEF, MYF(0),
808 (fk_key->name.data() ? fk_key->name.data() : "foreign key without name"),
809 ER(ER_KEY_REF_DO_NOT_MATCH_TABLE_REF));
810 return true;
811 }
812 continue;
813 }
814 (*key_count)++;
815 tmp= engine->max_key_parts();
816 if (key->columns.size() > tmp)
817 {
818 my_error(ER_TOO_MANY_KEY_PARTS,MYF(0),tmp);
819 return true;
820 }
821 if (check_identifier_name(key->name, ER_TOO_LONG_IDENT))
822 return true;
823 key_iterator2= alter_info->key_list.begin();
824 if (key->type != Key::FOREIGN_KEY)
825 {
826 while ((key2 = key_iterator2++) != key)
827 {
828 /*
829 foreign_key_prefix(key, key2) returns 0 if key or key2, or both, is
830 'generated', and a generated key is a prefix of the other key.
831 Then we do not need the generated shorter key.
832 */
833 if ((key2->type != Key::FOREIGN_KEY &&
834 key2->name.data() != ignore_key &&
835 !foreign_key_prefix(key, key2)))
836 {
837 /* @todo issue warning message */
838 /* mark that the generated key should be ignored */
839 if (!key2->generated ||
840 (key->generated && key->columns.size() <
841 key2->columns.size()))
842 key->name.assign(ignore_key, 1);
843 else
844 {
845 key2->name.assign(ignore_key, 1);
846 key_parts-= key2->columns.size();
847 (*key_count)--;
848 }
849 break;
850 }
851 }
852 }
853 if (key->name.data() != ignore_key)
854 key_parts+=key->columns.size();
855 else
856 (*key_count)--;
857 if (key->name.data() && !tmp_table && (key->type != Key::PRIMARY) && is_primary_key(key->name.data()))
858 {
859 my_error(ER_WRONG_NAME_FOR_INDEX, MYF(0), key->name.data());
860 return true;
861 }
862 }
863 tmp= engine->max_keys();
864 if (*key_count > tmp)
865 {
866 my_error(ER_TOO_MANY_KEYS,MYF(0),tmp);
867 return true;
868 }
869
870 (*key_info_buffer)= key_info= (KeyInfo*) memory::sql_calloc(sizeof(KeyInfo) * (*key_count));
871 key_part_info=(KeyPartInfo*) memory::sql_calloc(sizeof(KeyPartInfo)*key_parts);
872
873 key_iterator= alter_info->key_list.begin();
874 key_number=0;
875 for (; (key=key_iterator++) ; key_number++)
876 {
877 uint32_t key_length=0;
878 Key_part_spec *column;
879
880 if (key->name.data() == ignore_key)
881 {
882 /* ignore redundant keys */
883 do
884 key=key_iterator++;
885 while (key && key->name.data() == ignore_key);
886 if (!key)
887 break;
888 }
889
890 switch (key->type) {
891 case Key::MULTIPLE:
892 key_info->flags= 0;
893 break;
894 case Key::FOREIGN_KEY:
895 key_number--; // Skip this key
896 continue;
897 default:
898 key_info->flags = HA_NOSAME;
899 break;
900 }
901 if (key->generated)
902 key_info->flags|= HA_GENERATED_KEY;
903
904 key_info->key_parts=(uint8_t) key->columns.size();
905 key_info->key_part=key_part_info;
906 key_info->usable_key_parts= key_number;
907 key_info->algorithm= key->key_create_info.algorithm;
908
909 uint32_t tmp_len= system_charset_info->cset->charpos(system_charset_info,
910 key->key_create_info.comment.begin(),
911 key->key_create_info.comment.end(),
912 INDEX_COMMENT_MAXLEN);
913
914 if (tmp_len < key->key_create_info.comment.size())
915 {
916 my_error(ER_WRONG_STRING_LENGTH, MYF(0), key->key_create_info.comment.data(), "INDEX COMMENT", (uint32_t) INDEX_COMMENT_MAXLEN);
917 return -1;
918 }
919
920 key_info->comment.assign(key_info->comment.data(), key->key_create_info.comment.size());
921 if (key_info->comment.size() > 0)
922 {
923 key_info->flags|= HA_USES_COMMENT;
924 key_info->comment.assign(key->key_create_info.comment.data(), key_info->comment.size()); // weird
925 }
926
927 message::Table::Field *protofield= NULL;
928
929 List<Key_part_spec>::iterator cols(key->columns.begin());
930 List<Key_part_spec>::iterator cols2(key->columns.begin());
931 for (uint32_t column_nr=0 ; (column=cols++) ; column_nr++)
932 {
933 uint32_t length;
934 Key_part_spec *dup_column;
935 int proto_field_nr= 0;
936
937 it= alter_info->create_list.begin();
938 field=0;
939 while ((sql_field=it++) && ++proto_field_nr &&
940 system_charset_info->strcasecmp(column->field_name.data(), sql_field->field_name))
941 {
942 field++;
943 }
944
945 if (!sql_field)
946 {
947 my_error(ER_KEY_COLUMN_DOES_NOT_EXITS, MYF(0), column->field_name.data());
948 return true;
949 }
950
951 while ((dup_column= cols2++) != column)
952 {
953 if (!system_charset_info->strcasecmp(column->field_name.data(), dup_column->field_name.data()))
954 {
955 my_printf_error(ER_DUP_FIELDNAME,
956 ER(ER_DUP_FIELDNAME),MYF(0),
957 column->field_name.data());
958 return true;
959 }
960 }
961 cols2= key->columns.begin();
962
963 if (create_proto.field_size() > 0)
964 protofield= create_proto.mutable_field(proto_field_nr - 1);
965
966 {
967 column->length*= sql_field->charset->mbmaxlen;
968
969 if (sql_field->sql_type == DRIZZLE_TYPE_BLOB)
970 {
971 if (! (engine->check_flag(HTON_BIT_CAN_INDEX_BLOBS)))
972 {
973 my_error(ER_BLOB_USED_AS_KEY, MYF(0), column->field_name.data());
974 return true;
975 }
976 if (! column->length)
977 {
978 my_error(ER_BLOB_KEY_WITHOUT_LENGTH, MYF(0), column->field_name.data());
979 return true;
980 }
981 }
982
983 if (! (sql_field->flags & NOT_NULL_FLAG))
984 {
985 if (key->type == Key::PRIMARY)
986 {
987 /* Implicitly set primary key fields to NOT NULL for ISO conf. */
988 sql_field->flags|= NOT_NULL_FLAG;
989 if (protofield)
990 {
991 message::Table::Field::FieldConstraints *constraints;
992 constraints= protofield->mutable_constraints();
993 constraints->set_is_notnull(true);
994 }
995
996 }
997 else
998 {
999 key_info->flags|= HA_NULL_PART_KEY;
1000 if (! (engine->check_flag(HTON_BIT_NULL_IN_KEY)))
1001 {
1002 my_error(ER_NULL_COLUMN_IN_INDEX, MYF(0), column->field_name.data());
1003 return true;
1004 }
1005 }
1006 }
1007
1008 if (MTYP_TYPENR(sql_field->unireg_check) == Field::NEXT_NUMBER)
1009 {
1010 if (column_nr == 0 || (engine->check_flag(HTON_BIT_AUTO_PART_KEY)))
1011 auto_increment--; // Field is used
1012 }
1013 }
1014
1015 key_part_info->fieldnr= field;
1016 key_part_info->offset= (uint16_t) sql_field->offset;
1017 key_part_info->key_type= 0;
1018 length= sql_field->key_length;
1019
1020 if (column->length)
1021 {
1022 if (sql_field->sql_type == DRIZZLE_TYPE_BLOB)
1023 {
1024 if ((length=column->length) > max_key_length ||
1025 length > engine->max_key_part_length())
1026 {
1027 length= min(max_key_length, engine->max_key_part_length());
1028 if (key->type == Key::MULTIPLE)
1029 {
1030 /* not a critical problem */
1031 char warn_buff[DRIZZLE_ERRMSG_SIZE];
1032 snprintf(warn_buff, sizeof(warn_buff), ER(ER_TOO_LONG_KEY),
1033 length);
1034 push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_WARN,
1035 ER_TOO_LONG_KEY, warn_buff);
1036 /* Align key length to multibyte char boundary */
1037 length-= length % sql_field->charset->mbmaxlen;
1038 }
1039 else
1040 {
1041 my_error(ER_TOO_LONG_KEY,MYF(0),length);
1042 return true;
1043 }
1044 }
1045 }
1046 else if ((column->length > length ||
1048 {
1049 my_message(ER_WRONG_SUB_KEY, ER(ER_WRONG_SUB_KEY), MYF(0));
1050 return true;
1051 }
1052 else if (! (engine->check_flag(HTON_BIT_NO_PREFIX_CHAR_KEYS)))
1053 {
1054 length=column->length;
1055 }
1056 }
1057 else if (length == 0)
1058 {
1059 my_error(ER_WRONG_KEY_COLUMN, MYF(0), column->field_name.data());
1060 return true;
1061 }
1062 if (length > engine->max_key_part_length())
1063 {
1064 length= engine->max_key_part_length();
1065 if (key->type == Key::MULTIPLE)
1066 {
1067 /* not a critical problem */
1068 char warn_buff[DRIZZLE_ERRMSG_SIZE];
1069 snprintf(warn_buff, sizeof(warn_buff), ER(ER_TOO_LONG_KEY),
1070 length);
1071 push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_WARN,
1072 ER_TOO_LONG_KEY, warn_buff);
1073 /* Align key length to multibyte char boundary */
1074 length-= length % sql_field->charset->mbmaxlen;
1075 }
1076 else
1077 {
1078 my_error(ER_TOO_LONG_KEY,MYF(0),length);
1079 return true;
1080 }
1081 }
1082 key_part_info->length=(uint16_t) length;
1083 /* Use packed keys for long strings on the first column */
1084 if (!((*db_options) & HA_OPTION_NO_PACK_KEYS) &&
1085 (length >= KEY_DEFAULT_PACK_LENGTH &&
1086 (sql_field->sql_type == DRIZZLE_TYPE_VARCHAR ||
1087 sql_field->sql_type == DRIZZLE_TYPE_BLOB)))
1088 {
1089 if ((column_nr == 0 && sql_field->sql_type == DRIZZLE_TYPE_BLOB) ||
1090 sql_field->sql_type == DRIZZLE_TYPE_VARCHAR)
1091 {
1092 key_info->flags|= HA_BINARY_PACK_KEY | HA_VAR_LENGTH_KEY;
1093 }
1094 else
1095 {
1096 key_info->flags|= HA_PACK_KEY;
1097 }
1098 }
1099 /* Check if the key segment is partial, set the key flag accordingly */
1100 if (length != sql_field->key_length)
1101 key_info->flags|= HA_KEY_HAS_PART_KEY_SEG;
1102
1103 key_length+=length;
1104 key_part_info++;
1105
1106 /* Create the key name based on the first column (if not given) */
1107 if (column_nr == 0)
1108 {
1109 if (key->type == Key::PRIMARY)
1110 {
1111 if (primary_key)
1112 {
1113 my_message(ER_MULTIPLE_PRI_KEY, ER(ER_MULTIPLE_PRI_KEY),
1114 MYF(0));
1115 return true;
1116 }
1117 static const char pkey_name[]= "PRIMARY";
1118 key_name=pkey_name;
1119 primary_key=1;
1120 }
1121 else if (!(key_name= key->name.data()))
1122 key_name=make_unique_key_name(sql_field->field_name,
1123 *key_info_buffer, key_info);
1124 if (check_if_keyname_exists(key_name, *key_info_buffer, key_info))
1125 {
1126 my_error(ER_DUP_KEYNAME, MYF(0), key_name);
1127 return true;
1128 }
1129 key_info->name=(char*) key_name;
1130 }
1131 }
1132
1133 if (!key_info->name || check_column_name(key_info->name))
1134 {
1135 my_error(ER_WRONG_NAME_FOR_INDEX, MYF(0), key_info->name);
1136 return true;
1137 }
1138
1139 if (!(key_info->flags & HA_NULL_PART_KEY))
1140 {
1141 unique_key=1;
1142 }
1143
1144 key_info->key_length=(uint16_t) key_length;
1145
1146 if (key_length > max_key_length)
1147 {
1148 my_error(ER_TOO_LONG_KEY,MYF(0),max_key_length);
1149 return true;
1150 }
1151
1152 key_info++;
1153 }
1154
1155 if (!unique_key && !primary_key &&
1156 (engine->check_flag(HTON_BIT_REQUIRE_PRIMARY_KEY)))
1157 {
1158 my_message(ER_REQUIRES_PRIMARY_KEY, ER(ER_REQUIRES_PRIMARY_KEY), MYF(0));
1159 return true;
1160 }
1161
1162 if (auto_increment > 0)
1163 {
1164 my_message(ER_WRONG_AUTO_KEY, ER(ER_WRONG_AUTO_KEY), MYF(0));
1165 return true;
1166 }
1167 /* Sort keys in optimized order */
1168 internal::my_qsort((unsigned char*) *key_info_buffer, *key_count, sizeof(KeyInfo),
1169 (qsort_cmp) sort_keys);
1170
1171 /* Check fields. */
1172 it= alter_info->create_list.begin();
1173 while ((sql_field=it++))
1174 {
1175 Field::utype type= (Field::utype) MTYP_TYPENR(sql_field->unireg_check);
1176
1177 if (session->variables.sql_mode & MODE_NO_ZERO_DATE &&
1178 !sql_field->def &&
1179 (sql_field->sql_type == DRIZZLE_TYPE_TIMESTAMP or sql_field->sql_type == DRIZZLE_TYPE_MICROTIME) &&
1180 (sql_field->flags & NOT_NULL_FLAG) &&
1181 (type == Field::NONE || type == Field::TIMESTAMP_UN_FIELD))
1182 {
1183 /*
1184 An error should be reported if:
1185 - NO_ZERO_DATE SQL mode is active;
1186 - there is no explicit DEFAULT clause (default column value);
1187 - this is a TIMESTAMP column;
1188 - the column is not NULL;
1189 - this is not the DEFAULT CURRENT_TIMESTAMP column.
1190
1191 In other words, an error should be reported if
1192 - NO_ZERO_DATE SQL mode is active;
1193 - the column definition is equivalent to
1194 'column_name TIMESTAMP DEFAULT 0'.
1195 */
1196
1197 my_error(ER_INVALID_DEFAULT, MYF(0), sql_field->field_name);
1198 return true;
1199 }
1200 }
1201
1202 return false;
1203}
1204
1205/*
1206 Extend long VARCHAR fields to blob & prepare field if it's a blob
1207
1208 SYNOPSIS
1209 prepare_blob_field()
1210 sql_field Field to check
1211
1212 RETURN
1213 0 ok
1214 1 Error (sql_field can't be converted to blob)
1215 In this case the error is given
1216*/
1217
1218static bool prepare_blob_field(Session *,
1219 CreateField *sql_field)
1220{
1221
1222 if (sql_field->length > MAX_FIELD_VARCHARLENGTH &&
1223 !(sql_field->flags & BLOB_FLAG))
1224 {
1225 my_error(ER_TOO_BIG_FIELDLENGTH, MYF(0), sql_field->field_name,
1226 MAX_FIELD_VARCHARLENGTH / sql_field->charset->mbmaxlen);
1227 return 1;
1228 }
1229
1230 if ((sql_field->flags & BLOB_FLAG) && sql_field->length)
1231 {
1232 if (sql_field->sql_type == DRIZZLE_TYPE_BLOB)
1233 {
1234 /* The user has given a length to the blob column */
1235 sql_field->pack_length= calc_pack_length(sql_field->sql_type, 0);
1236 }
1237 sql_field->length= 0;
1238 }
1239 return 0;
1240}
1241
1242static bool locked_create_event(Session *session,
1243 const identifier::Table &identifier,
1244 HA_CREATE_INFO *create_info,
1245 message::Table &table_proto,
1246 AlterInfo *alter_info,
1247 bool is_if_not_exists,
1248 bool internal_tmp_table,
1249 uint db_options,
1250 uint key_count,
1251 KeyInfo *key_info_buffer)
1252{
1253 bool error= true;
1254
1255 {
1256
1257 /*
1258 @note if we are building a temp table we need to check to see if a temp table
1259 already exists, otherwise we just need to find out if a normal table exists (aka it is fine
1260 to create a table under a temporary table.
1261 */
1262 bool exists=
1263 plugin::StorageEngine::doesTableExist(*session, identifier,
1264 identifier.getType() != message::Table::STANDARD );
1265
1266 if (exists)
1267 {
1268 if (is_if_not_exists)
1269 {
1270 error= false;
1271 push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
1272 ER_TABLE_EXISTS_ERROR, ER(ER_TABLE_EXISTS_ERROR),
1273 identifier.getTableName().c_str());
1274 create_info->table_existed= 1; // Mark that table existed
1275 return error;
1276 }
1277
1278 my_error(ER_TABLE_EXISTS_ERROR, identifier);
1279
1280 return error;
1281 }
1282
1283 if (identifier.getType() == message::Table::STANDARD) // We have a real table
1284 {
1285 /*
1286 We don't assert here, but check the result, because the table could be
1287 in the table definition cache and in the same time the .frm could be
1288 missing from the disk, in case of manual intervention which deletes
1289 the .frm cursor. The user has to use FLUSH TABLES; to clear the cache.
1290 Then she could create the table. This case is pretty obscure and
1291 therefore we don't introduce a new error message only for it.
1292 */
1293 /*
1294 @todo improve this error condition.
1295 */
1296 if (definition::Cache::find(identifier.getKey()))
1297 {
1298 my_error(ER_TABLE_EXISTS_ERROR, identifier);
1299
1300 return error;
1301 }
1302 }
1303 }
1304
1305 session->set_proc_info("creating table");
1306 create_info->table_existed= 0; // Mark that table is created
1307
1308 create_info->table_options= db_options;
1309
1310 if (not rea_create_table(session, identifier,
1311 table_proto,
1312 create_info, alter_info->create_list,
1313 key_count, key_info_buffer))
1314 {
1315 return error;
1316 }
1317
1318 if (identifier.getType() == message::Table::TEMPORARY)
1319 {
1320 /* Open table and put in temporary table list */
1321 if (not (session->open_temporary_table(identifier)))
1322 {
1323 (void) session->open_tables.rm_temporary_table(identifier);
1324 return error;
1325 }
1326 }
1327
1328 /*
1329 We keep this behind the lock to make sure ordering is correct for a table.
1330 This is a very unlikely problem where before we would write out to the
1331 trans log, someone would do a delete/create operation.
1332 */
1333
1334 if (table_proto.type() == message::Table::STANDARD && not internal_tmp_table)
1335 {
1336 TransactionServices::createTable(*session, table_proto);
1337 }
1338
1339 return false;
1340}
1341
1342
1343/*
1344 Ignore the name of this function... it locks :(
1345
1346 Create a table
1347
1348 SYNOPSIS
1349 create_table_no_lock()
1350 session Thread object
1351 db Database
1352 table_name Table name
1353 create_info Create information (like MAX_ROWS)
1354 fields List of fields to create
1355 keys List of keys to create
1356 internal_tmp_table Set to 1 if this is an internal temporary table
1357 (From ALTER Table)
1358 select_field_count
1359
1360 DESCRIPTION
1361 If one creates a temporary table, this is automatically opened
1362
1363 Note that this function assumes that caller already have taken
1364 name-lock on table being created or used some other way to ensure
1365 that concurrent operations won't intervene. create_table()
1366 is a wrapper that can be used for this.
1367
1368 RETURN VALUES
1369 false OK
1370 true error
1371*/
1372
1373bool create_table_no_lock(Session *session,
1374 const identifier::Table &identifier,
1375 HA_CREATE_INFO *create_info,
1376 message::Table &table_proto,
1377 AlterInfo *alter_info,
1378 bool internal_tmp_table,
1379 uint32_t select_field_count,
1380 bool is_if_not_exists)
1381{
1382 uint db_options, key_count;
1383 KeyInfo *key_info_buffer;
1384 bool error= true;
1385
1386 /* Check for duplicate fields and check type of table to create */
1387 if (not alter_info->create_list.size())
1388 {
1389 my_message(ER_TABLE_MUST_HAVE_COLUMNS, ER(ER_TABLE_MUST_HAVE_COLUMNS),
1390 MYF(0));
1391 return true;
1392 }
1393 assert(identifier.getTableName() == table_proto.name());
1394 db_options= create_info->table_options;
1395
1396 set_table_default_charset(session->catalog().identifier(),create_info, identifier.getSchemaName().c_str());
1397
1398 /* Build a Table object to pass down to the engine, and the do the actual create. */
1399 if (not prepare_create_table(session, create_info, table_proto, alter_info,
1400 internal_tmp_table,
1401 &db_options,
1402 &key_info_buffer, &key_count,
1403 select_field_count))
1404 {
1405 boost::mutex::scoped_lock lock(table::Cache::mutex()); /* CREATE TABLE (some confussion on naming, double check) */
1406 error= locked_create_event(session,
1407 identifier,
1408 create_info,
1409 table_proto,
1410 alter_info,
1411 is_if_not_exists,
1412 internal_tmp_table,
1413 db_options, key_count,
1414 key_info_buffer);
1415 }
1416
1417 session->set_proc_info("After create");
1418
1419 return(error);
1420}
1421
1425static bool drizzle_create_table(Session *session,
1426 const identifier::Table &identifier,
1427 HA_CREATE_INFO *create_info,
1428 message::Table &table_proto,
1429 AlterInfo *alter_info,
1430 bool internal_tmp_table,
1431 uint32_t select_field_count,
1432 bool is_if_not_exists)
1433{
1434 Table *name_lock= session->lock_table_name_if_not_cached(identifier);
1435 bool result;
1436 if (name_lock == NULL)
1437 {
1438 if (is_if_not_exists)
1439 {
1440 push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
1441 ER_TABLE_EXISTS_ERROR, ER(ER_TABLE_EXISTS_ERROR),
1442 identifier.getTableName().c_str());
1443 create_info->table_existed= 1;
1444 result= false;
1445 }
1446 else
1447 {
1448 my_error(ER_TABLE_EXISTS_ERROR, identifier);
1449 result= true;
1450 }
1451 }
1452 else
1453 {
1454 result= create_table_no_lock(session,
1455 identifier,
1456 create_info,
1457 table_proto,
1458 alter_info,
1459 internal_tmp_table,
1460 select_field_count,
1461 is_if_not_exists);
1462 }
1463
1464 if (name_lock)
1465 {
1466 boost::mutex::scoped_lock lock(table::Cache::mutex()); /* Lock for removing name_lock during table create */
1467 session->unlink_open_table(name_lock);
1468 }
1469
1470 return(result);
1471}
1472
1473
1474/*
1475 Database locking aware wrapper for create_table_no_lock(),
1476*/
1477bool create_table(Session *session,
1478 const identifier::Table &identifier,
1479 HA_CREATE_INFO *create_info,
1480 message::Table &table_proto,
1481 AlterInfo *alter_info,
1482 bool internal_tmp_table,
1483 uint32_t select_field_count,
1484 bool is_if_not_exists)
1485{
1486 if (identifier.isTmp())
1487 {
1488 return create_table_no_lock(session,
1489 identifier,
1490 create_info,
1491 table_proto,
1492 alter_info,
1493 internal_tmp_table,
1494 select_field_count,
1495 is_if_not_exists);
1496 }
1497
1498 return drizzle_create_table(session,
1499 identifier,
1500 create_info,
1501 table_proto,
1502 alter_info,
1503 internal_tmp_table,
1504 select_field_count,
1505 is_if_not_exists);
1506}
1507
1508
1509/*
1510** Give the key name after the first field with an optional '_#' after
1511**/
1512
1513static bool
1514check_if_keyname_exists(const char *name, KeyInfo *start, KeyInfo *end)
1515{
1516 for (KeyInfo *key= start; key != end; key++)
1517 {
1518 if (!system_charset_info->strcasecmp(name, key->name))
1519 return 1;
1520 }
1521 return 0;
1522}
1523
1524
1525static const char*
1526make_unique_key_name(const char *field_name,KeyInfo *start,KeyInfo *end)
1527{
1528 char buff[MAX_FIELD_NAME],*buff_end;
1529
1530 if (not check_if_keyname_exists(field_name,start,end) && not is_primary_key(field_name))
1531 {
1532 return field_name; // Use fieldname
1533 }
1534
1535 buff_end= strncpy(buff, field_name, sizeof(buff)-4);
1536 buff_end+= strlen(buff);
1537
1538 /*
1539 Only 3 chars + '\0' left, so need to limit to 2 digit
1540 This is ok as we can't have more than 100 keys anyway
1541 */
1542 for (uint32_t i=2 ; i< 100; i++)
1543 {
1544 *buff_end= '_';
1545 internal::int10_to_str(i, buff_end+1, 10);
1546 if (!check_if_keyname_exists(buff,start,end))
1547 return memory::sql_strdup(buff);
1548 }
1549 return (char*) "not_specified"; // Should never happen
1550}
1551
1552
1553/****************************************************************************
1554** Alter a table definition
1555****************************************************************************/
1556
1557/*
1558 Rename a table.
1559
1560 SYNOPSIS
1561 rename_table()
1562 session
1563 base The plugin::StorageEngine handle.
1564 old_db The old database name.
1565 old_name The old table name.
1566 new_db The new database name.
1567 new_name The new table name.
1568
1569 RETURN
1570 false OK
1571 true Error
1572*/
1573
1574bool
1575rename_table(Session &session,
1577 const identifier::Table &from,
1578 const identifier::Table &to)
1579{
1580 if (not plugin::StorageEngine::doesSchemaExist(to))
1581 {
1582 my_error(ER_NO_DB_ERROR, MYF(0), to.getSchemaName().c_str());
1583 return true;
1584 }
1585
1586 int error= base->renameTable(session, from, to);
1587 if (error == HA_ERR_WRONG_COMMAND)
1588 my_error(ER_NOT_SUPPORTED_YET, MYF(0), "ALTER Table");
1589 else if (error)
1590 {
1591 my_error(ER_ERROR_ON_RENAME, MYF(0),
1592 from.isTmp() ? "#sql-temporary" : from.getSQLPath().c_str(),
1593 to.isTmp() ? "#sql-temporary" : to.getSQLPath().c_str(), error);
1594 }
1595 return error;
1596}
1597
1598
1599/*
1600 Force all other threads to stop using the table
1601
1602 SYNOPSIS
1603 wait_while_table_is_used()
1604 session Thread Cursor
1605 table Table to remove from cache
1606 function HA_EXTRA_PREPARE_FOR_DROP if table is to be deleted
1607 HA_EXTRA_FORCE_REOPEN if table is not be used
1608 HA_EXTRA_PREPARE_FOR_RENAME if table is to be renamed
1609 NOTES
1610 When returning, the table will be unusable for other threads until
1611 the table is closed.
1612
1613 PREREQUISITES
1614 Lock on table::Cache::mutex()
1615 Win32 clients must also have a WRITE LOCK on the table !
1616*/
1617
1618void wait_while_table_is_used(Session *session, Table *table,
1619 enum ha_extra_function function)
1620{
1621
1622 safe_mutex_assert_owner(table::Cache::mutex().native_handle());
1623
1624 table->cursor->extra(function);
1625 /* Mark all tables that are in use as 'old' */
1626 session->abortLock(table); /* end threads waiting on lock */
1627
1628 /* Wait until all there are no other threads that has this table open */
1629 identifier::Table identifier(session->catalog().identifier(),table->getShare()->getSchemaName(), table->getShare()->getTableName());
1630 table::Cache::removeTable(*session, identifier, RTFC_WAIT_OTHER_THREAD_FLAG);
1631}
1632
1633/*
1634 Close a cached table
1635
1636 SYNOPSIS
1637 close_cached_table()
1638 session Thread Cursor
1639 table Table to remove from cache
1640
1641 NOTES
1642 Function ends by signaling threads waiting for the table to try to
1643 reopen the table.
1644
1645 PREREQUISITES
1646 Lock on table::Cache::mutex()
1647 Win32 clients must also have a WRITE LOCK on the table !
1648*/
1649
1650void Session::close_cached_table(Table *table)
1651{
1652
1653 wait_while_table_is_used(this, table, HA_EXTRA_FORCE_REOPEN);
1654 /* Close lock if this is not got with LOCK TABLES */
1655 if (open_tables.lock)
1656 {
1657 unlockTables(open_tables.lock);
1658 open_tables.lock= NULL; // Start locked threads
1659 }
1660 /* Close all copies of 'table'. This also frees all LOCK TABLES lock */
1661 unlink_open_table(table);
1662
1663 /* When lock on table::Cache::mutex() is freed other threads can continue */
1665}
1666
1667/*
1668 RETURN VALUES
1669 false Message sent to net (admin operation went ok)
1670 true Message should be sent by caller
1671 (admin operation or network communication failed)
1672*/
1673static bool admin_table(Session* session, TableList* tables,
1674 const char *operator_name,
1675 thr_lock_type lock_type,
1676 bool open_for_modify,
1677 int (Cursor::*operator_func)(Session*))
1678{
1679 TableList *table;
1680 Select_Lex *select= &session->lex().select_lex;
1681 List<Item> field_list;
1682 Item *item;
1683 int result_code= 0;
1684 const charset_info_st * const cs= system_charset_info;
1685
1686 if (! session->endActiveTransaction())
1687 return 1;
1688
1689 field_list.push_back(item = new Item_empty_string("Table", NAME_CHAR_LEN * 2, cs));
1690 item->maybe_null = 1;
1691 field_list.push_back(item = new Item_empty_string("Op", 10, cs));
1692 item->maybe_null = 1;
1693 field_list.push_back(item = new Item_empty_string("Msg_type", 10, cs));
1694 item->maybe_null = 1;
1695 field_list.push_back(item = new Item_empty_string("Msg_text", 255, cs));
1696 item->maybe_null = 1;
1697 session->getClient()->sendFields(field_list);
1698
1699 for (table= tables; table; table= table->next_local)
1700 {
1701 identifier::Table table_identifier(session->catalog().identifier(), table->getSchemaName(), table->getTableName());
1702 bool fatal_error=0;
1703
1704 std::string table_name = table_identifier.getSQLPath();
1705
1706 table->lock_type= lock_type;
1707 /* open only one table from local list of command */
1708 {
1709 TableList *save_next_global, *save_next_local;
1710 save_next_global= table->next_global;
1711 table->next_global= 0;
1712 save_next_local= table->next_local;
1713 table->next_local= 0;
1714 select->table_list.first= (unsigned char*)table;
1715 /*
1716 Time zone tables and SP tables can be add to lex->query_tables list,
1717 so it have to be prepared.
1718 @todo Investigate if we can put extra tables into argument instead of using lex->query_tables
1719 */
1720 session->lex().query_tables= table;
1721 session->lex().query_tables_last= &table->next_global;
1722 session->lex().query_tables_own_last= 0;
1723 session->no_warnings_for_error= 0;
1724
1725 session->openTablesLock(table);
1726 session->no_warnings_for_error= 0;
1727 table->next_global= save_next_global;
1728 table->next_local= save_next_local;
1729 }
1730
1731 /*
1732 CHECK Table command is only command where VIEW allowed here and this
1733 command use only temporary teble method for VIEWs resolving => there
1734 can't be VIEW tree substitition of join view => if opening table
1735 succeed then table->table will have real Table pointer as value (in
1736 case of join view substitution table->table can be 0, but here it is
1737 impossible)
1738 */
1739 if (!table->table)
1740 {
1741 if (!session->main_da().m_warn_list.size())
1742 push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_ERROR,
1743 ER_CHECK_NO_SUCH_TABLE, ER(ER_CHECK_NO_SUCH_TABLE));
1744 result_code= HA_ADMIN_CORRUPT;
1745 goto send_result;
1746 }
1747
1748 if ((table->table->db_stat & HA_READ_ONLY) && open_for_modify)
1749 {
1750 char buff[FN_REFLEN + DRIZZLE_ERRMSG_SIZE];
1751 uint32_t length;
1752 session->getClient()->store(table_name.c_str());
1753 session->getClient()->store(operator_name);
1754 session->getClient()->store(STRING_WITH_LEN("error"));
1755 length= snprintf(buff, sizeof(buff), ER(ER_OPEN_AS_READONLY),
1756 table_name.c_str());
1757 session->getClient()->store(buff, length);
1759 session->endTransaction(COMMIT);
1760 session->close_thread_tables();
1761 session->lex().reset_query_tables_list(false);
1762 table->table=0; // For query cache
1763 if (session->getClient()->flush())
1764 goto err;
1765 continue;
1766 }
1767
1768 /* Close all instances of the table to allow repair to rename files */
1769 if (lock_type == TL_WRITE && table->table->getShare()->getVersion())
1770 {
1771 table::Cache::mutex().lock(); /* Lock type is TL_WRITE and we lock to repair the table */
1772 const char *old_message=session->enter_cond(COND_refresh, table::Cache::mutex(),
1773 "Waiting to get writelock");
1774 session->abortLock(table->table);
1775 identifier::Table identifier(session->catalog().identifier(),table->table->getShare()->getSchemaName(), table->table->getShare()->getTableName());
1776 table::Cache::removeTable(*session, identifier, RTFC_WAIT_OTHER_THREAD_FLAG | RTFC_CHECK_KILLED_FLAG);
1777 session->exit_cond(old_message);
1778 if (session->getKilled())
1779 goto err;
1780 open_for_modify= 0;
1781 }
1782
1783 result_code = (table->table->cursor->*operator_func)(session);
1784
1785send_result:
1786
1787 session->lex().cleanup_after_one_table_open();
1788 session->clear_error(); // these errors shouldn't get client
1789 {
1790 for (DRIZZLE_ERROR* err : session->main_da().m_warn_list)
1791 {
1792 session->getClient()->store(table_name.c_str());
1793 session->getClient()->store(operator_name);
1794 session->getClient()->store(warning_level_names[err->level].data(), warning_level_names[err->level].size());
1795 session->getClient()->store(err->msg);
1796 if (session->getClient()->flush())
1797 goto err;
1798 }
1799 drizzle_reset_errors(*session, true);
1800 }
1801 session->getClient()->store(table_name.c_str());
1802 session->getClient()->store(operator_name);
1803
1804 switch (result_code) {
1805 case HA_ADMIN_NOT_IMPLEMENTED:
1806 {
1807 char buf[ERRMSGSIZE+20];
1808 uint32_t length=snprintf(buf, ERRMSGSIZE,
1809 ER(ER_CHECK_NOT_IMPLEMENTED), operator_name);
1810 session->getClient()->store(STRING_WITH_LEN("note"));
1811 session->getClient()->store(buf, length);
1812 }
1813 break;
1814
1815 case HA_ADMIN_OK:
1816 session->getClient()->store(STRING_WITH_LEN("status"));
1817 session->getClient()->store(STRING_WITH_LEN("OK"));
1818 break;
1819
1820 case HA_ADMIN_FAILED:
1821 session->getClient()->store(STRING_WITH_LEN("status"));
1822 session->getClient()->store(STRING_WITH_LEN("Operation failed"));
1823 break;
1824
1825 case HA_ADMIN_REJECT:
1826 session->getClient()->store(STRING_WITH_LEN("status"));
1827 session->getClient()->store(STRING_WITH_LEN("Operation need committed state"));
1828 open_for_modify= false;
1829 break;
1830
1831 case HA_ADMIN_ALREADY_DONE:
1832 session->getClient()->store(STRING_WITH_LEN("status"));
1833 session->getClient()->store(STRING_WITH_LEN("Table is already up to date"));
1834 break;
1835
1836 case HA_ADMIN_CORRUPT:
1837 session->getClient()->store(STRING_WITH_LEN("error"));
1838 session->getClient()->store(STRING_WITH_LEN("Corrupt"));
1839 fatal_error=1;
1840 break;
1841
1842 case HA_ADMIN_INVALID:
1843 session->getClient()->store(STRING_WITH_LEN("error"));
1844 session->getClient()->store(STRING_WITH_LEN("Invalid argument"));
1845 break;
1846
1847 default: // Probably HA_ADMIN_INTERNAL_ERROR
1848 {
1849 char buf[ERRMSGSIZE+20];
1850 uint32_t length=snprintf(buf, ERRMSGSIZE,
1851 _("Unknown - internal error %d during operation"),
1852 result_code);
1853 session->getClient()->store(STRING_WITH_LEN("error"));
1854 session->getClient()->store(buf, length);
1855 fatal_error=1;
1856 break;
1857 }
1858 }
1859 if (table->table)
1860 {
1861 if (fatal_error)
1862 {
1863 table->table->getMutableShare()->resetVersion(); // Force close of table
1864 }
1865 else if (open_for_modify)
1866 {
1867 if (table->table->getShare()->getType())
1868 {
1869 table->table->cursor->info(HA_STATUS_CONST);
1870 }
1871 else
1872 {
1873 boost::unique_lock<boost::mutex> lock(table::Cache::mutex());
1874 identifier::Table identifier(session->catalog().identifier(),
1875 table->table->getShare()->getSchemaName(),
1876 table->table->getShare()->getTableName());
1877 table::Cache::removeTable(*session, identifier, RTFC_NO_FLAG);
1878 }
1879 }
1880 }
1882 session->endTransaction(COMMIT);
1883 session->close_thread_tables();
1884 table->table=0; // For query cache
1885 if (session->getClient()->flush())
1886 goto err;
1887 }
1888
1889 session->my_eof();
1890 return false;
1891
1892err:
1894 session->endTransaction(ROLLBACK);
1895 session->close_thread_tables(); // Shouldn't be needed
1896 if (table)
1897 table->table=0;
1898 return true;
1899}
1900
1901 /*
1902 Create a new table by copying from source table
1903
1904 Altough exclusive name-lock on target table protects us from concurrent
1905 DML and DDL operations on it we still want to wrap .FRM creation and call
1906 to plugin::StorageEngine::createTable() in critical section protected by
1907 table::Cache::mutex() in order to provide minimal atomicity against operations which
1908 disregard name-locks, like I_S implementation, for example. This is a
1909 temporary and should not be copied. Instead we should fix our code to
1910 always honor name-locks.
1911
1912 Also some engines (e.g. NDB cluster) require that table::Cache::mutex() should be held
1913 during the call to plugin::StorageEngine::createTable().
1914 See bug #28614 for more info.
1915 */
1916static bool create_table_wrapper(Session &session,
1917 const message::Table& create_table_proto,
1918 const identifier::Table& destination_identifier,
1919 const identifier::Table& source_identifier,
1920 bool is_engine_set)
1921{
1922 // We require an additional table message because during parsing we used
1923 // a "new" message and it will not have all of the information that the
1924 // source table message would have.
1925 message::Table new_table_message;
1926
1927 message::table::shared_ptr source_table_message= plugin::StorageEngine::getTableMessage(session, source_identifier);
1928
1929 if (not source_table_message)
1930 {
1931 my_error(ER_TABLE_UNKNOWN, source_identifier);
1932 return false;
1933 }
1934
1935 new_table_message.CopyFrom(*source_table_message);
1936 new_table_message.set_type(destination_identifier.isTmp() ? message::Table::TEMPORARY : message::Table::STANDARD);
1937
1938 if (is_engine_set)
1939 {
1940 new_table_message.mutable_engine()->set_name(create_table_proto.engine().name());
1941 }
1942
1943 { // We now do a selective copy of elements on to the new table.
1944 new_table_message.set_name(create_table_proto.name());
1945 new_table_message.set_schema(create_table_proto.schema());
1946 new_table_message.set_catalog(create_table_proto.catalog());
1947 }
1948
1949 /* Fix names of foreign keys being added */
1950 for (int32_t j= 0; j < new_table_message.fk_constraint_size(); j++)
1951 {
1952 if (new_table_message.fk_constraint(j).has_name())
1953 {
1954 std::string name(new_table_message.name());
1955 char number[20];
1956
1957 name.append("_ibfk_");
1958 snprintf(number, sizeof(number), "%d", j+1);
1959 name.append(number);
1960
1961 message::Table::ForeignKeyConstraint *pfkey= new_table_message.mutable_fk_constraint(j);
1962 pfkey->set_name(name);
1963 }
1964 }
1965
1966 /*
1967 As mysql_truncate don't work on a new table at this stage of
1968 creation, instead create the table directly (for both normal and temporary tables).
1969 */
1970 bool success= plugin::StorageEngine::createTable(session, destination_identifier, new_table_message);
1971
1972 if (success && not destination_identifier.isTmp())
1973 {
1974 TransactionServices::createTable(session, new_table_message);
1975 }
1976
1977 return success;
1978}
1979
1980/*
1981 Create a table identical to the specified table
1982
1983 SYNOPSIS
1984 create_like_table()
1985 session Thread object
1986 table Table list element for target table
1987 src_table Table list element for source table
1988 create_info Create info
1989
1990 RETURN VALUES
1991 false OK
1992 true error
1993*/
1994
1995bool create_like_table(Session* session,
1996 const identifier::Table& destination_identifier,
1997 const identifier::Table& source_identifier,
1998 message::Table &create_table_proto,
1999 bool is_if_not_exists,
2000 bool is_engine_set)
2001{
2002 bool res= true;
2003 bool table_exists= false;
2004
2005 /*
2006 Check that destination tables does not exist. Note that its name
2007 was already checked when it was added to the table list.
2008
2009 For temporary tables we don't aim to grab locks.
2010 */
2011 if (destination_identifier.isTmp())
2012 {
2013 if (session->open_tables.find_temporary_table(destination_identifier))
2014 {
2015 table_exists= true;
2016 }
2017 else
2018 {
2019 bool was_created= create_table_wrapper(*session,
2020 create_table_proto,
2021 destination_identifier,
2022 source_identifier,
2023 is_engine_set);
2024 if (not was_created) // This is pretty paranoid, but we assume something might not clean up after itself
2025 {
2026 (void) session->open_tables.rm_temporary_table(destination_identifier, true);
2027 }
2028 else if (not session->open_temporary_table(destination_identifier))
2029 {
2030 // We created, but we can't open... also, a hack.
2031 (void) session->open_tables.rm_temporary_table(destination_identifier, true);
2032 }
2033 else
2034 {
2035 res= false;
2036 }
2037 }
2038 }
2039 else // Standard table which will require locks.
2040 {
2041 Table *name_lock= session->lock_table_name_if_not_cached(destination_identifier);
2042 if (not name_lock)
2043 {
2044 table_exists= true;
2045 }
2046 else if (plugin::StorageEngine::doesTableExist(*session, destination_identifier))
2047 {
2048 table_exists= true;
2049 }
2050 else // Otherwise we create the table
2051 {
2052 bool was_created;
2053 {
2054 boost::mutex::scoped_lock lock(table::Cache::mutex()); /* We lock for CREATE TABLE LIKE to copy table definition */
2055 was_created= create_table_wrapper(*session, create_table_proto, destination_identifier,
2056 source_identifier, is_engine_set);
2057 }
2058
2059 // So we blew the creation of the table, and we scramble to clean up
2060 // anything that might have been created (read... it is a hack)
2061 if (not was_created)
2062 {
2063 plugin::StorageEngine::dropTable(*session, destination_identifier);
2064 }
2065 else
2066 {
2067 res= false;
2068 }
2069 }
2070
2071 if (name_lock)
2072 {
2073 boost::mutex::scoped_lock lock(table::Cache::mutex()); /* unlink open tables for create table like*/
2074 session->unlink_open_table(name_lock);
2075 }
2076 }
2077
2078 if (table_exists)
2079 {
2080 if (is_if_not_exists)
2081 {
2082 char warn_buff[DRIZZLE_ERRMSG_SIZE];
2083 snprintf(warn_buff, sizeof(warn_buff),
2084 ER(ER_TABLE_EXISTS_ERROR), destination_identifier.getTableName().c_str());
2085 push_warning(session, DRIZZLE_ERROR::WARN_LEVEL_NOTE,
2086 ER_TABLE_EXISTS_ERROR, warn_buff);
2087 return false;
2088 }
2089
2090 my_error(ER_TABLE_EXISTS_ERROR, destination_identifier);
2091
2092 return true;
2093 }
2094
2095 return res;
2096}
2097
2098
2099bool analyze_table(Session* session, TableList* tables)
2100{
2101 return admin_table(session, tables, "analyze", TL_READ_NO_INSERT, true, &Cursor::ha_analyze);
2102}
2103
2104
2105bool check_table(Session* session, TableList* tables)
2106{
2107 return admin_table(session, tables, "check", TL_READ_NO_INSERT, false, &Cursor::ha_check);
2108}
2109
2110} /* namespace drizzled */
const char * field_name
enum_field_types sql_type
const charset_info_st * charset
void create_length_to_internal_length(void)
int ha_analyze(Session *)
static bool type_can_have_key_part(enum_field_types)
Definition field.cc:859
virtual String * val_str(String *str)=0
void unlink_open_table(Table *find)
Definition sql_base.cc:583
TableList * next_global
Definition table_list.h:110
TableList * next_local
Definition table_list.h:107
Select_Lex * select_lex
Definition table_list.h:208
static void createTable(Session &, const message::Table &)
static int autocommitOrRollback(Session &, int error)
static void dropTable(Session &, const identifier::Table &identifier, message::table::const_reference table, bool if_exists)
static bool doesTableExist(Session &session, const drizzled::identifier::Table &identifier, bool include_temporary_tables=true)
static bool createTable(Session &session, const identifier::Table &identifier, message::Table &table_message)
#define KEY_DEFAULT_PACK_LENGTH
void broadcast_refresh(void)
Definition global.cc:1115
Convert from decimal to binary representation.
Definition common_fwd.h:215
TODO: Rename this file - func.h is stupid.
static bool drizzle_create_table(Session *session, const identifier::Table &identifier, HA_CREATE_INFO *create_info, message::Table &table_proto, AlterInfo *alter_info, bool internal_tmp_table, uint32_t select_field_count, bool is_if_not_exists)
int(* qsort_cmp)(const void *, const void *)
Definition qsort_cmp.h:26
static int prepare_create_table(Session *session, HA_CREATE_INFO *create_info, message::Table &create_proto, AlterInfo *alter_info, bool tmp_table, uint32_t *db_options, KeyInfo **key_info_buffer, uint32_t *key_count, int select_field_count)
Definition sql_table.cc:508
STL namespace.