MySQL 5.6.14 Source Code Document
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
table.cc
1 /*
2  Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
3 
4  This program is free software; you can redistribute it and/or modify
5  it under the terms of the GNU General Public License as published by
6  the Free Software Foundation; version 2 of the License.
7 
8  This program is distributed in the hope that it will be useful,
9  but WITHOUT ANY WARRANTY; without even the implied warranty of
10  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11  GNU General Public License for more details.
12 
13  You should have received a copy of the GNU General Public License
14  along with this program; if not, write to the Free Software
15  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
16 
17 /* Some general useful functions */
18 
19 #include "my_global.h" /* NO_EMBEDDED_ACCESS_CHECKS */
20 #include "sql_priv.h"
21 #include "unireg.h" // REQUIRED: for other includes
22 #include "table.h"
23 #include "frm_crypt.h" // get_crypt_for_frm
24 #include "key.h" // find_ref_key
25 #include "sql_table.h" // build_table_filename,
26  // primary_key_name
27 #include "sql_trigger.h"
28 #include "sql_parse.h" // free_items
29 #include "strfunc.h" // unhex_type2
30 #include "sql_partition.h" // mysql_unpack_partition,
31  // fix_partition_func, partition_info
32 #include "sql_acl.h" // *_ACL, acl_getroot_no_password
33 #include "sql_base.h" // release_table_share
34 #include "sql_derived.h"
35 #include <m_ctype.h>
36 #include "my_md5.h"
37 #include "my_bit.h"
38 #include "sql_select.h"
39 #include "mdl.h" // MDL_wait_for_graph_visitor
40 #include "opt_trace.h" // opt_trace_disable_if_no_security_...
41 #include "table_cache.h" // table_cache_manager
42 #include "sql_view.h"
43 
44 /* INFORMATION_SCHEMA name */
45 LEX_STRING INFORMATION_SCHEMA_NAME= {C_STRING_WITH_LEN("information_schema")};
46 
47 /* PERFORMANCE_SCHEMA name */
48 LEX_STRING PERFORMANCE_SCHEMA_DB_NAME= {C_STRING_WITH_LEN("performance_schema")};
49 
50 /* MYSQL_SCHEMA name */
51 LEX_STRING MYSQL_SCHEMA_NAME= {C_STRING_WITH_LEN("mysql")};
52 
53 /* GENERAL_LOG name */
54 LEX_STRING GENERAL_LOG_NAME= {C_STRING_WITH_LEN("general_log")};
55 
56 /* SLOW_LOG name */
57 LEX_STRING SLOW_LOG_NAME= {C_STRING_WITH_LEN("slow_log")};
58 
59 /* RLI_INFO name */
60 LEX_STRING RLI_INFO_NAME= {C_STRING_WITH_LEN("slave_relay_log_info")};
61 
62 /* MI_INFO name */
63 LEX_STRING MI_INFO_NAME= {C_STRING_WITH_LEN("slave_master_info")};
64 
65 /* WORKER_INFO name */
66 LEX_STRING WORKER_INFO_NAME= {C_STRING_WITH_LEN("slave_worker_info")};
67 
68  /* Functions defined in this file */
69 
70 void open_table_error(TABLE_SHARE *share, int error, int db_errno,
71  myf errortype, int errarg);
72 static int open_binary_frm(THD *thd, TABLE_SHARE *share,
73  uchar *head, File file);
74 static void fix_type_pointers(const char ***array, TYPELIB *point_to_type,
75  uint types, char **names);
76 static uint find_field(Field **fields, uchar *record, uint start, uint length);
77 
78 static Item *create_view_field(THD *thd, TABLE_LIST *view, Item **field_ref,
79  const char *name,
80  Name_resolution_context *context);
81 
82 inline bool is_system_table_name(const char *name, uint length);
83 
84 static ulong get_form_pos(File file, uchar *head);
85 
86 /**************************************************************************
87  Object_creation_ctx implementation.
88 **************************************************************************/
89 
90 Object_creation_ctx *Object_creation_ctx::set_n_backup(THD *thd)
91 {
92  Object_creation_ctx *backup_ctx;
93  DBUG_ENTER("Object_creation_ctx::set_n_backup");
94 
95  backup_ctx= create_backup_ctx(thd);
96  change_env(thd);
97 
98  DBUG_RETURN(backup_ctx);
99 }
100 
101 void Object_creation_ctx::restore_env(THD *thd, Object_creation_ctx *backup_ctx)
102 {
103  if (!backup_ctx)
104  return;
105 
106  backup_ctx->change_env(thd);
107 
108  delete backup_ctx;
109 }
110 
111 /**************************************************************************
112  Default_object_creation_ctx implementation.
113 **************************************************************************/
114 
115 Default_object_creation_ctx::Default_object_creation_ctx(THD *thd)
116  : m_client_cs(thd->variables.character_set_client),
117  m_connection_cl(thd->variables.collation_connection)
118 { }
119 
120 Default_object_creation_ctx::Default_object_creation_ctx(
121  const CHARSET_INFO *client_cs, const CHARSET_INFO *connection_cl)
122  : m_client_cs(client_cs),
123  m_connection_cl(connection_cl)
124 { }
125 
127 Default_object_creation_ctx::create_backup_ctx(THD *thd) const
128 {
129  return new Default_object_creation_ctx(thd);
130 }
131 
132 void Default_object_creation_ctx::change_env(THD *thd) const
133 {
134  thd->variables.character_set_client= m_client_cs;
135  thd->variables.collation_connection= m_connection_cl;
136 
137  thd->update_charset();
138 }
139 
140 /**************************************************************************
141  View_creation_ctx implementation.
142 **************************************************************************/
143 
144 View_creation_ctx *View_creation_ctx::create(THD *thd)
145 {
146  View_creation_ctx *ctx= new (thd->mem_root) View_creation_ctx(thd);
147 
148  return ctx;
149 }
150 
151 /*************************************************************************/
152 
153 View_creation_ctx * View_creation_ctx::create(THD *thd,
154  TABLE_LIST *view)
155 {
156  View_creation_ctx *ctx= new (thd->mem_root) View_creation_ctx(thd);
157 
158  /* Throw a warning if there is NULL cs name. */
159 
160  if (!view->view_client_cs_name.str ||
161  !view->view_connection_cl_name.str)
162  {
163  push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE,
164  ER_VIEW_NO_CREATION_CTX,
165  ER(ER_VIEW_NO_CREATION_CTX),
166  (const char *) view->db,
167  (const char *) view->table_name);
168 
169  ctx->m_client_cs= system_charset_info;
170  ctx->m_connection_cl= system_charset_info;
171 
172  return ctx;
173  }
174 
175  /* Resolve cs names. Throw a warning if there is unknown cs name. */
176 
177  bool invalid_creation_ctx;
178 
179  invalid_creation_ctx= resolve_charset(view->view_client_cs_name.str,
180  system_charset_info,
181  &ctx->m_client_cs);
182 
183  invalid_creation_ctx= resolve_collation(view->view_connection_cl_name.str,
184  system_charset_info,
185  &ctx->m_connection_cl) ||
186  invalid_creation_ctx;
187 
188  if (invalid_creation_ctx)
189  {
190  sql_print_warning("View '%s'.'%s': there is unknown charset/collation "
191  "names (client: '%s'; connection: '%s').",
192  (const char *) view->db,
193  (const char *) view->table_name,
194  (const char *) view->view_client_cs_name.str,
195  (const char *) view->view_connection_cl_name.str);
196 
197  push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE,
198  ER_VIEW_INVALID_CREATION_CTX,
199  ER(ER_VIEW_INVALID_CREATION_CTX),
200  (const char *) view->db,
201  (const char *) view->table_name);
202  }
203 
204  return ctx;
205 }
206 
207 /*************************************************************************/
208 
209 /* Get column name from column hash */
210 
211 static uchar *get_field_name(Field **buff, size_t *length,
212  my_bool not_used __attribute__((unused)))
213 {
214  *length= (uint) strlen((*buff)->field_name);
215  return (uchar*) (*buff)->field_name;
216 }
217 
218 
219 /*
220  Returns pointer to '.frm' extension of the file name.
221 
222  SYNOPSIS
223  fn_rext()
224  name file name
225 
226  DESCRIPTION
227  Checks file name part starting with the rightmost '.' character,
228  and returns it if it is equal to '.frm'.
229 
230  TODO
231  It is a good idea to get rid of this function modifying the code
232  to garantee that the functions presently calling fn_rext() always
233  get arguments in the same format: either with '.frm' or without '.frm'.
234 
235  RETURN VALUES
236  Pointer to the '.frm' extension. If there is no extension,
237  or extension is not '.frm', pointer at the end of file name.
238 */
239 
240 char *fn_rext(char *name)
241 {
242  char *res= strrchr(name, '.');
243  if (res && !strcmp(res, reg_ext))
244  return res;
245  return name + strlen(name);
246 }
247 
248 TABLE_CATEGORY get_table_category(const LEX_STRING *db, const LEX_STRING *name)
249 {
250  DBUG_ASSERT(db != NULL);
251  DBUG_ASSERT(name != NULL);
252 
253  if (is_infoschema_db(db->str, db->length))
254  return TABLE_CATEGORY_INFORMATION;
255 
256  if ((db->length == PERFORMANCE_SCHEMA_DB_NAME.length) &&
257  (my_strcasecmp(system_charset_info,
258  PERFORMANCE_SCHEMA_DB_NAME.str,
259  db->str) == 0))
260  return TABLE_CATEGORY_PERFORMANCE;
261 
262  if ((db->length == MYSQL_SCHEMA_NAME.length) &&
263  (my_strcasecmp(system_charset_info,
264  MYSQL_SCHEMA_NAME.str,
265  db->str) == 0))
266  {
267  if (is_system_table_name(name->str, name->length))
268  return TABLE_CATEGORY_SYSTEM;
269 
270  if ((name->length == GENERAL_LOG_NAME.length) &&
271  (my_strcasecmp(system_charset_info,
272  GENERAL_LOG_NAME.str,
273  name->str) == 0))
274  return TABLE_CATEGORY_LOG;
275 
276  if ((name->length == SLOW_LOG_NAME.length) &&
277  (my_strcasecmp(system_charset_info,
278  SLOW_LOG_NAME.str,
279  name->str) == 0))
280  return TABLE_CATEGORY_LOG;
281 
282  if ((name->length == RLI_INFO_NAME.length) &&
283  (my_strcasecmp(system_charset_info,
284  RLI_INFO_NAME.str,
285  name->str) == 0))
286  return TABLE_CATEGORY_RPL_INFO;
287 
288  if ((name->length == MI_INFO_NAME.length) &&
289  (my_strcasecmp(system_charset_info,
290  MI_INFO_NAME.str,
291  name->str) == 0))
292  return TABLE_CATEGORY_RPL_INFO;
293 
294  if ((name->length == WORKER_INFO_NAME.length) &&
295  (my_strcasecmp(system_charset_info,
296  WORKER_INFO_NAME.str,
297  name->str) == 0))
298  return TABLE_CATEGORY_RPL_INFO;
299  }
300 
301  return TABLE_CATEGORY_USER;
302 }
303 
304 
305 /*
306  Allocate a setup TABLE_SHARE structure
307 
308  SYNOPSIS
309  alloc_table_share()
310  TABLE_LIST Take database and table name from there
311  key Table cache key (db \0 table_name \0...)
312  key_length Length of key
313 
314  RETURN
315  0 Error (out of memory)
316  # Share
317 */
318 
319 TABLE_SHARE *alloc_table_share(TABLE_LIST *table_list, const char *key,
320  uint key_length)
321 {
322  MEM_ROOT mem_root;
323  TABLE_SHARE *share;
324  char *key_buff, *path_buff;
325  char path[FN_REFLEN];
326  uint path_length;
327  Table_cache_element **cache_element_array;
328  DBUG_ENTER("alloc_table_share");
329  DBUG_PRINT("enter", ("table: '%s'.'%s'",
330  table_list->db, table_list->table_name));
331 
332  path_length= build_table_filename(path, sizeof(path) - 1,
333  table_list->db,
334  table_list->table_name, "", 0);
335  init_sql_alloc(&mem_root, TABLE_ALLOC_BLOCK_SIZE, 0);
336  if (multi_alloc_root(&mem_root,
337  &share, sizeof(*share),
338  &key_buff, key_length,
339  &path_buff, path_length + 1,
340  &cache_element_array,
341  table_cache_instances * sizeof(*cache_element_array),
342  NULL))
343  {
344  memset(share, 0, sizeof(*share));
345 
346  share->set_table_cache_key(key_buff, key, key_length);
347 
348  share->path.str= path_buff;
349  share->path.length= path_length;
350  strmov(share->path.str, path);
351  share->normalized_path.str= share->path.str;
352  share->normalized_path.length= path_length;
353 
354  share->version= refresh_version;
355 
356  /*
357  Since alloc_table_share() can be called without any locking (for
358  example, ha_create_table... functions), we do not assign a table
359  map id here. Instead we assign a value that is not used
360  elsewhere, and then assign a table map id inside open_table()
361  under the protection of the LOCK_open mutex.
362  */
363  share->table_map_id= ~0ULL;
364  share->cached_row_logging_check= -1;
365 
366  share->m_flush_tickets.empty();
367 
368  memset(cache_element_array, 0,
369  table_cache_instances * sizeof(*cache_element_array));
370  share->cache_element= cache_element_array;
371 
372  memcpy((char*) &share->mem_root, (char*) &mem_root, sizeof(mem_root));
373  mysql_mutex_init(key_TABLE_SHARE_LOCK_ha_data,
374  &share->LOCK_ha_data, MY_MUTEX_INIT_FAST);
375  }
376  DBUG_RETURN(share);
377 }
378 
379 
380 /*
381  Initialize share for temporary tables
382 
383  SYNOPSIS
384  init_tmp_table_share()
385  thd thread handle
386  share Share to fill
387  key Table_cache_key, as generated from create_table_def_key.
388  must start with db name.
389  key_length Length of key
390  table_name Table name
391  path Path to file (possible in lower case) without .frm
392 
393  NOTES
394  This is different from alloc_table_share() because temporary tables
395  don't have to be shared between threads or put into the table def
396  cache, so we can do some things notable simpler and faster
397 
398  If table is not put in thd->temporary_tables (happens only when
399  one uses OPEN TEMPORARY) then one can specify 'db' as key and
400  use key_length= 0 as neither table_cache_key or key_length will be used).
401 */
402 
403 void init_tmp_table_share(THD *thd, TABLE_SHARE *share, const char *key,
404  uint key_length, const char *table_name,
405  const char *path)
406 {
407  DBUG_ENTER("init_tmp_table_share");
408  DBUG_PRINT("enter", ("table: '%s'.'%s'", key, table_name));
409 
410  memset(share, 0, sizeof(*share));
411  init_sql_alloc(&share->mem_root, TABLE_ALLOC_BLOCK_SIZE, 0);
412  share->table_category= TABLE_CATEGORY_TEMPORARY;
413  share->tmp_table= INTERNAL_TMP_TABLE;
414  share->db.str= (char*) key;
415  share->db.length= strlen(key);
416  share->table_cache_key.str= (char*) key;
417  share->table_cache_key.length= key_length;
418  share->table_name.str= (char*) table_name;
419  share->table_name.length= strlen(table_name);
420  share->path.str= (char*) path;
421  share->normalized_path.str= (char*) path;
422  share->path.length= share->normalized_path.length= strlen(path);
423  share->frm_version= FRM_VER_TRUE_VARCHAR;
424 
425  share->cached_row_logging_check= -1;
426 
427  /*
428  table_map_id is also used for MERGE tables to suppress repeated
429  compatibility checks.
430  */
431  share->table_map_id= (ulonglong) thd->query_id;
432 
433  share->m_flush_tickets.empty();
434 
435  DBUG_VOID_RETURN;
436 }
437 
438 
446 {
447  uint idx;
448  KEY *info_it;
449 
450  DBUG_ENTER("TABLE_SHARE::destroy");
451  DBUG_PRINT("info", ("db: %s table: %s", db.str, table_name.str));
452  if (ha_share)
453  {
454  delete ha_share;
455  ha_share= NULL;
456  }
457  /* The mutex is initialized only for shares that are part of the TDC */
458  if (tmp_table == NO_TMP_TABLE)
459  mysql_mutex_destroy(&LOCK_ha_data);
460  my_hash_free(&name_hash);
461 
462  plugin_unlock(NULL, db_plugin);
463  db_plugin= NULL;
464 
465  /* Release fulltext parsers */
466  info_it= key_info;
467  for (idx= keys; idx; idx--, info_it++)
468  {
469  if (info_it->flags & HA_USES_PARSER)
470  {
471  plugin_unlock(NULL, info_it->parser);
472  info_it->flags= 0;
473  }
474  }
475 
476 #ifdef HAVE_PSI_TABLE_INTERFACE
477  PSI_TABLE_CALL(release_table_share)(m_psi);
478 #endif
479 
480  /*
481  Make a copy since the share is allocated in its own root,
482  and free_root() updates its argument after freeing the memory.
483  */
484  MEM_ROOT own_root= mem_root;
485  free_root(&own_root, MYF(0));
486  DBUG_VOID_RETURN;
487 }
488 
489 /*
490  Free table share and memory used by it
491 
492  SYNOPSIS
493  free_table_share()
494  share Table share
495 */
496 
497 void free_table_share(TABLE_SHARE *share)
498 {
499  DBUG_ENTER("free_table_share");
500  DBUG_PRINT("enter", ("table: %s.%s", share->db.str, share->table_name.str));
501  DBUG_ASSERT(share->ref_count == 0);
502 
503  if (share->m_flush_tickets.is_empty())
504  {
505  /*
506  No threads are waiting for this share to be flushed (the
507  share is not old, is for a temporary table, or just nobody
508  happens to be waiting for it). Destroy it.
509  */
510  share->destroy();
511  }
512  else
513  {
515  Wait_for_flush *ticket;
516  /*
517  We're about to iterate over a list that is used
518  concurrently. Make sure this never happens without a lock.
519  */
521 
522  while ((ticket= it++))
523  (void) ticket->get_ctx()->m_wait.set_status(MDL_wait::GRANTED);
524  /*
525  If there are threads waiting for this share to be flushed,
526  the last one to receive the notification will destroy the
527  share. At this point the share is removed from the table
528  definition cache, so is OK to proceed here without waiting
529  for this thread to do the work.
530  */
531  }
532  DBUG_VOID_RETURN;
533 }
534 
535 
550 inline bool is_system_table_name(const char *name, uint length)
551 {
552  CHARSET_INFO *ci= system_charset_info;
553 
554  return (
555  /* mysql.proc table */
556  (length == 4 &&
557  my_tolower(ci, name[0]) == 'p' &&
558  my_tolower(ci, name[1]) == 'r' &&
559  my_tolower(ci, name[2]) == 'o' &&
560  my_tolower(ci, name[3]) == 'c') ||
561 
562  (length > 4 &&
563  (
564  /* one of mysql.help* tables */
565  (my_tolower(ci, name[0]) == 'h' &&
566  my_tolower(ci, name[1]) == 'e' &&
567  my_tolower(ci, name[2]) == 'l' &&
568  my_tolower(ci, name[3]) == 'p') ||
569 
570  /* one of mysql.time_zone* tables */
571  (my_tolower(ci, name[0]) == 't' &&
572  my_tolower(ci, name[1]) == 'i' &&
573  my_tolower(ci, name[2]) == 'm' &&
574  my_tolower(ci, name[3]) == 'e') ||
575 
576  /* mysql.event table */
577  (my_tolower(ci, name[0]) == 'e' &&
578  my_tolower(ci, name[1]) == 'v' &&
579  my_tolower(ci, name[2]) == 'e' &&
580  my_tolower(ci, name[3]) == 'n' &&
581  my_tolower(ci, name[4]) == 't')
582  )
583  )
584  );
585 }
586 
587 
592 static inline bool has_disabled_path_chars(const char *str)
593 {
594  for (; *str; str++)
595  switch (*str)
596  {
597  case FN_EXTCHAR:
598  case '/':
599  case '\\':
600  case '~':
601  case '@':
602  return TRUE;
603  }
604  return FALSE;
605 }
606 
607 
608 /*
609  Read table definition from a binary / text based .frm file
610 
611  SYNOPSIS
612  open_table_def()
613  thd Thread handler
614  share Fill this with table definition
615  db_flags Bit mask of the following flags: OPEN_VIEW
616 
617  NOTES
618  This function is called when the table definition is not cached in
619  table_def_cache
620  The data is returned in 'share', which is alloced by
621  alloc_table_share().. The code assumes that share is initialized.
622 
623  RETURN VALUES
624  0 ok
625  1 Error (see open_table_error)
626  2 Error (see open_table_error)
627  3 Wrong data in .frm file
628  4 Error (see open_table_error)
629  5 Error (see open_table_error: charset unavailable)
630  6 Unknown .frm version
631  8 Error while reading view definition from .FRM file.
632  9 Wrong type in view's .frm file.
633 */
634 
635 int open_table_def(THD *thd, TABLE_SHARE *share, uint db_flags)
636 {
637  int error, table_type;
638  bool error_given;
639  File file;
640  uchar head[64];
641  char path[FN_REFLEN];
642  MEM_ROOT **root_ptr, *old_root;
643  DBUG_ENTER("open_table_def");
644  DBUG_PRINT("enter", ("table: '%s'.'%s' path: '%s'", share->db.str,
645  share->table_name.str, share->normalized_path.str));
646 
647  error= 1;
648  error_given= 0;
649 
650  strxmov(path, share->normalized_path.str, reg_ext, NullS);
651  if ((file= mysql_file_open(key_file_frm,
652  path, O_RDONLY | O_SHARE, MYF(0))) < 0)
653  {
654  /*
655  We don't try to open 5.0 unencoded name, if
656  - non-encoded name contains '@' signs,
657  because '@' can be misinterpreted.
658  It is not clear if '@' is escape character in 5.1,
659  or a normal character in 5.0.
660 
661  - non-encoded db or table name contain "#mysql50#" prefix.
662  This kind of tables must have been opened only by the
663  mysql_file_open() above.
664  */
665  if (has_disabled_path_chars(share->table_name.str) ||
666  has_disabled_path_chars(share->db.str) ||
667  !strncmp(share->db.str, MYSQL50_TABLE_NAME_PREFIX,
668  MYSQL50_TABLE_NAME_PREFIX_LENGTH) ||
669  !strncmp(share->table_name.str, MYSQL50_TABLE_NAME_PREFIX,
670  MYSQL50_TABLE_NAME_PREFIX_LENGTH))
671  goto err_not_open;
672 
673  /* Try unencoded 5.0 name */
674  uint length;
675  strxnmov(path, sizeof(path)-1,
676  mysql_data_home, "/", share->db.str, "/",
677  share->table_name.str, reg_ext, NullS);
678  length= unpack_filename(path, path) - reg_ext_length;
679  /*
680  The following is a safety test and should never fail
681  as the old file name should never be longer than the new one.
682  */
683  DBUG_ASSERT(length <= share->normalized_path.length);
684  /*
685  If the old and the new names have the same length,
686  then table name does not have tricky characters,
687  so no need to check the old file name.
688  */
689  if (length == share->normalized_path.length ||
690  ((file= mysql_file_open(key_file_frm,
691  path, O_RDONLY | O_SHARE, MYF(0))) < 0))
692  goto err_not_open;
693 
694  /* Unencoded 5.0 table name found */
695  path[length]= '\0'; // Remove .frm extension
696  strmov(share->normalized_path.str, path);
697  share->normalized_path.length= length;
698  }
699 
700  error= 4;
701  if (mysql_file_read(file, head, 64, MYF(MY_NABP)))
702  goto err;
703 
704  if (head[0] == (uchar) 254 && head[1] == 1)
705  {
706  if (head[2] == FRM_VER || head[2] == FRM_VER+1 ||
707  (head[2] >= FRM_VER+3 && head[2] <= FRM_VER+4))
708  {
709  /* Open view only */
710  if (db_flags & OPEN_VIEW_ONLY)
711  {
712  error_given= 1;
713  goto err;
714  }
715  table_type= 1;
716  }
717  else
718  {
719  error= 6; // Unkown .frm version
720  goto err;
721  }
722  }
723  else if (memcmp(head, STRING_WITH_LEN("TYPE=")) == 0)
724  {
725  error= 5;
726  if (memcmp(head+5, "VIEW", 4) == 0)
727  {
728  share->is_view= 1;
729  if (db_flags & OPEN_VIEW)
730  table_type= 2;
731  else
732  goto err;
733  }
734  else
735  goto err;
736  }
737  else
738  goto err;
739 
740  if (table_type == 1)
741  {
742  root_ptr= my_pthread_getspecific_ptr(MEM_ROOT**, THR_MALLOC);
743  old_root= *root_ptr;
744  *root_ptr= &share->mem_root;
745  error= open_binary_frm(thd, share, head, file);
746  *root_ptr= old_root;
747  error_given= 1;
748  }
749  else if (table_type == 2)
750  {
751  LEX_STRING pathstr= { path, strlen(path) };
752 
753  /*
754  Create view file parser and hold it in TABLE_SHARE member
755  view_def.
756  */
757  share->view_def= sql_parse_prepare(&pathstr, &share->mem_root, true);
758  if (!share->view_def)
759  error= 8;
760  else if (!is_equal(&view_type, share->view_def->type()))
761  error= 9;
762  else
763  error= 0;
764  }
765 
766  share->table_category= get_table_category(& share->db, & share->table_name);
767 
768  if (!error)
769  thd->status_var.opened_shares++;
770 
771 err:
772  mysql_file_close(file, MYF(MY_WME));
773 
774 err_not_open:
775  if (error && !error_given)
776  {
777  share->error= error;
778  open_table_error(share, error, (share->open_errno= my_errno), 0);
779  }
780 
781  DBUG_RETURN(error);
782 }
783 
784 
790 {
791  DBUG_ASSERT(field);
792  if (field->type() == MYSQL_TYPE_BLOB ||
793  field->type() == MYSQL_TYPE_GEOMETRY)
794  key_part_flag|= HA_BLOB_PART;
795  else if (field->real_type() == MYSQL_TYPE_VARCHAR)
796  key_part_flag|= HA_VAR_LENGTH_PART;
797  else if (field->type() == MYSQL_TYPE_BIT)
798  key_part_flag|= HA_BIT_PART;
799 }
800 
801 
809 {
810  field= fld;
811  fieldnr= field->field_index + 1;
812  null_bit= field->null_bit;
813  null_offset= field->null_offset();
814  offset= field->offset(field->table->record[0]);
815  length= (uint16) field->key_length();
816  store_length= length;
817  key_part_flag= 0;
818 
819  if (field->real_maybe_null())
820  store_length+= HA_KEY_NULL_LENGTH;
821  if (field->type() == MYSQL_TYPE_BLOB ||
822  field->real_type() == MYSQL_TYPE_VARCHAR ||
823  field->type() == MYSQL_TYPE_GEOMETRY)
824  {
825  store_length+= HA_KEY_BLOB_LENGTH;
826  }
827  init_flags();
828 
829  type= (uint8) field->key_type();
830  key_type =
831  ((ha_base_keytype) type == HA_KEYTYPE_TEXT ||
832  (ha_base_keytype) type == HA_KEYTYPE_VARTEXT1 ||
833  (ha_base_keytype) type == HA_KEYTYPE_VARTEXT2) ?
834  0 : FIELDFLAG_BINARY;
835 }
836 
837 
850 static void setup_key_part_field(TABLE_SHARE *share, handler *handler_file,
851  uint primary_key_n, KEY *keyinfo, uint key_n,
852  uint key_part_n, uint *usable_parts)
853 {
854  KEY_PART_INFO *key_part= &keyinfo->key_part[key_part_n];
855  Field *field= key_part->field;
856 
857  /* Flag field as unique if it is the only keypart in a unique index */
858  if (key_part_n == 0 && key_n != primary_key_n)
859  field->flags |= (((keyinfo->flags & HA_NOSAME) &&
860  (keyinfo->user_defined_key_parts == 1)) ?
861  UNIQUE_KEY_FLAG : MULTIPLE_KEY_FLAG);
862  if (key_part_n == 0)
863  field->key_start.set_bit(key_n);
864  if (field->key_length() == key_part->length &&
865  !(field->flags & BLOB_FLAG))
866  {
867  if (handler_file->index_flags(key_n, key_part_n, 0) & HA_KEYREAD_ONLY)
868  {
869  share->keys_for_keyread.set_bit(key_n);
870  field->part_of_key.set_bit(key_n);
871  field->part_of_key_not_clustered.set_bit(key_n);
872  }
873  if (handler_file->index_flags(key_n, key_part_n, 1) & HA_READ_ORDER)
874  field->part_of_sortkey.set_bit(key_n);
875  }
876 
877  if (!(key_part->key_part_flag & HA_REVERSE_SORT) &&
878  *usable_parts == key_part_n)
879  (*usable_parts)++; // For FILESORT
880 }
881 
882 
910 static uint add_pk_parts_to_sk(KEY *sk, uint sk_n, KEY *pk, uint pk_n,
911  TABLE_SHARE *share, handler *handler_file,
912  uint *usable_parts)
913 {
914  uint max_key_length= sk->key_length;
915  bool is_unique_key= false;
916  KEY_PART_INFO *current_key_part= &sk->key_part[sk->user_defined_key_parts];
917  ulong *current_rec_per_key= &sk->rec_per_key[sk->user_defined_key_parts];
918 
919  /*
920  For each keypart in the primary key: check if the keypart is
921  already part of the secondary key and add it if not.
922  */
923  for (uint pk_part= 0; pk_part < pk->user_defined_key_parts; pk_part++)
924  {
925  KEY_PART_INFO *pk_key_part= &pk->key_part[pk_part];
926  /* MySQL does not supports more key parts than MAX_REF_LENGTH */
927  if (sk->actual_key_parts >= MAX_REF_PARTS)
928  goto end;
929 
930  bool pk_field_is_in_sk= false;
931  for (uint j= 0; j < sk->user_defined_key_parts; j++)
932  {
933  if (sk->key_part[j].fieldnr == pk_key_part->fieldnr &&
934  share->field[pk_key_part->fieldnr - 1]->key_length() ==
935  sk->key_part[j].length)
936  {
937  pk_field_is_in_sk= true;
938  break;
939  }
940  }
941 
942  /* Add PK field to secondary key if it's not already part of the key. */
943  if (!pk_field_is_in_sk)
944  {
945  /* MySQL does not supports keys longer than MAX_KEY_LENGTH */
946  if (max_key_length + pk_key_part->length > MAX_KEY_LENGTH)
947  goto end;
948 
949  *current_key_part= *pk_key_part;
950  setup_key_part_field(share, handler_file, pk_n, sk, sk_n,
951  sk->actual_key_parts, usable_parts);
952  *current_rec_per_key++= 0;
953  sk->actual_key_parts++;
954  sk->unused_key_parts--;
955  current_key_part++;
956  max_key_length+= pk_key_part->length;
957  /*
958  Secondary key will be unique if the key does not exceed
959  key length limitation and key parts limitation.
960  */
961  is_unique_key= true;
962  }
963  }
964  if (is_unique_key)
965  sk->actual_flags|= HA_NOSAME;
966 
967 end:
968  return (sk->actual_key_parts - sk->user_defined_key_parts);
969 }
970 
971 
972 /*
973  Read data from a binary .frm file from MySQL 3.23 - 5.0 into TABLE_SHARE
974 
975  NOTE: Much of the logic here is duplicated in create_tmp_table()
976  (see sql_select.cc). Hence, changes to this function may have to be
977  repeated there.
978 */
979 
980 static int open_binary_frm(THD *thd, TABLE_SHARE *share, uchar *head,
981  File file)
982 {
983  int error, errarg= 0;
984  uint new_frm_ver, field_pack_length, new_field_pack_flag;
985  uint interval_count, interval_parts, read_length, int_length;
986  uint db_create_options, keys, key_parts, n_length;
987  uint key_info_length, com_length, null_bit_pos;
988  uint extra_rec_buf_length;
989  uint i,j;
990  bool use_extended_sk; // Supported extending of secondary keys with PK parts
991  bool use_hash;
992  char *keynames, *names, *comment_pos;
993  uchar forminfo[288];
994  uchar *record;
995  uchar *disk_buff, *strpos, *null_flags, *null_pos;
996  ulong pos, record_offset, *rec_per_key, rec_buff_length;
997  handler *handler_file= 0;
998  KEY *keyinfo;
999  KEY_PART_INFO *key_part;
1000  SQL_CRYPT *crypted=0;
1001  Field **field_ptr, *reg_field;
1002  const char **interval_array;
1003  enum legacy_db_type legacy_db_type;
1004  my_bitmap_map *bitmaps;
1005  uchar *extra_segment_buff= 0;
1006  const uint format_section_header_size= 8;
1007  uchar *format_section_fields= 0;
1008  DBUG_ENTER("open_binary_frm");
1009 
1010  new_field_pack_flag= head[27];
1011  new_frm_ver= (head[2] - FRM_VER);
1012  field_pack_length= new_frm_ver < 2 ? 11 : 17;
1013  disk_buff= 0;
1014 
1015  error= 3;
1016  /* Position of the form in the form file. */
1017  if (!(pos= get_form_pos(file, head)))
1018  goto err; /* purecov: inspected */
1019 
1020  mysql_file_seek(file,pos,MY_SEEK_SET,MYF(0));
1021  if (mysql_file_read(file, forminfo,288,MYF(MY_NABP)))
1022  goto err;
1023  share->frm_version= head[2];
1024  /*
1025  Check if .frm file created by MySQL 5.0. In this case we want to
1026  display CHAR fields as CHAR and not as VARCHAR.
1027  We do it this way as we want to keep the old frm version to enable
1028  MySQL 4.1 to read these files.
1029  */
1030  if (share->frm_version == FRM_VER_TRUE_VARCHAR -1 && head[33] == 5)
1031  share->frm_version= FRM_VER_TRUE_VARCHAR;
1032 
1033 #ifdef WITH_PARTITION_STORAGE_ENGINE
1034  if (*(head+61) &&
1035  !(share->default_part_db_type=
1036  ha_checktype(thd, (enum legacy_db_type) (uint) *(head+61), 1, 0)))
1037  goto err;
1038  DBUG_PRINT("info", ("default_part_db_type = %u", head[61]));
1039 #endif
1040  legacy_db_type= (enum legacy_db_type) (uint) *(head+3);
1041  DBUG_ASSERT(share->db_plugin == NULL);
1042  /*
1043  if the storage engine is dynamic, no point in resolving it by its
1044  dynamically allocated legacy_db_type. We will resolve it later by name.
1045  */
1046  if (legacy_db_type > DB_TYPE_UNKNOWN &&
1047  legacy_db_type < DB_TYPE_FIRST_DYNAMIC)
1048  share->db_plugin= ha_lock_engine(NULL,
1049  ha_checktype(thd, legacy_db_type, 0, 0));
1050  share->db_create_options= db_create_options= uint2korr(head+30);
1051  share->db_options_in_use= share->db_create_options;
1052  share->mysql_version= uint4korr(head+51);
1053  share->null_field_first= 0;
1054  if (!head[32]) // New frm file in 3.23
1055  {
1056  share->avg_row_length= uint4korr(head+34);
1057  share->row_type= (row_type) head[40];
1058  share->table_charset= get_charset((((uint) head[41]) << 8) +
1059  (uint) head[38],MYF(0));
1060  share->null_field_first= 1;
1061  share->stats_sample_pages= uint2korr(head+42);
1062  share->stats_auto_recalc= static_cast<enum_stats_auto_recalc>(head[44]);
1063  }
1064  if (!share->table_charset)
1065  {
1066  /* unknown charset in head[38] or pre-3.23 frm */
1067  if (use_mb(default_charset_info))
1068  {
1069  /* Warn that we may be changing the size of character columns */
1070  sql_print_warning("'%s' had no or invalid character set, "
1071  "and default character set is multi-byte, "
1072  "so character column sizes may have changed",
1073  share->path.str);
1074  }
1075  share->table_charset= default_charset_info;
1076  }
1077  share->db_record_offset= 1;
1078  /* Set temporarily a good value for db_low_byte_first */
1079  share->db_low_byte_first= test(legacy_db_type != DB_TYPE_ISAM);
1080  error=4;
1081  share->max_rows= uint4korr(head+18);
1082  share->min_rows= uint4korr(head+22);
1083 
1084  /* Read keyinformation */
1085  key_info_length= (uint) uint2korr(head+28);
1086  mysql_file_seek(file, (ulong) uint2korr(head+6), MY_SEEK_SET, MYF(0));
1087  if (read_string(file,(uchar**) &disk_buff,key_info_length))
1088  goto err; /* purecov: inspected */
1089  if (disk_buff[0] & 0x80)
1090  {
1091  share->keys= keys= (disk_buff[1] << 7) | (disk_buff[0] & 0x7f);
1092  share->key_parts= key_parts= uint2korr(disk_buff+2);
1093  }
1094  else
1095  {
1096  share->keys= keys= disk_buff[0];
1097  share->key_parts= key_parts= disk_buff[1];
1098  }
1099  share->keys_for_keyread.init(0);
1100  share->keys_in_use.init(keys);
1101 
1102  strpos=disk_buff+6;
1103 
1104  use_extended_sk=
1105  ha_check_storage_engine_flag(share->db_type(),
1106  HTON_SUPPORTS_EXTENDED_KEYS);
1107 
1108  uint total_key_parts;
1109  if (use_extended_sk)
1110  {
1111  uint primary_key_parts= keys ?
1112  (new_frm_ver >= 3) ? (uint) strpos[4] : (uint) strpos[3] : 0;
1113  total_key_parts= key_parts + primary_key_parts * (keys - 1);
1114  }
1115  else
1116  total_key_parts= key_parts;
1117  n_length= keys * sizeof(KEY) + total_key_parts * sizeof(KEY_PART_INFO);
1118 
1119  if (!(keyinfo = (KEY*) alloc_root(&share->mem_root,
1120  n_length + uint2korr(disk_buff+4))))
1121  goto err; /* purecov: inspected */
1122  memset(keyinfo, 0, n_length);
1123  share->key_info= keyinfo;
1124  key_part= reinterpret_cast<KEY_PART_INFO*>(keyinfo+keys);
1125 
1126  if (!(rec_per_key= (ulong*) alloc_root(&share->mem_root,
1127  sizeof(ulong) * total_key_parts)))
1128  goto err;
1129 
1130  for (i=0 ; i < keys ; i++, keyinfo++)
1131  {
1132  keyinfo->table= 0; // Updated in open_frm
1133  if (new_frm_ver >= 3)
1134  {
1135  keyinfo->flags= (uint) uint2korr(strpos) ^ HA_NOSAME;
1136  keyinfo->key_length= (uint) uint2korr(strpos+2);
1137  keyinfo->user_defined_key_parts= (uint) strpos[4];
1138  keyinfo->algorithm= (enum ha_key_alg) strpos[5];
1139  keyinfo->block_size= uint2korr(strpos+6);
1140  strpos+=8;
1141  }
1142  else
1143  {
1144  keyinfo->flags= ((uint) strpos[0]) ^ HA_NOSAME;
1145  keyinfo->key_length= (uint) uint2korr(strpos+1);
1146  keyinfo->user_defined_key_parts= (uint) strpos[3];
1147  keyinfo->algorithm= HA_KEY_ALG_UNDEF;
1148  strpos+=4;
1149  }
1150 
1151  keyinfo->key_part= key_part;
1152  keyinfo->rec_per_key= rec_per_key;
1153  for (j=keyinfo->user_defined_key_parts ; j-- ; key_part++)
1154  {
1155  *rec_per_key++=0;
1156  key_part->fieldnr= (uint16) (uint2korr(strpos) & FIELD_NR_MASK);
1157  key_part->offset= (uint) uint2korr(strpos+2)-1;
1158  key_part->key_type= (uint) uint2korr(strpos+5);
1159  // key_part->field= (Field*) 0; // Will be fixed later
1160  if (new_frm_ver >= 1)
1161  {
1162  key_part->key_part_flag= *(strpos+4);
1163  key_part->length= (uint) uint2korr(strpos+7);
1164  strpos+=9;
1165  }
1166  else
1167  {
1168  key_part->length= *(strpos+4);
1169  key_part->key_part_flag=0;
1170  if (key_part->length > 128)
1171  {
1172  key_part->length&=127; /* purecov: inspected */
1173  key_part->key_part_flag=HA_REVERSE_SORT; /* purecov: inspected */
1174  }
1175  strpos+=7;
1176  }
1177  key_part->store_length=key_part->length;
1178  }
1179  /*
1180  Add primary key parts if engine supports primary key extension for
1181  secondary keys. Here we add unique first key parts to the end of
1182  secondary key parts array and increase actual number of key parts.
1183  Note that primary key is always first if exists. Later if there is no
1184  primary key in the table then number of actual keys parts is set to
1185  user defined key parts.
1186  */
1187  keyinfo->actual_key_parts= keyinfo->user_defined_key_parts;
1188  keyinfo->actual_flags= keyinfo->flags;
1189  if (use_extended_sk && i && !(keyinfo->flags & HA_NOSAME))
1190  {
1191  const uint primary_key_parts= share->key_info->user_defined_key_parts;
1192  keyinfo->unused_key_parts= primary_key_parts;
1193  key_part+= primary_key_parts;
1194  rec_per_key+= primary_key_parts;
1195  share->key_parts+= primary_key_parts;
1196  }
1197  }
1198  keynames=(char*) key_part;
1199  strpos+= (strmov(keynames, (char *) strpos) - keynames)+1;
1200 
1201  //reading index comments
1202  for (keyinfo= share->key_info, i=0; i < keys; i++, keyinfo++)
1203  {
1204  if (keyinfo->flags & HA_USES_COMMENT)
1205  {
1206  keyinfo->comment.length= uint2korr(strpos);
1207  keyinfo->comment.str= strmake_root(&share->mem_root, (char*) strpos+2,
1208  keyinfo->comment.length);
1209  strpos+= 2 + keyinfo->comment.length;
1210  }
1211  DBUG_ASSERT(test(keyinfo->flags & HA_USES_COMMENT) ==
1212  (keyinfo->comment.length > 0));
1213  }
1214 
1215  share->reclength = uint2korr((head+16));
1216  if (*(head+26) == 1)
1217  share->system= 1; /* one-record-database */
1218 #ifdef HAVE_CRYPTED_FRM
1219  else if (*(head+26) == 2)
1220  {
1221  crypted= get_crypt_for_frm();
1222  share->crypted= 1;
1223  }
1224 #endif
1225 
1226  record_offset= (ulong) (uint2korr(head+6)+
1227  ((uint2korr(head+14) == 0xffff ?
1228  uint4korr(head+47) : uint2korr(head+14))));
1229 
1230  if ((n_length= uint4korr(head+55)))
1231  {
1232  /* Read extra data segment */
1233  uchar *next_chunk, *buff_end;
1234  DBUG_PRINT("info", ("extra segment size is %u bytes", n_length));
1235  if (!(extra_segment_buff= (uchar*) my_malloc(n_length, MYF(MY_WME))))
1236  goto err;
1237  next_chunk= extra_segment_buff;
1238  if (mysql_file_pread(file, extra_segment_buff,
1239  n_length, record_offset + share->reclength,
1240  MYF(MY_NABP)))
1241  {
1242  goto err;
1243  }
1244  share->connect_string.length= uint2korr(next_chunk);
1245  if (!(share->connect_string.str= strmake_root(&share->mem_root,
1246  (char*) next_chunk + 2,
1247  share->connect_string.
1248  length)))
1249  {
1250  goto err;
1251  }
1252  next_chunk+= share->connect_string.length + 2;
1253  buff_end= extra_segment_buff + n_length;
1254  if (next_chunk + 2 < buff_end)
1255  {
1256  uint str_db_type_length= uint2korr(next_chunk);
1257  LEX_STRING name;
1258  name.str= (char*) next_chunk + 2;
1259  name.length= str_db_type_length;
1260 
1261  plugin_ref tmp_plugin= ha_resolve_by_name(thd, &name, FALSE);
1262  if (tmp_plugin != NULL && !plugin_equals(tmp_plugin, share->db_plugin))
1263  {
1264  if (legacy_db_type > DB_TYPE_UNKNOWN &&
1265  legacy_db_type < DB_TYPE_FIRST_DYNAMIC &&
1266  legacy_db_type != ha_legacy_type(
1267  plugin_data(tmp_plugin, handlerton *)))
1268  {
1269  /* bad file, legacy_db_type did not match the name */
1270  goto err;
1271  }
1272  /*
1273  tmp_plugin is locked with a local lock.
1274  we unlock the old value of share->db_plugin before
1275  replacing it with a globally locked version of tmp_plugin
1276  */
1277  plugin_unlock(NULL, share->db_plugin);
1278  share->db_plugin= my_plugin_lock(NULL, &tmp_plugin);
1279  DBUG_PRINT("info", ("setting dbtype to '%.*s' (%d)",
1280  str_db_type_length, next_chunk + 2,
1281  ha_legacy_type(share->db_type())));
1282  }
1283 #ifdef WITH_PARTITION_STORAGE_ENGINE
1284  else if (str_db_type_length == 9 &&
1285  !strncmp((char *) next_chunk + 2, "partition", 9))
1286  {
1287  /*
1288  Use partition handler
1289  tmp_plugin is locked with a local lock.
1290  we unlock the old value of share->db_plugin before
1291  replacing it with a globally locked version of tmp_plugin
1292  */
1293  /* Check if the partitioning engine is ready */
1294  if (!plugin_is_ready(&name, MYSQL_STORAGE_ENGINE_PLUGIN))
1295  {
1296  error= 8;
1297  my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0),
1298  "--skip-partition");
1299  goto err;
1300  }
1301  plugin_unlock(NULL, share->db_plugin);
1302  share->db_plugin= ha_lock_engine(NULL, partition_hton);
1303  DBUG_PRINT("info", ("setting dbtype to '%.*s' (%d)",
1304  str_db_type_length, next_chunk + 2,
1305  ha_legacy_type(share->db_type())));
1306  }
1307 #endif
1308  else if (!tmp_plugin)
1309  {
1310  /* purecov: begin inspected */
1311  error= 8;
1312  name.str[name.length]=0;
1313  my_error(ER_UNKNOWN_STORAGE_ENGINE, MYF(0), name.str);
1314  goto err;
1315  /* purecov: end */
1316  }
1317  next_chunk+= str_db_type_length + 2;
1318  }
1319  if (next_chunk + 5 < buff_end)
1320  {
1321  uint32 partition_info_str_len = uint4korr(next_chunk);
1322 #ifdef WITH_PARTITION_STORAGE_ENGINE
1323  if ((share->partition_info_buffer_size=
1324  share->partition_info_str_len= partition_info_str_len))
1325  {
1326  if (!(share->partition_info_str= (char*)
1327  memdup_root(&share->mem_root, next_chunk + 4,
1328  partition_info_str_len + 1)))
1329  {
1330  goto err;
1331  }
1332  }
1333 #else
1334  if (partition_info_str_len)
1335  {
1336  DBUG_PRINT("info", ("WITH_PARTITION_STORAGE_ENGINE is not defined"));
1337  goto err;
1338  }
1339 #endif
1340  next_chunk+= 5 + partition_info_str_len;
1341  }
1342 #if MYSQL_VERSION_ID < 50200
1343  if (share->mysql_version >= 50106 && share->mysql_version <= 50109)
1344  {
1345  /*
1346  Partition state array was here in version 5.1.6 to 5.1.9, this code
1347  makes it possible to load a 5.1.6 table in later versions. Can most
1348  likely be removed at some point in time. Will only be used for
1349  upgrades within 5.1 series of versions. Upgrade to 5.2 can only be
1350  done from newer 5.1 versions.
1351  */
1352  next_chunk+= 4;
1353  }
1354  else
1355 #endif
1356  if (share->mysql_version >= 50110 && next_chunk < buff_end)
1357  {
1358  /* New auto_partitioned indicator introduced in 5.1.11 */
1359 #ifdef WITH_PARTITION_STORAGE_ENGINE
1360  share->auto_partitioned= *next_chunk;
1361 #endif
1362  next_chunk++;
1363  }
1364  keyinfo= share->key_info;
1365  for (i= 0; i < keys; i++, keyinfo++)
1366  {
1367  if (keyinfo->flags & HA_USES_PARSER)
1368  {
1369  LEX_STRING parser_name;
1370  if (next_chunk >= buff_end)
1371  {
1372  DBUG_PRINT("error",
1373  ("fulltext key uses parser that is not defined in .frm"));
1374  goto err;
1375  }
1376  parser_name.str= (char*) next_chunk;
1377  parser_name.length= strlen((char*) next_chunk);
1378  next_chunk+= parser_name.length + 1;
1379  keyinfo->parser= my_plugin_lock_by_name(NULL, &parser_name,
1380  MYSQL_FTPARSER_PLUGIN);
1381  if (! keyinfo->parser)
1382  {
1383  my_error(ER_PLUGIN_IS_NOT_LOADED, MYF(0), parser_name.str);
1384  goto err;
1385  }
1386  }
1387  }
1388  if (forminfo[46] == (uchar)255)
1389  {
1390  //reading long table comment
1391  if (next_chunk + 2 > buff_end)
1392  {
1393  DBUG_PRINT("error",
1394  ("long table comment is not defined in .frm"));
1395  goto err;
1396  }
1397  share->comment.length = uint2korr(next_chunk);
1398  if (! (share->comment.str= strmake_root(&share->mem_root,
1399  (char*)next_chunk + 2, share->comment.length)))
1400  {
1401  goto err;
1402  }
1403  next_chunk+= 2 + share->comment.length;
1404  }
1405 
1406  if (next_chunk + format_section_header_size < buff_end)
1407  {
1408  /*
1409  New extra data segment called "format section" with additional
1410  table and column properties introduced by MySQL Cluster
1411  based on 5.1.20
1412 
1413  Table properties:
1414  TABLESPACE <ts> and STORAGE [DISK|MEMORY]
1415 
1416  Column properties:
1417  COLUMN_FORMAT [DYNAMIC|FIXED] and STORAGE [DISK|MEMORY]
1418  */
1419  DBUG_PRINT("info", ("Found format section"));
1420 
1421  /* header */
1422  const uint format_section_length= uint2korr(next_chunk);
1423  const uint format_section_flags= uint4korr(next_chunk+2);
1424  /* 2 bytes unused */
1425 
1426  if (next_chunk + format_section_length > buff_end)
1427  {
1428  DBUG_PRINT("error", ("format section length too long: %u",
1429  format_section_length));
1430  goto err;
1431  }
1432  DBUG_PRINT("info", ("format_section_length: %u, format_section_flags: %u",
1433  format_section_length, format_section_flags));
1434 
1435  share->default_storage_media=
1436  (enum ha_storage_media) (format_section_flags & 0x7);
1437 
1438  /* tablespace */
1439  const char *tablespace=
1440  (const char*)next_chunk + format_section_header_size;
1441  const uint tablespace_length= strlen(tablespace);
1442  if (tablespace_length &&
1443  !(share->tablespace= strmake_root(&share->mem_root,
1444  tablespace, tablespace_length+1)))
1445  {
1446  goto err;
1447  }
1448  DBUG_PRINT("info", ("tablespace: '%s'",
1449  share->tablespace ? share->tablespace : "<null>"));
1450 
1451  /* pointer to format section for fields */
1452  format_section_fields=
1453  next_chunk + format_section_header_size + tablespace_length + 1;
1454 
1455  next_chunk+= format_section_length;
1456  }
1457  }
1458  share->key_block_size= uint2korr(head+62);
1459 
1460  error=4;
1461  extra_rec_buf_length= uint2korr(head+59);
1462  rec_buff_length= ALIGN_SIZE(share->reclength + 1 + extra_rec_buf_length);
1463  share->rec_buff_length= rec_buff_length;
1464  if (!(record= (uchar *) alloc_root(&share->mem_root,
1465  rec_buff_length)))
1466  goto err; /* purecov: inspected */
1467  share->default_values= record;
1468  if (mysql_file_pread(file, record, (size_t) share->reclength,
1469  record_offset, MYF(MY_NABP)))
1470  goto err; /* purecov: inspected */
1471 
1472  mysql_file_seek(file, pos+288, MY_SEEK_SET, MYF(0));
1473 #ifdef HAVE_CRYPTED_FRM
1474  if (crypted)
1475  {
1476  crypted->decode((char*) forminfo+256,288-256);
1477  if (sint2korr(forminfo+284) != 0) // Should be 0
1478  goto err; // Wrong password
1479  }
1480 #endif
1481 
1482  share->fields= uint2korr(forminfo+258);
1483  pos= uint2korr(forminfo+260); /* Length of all screens */
1484  n_length= uint2korr(forminfo+268);
1485  interval_count= uint2korr(forminfo+270);
1486  interval_parts= uint2korr(forminfo+272);
1487  int_length= uint2korr(forminfo+274);
1488  share->null_fields= uint2korr(forminfo+282);
1489  com_length= uint2korr(forminfo+284);
1490  if (forminfo[46] != (uchar)255)
1491  {
1492  share->comment.length= (int) (forminfo[46]);
1493  share->comment.str= strmake_root(&share->mem_root, (char*) forminfo+47,
1494  share->comment.length);
1495  }
1496 
1497  DBUG_PRINT("info",("i_count: %d i_parts: %d index: %d n_length: %d int_length: %d com_length: %d", interval_count,interval_parts, share->keys,n_length,int_length, com_length));
1498 
1499  if (!(field_ptr = (Field **)
1500  alloc_root(&share->mem_root,
1501  (uint) ((share->fields+1)*sizeof(Field*)+
1502  interval_count*sizeof(TYPELIB)+
1503  (share->fields+interval_parts+
1504  keys+3)*sizeof(char *)+
1505  (n_length+int_length+com_length)))))
1506  goto err; /* purecov: inspected */
1507 
1508  share->field= field_ptr;
1509  read_length=(uint) (share->fields * field_pack_length +
1510  pos+ (uint) (n_length+int_length+com_length));
1511  if (read_string(file,(uchar**) &disk_buff,read_length))
1512  goto err; /* purecov: inspected */
1513 #ifdef HAVE_CRYPTED_FRM
1514  if (crypted)
1515  {
1516  crypted->decode((char*) disk_buff,read_length);
1517  delete crypted;
1518  crypted=0;
1519  }
1520 #endif
1521  strpos= disk_buff+pos;
1522 
1523  share->intervals= (TYPELIB*) (field_ptr+share->fields+1);
1524  interval_array= (const char **) (share->intervals+interval_count);
1525  names= (char*) (interval_array+share->fields+interval_parts+keys+3);
1526  if (!interval_count)
1527  share->intervals= 0; // For better debugging
1528  memcpy((char*) names, strpos+(share->fields*field_pack_length),
1529  (uint) (n_length+int_length));
1530  comment_pos= names+(n_length+int_length);
1531  memcpy(comment_pos, disk_buff+read_length-com_length, com_length);
1532 
1533  fix_type_pointers(&interval_array, &share->fieldnames, 1, &names);
1534  if (share->fieldnames.count != share->fields)
1535  goto err;
1536  fix_type_pointers(&interval_array, share->intervals, interval_count,
1537  &names);
1538 
1539  {
1540  /* Set ENUM and SET lengths */
1541  TYPELIB *interval;
1542  for (interval= share->intervals;
1543  interval < share->intervals + interval_count;
1544  interval++)
1545  {
1546  uint count= (uint) (interval->count + 1) * sizeof(uint);
1547  if (!(interval->type_lengths= (uint *) alloc_root(&share->mem_root,
1548  count)))
1549  goto err;
1550  for (count= 0; count < interval->count; count++)
1551  {
1552  char *val= (char*) interval->type_names[count];
1553  interval->type_lengths[count]= strlen(val);
1554  }
1555  interval->type_lengths[count]= 0;
1556  }
1557  }
1558 
1559  if (keynames)
1560  fix_type_pointers(&interval_array, &share->keynames, 1, &keynames);
1561 
1562  /* Allocate handler */
1563  if (!(handler_file= get_new_handler(share, thd->mem_root,
1564  share->db_type())))
1565  goto err;
1566 
1567  if (handler_file->set_ha_share_ref(&share->ha_share))
1568  goto err;
1569 
1570  record= share->default_values-1; /* Fieldstart = 1 */
1571  if (share->null_field_first)
1572  {
1573  null_flags= null_pos= (uchar*) record+1;
1574  null_bit_pos= (db_create_options & HA_OPTION_PACK_RECORD) ? 0 : 1;
1575  /*
1576  null_bytes below is only correct under the condition that
1577  there are no bit fields. Correct values is set below after the
1578  table struct is initialized
1579  */
1580  share->null_bytes= (share->null_fields + null_bit_pos + 7) / 8;
1581  }
1582 #ifndef WE_WANT_TO_SUPPORT_VERY_OLD_FRM_FILES
1583  else
1584  {
1585  share->null_bytes= (share->null_fields+7)/8;
1586  null_flags= null_pos= (uchar*) (record + 1 +share->reclength -
1587  share->null_bytes);
1588  null_bit_pos= 0;
1589  }
1590 #endif
1591 
1592  use_hash= share->fields >= MAX_FIELDS_BEFORE_HASH;
1593  if (use_hash)
1594  use_hash= !my_hash_init(&share->name_hash,
1595  system_charset_info,
1596  share->fields,0,0,
1597  (my_hash_get_key) get_field_name,0,0);
1598 
1599  for (i=0 ; i < share->fields; i++, strpos+=field_pack_length, field_ptr++)
1600  {
1601  uint pack_flag, interval_nr, unireg_type, recpos, field_length;
1602  enum_field_types field_type;
1603  const CHARSET_INFO *charset=NULL;
1604  Field::geometry_type geom_type= Field::GEOM_GEOMETRY;
1605  LEX_STRING comment;
1606 
1607  if (new_frm_ver >= 3)
1608  {
1609  /* new frm file in 4.1 */
1610  field_length= uint2korr(strpos+3);
1611  recpos= uint3korr(strpos+5);
1612  pack_flag= uint2korr(strpos+8);
1613  unireg_type= (uint) strpos[10];
1614  interval_nr= (uint) strpos[12];
1615  uint comment_length=uint2korr(strpos+15);
1616  field_type=(enum_field_types) (uint) strpos[13];
1617 
1618  /* charset and geometry_type share the same byte in frm */
1619  if (field_type == MYSQL_TYPE_GEOMETRY)
1620  {
1621 #ifdef HAVE_SPATIAL
1622  geom_type= (Field::geometry_type) strpos[14];
1623  charset= &my_charset_bin;
1624 #else
1625  error= 4; // unsupported field type
1626  goto err;
1627 #endif
1628  }
1629  else
1630  {
1631  uint csid= strpos[14] + (((uint) strpos[11]) << 8);
1632  if (!csid)
1633  charset= &my_charset_bin;
1634  else if (!(charset= get_charset(csid, MYF(0))))
1635  {
1636  error= 5; // Unknown or unavailable charset
1637  errarg= (int) csid;
1638  goto err;
1639  }
1640  }
1641  if (!comment_length)
1642  {
1643  comment.str= (char*) "";
1644  comment.length=0;
1645  }
1646  else
1647  {
1648  comment.str= (char*) comment_pos;
1649  comment.length= comment_length;
1650  comment_pos+= comment_length;
1651  }
1652  }
1653  else
1654  {
1655  field_length= (uint) strpos[3];
1656  recpos= uint2korr(strpos+4),
1657  pack_flag= uint2korr(strpos+6);
1658  pack_flag&= ~FIELDFLAG_NO_DEFAULT; // Safety for old files
1659  unireg_type= (uint) strpos[8];
1660  interval_nr= (uint) strpos[10];
1661 
1662  /* old frm file */
1663  field_type= (enum_field_types) f_packtype(pack_flag);
1664  if (f_is_binary(pack_flag))
1665  {
1666  /*
1667  Try to choose the best 4.1 type:
1668  - for 4.0 "CHAR(N) BINARY" or "VARCHAR(N) BINARY"
1669  try to find a binary collation for character set.
1670  - for other types (e.g. BLOB) just use my_charset_bin.
1671  */
1672  if (!f_is_blob(pack_flag))
1673  {
1674  // 3.23 or 4.0 string
1675  if (!(charset= get_charset_by_csname(share->table_charset->csname,
1676  MY_CS_BINSORT, MYF(0))))
1677  charset= &my_charset_bin;
1678  }
1679  else
1680  charset= &my_charset_bin;
1681  }
1682  else
1683  charset= share->table_charset;
1684  memset(&comment, 0, sizeof(comment));
1685  }
1686 
1687  if (interval_nr && charset->mbminlen > 1)
1688  {
1689  /* Unescape UCS2 intervals from HEX notation */
1690  TYPELIB *interval= share->intervals + interval_nr - 1;
1691  unhex_type2(interval);
1692  }
1693 
1694 #ifndef TO_BE_DELETED_ON_PRODUCTION
1695  if (field_type == MYSQL_TYPE_NEWDECIMAL && !share->mysql_version)
1696  {
1697  /*
1698  Fix pack length of old decimal values from 5.0.3 -> 5.0.4
1699  The difference is that in the old version we stored precision
1700  in the .frm table while we now store the display_length
1701  */
1702  uint decimals= f_decimals(pack_flag);
1703  field_length= my_decimal_precision_to_length(field_length,
1704  decimals,
1705  f_is_dec(pack_flag) == 0);
1706  sql_print_error("Found incompatible DECIMAL field '%s' in %s; "
1707  "Please do \"ALTER TABLE `%s` FORCE\" to fix it!",
1708  share->fieldnames.type_names[i], share->table_name.str,
1709  share->table_name.str);
1710  push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
1711  ER_CRASHED_ON_USAGE,
1712  "Found incompatible DECIMAL field '%s' in %s; "
1713  "Please do \"ALTER TABLE `%s` FORCE\" to fix it!",
1714  share->fieldnames.type_names[i],
1715  share->table_name.str,
1716  share->table_name.str);
1717  share->crashed= 1; // Marker for CHECK TABLE
1718  }
1719 #endif
1720 
1721  *field_ptr= reg_field=
1722  make_field(share, record+recpos,
1723  (uint32) field_length,
1724  null_pos, null_bit_pos,
1725  pack_flag,
1726  field_type,
1727  charset,
1728  geom_type,
1729  (Field::utype) MTYP_TYPENR(unireg_type),
1730  (interval_nr ?
1731  share->intervals+interval_nr-1 :
1732  (TYPELIB*) 0),
1733  share->fieldnames.type_names[i]);
1734  if (!reg_field) // Not supported field type
1735  {
1736  error= 4;
1737  goto err; /* purecov: inspected */
1738  }
1739 
1740  reg_field->field_index= i;
1741  reg_field->comment=comment;
1742  if (field_type == MYSQL_TYPE_BIT && !f_bit_as_char(pack_flag))
1743  {
1744  if ((null_bit_pos+= field_length & 7) > 7)
1745  {
1746  null_pos++;
1747  null_bit_pos-= 8;
1748  }
1749  }
1750  if (!(reg_field->flags & NOT_NULL_FLAG))
1751  {
1752  if (!(null_bit_pos= (null_bit_pos + 1) & 7))
1753  null_pos++;
1754  }
1755  if (f_no_default(pack_flag))
1756  reg_field->flags|= NO_DEFAULT_VALUE_FLAG;
1757 
1758  if (reg_field->unireg_check == Field::NEXT_NUMBER)
1759  share->found_next_number_field= field_ptr;
1760 
1761  if (use_hash)
1762  if (my_hash_insert(&share->name_hash, (uchar*) field_ptr) )
1763  {
1764  /*
1765  Set return code 8 here to indicate that an error has
1766  occurred but that the error message already has been
1767  sent (OOM).
1768  */
1769  error= 8;
1770  goto err;
1771  }
1772 
1773  if (format_section_fields)
1774  {
1775  const uchar field_flags= format_section_fields[i];
1776  const uchar field_storage= (field_flags & STORAGE_TYPE_MASK);
1777  const uchar field_column_format=
1778  ((field_flags >> COLUMN_FORMAT_SHIFT)& COLUMN_FORMAT_MASK);
1779  DBUG_PRINT("debug", ("field flags: %u, storage: %u, column_format: %u",
1780  field_flags, field_storage, field_column_format));
1781  reg_field->set_storage_type((ha_storage_media)field_storage);
1782  reg_field->set_column_format((column_format_type)field_column_format);
1783  }
1784  }
1785  *field_ptr=0; // End marker
1786 
1787  /* Fix key->name and key_part->field */
1788  if (key_parts)
1789  {
1790  uint primary_key=(uint) (find_type(primary_key_name, &share->keynames,
1791  FIND_TYPE_NO_PREFIX) - 1);
1792  longlong ha_option= handler_file->ha_table_flags();
1793  keyinfo= share->key_info;
1794  key_part= keyinfo->key_part;
1795 
1796  for (uint key=0 ; key < share->keys ; key++,keyinfo++)
1797  {
1798  uint usable_parts= 0;
1799  keyinfo->name=(char*) share->keynames.type_names[key];
1800  /* Fix fulltext keys for old .frm files */
1801  if (share->key_info[key].flags & HA_FULLTEXT)
1802  share->key_info[key].algorithm= HA_KEY_ALG_FULLTEXT;
1803 
1804  if (primary_key >= MAX_KEY && (keyinfo->flags & HA_NOSAME))
1805  {
1806  /*
1807  If the UNIQUE key doesn't have NULL columns and is not a part key
1808  declare this as a primary key.
1809  */
1810  primary_key=key;
1811  for (i=0 ; i < keyinfo->user_defined_key_parts ;i++)
1812  {
1813  DBUG_ASSERT(key_part[i].fieldnr > 0);
1814  // Table field corresponding to the i'th key part.
1815  Field *table_field= share->field[key_part[i].fieldnr - 1];
1816 
1817  /*
1818  If the key column is of NOT NULL BLOB type, then it
1819  will definitly have key prefix. And if key part prefix size
1820  is equal to the BLOB column max size, then we can promote
1821  it to primary key.
1822  */
1823  if (!table_field->real_maybe_null() &&
1824  table_field->type() == MYSQL_TYPE_BLOB &&
1825  table_field->field_length == key_part[i].length)
1826  continue;
1827 
1828  if (table_field->real_maybe_null() ||
1829  table_field->key_length() != key_part[i].length)
1830  {
1831  primary_key= MAX_KEY; // Can't be used
1832  break;
1833  }
1834  }
1835  }
1836 
1837  for (i=0 ; i < keyinfo->user_defined_key_parts ; key_part++,i++)
1838  {
1839  Field *field;
1840  if (new_field_pack_flag <= 1)
1841  key_part->fieldnr= (uint16) find_field(share->field,
1842  share->default_values,
1843  (uint) key_part->offset,
1844  (uint) key_part->length);
1845  if (!key_part->fieldnr)
1846  {
1847  error= 4; // Wrong file
1848  goto err;
1849  }
1850  field= key_part->field= share->field[key_part->fieldnr-1];
1851  key_part->type= field->key_type();
1852  if (field->real_maybe_null())
1853  {
1854  key_part->null_offset=field->null_offset(share->default_values);
1855  key_part->null_bit= field->null_bit;
1856  key_part->store_length+=HA_KEY_NULL_LENGTH;
1857  keyinfo->flags|=HA_NULL_PART_KEY;
1858  keyinfo->key_length+= HA_KEY_NULL_LENGTH;
1859  }
1860  if (field->type() == MYSQL_TYPE_BLOB ||
1861  field->real_type() == MYSQL_TYPE_VARCHAR ||
1862  field->type() == MYSQL_TYPE_GEOMETRY)
1863  {
1864  key_part->store_length+=HA_KEY_BLOB_LENGTH;
1865  if (i + 1 <= keyinfo->user_defined_key_parts)
1866  keyinfo->key_length+= HA_KEY_BLOB_LENGTH;
1867  }
1868  key_part->init_flags();
1869 
1870  setup_key_part_field(share, handler_file, primary_key,
1871  keyinfo, key, i, &usable_parts);
1872 
1873  field->flags|= PART_KEY_FLAG;
1874  if (key == primary_key)
1875  {
1876  field->flags|= PRI_KEY_FLAG;
1877  /*
1878  If this field is part of the primary key and all keys contains
1879  the primary key, then we can use any key to find this column
1880  */
1881  if (ha_option & HA_PRIMARY_KEY_IN_READ_INDEX)
1882  {
1883  if (field->key_length() == key_part->length &&
1884  !(field->flags & BLOB_FLAG))
1885  field->part_of_key= share->keys_in_use;
1886  if (field->part_of_sortkey.is_set(key))
1887  field->part_of_sortkey= share->keys_in_use;
1888  }
1889  }
1890  if (field->key_length() != key_part->length)
1891  {
1892 #ifndef TO_BE_DELETED_ON_PRODUCTION
1893  if (field->type() == MYSQL_TYPE_NEWDECIMAL)
1894  {
1895  /*
1896  Fix a fatal error in decimal key handling that causes crashes
1897  on Innodb. We fix it by reducing the key length so that
1898  InnoDB never gets a too big key when searching.
1899  This allows the end user to do an ALTER TABLE to fix the
1900  error.
1901  */
1902  keyinfo->key_length-= (key_part->length - field->key_length());
1903  key_part->store_length-= (uint16)(key_part->length -
1904  field->key_length());
1905  key_part->length= (uint16)field->key_length();
1906  sql_print_error("Found wrong key definition in %s; "
1907  "Please do \"ALTER TABLE `%s` FORCE \" to fix it!",
1908  share->table_name.str,
1909  share->table_name.str);
1910  push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
1911  ER_CRASHED_ON_USAGE,
1912  "Found wrong key definition in %s; "
1913  "Please do \"ALTER TABLE `%s` FORCE\" to fix "
1914  "it!",
1915  share->table_name.str,
1916  share->table_name.str);
1917  share->crashed= 1; // Marker for CHECK TABLE
1918  continue;
1919  }
1920 #endif
1921  key_part->key_part_flag|= HA_PART_KEY_SEG;
1922  }
1923  }
1924 
1925 
1926  if (use_extended_sk && primary_key < MAX_KEY &&
1927  key && !(keyinfo->flags & HA_NOSAME))
1928  key_part+= add_pk_parts_to_sk(keyinfo, key, share->key_info, primary_key,
1929  share, handler_file, &usable_parts);
1930 
1931  /* Skip unused key parts if they exist */
1932  key_part+= keyinfo->unused_key_parts;
1933 
1934  keyinfo->usable_key_parts= usable_parts; // Filesort
1935 
1936  set_if_bigger(share->max_key_length,keyinfo->key_length+
1937  keyinfo->user_defined_key_parts);
1938  share->total_key_length+= keyinfo->key_length;
1939  /*
1940  MERGE tables do not have unique indexes. But every key could be
1941  an unique index on the underlying MyISAM table. (Bug #10400)
1942  */
1943  if ((keyinfo->flags & HA_NOSAME) ||
1944  (ha_option & HA_ANY_INDEX_MAY_BE_UNIQUE))
1945  set_if_bigger(share->max_unique_length,keyinfo->key_length);
1946  }
1947  if (primary_key < MAX_KEY &&
1948  (share->keys_in_use.is_set(primary_key)))
1949  {
1950  share->primary_key= primary_key;
1951  /*
1952  If we are using an integer as the primary key then allow the user to
1953  refer to it as '_rowid'
1954  */
1955  if (share->key_info[primary_key].user_defined_key_parts == 1)
1956  {
1957  Field *field= share->key_info[primary_key].key_part[0].field;
1958  if (field && field->result_type() == INT_RESULT)
1959  {
1960  /* note that fieldnr here (and rowid_field_offset) starts from 1 */
1961  share->rowid_field_offset= (share->key_info[primary_key].key_part[0].
1962  fieldnr);
1963  }
1964  }
1965  }
1966  else
1967  share->primary_key = MAX_KEY; // we do not have a primary key
1968  }
1969  else
1970  share->primary_key= MAX_KEY;
1971  my_free(disk_buff);
1972  disk_buff=0;
1973  if (new_field_pack_flag <= 1)
1974  {
1975  /* Old file format with default as not null */
1976  uint null_length= (share->null_fields+7)/8;
1977  memset(share->default_values + (null_flags - (uchar*) record), 255,
1978  null_length);
1979  }
1980 
1981  if (share->found_next_number_field)
1982  {
1983  reg_field= *share->found_next_number_field;
1984  if ((int) (share->next_number_index= (uint)
1985  find_ref_key(share->key_info, share->keys,
1986  share->default_values, reg_field,
1987  &share->next_number_key_offset,
1988  &share->next_number_keypart)) < 0)
1989  {
1990  /* Wrong field definition */
1991  error= 4;
1992  goto err;
1993  }
1994  else
1995  reg_field->flags |= AUTO_INCREMENT_FLAG;
1996  }
1997 
1998  if (share->blob_fields)
1999  {
2000  Field **ptr;
2001  uint k, *save;
2002 
2003  /* Store offsets to blob fields to find them fast */
2004  if (!(share->blob_field= save=
2005  (uint*) alloc_root(&share->mem_root,
2006  (uint) (share->blob_fields* sizeof(uint)))))
2007  goto err;
2008  for (k=0, ptr= share->field ; *ptr ; ptr++, k++)
2009  {
2010  if ((*ptr)->flags & BLOB_FLAG)
2011  (*save++)= k;
2012  }
2013  }
2014 
2015  /*
2016  the correct null_bytes can now be set, since bitfields have been taken
2017  into account
2018  */
2019  share->null_bytes= (null_pos - (uchar*) null_flags +
2020  (null_bit_pos + 7) / 8);
2021  share->last_null_bit_pos= null_bit_pos;
2022 
2023  share->db_low_byte_first= handler_file->low_byte_first();
2024  share->column_bitmap_size= bitmap_buffer_size(share->fields);
2025 
2026  if (!(bitmaps= (my_bitmap_map*) alloc_root(&share->mem_root,
2027  share->column_bitmap_size)))
2028  goto err;
2029  bitmap_init(&share->all_set, bitmaps, share->fields, FALSE);
2030  bitmap_set_all(&share->all_set);
2031 
2032  delete handler_file;
2033 #ifndef DBUG_OFF
2034  if (use_hash)
2035  (void) my_hash_check(&share->name_hash);
2036 #endif
2037  my_free(extra_segment_buff);
2038  DBUG_RETURN (0);
2039 
2040  err:
2041  share->error= error;
2042  share->open_errno= my_errno;
2043  share->errarg= errarg;
2044  my_free(disk_buff);
2045  my_free(extra_segment_buff);
2046  delete crypted;
2047  delete handler_file;
2048  my_hash_free(&share->name_hash);
2049 
2050  open_table_error(share, error, share->open_errno, errarg);
2051  DBUG_RETURN(error);
2052 } /* open_binary_frm */
2053 
2054 
2055 /*
2056  Open a table based on a TABLE_SHARE
2057 
2058  SYNOPSIS
2059  open_table_from_share()
2060  thd Thread handler
2061  share Table definition
2062  alias Alias for table
2063  db_stat open flags (for example HA_OPEN_KEYFILE|
2064  HA_OPEN_RNDFILE..) can be 0 (example in
2065  ha_example_table)
2066  prgflag READ_ALL etc..
2067  ha_open_flags HA_OPEN_ABORT_IF_LOCKED etc..
2068  outparam result table
2069  is_create_table Indicates that table is opened as part
2070  of CREATE or ALTER and does not yet exist in SE
2071 
2072  RETURN VALUES
2073  0 ok
2074  1 Error (see open_table_error)
2075  2 Error (see open_table_error)
2076  3 Wrong data in .frm file
2077  4 Error (see open_table_error)
2078  5 Error (see open_table_error: charset unavailable)
2079  7 Table definition has changed in engine
2080 */
2081 
2082 int open_table_from_share(THD *thd, TABLE_SHARE *share, const char *alias,
2083  uint db_stat, uint prgflag, uint ha_open_flags,
2084  TABLE *outparam, bool is_create_table)
2085 {
2086  int error;
2087  uint records, i, bitmap_size;
2088  bool error_reported= FALSE;
2089  uchar *record, *bitmaps;
2090  Field **field_ptr;
2091  DBUG_ENTER("open_table_from_share");
2092  DBUG_PRINT("enter",("name: '%s.%s' form: 0x%lx", share->db.str,
2093  share->table_name.str, (long) outparam));
2094 
2095  error= 1;
2096  memset(outparam, 0, sizeof(*outparam));
2097  outparam->in_use= thd;
2098  outparam->s= share;
2099  outparam->db_stat= db_stat;
2100  outparam->write_row_record= NULL;
2101 
2102  init_sql_alloc(&outparam->mem_root, TABLE_ALLOC_BLOCK_SIZE, 0);
2103 
2104  if (!(outparam->alias= my_strdup(alias, MYF(MY_WME))))
2105  goto err;
2106  outparam->quick_keys.init();
2107  outparam->possible_quick_keys.init();
2108  outparam->covering_keys.init();
2109  outparam->merge_keys.init();
2110  outparam->keys_in_use_for_query.init();
2111 
2112  /* Allocate handler */
2113  outparam->file= 0;
2114  if (!(prgflag & OPEN_FRM_FILE_ONLY))
2115  {
2116  if (!(outparam->file= get_new_handler(share, &outparam->mem_root,
2117  share->db_type())))
2118  goto err;
2119  if (outparam->file->set_ha_share_ref(&share->ha_share))
2120  goto err;
2121  }
2122  else
2123  {
2124  DBUG_ASSERT(!db_stat);
2125  }
2126 
2127  error= 4;
2128  outparam->reginfo.lock_type= TL_UNLOCK;
2129  outparam->current_lock= F_UNLCK;
2130  records=0;
2131  if ((db_stat & HA_OPEN_KEYFILE) || (prgflag & DELAYED_OPEN))
2132  records=1;
2133  if (prgflag & (READ_ALL+EXTRA_RECORD))
2134  records++;
2135 
2136  if (!(record= (uchar*) alloc_root(&outparam->mem_root,
2137  share->rec_buff_length * records)))
2138  goto err; /* purecov: inspected */
2139 
2140  if (records == 0)
2141  {
2142  /* We are probably in hard repair, and the buffers should not be used */
2143  outparam->record[0]= outparam->record[1]= share->default_values;
2144  }
2145  else
2146  {
2147  outparam->record[0]= record;
2148  if (records > 1)
2149  outparam->record[1]= record+ share->rec_buff_length;
2150  else
2151  outparam->record[1]= outparam->record[0]; // Safety
2152  }
2153 
2154 #ifdef HAVE_purify
2155  /*
2156  We need this because when we read var-length rows, we are not updating
2157  bytes after end of varchar
2158  */
2159  if (records > 1)
2160  {
2161  memcpy(outparam->record[0], share->default_values, share->rec_buff_length);
2162  memcpy(outparam->record[1], share->default_values, share->null_bytes);
2163  }
2164 #endif
2165 
2166  if (!(field_ptr = (Field **) alloc_root(&outparam->mem_root,
2167  (uint) ((share->fields+1)*
2168  sizeof(Field*)))))
2169  goto err; /* purecov: inspected */
2170 
2171  outparam->field= field_ptr;
2172 
2173  record= (uchar*) outparam->record[0]-1; /* Fieldstart = 1 */
2174  if (share->null_field_first)
2175  outparam->null_flags= (uchar*) record+1;
2176  else
2177  outparam->null_flags= (uchar*) (record+ 1+ share->reclength -
2178  share->null_bytes);
2179 
2180  /* Setup copy of fields from share, but use the right alias and record */
2181  for (i=0 ; i < share->fields; i++, field_ptr++)
2182  {
2183  Field *new_field= share->field[i]->clone(&outparam->mem_root);
2184  *field_ptr= new_field;
2185  if (new_field == NULL)
2186  goto err;
2187  new_field->init(outparam);
2188  new_field->move_field_offset((my_ptrdiff_t) (outparam->record[0] -
2189  outparam->s->default_values));
2190  }
2191  (*field_ptr)= 0; // End marker
2192 
2193  if (share->found_next_number_field)
2194  outparam->found_next_number_field=
2195  outparam->field[(uint) (share->found_next_number_field - share->field)];
2196 
2197  /* Fix key->name and key_part->field */
2198  if (share->key_parts)
2199  {
2200  KEY *key_info, *key_info_end;
2201  KEY_PART_INFO *key_part;
2202  uint n_length;
2203  n_length= share->keys * sizeof(KEY) +
2204  share->key_parts * sizeof(KEY_PART_INFO);
2205 
2206  if (!(key_info= (KEY*) alloc_root(&outparam->mem_root, n_length)))
2207  goto err;
2208  outparam->key_info= key_info;
2209  key_part= (reinterpret_cast<KEY_PART_INFO*>(key_info+share->keys));
2210 
2211  memcpy(key_info, share->key_info, sizeof(*key_info)*share->keys);
2212  memcpy(key_part, share->key_info[0].key_part, (sizeof(*key_part) *
2213  share->key_parts));
2214 
2215  for (key_info_end= key_info + share->keys ;
2216  key_info < key_info_end ;
2217  key_info++)
2218  {
2219  KEY_PART_INFO *key_part_end;
2220 
2221  key_info->table= outparam;
2222  key_info->key_part= key_part;
2223 
2224  for (key_part_end= key_part + key_info->actual_key_parts ;
2225  key_part < key_part_end ;
2226  key_part++)
2227  {
2228  Field *field= key_part->field= outparam->field[key_part->fieldnr-1];
2229 
2230  if (field->key_length() != key_part->length &&
2231  !(field->flags & BLOB_FLAG))
2232  {
2233  /*
2234  We are using only a prefix of the column as a key:
2235  Create a new field for the key part that matches the index
2236  */
2237  field= key_part->field=field->new_field(&outparam->mem_root,
2238  outparam, 0);
2239  field->field_length= key_part->length;
2240  }
2241  }
2242  /* Skip unused key parts if they exist */
2243  key_part+= key_info->unused_key_parts;
2244  }
2245  }
2246 
2247 #ifdef WITH_PARTITION_STORAGE_ENGINE
2248  if (share->partition_info_str_len && outparam->file)
2249  {
2250  /*
2251  In this execution we must avoid calling thd->change_item_tree since
2252  we might release memory before statement is completed. We do this
2253  by changing to a new statement arena. As part of this arena we also
2254  set the memory root to be the memory root of the table since we
2255  call the parser and fix_fields which both can allocate memory for
2256  item objects. We keep the arena to ensure that we can release the
2257  free_list when closing the table object.
2258  SEE Bug #21658
2259  */
2260 
2261  Query_arena *backup_stmt_arena_ptr= thd->stmt_arena;
2262  Query_arena backup_arena;
2263  Query_arena part_func_arena(&outparam->mem_root,
2264  Query_arena::STMT_INITIALIZED);
2265  thd->set_n_backup_active_arena(&part_func_arena, &backup_arena);
2266  thd->stmt_arena= &part_func_arena;
2267  bool tmp;
2268  bool work_part_info_used;
2269 
2270  tmp= mysql_unpack_partition(thd, share->partition_info_str,
2271  share->partition_info_str_len,
2272  outparam, is_create_table,
2273  share->default_part_db_type,
2274  &work_part_info_used);
2275  if (tmp)
2276  {
2277  thd->stmt_arena= backup_stmt_arena_ptr;
2278  thd->restore_active_arena(&part_func_arena, &backup_arena);
2279  goto partititon_err;
2280  }
2281  outparam->part_info->is_auto_partitioned= share->auto_partitioned;
2282  DBUG_PRINT("info", ("autopartitioned: %u", share->auto_partitioned));
2283  /*
2284  We should perform the fix_partition_func in either local or
2285  caller's arena depending on work_part_info_used value.
2286  */
2287  if (!work_part_info_used)
2288  tmp= fix_partition_func(thd, outparam, is_create_table);
2289  thd->stmt_arena= backup_stmt_arena_ptr;
2290  thd->restore_active_arena(&part_func_arena, &backup_arena);
2291  if (!tmp)
2292  {
2293  if (work_part_info_used)
2294  tmp= fix_partition_func(thd, outparam, is_create_table);
2295  }
2296  outparam->part_info->item_free_list= part_func_arena.free_list;
2297 partititon_err:
2298  if (tmp)
2299  {
2300  if (is_create_table)
2301  {
2302  /*
2303  During CREATE/ALTER TABLE it is ok to receive errors here.
2304  It is not ok if it happens during the opening of an frm
2305  file as part of a normal query.
2306  */
2307  error_reported= TRUE;
2308  }
2309  goto err;
2310  }
2311  }
2312 #endif
2313 
2314  /* Allocate bitmaps */
2315 
2316  bitmap_size= share->column_bitmap_size;
2317  if (!(bitmaps= (uchar*) alloc_root(&outparam->mem_root, bitmap_size*3)))
2318  goto err;
2319  bitmap_init(&outparam->def_read_set,
2320  (my_bitmap_map*) bitmaps, share->fields, FALSE);
2321  bitmap_init(&outparam->def_write_set,
2322  (my_bitmap_map*) (bitmaps+bitmap_size), share->fields, FALSE);
2323  bitmap_init(&outparam->tmp_set,
2324  (my_bitmap_map*) (bitmaps+bitmap_size*2), share->fields, FALSE);
2325  outparam->default_column_bitmaps();
2326 
2327  /* The table struct is now initialized; Open the table */
2328  error= 2;
2329  if (db_stat)
2330  {
2331  int ha_err;
2332  if ((ha_err= (outparam->file->
2333  ha_open(outparam, share->normalized_path.str,
2334  (db_stat & HA_READ_ONLY ? O_RDONLY : O_RDWR),
2335  (db_stat & HA_OPEN_TEMPORARY ? HA_OPEN_TMP_TABLE :
2336  ((db_stat & HA_WAIT_IF_LOCKED) ||
2337  (specialflag & SPECIAL_WAIT_IF_LOCKED)) ?
2338  HA_OPEN_WAIT_IF_LOCKED :
2339  (db_stat & (HA_ABORT_IF_LOCKED | HA_GET_INFO)) ?
2340  HA_OPEN_ABORT_IF_LOCKED :
2341  HA_OPEN_IGNORE_IF_LOCKED) | ha_open_flags))))
2342  {
2343  /* Set a flag if the table is crashed and it can be auto. repaired */
2344  share->crashed= ((ha_err == HA_ERR_CRASHED_ON_USAGE) &&
2345  outparam->file->auto_repair() &&
2346  !(ha_open_flags & HA_OPEN_FOR_REPAIR));
2347 
2348  switch (ha_err)
2349  {
2350  case HA_ERR_NO_SUCH_TABLE:
2351  /*
2352  The table did not exists in storage engine, use same error message
2353  as if the .frm file didn't exist
2354  */
2355  error= 1;
2356  my_errno= ENOENT;
2357  break;
2358  case EMFILE:
2359  /*
2360  Too many files opened, use same error message as if the .frm
2361  file can't open
2362  */
2363  DBUG_PRINT("error", ("open file: %s failed, too many files opened (errno: %d)",
2364  share->normalized_path.str, ha_err));
2365  error= 1;
2366  my_errno= EMFILE;
2367  break;
2368  default:
2369  outparam->file->print_error(ha_err, MYF(0));
2370  error_reported= TRUE;
2371  if (ha_err == HA_ERR_TABLE_DEF_CHANGED)
2372  error= 7;
2373  break;
2374  }
2375  goto err; /* purecov: inspected */
2376  }
2377  }
2378 
2379 #if defined(HAVE_purify) && !defined(DBUG_OFF)
2380  memset(bitmaps, 0, bitmap_size*3);
2381 #endif
2382 
2383  if ((share->table_category == TABLE_CATEGORY_LOG) ||
2384  (share->table_category == TABLE_CATEGORY_RPL_INFO))
2385  {
2386  outparam->no_replicate= TRUE;
2387  }
2388  else if (outparam->file)
2389  {
2390  handler::Table_flags flags= outparam->file->ha_table_flags();
2391  outparam->no_replicate= ! test(flags & (HA_BINLOG_STMT_CAPABLE
2392  | HA_BINLOG_ROW_CAPABLE))
2393  || test(flags & HA_HAS_OWN_BINLOGGING);
2394  }
2395  else
2396  {
2397  outparam->no_replicate= FALSE;
2398  }
2399 
2400  thd->status_var.opened_tables++;
2401 
2402  DBUG_RETURN (0);
2403 
2404  err:
2405  if (! error_reported)
2406  open_table_error(share, error, my_errno, 0);
2407  delete outparam->file;
2408 #ifdef WITH_PARTITION_STORAGE_ENGINE
2409  if (outparam->part_info)
2410  free_items(outparam->part_info->item_free_list);
2411 #endif
2412  outparam->file= 0; // For easier error checking
2413  outparam->db_stat=0;
2414  free_root(&outparam->mem_root, MYF(0));
2415  my_free((void *) outparam->alias);
2416  DBUG_RETURN (error);
2417 }
2418 
2419 
2420 /*
2421  Free information allocated by openfrm
2422 
2423  SYNOPSIS
2424  closefrm()
2425  table TABLE object to free
2426  free_share Is 1 if we also want to free table_share
2427 */
2428 
2429 int closefrm(register TABLE *table, bool free_share)
2430 {
2431  int error=0;
2432  DBUG_ENTER("closefrm");
2433  DBUG_PRINT("enter", ("table: 0x%lx", (long) table));
2434 
2435  if (table->db_stat)
2436  error=table->file->ha_close();
2437  my_free((void *) table->alias);
2438  table->alias= 0;
2439  if (table->field)
2440  {
2441  for (Field **ptr=table->field ; *ptr ; ptr++)
2442  delete *ptr;
2443  table->field= 0;
2444  }
2445  delete table->file;
2446  table->file= 0; /* For easier errorchecking */
2447 #ifdef WITH_PARTITION_STORAGE_ENGINE
2448  if (table->part_info)
2449  {
2450  /* Allocated through table->mem_root, freed below */
2451  free_items(table->part_info->item_free_list);
2452  table->part_info->item_free_list= 0;
2453  table->part_info= 0;
2454  }
2455 #endif
2456  if (free_share)
2457  {
2458  if (table->s->tmp_table == NO_TMP_TABLE)
2459  release_table_share(table->s);
2460  else
2461  free_table_share(table->s);
2462  }
2463  free_root(&table->mem_root, MYF(0));
2464  DBUG_RETURN(error);
2465 }
2466 
2467 
2468 /* Deallocate temporary blob storage */
2469 
2470 void free_blobs(register TABLE *table)
2471 {
2472  uint *ptr, *end;
2473  for (ptr= table->s->blob_field, end=ptr + table->s->blob_fields ;
2474  ptr != end ;
2475  ptr++)
2476  {
2477  /*
2478  Reduced TABLE objects which are used by row-based replication for
2479  type conversion might have some fields missing. Skip freeing BLOB
2480  buffers for such missing fields.
2481  */
2482  if (table->field[*ptr])
2483  ((Field_blob*) table->field[*ptr])->free();
2484  }
2485 }
2486 
2487 
2497 void free_field_buffers_larger_than(TABLE *table, uint32 size)
2498 {
2499  uint *ptr, *end;
2500  for (ptr= table->s->blob_field, end=ptr + table->s->blob_fields ;
2501  ptr != end ;
2502  ptr++)
2503  {
2504  Field_blob *blob= (Field_blob*) table->field[*ptr];
2505  if (blob->get_field_buffer_size() > size)
2506  blob->free();
2507  }
2508 }
2509 
2520 static ulong get_form_pos(File file, uchar *head)
2521 {
2522  uchar *pos, *buf;
2523  uint names, length;
2524  ulong ret_value=0;
2525  DBUG_ENTER("get_form_pos");
2526 
2527  names= uint2korr(head+8);
2528 
2529  if (!(names= uint2korr(head+8)))
2530  DBUG_RETURN(0);
2531 
2532  length= uint2korr(head+4);
2533 
2534  mysql_file_seek(file, 64L, MY_SEEK_SET, MYF(0));
2535 
2536  if (!(buf= (uchar*) my_malloc(length+names*4, MYF(MY_WME))))
2537  DBUG_RETURN(0);
2538 
2539  if (mysql_file_read(file, buf, length+names*4, MYF(MY_NABP)))
2540  {
2541  my_free(buf);
2542  DBUG_RETURN(0);
2543  }
2544 
2545  pos= buf+length;
2546  ret_value= uint4korr(pos);
2547 
2548  my_free(buf);
2549 
2550  DBUG_RETURN(ret_value);
2551 }
2552 
2553 
2554 /*
2555  Read string from a file with malloc
2556 
2557  NOTES:
2558  We add an \0 at end of the read string to make reading of C strings easier
2559 */
2560 
2561 int read_string(File file, uchar**to, size_t length)
2562 {
2563  DBUG_ENTER("read_string");
2564 
2565  my_free(*to);
2566  if (!(*to= (uchar*) my_malloc(length+1,MYF(MY_WME))) ||
2567  mysql_file_read(file, *to, length, MYF(MY_NABP)))
2568  {
2569  my_free(*to); /* purecov: inspected */
2570  *to= 0; /* purecov: inspected */
2571  DBUG_RETURN(1); /* purecov: inspected */
2572  }
2573  *((char*) *to+length)= '\0';
2574  DBUG_RETURN (0);
2575 } /* read_string */
2576 
2577 
2578  /* Add a new form to a form file */
2579 
2580 ulong make_new_entry(File file, uchar *fileinfo, TYPELIB *formnames,
2581  const char *newname)
2582 {
2583  uint i,bufflength,maxlength,n_length,length,names;
2584  ulong endpos,newpos;
2585  uchar buff[IO_SIZE];
2586  uchar *pos;
2587  DBUG_ENTER("make_new_entry");
2588 
2589  length=(uint) strlen(newname)+1;
2590  n_length=uint2korr(fileinfo+4);
2591  maxlength=uint2korr(fileinfo+6);
2592  names=uint2korr(fileinfo+8);
2593  newpos=uint4korr(fileinfo+10);
2594 
2595  if (64+length+n_length+(names+1)*4 > maxlength)
2596  { /* Expand file */
2597  newpos+=IO_SIZE;
2598  int4store(fileinfo+10,newpos);
2599  /* Copy from file-end */
2600  endpos= (ulong) mysql_file_seek(file, 0L, MY_SEEK_END, MYF(0));
2601  bufflength= (uint) (endpos & (IO_SIZE-1)); /* IO_SIZE is a power of 2 */
2602 
2603  while (endpos > maxlength)
2604  {
2605  mysql_file_seek(file, (ulong) (endpos-bufflength), MY_SEEK_SET, MYF(0));
2606  if (mysql_file_read(file, buff, bufflength, MYF(MY_NABP+MY_WME)))
2607  DBUG_RETURN(0L);
2608  mysql_file_seek(file, (ulong) (endpos-bufflength+IO_SIZE), MY_SEEK_SET,
2609  MYF(0));
2610  if ((mysql_file_write(file, buff, bufflength, MYF(MY_NABP+MY_WME))))
2611  DBUG_RETURN(0);
2612  endpos-=bufflength; bufflength=IO_SIZE;
2613  }
2614  memset(buff, 0, IO_SIZE); /* Null new block */
2615  mysql_file_seek(file, (ulong) maxlength, MY_SEEK_SET, MYF(0));
2616  if (mysql_file_write(file, buff, bufflength, MYF(MY_NABP+MY_WME)))
2617  DBUG_RETURN(0L);
2618  maxlength+=IO_SIZE; /* Fix old ref */
2619  int2store(fileinfo+6,maxlength);
2620  for (i=names, pos= (uchar*) *formnames->type_names+n_length-1; i-- ;
2621  pos+=4)
2622  {
2623  endpos=uint4korr(pos)+IO_SIZE;
2624  int4store(pos,endpos);
2625  }
2626  }
2627 
2628  if (n_length == 1 )
2629  { /* First name */
2630  length++;
2631  (void) strxmov((char*) buff,"/",newname,"/",NullS);
2632  }
2633  else
2634  (void) strxmov((char*) buff,newname,"/",NullS); /* purecov: inspected */
2635  mysql_file_seek(file, 63L+(ulong) n_length, MY_SEEK_SET, MYF(0));
2636  if (mysql_file_write(file, buff, (size_t) length+1, MYF(MY_NABP+MY_WME)) ||
2637  (names && mysql_file_write(file,
2638  (uchar*) (*formnames->type_names+n_length-1),
2639  names*4, MYF(MY_NABP+MY_WME))) ||
2640  mysql_file_write(file, fileinfo+10, 4, MYF(MY_NABP+MY_WME)))
2641  DBUG_RETURN(0L); /* purecov: inspected */
2642 
2643  int2store(fileinfo+8,names+1);
2644  int2store(fileinfo+4,n_length+length);
2645  (void) mysql_file_chsize(file, newpos, 0, MYF(MY_WME));/* Append file with '\0' */
2646  DBUG_RETURN(newpos);
2647 } /* make_new_entry */
2648 
2649 
2650  /* error message when opening a form file */
2651 
2652 void open_table_error(TABLE_SHARE *share, int error, int db_errno, int errarg)
2653 {
2654  int err_no;
2655  char buff[FN_REFLEN];
2656  char errbuf[MYSYS_STRERROR_SIZE];
2657  myf errortype= ME_ERROR+ME_WAITTANG;
2658  DBUG_ENTER("open_table_error");
2659 
2660  switch (error) {
2661  case 7:
2662  case 1:
2663  if (db_errno == ENOENT)
2664  my_error(ER_NO_SUCH_TABLE, MYF(0), share->db.str, share->table_name.str);
2665  else
2666  {
2667  strxmov(buff, share->normalized_path.str, reg_ext, NullS);
2668  my_error((db_errno == EMFILE) ? ER_CANT_OPEN_FILE : ER_FILE_NOT_FOUND,
2669  errortype, buff,
2670  db_errno, my_strerror(errbuf, sizeof(errbuf), db_errno));
2671  }
2672  break;
2673  case 2:
2674  {
2675  handler *file= 0;
2676  const char *datext= "";
2677 
2678  if (share->db_type() != NULL)
2679  {
2680  if ((file= get_new_handler(share, current_thd->mem_root,
2681  share->db_type())))
2682  {
2683  if (!(datext= *file->bas_ext()))
2684  datext= "";
2685  }
2686  }
2687  err_no= (db_errno == ENOENT) ? ER_FILE_NOT_FOUND : (db_errno == EAGAIN) ?
2688  ER_FILE_USED : ER_CANT_OPEN_FILE;
2689  strxmov(buff, share->normalized_path.str, datext, NullS);
2690  my_error(err_no,errortype, buff,
2691  db_errno, my_strerror(errbuf, sizeof(errbuf), db_errno));
2692  delete file;
2693  break;
2694  }
2695  case 5:
2696  {
2697  const char *csname= get_charset_name((uint) errarg);
2698  char tmp[10];
2699  if (!csname || csname[0] =='?')
2700  {
2701  my_snprintf(tmp, sizeof(tmp), "#%d", errarg);
2702  csname= tmp;
2703  }
2704  my_printf_error(ER_UNKNOWN_COLLATION,
2705  "Unknown collation '%s' in table '%-.64s' definition",
2706  MYF(0), csname, share->table_name.str);
2707  break;
2708  }
2709  case 6:
2710  strxmov(buff, share->normalized_path.str, reg_ext, NullS);
2711  my_printf_error(ER_NOT_FORM_FILE,
2712  "Table '%-.64s' was created with a different version "
2713  "of MySQL and cannot be read",
2714  MYF(0), buff);
2715  break;
2716  case 8:
2717  break;
2718  case 9:
2719  /* Unknown FRM type read while preparing File_parser object for view*/
2720  my_error(ER_FRM_UNKNOWN_TYPE, MYF(0), share->path.str,
2721  share->view_def->type()->str);
2722  break;
2723  default: /* Better wrong error than none */
2724  case 4:
2725  strxmov(buff, share->normalized_path.str, reg_ext, NullS);
2726  my_error(ER_NOT_FORM_FILE, errortype, buff);
2727  break;
2728  }
2729  DBUG_VOID_RETURN;
2730 } /* open_table_error */
2731 
2732 
2733  /*
2734  ** fix a str_type to a array type
2735  ** typeparts separated with some char. differents types are separated
2736  ** with a '\0'
2737  */
2738 
2739 static void
2740 fix_type_pointers(const char ***array, TYPELIB *point_to_type, uint types,
2741  char **names)
2742 {
2743  char *type_name, *ptr;
2744  char chr;
2745 
2746  ptr= *names;
2747  while (types--)
2748  {
2749  point_to_type->name=0;
2750  point_to_type->type_names= *array;
2751 
2752  if ((chr= *ptr)) /* Test if empty type */
2753  {
2754  while ((type_name=strchr(ptr+1,chr)) != NullS)
2755  {
2756  *((*array)++) = ptr+1;
2757  *type_name= '\0'; /* End string */
2758  ptr=type_name;
2759  }
2760  ptr+=2; /* Skip end mark and last 0 */
2761  }
2762  else
2763  ptr++;
2764  point_to_type->count= (uint) (*array - point_to_type->type_names);
2765  point_to_type++;
2766  *((*array)++)= NullS; /* End of type */
2767  }
2768  *names=ptr; /* Update end */
2769  return;
2770 } /* fix_type_pointers */
2771 
2772 
2773 TYPELIB *typelib(MEM_ROOT *mem_root, List<String> &strings)
2774 {
2775  TYPELIB *result= (TYPELIB*) alloc_root(mem_root, sizeof(TYPELIB));
2776  if (!result)
2777  return 0;
2778  result->count=strings.elements;
2779  result->name="";
2780  uint nbytes= (sizeof(char*) + sizeof(uint)) * (result->count + 1);
2781  if (!(result->type_names= (const char**) alloc_root(mem_root, nbytes)))
2782  return 0;
2783  result->type_lengths= (uint*) (result->type_names + result->count + 1);
2784  List_iterator<String> it(strings);
2785  String *tmp;
2786  for (uint i=0; (tmp=it++) ; i++)
2787  {
2788  result->type_names[i]= tmp->ptr();
2789  result->type_lengths[i]= tmp->length();
2790  }
2791  result->type_names[result->count]= 0; // End marker
2792  result->type_lengths[result->count]= 0;
2793  return result;
2794 }
2795 
2796 
2797 /*
2798  Search after a field with given start & length
2799  If an exact field isn't found, return longest field with starts
2800  at right position.
2801 
2802  NOTES
2803  This is needed because in some .frm fields 'fieldnr' was saved wrong
2804 
2805  RETURN
2806  0 error
2807  # field number +1
2808 */
2809 
2810 static uint find_field(Field **fields, uchar *record, uint start, uint length)
2811 {
2812  Field **field;
2813  uint i, pos;
2814 
2815  pos= 0;
2816  for (field= fields, i=1 ; *field ; i++,field++)
2817  {
2818  if ((*field)->offset(record) == start)
2819  {
2820  if ((*field)->key_length() == length)
2821  return (i);
2822  if (!pos || fields[pos-1]->pack_length() <
2823  (*field)->pack_length())
2824  pos= i;
2825  }
2826  }
2827  return (pos);
2828 }
2829 
2830 
2831  /* Check that the integer is in the internal */
2832 
2833 int set_zone(register int nr, int min_zone, int max_zone)
2834 {
2835  if (nr<=min_zone)
2836  return (min_zone);
2837  if (nr>=max_zone)
2838  return (max_zone);
2839  return (nr);
2840 } /* set_zone */
2841 
2842  /* Adjust number to next larger disk buffer */
2843 
2844 ulong next_io_size(register ulong pos)
2845 {
2846  reg2 ulong offset;
2847  if ((offset= pos & (IO_SIZE-1)))
2848  return pos-offset+IO_SIZE;
2849  return pos;
2850 } /* next_io_size */
2851 
2852 
2853 /*
2854  Store an SQL quoted string.
2855 
2856  SYNOPSIS
2857  append_unescaped()
2858  res result String
2859  pos string to be quoted
2860  length it's length
2861 
2862  NOTE
2863  This function works correctly with utf8 or single-byte charset strings.
2864  May fail with some multibyte charsets though.
2865 */
2866 
2867 void append_unescaped(String *res, const char *pos, uint length)
2868 {
2869  const char *end= pos+length;
2870  res->append('\'');
2871 
2872  for (; pos != end ; pos++)
2873  {
2874 #if defined(USE_MB) && MYSQL_VERSION_ID < 40100
2875  uint mblen;
2876  if (use_mb(default_charset_info) &&
2877  (mblen= my_ismbchar(default_charset_info, pos, end)))
2878  {
2879  res->append(pos, mblen);
2880  pos+= mblen;
2881  continue;
2882  }
2883 #endif
2884 
2885  switch (*pos) {
2886  case 0: /* Must be escaped for 'mysql' */
2887  res->append('\\');
2888  res->append('0');
2889  break;
2890  case '\n': /* Must be escaped for logs */
2891  res->append('\\');
2892  res->append('n');
2893  break;
2894  case '\r':
2895  res->append('\\'); /* This gives better readability */
2896  res->append('r');
2897  break;
2898  case '\\':
2899  res->append('\\'); /* Because of the sql syntax */
2900  res->append('\\');
2901  break;
2902  case '\'':
2903  res->append('\''); /* Because of the sql syntax */
2904  res->append('\'');
2905  break;
2906  default:
2907  res->append(*pos);
2908  break;
2909  }
2910  }
2911  res->append('\'');
2912 }
2913 
2914 
2915  /* Create a .frm file */
2916 
2917 File create_frm(THD *thd, const char *name, const char *db,
2918  const char *table, uint reclength, uchar *fileinfo,
2919  HA_CREATE_INFO *create_info, uint keys, KEY *key_info)
2920 {
2921  register File file;
2922  ulong length;
2923  uchar fill[IO_SIZE];
2924  int create_flags= O_RDWR | O_TRUNC;
2925  ulong key_comment_total_bytes= 0;
2926  uint i;
2927 
2928  if (create_info->options & HA_LEX_CREATE_TMP_TABLE)
2929  create_flags|= O_EXCL | O_NOFOLLOW;
2930 
2931  /* Fix this when we have new .frm files; Current limit is 4G rows (QQ) */
2932  if (create_info->max_rows > UINT_MAX32)
2933  create_info->max_rows= UINT_MAX32;
2934  if (create_info->min_rows > UINT_MAX32)
2935  create_info->min_rows= UINT_MAX32;
2936 
2937  if ((file= mysql_file_create(key_file_frm,
2938  name, CREATE_MODE, create_flags, MYF(0))) >= 0)
2939  {
2940  uint key_length, tmp_key_length, tmp, csid;
2941  memset(fileinfo, 0, 64);
2942  /* header */
2943  fileinfo[0]=(uchar) 254;
2944  fileinfo[1]= 1;
2945  fileinfo[2]= FRM_VER+3+ test(create_info->varchar);
2946 
2947  fileinfo[3]= (uchar) ha_legacy_type(
2948  ha_checktype(thd,ha_legacy_type(create_info->db_type),0,0));
2949  fileinfo[4]=1;
2950  int2store(fileinfo+6,IO_SIZE); /* Next block starts here */
2951  /*
2952  Keep in sync with pack_keys() in unireg.cc
2953  For each key:
2954  8 bytes for the key header
2955  9 bytes for each key-part (MAX_REF_PARTS)
2956  NAME_LEN bytes for the name
2957  1 byte for the NAMES_SEP_CHAR (before the name)
2958  For all keys:
2959  6 bytes for the header
2960  1 byte for the NAMES_SEP_CHAR (after the last name)
2961  9 extra bytes (padding for safety? alignment?)
2962  */
2963  for (i= 0; i < keys; i++)
2964  {
2965  DBUG_ASSERT(test(key_info[i].flags & HA_USES_COMMENT) ==
2966  (key_info[i].comment.length > 0));
2967  if (key_info[i].flags & HA_USES_COMMENT)
2968  key_comment_total_bytes += 2 + key_info[i].comment.length;
2969  }
2970 
2971  key_length= keys * (8 + MAX_REF_PARTS * 9 + NAME_LEN + 1) + 16
2972  + key_comment_total_bytes;
2973 
2974  length= next_io_size((ulong) (IO_SIZE+key_length+reclength+
2975  create_info->extra_size));
2976  int4store(fileinfo+10,length);
2977  tmp_key_length= (key_length < 0xffff) ? key_length : 0xffff;
2978  int2store(fileinfo+14,tmp_key_length);
2979  int2store(fileinfo+16,reclength);
2980  int4store(fileinfo+18,create_info->max_rows);
2981  int4store(fileinfo+22,create_info->min_rows);
2982  /* fileinfo[26] is set in mysql_create_frm() */
2983  fileinfo[27]=2; // Use long pack-fields
2984  /* fileinfo[28 & 29] is set to key_info_length in mysql_create_frm() */
2985  create_info->table_options|=HA_OPTION_LONG_BLOB_PTR; // Use portable blob pointers
2986  int2store(fileinfo+30,create_info->table_options);
2987  fileinfo[32]=0; // No filename anymore
2988  fileinfo[33]=5; // Mark for 5.0 frm file
2989  int4store(fileinfo+34,create_info->avg_row_length);
2990  csid= (create_info->default_table_charset ?
2991  create_info->default_table_charset->number : 0);
2992  fileinfo[38]= (uchar) csid;
2993  /*
2994  In future versions, we will store in fileinfo[39] the values of the
2995  TRANSACTIONAL and PAGE_CHECKSUM clauses of CREATE TABLE.
2996  */
2997  fileinfo[39]= 0;
2998  fileinfo[40]= (uchar) create_info->row_type;
2999  /* Bytes 41-46 were for RAID support; now reused for other purposes */
3000  fileinfo[41]= (uchar) (csid >> 8);
3001  int2store(fileinfo+42, create_info->stats_sample_pages & 0xffff);
3002  fileinfo[44]= (uchar) create_info->stats_auto_recalc;
3003  fileinfo[45]= 0;
3004  fileinfo[46]= 0;
3005  int4store(fileinfo+47, key_length);
3006  tmp= MYSQL_VERSION_ID; // Store to avoid warning from int4store
3007  int4store(fileinfo+51, tmp);
3008  int4store(fileinfo+55, create_info->extra_size);
3009  /*
3010  59-60 is reserved for extra_rec_buf_length,
3011  61 for default_part_db_type
3012  */
3013  int2store(fileinfo+62, create_info->key_block_size);
3014  memset(fill, 0, IO_SIZE);
3015  for (; length > IO_SIZE ; length-= IO_SIZE)
3016  {
3017  if (mysql_file_write(file, fill, IO_SIZE, MYF(MY_WME | MY_NABP)))
3018  {
3019  (void) mysql_file_close(file, MYF(0));
3020  (void) mysql_file_delete(key_file_frm, name, MYF(0));
3021  return(-1);
3022  }
3023  }
3024  }
3025  else
3026  {
3027  if (my_errno == ENOENT)
3028  my_error(ER_BAD_DB_ERROR,MYF(0),db);
3029  else
3030  my_error(ER_CANT_CREATE_TABLE,MYF(0),table,my_errno);
3031  }
3032  return (file);
3033 } /* create_frm */
3034 
3035 
3036 void update_create_info_from_table(HA_CREATE_INFO *create_info, TABLE *table)
3037 {
3038  TABLE_SHARE *share= table->s;
3039  DBUG_ENTER("update_create_info_from_table");
3040 
3041  create_info->max_rows= share->max_rows;
3042  create_info->min_rows= share->min_rows;
3043  create_info->table_options= share->db_create_options;
3044  create_info->avg_row_length= share->avg_row_length;
3045  create_info->row_type= share->row_type;
3046  create_info->default_table_charset= share->table_charset;
3047  create_info->table_charset= 0;
3048  create_info->comment= share->comment;
3049  create_info->storage_media= share->default_storage_media;
3050  create_info->tablespace= share->tablespace;
3051 
3052  DBUG_VOID_RETURN;
3053 }
3054 
3055 int
3056 rename_file_ext(const char * from,const char * to,const char * ext)
3057 {
3058  char from_b[FN_REFLEN],to_b[FN_REFLEN];
3059  (void) strxmov(from_b,from,ext,NullS);
3060  (void) strxmov(to_b,to,ext,NullS);
3061  return (mysql_file_rename(key_file_frm, from_b, to_b, MYF(MY_WME)));
3062 }
3063 
3064 
3065 /*
3066  Allocate string field in MEM_ROOT and return it as String
3067 
3068  SYNOPSIS
3069  get_field()
3070  mem MEM_ROOT for allocating
3071  field Field for retrieving of string
3072  res result String
3073 
3074  RETURN VALUES
3075  1 string is empty
3076  0 all ok
3077 */
3078 
3079 bool get_field(MEM_ROOT *mem, Field *field, String *res)
3080 {
3081  char buff[MAX_FIELD_WIDTH], *to;
3082  String str(buff,sizeof(buff),&my_charset_bin);
3083  uint length;
3084 
3085  field->val_str(&str);
3086  if (!(length= str.length()))
3087  {
3088  res->length(0);
3089  return 1;
3090  }
3091  if (!(to= strmake_root(mem, str.ptr(), length)))
3092  length= 0; // Safety fix
3093  res->set(to, length, field->charset());
3094  return 0;
3095 }
3096 
3097 
3098 /*
3099  Allocate string field in MEM_ROOT and return it as NULL-terminated string
3100 
3101  SYNOPSIS
3102  get_field()
3103  mem MEM_ROOT for allocating
3104  field Field for retrieving of string
3105 
3106  RETURN VALUES
3107  NullS string is empty
3108  # pointer to NULL-terminated string value of field
3109 */
3110 
3111 char *get_field(MEM_ROOT *mem, Field *field)
3112 {
3113  char buff[MAX_FIELD_WIDTH], *to;
3114  String str(buff,sizeof(buff),&my_charset_bin);
3115  uint length;
3116 
3117  field->val_str(&str);
3118  length= str.length();
3119  if (!length || !(to= (char*) alloc_root(mem,length+1)))
3120  return NullS;
3121  memcpy(to,str.ptr(),(uint) length);
3122  to[length]=0;
3123  return to;
3124 }
3125 
3126 /*
3127  DESCRIPTION
3128  given a buffer with a key value, and a map of keyparts
3129  that are present in this value, returns the length of the value
3130 */
3131 uint calculate_key_len(TABLE *table, uint key, const uchar *buf,
3132  key_part_map keypart_map)
3133 {
3134  /* works only with key prefixes */
3135  DBUG_ASSERT(((keypart_map + 1) & keypart_map) == 0);
3136 
3137  KEY *key_info= table->key_info + key;
3138  KEY_PART_INFO *key_part= key_info->key_part;
3139  KEY_PART_INFO *end_key_part= key_part + actual_key_parts(key_info);
3140  uint length= 0;
3141 
3142  while (key_part < end_key_part && keypart_map)
3143  {
3144  length+= key_part->store_length;
3145  keypart_map >>= 1;
3146  key_part++;
3147  }
3148  return length;
3149 }
3150 
3169 enum_ident_name_check check_and_convert_db_name(LEX_STRING *org_name,
3170  bool preserve_lettercase)
3171 {
3172  char *name= org_name->str;
3173  uint name_length= org_name->length;
3174  bool check_for_path_chars;
3175  enum_ident_name_check ident_check_status;
3176 
3177  if (!name_length || name_length > NAME_LEN)
3178  {
3179  my_error(ER_WRONG_DB_NAME, MYF(0), org_name->str);
3180  return IDENT_NAME_WRONG;
3181  }
3182 
3183  if ((check_for_path_chars= check_mysql50_prefix(name)))
3184  {
3185  name+= MYSQL50_TABLE_NAME_PREFIX_LENGTH;
3186  name_length-= MYSQL50_TABLE_NAME_PREFIX_LENGTH;
3187  }
3188 
3189  if (!preserve_lettercase && lower_case_table_names && name != any_db)
3190  my_casedn_str(files_charset_info, name);
3191 
3192  ident_check_status= check_table_name(name, name_length, check_for_path_chars);
3193  if (ident_check_status == IDENT_NAME_WRONG)
3194  my_error(ER_WRONG_DB_NAME, MYF(0), org_name->str);
3195  else if (ident_check_status == IDENT_NAME_TOO_LONG)
3196  my_error(ER_TOO_LONG_IDENT, MYF(0), org_name->str);
3197  return ident_check_status;
3198 }
3199 
3200 
3217 enum_ident_name_check check_table_name(const char *name, size_t length,
3218  bool check_for_path_chars)
3219 {
3220  // name length in symbols
3221  size_t name_length= 0;
3222  const char *end= name+length;
3223  if (!length || length > NAME_LEN)
3224  return IDENT_NAME_WRONG;
3225 #if defined(USE_MB) && defined(USE_MB_IDENT)
3226  bool last_char_is_space= FALSE;
3227 #else
3228  if (name[length-1]==' ')
3229  return IDENT_NAME_WRONG;
3230 #endif
3231 
3232  while (name != end)
3233  {
3234 #if defined(USE_MB) && defined(USE_MB_IDENT)
3235  last_char_is_space= my_isspace(system_charset_info, *name);
3236  if (use_mb(system_charset_info))
3237  {
3238  int len=my_ismbchar(system_charset_info, name, end);
3239  if (len)
3240  {
3241  name += len;
3242  name_length++;
3243  continue;
3244  }
3245  }
3246 #endif
3247  if (check_for_path_chars &&
3248  (*name == '/' || *name == '\\' || *name == '~' || *name == FN_EXTCHAR))
3249  return IDENT_NAME_WRONG;
3250  name++;
3251  name_length++;
3252  }
3253 #if defined(USE_MB) && defined(USE_MB_IDENT)
3254  if (last_char_is_space)
3255  return IDENT_NAME_WRONG;
3256  else if (name_length > NAME_CHAR_LEN)
3257  return IDENT_NAME_TOO_LONG;
3258 #endif
3259  return IDENT_NAME_OK;
3260 }
3261 
3262 
3263 bool check_column_name(const char *name)
3264 {
3265  // name length in symbols
3266  size_t name_length= 0;
3267  bool last_char_is_space= TRUE;
3268 
3269  while (*name)
3270  {
3271 #if defined(USE_MB) && defined(USE_MB_IDENT)
3272  last_char_is_space= my_isspace(system_charset_info, *name);
3273  if (use_mb(system_charset_info))
3274  {
3275  int len=my_ismbchar(system_charset_info, name,
3276  name+system_charset_info->mbmaxlen);
3277  if (len)
3278  {
3279  name += len;
3280  name_length++;
3281  continue;
3282  }
3283  }
3284 #else
3285  last_char_is_space= *name==' ';
3286 #endif
3287  if (*name == NAMES_SEP_CHAR)
3288  return 1;
3289  name++;
3290  name_length++;
3291  }
3292  /* Error if empty or too long column name */
3293  return last_char_is_space || (name_length > NAME_CHAR_LEN);
3294 }
3295 
3296 
3314 bool
3316 {
3317  uint i;
3318  my_bool error= FALSE;
3319  const TABLE_FIELD_TYPE *field_def= table_def->field;
3320  DBUG_ENTER("table_check_intact");
3321  DBUG_PRINT("info",("table: %s expected_count: %d",
3322  table->alias, table_def->count));
3323 
3324  /* Whether the table definition has already been validated. */
3325  if (table->s->table_field_def_cache == table_def)
3326  DBUG_RETURN(FALSE);
3327 
3328  if (table->s->fields != table_def->count)
3329  {
3330  DBUG_PRINT("info", ("Column count has changed, checking the definition"));
3331 
3332  /* previous MySQL version */
3333  if (MYSQL_VERSION_ID > table->s->mysql_version)
3334  {
3335  report_error(ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE,
3336  ER(ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE),
3337  table->alias, table_def->count, table->s->fields,
3338  static_cast<int>(table->s->mysql_version),
3339  MYSQL_VERSION_ID);
3340  DBUG_RETURN(TRUE);
3341  }
3342  else if (MYSQL_VERSION_ID == table->s->mysql_version)
3343  {
3344  report_error(ER_COL_COUNT_DOESNT_MATCH_CORRUPTED_V2,
3345  ER(ER_COL_COUNT_DOESNT_MATCH_CORRUPTED_V2),
3346  table->s->db.str, table->s->table_name.str,
3347  table_def->count, table->s->fields);
3348  DBUG_RETURN(TRUE);
3349  }
3350  /*
3351  Something has definitely changed, but we're running an older
3352  version of MySQL with new system tables.
3353  Let's check column definitions. If a column was added at
3354  the end of the table, then we don't care much since such change
3355  is backward compatible.
3356  */
3357  }
3358  char buffer[STRING_BUFFER_USUAL_SIZE];
3359  for (i=0 ; i < table_def->count; i++, field_def++)
3360  {
3361  String sql_type(buffer, sizeof(buffer), system_charset_info);
3362  sql_type.length(0);
3363  if (i < table->s->fields)
3364  {
3365  Field *field= table->field[i];
3366 
3367  if (strncmp(field->field_name, field_def->name.str,
3368  field_def->name.length))
3369  {
3370  /*
3371  Name changes are not fatal, we use ordinal numbers to access columns.
3372  Still this can be a sign of a tampered table, output an error
3373  to the error log.
3374  */
3375  report_error(0, "Incorrect definition of table %s.%s: "
3376  "expected column '%s' at position %d, found '%s'.",
3377  table->s->db.str, table->alias, field_def->name.str, i,
3378  field->field_name);
3379  }
3380  field->sql_type(sql_type);
3381  /*
3382  Generally, if column types don't match, then something is
3383  wrong.
3384 
3385  However, we only compare column definitions up to the
3386  length of the original definition, since we consider the
3387  following definitions compatible:
3388 
3389  1. DATETIME and DATETIM
3390  2. INT(11) and INT(11
3391  3. SET('one', 'two') and SET('one', 'two', 'more')
3392 
3393  For SETs or ENUMs, if the same prefix is there it's OK to
3394  add more elements - they will get higher ordinal numbers and
3395  the new table definition is backward compatible with the
3396  original one.
3397  */
3398  if (strncmp(sql_type.c_ptr_safe(), field_def->type.str,
3399  field_def->type.length - 1))
3400  {
3401  report_error(0, "Incorrect definition of table %s.%s: "
3402  "expected column '%s' at position %d to have type "
3403  "%s, found type %s.", table->s->db.str, table->alias,
3404  field_def->name.str, i, field_def->type.str,
3405  sql_type.c_ptr_safe());
3406  error= TRUE;
3407  }
3408  else if (field_def->cset.str && !field->has_charset())
3409  {
3410  report_error(0, "Incorrect definition of table %s.%s: "
3411  "expected the type of column '%s' at position %d "
3412  "to have character set '%s' but the type has no "
3413  "character set.", table->s->db.str, table->alias,
3414  field_def->name.str, i, field_def->cset.str);
3415  error= TRUE;
3416  }
3417  else if (field_def->cset.str &&
3418  strcmp(field->charset()->csname, field_def->cset.str))
3419  {
3420  report_error(0, "Incorrect definition of table %s.%s: "
3421  "expected the type of column '%s' at position %d "
3422  "to have character set '%s' but found "
3423  "character set '%s'.", table->s->db.str, table->alias,
3424  field_def->name.str, i, field_def->cset.str,
3425  field->charset()->csname);
3426  error= TRUE;
3427  }
3428  }
3429  else
3430  {
3431  report_error(0, "Incorrect definition of table %s.%s: "
3432  "expected column '%s' at position %d to have type %s "
3433  " but the column is not found.",
3434  table->s->db.str, table->alias,
3435  field_def->name.str, i, field_def->type.str);
3436  error= TRUE;
3437  }
3438  }
3439 
3440  if (! error)
3441  table->s->table_field_def_cache= table_def;
3442 
3443  DBUG_RETURN(error);
3444 }
3445 
3446 
3457 {
3458  return m_share->visit_subgraph(this, gvisitor);
3459 }
3460 
3461 
3462 uint Wait_for_flush::get_deadlock_weight() const
3463 {
3464  return m_deadlock_weight;
3465 }
3466 
3467 
3481  MDL_wait_for_graph_visitor *gvisitor)
3482 {
3483  TABLE *table;
3484  MDL_context *src_ctx= wait_for_flush->get_ctx();
3485  bool result= TRUE;
3486  bool locked= FALSE;
3487 
3488  /*
3489  To protect used_tables list from being concurrently modified
3490  while we are iterating through it we acquire LOCK_open.
3491  This does not introduce deadlocks in the deadlock detector
3492  because we won't try to acquire LOCK_open while
3493  holding a write-lock on MDL_lock::m_rwlock.
3494  */
3495  if (gvisitor->m_lock_open_count++ == 0)
3496  {
3497  locked= TRUE;
3498  table_cache_manager.lock_all_and_tdc();
3499  }
3500 
3501  Table_cache_iterator tables_it(this);
3502 
3503  /*
3504  In case of multiple searches running in parallel, avoid going
3505  over the same loop twice and shortcut the search.
3506  Do it after taking the lock to weed out unnecessary races.
3507  */
3508  if (src_ctx->m_wait.get_status() != MDL_wait::EMPTY)
3509  {
3510  result= FALSE;
3511  goto end;
3512  }
3513 
3514  if (gvisitor->enter_node(src_ctx))
3515  goto end;
3516 
3517  while ((table= tables_it++))
3518  {
3519  if (gvisitor->inspect_edge(&table->in_use->mdl_context))
3520  {
3521  goto end_leave_node;
3522  }
3523  }
3524 
3525  tables_it.rewind();
3526  while ((table= tables_it++))
3527  {
3528  if (table->in_use->mdl_context.visit_subgraph(gvisitor))
3529  {
3530  goto end_leave_node;
3531  }
3532  }
3533 
3534  result= FALSE;
3535 
3536 end_leave_node:
3537  gvisitor->leave_node(src_ctx);
3538 
3539 end:
3540  gvisitor->m_lock_open_count--;
3541  if (locked)
3542  {
3543  DBUG_ASSERT(gvisitor->m_lock_open_count == 0);
3544  table_cache_manager.unlock_all_and_tdc();
3545  }
3546 
3547  return result;
3548 }
3549 
3550 
3568 bool TABLE_SHARE::wait_for_old_version(THD *thd, struct timespec *abstime,
3569  uint deadlock_weight)
3570 {
3571  MDL_context *mdl_context= &thd->mdl_context;
3572  Wait_for_flush ticket(mdl_context, this, deadlock_weight);
3573  MDL_wait::enum_wait_status wait_status;
3574 
3576  /*
3577  We should enter this method only when share's version is not
3578  up to date and the share is referenced. Otherwise our
3579  thread will never be woken up from wait.
3580  */
3581  DBUG_ASSERT(version != refresh_version && ref_count != 0);
3582 
3583  m_flush_tickets.push_front(&ticket);
3584 
3585  mdl_context->m_wait.reset_status();
3586 
3588 
3589  mdl_context->will_wait_for(&ticket);
3590 
3591  mdl_context->find_deadlock();
3592 
3593  wait_status= mdl_context->m_wait.timed_wait(thd, abstime, TRUE,
3594  &stage_waiting_for_table_flush);
3595 
3596  mdl_context->done_waiting_for();
3597 
3599 
3600  m_flush_tickets.remove(&ticket);
3601 
3602  if (m_flush_tickets.is_empty() && ref_count == 0)
3603  {
3604  /*
3605  If our thread was the last one using the share,
3606  we must destroy it here.
3607  */
3608  destroy();
3609  }
3610 
3611  /*
3612  In cases when our wait was aborted by KILL statement,
3613  a deadlock or a timeout, the share might still be referenced,
3614  so we don't delete it. Note, that we can't determine this
3615  condition by checking wait_status alone, since, for example,
3616  a timeout can happen after all references to the table share
3617  were released, but before the share is removed from the
3618  cache and we receive the notification. This is why
3619  we first destroy the share, and then look at
3620  wait_status.
3621  */
3622  switch (wait_status)
3623  {
3624  case MDL_wait::GRANTED:
3625  return FALSE;
3626  case MDL_wait::VICTIM:
3627  my_error(ER_LOCK_DEADLOCK, MYF(0));
3628  return TRUE;
3629  case MDL_wait::TIMEOUT:
3630  my_error(ER_LOCK_WAIT_TIMEOUT, MYF(0));
3631  return TRUE;
3632  case MDL_wait::KILLED:
3633  return TRUE;
3634  default:
3635  DBUG_ASSERT(0);
3636  return TRUE;
3637  }
3638 }
3639 
3640 
3652 void TABLE::init(THD *thd, TABLE_LIST *tl)
3653 {
3654  DBUG_ASSERT(s->ref_count > 0 || s->tmp_table != NO_TMP_TABLE);
3655 
3656  if (thd->lex->need_correct_ident())
3657  alias_name_used= my_strcasecmp(table_alias_charset,
3658  s->table_name.str,
3659  tl->alias);
3660  /* Fix alias if table name changes. */
3661  if (strcmp(alias, tl->alias))
3662  {
3663  uint length= (uint) strlen(tl->alias)+1;
3664  alias= (char*) my_realloc((char*) alias, length, MYF(MY_WME));
3665  memcpy((char*) alias, tl->alias, length);
3666  }
3667 
3668  tablenr= thd->current_tablenr++;
3669  used_fields= 0;
3670  const_table= 0;
3671  null_row= 0;
3672  maybe_null= 0;
3673  force_index= 0;
3674  force_index_order= 0;
3675  force_index_group= 0;
3676  status= STATUS_GARBAGE | STATUS_NOT_FOUND;
3677  insert_values= 0;
3678  fulltext_searched= 0;
3679  file->ft_handler= 0;
3680  reginfo.impossible_range= 0;
3681 
3682  /* Catch wrong handling of the auto_increment_field_not_null. */
3683  DBUG_ASSERT(!auto_increment_field_not_null);
3684  auto_increment_field_not_null= FALSE;
3685 
3686  pos_in_table_list= tl;
3687 
3688  clear_column_bitmaps();
3689 
3690  DBUG_ASSERT(key_read == 0);
3691 
3692  /* Tables may be reused in a sub statement. */
3693  DBUG_ASSERT(!file->extra(HA_EXTRA_IS_ATTACHED_CHILDREN));
3694 }
3695 
3696 
3697 /*
3698  Create Item_field for each column in the table.
3699 
3700  SYNPOSIS
3701  TABLE::fill_item_list()
3702  item_list a pointer to an empty list used to store items
3703 
3704  DESCRIPTION
3705  Create Item_field object for each column in the table and
3706  initialize it with the corresponding Field. New items are
3707  created in the current THD memory root.
3708 
3709  RETURN VALUE
3710  0 success
3711  1 out of memory
3712 */
3713 
3714 bool TABLE::fill_item_list(List<Item> *item_list) const
3715 {
3716  /*
3717  All Item_field's created using a direct pointer to a field
3718  are fixed in Item_field constructor.
3719  */
3720  for (Field **ptr= field; *ptr; ptr++)
3721  {
3722  Item_field *item= new Item_field(*ptr);
3723  if (!item || item_list->push_back(item))
3724  return TRUE;
3725  }
3726  return FALSE;
3727 }
3728 
3729 /*
3730  Reset an existing list of Item_field items to point to the
3731  Fields of this table.
3732 
3733  SYNPOSIS
3734  TABLE::fill_item_list()
3735  item_list a non-empty list with Item_fields
3736 
3737  DESCRIPTION
3738  This is a counterpart of fill_item_list used to redirect
3739  Item_fields to the fields of a newly created table.
3740  The caller must ensure that number of items in the item_list
3741  is the same as the number of columns in the table.
3742 */
3743 
3744 void TABLE::reset_item_list(List<Item> *item_list) const
3745 {
3746  List_iterator_fast<Item> it(*item_list);
3747  for (Field **ptr= field; *ptr; ptr++)
3748  {
3749  Item_field *item_field= (Item_field*) it++;
3750  DBUG_ASSERT(item_field != 0);
3751  item_field->reset_field(*ptr);
3752  }
3753 }
3754 
3768  const char *alias,
3769  TABLE_LIST *embedding,
3770  List<TABLE_LIST> *belongs_to,
3771  class st_select_lex *select)
3772 {
3773  DBUG_ASSERT(belongs_to && select);
3774 
3775  TABLE_LIST *const join_nest=
3776  (TABLE_LIST *) alloc_root(allocator, ALIGN_SIZE(sizeof(TABLE_LIST))+
3777  sizeof(NESTED_JOIN));
3778  if (join_nest == NULL)
3779  return NULL;
3780 
3781  memset(join_nest, 0, ALIGN_SIZE(sizeof(TABLE_LIST)) + sizeof(NESTED_JOIN));
3782  join_nest->nested_join=
3783  (NESTED_JOIN *) ((uchar *)join_nest + ALIGN_SIZE(sizeof(TABLE_LIST)));
3784 
3785  join_nest->db= (char *)"";
3786  join_nest->db_length= 0;
3787  join_nest->table_name= (char *)"";
3788  join_nest->table_name_length= 0;
3789  join_nest->alias= (char *)alias;
3790 
3791  join_nest->embedding= embedding;
3792  join_nest->join_list= belongs_to;
3793  join_nest->select_lex= select;
3794 
3795  join_nest->nested_join->join_list.empty();
3796 
3797  return join_nest;
3798 }
3799 /*
3800  calculate md5 of query
3801 
3802  SYNOPSIS
3803  TABLE_LIST::calc_md5()
3804  buffer buffer for md5 writing
3805 */
3806 
3807 void TABLE_LIST::calc_md5(char *buffer)
3808 {
3809  uchar digest[MD5_HASH_SIZE];
3810  compute_md5_hash((char *) digest, (const char *) select_stmt.str,
3811  select_stmt.length);
3812  array_to_hex((char *) buffer, digest, MD5_HASH_SIZE);
3813 }
3814 
3815 
3840 {
3841  TABLE_LIST *tbl;
3842 
3843  if ((tbl= merge_underlying_list))
3844  {
3845  /* This is a view. Process all tables of view */
3846  DBUG_ASSERT(view && effective_algorithm == VIEW_ALGORITHM_MERGE);
3847  do
3848  {
3849  if (tbl->merge_underlying_list) // This is a view
3850  {
3851  DBUG_ASSERT(tbl->view &&
3852  tbl->effective_algorithm == VIEW_ALGORITHM_MERGE);
3853  /*
3854  This is the only case where set_ancestor is called on an object
3855  that may not be a view (in which case ancestor is 0)
3856  */
3857  tbl->merge_underlying_list->set_underlying_merge();
3858  }
3859  } while ((tbl= tbl->next_local));
3860 
3861  if (!multitable_view)
3862  {
3863  table= merge_underlying_list->table;
3864  /*
3865  If underlying view is not updatable and current view
3866  is a single table view
3867  */
3868  if (!merge_underlying_list->updatable)
3869  updatable= false;
3870  schema_table= merge_underlying_list->schema_table;
3871  }
3872  }
3873 }
3874 
3875 
3876 /*
3877  setup fields of placeholder of merged VIEW
3878 
3879  SYNOPSIS
3880  TABLE_LIST::setup_underlying()
3881  thd - thread handler
3882 
3883  DESCRIPTION
3884  It is:
3885  - preparing translation table for view columns
3886  If there are underlying view(s) procedure first will be called for them.
3887 
3888  RETURN
3889  FALSE - OK
3890  TRUE - error
3891 */
3892 
3893 bool TABLE_LIST::setup_underlying(THD *thd)
3894 {
3895  DBUG_ENTER("TABLE_LIST::setup_underlying");
3896 
3897  if (!field_translation && merge_underlying_list)
3898  {
3899  Field_translator *transl;
3900  SELECT_LEX *select= &view->select_lex;
3901  Item *item;
3902  TABLE_LIST *tbl;
3903  List_iterator_fast<Item> it(select->item_list);
3904  uint field_count= 0;
3905 
3906  if (check_stack_overrun(thd, STACK_MIN_SIZE, (uchar*) &field_count))
3907  {
3908  DBUG_RETURN(TRUE);
3909  }
3910 
3911  for (tbl= merge_underlying_list; tbl; tbl= tbl->next_local)
3912  {
3913  if (tbl->merge_underlying_list &&
3914  tbl->setup_underlying(thd))
3915  {
3916  DBUG_RETURN(TRUE);
3917  }
3918  }
3919 
3920  /* Create view fields translation table */
3921 
3922  if (!(transl=
3923  (Field_translator*)(thd->stmt_arena->
3924  alloc(select->item_list.elements *
3925  sizeof(Field_translator)))))
3926  {
3927  DBUG_RETURN(TRUE);
3928  }
3929 
3930  while ((item= it++))
3931  {
3932  transl[field_count].name= item->item_name.ptr();
3933  transl[field_count++].item= item;
3934  }
3935  field_translation= transl;
3936  field_translation_end= transl + field_count;
3937  /* TODO: use hash for big number of fields */
3938 
3939  /* full text function moving to current select */
3940  if (view->select_lex.ftfunc_list->elements)
3941  {
3942  Item_func_match *ifm;
3943  SELECT_LEX *current_select= thd->lex->current_select;
3945  li(*(view->select_lex.ftfunc_list));
3946  while ((ifm= li++))
3947  current_select->ftfunc_list->push_front(ifm);
3948  }
3949  }
3950  DBUG_RETURN(FALSE);
3951 }
3952 
3953 
3954 /*
3955  Prepare where expression of view
3956 
3957  SYNOPSIS
3958  TABLE_LIST::prep_where()
3959  thd - thread handler
3960  conds - condition of this JOIN
3961  no_where_clause - do not build WHERE or ON outer qwery do not need it
3962  (it is INSERT), we do not need conds if this flag is set
3963 
3964  NOTE: have to be called befor CHECK OPTION preparation, because it makes
3965  fix_fields for view WHERE clause
3966 
3967  RETURN
3968  FALSE - OK
3969  TRUE - error
3970 */
3971 
3972 bool TABLE_LIST::prep_where(THD *thd, Item **conds,
3973  bool no_where_clause)
3974 {
3975  DBUG_ENTER("TABLE_LIST::prep_where");
3976 
3977  for (TABLE_LIST *tbl= merge_underlying_list; tbl; tbl= tbl->next_local)
3978  {
3979  if (tbl->view && tbl->prep_where(thd, conds, no_where_clause))
3980  {
3981  DBUG_RETURN(TRUE);
3982  }
3983  }
3984 
3985  if (where && !where_processed)
3986  {
3987 
3988  if (!where->fixed)
3989  {
3990  /*
3991  This WHERE will be included in check_option. If it contains a
3992  subquery, fix_fields() may convert it to semijoin, making it
3993  impossible to call val_int() on the Item[...]_subselect, preventing
3994  evaluation of check_option when we insert/update/delete a row.
3995  So we must forbid semijoin transformation in fix_fields():
3996  */
3997  Switch_resolve_place SRP(&thd->lex->current_select->resolve_place,
3998  st_select_lex::RESOLVE_NONE,
3999  effective_with_check != VIEW_CHECK_NONE);
4000 
4001  if (where->fix_fields(thd, &where))
4002  DBUG_RETURN(TRUE);
4003  }
4004 
4005  /*
4006  check that it is not VIEW in which we insert with INSERT SELECT
4007  (in this case we can't add view WHERE condition to main SELECT_LEX)
4008  */
4009  if (!no_where_clause)
4010  {
4011  TABLE_LIST *tbl= this;
4012 
4013  Prepared_stmt_arena_holder ps_arena_holder(thd);
4014 
4015  /* Go up to join tree and try to find left join */
4016  for (; tbl; tbl= tbl->embedding)
4017  {
4018  if (tbl->outer_join)
4019  {
4020  /*
4021  Store WHERE condition to ON expression for outer join, because
4022  we can't use WHERE to correctly execute left joins on VIEWs and
4023  this expression will not be moved to WHERE condition (i.e. will
4024  be clean correctly for PS/SP)
4025  */
4026  tbl->set_join_cond(and_conds(tbl->join_cond(),
4027  where->copy_andor_structure(thd)));
4028  break;
4029  }
4030  }
4031  if (tbl == 0)
4032  *conds= and_conds(*conds, where->copy_andor_structure(thd));
4033  where_processed= TRUE;
4034  }
4035  }
4036 
4037  DBUG_RETURN(FALSE);
4038 }
4039 
4040 
4041 /*
4042  Merge ON expressions for a view
4043 
4044  SYNOPSIS
4045  merge_on_conds()
4046  thd thread handle
4047  table table for the VIEW
4048  is_cascaded TRUE <=> merge ON expressions from underlying views
4049 
4050  DESCRIPTION
4051  This function returns the result of ANDing the ON expressions
4052  of the given view and all underlying views. The ON expressions
4053  of the underlying views are added only if is_cascaded is TRUE.
4054 
4055  RETURN
4056  Pointer to the built expression if there is any.
4057  Otherwise and in the case of a failure NULL is returned.
4058 */
4059 
4060 static Item *
4061 merge_on_conds(THD *thd, TABLE_LIST *table, bool is_cascaded)
4062 {
4063  DBUG_ENTER("merge_on_conds");
4064 
4065  Item *cond= NULL;
4066  DBUG_PRINT("info", ("alias: %s", table->alias));
4067  if (table->join_cond())
4068  cond= table->join_cond()->copy_andor_structure(thd);
4069  if (!table->nested_join)
4070  DBUG_RETURN(cond);
4071  List_iterator<TABLE_LIST> li(table->nested_join->join_list);
4072  while (TABLE_LIST *tbl= li++)
4073  {
4074  if (tbl->view && !is_cascaded)
4075  continue;
4076  cond= and_conds(cond, merge_on_conds(thd, tbl, is_cascaded));
4077  }
4078  DBUG_RETURN(cond);
4079 }
4080 
4081 
4082 /*
4083  Prepare check option expression of table
4084 
4085  SYNOPSIS
4086  TABLE_LIST::prep_check_option()
4087  thd - thread handler
4088  check_opt_type - WITH CHECK OPTION type (VIEW_CHECK_NONE,
4089  VIEW_CHECK_LOCAL, VIEW_CHECK_CASCADED)
4090  we use this parameter instead of direct check of
4091  effective_with_check to change type of underlying
4092  views to VIEW_CHECK_CASCADED if outer view have
4093  such option and prevent processing of underlying
4094  view check options if outer view have just
4095  VIEW_CHECK_LOCAL option.
4096 
4097  NOTE
4098  This method builds check option condition to use it later on
4099  every call (usual execution or every SP/PS call).
4100  This method have to be called after WHERE preparation
4101  (TABLE_LIST::prep_where)
4102 
4103  RETURN
4104  FALSE - OK
4105  TRUE - error
4106 */
4107 
4108 bool TABLE_LIST::prep_check_option(THD *thd, uint8 check_opt_type)
4109 {
4110  DBUG_ENTER("TABLE_LIST::prep_check_option");
4111  bool is_cascaded= check_opt_type == VIEW_CHECK_CASCADED;
4112 
4113  for (TABLE_LIST *tbl= merge_underlying_list; tbl; tbl= tbl->next_local)
4114  {
4115  /* see comment of check_opt_type parameter */
4116  if (tbl->view && tbl->prep_check_option(thd, (is_cascaded ?
4117  VIEW_CHECK_CASCADED :
4118  VIEW_CHECK_NONE)))
4119  DBUG_RETURN(TRUE);
4120  }
4121 
4122  if (check_opt_type && !check_option_processed)
4123  {
4124  Prepared_stmt_arena_holder ps_arena_holder(thd);
4125 
4126  if (where)
4127  {
4128  DBUG_ASSERT(where->fixed);
4129  check_option= where->copy_andor_structure(thd);
4130  }
4131  if (is_cascaded)
4132  {
4133  for (TABLE_LIST *tbl= merge_underlying_list; tbl; tbl= tbl->next_local)
4134  {
4135  if (tbl->check_option)
4136  check_option= and_conds(check_option, tbl->check_option);
4137  }
4138  }
4139  check_option= and_conds(check_option,
4140  merge_on_conds(thd, this, is_cascaded));
4141 
4142  check_option_processed= TRUE;
4143  }
4144 
4145  if (check_option)
4146  {
4147  const char *save_where= thd->where;
4148  thd->where= "check option";
4149  if ((!check_option->fixed &&
4150  check_option->fix_fields(thd, &check_option)) ||
4151  check_option->check_cols(1))
4152  {
4153  DBUG_RETURN(TRUE);
4154  }
4155  thd->where= save_where;
4156  }
4157  DBUG_RETURN(FALSE);
4158 }
4159 
4160 
4175 {
4176  if (thd->killed || thd->get_internal_handler())
4177  return;
4178  /* Hide "Unknown column" or "Unknown function" error */
4179  DBUG_ASSERT(thd->is_error());
4180 
4181  switch (thd->get_stmt_da()->sql_errno()) {
4182  case ER_BAD_FIELD_ERROR:
4183  case ER_SP_DOES_NOT_EXIST:
4184  case ER_FUNC_INEXISTENT_NAME_COLLISION:
4185  case ER_PROCACCESS_DENIED_ERROR:
4186  case ER_COLUMNACCESS_DENIED_ERROR:
4187  case ER_TABLEACCESS_DENIED_ERROR:
4188  case ER_TABLE_NOT_LOCKED:
4189  case ER_NO_SUCH_TABLE:
4190  {
4191  TABLE_LIST *top= top_table();
4192  thd->clear_error();
4193  my_error(ER_VIEW_INVALID, MYF(0),
4194  top->view_db.str, top->view_name.str);
4195  break;
4196  }
4197 
4198  case ER_NO_DEFAULT_FOR_FIELD:
4199  {
4200  TABLE_LIST *top= top_table();
4201  thd->clear_error();
4202  // TODO: make correct error message
4203  my_error(ER_NO_DEFAULT_FOR_VIEW_FIELD, MYF(0),
4204  top->view_db.str, top->view_name.str);
4205  break;
4206  }
4207  }
4208 }
4209 
4210 
4211 /*
4212  Find underlying base tables (TABLE_LIST) which represent given
4213  table_to_find (TABLE)
4214 
4215  SYNOPSIS
4216  TABLE_LIST::find_underlying_table()
4217  table_to_find table to find
4218 
4219  RETURN
4220  0 table is not found
4221  found table reference
4222 */
4223 
4224 TABLE_LIST *TABLE_LIST::find_underlying_table(TABLE *table_to_find)
4225 {
4226  /* is this real table and table which we are looking for? */
4227  if (table == table_to_find && merge_underlying_list == 0)
4228  return this;
4229 
4230  for (TABLE_LIST *tbl= merge_underlying_list; tbl; tbl= tbl->next_local)
4231  {
4232  TABLE_LIST *result;
4233  if ((result= tbl->find_underlying_table(table_to_find)))
4234  return result;
4235  }
4236  return 0;
4237 }
4238 
4239 /*
4240  cleanup items belonged to view fields translation table
4241 
4242  SYNOPSIS
4243  TABLE_LIST::cleanup_items()
4244 */
4245 
4246 void TABLE_LIST::cleanup_items()
4247 {
4248  if (!field_translation)
4249  return;
4250 
4251  for (Field_translator *transl= field_translation;
4252  transl < field_translation_end;
4253  transl++)
4254  transl->item->walk(&Item::cleanup_processor, 0, 0);
4255 }
4256 
4257 
4258 /*
4259  check CHECK OPTION condition
4260 
4261  SYNOPSIS
4262  TABLE_LIST::view_check_option()
4263  ignore_failure ignore check option fail
4264 
4265  RETURN
4266  VIEW_CHECK_OK OK
4267  VIEW_CHECK_ERROR FAILED
4268  VIEW_CHECK_SKIP FAILED, but continue
4269 */
4270 
4271 int TABLE_LIST::view_check_option(THD *thd, bool ignore_failure) const
4272 {
4273  if (check_option && check_option->val_int() == 0)
4274  {
4275  const TABLE_LIST *main_view= top_table();
4276  if (ignore_failure)
4277  {
4278  push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
4279  ER_VIEW_CHECK_FAILED, ER(ER_VIEW_CHECK_FAILED),
4280  main_view->view_db.str, main_view->view_name.str);
4281  return(VIEW_CHECK_SKIP);
4282  }
4283  my_error(ER_VIEW_CHECK_FAILED, MYF(0), main_view->view_db.str,
4284  main_view->view_name.str);
4285  return(VIEW_CHECK_ERROR);
4286  }
4287  return(VIEW_CHECK_OK);
4288 }
4289 
4290 
4291 /*
4292  Find table in underlying tables by mask and check that only this
4293  table belong to given mask
4294 
4295  SYNOPSIS
4296  TABLE_LIST::check_single_table()
4297  table_arg reference on variable where to store found table
4298  (should be 0 on call, to find table, or point to table for
4299  unique test)
4300  map bit mask of tables
4301  view_arg view for which we are looking table
4302 
4303  RETURN
4304  FALSE table not found or found only one
4305  TRUE found several tables
4306 */
4307 
4308 bool TABLE_LIST::check_single_table(TABLE_LIST **table_arg,
4309  table_map map,
4310  TABLE_LIST *view_arg)
4311 {
4312  for (TABLE_LIST *tbl= merge_underlying_list; tbl; tbl= tbl->next_local)
4313  {
4314  if (tbl->table)
4315  {
4316  if (tbl->table->map & map)
4317  {
4318  if (*table_arg)
4319  return TRUE;
4320  *table_arg= tbl;
4321  tbl->check_option= view_arg->check_option;
4322  }
4323  }
4324  else if (tbl->check_single_table(table_arg, map, view_arg))
4325  return TRUE;
4326  }
4327  return FALSE;
4328 }
4329 
4330 
4331 /*
4332  Set insert_values buffer
4333 
4334  SYNOPSIS
4335  set_insert_values()
4336  mem_root memory pool for allocating
4337 
4338  RETURN
4339  FALSE - OK
4340  TRUE - out of memory
4341 */
4342 
4343 bool TABLE_LIST::set_insert_values(MEM_ROOT *mem_root)
4344 {
4345  if (table)
4346  {
4347  if (!table->insert_values &&
4348  !(table->insert_values= (uchar *)alloc_root(mem_root,
4349  table->s->rec_buff_length)))
4350  return TRUE;
4351  }
4352  else
4353  {
4354  DBUG_ASSERT(view && merge_underlying_list);
4355  for (TABLE_LIST *tbl= merge_underlying_list; tbl; tbl= tbl->next_local)
4356  if (tbl->set_insert_values(mem_root))
4357  return TRUE;
4358  }
4359  return FALSE;
4360 }
4361 
4362 
4363 /*
4364  Test if this is a leaf with respect to name resolution.
4365 
4366  SYNOPSIS
4367  TABLE_LIST::is_leaf_for_name_resolution()
4368 
4369  DESCRIPTION
4370  A table reference is a leaf with respect to name resolution if
4371  it is either a leaf node in a nested join tree (table, view,
4372  schema table, subquery), or an inner node that represents a
4373  NATURAL/USING join, or a nested join with materialized join
4374  columns.
4375 
4376  RETURN
4377  TRUE if a leaf, FALSE otherwise.
4378 */
4379 bool TABLE_LIST::is_leaf_for_name_resolution()
4380 {
4381  return (view || is_natural_join || is_join_columns_complete ||
4382  !nested_join);
4383 }
4384 
4385 
4386 /*
4387  Retrieve the first (left-most) leaf in a nested join tree with
4388  respect to name resolution.
4389 
4390  SYNOPSIS
4391  TABLE_LIST::first_leaf_for_name_resolution()
4392 
4393  DESCRIPTION
4394  Given that 'this' is a nested table reference, recursively walk
4395  down the left-most children of 'this' until we reach a leaf
4396  table reference with respect to name resolution.
4397 
4398  IMPLEMENTATION
4399  The left-most child of a nested table reference is the last element
4400  in the list of children because the children are inserted in
4401  reverse order.
4402 
4403  RETURN
4404  If 'this' is a nested table reference - the left-most child of
4405  the tree rooted in 'this',
4406  else return 'this'
4407 */
4408 
4409 TABLE_LIST *TABLE_LIST::first_leaf_for_name_resolution()
4410 {
4411  TABLE_LIST *cur_table_ref;
4412  NESTED_JOIN *cur_nested_join;
4413  LINT_INIT(cur_table_ref);
4414 
4415  if (is_leaf_for_name_resolution())
4416  return this;
4417  DBUG_ASSERT(nested_join);
4418 
4419  for (cur_nested_join= nested_join;
4420  cur_nested_join;
4421  cur_nested_join= cur_table_ref->nested_join)
4422  {
4423  List_iterator_fast<TABLE_LIST> it(cur_nested_join->join_list);
4424  cur_table_ref= it++;
4425  /*
4426  If the current nested join is a RIGHT JOIN, the operands in
4427  'join_list' are in reverse order, thus the first operand is
4428  already at the front of the list. Otherwise the first operand
4429  is in the end of the list of join operands.
4430  */
4431  if (!(cur_table_ref->outer_join & JOIN_TYPE_RIGHT))
4432  {
4433  TABLE_LIST *next;
4434  while ((next= it++))
4435  cur_table_ref= next;
4436  }
4437  if (cur_table_ref->is_leaf_for_name_resolution())
4438  break;
4439  }
4440  return cur_table_ref;
4441 }
4442 
4443 
4444 /*
4445  Retrieve the last (right-most) leaf in a nested join tree with
4446  respect to name resolution.
4447 
4448  SYNOPSIS
4449  TABLE_LIST::last_leaf_for_name_resolution()
4450 
4451  DESCRIPTION
4452  Given that 'this' is a nested table reference, recursively walk
4453  down the right-most children of 'this' until we reach a leaf
4454  table reference with respect to name resolution.
4455 
4456  IMPLEMENTATION
4457  The right-most child of a nested table reference is the first
4458  element in the list of children because the children are inserted
4459  in reverse order.
4460 
4461  RETURN
4462  - If 'this' is a nested table reference - the right-most child of
4463  the tree rooted in 'this',
4464  - else - 'this'
4465 */
4466 
4467 TABLE_LIST *TABLE_LIST::last_leaf_for_name_resolution()
4468 {
4469  TABLE_LIST *cur_table_ref= this;
4470  NESTED_JOIN *cur_nested_join;
4471 
4472  if (is_leaf_for_name_resolution())
4473  return this;
4474  DBUG_ASSERT(nested_join);
4475 
4476  for (cur_nested_join= nested_join;
4477  cur_nested_join;
4478  cur_nested_join= cur_table_ref->nested_join)
4479  {
4480  cur_table_ref= cur_nested_join->join_list.head();
4481  /*
4482  If the current nested is a RIGHT JOIN, the operands in
4483  'join_list' are in reverse order, thus the last operand is in the
4484  end of the list.
4485  */
4486  if ((cur_table_ref->outer_join & JOIN_TYPE_RIGHT))
4487  {
4488  List_iterator_fast<TABLE_LIST> it(cur_nested_join->join_list);
4489  TABLE_LIST *next;
4490  cur_table_ref= it++;
4491  while ((next= it++))
4492  cur_table_ref= next;
4493  }
4494  if (cur_table_ref->is_leaf_for_name_resolution())
4495  break;
4496  }
4497  return cur_table_ref;
4498 }
4499 
4500 
4501 /*
4502  Register access mode which we need for underlying tables
4503 
4504  SYNOPSIS
4505  register_want_access()
4506  want_access Acess which we require
4507 */
4508 
4509 void TABLE_LIST::register_want_access(ulong want_access)
4510 {
4511  /* Remove SHOW_VIEW_ACL, because it will be checked during making view */
4512  want_access&= ~SHOW_VIEW_ACL;
4513  if (belong_to_view)
4514  {
4515  grant.want_privilege= want_access;
4516  if (table)
4517  table->grant.want_privilege= want_access;
4518  }
4519  for (TABLE_LIST *tbl= merge_underlying_list; tbl; tbl= tbl->next_local)
4520  tbl->register_want_access(want_access);
4521 }
4522 
4523 
4524 /*
4525  Load security context information for this view
4526 
4527  SYNOPSIS
4528  TABLE_LIST::prepare_view_securety_context()
4529  thd [in] thread handler
4530 
4531  RETURN
4532  FALSE OK
4533  TRUE Error
4534 */
4535 
4536 #ifndef NO_EMBEDDED_ACCESS_CHECKS
4537 bool TABLE_LIST::prepare_view_securety_context(THD *thd)
4538 {
4539  DBUG_ENTER("TABLE_LIST::prepare_view_securety_context");
4540  DBUG_PRINT("enter", ("table: %s", alias));
4541 
4542  DBUG_ASSERT(!prelocking_placeholder && view);
4543  if (view_suid)
4544  {
4545  DBUG_PRINT("info", ("This table is suid view => load contest"));
4546  DBUG_ASSERT(view && view_sctx);
4547  if (acl_getroot(view_sctx, definer.user.str, definer.host.str,
4548  definer.host.str, thd->db))
4549  {
4550  if ((thd->lex->sql_command == SQLCOM_SHOW_CREATE) ||
4551  (thd->lex->sql_command == SQLCOM_SHOW_FIELDS))
4552  {
4553  push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE,
4554  ER_NO_SUCH_USER,
4555  ER(ER_NO_SUCH_USER),
4556  definer.user.str, definer.host.str);
4557  }
4558  else
4559  {
4560  if (thd->security_ctx->master_access & SUPER_ACL)
4561  {
4562  my_error(ER_NO_SUCH_USER, MYF(0), definer.user.str, definer.host.str);
4563 
4564  }
4565  else
4566  {
4567  if (thd->password == 2)
4568  my_error(ER_ACCESS_DENIED_NO_PASSWORD_ERROR, MYF(0),
4569  thd->security_ctx->priv_user,
4570  thd->security_ctx->priv_host);
4571  else
4572  my_error(ER_ACCESS_DENIED_ERROR, MYF(0),
4573  thd->security_ctx->priv_user,
4574  thd->security_ctx->priv_host,
4575  (thd->password ? ER(ER_YES) : ER(ER_NO)));
4576  }
4577  DBUG_RETURN(TRUE);
4578  }
4579  }
4580  }
4581  DBUG_RETURN(FALSE);
4582 }
4583 #endif
4584 
4585 
4586 /*
4587  Find security context of current view
4588 
4589  SYNOPSIS
4590  TABLE_LIST::find_view_security_context()
4591  thd [in] thread handler
4592 
4593 */
4594 
4595 #ifndef NO_EMBEDDED_ACCESS_CHECKS
4596 Security_context *TABLE_LIST::find_view_security_context(THD *thd)
4597 {
4598  Security_context *sctx;
4599  TABLE_LIST *upper_view= this;
4600  DBUG_ENTER("TABLE_LIST::find_view_security_context");
4601 
4602  DBUG_ASSERT(view);
4603  while (upper_view && !upper_view->view_suid)
4604  {
4605  DBUG_ASSERT(!upper_view->prelocking_placeholder);
4606  upper_view= upper_view->referencing_view;
4607  }
4608  if (upper_view)
4609  {
4610  DBUG_PRINT("info", ("Securety context of view %s will be used",
4611  upper_view->alias));
4612  sctx= upper_view->view_sctx;
4613  DBUG_ASSERT(sctx);
4614  }
4615  else
4616  {
4617  DBUG_PRINT("info", ("Current global context will be used"));
4618  sctx= thd->security_ctx;
4619  }
4620  DBUG_RETURN(sctx);
4621 }
4622 #endif
4623 
4624 
4625 /*
4626  Prepare security context and load underlying tables priveleges for view
4627 
4628  SYNOPSIS
4629  TABLE_LIST::prepare_security()
4630  thd [in] thread handler
4631 
4632  RETURN
4633  FALSE OK
4634  TRUE Error
4635 */
4636 
4637 bool TABLE_LIST::prepare_security(THD *thd)
4638 {
4639  List_iterator_fast<TABLE_LIST> tb(*view_tables);
4640  TABLE_LIST *tbl;
4641  DBUG_ENTER("TABLE_LIST::prepare_security");
4642 #ifndef NO_EMBEDDED_ACCESS_CHECKS
4643  Security_context *save_security_ctx= thd->security_ctx;
4644 
4645  DBUG_ASSERT(!prelocking_placeholder);
4646  if (prepare_view_securety_context(thd))
4647  DBUG_RETURN(TRUE);
4648  thd->security_ctx= find_view_security_context(thd);
4649  opt_trace_disable_if_no_security_context_access(thd);
4650  while ((tbl= tb++))
4651  {
4652  DBUG_ASSERT(tbl->referencing_view);
4653  char *local_db, *local_table_name;
4654  if (tbl->view)
4655  {
4656  local_db= tbl->view_db.str;
4657  local_table_name= tbl->view_name.str;
4658  }
4659  else
4660  {
4661  local_db= tbl->db;
4662  local_table_name= tbl->table_name;
4663  }
4664  fill_effective_table_privileges(thd, &tbl->grant, local_db,
4665  local_table_name);
4666  if (tbl->table)
4667  tbl->table->grant= grant;
4668  }
4669  thd->security_ctx= save_security_ctx;
4670 #else
4671  while ((tbl= tb++))
4672  tbl->grant.privilege= ~NO_ACCESS;
4673 #endif
4674  DBUG_RETURN(FALSE);
4675 }
4676 
4677 
4678 Natural_join_column::Natural_join_column(Field_translator *field_param,
4679  TABLE_LIST *tab)
4680 {
4681  DBUG_ASSERT(tab->field_translation);
4682  view_field= field_param;
4683  table_field= NULL;
4684  table_ref= tab;
4685  is_common= FALSE;
4686 }
4687 
4688 
4689 Natural_join_column::Natural_join_column(Item_field *field_param,
4690  TABLE_LIST *tab)
4691 {
4692  DBUG_ASSERT(tab->table == field_param->field->table);
4693  table_field= field_param;
4694  view_field= NULL;
4695  table_ref= tab;
4696  is_common= FALSE;
4697 }
4698 
4699 
4700 const char *Natural_join_column::name()
4701 {
4702  if (view_field)
4703  {
4704  DBUG_ASSERT(table_field == NULL);
4705  return view_field->name;
4706  }
4707 
4708  return table_field->field_name;
4709 }
4710 
4711 
4712 Item *Natural_join_column::create_item(THD *thd)
4713 {
4714  if (view_field)
4715  {
4716  DBUG_ASSERT(table_field == NULL);
4717  SELECT_LEX *select= thd->lex->current_select;
4718  return create_view_field(thd, table_ref, &view_field->item,
4719  view_field->name, &select->context);
4720  }
4721  return table_field;
4722 }
4723 
4724 
4725 Field *Natural_join_column::field()
4726 {
4727  if (view_field)
4728  {
4729  DBUG_ASSERT(table_field == NULL);
4730  return NULL;
4731  }
4732  return table_field->field;
4733 }
4734 
4735 
4736 const char *Natural_join_column::table_name()
4737 {
4738  DBUG_ASSERT(table_ref);
4739  return table_ref->alias;
4740 }
4741 
4742 
4743 const char *Natural_join_column::db_name()
4744 {
4745  if (view_field)
4746  return table_ref->view_db.str;
4747 
4748  /*
4749  Test that TABLE_LIST::db is the same as TABLE_SHARE::db to
4750  ensure consistency. An exception are I_S schema tables, which
4751  are inconsistent in this respect.
4752  */
4753  DBUG_ASSERT(!strcmp(table_ref->db,
4754  table_ref->table->s->db.str) ||
4755  (table_ref->schema_table &&
4756  is_infoschema_db(table_ref->table->s->db.str,
4757  table_ref->table->s->db.length)));
4758  return table_ref->db;
4759 }
4760 
4761 
4762 GRANT_INFO *Natural_join_column::grant()
4763 {
4764  if (view_field)
4765  return &(table_ref->grant);
4766  return &(table_ref->table->grant);
4767 }
4768 
4769 
4770 void Field_iterator_view::set(TABLE_LIST *table)
4771 {
4772  DBUG_ASSERT(table->field_translation);
4773  view= table;
4774  ptr= table->field_translation;
4775  array_end= table->field_translation_end;
4776 }
4777 
4778 
4779 const char *Field_iterator_table::name()
4780 {
4781  return (*ptr)->field_name;
4782 }
4783 
4784 
4785 Item *Field_iterator_table::create_item(THD *thd)
4786 {
4787  SELECT_LEX *select= thd->lex->current_select;
4788 
4789  Item_field *item= new Item_field(thd, &select->context, *ptr);
4790  /*
4791  This function creates Item-s which don't go through fix_fields(); see same
4792  code in Item_field::fix_fields().
4793  */
4794  if (item && !thd->lex->in_sum_func &&
4795  select->cur_pos_in_all_fields != SELECT_LEX::ALL_FIELDS_UNDEF_POS)
4796  {
4797  if (thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY)
4798  {
4799  item->push_to_non_agg_fields(select);
4800  select->set_non_agg_field_used(true);
4801  }
4802  if (thd->lex->current_select->with_sum_func &&
4803  !thd->lex->current_select->group_list.elements)
4804  item->maybe_null= true;
4805  }
4806  return item;
4807 }
4808 
4809 
4810 const char *Field_iterator_view::name()
4811 {
4812  return ptr->name;
4813 }
4814 
4815 
4816 Item *Field_iterator_view::create_item(THD *thd)
4817 {
4818  SELECT_LEX *select= thd->lex->current_select;
4819  return create_view_field(thd, view, &ptr->item, ptr->name,
4820  &select->context);
4821 }
4822 
4823 static Item *create_view_field(THD *thd, TABLE_LIST *view, Item **field_ref,
4824  const char *name,
4825  Name_resolution_context *context)
4826 {
4827  bool save_wrapper= thd->lex->select_lex.no_wrap_view_item;
4828  Item *field= *field_ref;
4829  DBUG_ENTER("create_view_field");
4830 
4831  if (view->schema_table_reformed)
4832  {
4833  /*
4834  Translation table items are always Item_fields and already fixed
4835  ('mysql_schema_table' function). So we can return directly the
4836  field. This case happens only for 'show & where' commands.
4837  */
4838  DBUG_ASSERT(field && field->fixed);
4839  DBUG_RETURN(field);
4840  }
4841 
4842  DBUG_ASSERT(field);
4843  thd->lex->current_select->no_wrap_view_item= TRUE;
4844  if (!field->fixed)
4845  {
4846  if (field->fix_fields(thd, field_ref))
4847  {
4848  thd->lex->current_select->no_wrap_view_item= save_wrapper;
4849  DBUG_RETURN(0);
4850  }
4851  field= *field_ref;
4852  }
4853  thd->lex->current_select->no_wrap_view_item= save_wrapper;
4854  if (save_wrapper)
4855  {
4856  DBUG_RETURN(field);
4857  }
4858  Item *item= new Item_direct_view_ref(context, field_ref,
4859  view->alias, view->table_name, name);
4860  DBUG_RETURN(item);
4861 }
4862 
4863 
4864 void Field_iterator_natural_join::set(TABLE_LIST *table_ref)
4865 {
4866  DBUG_ASSERT(table_ref->join_columns);
4867  column_ref_it.init(*(table_ref->join_columns));
4868  cur_column_ref= column_ref_it++;
4869 }
4870 
4871 
4872 void Field_iterator_natural_join::next()
4873 {
4874  cur_column_ref= column_ref_it++;
4875  DBUG_ASSERT(!cur_column_ref || ! cur_column_ref->table_field ||
4876  cur_column_ref->table_ref->table ==
4877  cur_column_ref->table_field->field->table);
4878 }
4879 
4880 
4881 void Field_iterator_table_ref::set_field_iterator()
4882 {
4883  DBUG_ENTER("Field_iterator_table_ref::set_field_iterator");
4884  /*
4885  If the table reference we are iterating over is a natural join, or it is
4886  an operand of a natural join, and TABLE_LIST::join_columns contains all
4887  the columns of the join operand, then we pick the columns from
4888  TABLE_LIST::join_columns, instead of the orginial container of the
4889  columns of the join operator.
4890  */
4891  if (table_ref->is_join_columns_complete)
4892  {
4893  /* Necesary, but insufficient conditions. */
4894  DBUG_ASSERT(table_ref->is_natural_join ||
4895  table_ref->nested_join ||
4896  (table_ref->join_columns &&
4897  /* This is a merge view. */
4898  ((table_ref->field_translation &&
4899  table_ref->join_columns->elements ==
4900  (ulong)(table_ref->field_translation_end -
4901  table_ref->field_translation)) ||
4902  /* This is stored table or a tmptable view. */
4903  (!table_ref->field_translation &&
4904  table_ref->join_columns->elements ==
4905  table_ref->table->s->fields))));
4906  field_it= &natural_join_it;
4907  DBUG_PRINT("info",("field_it for '%s' is Field_iterator_natural_join",
4908  table_ref->alias));
4909  }
4910  /* This is a merge view, so use field_translation. */
4911  else if (table_ref->field_translation)
4912  {
4913  DBUG_ASSERT(table_ref->view &&
4914  table_ref->effective_algorithm == VIEW_ALGORITHM_MERGE);
4915  field_it= &view_field_it;
4916  DBUG_PRINT("info", ("field_it for '%s' is Field_iterator_view",
4917  table_ref->alias));
4918  }
4919  /* This is a base table or stored view. */
4920  else
4921  {
4922  DBUG_ASSERT(table_ref->table || table_ref->view);
4923  field_it= &table_field_it;
4924  DBUG_PRINT("info", ("field_it for '%s' is Field_iterator_table",
4925  table_ref->alias));
4926  }
4927  field_it->set(table_ref);
4928  DBUG_VOID_RETURN;
4929 }
4930 
4931 
4932 void Field_iterator_table_ref::set(TABLE_LIST *table)
4933 {
4934  DBUG_ASSERT(table);
4935  first_leaf= table->first_leaf_for_name_resolution();
4936  last_leaf= table->last_leaf_for_name_resolution();
4937  DBUG_ASSERT(first_leaf && last_leaf);
4938  table_ref= first_leaf;
4939  set_field_iterator();
4940 }
4941 
4942 
4943 void Field_iterator_table_ref::next()
4944 {
4945  /* Move to the next field in the current table reference. */
4946  field_it->next();
4947  /*
4948  If all fields of the current table reference are exhausted, move to
4949  the next leaf table reference.
4950  */
4951  if (field_it->end_of_fields() && table_ref != last_leaf)
4952  {
4953  table_ref= table_ref->next_name_resolution_table;
4954  DBUG_ASSERT(table_ref);
4955  set_field_iterator();
4956  }
4957 }
4958 
4959 
4960 const char *Field_iterator_table_ref::get_table_name()
4961 {
4962  if (table_ref->view)
4963  return table_ref->view_name.str;
4964  else if (table_ref->is_natural_join)
4965  return natural_join_it.column_ref()->table_name();
4966 
4967  DBUG_ASSERT(!strcmp(table_ref->table_name,
4968  table_ref->table->s->table_name.str));
4969  return table_ref->table_name;
4970 }
4971 
4972 
4973 const char *Field_iterator_table_ref::get_db_name()
4974 {
4975  if (table_ref->view)
4976  return table_ref->view_db.str;
4977  else if (table_ref->is_natural_join)
4978  return natural_join_it.column_ref()->db_name();
4979 
4980  /*
4981  Test that TABLE_LIST::db is the same as TABLE_SHARE::db to
4982  ensure consistency. An exception are I_S schema tables, which
4983  are inconsistent in this respect.
4984  */
4985  DBUG_ASSERT(!strcmp(table_ref->db, table_ref->table->s->db.str) ||
4986  (table_ref->schema_table &&
4987  is_infoschema_db(table_ref->table->s->db.str,
4988  table_ref->table->s->db.length)));
4989 
4990  return table_ref->db;
4991 }
4992 
4993 
4994 GRANT_INFO *Field_iterator_table_ref::grant()
4995 {
4996  if (table_ref->view)
4997  return &(table_ref->grant);
4998  else if (table_ref->is_natural_join)
4999  return natural_join_it.column_ref()->grant();
5000  return &(table_ref->table->grant);
5001 }
5002 
5003 
5004 /*
5005  Create new or return existing column reference to a column of a
5006  natural/using join.
5007 
5008  SYNOPSIS
5009  Field_iterator_table_ref::get_or_create_column_ref()
5010  parent_table_ref the parent table reference over which the
5011  iterator is iterating
5012 
5013  DESCRIPTION
5014  Create a new natural join column for the current field of the
5015  iterator if no such column was created, or return an already
5016  created natural join column. The former happens for base tables or
5017  views, and the latter for natural/using joins. If a new field is
5018  created, then the field is added to 'parent_table_ref' if it is
5019  given, or to the original table referene of the field if
5020  parent_table_ref == NULL.
5021 
5022  NOTES
5023  This method is designed so that when a Field_iterator_table_ref
5024  walks through the fields of a table reference, all its fields
5025  are created and stored as follows:
5026  - If the table reference being iterated is a stored table, view or
5027  natural/using join, store all natural join columns in a list
5028  attached to that table reference.
5029  - If the table reference being iterated is a nested join that is
5030  not natural/using join, then do not materialize its result
5031  fields. This is OK because for such table references
5032  Field_iterator_table_ref iterates over the fields of the nested
5033  table references (recursively). In this way we avoid the storage
5034  of unnecessay copies of result columns of nested joins.
5035 
5036  RETURN
5037  # Pointer to a column of a natural join (or its operand)
5038  NULL No memory to allocate the column
5039 */
5040 
5042 Field_iterator_table_ref::get_or_create_column_ref(THD *thd, TABLE_LIST *parent_table_ref)
5043 {
5044  Natural_join_column *nj_col;
5045  bool is_created= TRUE;
5046  uint field_count;
5047  TABLE_LIST *add_table_ref= parent_table_ref ?
5048  parent_table_ref : table_ref;
5049  LINT_INIT(field_count);
5050 
5051  if (field_it == &table_field_it)
5052  {
5053  /* The field belongs to a stored table. */
5054  Field *tmp_field= table_field_it.field();
5055  Item_field *tmp_item=
5056  new Item_field(thd, &thd->lex->current_select->context, tmp_field);
5057  if (!tmp_item)
5058  return NULL;
5059  nj_col= new Natural_join_column(tmp_item, table_ref);
5060  field_count= table_ref->table->s->fields;
5061  }
5062  else if (field_it == &view_field_it)
5063  {
5064  /* The field belongs to a merge view or information schema table. */
5065  Field_translator *translated_field= view_field_it.field_translator();
5066  nj_col= new Natural_join_column(translated_field, table_ref);
5067  field_count= table_ref->field_translation_end -
5068  table_ref->field_translation;
5069  }
5070  else
5071  {
5072  /*
5073  The field belongs to a NATURAL join, therefore the column reference was
5074  already created via one of the two constructor calls above. In this case
5075  we just return the already created column reference.
5076  */
5077  DBUG_ASSERT(table_ref->is_join_columns_complete);
5078  is_created= FALSE;
5079  nj_col= natural_join_it.column_ref();
5080  DBUG_ASSERT(nj_col);
5081  }
5082  DBUG_ASSERT(!nj_col->table_field ||
5083  nj_col->table_ref->table == nj_col->table_field->field->table);
5084 
5085  /*
5086  If the natural join column was just created add it to the list of
5087  natural join columns of either 'parent_table_ref' or to the table
5088  reference that directly contains the original field.
5089  */
5090  if (is_created)
5091  {
5092  /* Make sure not all columns were materialized. */
5093  DBUG_ASSERT(!add_table_ref->is_join_columns_complete);
5094  if (!add_table_ref->join_columns)
5095  {
5096  /* Create a list of natural join columns on demand. */
5097  if (!(add_table_ref->join_columns= new List<Natural_join_column>))
5098  return NULL;
5099  add_table_ref->is_join_columns_complete= FALSE;
5100  }
5101  add_table_ref->join_columns->push_back(nj_col);
5102  /*
5103  If new fields are added to their original table reference, mark if
5104  all fields were added. We do it here as the caller has no easy way
5105  of knowing when to do it.
5106  If the fields are being added to parent_table_ref, then the caller
5107  must take care to mark when all fields are created/added.
5108  */
5109  if (!parent_table_ref &&
5110  add_table_ref->join_columns->elements == field_count)
5111  add_table_ref->is_join_columns_complete= TRUE;
5112  }
5113 
5114  return nj_col;
5115 }
5116 
5117 
5118 /*
5119  Return an existing reference to a column of a natural/using join.
5120 
5121  SYNOPSIS
5122  Field_iterator_table_ref::get_natural_column_ref()
5123 
5124  DESCRIPTION
5125  The method should be called in contexts where it is expected that
5126  all natural join columns are already created, and that the column
5127  being retrieved is a Natural_join_column.
5128 
5129  RETURN
5130  # Pointer to a column of a natural join (or its operand)
5131  NULL No memory to allocate the column
5132 */
5133 
5135 Field_iterator_table_ref::get_natural_column_ref()
5136 {
5137  Natural_join_column *nj_col;
5138 
5139  DBUG_ASSERT(field_it == &natural_join_it);
5140  /*
5141  The field belongs to a NATURAL join, therefore the column reference was
5142  already created via one of the two constructor calls above. In this case
5143  we just return the already created column reference.
5144  */
5145  nj_col= natural_join_it.column_ref();
5146  DBUG_ASSERT(nj_col &&
5147  (!nj_col->table_field ||
5148  nj_col->table_ref->table == nj_col->table_field->field->table));
5149  return nj_col;
5150 }
5151 
5152 /*****************************************************************************
5153  Functions to handle column usage bitmaps (read_set, write_set etc...)
5154 *****************************************************************************/
5155 
5156 /* Reset all columns bitmaps */
5157 
5158 void TABLE::clear_column_bitmaps()
5159 {
5160  /*
5161  Reset column read/write usage. It's identical to:
5162  bitmap_clear_all(&table->def_read_set);
5163  bitmap_clear_all(&table->def_write_set);
5164  */
5165  memset(def_read_set.bitmap, 0, s->column_bitmap_size*2);
5166  column_bitmaps_set(&def_read_set, &def_write_set);
5167 }
5168 
5169 
5183 {
5184  DBUG_ENTER("TABLE::prepare_for_position");
5185 
5186  if ((file->ha_table_flags() & HA_PRIMARY_KEY_REQUIRED_FOR_POSITION) &&
5187  s->primary_key < MAX_KEY)
5188  {
5189  mark_columns_used_by_index_no_reset(s->primary_key, read_set);
5190  /* signal change */
5191  file->column_bitmaps_signal();
5192  }
5193  DBUG_VOID_RETURN;
5194 }
5195 
5196 
5197 /*
5198  Mark that only fields from one key is used
5199 
5200  NOTE:
5201  This changes the bitmap to use the tmp bitmap
5202  After this, you can't access any other columns in the table until
5203  bitmaps are reset, for example with TABLE::clear_column_bitmaps().
5204 */
5205 
5206 void TABLE::mark_columns_used_by_index(uint index)
5207 {
5208  MY_BITMAP *bitmap= &tmp_set;
5209  DBUG_ENTER("TABLE::mark_columns_used_by_index");
5210 
5211  set_keyread(TRUE);
5212  bitmap_clear_all(bitmap);
5213  mark_columns_used_by_index_no_reset(index, bitmap);
5214  column_bitmaps_set(bitmap, bitmap);
5215  DBUG_VOID_RETURN;
5216 }
5217 
5218 
5219 /*
5220  mark columns used by key, but don't reset other fields
5221 */
5222 
5223 void TABLE::mark_columns_used_by_index_no_reset(uint index,
5224  MY_BITMAP *bitmap)
5225 {
5226  KEY_PART_INFO *key_part= key_info[index].key_part;
5227  KEY_PART_INFO *key_part_end= (key_part +
5228  key_info[index].user_defined_key_parts);
5229  for (;key_part != key_part_end; key_part++)
5230  bitmap_set_bit(bitmap, key_part->fieldnr-1);
5231 }
5232 
5233 
5234 /*
5235  Mark auto-increment fields as used fields in both read and write maps
5236 
5237  NOTES
5238  This is needed in insert & update as the auto-increment field is
5239  always set and sometimes read.
5240 */
5241 
5242 void TABLE::mark_auto_increment_column()
5243 {
5244  DBUG_ASSERT(found_next_number_field);
5245  /*
5246  We must set bit in read set as update_auto_increment() is using the
5247  store() to check overflow of auto_increment values
5248  */
5249  bitmap_set_bit(read_set, found_next_number_field->field_index);
5250  bitmap_set_bit(write_set, found_next_number_field->field_index);
5251  if (s->next_number_keypart)
5252  mark_columns_used_by_index_no_reset(s->next_number_index, read_set);
5253  file->column_bitmaps_signal();
5254 }
5255 
5256 
5257 /*
5258  Mark columns needed for doing an delete of a row
5259 
5260  DESCRIPTON
5261  Some table engines don't have a cursor on the retrieve rows
5262  so they need either to use the primary key or all columns to
5263  be able to delete a row.
5264 
5265  If the engine needs this, the function works as follows:
5266  - If primary key exits, mark the primary key columns to be read.
5267  - If not, mark all columns to be read
5268 
5269  If the engine has HA_REQUIRES_KEY_COLUMNS_FOR_DELETE, we will
5270  mark all key columns as 'to-be-read'. This allows the engine to
5271  loop over the given record to find all keys and doesn't have to
5272  retrieve the row again.
5273 */
5274 
5275 void TABLE::mark_columns_needed_for_delete()
5276 {
5278 
5279  if (triggers)
5280  triggers->mark_fields_used(TRG_EVENT_DELETE);
5281  if (file->ha_table_flags() & HA_REQUIRES_KEY_COLUMNS_FOR_DELETE)
5282  {
5283  Field **reg_field;
5284  for (reg_field= field ; *reg_field ; reg_field++)
5285  {
5286  if ((*reg_field)->flags & PART_KEY_FLAG)
5287  bitmap_set_bit(read_set, (*reg_field)->field_index);
5288  }
5289  file->column_bitmaps_signal();
5290  }
5291  if (file->ha_table_flags() & HA_PRIMARY_KEY_REQUIRED_FOR_DELETE)
5292  {
5293 
5294  /*
5295  If the handler has no cursor capabilites we have to read
5296  either the primary key, the hidden primary key or all columns to
5297  be able to do an delete
5298  */
5299  if (s->primary_key == MAX_KEY)
5300  {
5301  /*
5302  If in RBR, we have alreay marked the full before image
5303  in mark_columns_per_binlog_row_image, if not, then use
5304  the hidden primary key
5305  */
5306  if (!(mysql_bin_log.is_open() && in_use &&
5307  in_use->is_current_stmt_binlog_format_row()))
5308  file->use_hidden_primary_key();
5309  }
5310  else
5311  mark_columns_used_by_index_no_reset(s->primary_key, read_set);
5312 
5313  file->column_bitmaps_signal();
5314  }
5315 }
5316 
5317 
5342 {
5343 
5344  DBUG_ENTER("mark_columns_needed_for_update");
5346  if (file->ha_table_flags() & HA_REQUIRES_KEY_COLUMNS_FOR_DELETE)
5347  {
5348  /* Mark all used key columns for read */
5349  Field **reg_field;
5350  for (reg_field= field ; *reg_field ; reg_field++)
5351  {
5352  /* Merge keys is all keys that had a column refered to in the query */
5353  if (merge_keys.is_overlapping((*reg_field)->part_of_key))
5354  bitmap_set_bit(read_set, (*reg_field)->field_index);
5355  }
5356  file->column_bitmaps_signal();
5357  }
5358 
5359  if (file->ha_table_flags() & HA_PRIMARY_KEY_REQUIRED_FOR_DELETE)
5360  {
5361  /*
5362  If the handler has no cursor capabilites we have to read either
5363  the primary key, the hidden primary key or all columns to be
5364  able to do an update
5365  */
5366  if (s->primary_key == MAX_KEY)
5367  {
5368  /*
5369  If in RBR, we have alreay marked the full before image
5370  in mark_columns_per_binlog_row_image, if not, then use
5371  the hidden primary key
5372  */
5373  if (!(mysql_bin_log.is_open() && in_use &&
5374  in_use->is_current_stmt_binlog_format_row()))
5375  file->use_hidden_primary_key();
5376  }
5377  else
5378  mark_columns_used_by_index_no_reset(s->primary_key, read_set);
5379 
5380  file->column_bitmaps_signal();
5381  }
5382  DBUG_VOID_RETURN;
5383 }
5384 
5385 /*
5386  Mark columns according the binlog row image option.
5387 
5388  When logging in RBR, the user can select whether to
5389  log partial or full rows, depending on the table
5390  definition, and the value of binlog_row_image.
5391 
5392  Semantics of the binlog_row_image are the following
5393  (PKE - primary key equivalent, ie, PK fields if PK
5394  exists, all fields otherwise):
5395 
5396  binlog_row_image= MINIMAL
5397  - This marks the PKE fields in the read_set
5398  - This marks all fields where a value was specified
5399  in the write_set
5400 
5401  binlog_row_image= NOBLOB
5402  - This marks PKE + all non-blob fields in the read_set
5403  - This marks all fields where a value was specified
5404  and all non-blob fields in the write_set
5405 
5406  binlog_row_image= FULL
5407  - all columns in the read_set
5408  - all columns in the write_set
5409 
5410  This marking is done without resetting the original
5411  bitmaps. This means that we will strip extra fields in
5412  the read_set at binlogging time (for those cases that
5413  we only want to log a PK and we needed other fields for
5414  execution).
5415  */
5417 {
5418  DBUG_ENTER("mark_columns_per_binlog_row_image");
5419  DBUG_ASSERT(read_set->bitmap);
5420  DBUG_ASSERT(write_set->bitmap);
5421 
5426  if ((mysql_bin_log.is_open() && in_use &&
5427  in_use->is_current_stmt_binlog_format_row() &&
5428  !ha_check_storage_engine_flag(s->db_type(), HTON_NO_BINLOG_ROW_OPT)))
5429  {
5430 
5431  THD *thd= current_thd;
5432 
5433  /* if there is no PK, then mark all columns for the BI. */
5434  if (s->primary_key >= MAX_KEY)
5435  bitmap_set_all(read_set);
5436 
5437  switch (thd->variables.binlog_row_image)
5438  {
5439  case BINLOG_ROW_IMAGE_FULL:
5440  if (s->primary_key < MAX_KEY)
5441  bitmap_set_all(read_set);
5442  bitmap_set_all(write_set);
5443  break;
5444  case BINLOG_ROW_IMAGE_NOBLOB:
5445  /* for every field that is not set, mark it unless it is a blob */
5446  for (Field **ptr=field ; *ptr ; ptr++)
5447  {
5448  Field *field= *ptr;
5449  /*
5450  bypass blob fields. These can be set or not set, we don't care.
5451  Later, at binlogging time, if we don't need them in the before
5452  image, we will discard them.
5453 
5454  If set in the AI, then the blob is really needed, there is
5455  nothing we can do about it.
5456  */
5457  if ((s->primary_key < MAX_KEY) &&
5458  ((field->flags & PRI_KEY_FLAG) ||
5459  (field->type() != MYSQL_TYPE_BLOB)))
5460  bitmap_set_bit(read_set, field->field_index);
5461 
5462  if (field->type() != MYSQL_TYPE_BLOB)
5463  bitmap_set_bit(write_set, field->field_index);
5464  }
5465  break;
5466  case BINLOG_ROW_IMAGE_MINIMAL:
5467  /* mark the primary key if available in the read_set */
5468  if (s->primary_key < MAX_KEY)
5469  mark_columns_used_by_index_no_reset(s->primary_key, read_set);
5470  break;
5471 
5472  default:
5473  DBUG_ASSERT(FALSE);
5474  }
5475  file->column_bitmaps_signal();
5476  }
5477 
5478  DBUG_VOID_RETURN;
5479 }
5480 
5481 
5482 
5496 bool TABLE::alloc_keys(uint key_count)
5497 {
5498  DBUG_ASSERT(!s->keys);
5499  max_keys= key_count;
5500  if (!(key_info= s->key_info=
5501  (KEY*) alloc_root(&mem_root, sizeof(KEY)*max_keys)))
5502  return TRUE;
5503 
5504  memset(key_info, 0, sizeof(KEY)*max_keys);
5505  return FALSE;
5506 }
5507 
5508 
5528 bool TABLE::add_tmp_key(Field_map *key_parts, char *key_name)
5529 {
5530  DBUG_ASSERT(!created && s->keys < max_keys && key_parts);
5531 
5532  KEY* cur_key= key_info + s->keys;
5533  Field **reg_field;
5534  uint i;
5535  bool key_start= TRUE;
5536  uint field_count= 0;
5537  uchar *key_buf;
5538  KEY_PART_INFO* key_part_info;
5539  uint key_len= 0;
5540 
5541  for (i= 0, reg_field=field ; *reg_field; i++, reg_field++)
5542  {
5543  if (key_parts->is_set(i))
5544  {
5545  KEY_PART_INFO tkp;
5546  // Ensure that we're not creating a key over a blob field.
5547  DBUG_ASSERT(!((*reg_field)->flags & BLOB_FLAG));
5548  /*
5549  Check if possible key is too long, ignore it if so.
5550  The reason to use MI_MAX_KEY_LENGTH (myisam's default) is that it is
5551  smaller than MAX_KEY_LENGTH (heap's default) and it's unknown whether
5552  myisam or heap will be used for tmp table.
5553  */
5554  tkp.init_from_field(*reg_field);
5555  key_len+= tkp.store_length;
5556  if (key_len > MI_MAX_KEY_LENGTH)
5557  {
5558  max_keys--;
5559  return FALSE;
5560  }
5561  }
5562  field_count++;
5563  }
5564  const uint key_part_count= key_parts->bits_set();
5565 
5566  /* Allocate key parts in the tables' mem_root. */
5567  size_t key_buf_size= sizeof(KEY_PART_INFO) * key_part_count +
5568  sizeof(ulong) * key_part_count;
5569  key_buf= (uchar*) alloc_root(&mem_root, key_buf_size);
5570 
5571  if (!key_buf)
5572  return TRUE;
5573  memset(key_buf, 0, key_buf_size);
5574  cur_key->key_part= key_part_info= (KEY_PART_INFO*) key_buf;
5575  cur_key->usable_key_parts= cur_key->user_defined_key_parts= key_part_count;
5576  cur_key->actual_key_parts= cur_key->user_defined_key_parts;
5577  s->key_parts+= key_part_count;
5578  cur_key->key_length= key_len;
5579  cur_key->algorithm= HA_KEY_ALG_BTREE;
5580  cur_key->name= key_name;
5581  cur_key->actual_flags= cur_key->flags= HA_GENERATED_KEY;
5582  cur_key->rec_per_key= (ulong*) (key_buf + sizeof(KEY_PART_INFO) * key_part_count);
5583  cur_key->table= this;
5584 
5585  if (field_count == key_part_count)
5586  covering_keys.set_bit(s->keys);
5587 
5588  keys_in_use_for_group_by.set_bit(s->keys);
5589  keys_in_use_for_order_by.set_bit(s->keys);
5590  for (i= 0, reg_field=field ; *reg_field; i++, reg_field++)
5591  {
5592  if (!(key_parts->is_set(i)))
5593  continue;
5594 
5595  if (key_start)
5596  (*reg_field)->key_start.set_bit(s->keys);
5597  key_start= FALSE;
5598  (*reg_field)->part_of_key.set_bit(s->keys);
5599  (*reg_field)->part_of_sortkey.set_bit(s->keys);
5600  (*reg_field)->flags|= PART_KEY_FLAG;
5601  key_part_info->init_from_field(*reg_field);
5602  key_part_info++;
5603  }
5604  set_if_bigger(s->max_key_length, cur_key->key_length);
5605  s->keys++;
5606  return FALSE;
5607 }
5608 
5609 /*
5610  @brief
5611  Save the specified index for later use for ref access.
5612 
5613  @param key_to_save the key to save
5614 
5615  @details
5616  Save given index as index #0. Table is configured to ignore other indexes.
5617  Memory occupied by other indexes and index parts will be freed along with
5618  the table. If the 'key_to_save' is negative then all indexes are freed.
5619  After keys info being changed, info in fields regarding taking part in keys
5620  becomes outdated. This function fixes this also.
5621  @see add_derived_key
5622 */
5623 
5624 void TABLE::use_index(int key_to_save)
5625 {
5626  DBUG_ASSERT(!created && s->keys && key_to_save < (int)s->keys);
5627 
5628  /* Correct fields' info about taking part in keys */
5629  for (int i= 0; i < (int)s->keys; i++)
5630  {
5631  uint j;
5632  KEY_PART_INFO *kp;
5633  for (kp= key_info[i].key_part, j= 0;
5634  j < key_info[i].user_defined_key_parts;
5635  j++, kp++)
5636  {
5637  if (i == key_to_save)
5638  {
5639  if (kp->field->key_start.is_set(i))
5640  kp->field->key_start.set_prefix(1);
5641  kp->field->part_of_key.set_prefix(1);
5642  kp->field->part_of_sortkey.set_prefix(1);
5643  }
5644  else
5645  {
5646  kp->field->key_start.clear_all();
5647  kp->field->part_of_key.clear_all();
5648  kp->field->part_of_sortkey.clear_all();
5649  }
5650  }
5651  }
5652 
5653  if (key_to_save < 0)
5654  {
5655  /* Drop all keys; */
5656  key_info= s->key_info= 0;
5657  s->key_parts= 0;
5658  s->keys= 0;
5659  covering_keys.clear_all();
5660  keys_in_use_for_group_by.clear_all();
5661  keys_in_use_for_order_by.clear_all();
5662  }
5663  else
5664  {
5665  /* Save the given key. No need to copy key#0. */
5666  if (key_to_save > 0)
5667  key_info[0]= key_info[key_to_save];
5668  s->keys= 1;
5669  s->key_parts= key_info[0].user_defined_key_parts;
5670  if (covering_keys.is_set(key_to_save))
5671  covering_keys.set_prefix(1);
5672  else
5673  covering_keys.clear_all();
5674  keys_in_use_for_group_by.set_prefix(1);
5675  keys_in_use_for_order_by.set_prefix(1);
5676  }
5677 }
5678 
5679 
5680 
5681 /*
5682  Mark columns the handler needs for doing an insert
5683 
5684  For now, this is used to mark fields used by the trigger
5685  as changed.
5686 */
5687 
5688 void TABLE::mark_columns_needed_for_insert()
5689 {
5691  if (triggers)
5692  {
5693  /*
5694  We don't need to mark columns which are used by ON DELETE and
5695  ON UPDATE triggers, which may be invoked in case of REPLACE or
5696  INSERT ... ON DUPLICATE KEY UPDATE, since before doing actual
5697  row replacement or update write_record() will mark all table
5698  fields as used.
5699  */
5700  triggers->mark_fields_used(TRG_EVENT_INSERT);
5701  }
5702  if (found_next_number_field)
5703  mark_auto_increment_column();
5704 }
5705 
5706 
5707 /*
5708  Cleanup this table for re-execution.
5709 
5710  SYNOPSIS
5711  TABLE_LIST::reinit_before_use()
5712 */
5713 
5714 void TABLE_LIST::reinit_before_use(THD *thd)
5715 {
5716  /*
5717  Reset old pointers to TABLEs: they are not valid since the tables
5718  were closed in the end of previous prepare or execute call.
5719  */
5720  table= 0;
5721 
5722  /*
5723  Reset table_name and table_name_length,if it is a anonymous derived table
5724  or schema table. They are not valid as TABLEs were closed in the end of
5725  previous prepare or execute call.
5726  */
5727  if (derived)
5728  {
5729  table_name= NULL;
5730  table_name_length= 0;
5731  }
5732  else if (schema_table_name)
5733  {
5734  table_name= schema_table_name;
5735  table_name_length= strlen(schema_table_name);
5736  }
5737 
5738  /* Reset is_schema_table_processed value(needed for I_S tables */
5739  schema_table_state= NOT_PROCESSED;
5740 
5741  TABLE_LIST *embedded; /* The table at the current level of nesting. */
5742  TABLE_LIST *parent_embedding= this; /* The parent nested table reference. */
5743  do
5744  {
5745  embedded= parent_embedding;
5746  if (embedded->prep_join_cond)
5747  embedded->
5748  set_join_cond(embedded->prep_join_cond->copy_andor_structure(thd));
5749  parent_embedding= embedded->embedding;
5750  }
5751  while (parent_embedding &&
5752  parent_embedding->nested_join->join_list.head() == embedded);
5753 
5754  mdl_request.ticket= NULL;
5755 }
5756 
5757 /*
5758  Return subselect that contains the FROM list this table is taken from
5759 
5760  SYNOPSIS
5761  TABLE_LIST::containing_subselect()
5762 
5763  RETURN
5764  Subselect item for the subquery that contains the FROM list
5765  this table is taken from if there is any
5766  0 - otherwise
5767 
5768 */
5769 
5770 Item_subselect *TABLE_LIST::containing_subselect()
5771 {
5772  return (select_lex ? select_lex->master_unit()->item : 0);
5773 }
5774 
5776 {
5777  return derived ? derived->first_select()->select_number : 0;
5778 }
5779 
5780 /*
5781  Compiles the tagged hints list and fills up the bitmasks.
5782 
5783  SYNOPSIS
5784  process_index_hints()
5785  table the TABLE to operate on.
5786 
5787  DESCRIPTION
5788  The parser collects the index hints for each table in a "tagged list"
5789  (TABLE_LIST::index_hints). Using the information in this tagged list
5790  this function sets the members st_table::keys_in_use_for_query,
5791  st_table::keys_in_use_for_group_by, st_table::keys_in_use_for_order_by,
5792  st_table::force_index, st_table::force_index_order,
5793  st_table::force_index_group and st_table::covering_keys.
5794 
5795  Current implementation of the runtime does not allow mixing FORCE INDEX
5796  and USE INDEX, so this is checked here. Then the FORCE INDEX list
5797  (if non-empty) is appended to the USE INDEX list and a flag is set.
5798 
5799  Multiple hints of the same kind are processed so that each clause
5800  is applied to what is computed in the previous clause.
5801  For example:
5802  USE INDEX (i1) USE INDEX (i2)
5803  is equivalent to
5804  USE INDEX (i1,i2)
5805  and means "consider only i1 and i2".
5806 
5807  Similarly
5808  USE INDEX () USE INDEX (i1)
5809  is equivalent to
5810  USE INDEX (i1)
5811  and means "consider only the index i1"
5812 
5813  It is OK to have the same index several times, e.g. "USE INDEX (i1,i1)" is
5814  not an error.
5815 
5816  Different kind of hints (USE/FORCE/IGNORE) are processed in the following
5817  order:
5818  1. All indexes in USE (or FORCE) INDEX are added to the mask.
5819  2. All IGNORE INDEX
5820 
5821  e.g. "USE INDEX i1, IGNORE INDEX i1, USE INDEX i1" will not use i1 at all
5822  as if we had "USE INDEX i1, USE INDEX i1, IGNORE INDEX i1".
5823 
5824  As an optimization if there is a covering index, and we have
5825  IGNORE INDEX FOR GROUP/ORDER, and this index is used for the JOIN part,
5826  then we have to ignore the IGNORE INDEX FROM GROUP/ORDER.
5827 
5828  RETURN VALUE
5829  FALSE no errors found
5830  TRUE found and reported an error.
5831 */
5832 bool TABLE_LIST::process_index_hints(TABLE *tbl)
5833 {
5834  /* initialize the result variables */
5835  tbl->keys_in_use_for_query= tbl->keys_in_use_for_group_by=
5836  tbl->keys_in_use_for_order_by= tbl->s->keys_in_use;
5837 
5838  /* index hint list processing */
5839  if (index_hints)
5840  {
5841  /* Temporary variables used to collect hints of each kind. */
5842  key_map index_join[INDEX_HINT_FORCE + 1];
5843  key_map index_order[INDEX_HINT_FORCE + 1];
5844  key_map index_group[INDEX_HINT_FORCE + 1];
5845  Index_hint *hint;
5846  bool have_empty_use_join= FALSE, have_empty_use_order= FALSE,
5847  have_empty_use_group= FALSE;
5848  List_iterator <Index_hint> iter(*index_hints);
5849 
5850  /* iterate over the hints list */
5851  while ((hint= iter++))
5852  {
5853  uint pos;
5854 
5855  /* process empty USE INDEX () */
5856  if (hint->type == INDEX_HINT_USE && !hint->key_name.str)
5857  {
5858  if (hint->clause & INDEX_HINT_MASK_JOIN)
5859  {
5860  index_join[hint->type].clear_all();
5861  have_empty_use_join= TRUE;
5862  }
5863  if (hint->clause & INDEX_HINT_MASK_ORDER)
5864  {
5865  index_order[hint->type].clear_all();
5866  have_empty_use_order= TRUE;
5867  }
5868  if (hint->clause & INDEX_HINT_MASK_GROUP)
5869  {
5870  index_group[hint->type].clear_all();
5871  have_empty_use_group= TRUE;
5872  }
5873  continue;
5874  }
5875 
5876  /*
5877  Check if an index with the given name exists and get his offset in
5878  the keys bitmask for the table
5879  */
5880  if (tbl->s->keynames.type_names == 0 ||
5881  (pos= find_type(&tbl->s->keynames, hint->key_name.str,
5882  hint->key_name.length, 1)) <= 0)
5883  {
5884  my_error(ER_KEY_DOES_NOT_EXITS, MYF(0), hint->key_name.str, alias);
5885  return 1;
5886  }
5887 
5888  pos--;
5889 
5890  /* add to the appropriate clause mask */
5891  if (hint->clause & INDEX_HINT_MASK_JOIN)
5892  index_join[hint->type].set_bit (pos);
5893  if (hint->clause & INDEX_HINT_MASK_ORDER)
5894  index_order[hint->type].set_bit (pos);
5895  if (hint->clause & INDEX_HINT_MASK_GROUP)
5896  index_group[hint->type].set_bit (pos);
5897  }
5898 
5899  /* cannot mix USE INDEX and FORCE INDEX */
5900  if ((!index_join[INDEX_HINT_FORCE].is_clear_all() ||
5901  !index_order[INDEX_HINT_FORCE].is_clear_all() ||
5902  !index_group[INDEX_HINT_FORCE].is_clear_all()) &&
5903  (!index_join[INDEX_HINT_USE].is_clear_all() || have_empty_use_join ||
5904  !index_order[INDEX_HINT_USE].is_clear_all() || have_empty_use_order ||
5905  !index_group[INDEX_HINT_USE].is_clear_all() || have_empty_use_group))
5906  {
5907  my_error(ER_WRONG_USAGE, MYF(0), index_hint_type_name[INDEX_HINT_USE],
5908  index_hint_type_name[INDEX_HINT_FORCE]);
5909  return 1;
5910  }
5911 
5912  /* process FORCE INDEX as USE INDEX with a flag */
5913  if (!index_order[INDEX_HINT_FORCE].is_clear_all())
5914  {
5915  tbl->force_index_order= TRUE;
5916  index_order[INDEX_HINT_USE].merge(index_order[INDEX_HINT_FORCE]);
5917  }
5918 
5919  if (!index_group[INDEX_HINT_FORCE].is_clear_all())
5920  {
5921  tbl->force_index_group= TRUE;
5922  index_group[INDEX_HINT_USE].merge(index_group[INDEX_HINT_FORCE]);
5923  }
5924 
5925  /*
5926  TODO: get rid of tbl->force_index (on if any FORCE INDEX is specified) and
5927  create tbl->force_index_join instead.
5928  Then use the correct force_index_XX instead of the global one.
5929  */
5930  if (!index_join[INDEX_HINT_FORCE].is_clear_all() ||
5931  tbl->force_index_group || tbl->force_index_order)
5932  {
5933  tbl->force_index= TRUE;
5934  index_join[INDEX_HINT_USE].merge(index_join[INDEX_HINT_FORCE]);
5935  }
5936 
5937  /* apply USE INDEX */
5938  if (!index_join[INDEX_HINT_USE].is_clear_all() || have_empty_use_join)
5939  tbl->keys_in_use_for_query.intersect(index_join[INDEX_HINT_USE]);
5940  if (!index_order[INDEX_HINT_USE].is_clear_all() || have_empty_use_order)
5941  tbl->keys_in_use_for_order_by.intersect (index_order[INDEX_HINT_USE]);
5942  if (!index_group[INDEX_HINT_USE].is_clear_all() || have_empty_use_group)
5943  tbl->keys_in_use_for_group_by.intersect (index_group[INDEX_HINT_USE]);
5944 
5945  /* apply IGNORE INDEX */
5946  tbl->keys_in_use_for_query.subtract (index_join[INDEX_HINT_IGNORE]);
5947  tbl->keys_in_use_for_order_by.subtract (index_order[INDEX_HINT_IGNORE]);
5948  tbl->keys_in_use_for_group_by.subtract (index_group[INDEX_HINT_IGNORE]);
5949  }
5950 
5951  /* make sure covering_keys don't include indexes disabled with a hint */
5952  tbl->covering_keys.intersect(tbl->keys_in_use_for_query);
5953  return 0;
5954 }
5955 
5956 
5957 size_t max_row_length(TABLE *table, const uchar *data)
5958 {
5959  TABLE_SHARE *table_s= table->s;
5960  size_t length= table_s->reclength + 2 * table_s->fields;
5961  uint *const beg= table_s->blob_field;
5962  uint *const end= beg + table_s->blob_fields;
5963 
5964  for (uint *ptr= beg ; ptr != end ; ++ptr)
5965  {
5966  Field_blob* const blob= (Field_blob*) table->field[*ptr];
5967  length+= blob->get_length((const uchar*)
5968  (data + blob->offset(table->record[0]))) +
5969  HA_KEY_BLOB_LENGTH;
5970  }
5971  return length;
5972 }
5973 
5974 
5980 void init_mdl_requests(TABLE_LIST *table_list)
5981 {
5982  for ( ; table_list ; table_list= table_list->next_global)
5983  table_list->mdl_request.init(MDL_key::TABLE,
5984  table_list->db, table_list->table_name,
5985  table_list->lock_type >= TL_WRITE_ALLOW_WRITE ?
5986  MDL_SHARED_WRITE : MDL_SHARED_READ,
5987  MDL_TRANSACTION);
5988 }
5989 
5990 
5991 
5994 {
5995  DBUG_ASSERT(uses_materialization());
5996  return get_unit()->get_result()->estimated_rowcount <= 1;
5997 }
5998 
6014 {
6015  int error= 0;
6016  if (uses_materialization())
6017  table->file->stats.records= derived->get_result()->estimated_rowcount;
6018  else
6019  error= table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);
6020  return error;
6021 }
6022 
6023 
6102 static bool add_derived_key(List<Derived_key> &derived_key_list, Field *field,
6103  table_map ref_by_tbl)
6104 {
6105  uint key= 0;
6106  Derived_key *entry= 0;
6107  List_iterator<Derived_key> ki(derived_key_list);
6108 
6109  /* Search for already existing possible key. */
6110  while ((entry= ki++))
6111  {
6112  key++;
6113  if (ref_by_tbl)
6114  {
6115  /* Search for the entry for the specified table.*/
6116  if (entry->referenced_by & ref_by_tbl)
6117  break;
6118  }
6119  else
6120  {
6121  /*
6122  Search for the special entry that should contain fields referred
6123  from any table.
6124  */
6125  if (!entry->referenced_by)
6126  break;
6127  }
6128  }
6129  /* Add new possible key if nothing is found. */
6130  if (!entry)
6131  {
6132  THD *thd= field->table->in_use;
6133  key++;
6134  entry= new (thd->stmt_arena->mem_root) Derived_key();
6135  if (!entry)
6136  return TRUE;
6137  entry->referenced_by= ref_by_tbl;
6138  entry->used_fields.clear_all();
6139  if (derived_key_list.push_back(entry, thd->stmt_arena->mem_root))
6140  return TRUE;
6141  field->table->max_keys++;
6142  }
6143  /* Don't create keys longer than REF access can use. */
6144  if (entry->used_fields.bits_set() < MAX_REF_PARTS)
6145  {
6146  field->part_of_key.set_bit(key - 1);
6147  field->flags|= PART_KEY_FLAG;
6148  entry->used_fields.set_bit(field->field_index);
6149  }
6150  return FALSE;
6151 }
6152 
6153 /*
6154  @brief
6155  Update derived table's list of possible keys
6156 
6157  @param field derived table's field to take part in a key
6158  @param values array of values that a part of equality predicate with the
6159  field above
6160  @param num_values number of elements in the array values
6161 
6162  @details
6163  This function creates/extends a list of possible keys for this derived
6164  table/view. For each table used by a value from the 'values' array the
6165  corresponding possible key is extended to include the 'field'.
6166  If there is no such possible key, then it is created. field's
6167  part_of_key bitmaps are updated accordingly.
6168  @see add_derived_key
6169 
6170  @return TRUE new possible key can't be allocated.
6171  @return FALSE list of possible keys successfully updated.
6172 */
6173 
6174 bool TABLE_LIST::update_derived_keys(Field *field, Item **values,
6175  uint num_values)
6176 {
6177  /* Don't bother with keys for CREATE VIEW and for BLOB fields. */
6178  if (field->table->in_use->lex->is_ps_or_view_context_analysis() ||
6179  field->flags & BLOB_FLAG)
6180  return FALSE;
6181 
6182  /* Allow all keys to be used. */
6183  if (derived_key_list.elements == 0)
6184  {
6185  table->keys_in_use_for_query.set_all();
6186  table->s->uniques= 0;
6187  }
6188 
6189  for (uint i= 0; i < num_values; i++)
6190  {
6191  table_map tables= values[i]->used_tables() & ~PSEUDO_TABLE_BITS;
6192  if (!tables || values[i]->real_item()->type() != Item::FIELD_ITEM)
6193  continue;
6194  for (table_map tbl= 1; tables >= tbl; tbl<<= 1)
6195  {
6196  if (! (tables & tbl))
6197  continue;
6198  if (add_derived_key(derived_key_list, field, tbl))
6199  return TRUE;
6200  }
6201  }
6202  /* Extend key which includes all referenced fields. */
6203  if (add_derived_key(derived_key_list, field, (table_map)0))
6204  return TRUE;
6205  return FALSE;
6206 }
6207 
6208 
6209 /*
6210  Comparison function for Derived_key entries.
6211  See TABLE_LIST::generate_keys.
6212 */
6213 
6214 static int Derived_key_comp(Derived_key *e1, Derived_key *e2, void *arg)
6215 {
6216  /* Move entries for tables with greater table bit to the end. */
6217  return ((e1->referenced_by < e2->referenced_by) ? -1 :
6218  ((e1->referenced_by > e2->referenced_by) ? 1 : 0));
6219 }
6220 
6221 
6238 {
6239  List_iterator<Derived_key> it(derived_key_list);
6240  Derived_key *entry;
6241  uint key= 0;
6242  char buf[NAME_CHAR_LEN];
6243  DBUG_ASSERT(uses_materialization());
6244 
6245  if (!derived_key_list.elements)
6246  return FALSE;
6247 
6248  if (table->alloc_keys(derived_key_list.elements))
6249  return TRUE;
6250 
6251  /* Sort entries to make key numbers sequence deterministic. */
6252  derived_key_list.sort((Node_cmp_func)Derived_key_comp, 0);
6253  while ((entry= it++))
6254  {
6255  sprintf(buf, "<auto_key%i>", key++);
6256  if (table->add_tmp_key(&entry->used_fields,
6257  table->in_use->strdup(buf)))
6258  return TRUE;
6259  }
6260  return FALSE;
6261 }
6262 
6263 
6264 /*
6265  @brief Run derived tables/view handling phases on underlying select_lex.
6266 
6267  @param lex LEX for this thread
6268  @param phases derived tables/views handling phases to run
6269  (set of DT_XXX constants)
6270  @details
6271  This function runs this derived table through specified 'phases' and used for
6272  handling materialized derived tables on all stages except preparation.
6273  The reason that on all stages except prepare derived tables of different
6274  type needs different handling. Materializable derived tables needs
6275  processor to be called directly on them. Mergeable derived tables doesn't
6276  need such call, but require diving into them to process underlying derived
6277  tables. This differs from the mysql_handle_derived which runs preparation
6278  processor on all derived tables without exception. 'lex' is passed as
6279  an argument to called functions.
6280 
6281  @see mysql_handle_derived.
6282 
6283  @return TRUE on error
6284  @return FALSE ok
6285 */
6286 
6287 bool TABLE_LIST::handle_derived(LEX *lex,
6288  bool (*processor)(THD*, LEX*, TABLE_LIST*))
6289 {
6290  SELECT_LEX_UNIT *unit= get_unit();
6291  DBUG_ASSERT(unit);
6292 
6293  /* Dive into a merged derived table or materialize as is otherwise. */
6294  if (!uses_materialization())
6295  {
6296  for (SELECT_LEX *sl= unit->first_select(); sl; sl= sl->next_select())
6297  if (sl->handle_derived(lex, processor))
6298  return TRUE;
6299  }
6300  else
6301  return mysql_handle_single_derived(lex, this, processor);
6302 
6303  return FALSE;
6304 }
6305 
6306 
6315 st_select_lex_unit *TABLE_LIST::get_unit() const
6316 {
6317  return (view ? &view->unit : derived);
6318 }
6319 
6320 
6335 {
6336  memset(const_key_parts, 0, sizeof(key_part_map) * s->keys);
6337 
6338  if (conds == NULL)
6339  return FALSE;
6340 
6341  for (uint index= 0; index < s->keys; index++)
6342  {
6343  KEY_PART_INFO *keyinfo= key_info[index].key_part;
6344  KEY_PART_INFO *keyinfo_end= keyinfo + key_info[index].user_defined_key_parts;
6345 
6346  for (key_part_map part_map= (key_part_map)1;
6347  keyinfo < keyinfo_end;
6348  keyinfo++, part_map<<= 1)
6349  {
6350  if (const_expression_in_where(conds, NULL, keyinfo->field))
6351  const_key_parts[index]|= part_map;
6352  }
6353  }
6354  return FALSE;
6355 }
6356 
6357 
6371 {
6372  DBUG_ENTER("check_read_removal");
6373  DBUG_ASSERT(file->ha_table_flags() & HA_READ_BEFORE_WRITE_REMOVAL);
6374  DBUG_ASSERT(index != MAX_KEY);
6375 
6376  // Index must be unique
6377  if ((key_info[index].flags & HA_NOSAME) == 0)
6378  DBUG_RETURN(false);
6379 
6380  // Full index must be used
6381  bitmap_clear_all(&tmp_set);
6382  mark_columns_used_by_index_no_reset(index, &tmp_set);
6383  if (!bitmap_cmp(&tmp_set, read_set))
6384  DBUG_RETURN(false);
6385 
6386  // Start read removal in handler
6387  DBUG_RETURN(file->start_read_removal());
6388 }
6389 
6390 
6399 bool is_simple_order(ORDER *order)
6400 {
6401  for (ORDER *ord= order; ord; ord= ord->next)
6402  {
6403  if (ord->item[0]->real_item()->type() != Item::FIELD_ITEM)
6404  return FALSE;
6405  }
6406  return TRUE;
6407 }