[packages/mysql/MYSQL_5_6] Rel 93.0.1; Percona 5.6.51-93.0 + post-EOL fixes from Percona 5.7

arekm arekm at pld-linux.org
Mon Nov 2 14:05:20 CET 2026


commit d6e5d32452c0af7e2bbf8af0cd1e7e8fe15e523d
Author: Arkadiusz Miśkiewicz <arekm at maven.pl>
Date:   Mon Nov 2 14:04:28 2026 +0100

    Rel 93.0.1; Percona 5.6.51-93.0 + post-EOL fixes from Percona 5.7
    
    Fixes CVE-2024-20963.

 mysql-append-identifier-overread.patch |    18 +
 mysql-avg-decimal-scale.patch          |    15 +
 mysql-blob-prefix-key-field.patch      | 15279 +++++++++++++++++++++++++++++++
 mysql-btr-merge-backward-scan.patch    |    32 +
 mysql-client-table-leak.patch          |    24 +
 mysql-connect-attrs-oob.patch          |    25 +
 mysql-drop-user-acl-cache.patch        |    15 +
 mysql-dump-comment-buffer-reuse.patch  |    18 +
 mysql-dump-server-version.patch        |    66 +
 mysql-dump-tablespace-escape.patch     |  7496 +++++++++++++++
 mysql-dump-view-query-escape.patch     |    35 +
 mysql-fts-doc-id-cmp.patch             |    48 +
 mysql-fts-drop-add-index.patch         |    87 +
 mysql-fts-optimize-last-word.patch     |   133 +
 mysql-fts-self-fk-cascade.patch        |   104 +
 mysql-getopt-help-overrun.patch        |    33 +
 mysql-greedy-search-no-plan.patch      |    22 +
 mysql-join-max-tables.patch            |    19 +
 mysql-lex-end-comment-delimiter.patch  |    16 +
 mysql-make-set-pullout.patch           |    35 +
 mysql-md5-length.patch                 |    35 +
 mysql-privilege-desc-bounds.patch      |    14 +
 mysql-subselect-null-name.patch        |    16 +
 mysql-table-map-name-length.patch      |    28 +
 mysql-updatexml-root-copy.patch        |    16 +
 mysql-xml-parse-slash.patch            |    45 +
 mysql.init                             |     3 +-
 mysql.spec                             |    76 +-
 percona-server-5.6.51-93.0.patch       |  3112 +++++++
 29 files changed, 26857 insertions(+), 8 deletions(-)
---
diff --git a/mysql.spec b/mysql.spec
index 67b30f6..4d094e0 100644
--- a/mysql.spec
+++ b/mysql.spec
@@ -30,8 +30,8 @@
 %undefine	with_tokudb
 %endif
 
-%define		rel	3
-%define		percona_rel	91.0
+%define		rel	1
+%define		percona_rel	93.0
 Summary:	MySQL: a very fast and reliable SQL database engine
 Summary(de.UTF-8):	MySQL: ist eine SQL-Datenbank
 Summary(fr.UTF-8):	MySQL: un serveur SQL rapide et fiable
@@ -47,9 +47,10 @@ License:	GPL + MySQL FLOSS Exception
 Group:		Applications/Databases
 # Source0Download: http://dev.mysql.com/downloads/mysql/5.5.html#downloads
 # Source0:	http://vesta.informatik.rwth-aachen.de/mysql/Downloads/MySQL-5.5/%{name}-%{version}.tar.gz
-Source0:	http://www.percona.com/downloads/Percona-Server-5.6/LATEST/source/tarball/percona-server-%{version}-%{percona_rel}.tar.gz
+# last Percona 5.6 source tarball; 92.0 and 93.0 were published as git tags only, see Patch100
+Source0:	https://downloads.percona.com/downloads/Percona-Server-5.6/Percona-Server-%{version}-91.0/source/tarball/percona-server-%{version}-91.0.tar.gz
 # Source0-md5:	05f0f2fbba5dec1d78bb56998a6749c7
-Source100:	http://www.sphinxsearch.com/files/sphinx-2.2.11-release.tar.gz
+Source100:	https://sphinxsearch.com/files/sphinx-2.2.11-release.tar.gz
 # Source100-md5:	5cac34f3d78a9d612ca4301abfcbd666
 Source1:	%{name}.init
 Source2:	%{name}.sysconfig
@@ -89,16 +90,44 @@ Patch24:	%{name}-cmake.patch
 
 Patch26:	mysqldumpslow-clusters.patch
 Patch27:	x32.patch
+Patch100:	percona-server-%{version}-%{percona_rel}.patch
+# fixes Percona carried in 5.7.44-48..60 (post-EOL), ported to 5.6; see each patch
+Patch101:	%{name}-getopt-help-overrun.patch
+Patch102:	%{name}-md5-length.patch
+Patch103:	%{name}-client-table-leak.patch
+Patch104:	%{name}-append-identifier-overread.patch
+Patch105:	%{name}-subselect-null-name.patch
+Patch106:	%{name}-privilege-desc-bounds.patch
+Patch107:	%{name}-updatexml-root-copy.patch
+Patch108:	%{name}-connect-attrs-oob.patch
+Patch109:	%{name}-table-map-name-length.patch
+Patch110:	%{name}-drop-user-acl-cache.patch
+Patch111:	%{name}-xml-parse-slash.patch
+Patch112:	%{name}-avg-decimal-scale.patch
+Patch113:	%{name}-dump-server-version.patch
+Patch114:	%{name}-lex-end-comment-delimiter.patch
+Patch115:	%{name}-fts-optimize-last-word.patch
+Patch116:	%{name}-btr-merge-backward-scan.patch
+Patch117:	%{name}-dump-tablespace-escape.patch
+Patch118:	%{name}-dump-view-query-escape.patch
+Patch119:	%{name}-join-max-tables.patch
+Patch120:	%{name}-blob-prefix-key-field.patch
+Patch121:	%{name}-fts-doc-id-cmp.patch
+Patch122:	%{name}-greedy-search-no-plan.patch
+Patch123:	%{name}-make-set-pullout.patch
+Patch124:	%{name}-dump-comment-buffer-reuse.patch
+Patch125:	%{name}-fts-self-fk-cascade.patch
+Patch126:	%{name}-fts-drop-add-index.patch
 URL:		http://www.mysql.com/products/community/
 BuildRequires:	bison >= 1.875
 BuildRequires:	cmake >= 2.6
+BuildRequires:	libaio-devel
 BuildRequires:	readline-devel >= 6.2
 %if "%{pld_release}" == "ac"
 BuildRequires:	libstdc++4-devel >= 5:4.0
 %else
 BuildRequires:	libstdc++-devel >= 5:4.0
 %endif
-BuildRequires:	automake
 %{?with_system_hsclient:BuildRequires:	libhsclient-devel}
 %{?with_tcpd:BuildRequires:	libwrap-devel}
 BuildRequires:	ncurses-devel >= 4.2
@@ -106,7 +135,6 @@ BuildRequires:	ncurses-devel >= 4.2
 BuildRequires:	pam-devel
 %{?with_autodeps:BuildRequires:	perl-DBI}
 BuildRequires:	perl-devel >= 1:5.6.1
-BuildRequires:	python-modules
 BuildRequires:	rpm-perlprov >= 4.1-13
 BuildRequires:	rpmbuild(macros) >= 1.597
 BuildRequires:	sed >= 4.0
@@ -508,7 +536,8 @@ This package contains the standard MySQL NDB CPC Daemon.
 Ten pakiet zawiera standardowego demona MySQL NDB CPC.
 
 %prep
-%setup -q -n percona-server-%{version}-%{percona_rel} %{?with_sphinx:-a100}
+%setup -q -n percona-server-%{version}-91.0 %{?with_sphinx:-a100}
+%patch -P100 -p1
 
 # we want to use old, mysql compatible client library name
 find . -name CMakeLists.txt -exec sed -i -e 's#perconaserverclient#mysqlclient#g' "{}" ";"
@@ -545,6 +574,33 @@ mv sphinx-*/mysqlse storage/sphinx
 #%patch26 -p1
 %patch -P27 -p1
 
+%patch -P101 -p1
+%patch -P102 -p1
+%patch -P103 -p1
+%patch -P104 -p1
+%patch -P105 -p1
+%patch -P106 -p1
+%patch -P107 -p1
+%patch -P108 -p1
+%patch -P109 -p1
+%patch -P110 -p1
+%patch -P111 -p1
+%patch -P112 -p1
+%patch -P113 -p1
+%patch -P114 -p1
+%patch -P115 -p1
+%patch -P116 -p1
+%patch -P117 -p1
+%patch -P118 -p1
+%patch -P119 -p1
+%patch -P120 -p1
+%patch -P121 -p1
+%patch -P122 -p1
+%patch -P123 -p1
+%patch -P124 -p1
+%patch -P125 -p1
+%patch -P126 -p1
+
 # to get these files rebuild
 [ -f sql/sql_yacc.cc ] && %{__rm} sql/sql_yacc.cc
 [ -f sql/sql_yacc.h ] && %{__rm} sql/sql_yacc.h
@@ -708,6 +764,12 @@ mv $RPM_BUILD_ROOT{%{_bindir},%{_sbindir}}/mysqlcheck
 # not needed
 %{__rm} $RPM_BUILD_ROOT%{_libdir}/%{name}/plugin/libdaemon_example.*
 %{__rm} $RPM_BUILD_ROOT%{_libdir}/%{name}/plugin/daemon_example.ini
+%{__rm} $RPM_BUILD_ROOT%{_libdir}/%{name}/plugin/{udf_example,test_udf_services}.so
+%if %{with tokudb}
+# PerconaFT and TokuBackup install their docs and API header into the prefix
+%{__rm} $RPM_BUILD_ROOT%{_prefix}/{COPYING.AGPLv3,COPYING.GPLv2,PATENTS,README.md}
+%{__rm} $RPM_BUILD_ROOT%{_includedir}/backup.h
+%endif
 
 # not an .info file
 %{__rm} $RPM_BUILD_ROOT%{_infodir}/mysql.info
diff --git a/mysql-append-identifier-overread.patch b/mysql-append-identifier-overread.patch
new file mode 100644
index 0000000..0e44ddc
--- /dev/null
+++ b/mysql-append-identifier-overread.patch
@@ -0,0 +1,18 @@
+append_identifier() copied a whole multibyte character past the end of an
+identifier ending in a truncated one, e.g. NAME_CONST(0xE0,..) in a view
+(Bug#22958632).
+https://github.com/percona/percona-server/commit/b3d19a5392 (https://github.com/mysql/mysql-server/commit/5f3490aea8c)
+
+--- percona-server-5.6.51-91.0.orig/sql/sql_show.cc
++++ percona-server-5.6.51-91.0/sql/sql_show.cc
+@@ -1195,7 +1195,9 @@ append_identifier(THD *thd, String *packet, const char *name, uint length,
+       to_length= 1;
+     if (to_length == 1 && chr == (uchar) quote_char)
+       packet->append(&quote_char, 1, system_charset_info);
+-    packet->append(to_name, to_length, system_charset_info);
++    packet->append(to_name,
++                   min(to_length, static_cast<size_t>(name_end - to_name)),
++                   system_charset_info);
+   }
+   packet->append(&quote_char, 1, system_charset_info);
+ }
diff --git a/mysql-avg-decimal-scale.patch b/mysql-avg-decimal-scale.patch
new file mode 100644
index 0000000..36aa74f
--- /dev/null
+++ b/mysql-avg-decimal-scale.patch
@@ -0,0 +1,15 @@
+AVG() of a DECIMAL argument with more decimals than precision overflowed a
+global lookup table (Bug#36563773).
+https://github.com/percona/percona-server/commit/2a26b295f3 (https://github.com/mysql/mysql-server/commit/2f67801d010)
+
+--- percona-server-5.6.51-91.0.orig/sql/item_sum.cc
++++ percona-server-5.6.51-91.0/sql/item_sum.cc
+@@ -1640,7 +1640,7 @@ void Item_sum_avg::fix_length_and_dec()
+                                                              decimals,
+                                                              unsigned_flag);
+     f_precision= min(precision+DECIMAL_LONGLONG_DIGITS, DECIMAL_MAX_PRECISION);
+-    f_scale=  args[0]->decimals;
++    f_scale = min<uint>(args[0]->decimals, f_precision);
+     dec_bin_size= my_decimal_get_binary_size(f_precision, f_scale);
+   }
+   else {
diff --git a/mysql-blob-prefix-key-field.patch b/mysql-blob-prefix-key-field.patch
new file mode 100644
index 0000000..f0be9f6
--- /dev/null
+++ b/mysql-blob-prefix-key-field.patch
@@ -0,0 +1,15279 @@
+Range queries on a BLOB/TEXT prefix key extended with primary key parts
+read the whole column through the key part and crashed (Bug#31360522).
+https://github.com/percona/percona-server/commit/170d346611 (https://github.com/mysql/mysql-server/commit/c51237cec9f)
+https://github.com/percona/percona-server/commit/115708f851
+
+--- percona-server-5.6.51-91.0.orig/sql/sql_partition.cc
++++ percona-server-5.6.51-91.0/sql/sql_partition.cc
+@@ -849,6 +849,12 @@ static bool handle_list_of_fields(List_iterator<char> it,
+       for (i= 0; i < num_key_parts; i++)
+       {
+         Field *field= table->key_info[primary_key].key_part[i].field;
++        // BLOB/TEXT columns are not allowed in partitioning keys.
++        if (field->flags & BLOB_FLAG)
++        {
++          my_error(ER_BLOB_FIELD_IN_PART_FUNC_ERROR, MYF(0));
++          DBUG_RETURN(TRUE);
++        }
+         field->flags|= GET_FIXED_FIELDS_FLAG;
+       }
+     }
+new file mode 100644
+--- /dev/null
++++ percona-server-5.6.51-91.0/sql/sql_partition.cc.orig
+@@ -0,0 +1,8514 @@
++/* Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved.
++
++   This program is free software; you can redistribute it and/or modify
++   it under the terms of the GNU General Public License, version 2.0,
++   as published by the Free Software Foundation.
++
++   This program is also distributed with certain software (including
++   but not limited to OpenSSL) that is licensed under separate terms,
++   as designated in a particular file or component or in included license
++   documentation.  The authors of MySQL hereby grant you an additional
++   permission to link the program and your derivative works with the
++   separately licensed software that they have included with MySQL.
++
++   This program is distributed in the hope that it will be useful,
++   but WITHOUT ANY WARRANTY; without even the implied warranty of
++   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
++   GNU General Public License, version 2.0, for more details.
++
++   You should have received a copy of the GNU General Public License
++   along with this program; if not, write to the Free Software
++   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA */
++
++/*
++  This file is a container for general functionality related
++  to partitioning introduced in MySQL version 5.1. It contains functionality
++  used by all handlers that support partitioning, such as
++  the partitioning handler itself and the NDB handler.
++  (Much of the code in this file has been split into partition_info.cc and
++   the header files partition_info.h + partition_element.h + sql_partition.h)
++
++  The first version was written by Mikael Ronstrom 2004-2006.
++  Various parts of the optimizer code was written by Sergey Petrunia.
++  Code have been maintained by Mattias Jonsson.
++  The second version was written by Mikael Ronstrom 2006-2007 with some
++  final fixes for partition pruning in 2008-2009 with assistance from Sergey
++  Petrunia and Mattias Jonsson.
++
++  The first version supports RANGE partitioning, LIST partitioning, HASH
++  partitioning and composite partitioning (hereafter called subpartitioning)
++  where each RANGE/LIST partitioning is HASH partitioned. The hash function
++  can either be supplied by the user or by only a list of fields (also
++  called KEY partitioning), where the MySQL server will use an internal
++  hash function.
++  There are quite a few defaults that can be used as well.
++
++  The second version introduces a new variant of RANGE and LIST partitioning
++  which is often referred to as column lists in the code variables. This
++  enables a user to specify a set of columns and their concatenated value
++  as the partition value. By comparing the concatenation of these values
++  the proper partition can be choosen.
++*/
++
++/* Some general useful functions */
++
++#define MYSQL_LEX 1
++#include "sql_priv.h"
++#include "unireg.h"                    // REQUIRED: for other includes
++#include "sql_partition.h"
++#include "key.h"                            // key_restore
++#include "sql_parse.h"                      // parse_sql
++#include "sql_cache.h"                      // query_cache_invalidate3
++#include "lock.h"                           // mysql_lock_remove
++#include "sql_show.h"                       // append_identifier
++#include <errno.h>
++#include <m_ctype.h>
++#include "my_md5.h"
++#include "transaction.h"
++#include "debug_sync.h"
++
++#include "sql_base.h"                   // close_all_tables_for_name
++#include "sql_table.h"                  // build_table_filename,
++                                        // build_table_shadow_filename,
++                                        // table_to_filename
++                                        // mysql_*_alter_copy_data
++#include "opt_range.h"                  // store_key_image_to_rec
++#include "sql_analyse.h"                // append_escaped
++#include "sql_alter.h"                  // Alter_table_ctx
++
++#include <algorithm>
++using std::max;
++using std::min;
++
++#ifdef WITH_PARTITION_STORAGE_ENGINE
++#include "ha_partition.h"
++
++#define ERROR_INJECT_CRASH(code) \
++  DBUG_EVALUATE_IF(code, (DBUG_SUICIDE(), 0), 0)
++#define ERROR_INJECT_ERROR(code) \
++  DBUG_EVALUATE_IF(code, (my_error(ER_UNKNOWN_ERROR, MYF(0)), TRUE), 0)
++
++/*
++  Partition related functions declarations and some static constants;
++*/
++const LEX_STRING partition_keywords[]=
++{
++  { C_STRING_WITH_LEN("HASH") },
++  { C_STRING_WITH_LEN("RANGE") },
++  { C_STRING_WITH_LEN("LIST") }, 
++  { C_STRING_WITH_LEN("KEY") },
++  { C_STRING_WITH_LEN("MAXVALUE") },
++  { C_STRING_WITH_LEN("LINEAR ") },
++  { C_STRING_WITH_LEN(" COLUMNS") },
++  { C_STRING_WITH_LEN("ALGORITHM") }
++
++};
++static const char *part_str= "PARTITION";
++static const char *sub_str= "SUB";
++static const char *by_str= "BY";
++static const char *space_str= " ";
++static const char *equal_str= "=";
++static const char *end_paren_str= ")";
++static const char *begin_paren_str= "(";
++static const char *comma_str= ",";
++
++int get_partition_id_list_col(partition_info *part_info,
++                              uint32 *part_id,
++                              longlong *func_value);
++int get_partition_id_list(partition_info *part_info,
++                          uint32 *part_id,
++                          longlong *func_value);
++int get_partition_id_range_col(partition_info *part_info,
++                               uint32 *part_id,
++                               longlong *func_value);
++int get_partition_id_range(partition_info *part_info,
++                           uint32 *part_id,
++                           longlong *func_value);
++static int get_part_id_charset_func_part(partition_info *part_info,
++                                         uint32 *part_id,
++                                         longlong *func_value);
++static int get_part_id_charset_func_subpart(partition_info *part_info,
++                                            uint32 *part_id);
++int get_partition_id_hash_nosub(partition_info *part_info,
++                                uint32 *part_id,
++                                longlong *func_value);
++int get_partition_id_key_nosub(partition_info *part_info,
++                               uint32 *part_id,
++                               longlong *func_value);
++int get_partition_id_linear_hash_nosub(partition_info *part_info,
++                                       uint32 *part_id,
++                                       longlong *func_value);
++int get_partition_id_linear_key_nosub(partition_info *part_info,
++                                      uint32 *part_id,
++                                      longlong *func_value);
++int get_partition_id_with_sub(partition_info *part_info,
++                              uint32 *part_id,
++                              longlong *func_value);
++int get_partition_id_hash_sub(partition_info *part_info,
++                              uint32 *part_id); 
++int get_partition_id_key_sub(partition_info *part_info,
++                             uint32 *part_id); 
++int get_partition_id_linear_hash_sub(partition_info *part_info,
++                                     uint32 *part_id); 
++int get_partition_id_linear_key_sub(partition_info *part_info,
++                                    uint32 *part_id); 
++static uint32 get_next_partition_via_walking(PARTITION_ITERATOR*);
++static void set_up_range_analysis_info(partition_info *part_info);
++static uint32 get_next_subpartition_via_walking(PARTITION_ITERATOR*);
++#endif
++
++uint32 get_next_partition_id_range(PARTITION_ITERATOR* part_iter);
++uint32 get_next_partition_id_list(PARTITION_ITERATOR* part_iter);
++int get_part_iter_for_interval_via_mapping(partition_info *part_info,
++                                           bool is_subpart,
++                                           uint32 *store_length_array,
++                                           uchar *min_value, uchar *max_value,
++                                           uint min_len, uint max_len,
++                                           uint flags,
++                                           PARTITION_ITERATOR *part_iter);
++int get_part_iter_for_interval_cols_via_map(partition_info *part_info,
++                                            bool is_subpart,
++                                            uint32 *store_length_array,
++                                            uchar *min_value, uchar *max_value,
++                                            uint min_len, uint max_len,
++                                            uint flags,
++                                            PARTITION_ITERATOR *part_iter);
++int get_part_iter_for_interval_via_walking(partition_info *part_info,
++                                           bool is_subpart,
++                                           uint32 *store_length_array,
++                                           uchar *min_value, uchar *max_value,
++                                           uint min_len, uint max_len,
++                                           uint flags,
++                                           PARTITION_ITERATOR *part_iter);
++
++#ifdef WITH_PARTITION_STORAGE_ENGINE
++static int cmp_rec_and_tuple(part_column_list_val *val, uint32 nvals_in_rec);
++static int cmp_rec_and_tuple_prune(part_column_list_val *val,
++                                   uint32 n_vals_in_rec,
++                                   bool is_left_endpoint,
++                                   bool include_endpoint);
++
++/*
++  Convert constants in VALUES definition to the character set the
++  corresponding field uses.
++
++  SYNOPSIS
++    convert_charset_partition_constant()
++    item                                Item to convert
++    cs                                  Character set to convert to
++
++  RETURN VALUE
++    NULL                                Error
++    item                                New converted item
++*/
++
++Item* convert_charset_partition_constant(Item *item, const CHARSET_INFO *cs)
++{
++  THD *thd= current_thd;
++  Name_resolution_context *context= &thd->lex->current_select->context;
++  TABLE_LIST *save_list= context->table_list;
++  const char *save_where= thd->where;
++
++  item= item->safe_charset_converter(cs);
++  context->table_list= NULL;
++  thd->where= "convert character set partition constant";
++  if (!item || item->fix_fields(thd, (Item**)NULL))
++    item= NULL;
++  thd->where= save_where;
++  context->table_list= save_list;
++  return item;
++}
++
++
++/**
++  A support function to check if a name is in a list of strings.
++
++  @param name        String searched for
++  @param list_names  A list of names searched in
++
++  @return True if if the name is in the list.
++    @retval true   String found
++    @retval false  String not found
++*/
++
++static bool is_name_in_list(char *name, List<char> list_names)
++{
++  List_iterator<char> names_it(list_names);
++  uint num_names= list_names.elements;
++  uint i= 0;
++
++  do
++  {
++    char *list_name= names_it++;
++    if (!(my_strcasecmp(system_charset_info, name, list_name)))
++      return TRUE;
++  } while (++i < num_names);
++  return FALSE;
++}
++
++
++
++/*
++  Set-up defaults for partitions. 
++
++  SYNOPSIS
++    partition_default_handling()
++    table                         Table object
++    part_info                     Partition info to set up
++    is_create_table_ind           Is this part of a table creation
++    normalized_path               Normalized path name of table and database
++
++  RETURN VALUES
++    TRUE                          Error
++    FALSE                         Success
++*/
++
++bool partition_default_handling(TABLE *table, partition_info *part_info,
++                                bool is_create_table_ind,
++                                const char *normalized_path)
++{
++  DBUG_ENTER("partition_default_handling");
++
++  if (!is_create_table_ind)
++  {
++    if (part_info->use_default_num_partitions)
++    {
++      if (table->file->get_no_parts(normalized_path, &part_info->num_parts))
++      {
++        DBUG_RETURN(TRUE);
++      }
++    }
++    else if (part_info->is_sub_partitioned() &&
++             part_info->use_default_num_subpartitions)
++    {
++      uint num_parts;
++      if (table->file->get_no_parts(normalized_path, &num_parts))
++      {
++        DBUG_RETURN(TRUE);
++      }
++      DBUG_ASSERT(part_info->num_parts > 0);
++      DBUG_ASSERT((num_parts % part_info->num_parts) == 0);
++      part_info->num_subparts= num_parts / part_info->num_parts;
++    }
++  }
++  part_info->set_up_defaults_for_partitioning(table->file,
++                                              NULL, 0U);
++  DBUG_RETURN(FALSE);
++}
++
++
++/*
++  A useful routine used by update_row for partition handlers to calculate
++  the partition ids of the old and the new record.
++
++  SYNOPSIS
++    get_part_for_update()
++    old_data                Buffer of old record
++    new_data                Buffer of new record
++    rec0                    Reference to table->record[0]
++    part_info               Reference to partition information
++    out:old_part_id         The returned partition id of old record 
++    out:new_part_id         The returned partition id of new record
++
++  RETURN VALUE
++    0                       Success
++    > 0                     Error code
++*/
++
++int get_parts_for_update(const uchar *old_data, uchar *new_data,
++                         const uchar *rec0, partition_info *part_info,
++                         uint32 *old_part_id, uint32 *new_part_id,
++                         longlong *new_func_value)
++{
++  Field **part_field_array= part_info->full_part_field_array;
++  int error;
++  longlong old_func_value;
++  DBUG_ENTER("get_parts_for_update");
++
++  DBUG_ASSERT(new_data == rec0);             // table->record[0]
++  set_field_ptr(part_field_array, old_data, rec0);
++  error= part_info->get_partition_id(part_info, old_part_id,
++                                     &old_func_value);
++  set_field_ptr(part_field_array, rec0, old_data);
++  if (unlikely(error))                             // Should never happen
++  {
++    DBUG_ASSERT(0);
++    DBUG_RETURN(error);
++  }
++#ifdef NOT_NEEDED
++  if (new_data == rec0)
++#endif
++  {
++    if (unlikely(error= part_info->get_partition_id(part_info,
++                                                    new_part_id,
++                                                    new_func_value)))
++    {
++      DBUG_RETURN(error);
++    }
++  }
++#ifdef NOT_NEEDED
++  else
++  {
++    /*
++      This branch should never execute but it is written anyways for
++      future use. It will be tested by ensuring that the above
++      condition is false in one test situation before pushing the code.
++    */
++    set_field_ptr(part_field_array, new_data, rec0);
++    error= part_info->get_partition_id(part_info, new_part_id,
++                                       new_func_value);
++    set_field_ptr(part_field_array, rec0, new_data);
++    if (unlikely(error))
++    {
++      DBUG_RETURN(error);
++    }
++  }
++#endif
++  DBUG_RETURN(0);
++}
++
++
++/*
++  A useful routine used by delete_row for partition handlers to calculate
++  the partition id.
++
++  SYNOPSIS
++    get_part_for_delete()
++    buf                     Buffer of old record
++    rec0                    Reference to table->record[0]
++    part_info               Reference to partition information
++    out:part_id             The returned partition id to delete from
++
++  RETURN VALUE
++    0                       Success
++    > 0                     Error code
++
++  DESCRIPTION
++    Dependent on whether buf is not record[0] we need to prepare the
++    fields. Then we call the function pointer get_partition_id to
++    calculate the partition id.
++*/
++
++int get_part_for_delete(const uchar *buf, const uchar *rec0,
++                        partition_info *part_info, uint32 *part_id)
++{
++  int error;
++  longlong func_value;
++  DBUG_ENTER("get_part_for_delete");
++
++  if (likely(buf == rec0))
++  {
++    if (unlikely((error= part_info->get_partition_id(part_info, part_id,
++                                                     &func_value))))
++    {
++      DBUG_RETURN(error);
++    }
++    DBUG_PRINT("info", ("Delete from partition %d", *part_id));
++  }
++  else
++  {
++    Field **part_field_array= part_info->full_part_field_array;
++    set_field_ptr(part_field_array, buf, rec0);
++    error= part_info->get_partition_id(part_info, part_id, &func_value);
++    set_field_ptr(part_field_array, rec0, buf);
++    if (unlikely(error))
++    {
++      DBUG_RETURN(error);
++    }
++    DBUG_PRINT("info", ("Delete from partition %d (path2)", *part_id));
++  }
++  DBUG_RETURN(0);
++}
++
++
++/*
++  This method is used to set-up both partition and subpartitioning
++  field array and used for all types of partitioning.
++  It is part of the logic around fix_partition_func.
++
++  SYNOPSIS
++    set_up_field_array()
++    table                TABLE object for which partition fields are set-up
++    sub_part             Is the table subpartitioned as well
++
++  RETURN VALUE
++    TRUE                 Error, some field didn't meet requirements
++    FALSE                Ok, partition field array set-up
++
++  DESCRIPTION
++
++    A great number of functions below here is part of the fix_partition_func
++    method. It is used to set up the partition structures for execution from
++    openfrm. It is called at the end of the openfrm when the table struct has
++    been set-up apart from the partition information.
++    It involves:
++    1) Setting arrays of fields for the partition functions.
++    2) Setting up binary search array for LIST partitioning
++    3) Setting up array for binary search for RANGE partitioning
++    4) Setting up key_map's to assist in quick evaluation whether one
++       can deduce anything from a given index of what partition to use
++    5) Checking whether a set of partitions can be derived from a range on
++       a field in the partition function.
++    As part of doing this there is also a great number of error controls.
++    This is actually the place where most of the things are checked for
++    partition information when creating a table.
++    Things that are checked includes
++    1) All fields of partition function in Primary keys and unique indexes
++       (if not supported)
++
++
++    Create an array of partition fields (NULL terminated). Before this method
++    is called fix_fields or find_table_in_sef has been called to set
++    GET_FIXED_FIELDS_FLAG on all fields that are part of the partition
++    function.
++*/
++
++static bool set_up_field_array(TABLE *table,
++                              bool is_sub_part)
++{
++  Field **ptr, *field, **field_array;
++  uint num_fields= 0;
++  uint size_field_array;
++  uint i= 0;
++  uint inx;
++  partition_info *part_info= table->part_info;
++  int result= FALSE;
++  DBUG_ENTER("set_up_field_array");
++
++  ptr= table->field;
++  while ((field= *(ptr++))) 
++  {
++    if (field->flags & GET_FIXED_FIELDS_FLAG)
++      num_fields++;
++  }
++  if (num_fields > MAX_REF_PARTS)
++  {
++    char *err_str;
++    if (is_sub_part)
++      err_str= (char*)"subpartition function";
++    else
++      err_str= (char*)"partition function";
++    my_error(ER_TOO_MANY_PARTITION_FUNC_FIELDS_ERROR, MYF(0), err_str);
++    DBUG_RETURN(TRUE);
++  }
++  if (num_fields == 0)
++  {
++    /*
++      We are using hidden key as partitioning field
++    */
++    DBUG_ASSERT(!is_sub_part);
++    DBUG_RETURN(result);
++  }
++  size_field_array= (num_fields+1)*sizeof(Field*);
++  field_array= (Field**)sql_calloc(size_field_array);
++  if (unlikely(!field_array))
++  {
++    mem_alloc_error(size_field_array);
++    result= TRUE;
++  }
++  ptr= table->field;
++  while ((field= *(ptr++))) 
++  {
++    if (field->flags & GET_FIXED_FIELDS_FLAG)
++    {
++      field->flags&= ~GET_FIXED_FIELDS_FLAG;
++      field->flags|= FIELD_IN_PART_FUNC_FLAG;
++      if (likely(!result))
++      {
++        if (!is_sub_part && part_info->column_list)
++        {
++          List_iterator<char> it(part_info->part_field_list);
++          char *field_name;
++
++          DBUG_ASSERT(num_fields == part_info->part_field_list.elements);
++          inx= 0;
++          do
++          {
++            field_name= it++;
++            if (!my_strcasecmp(system_charset_info,
++                               field_name,
++                               field->field_name))
++              break;
++          } while (++inx < num_fields);
++          if (inx == num_fields)
++          {
++            /*
++              Should not occur since it should already been checked in either
++              add_column_list_values, handle_list_of_fields,
++              check_partition_info etc.
++            */
++            DBUG_ASSERT(0);
++            my_error(ER_FIELD_NOT_FOUND_PART_ERROR, MYF(0));
++            result= TRUE;
++            continue;
++          }
++        }
++        else
++          inx= i;
++        field_array[inx]= field;
++        i++;
++
++        /*
++          We check that the fields are proper. It is required for each
++          field in a partition function to:
++          1) Not be a BLOB of any type
++            A BLOB takes too long time to evaluate so we don't want it for
++            performance reasons.
++        */
++
++        if (unlikely(field->flags & BLOB_FLAG))
++        {
++          my_error(ER_BLOB_FIELD_IN_PART_FUNC_ERROR, MYF(0));
++          result= TRUE;
++        }
++      }
++    }
++  }
++  field_array[num_fields]= 0;
++  if (!is_sub_part)
++  {
++    part_info->part_field_array= field_array;
++    part_info->num_part_fields= num_fields;
++  }
++  else
++  {
++    part_info->subpart_field_array= field_array;
++    part_info->num_subpart_fields= num_fields;
++  }
++  DBUG_RETURN(result);
++}
++
++
++
++/*
++  Create a field array including all fields of both the partitioning and the
++  subpartitioning functions.
++
++  SYNOPSIS
++    create_full_part_field_array()
++    thd                  Thread handle
++    table                TABLE object for which partition fields are set-up
++    part_info            Reference to partitioning data structure
++
++  RETURN VALUE
++    TRUE                 Memory allocation of field array failed
++    FALSE                Ok
++
++  DESCRIPTION
++    If there is no subpartitioning then the same array is used as for the
++    partitioning. Otherwise a new array is built up using the flag
++    FIELD_IN_PART_FUNC in the field object.
++    This function is called from fix_partition_func
++*/
++
++static bool create_full_part_field_array(THD *thd, TABLE *table,
++                                         partition_info *part_info)
++{
++  bool result= FALSE;
++  Field **ptr;
++  my_bitmap_map *bitmap_buf;
++  DBUG_ENTER("create_full_part_field_array");
++
++  if (!part_info->is_sub_partitioned())
++  {
++    part_info->full_part_field_array= part_info->part_field_array;
++    part_info->num_full_part_fields= part_info->num_part_fields;
++  }
++  else
++  {
++    Field *field, **field_array;
++    uint num_part_fields=0, size_field_array;
++    ptr= table->field;
++    while ((field= *(ptr++)))
++    {
++      if (field->flags & FIELD_IN_PART_FUNC_FLAG)
++        num_part_fields++;
++    }
++    size_field_array= (num_part_fields+1)*sizeof(Field*);
++    field_array= (Field**)sql_calloc(size_field_array);
++    if (unlikely(!field_array))
++    {
++      mem_alloc_error(size_field_array);
++      result= TRUE;
++      goto end;
++    }
++    num_part_fields= 0;
++    ptr= table->field;
++    while ((field= *(ptr++)))
++    {
++      if (field->flags & FIELD_IN_PART_FUNC_FLAG)
++        field_array[num_part_fields++]= field;
++    }
++    field_array[num_part_fields]=0;
++    part_info->full_part_field_array= field_array;
++    part_info->num_full_part_fields= num_part_fields;
++  }
++
++  /*
++    Initialize the set of all fields used in partition and subpartition
++    expression. Required for testing of partition fields in write_set
++    when updating. We need to set all bits in read_set because the row
++    may need to be inserted in a different [sub]partition.
++  */
++  if (!(bitmap_buf= (my_bitmap_map*)
++        thd->alloc(bitmap_buffer_size(table->s->fields))))
++  {
++    mem_alloc_error(bitmap_buffer_size(table->s->fields));
++    result= TRUE;
++    goto end;
++  }
++  if (bitmap_init(&part_info->full_part_field_set, bitmap_buf,
++                  table->s->fields, FALSE))
++  {
++    mem_alloc_error(table->s->fields);
++    result= TRUE;
++    goto end;
++  }
++  /*
++    full_part_field_array may be NULL if storage engine supports native
++    partitioning.
++  */
++  if ((ptr= part_info->full_part_field_array))
++    for (; *ptr; ptr++)
++      bitmap_set_bit(&part_info->full_part_field_set, (*ptr)->field_index);
++
++end:
++  DBUG_RETURN(result);
++}
++
++
++/*
++
++  Clear flag GET_FIXED_FIELDS_FLAG in all fields of a key previously set by
++  set_indicator_in_key_fields (always used in pairs).
++
++  SYNOPSIS
++    clear_indicator_in_key_fields()
++    key_info                  Reference to find the key fields
++
++  RETURN VALUE
++    NONE
++
++  DESCRIPTION
++    These support routines is used to set/reset an indicator of all fields
++    in a certain key. It is used in conjunction with another support routine
++    that traverse all fields in the PF to find if all or some fields in the
++    PF is part of the key. This is used to check primary keys and unique
++    keys involve all fields in PF (unless supported) and to derive the
++    key_map's used to quickly decide whether the index can be used to
++    derive which partitions are needed to scan.
++*/
++
++static void clear_indicator_in_key_fields(KEY *key_info)
++{
++  KEY_PART_INFO *key_part;
++  uint key_parts= key_info->user_defined_key_parts, i;
++  for (i= 0, key_part=key_info->key_part; i < key_parts; i++, key_part++)
++    key_part->field->flags&= (~GET_FIXED_FIELDS_FLAG);
++}
++
++
++/*
++  Set flag GET_FIXED_FIELDS_FLAG in all fields of a key.
++
++  SYNOPSIS
++    set_indicator_in_key_fields
++    key_info                  Reference to find the key fields
++
++  RETURN VALUE
++    NONE
++*/
++
++static void set_indicator_in_key_fields(KEY *key_info)
++{
++  KEY_PART_INFO *key_part;
++  uint key_parts= key_info->user_defined_key_parts, i;
++  for (i= 0, key_part=key_info->key_part; i < key_parts; i++, key_part++)
++    key_part->field->flags|= GET_FIXED_FIELDS_FLAG;
++}
++
++
++/*
++  Check if all or some fields in partition field array is part of a key
++  previously used to tag key fields.
++
++  SYNOPSIS
++    check_fields_in_PF()
++    ptr                  Partition field array
++    out:all_fields       Is all fields of partition field array used in key
++    out:some_fields      Is some fields of partition field array used in key
++
++  RETURN VALUE
++    all_fields, some_fields
++*/
++
++static void check_fields_in_PF(Field **ptr, bool *all_fields,
++                               bool *some_fields)
++{
++  DBUG_ENTER("check_fields_in_PF");
++
++  *all_fields= TRUE;
++  *some_fields= FALSE;
++  if ((!ptr) || !(*ptr))
++  {
++    *all_fields= FALSE;
++    DBUG_VOID_RETURN;
++  }
++  do
++  {
++  /* Check if the field of the PF is part of the current key investigated */
++    if ((*ptr)->flags & GET_FIXED_FIELDS_FLAG)
++      *some_fields= TRUE; 
++    else
++      *all_fields= FALSE;
++  } while (*(++ptr));
++  DBUG_VOID_RETURN;
++}
++
++
++/*
++  Clear flag GET_FIXED_FIELDS_FLAG in all fields of the table.
++  This routine is used for error handling purposes.
++
++  SYNOPSIS
++    clear_field_flag()
++    table                TABLE object for which partition fields are set-up
++
++  RETURN VALUE
++    NONE
++*/
++
++static void clear_field_flag(TABLE *table)
++{
++  Field **ptr;
++  DBUG_ENTER("clear_field_flag");
++
++  for (ptr= table->field; *ptr; ptr++)
++    (*ptr)->flags&= (~GET_FIXED_FIELDS_FLAG);
++  DBUG_VOID_RETURN;
++}
++
++
++/*
++  find_field_in_table_sef finds the field given its name. All fields get
++  GET_FIXED_FIELDS_FLAG set.
++
++  SYNOPSIS
++    handle_list_of_fields()
++    it                   A list of field names for the partition function
++    table                TABLE object for which partition fields are set-up
++    part_info            Reference to partitioning data structure
++    sub_part             Is the table subpartitioned as well
++
++  RETURN VALUE
++    TRUE                 Fields in list of fields not part of table
++    FALSE                All fields ok and array created
++
++  DESCRIPTION
++    This routine sets-up the partition field array for KEY partitioning, it
++    also verifies that all fields in the list of fields is actually a part of
++    the table.
++
++*/
++
++
++static bool handle_list_of_fields(List_iterator<char> it,
++                                  TABLE *table,
++                                  partition_info *part_info,
++                                  bool is_sub_part)
++{
++  Field *field;
++  bool result;
++  char *field_name;
++  bool is_list_empty= TRUE;
++  DBUG_ENTER("handle_list_of_fields");
++
++  while ((field_name= it++))
++  {
++    is_list_empty= FALSE;
++    field= find_field_in_table_sef(table, field_name);
++    if (likely(field != 0))
++      field->flags|= GET_FIXED_FIELDS_FLAG;
++    else
++    {
++      my_error(ER_FIELD_NOT_FOUND_PART_ERROR, MYF(0));
++      clear_field_flag(table);
++      result= TRUE;
++      goto end;
++    }
++  }
++  if (is_list_empty && part_info->part_type == HASH_PARTITION)
++  {
++    uint primary_key= table->s->primary_key;
++    if (primary_key != MAX_KEY)
++    {
++      uint num_key_parts= table->key_info[primary_key].user_defined_key_parts, i;
++      /*
++        In the case of an empty list we use primary key as partition key.
++      */
++      for (i= 0; i < num_key_parts; i++)
++      {
++        Field *field= table->key_info[primary_key].key_part[i].field;
++        field->flags|= GET_FIXED_FIELDS_FLAG;
++      }
++    }
++    else
++    {
++      if (table->s->db_type()->partition_flags &&
++          (table->s->db_type()->partition_flags() & HA_USE_AUTO_PARTITION) &&
++          (table->s->db_type()->partition_flags() & HA_CAN_PARTITION))
++      {
++        /*
++          This engine can handle automatic partitioning and there is no
++          primary key. In this case we rely on that the engine handles
++          partitioning based on a hidden key. Thus we allocate no
++          array for partitioning fields.
++        */
++        DBUG_RETURN(FALSE);
++      }
++      else
++      {
++        my_error(ER_FIELD_NOT_FOUND_PART_ERROR, MYF(0));
++        DBUG_RETURN(TRUE);
++      }
++    }
++  }
++  result= set_up_field_array(table, is_sub_part);
++end:
++  DBUG_RETURN(result);
++}
++
++
++/*
++  Support function to check if all VALUES * (expression) is of the
++  right sign (no signed constants when unsigned partition function)
++
++  SYNOPSIS
++    check_signed_flag()
++    part_info                Partition info object
++
++  RETURN VALUES
++    0                        No errors due to sign errors
++    >0                       Sign error
++*/
++
++int check_signed_flag(partition_info *part_info)
++{
++  int error= 0;
++  uint i= 0;
++  if (part_info->part_type != HASH_PARTITION &&
++      part_info->part_expr->unsigned_flag)
++  {
++    List_iterator<partition_element> part_it(part_info->partitions);
++    do
++    {
++      partition_element *part_elem= part_it++;
++
++      if (part_elem->signed_flag)
++      {
++        my_error(ER_PARTITION_CONST_DOMAIN_ERROR, MYF(0));
++        error= ER_PARTITION_CONST_DOMAIN_ERROR;
++        break;
++      }
++    } while (++i < part_info->num_parts);
++  }
++  return error;
++}
++
++/**
++  Initialize lex object for use in fix_fields and parsing.
++
++  SYNOPSIS
++    init_lex_with_single_table()
++    @param thd                 The thread object
++    @param table               The table object
++  @return Operation status
++    @retval TRUE                An error occurred, memory allocation error
++    @retval FALSE               Ok
++
++  DESCRIPTION
++    This function is used to initialize a lex object on the
++    stack for use by fix_fields and for parsing. In order to
++    work properly it also needs to initialize the
++    Name_resolution_context object of the lexer.
++    Finally it needs to set a couple of variables to ensure
++    proper functioning of fix_fields.
++*/
++
++static int
++init_lex_with_single_table(THD *thd, TABLE *table, LEX *lex)
++{
++  TABLE_LIST *table_list;
++  Table_ident *table_ident;
++  SELECT_LEX *select_lex= &lex->select_lex;
++  Name_resolution_context *context= &select_lex->context;
++  /*
++    We will call the parser to create a part_info struct based on the
++    partition string stored in the frm file.
++    We will use a local lex object for this purpose. However we also
++    need to set the Name_resolution_object for this lex object. We
++    do this by using add_table_to_list where we add the table that
++    we're working with to the Name_resolution_context.
++  */
++  thd->lex= lex;
++  lex_start(thd);
++  context->init();
++  if ((!(table_ident= new Table_ident(thd,
++                                      table->s->table_name,
++                                      table->s->db, TRUE))) ||
++      (!(table_list= select_lex->add_table_to_list(thd,
++                                                   table_ident,
++                                                   NULL,
++                                                   0))))
++    return TRUE;
++  context->resolve_in_table_list_only(table_list);
++  lex->use_only_table_context= TRUE;
++  table->map= 1; //To ensure correct calculation of const item
++  table->get_fields_in_item_tree= TRUE;
++  table_list->table= table;
++  table_list->cacheable_table= false;
++  return FALSE;
++}
++
++/**
++  End use of local lex with single table
++
++  SYNOPSIS
++    end_lex_with_single_table()
++    @param thd               The thread object
++    @param table             The table object
++    @param old_lex           The real lex object connected to THD
++
++  DESCRIPTION
++    This function restores the real lex object after calling
++    init_lex_with_single_table and also restores some table
++    variables temporarily set.
++*/
++
++static void
++end_lex_with_single_table(THD *thd, TABLE *table, LEX *old_lex)
++{
++  LEX *lex= thd->lex;
++  table->map= 0;
++  table->get_fields_in_item_tree= FALSE;
++  lex_end(lex);
++  thd->lex= old_lex;
++}
++
++/*
++  The function uses a new feature in fix_fields where the flag 
++  GET_FIXED_FIELDS_FLAG is set for all fields in the item tree.
++  This field must always be reset before returning from the function
++  since it is used for other purposes as well.
++
++  SYNOPSIS
++    fix_fields_part_func()
++    thd                  The thread object
++    func_expr            The item tree reference of the partition function
++    table                The table object
++    part_info            Reference to partitioning data structure
++    is_sub_part          Is the table subpartitioned as well
++    is_create_table_ind  Indicator of whether openfrm was called as part of
++                         CREATE or ALTER TABLE
++
++  RETURN VALUE
++    TRUE                 An error occurred, something was wrong with the
++                         partition function.
++    FALSE                Ok, a partition field array was created
++
++  DESCRIPTION
++    This function is used to build an array of partition fields for the
++    partitioning function and subpartitioning function. The partitioning
++    function is an item tree that must reference at least one field in the
++    table. This is checked first in the parser that the function doesn't
++    contain non-cacheable parts (like a random function) and by checking
++    here that the function isn't a constant function.
++
++    Calculate the number of fields in the partition function.
++    Use it allocate memory for array of Field pointers.
++    Initialise array of field pointers. Use information set when
++    calling fix_fields and reset it immediately after.
++    The get_fields_in_item_tree activates setting of bit in flags
++    on the field object.
++*/
++
++static bool fix_fields_part_func(THD *thd, Item* func_expr, TABLE *table,
++                          bool is_sub_part, bool is_create_table_ind)
++{
++  partition_info *part_info= table->part_info;
++  bool result= TRUE;
++  int error;
++  LEX *old_lex= thd->lex;
++  LEX lex;
++  DBUG_ENTER("fix_fields_part_func");
++
++  if (init_lex_with_single_table(thd, table, &lex))
++    goto end;
++
++  func_expr->walk(&Item::change_context_processor, 0,
++                  (uchar*) &lex.select_lex.context);
++  thd->where= "partition function";
++  /*
++    In execution we must avoid the use of thd->change_item_tree since
++    we might release memory before statement is completed. We do this
++    by temporarily setting the stmt_arena->mem_root to be the mem_root
++    of the table object, this also ensures that any memory allocated
++    during fix_fields will not be released at end of execution of this
++    statement. Thus the item tree will remain valid also in subsequent
++    executions of this table object. We do however not at the moment
++    support allocations during execution of val_int so any item class
++    that does this during val_int must be disallowed as partition
++    function.
++    SEE Bug #21658
++
++    This is a tricky call to prepare for since it can have a large number
++    of interesting side effects, both desirable and undesirable.
++  */
++  {
++    const bool save_agg_field= thd->lex->current_select->non_agg_field_used();
++    const bool save_agg_func=  thd->lex->current_select->agg_func_used();
++    const nesting_map saved_allow_sum_func= thd->lex->allow_sum_func;
++    thd->lex->allow_sum_func= 0;
++
++    error= func_expr->fix_fields(thd, (Item**)&func_expr);
++
++    /*
++      Restore agg_field/agg_func  and allow_sum_func,
++      fix_fields should not affect mysql_select later, see Bug#46923.
++    */
++    thd->lex->current_select->set_non_agg_field_used(save_agg_field);
++    thd->lex->current_select->set_agg_func_used(save_agg_func);
++    thd->lex->allow_sum_func= saved_allow_sum_func;
++  }
++  if (unlikely(error))
++  {
++    DBUG_PRINT("info", ("Field in partition function not part of table"));
++    clear_field_flag(table);
++    goto end;
++  }
++  if (unlikely(func_expr->const_item()))
++  {
++    my_error(ER_WRONG_EXPR_IN_PARTITION_FUNC_ERROR, MYF(0));
++    clear_field_flag(table);
++    goto end;
++  }
++
++  /*
++    We don't allow creating partitions with expressions with non matching
++    arguments as a (sub)partitioning function,
++    but we want to allow such expressions when opening existing tables for
++    easier maintenance. This exception should be deprecated at some point
++    in future so that we always throw an error.
++  */
++  if (func_expr->walk(&Item::check_valid_arguments_processor,
++                      0, NULL))
++  {
++    if (is_create_table_ind)
++    {
++      my_error(ER_WRONG_EXPR_IN_PARTITION_FUNC_ERROR, MYF(0));
++      goto end;
++    }
++    else
++      push_warning(thd, Sql_condition::WARN_LEVEL_WARN,
++                   ER_WRONG_EXPR_IN_PARTITION_FUNC_ERROR,
++                   ER(ER_WRONG_EXPR_IN_PARTITION_FUNC_ERROR));
++  }
++
++  if ((!is_sub_part) && (error= check_signed_flag(part_info)))
++    goto end;
++  result= set_up_field_array(table, is_sub_part);
++end:
++  end_lex_with_single_table(thd, table, old_lex);
++#if !defined(DBUG_OFF)
++  func_expr->walk(&Item::change_context_processor, 0,
++                  (uchar*) 0);
++#endif
++  DBUG_RETURN(result);
++}
++
++
++/*
++  Check that the primary key contains all partition fields if defined
++
++  SYNOPSIS
++    check_primary_key()
++    table                TABLE object for which partition fields are set-up
++
++  RETURN VALUES
++    TRUE                 Not all fields in partitioning function was part
++                         of primary key
++    FALSE                Ok, all fields of partitioning function were part
++                         of primary key
++
++  DESCRIPTION
++    This function verifies that if there is a primary key that it contains
++    all the fields of the partition function.
++    This is a temporary limitation that will hopefully be removed after a
++    while.
++*/
++
++static bool check_primary_key(TABLE *table)
++{
++  uint primary_key= table->s->primary_key;
++  bool all_fields, some_fields;
++  bool result= FALSE;
++  DBUG_ENTER("check_primary_key");
++
++  if (primary_key < MAX_KEY)
++  {
++    set_indicator_in_key_fields(table->key_info+primary_key);
++    check_fields_in_PF(table->part_info->full_part_field_array,
++                        &all_fields, &some_fields);
++    clear_indicator_in_key_fields(table->key_info+primary_key);
++    if (unlikely(!all_fields))
++    {
++      my_error(ER_UNIQUE_KEY_NEED_ALL_FIELDS_IN_PF,MYF(0),"PRIMARY KEY");
++      result= TRUE;
++    }
++  }
++  DBUG_RETURN(result);
++}
++
++
++/*
++  Check that unique keys contains all partition fields
++
++  SYNOPSIS
++    check_unique_keys()
++    table                TABLE object for which partition fields are set-up
++
++  RETURN VALUES
++    TRUE                 Not all fields in partitioning function was part
++                         of all unique keys
++    FALSE                Ok, all fields of partitioning function were part
++                         of unique keys
++
++  DESCRIPTION
++    This function verifies that if there is a unique index that it contains
++    all the fields of the partition function.
++    This is a temporary limitation that will hopefully be removed after a
++    while.
++*/
++
++static bool check_unique_keys(TABLE *table)
++{
++  bool all_fields, some_fields;
++  bool result= FALSE;
++  uint keys= table->s->keys;
++  uint i;
++  DBUG_ENTER("check_unique_keys");
++
++  for (i= 0; i < keys; i++)
++  {
++    if (table->key_info[i].flags & HA_NOSAME) //Unique index
++    {
++      set_indicator_in_key_fields(table->key_info+i);
++      check_fields_in_PF(table->part_info->full_part_field_array,
++                         &all_fields, &some_fields);
++      clear_indicator_in_key_fields(table->key_info+i);
++      if (unlikely(!all_fields))
++      {
++        my_error(ER_UNIQUE_KEY_NEED_ALL_FIELDS_IN_PF,MYF(0),"UNIQUE INDEX");
++        result= TRUE;
++        break;
++      }
++    }
++  }
++  DBUG_RETURN(result);
++}
++
++
++/*
++  An important optimisation is whether a range on a field can select a subset
++  of the partitions.
++  A prerequisite for this to happen is that the PF is a growing function OR
++  a shrinking function.
++  This can never happen for a multi-dimensional PF. Thus this can only happen
++  with PF with at most one field involved in the PF.
++  The idea is that if the function is a growing function and you know that
++  the field of the PF is 4 <= A <= 6 then we can convert this to a range
++  in the PF instead by setting the range to PF(4) <= PF(A) <= PF(6). In the
++  case of RANGE PARTITIONING and LIST PARTITIONING this can be used to
++  calculate a set of partitions rather than scanning all of them.
++  Thus the following prerequisites are there to check if sets of partitions
++  can be found.
++  1) Only possible for RANGE and LIST partitioning (not for subpartitioning)
++  2) Only possible if PF only contains 1 field
++  3) Possible if PF is a growing function of the field
++  4) Possible if PF is a shrinking function of the field
++  OBSERVATION:
++  1) IF f1(A) is a growing function AND f2(A) is a growing function THEN
++     f1(A) + f2(A) is a growing function
++     f1(A) * f2(A) is a growing function if f1(A) >= 0 and f2(A) >= 0
++  2) IF f1(A) is a growing function and f2(A) is a shrinking function THEN
++     f1(A) / f2(A) is a growing function if f1(A) >= 0 and f2(A) > 0
++  3) IF A is a growing function then a function f(A) that removes the
++     least significant portion of A is a growing function
++     E.g. DATE(datetime) is a growing function
++     MONTH(datetime) is not a growing/shrinking function
++  4) IF f1(A) is a growing function and f2(A) is a growing function THEN
++     f1(f2(A)) and f2(f1(A)) are also growing functions
++  5) IF f1(A) is a shrinking function and f2(A) is a growing function THEN
++     f1(f2(A)) is a shrinking function and f2(f1(A)) is a shrinking function
++  6) f1(A) = A is a growing function
++  7) f1(A) = A*a + b (where a and b are constants) is a growing function
++
++  By analysing the item tree of the PF we can use these deducements and
++  derive whether the PF is a growing function or a shrinking function or
++  neither of it.
++
++  If the PF is range capable then a flag is set on the table object
++  indicating this to notify that we can use also ranges on the field
++  of the PF to deduce a set of partitions if the fields of the PF were
++  not all fully bound.
++
++  SYNOPSIS
++    check_range_capable_PF()
++    table                TABLE object for which partition fields are set-up
++
++  DESCRIPTION
++    Support for this is not implemented yet.
++*/
++
++void check_range_capable_PF(TABLE *table)
++{
++  DBUG_ENTER("check_range_capable_PF");
++
++  DBUG_VOID_RETURN;
++}
++
++
++/**
++  Set up partition bitmaps
++
++    @param thd           Thread object
++    @param part_info     Reference to partitioning data structure
++
++  @return Operation status
++    @retval TRUE         Memory allocation failure
++    @retval FALSE        Success
++
++    Allocate memory for bitmaps of the partitioned table
++    and initialise it.
++*/
++
++static bool set_up_partition_bitmaps(THD *thd, partition_info *part_info)
++{
++  uint32 *bitmap_buf;
++  uint bitmap_bits= part_info->num_subparts? 
++                     (part_info->num_subparts* part_info->num_parts):
++                      part_info->num_parts;
++  uint bitmap_bytes= bitmap_buffer_size(bitmap_bits);
++  DBUG_ENTER("set_up_partition_bitmaps");
++
++  DBUG_ASSERT(!part_info->bitmaps_are_initialized);
++
++  /* Allocate for both read and lock_partitions */
++  if (!(bitmap_buf= (uint32*) alloc_root(&part_info->table->mem_root,
++                                         bitmap_bytes * 2)))
++  {
++    mem_alloc_error(bitmap_bytes * 2);
++    DBUG_RETURN(TRUE);
++  }
++  bitmap_init(&part_info->read_partitions, bitmap_buf, bitmap_bits, FALSE);
++  /* Use the second half of the allocated buffer for lock_partitions */
++  bitmap_init(&part_info->lock_partitions, bitmap_buf + (bitmap_bytes / 4),
++              bitmap_bits, FALSE);
++  part_info->bitmaps_are_initialized= TRUE;
++  part_info->set_partition_bitmaps(NULL);
++  DBUG_RETURN(FALSE);
++}
++
++
++/*
++  Set up partition key maps
++
++  SYNOPSIS
++    set_up_partition_key_maps()
++    table                TABLE object for which partition fields are set-up
++    part_info            Reference to partitioning data structure
++
++  RETURN VALUES
++    None
++
++  DESCRIPTION
++    This function sets up a couple of key maps to be able to quickly check
++    if an index ever can be used to deduce the partition fields or even
++    a part of the fields of the  partition function.
++    We set up the following key_map's.
++    PF = Partition Function
++    1) All fields of the PF is set even by equal on the first fields in the
++       key
++    2) All fields of the PF is set if all fields of the key is set
++    3) At least one field in the PF is set if all fields is set
++    4) At least one field in the PF is part of the key
++*/
++
++static void set_up_partition_key_maps(TABLE *table,
++                                      partition_info *part_info)
++{
++  uint keys= table->s->keys;
++  uint i;
++  bool all_fields, some_fields;
++  DBUG_ENTER("set_up_partition_key_maps");
++
++  part_info->all_fields_in_PF.clear_all();
++  part_info->all_fields_in_PPF.clear_all();
++  part_info->all_fields_in_SPF.clear_all();
++  part_info->some_fields_in_PF.clear_all();
++  for (i= 0; i < keys; i++)
++  {
++    set_indicator_in_key_fields(table->key_info+i);
++    check_fields_in_PF(part_info->full_part_field_array,
++                       &all_fields, &some_fields);
++    if (all_fields)
++      part_info->all_fields_in_PF.set_bit(i);
++    if (some_fields)
++      part_info->some_fields_in_PF.set_bit(i);
++    if (part_info->is_sub_partitioned())
++    {
++      check_fields_in_PF(part_info->part_field_array,
++                         &all_fields, &some_fields);
++      if (all_fields)
++        part_info->all_fields_in_PPF.set_bit(i);
++      check_fields_in_PF(part_info->subpart_field_array,
++                         &all_fields, &some_fields);
++      if (all_fields)
++        part_info->all_fields_in_SPF.set_bit(i);
++    }
++    clear_indicator_in_key_fields(table->key_info+i);
++  }
++  DBUG_VOID_RETURN;
++}
++
++
++/*
++  Set up function pointers for partition function
++
++  SYNOPSIS
++    set_up_partition_func_pointers()
++    part_info            Reference to partitioning data structure
++
++  RETURN VALUE
++    NONE
++
++  DESCRIPTION
++    Set-up all function pointers for calculation of partition id,
++    subpartition id and the upper part in subpartitioning. This is to speed up
++    execution of get_partition_id which is executed once every record to be
++    written and deleted and twice for updates.
++*/
++
++static void set_up_partition_func_pointers(partition_info *part_info)
++{
++  DBUG_ENTER("set_up_partition_func_pointers");
++
++  if (part_info->is_sub_partitioned())
++  {
++    part_info->get_partition_id= get_partition_id_with_sub;
++    if (part_info->part_type == RANGE_PARTITION)
++    {
++      if (part_info->column_list)
++        part_info->get_part_partition_id= get_partition_id_range_col;
++      else
++        part_info->get_part_partition_id= get_partition_id_range;
++      if (part_info->list_of_subpart_fields)
++      {
++        if (part_info->linear_hash_ind)
++          part_info->get_subpartition_id= get_partition_id_linear_key_sub;
++        else
++          part_info->get_subpartition_id= get_partition_id_key_sub;
++      }
++      else
++      {
++        if (part_info->linear_hash_ind)
++          part_info->get_subpartition_id= get_partition_id_linear_hash_sub;
++        else
++          part_info->get_subpartition_id= get_partition_id_hash_sub;
++      }
++    }
++    else /* LIST Partitioning */
++    {
++      if (part_info->column_list)
++        part_info->get_part_partition_id= get_partition_id_list_col;
++      else
++        part_info->get_part_partition_id= get_partition_id_list;
++      if (part_info->list_of_subpart_fields)
++      {
++        if (part_info->linear_hash_ind)
++          part_info->get_subpartition_id= get_partition_id_linear_key_sub;
++        else
++          part_info->get_subpartition_id= get_partition_id_key_sub;
++      }
++      else
++      {
++        if (part_info->linear_hash_ind)
++          part_info->get_subpartition_id= get_partition_id_linear_hash_sub;
++        else
++          part_info->get_subpartition_id= get_partition_id_hash_sub;
++      }
++    }
++  }
++  else /* No subpartitioning */
++  {
++    part_info->get_part_partition_id= NULL;
++    part_info->get_subpartition_id= NULL;
++    if (part_info->part_type == RANGE_PARTITION)
++    {
++      if (part_info->column_list)
++        part_info->get_partition_id= get_partition_id_range_col;
++      else
++        part_info->get_partition_id= get_partition_id_range;
++    }
++    else if (part_info->part_type == LIST_PARTITION)
++    {
++      if (part_info->column_list)
++        part_info->get_partition_id= get_partition_id_list_col;
++      else
++        part_info->get_partition_id= get_partition_id_list;
++    }
++    else /* HASH partitioning */
++    {
++      if (part_info->list_of_part_fields)
++      {
++        if (part_info->linear_hash_ind)
++          part_info->get_partition_id= get_partition_id_linear_key_nosub;
++        else
++          part_info->get_partition_id= get_partition_id_key_nosub;
++      }
++      else
++      {
++        if (part_info->linear_hash_ind)
++          part_info->get_partition_id= get_partition_id_linear_hash_nosub;
++        else
++          part_info->get_partition_id= get_partition_id_hash_nosub;
++      }
++    }
++  }
++  /*
++    We need special functions to handle character sets since they require copy
++    of field pointers and restore afterwards. For subpartitioned tables we do
++    the copy and restore individually on the part and subpart parts. For non-
++    subpartitioned tables we use the same functions as used for the parts part
++    of subpartioning.
++    Thus for subpartitioned tables the get_partition_id is always
++    get_partition_id_with_sub, even when character sets exists.
++  */
++  if (part_info->part_charset_field_array)
++  {
++    if (part_info->is_sub_partitioned())
++    {
++      DBUG_ASSERT(part_info->get_part_partition_id);
++      if (!part_info->column_list)
++      {
++        part_info->get_part_partition_id_charset=
++          part_info->get_part_partition_id;
++        part_info->get_part_partition_id= get_part_id_charset_func_part;
++      }
++    }
++    else
++    {
++      DBUG_ASSERT(part_info->get_partition_id);
++      if (!part_info->column_list)
++      {
++        part_info->get_part_partition_id_charset= part_info->get_partition_id;
++        part_info->get_part_partition_id= get_part_id_charset_func_part;
++      }
++    }
++  }
++  if (part_info->subpart_charset_field_array)
++  {
++    DBUG_ASSERT(part_info->get_subpartition_id);
++    part_info->get_subpartition_id_charset=
++          part_info->get_subpartition_id;
++    part_info->get_subpartition_id= get_part_id_charset_func_subpart;
++  }
++  DBUG_VOID_RETURN;
++}
++
++
++/*
++  For linear hashing we need a mask which is on the form 2**n - 1 where
++  2**n >= num_parts. Thus if num_parts is 6 then mask is 2**3 - 1 = 8 - 1 = 7.
++
++  SYNOPSIS
++    set_linear_hash_mask()
++    part_info            Reference to partitioning data structure
++    num_parts            Number of parts in linear hash partitioning
++
++  RETURN VALUE
++    NONE
++*/
++
++void set_linear_hash_mask(partition_info *part_info, uint num_parts)
++{
++  uint mask;
++
++  for (mask= 1; mask < num_parts; mask<<=1)
++    ;
++  part_info->linear_hash_mask= mask - 1;
++}
++
++
++/*
++  This function calculates the partition id provided the result of the hash
++  function using linear hashing parameters, mask and number of partitions.
++
++  SYNOPSIS
++    get_part_id_from_linear_hash()
++    hash_value          Hash value calculated by HASH function or KEY function
++    mask                Mask calculated previously by set_linear_hash_mask
++    num_parts           Number of partitions in HASH partitioned part
++
++  RETURN VALUE
++    part_id             The calculated partition identity (starting at 0)
++
++  DESCRIPTION
++    The partition is calculated according to the theory of linear hashing.
++    See e.g. Linear hashing: a new tool for file and table addressing,
++    Reprinted from VLDB-80 in Readings Database Systems, 2nd ed, M. Stonebraker
++    (ed.), Morgan Kaufmann 1994.
++*/
++
++static uint32 get_part_id_from_linear_hash(longlong hash_value, uint mask,
++                                           uint num_parts)
++{
++  uint32 part_id= (uint32)(hash_value & mask);
++
++  if (part_id >= num_parts)
++  {
++    uint new_mask= ((mask + 1) >> 1) - 1;
++    part_id= (uint32)(hash_value & new_mask);
++  }
++  return part_id;
++}
++
++
++/*
++  Check if a particular field is in need of character set
++  handling for partition functions.
++
++  SYNOPSIS
++    field_is_partition_charset()
++    field                         The field to check
++
++  RETURN VALUES
++    FALSE                        Not in need of character set handling
++    TRUE                         In need of character set handling
++*/
++
++bool field_is_partition_charset(Field *field)
++{
++  if (!(field->type() == MYSQL_TYPE_STRING) &&
++      !(field->type() == MYSQL_TYPE_VARCHAR))
++    return FALSE;
++  {
++    const CHARSET_INFO *cs= field->charset();
++    if (!(field->type() == MYSQL_TYPE_STRING) ||
++        !(cs->state & MY_CS_BINSORT))
++      return TRUE;
++    return FALSE;
++  }
++}
++
++
++/*
++  Check that partition function doesn't contain any forbidden
++  character sets and collations.
++
++  SYNOPSIS
++    check_part_func_fields()
++    ptr                                 Array of Field pointers
++    ok_with_charsets                    Will we report allowed charset
++                                        fields as ok
++  RETURN VALUES
++    FALSE                               Success
++    TRUE                                Error
++
++  DESCRIPTION
++    We will check in this routine that the fields of the partition functions
++    do not contain unallowed parts. It can also be used to check if there
++    are fields that require special care by calling my_strnxfrm before
++    calling the functions to calculate partition id.
++*/
++
++bool check_part_func_fields(Field **ptr, bool ok_with_charsets)
++{
++  Field *field;
++  DBUG_ENTER("check_part_func_fields");
++
++  while ((field= *(ptr++)))
++  {
++    /*
++      For CHAR/VARCHAR fields we need to take special precautions.
++      Binary collation with CHAR is automatically supported. Other
++      types need some kind of standardisation function handling
++    */
++    if (field_is_partition_charset(field))
++    {
++      const CHARSET_INFO *cs= field->charset();
++      if (!ok_with_charsets ||
++          cs->mbmaxlen > 1 ||
++          cs->strxfrm_multiply > 1)
++      {
++        DBUG_RETURN(TRUE);
++      }
++    }
++  }
++  DBUG_RETURN(FALSE);
++}
++
++
++/*
++  fix partition functions
++
++  SYNOPSIS
++    fix_partition_func()
++    thd                  The thread object
++    table                TABLE object for which partition fields are set-up
++    is_create_table_ind  Indicator of whether openfrm was called as part of
++                         CREATE or ALTER TABLE
++
++  RETURN VALUE
++    TRUE                 Error
++    FALSE                Success
++
++  DESCRIPTION
++    The name parameter contains the full table name and is used to get the
++    database name of the table which is used to set-up a correct
++    TABLE_LIST object for use in fix_fields.
++
++NOTES
++    This function is called as part of opening the table by opening the .frm
++    file. It is a part of CREATE TABLE to do this so it is quite permissible
++    that errors due to erroneus syntax isn't found until we come here.
++    If the user has used a non-existing field in the table is one such example
++    of an error that is not discovered until here.
++*/
++
++bool fix_partition_func(THD *thd, TABLE *table,
++                        bool is_create_table_ind)
++{
++  bool result= TRUE;
++  partition_info *part_info= table->part_info;
++  enum_mark_columns save_mark_used_columns= thd->mark_used_columns;
++  DBUG_ENTER("fix_partition_func");
++
++  if (part_info->fixed)
++  {
++    DBUG_RETURN(FALSE);
++  }
++  thd->mark_used_columns= MARK_COLUMNS_NONE;
++  DBUG_PRINT("info", ("thd->mark_used_columns: %d", thd->mark_used_columns));
++
++  if (!is_create_table_ind ||
++       thd->lex->sql_command != SQLCOM_CREATE_TABLE)
++  {
++    if (partition_default_handling(table, part_info,
++                                   is_create_table_ind,
++                                   table->s->normalized_path.str))
++    {
++      DBUG_RETURN(TRUE);
++    }
++  }
++  if (part_info->is_sub_partitioned())
++  {
++    DBUG_ASSERT(part_info->subpart_type == HASH_PARTITION);
++    /*
++      Subpartition is defined. We need to verify that subpartitioning
++      function is correct.
++    */
++    if (part_info->linear_hash_ind)
++      set_linear_hash_mask(part_info, part_info->num_subparts);
++    if (part_info->list_of_subpart_fields)
++    {
++      List_iterator<char> it(part_info->subpart_field_list);
++      if (unlikely(handle_list_of_fields(it, table, part_info, TRUE)))
++        goto end;
++    }
++    else
++    {
++      if (unlikely(fix_fields_part_func(thd, part_info->subpart_expr,
++                                        table, TRUE, is_create_table_ind)))
++        goto end;
++      if (unlikely(part_info->subpart_expr->result_type() != INT_RESULT))
++      {
++        part_info->report_part_expr_error(TRUE);
++        goto end;
++      }
++    }
++  }
++  DBUG_ASSERT(part_info->part_type != NOT_A_PARTITION);
++  /*
++    Partition is defined. We need to verify that partitioning
++    function is correct.
++  */
++  if (part_info->part_type == HASH_PARTITION)
++  {
++    if (part_info->linear_hash_ind)
++      set_linear_hash_mask(part_info, part_info->num_parts);
++    if (part_info->list_of_part_fields)
++    {
++      List_iterator<char> it(part_info->part_field_list);
++      if (unlikely(handle_list_of_fields(it, table, part_info, FALSE)))
++        goto end;
++    }
++    else
++    {
++      if (unlikely(fix_fields_part_func(thd, part_info->part_expr,
++                                        table, FALSE, is_create_table_ind)))
++        goto end;
++      if (unlikely(part_info->part_expr->result_type() != INT_RESULT))
++      {
++        part_info->report_part_expr_error(FALSE);
++        goto end;
++      }
++    }
++    part_info->fixed= TRUE;
++  }
++  else
++  {
++    const char *error_str;
++    if (part_info->column_list)
++    {
++      List_iterator<char> it(part_info->part_field_list);
++      if (unlikely(handle_list_of_fields(it, table, part_info, FALSE)))
++        goto end;
++    }
++    else
++    {
++      if (unlikely(fix_fields_part_func(thd, part_info->part_expr,
++                                        table, FALSE, is_create_table_ind)))
++        goto end;
++    }
++    part_info->fixed= TRUE;
++    if (part_info->part_type == RANGE_PARTITION)
++    {
++      error_str= partition_keywords[PKW_RANGE].str; 
++      if (unlikely(part_info->check_range_constants(thd)))
++        goto end;
++    }
++    else if (part_info->part_type == LIST_PARTITION)
++    {
++      error_str= partition_keywords[PKW_LIST].str; 
++      if (unlikely(part_info->check_list_constants(thd)))
++        goto end;
++    }
++    else
++    {
++      DBUG_ASSERT(0);
++      my_error(ER_INCONSISTENT_PARTITION_INFO_ERROR, MYF(0));
++      goto end;
++    }
++    if (unlikely(part_info->num_parts < 1))
++    {
++      my_error(ER_PARTITIONS_MUST_BE_DEFINED_ERROR, MYF(0), error_str);
++      goto end;
++    }
++    if (unlikely(!part_info->column_list &&
++                  part_info->part_expr->result_type() != INT_RESULT))
++    {
++      part_info->report_part_expr_error(FALSE);
++      goto end;
++    }
++  }
++  if (((part_info->part_type != HASH_PARTITION ||
++        part_info->list_of_part_fields == FALSE) &&
++       !part_info->column_list &&
++       check_part_func_fields(part_info->part_field_array, TRUE)) ||
++      (part_info->list_of_subpart_fields == FALSE &&
++       part_info->is_sub_partitioned() &&
++       check_part_func_fields(part_info->subpart_field_array, TRUE)))
++  {
++    /*
++      Range/List/HASH (but not KEY) and not COLUMNS or HASH subpartitioning
++      with columns in the partitioning expression using unallowed charset.
++    */
++    my_error(ER_PARTITION_FUNCTION_IS_NOT_ALLOWED, MYF(0));
++    goto end;
++  }
++  if (unlikely(create_full_part_field_array(thd, table, part_info)))
++    goto end;
++  if (unlikely(check_primary_key(table)))
++    goto end;
++  if (unlikely((!(table->s->db_type()->partition_flags &&
++      (table->s->db_type()->partition_flags() & HA_CAN_PARTITION_UNIQUE))) &&
++               check_unique_keys(table)))
++    goto end;
++  if (unlikely(set_up_partition_bitmaps(thd, part_info)))
++    goto end;
++  if (unlikely(part_info->set_up_charset_field_preps()))
++  {
++    my_error(ER_PARTITION_FUNCTION_IS_NOT_ALLOWED, MYF(0));
++    goto end;
++  }
++  if (unlikely(part_info->check_partition_field_length()))
++  {
++    my_error(ER_PARTITION_FIELDS_TOO_LONG, MYF(0));
++    goto end;
++  }
++  check_range_capable_PF(table);
++  set_up_partition_key_maps(table, part_info);
++  set_up_partition_func_pointers(part_info);
++  set_up_range_analysis_info(part_info);
++  table->file->set_part_info(part_info, FALSE);
++  result= FALSE;
++end:
++  thd->mark_used_columns= save_mark_used_columns;
++  DBUG_PRINT("info", ("thd->mark_used_columns: %d", thd->mark_used_columns));
++  DBUG_RETURN(result);
++}
++
++
++/*
++  The code below is support routines for the reverse parsing of the 
++  partitioning syntax. This feature is very useful to generate syntax for
++  all default values to avoid all default checking when opening the frm
++  file. It is also used when altering the partitioning by use of various
++  ALTER TABLE commands. Finally it is used for SHOW CREATE TABLES.
++*/
++
++static int add_write(File fptr, const char *buf, uint len)
++{
++  uint ret_code= mysql_file_write(fptr, (const uchar*)buf, len, MYF(MY_FNABP));
++
++  if (likely(ret_code == 0))
++    return 0;
++  else
++    return 1;
++}
++
++static int add_string_object(File fptr, String *string)
++{
++  return add_write(fptr, string->ptr(), string->length());
++}
++
++static int add_string(File fptr, const char *string)
++{
++  return add_write(fptr, string, strlen(string));
++}
++
++static int add_string_len(File fptr, const char *string, uint len)
++{
++  return add_write(fptr, string, len);
++}
++
++static int add_space(File fptr)
++{
++  return add_string(fptr, space_str);
++}
++
++static int add_comma(File fptr)
++{
++  return add_string(fptr, comma_str);
++}
++
++static int add_equal(File fptr)
++{
++  return add_string(fptr, equal_str);
++}
++
++static int add_end_parenthesis(File fptr)
++{
++  return add_string(fptr, end_paren_str);
++}
++
++static int add_begin_parenthesis(File fptr)
++{
++  return add_string(fptr, begin_paren_str);
++}
++
++static int add_part_key_word(File fptr, const char *key_string)
++{
++  int err= add_string(fptr, key_string);
++  err+= add_space(fptr);
++  return err;
++}
++
++static int add_partition(File fptr)
++{
++  char buff[22];
++  strxmov(buff, part_str, space_str, NullS);
++  return add_string(fptr, buff);
++}
++
++static int add_subpartition(File fptr)
++{
++  int err= add_string(fptr, sub_str);
++
++  return err + add_partition(fptr);
++}
++
++static int add_partition_by(File fptr)
++{
++  char buff[22];
++  strxmov(buff, part_str, space_str, by_str, space_str, NullS);
++  return add_string(fptr, buff);
++}
++
++static int add_subpartition_by(File fptr)
++{
++  int err= add_string(fptr, sub_str);
++
++  return err + add_partition_by(fptr);
++}
++
++static int add_part_field_list(File fptr, List<char> field_list)
++{
++  uint i, num_fields;
++  int err= 0;
++
++  List_iterator<char> part_it(field_list);
++  num_fields= field_list.elements;
++  i= 0;
++  err+= add_begin_parenthesis(fptr);
++  while (i < num_fields)
++  {
++    const char *field_str= part_it++;
++    String field_string("", 0, system_charset_info);
++    THD *thd= current_thd;
++    ulonglong save_options= thd->variables.option_bits;
++    thd->variables.option_bits&= ~OPTION_QUOTE_SHOW_CREATE;
++    append_identifier(thd, &field_string, field_str,
++                      strlen(field_str));
++    thd->variables.option_bits= save_options;
++    err+= add_string_object(fptr, &field_string);
++    if (i != (num_fields-1))
++      err+= add_comma(fptr);
++    i++;
++  }
++  err+= add_end_parenthesis(fptr);
++  return err;
++}
++
++static int add_name_string(File fptr, const char *name)
++{
++  int err;
++  String name_string("", 0, system_charset_info);
++  THD *thd= current_thd;
++  ulonglong save_options= thd->variables.option_bits;
++  thd->variables.option_bits&= ~OPTION_QUOTE_SHOW_CREATE;
++  append_identifier(thd, &name_string, name,
++                    strlen(name));
++  thd->variables.option_bits= save_options;
++  err= add_string_object(fptr, &name_string);
++  return err;
++}
++
++static int add_int(File fptr, longlong number)
++{
++  char buff[32];
++  llstr(number, buff);
++  return add_string(fptr, buff);
++}
++
++static int add_uint(File fptr, ulonglong number)
++{
++  char buff[32];
++  longlong2str(number, buff, 10);
++  return add_string(fptr, buff);
++}
++
++/*
++   Must escape strings in partitioned tables frm-files,
++   parsing it later with mysql_unpack_partition will fail otherwise.
++*/
++static int add_quoted_string(File fptr, const char *quotestr)
++{
++  String orgstr(quotestr, system_charset_info);
++  String escapedstr;
++  int err= add_string(fptr, "'");
++  err+= append_escaped(&escapedstr, &orgstr);
++  err+= add_string(fptr, escapedstr.c_ptr_safe());
++  return err + add_string(fptr, "'");
++}
++
++/**
++  @brief  Truncate the partition file name from a path it it exists.
++
++  @note  A partition file name will contian one or more '#' characters.
++One of the occurances of '#' will be either "#P#" or "#p#" depending
++on whether the storage engine has converted the filename to lower case.
++*/
++void truncate_partition_filename(char *path)
++{
++  if (path)
++  {
++    char* last_slash= strrchr(path, FN_LIBCHAR);
++
++    if (!last_slash)
++      last_slash= strrchr(path, FN_LIBCHAR2);
++
++    if (last_slash)
++    {
++      /* Look for a partition-type filename */
++      for (char* pound= strchr(last_slash, '#');
++           pound; pound = strchr(pound + 1, '#'))
++      {
++        if ((pound[1] == 'P' || pound[1] == 'p') && pound[2] == '#')
++        {
++          last_slash[0] = '\0';	/* truncate the file name */
++          break;
++        }
++      }
++    }
++  }
++}
++
++
++/**
++  @brief  Output a filepath.  Similar to add_keyword_string except it
++also converts \ to / on Windows and skips the partition file name at
++the end if found.
++
++  @note  When Mysql sends a DATA DIRECTORY from SQL for partitions it does
++not use a file name, but it does for DATA DIRECTORY on a non-partitioned
++table.  So when the storage engine is asked for the DATA DIRECTORY string
++after a restart through Handler::update_create_options(), the storage
++engine may include the filename.
++*/
++static int add_keyword_path(File fptr, const char *keyword,
++                            const char *path)
++{
++
++  if (strlen(path) >= FN_REFLEN)
++  {
++    my_error(ER_PATH_LENGTH, MYF(0), "data/index directory (>=512 bytes)");
++    return 1;
++  }
++
++  int err= add_string(fptr, keyword);
++
++  err+= add_space(fptr);
++  err+= add_equal(fptr);
++  err+= add_space(fptr);
++
++  char temp_path[FN_REFLEN];
++  strncpy(temp_path, path, FN_REFLEN-1);
++  temp_path[FN_REFLEN-1] = '\0';
++#ifdef __WIN__
++  /* Convert \ to / to be able to create table on unix */
++  char *pos, *end;
++  uint length= strlen(temp_path);
++  for (pos= temp_path, end= pos+length ; pos < end ; pos++)
++  {
++    if (*pos == '\\')
++      *pos = '/';
++  }
++#endif
++
++  /*
++  If the partition file name with its "#P#" identifier
++  is found after the last slash, truncate that filename.
++  */
++  truncate_partition_filename(temp_path);
++
++  err+= add_quoted_string(fptr, temp_path);
++
++  return err + add_space(fptr);
++}
++
++static int add_keyword_string(File fptr, const char *keyword,
++                              bool should_use_quotes,
++                              const char *keystr)
++{
++  int err= add_string(fptr, keyword);
++
++  err+= add_space(fptr);
++  err+= add_equal(fptr);
++  err+= add_space(fptr);
++  if (should_use_quotes)
++    err+= add_quoted_string(fptr, keystr);
++  else
++    err+= add_string(fptr, keystr);
++  return err + add_space(fptr);
++}
++
++static int add_keyword_int(File fptr, const char *keyword, longlong num)
++{
++  int err= add_string(fptr, keyword);
++
++  err+= add_space(fptr);
++  err+= add_equal(fptr);
++  err+= add_space(fptr);
++  err+= add_int(fptr, num);
++  return err + add_space(fptr);
++}
++
++static int add_engine(File fptr, handlerton *engine_type)
++{
++  const char *engine_str= ha_resolve_storage_engine_name(engine_type);
++  DBUG_PRINT("info", ("ENGINE: %s", engine_str));
++  int err= add_string(fptr, "ENGINE = ");
++  return err + add_string(fptr, engine_str);
++}
++
++static int add_partition_options(File fptr, partition_element *p_elem)
++{
++  int err= 0;
++
++  err+= add_space(fptr);
++  if (p_elem->tablespace_name)
++    err+= add_keyword_string(fptr,"TABLESPACE", FALSE,
++                             p_elem->tablespace_name);
++  if (p_elem->nodegroup_id != UNDEF_NODEGROUP)
++    err+= add_keyword_int(fptr,"NODEGROUP",(longlong)p_elem->nodegroup_id);
++  if (p_elem->part_max_rows)
++    err+= add_keyword_int(fptr,"MAX_ROWS",(longlong)p_elem->part_max_rows);
++  if (p_elem->part_min_rows)
++    err+= add_keyword_int(fptr,"MIN_ROWS",(longlong)p_elem->part_min_rows);
++  if (!(current_thd->variables.sql_mode & MODE_NO_DIR_IN_CREATE))
++  {
++    if (p_elem->data_file_name)
++      err+= add_keyword_path(fptr, "DATA DIRECTORY", p_elem->data_file_name);
++    if (p_elem->index_file_name)
++      err+= add_keyword_path(fptr, "INDEX DIRECTORY", p_elem->index_file_name);
++  }
++  if (p_elem->part_comment)
++    err+= add_keyword_string(fptr, "COMMENT", TRUE, p_elem->part_comment);
++  return err + add_engine(fptr,p_elem->engine_type);
++}
++
++
++/*
++  Check partition fields for result type and if they need
++  to check the character set.
++
++  SYNOPSIS
++    check_part_field()
++    sql_type              Type provided by user
++    field_name            Name of field, used for error handling
++    result_type           Out value: Result type of field
++    need_cs_check         Out value: Do we need character set check
++
++  RETURN VALUES
++    TRUE                  Error
++    FALSE                 Ok
++*/
++
++static int check_part_field(enum_field_types sql_type,
++                            const char *field_name,
++                            Item_result *result_type,
++                            bool *need_cs_check)
++{
++  if (sql_type >= MYSQL_TYPE_TINY_BLOB &&
++      sql_type <= MYSQL_TYPE_BLOB)
++  {
++    my_error(ER_BLOB_FIELD_IN_PART_FUNC_ERROR, MYF(0));
++    return TRUE;
++  }
++  switch (sql_type)
++  {
++    case MYSQL_TYPE_TINY:
++    case MYSQL_TYPE_SHORT:
++    case MYSQL_TYPE_LONG:
++    case MYSQL_TYPE_LONGLONG:
++    case MYSQL_TYPE_INT24:
++      *result_type= INT_RESULT;
++      *need_cs_check= FALSE;
++      return FALSE;
++    case MYSQL_TYPE_NEWDATE:
++    case MYSQL_TYPE_DATE:
++    case MYSQL_TYPE_TIME:
++    case MYSQL_TYPE_DATETIME:
++    case MYSQL_TYPE_TIME2:
++    case MYSQL_TYPE_DATETIME2:
++      *result_type= STRING_RESULT;
++      *need_cs_check= TRUE;
++      return FALSE;
++    case MYSQL_TYPE_VARCHAR:
++    case MYSQL_TYPE_STRING:
++    case MYSQL_TYPE_VAR_STRING:
++      *result_type= STRING_RESULT;
++      *need_cs_check= TRUE;
++      return FALSE;
++    case MYSQL_TYPE_NEWDECIMAL:
++    case MYSQL_TYPE_DECIMAL:
++    case MYSQL_TYPE_TIMESTAMP:
++    case MYSQL_TYPE_TIMESTAMP2:
++    case MYSQL_TYPE_NULL:
++    case MYSQL_TYPE_FLOAT:
++    case MYSQL_TYPE_DOUBLE:
++    case MYSQL_TYPE_BIT:
++    case MYSQL_TYPE_ENUM:
++    case MYSQL_TYPE_SET:
++    case MYSQL_TYPE_GEOMETRY:
++      goto error;
++    default:
++      goto error;
++  }
++error:
++  my_error(ER_FIELD_TYPE_NOT_ALLOWED_AS_PARTITION_FIELD, MYF(0),
++           field_name);
++  return TRUE;
++}
++
++
++/*
++  Find the given field's Create_field object using name of field
++
++  SYNOPSIS
++    get_sql_field()
++    field_name                   Field name
++    alter_info                   Info from ALTER TABLE/CREATE TABLE
++
++  RETURN VALUE
++    sql_field                    Object filled in by parser about field
++    NULL                         No field found
++*/
++
++static Create_field* get_sql_field(char *field_name,
++                                   Alter_info *alter_info)
++{
++  List_iterator<Create_field> it(alter_info->create_list);
++  Create_field *sql_field;
++  DBUG_ENTER("get_sql_field");
++
++  while ((sql_field= it++))
++  {
++    if (!(my_strcasecmp(system_charset_info,
++                        sql_field->field_name,
++                        field_name)))
++    {
++      DBUG_RETURN(sql_field);
++    }
++  }
++  DBUG_RETURN(NULL);
++}
++
++
++static int add_column_list_values(File fptr, partition_info *part_info,
++                                  part_elem_value *list_value,
++                                  HA_CREATE_INFO *create_info,
++                                  Alter_info *alter_info)
++{
++  int err= 0;
++  uint i;
++  List_iterator<char> it(part_info->part_field_list);
++  uint num_elements= part_info->part_field_list.elements;
++  bool use_parenthesis= (part_info->part_type == LIST_PARTITION &&
++                         part_info->num_columns > 1U);
++
++  if (use_parenthesis)
++    err+= add_begin_parenthesis(fptr);
++  for (i= 0; i < num_elements; i++)
++  {
++    part_column_list_val *col_val= &list_value->col_val_array[i];
++    char *field_name= it++;
++    if (col_val->max_value)
++      err+= add_string(fptr, partition_keywords[PKW_MAXVALUE].str);
++    else if (col_val->null_value)
++      err+= add_string(fptr, "NULL");
++    else
++    {
++      char buffer[MAX_KEY_LENGTH];
++      String str(buffer, sizeof(buffer), &my_charset_bin);
++      Item *item_expr= col_val->item_expression;
++      if (item_expr->null_value)
++        err+= add_string(fptr, "NULL");
++      else
++      {
++        String *res;
++        const CHARSET_INFO *field_cs;
++        bool need_cs_check= FALSE;
++        Item_result result_type= STRING_RESULT;
++
++        /*
++          This function is called at a very early stage, even before
++          we have prepared the sql_field objects. Thus we have to
++          find the proper sql_field object and get the character set
++          from that object.
++        */
++        if (create_info)
++        {
++          Create_field *sql_field;
++
++          if (!(sql_field= get_sql_field(field_name,
++                                         alter_info)))
++          {
++            my_error(ER_FIELD_NOT_FOUND_PART_ERROR, MYF(0));
++            return 1;
++          }
++          if (check_part_field(sql_field->sql_type,
++                               sql_field->field_name,
++                               &result_type,
++                               &need_cs_check))
++            return 1;
++          if (need_cs_check)
++            field_cs= get_sql_field_charset(sql_field, create_info);
++          else
++            field_cs= NULL;
++        }
++        else
++        {
++          Field *field= part_info->part_field_array[i];
++          result_type= field->result_type();
++          if (check_part_field(field->real_type(),
++                               field->field_name,
++                               &result_type,
++                               &need_cs_check))
++            return 1;
++          DBUG_ASSERT(result_type == field->result_type());
++          if (need_cs_check)
++            field_cs= field->charset();
++          else
++            field_cs= NULL;
++        }
++        if (result_type != item_expr->result_type())
++        {
++          my_error(ER_WRONG_TYPE_COLUMN_VALUE_ERROR, MYF(0));
++          return 1;
++        }
++        if (field_cs && field_cs != item_expr->collation.collation)
++        {
++          if (!(item_expr= convert_charset_partition_constant(item_expr,
++                                                              field_cs)))
++          {
++            my_error(ER_PARTITION_FUNCTION_IS_NOT_ALLOWED, MYF(0));
++            return 1;
++          }
++        }
++        {
++          String val_conv;
++          val_conv.set_charset(system_charset_info);
++          res= item_expr->val_str(&str);
++          if (get_cs_converted_part_value_from_string(current_thd,
++                                                      item_expr, res,
++                                                      &val_conv, field_cs,
++                                                   (bool)(alter_info != NULL)))
++            return 1;
++          err+= add_string_object(fptr, &val_conv);
++        }
++      }
++    }
++    if (i != (num_elements - 1))
++      err+= add_string(fptr, comma_str);
++  }
++  if (use_parenthesis)
++    err+= add_end_parenthesis(fptr);
++  return err;
++}
++
++static int add_partition_values(File fptr, partition_info *part_info,
++                                partition_element *p_elem,
++                                HA_CREATE_INFO *create_info,
++                                Alter_info *alter_info)
++{
++  int err= 0;
++
++  if (part_info->part_type == RANGE_PARTITION)
++  {
++    err+= add_string(fptr, " VALUES LESS THAN ");
++    if (part_info->column_list)
++    {
++      List_iterator<part_elem_value> list_val_it(p_elem->list_val_list);
++      part_elem_value *list_value= list_val_it++;
++      err+= add_begin_parenthesis(fptr);
++      err+= add_column_list_values(fptr, part_info, list_value,
++                                   create_info, alter_info);
++      err+= add_end_parenthesis(fptr);
++    }
++    else
++    {
++      if (!p_elem->max_value)
++      {
++        err+= add_begin_parenthesis(fptr);
++        if (p_elem->signed_flag)
++          err+= add_int(fptr, p_elem->range_value);
++        else
++          err+= add_uint(fptr, p_elem->range_value);
++        err+= add_end_parenthesis(fptr);
++      }
++      else
++        err+= add_string(fptr, partition_keywords[PKW_MAXVALUE].str);
++    }
++  }
++  else if (part_info->part_type == LIST_PARTITION)
++  {
++    uint i;
++    List_iterator<part_elem_value> list_val_it(p_elem->list_val_list);
++    err+= add_string(fptr, " VALUES IN ");
++    uint num_items= p_elem->list_val_list.elements;
++
++    err+= add_begin_parenthesis(fptr);
++    if (p_elem->has_null_value)
++    {
++      err+= add_string(fptr, "NULL");
++      if (num_items == 0)
++      {
++        err+= add_end_parenthesis(fptr);
++        goto end;
++      }
++      err+= add_comma(fptr);
++    }
++    i= 0;
++    do
++    {
++      part_elem_value *list_value= list_val_it++;
++
++      if (part_info->column_list)
++        err+= add_column_list_values(fptr, part_info, list_value,
++                                     create_info, alter_info);
++      else
++      {
++        if (!list_value->unsigned_flag)
++          err+= add_int(fptr, list_value->value);
++        else
++          err+= add_uint(fptr, list_value->value);
++      }
++      if (i != (num_items-1))
++        err+= add_comma(fptr);
++    } while (++i < num_items);
++    err+= add_end_parenthesis(fptr);
++  }
++end:
++  return err;
++}
++
++
++/**
++  Add 'KEY' word, with optional 'ALGORTIHM = N'.
++
++  @param fptr                   File to write to.
++  @param part_info              partition_info holding the used key_algorithm
++  @param current_comment_start  NULL, or comment string encapsulating the
++                                PARTITION BY clause.
++
++  @return Operation status.
++    @retval 0    Success
++    @retval != 0 Failure
++*/
++
++static int add_key_with_algorithm(File fptr, partition_info *part_info,
++                                  const char *current_comment_start)
++{
++  int err= 0;
++  err+= add_part_key_word(fptr, partition_keywords[PKW_KEY].str);
++
++  /*
++    current_comment_start is given when called from SHOW CREATE TABLE,
++    Then only add ALGORITHM = 1, not the default 2 or non-set 0!
++    For .frm current_comment_start is NULL, then add ALGORITHM if != 0.
++  */
++  if (part_info->key_algorithm == partition_info::KEY_ALGORITHM_51 || // SHOW
++      (!current_comment_start &&                                      // .frm
++       (part_info->key_algorithm != partition_info::KEY_ALGORITHM_NONE)))
++  {
++    /* If we already are within a comment, end that comment first. */
++    if (current_comment_start)
++      err+= add_string(fptr, "*/ ");
++    err+= add_string(fptr, "/*!50611 ");
++    err+= add_part_key_word(fptr, partition_keywords[PKW_ALGORITHM].str);
++    err+= add_equal(fptr);
++    err+= add_space(fptr);
++    err+= add_int(fptr, part_info->key_algorithm);
++    err+= add_space(fptr);
++    err+= add_string(fptr, "*/ ");
++    if (current_comment_start)
++    {
++      /* Skip new line. */
++      if (current_comment_start[0] == '\n')
++        current_comment_start++;
++      err+= add_string(fptr, current_comment_start);
++      err+= add_space(fptr);
++    }
++  }
++  return err;
++}
++
++
++/*
++  Generate the partition syntax from the partition data structure.
++  Useful for support of generating defaults, SHOW CREATE TABLES
++  and easy partition management.
++
++  SYNOPSIS
++    generate_partition_syntax()
++    part_info                  The partitioning data structure
++    buf_length                 A pointer to the returned buffer length
++    use_sql_alloc              Allocate buffer from sql_alloc if true
++                               otherwise use my_malloc
++    show_partition_options     Should we display partition options
++    create_info                Info generated by parser
++    alter_info                 Info generated by parser
++
++  RETURN VALUES
++    NULL error
++    buf, buf_length            Buffer and its length
++
++  DESCRIPTION
++  Here we will generate the full syntax for the given command where all
++  defaults have been expanded. By so doing the it is also possible to
++  make lots of checks of correctness while at it.
++  This could will also be reused for SHOW CREATE TABLES and also for all
++  type ALTER TABLE commands focusing on changing the PARTITION structure
++  in any fashion.
++
++  The implementation writes the syntax to a temporary file (essentially
++  an abstraction of a dynamic array) and if all writes goes well it
++  allocates a buffer and writes the syntax into this one and returns it.
++
++  As a security precaution the file is deleted before writing into it. This
++  means that no other processes on the machine can open and read the file
++  while this processing is ongoing.
++
++  The code is optimised for minimal code size since it is not used in any
++  common queries.
++*/
++
++char *generate_partition_syntax(partition_info *part_info,
++                                uint *buf_length,
++                                bool use_sql_alloc,
++                                bool show_partition_options,
++                                HA_CREATE_INFO *create_info,
++                                Alter_info *alter_info,
++                                const char *current_comment_start)
++{
++  uint i,j, tot_num_parts, num_subparts;
++  partition_element *part_elem;
++  ulonglong buffer_length;
++  char path[FN_REFLEN];
++  int err= 0;
++  List_iterator<partition_element> part_it(part_info->partitions);
++  File fptr;
++  char *buf= NULL; //Return buffer
++  DBUG_ENTER("generate_partition_syntax");
++
++  if (unlikely(((fptr= create_temp_file(path,mysql_tmpdir,"psy", 
++                                        O_RDWR | O_BINARY | O_TRUNC |  
++                                        O_TEMPORARY, MYF(MY_WME)))) < 0))
++    DBUG_RETURN(NULL);
++#ifndef __WIN__
++  unlink(path);
++#endif
++  err+= add_space(fptr);
++  err+= add_partition_by(fptr);
++  switch (part_info->part_type)
++  {
++    case RANGE_PARTITION:
++      err+= add_part_key_word(fptr, partition_keywords[PKW_RANGE].str);
++      break;
++    case LIST_PARTITION:
++      err+= add_part_key_word(fptr, partition_keywords[PKW_LIST].str);
++      break;
++    case HASH_PARTITION:
++      if (part_info->linear_hash_ind)
++        err+= add_string(fptr, partition_keywords[PKW_LINEAR].str);
++      if (part_info->list_of_part_fields)
++      {
++        err+= add_key_with_algorithm(fptr, part_info,
++                                     current_comment_start);
++        err+= add_part_field_list(fptr, part_info->part_field_list);
++      }
++      else
++        err+= add_part_key_word(fptr, partition_keywords[PKW_HASH].str);
++      break;
++    default:
++      DBUG_ASSERT(0);
++      /* We really shouldn't get here, no use in continuing from here */
++      my_error(ER_OUT_OF_RESOURCES, MYF(ME_FATALERROR));
++      DBUG_RETURN(NULL);
++  }
++  if (part_info->part_expr)
++  {
++    err+= add_begin_parenthesis(fptr);
++    err+= add_string_len(fptr, part_info->part_func_string,
++                         part_info->part_func_len);
++    err+= add_end_parenthesis(fptr);
++  }
++  else if (part_info->column_list)
++  {
++    err+= add_string(fptr, partition_keywords[PKW_COLUMNS].str);
++    err+= add_part_field_list(fptr, part_info->part_field_list);
++  }
++  if ((!part_info->use_default_num_partitions) &&
++       part_info->use_default_partitions)
++  {
++    err+= add_string(fptr, "\n");
++    err+= add_string(fptr, "PARTITIONS ");
++    err+= add_int(fptr, part_info->num_parts);
++  }
++  if (part_info->is_sub_partitioned())
++  {
++    err+= add_string(fptr, "\n");
++    err+= add_subpartition_by(fptr);
++    /* Must be hash partitioning for subpartitioning */
++    if (part_info->linear_hash_ind)
++      err+= add_string(fptr, partition_keywords[PKW_LINEAR].str);
++    if (part_info->list_of_subpart_fields)
++    {
++      err+= add_key_with_algorithm(fptr, part_info,
++                                   current_comment_start);
++      err+= add_part_field_list(fptr, part_info->subpart_field_list);
++    }
++    else
++      err+= add_part_key_word(fptr, partition_keywords[PKW_HASH].str);
++    if (part_info->subpart_expr)
++    {
++      err+= add_begin_parenthesis(fptr);
++      err+= add_string_len(fptr, part_info->subpart_func_string,
++                           part_info->subpart_func_len);
++      err+= add_end_parenthesis(fptr);
++    }
++    if ((!part_info->use_default_num_subpartitions) && 
++          part_info->use_default_subpartitions)
++    {
++      err+= add_string(fptr, "\n");
++      err+= add_string(fptr, "SUBPARTITIONS ");
++      err+= add_int(fptr, part_info->num_subparts);
++    }
++  }
++  tot_num_parts= part_info->partitions.elements;
++  num_subparts= part_info->num_subparts;
++
++  if (!part_info->use_default_partitions)
++  {
++    bool first= TRUE;
++    err+= add_string(fptr, "\n");
++    err+= add_begin_parenthesis(fptr);
++    i= 0;
++    do
++    {
++      part_elem= part_it++;
++      if (part_elem->part_state != PART_TO_BE_DROPPED &&
++          part_elem->part_state != PART_REORGED_DROPPED)
++      {
++        if (!first)
++        {
++          err+= add_comma(fptr);
++          err+= add_string(fptr, "\n");
++          err+= add_space(fptr);
++        }
++        first= FALSE;
++        err+= add_partition(fptr);
++        err+= add_name_string(fptr, part_elem->partition_name);
++        err+= add_partition_values(fptr, part_info, part_elem,
++                                   create_info, alter_info);
++        if (!part_info->is_sub_partitioned() ||
++            part_info->use_default_subpartitions)
++        {
++          if (show_partition_options)
++            err+= add_partition_options(fptr, part_elem);
++        }
++        else
++        {
++          err+= add_string(fptr, "\n");
++          err+= add_space(fptr);
++          err+= add_begin_parenthesis(fptr);
++          List_iterator<partition_element> sub_it(part_elem->subpartitions);
++          j= 0;
++          do
++          {
++            part_elem= sub_it++;
++            err+= add_subpartition(fptr);
++            err+= add_name_string(fptr, part_elem->partition_name);
++            if (show_partition_options)
++              err+= add_partition_options(fptr, part_elem);
++            if (j != (num_subparts-1))
++            {
++              err+= add_comma(fptr);
++              err+= add_string(fptr, "\n");
++              err+= add_space(fptr);
++              err+= add_space(fptr);
++            }
++            else
++              err+= add_end_parenthesis(fptr);
++          } while (++j < num_subparts);
++        }
++      }
++      if (i == (tot_num_parts-1))
++        err+= add_end_parenthesis(fptr);
++    } while (++i < tot_num_parts);
++  }
++  if (err)
++    goto close_file;
++  buffer_length= mysql_file_seek(fptr, 0L, MY_SEEK_END, MYF(0));
++  if (unlikely(buffer_length == MY_FILEPOS_ERROR))
++    goto close_file;
++  if (unlikely(mysql_file_seek(fptr, 0L, MY_SEEK_SET, MYF(0))
++               == MY_FILEPOS_ERROR))
++    goto close_file;
++  *buf_length= (uint)buffer_length;
++  if (use_sql_alloc)
++    buf= (char*) sql_alloc(*buf_length+1);
++  else
++    buf= (char*) my_malloc(*buf_length+1, MYF(MY_WME));
++  if (!buf)
++    goto close_file;
++
++  if (unlikely(mysql_file_read(fptr, (uchar*)buf, *buf_length, MYF(MY_FNABP))))
++  {
++    if (!use_sql_alloc)
++      my_free(buf);
++    else
++      buf= NULL;
++  }
++  else
++    buf[*buf_length]= 0;
++
++close_file:
++  mysql_file_close(fptr, MYF(0));
++  DBUG_RETURN(buf);
++}
++
++
++/*
++  Check if partition key fields are modified and if it can be handled by the
++  underlying storage engine.
++
++  SYNOPSIS
++    partition_key_modified
++    table                TABLE object for which partition fields are set-up
++    fields               Bitmap representing fields to be modified
++
++  RETURN VALUES
++    TRUE                 Need special handling of UPDATE
++    FALSE                Normal UPDATE handling is ok
++*/
++
++bool partition_key_modified(TABLE *table, const MY_BITMAP *fields)
++{
++  Field **fld;
++  partition_info *part_info= table->part_info;
++  DBUG_ENTER("partition_key_modified");
++
++  if (!part_info)
++    DBUG_RETURN(FALSE);
++  if (table->s->db_type()->partition_flags &&
++      (table->s->db_type()->partition_flags() & HA_CAN_UPDATE_PARTITION_KEY))
++    DBUG_RETURN(FALSE);
++  for (fld= part_info->full_part_field_array; *fld; fld++)
++    if (bitmap_is_set(fields, (*fld)->field_index))
++      DBUG_RETURN(TRUE);
++  DBUG_RETURN(FALSE);
++}
++
++
++/*
++  A function to handle correct handling of NULL values in partition
++  functions.
++  SYNOPSIS
++    part_val_int()
++    item_expr                 The item expression to evaluate
++    out:result                The value of the partition function,
++                                LONGLONG_MIN if any null value in function
++  RETURN VALUES
++    TRUE      Error in val_int()
++    FALSE     ok
++*/
++
++static inline int part_val_int(Item *item_expr, longlong *result)
++{
++  *result= item_expr->val_int();
++  if (item_expr->null_value)
++  {
++    if (current_thd->is_error())
++      return TRUE;
++    else
++      *result= LONGLONG_MIN;
++  }
++  return FALSE;
++}
++
++
++/*
++  The next set of functions are used to calculate the partition identity.
++  A handler sets up a variable that corresponds to one of these functions
++  to be able to quickly call it whenever the partition id needs to calculated
++  based on the record in table->record[0] (or set up to fake that).
++  There are 4 functions for hash partitioning and 2 for RANGE/LIST partitions.
++  In addition there are 4 variants for RANGE subpartitioning and 4 variants
++  for LIST subpartitioning thus in total there are 14 variants of this
++  function.
++
++  We have a set of support functions for these 14 variants. There are 4
++  variants of hash functions and there is a function for each. The KEY
++  partitioning uses the function calculate_key_hash_value to calculate the hash
++  value based on an array of fields. The linear hash variants uses the
++  method get_part_id_from_linear_hash to get the partition id using the
++  hash value and some parameters calculated from the number of partitions.
++*/
++
++/*
++  A simple support function to calculate part_id given local part and
++  sub part.
++
++  SYNOPSIS
++    get_part_id_for_sub()
++    loc_part_id             Local partition id
++    sub_part_id             Subpartition id
++    num_subparts            Number of subparts
++*/
++
++inline
++static uint32 get_part_id_for_sub(uint32 loc_part_id, uint32 sub_part_id,
++                                  uint num_subparts)
++{
++  return (uint32)((loc_part_id * num_subparts) + sub_part_id);
++}
++
++
++/*
++  Calculate part_id for (SUB)PARTITION BY HASH
++
++  SYNOPSIS
++    get_part_id_hash()
++    num_parts                Number of hash partitions
++    part_expr                Item tree of hash function
++    out:part_id              The returned partition id
++    out:func_value           Value of hash function
++
++  RETURN VALUE
++    != 0                          Error code
++    FALSE                         Success
++*/
++
++static int get_part_id_hash(uint num_parts,
++                            Item *part_expr,
++                            uint32 *part_id,
++                            longlong *func_value)
++{
++  longlong int_hash_id;
++  DBUG_ENTER("get_part_id_hash");
++
++  if (part_val_int(part_expr, func_value))
++    DBUG_RETURN(HA_ERR_NO_PARTITION_FOUND);
++
++  int_hash_id= *func_value % num_parts;
++
++  *part_id= int_hash_id < 0 ? (uint32) -int_hash_id : (uint32) int_hash_id;
++  DBUG_RETURN(FALSE);
++}
++
++
++/*
++  Calculate part_id for (SUB)PARTITION BY LINEAR HASH
++
++  SYNOPSIS
++    get_part_id_linear_hash()
++    part_info           A reference to the partition_info struct where all the
++                        desired information is given
++    num_parts           Number of hash partitions
++    part_expr           Item tree of hash function
++    out:part_id         The returned partition id
++    out:func_value      Value of hash function
++
++  RETURN VALUE
++    != 0     Error code
++    0        OK
++*/
++
++static int get_part_id_linear_hash(partition_info *part_info,
++                                   uint num_parts,
++                                   Item *part_expr,
++                                   uint32 *part_id,
++                                   longlong *func_value)
++{
++  DBUG_ENTER("get_part_id_linear_hash");
++
++  if (part_val_int(part_expr, func_value))
++    DBUG_RETURN(HA_ERR_NO_PARTITION_FOUND);
++
++  *part_id= get_part_id_from_linear_hash(*func_value,
++                                         part_info->linear_hash_mask,
++                                         num_parts);
++  DBUG_RETURN(FALSE);
++}
++
++
++/**
++  Calculate part_id for (SUB)PARTITION BY KEY
++
++  @param file                Handler to storage engine
++  @param field_array         Array of fields for PARTTION KEY
++  @param num_parts           Number of KEY partitions
++  @param func_value[out]     Returns calculated hash value
++
++  @return Calculated partition id
++*/
++
++inline
++static uint32 get_part_id_key(handler *file,
++                              Field **field_array,
++                              uint num_parts,
++                              longlong *func_value)
++{
++  DBUG_ENTER("get_part_id_key");
++  *func_value= file->calculate_key_hash_value(field_array);
++  DBUG_RETURN((uint32) (*func_value % num_parts));
++}
++
++
++/*
++  Calculate part_id for (SUB)PARTITION BY LINEAR KEY
++
++  SYNOPSIS
++    get_part_id_linear_key()
++    part_info           A reference to the partition_info struct where all the
++                        desired information is given
++    field_array         Array of fields for PARTTION KEY
++    num_parts            Number of KEY partitions
++
++  RETURN VALUE
++    Calculated partition id
++*/
++
++inline
++static uint32 get_part_id_linear_key(partition_info *part_info,
++                                     Field **field_array,
++                                     uint num_parts,
++                                     longlong *func_value)
++{
++  DBUG_ENTER("get_part_id_linear_key");
++
++  *func_value= part_info->table->file->calculate_key_hash_value(field_array);
++  DBUG_RETURN(get_part_id_from_linear_hash(*func_value,
++                                           part_info->linear_hash_mask,
++                                           num_parts));
++}
++
++/*
++  Copy to field buffers and set up field pointers
++
++  SYNOPSIS
++    copy_to_part_field_buffers()
++    ptr                          Array of fields to copy
++    field_bufs                   Array of field buffers to copy to
++    restore_ptr                  Array of pointers to restore to
++
++  RETURN VALUES
++    NONE
++  DESCRIPTION
++    This routine is used to take the data from field pointer, convert
++    it to a standard format and store this format in a field buffer
++    allocated for this purpose. Next the field pointers are moved to
++    point to the field buffers. There is a separate to restore the
++    field pointers after this call.
++*/
++
++static void copy_to_part_field_buffers(Field **ptr,
++                                       uchar **field_bufs,
++                                       uchar **restore_ptr)
++{
++  Field *field;
++  while ((field= *(ptr++)))
++  {
++    *restore_ptr= field->ptr;
++    restore_ptr++;
++    if (!field->maybe_null() || !field->is_null())
++    {
++      const CHARSET_INFO *cs= field->charset();
++      uint max_len= field->pack_length();
++      uint data_len= field->data_length();
++      uchar *field_buf= *field_bufs;
++      /*
++         We only use the field buffer for VARCHAR and CHAR strings
++         which isn't of a binary collation. We also only use the
++         field buffer for fields which are not currently NULL.
++         The field buffer will store a normalised string. We use
++         the strnxfrm method to normalise the string.
++       */
++      if (field->type() == MYSQL_TYPE_VARCHAR)
++      {
++        uint len_bytes= ((Field_varstring*)field)->length_bytes;
++        my_strnxfrm(cs, field_buf + len_bytes, max_len,
++                    field->ptr + len_bytes, data_len);
++        if (len_bytes == 1)
++          *field_buf= (uchar) data_len;
++        else
++          int2store(field_buf, data_len);
++      }
++      else
++      {
++        my_strnxfrm(cs, field_buf, max_len,
++                    field->ptr, max_len);
++      }
++      field->ptr= field_buf;
++    }
++    field_bufs++;
++  }
++  return;
++}
++
++/*
++  Restore field pointers
++  SYNOPSIS
++    restore_part_field_pointers()
++    ptr                            Array of fields to restore
++    restore_ptr                    Array of field pointers to restore to
++
++  RETURN VALUES
++*/
++
++static void restore_part_field_pointers(Field **ptr, uchar **restore_ptr)
++{
++  Field *field;
++  while ((field= *(ptr++)))
++  {
++    field->ptr= *restore_ptr;
++    restore_ptr++;
++  }
++  return;
++}
++
++/*
++  This function is used to calculate the partition id where all partition
++  fields have been prepared to point to a record where the partition field
++  values are bound.
++
++  SYNOPSIS
++    get_partition_id()
++    part_info           A reference to the partition_info struct where all the
++                        desired information is given
++    out:part_id         The partition id is returned through this pointer
++    out:func_value      Value of partition function (longlong)
++
++  RETURN VALUE
++    part_id                     Partition id of partition that would contain
++                                row with given values of PF-fields
++    HA_ERR_NO_PARTITION_FOUND   The fields of the partition function didn't
++                                fit into any partition and thus the values of 
++                                the PF-fields are not allowed.
++
++  DESCRIPTION
++    A routine used from write_row, update_row and delete_row from any
++    handler supporting partitioning. It is also a support routine for
++    get_partition_set used to find the set of partitions needed to scan
++    for a certain index scan or full table scan.
++    
++    It is actually 9 different variants of this function which are called
++    through a function pointer.
++
++    get_partition_id_list
++    get_partition_id_list_col
++    get_partition_id_range
++    get_partition_id_range_col
++    get_partition_id_hash_nosub
++    get_partition_id_key_nosub
++    get_partition_id_linear_hash_nosub
++    get_partition_id_linear_key_nosub
++    get_partition_id_with_sub
++*/
++
++/*
++  This function is used to calculate the main partition to use in the case of
++  subpartitioning and we don't know enough to get the partition identity in
++  total.
++
++  SYNOPSIS
++    get_part_partition_id()
++    part_info           A reference to the partition_info struct where all the
++                        desired information is given
++    out:part_id         The partition id is returned through this pointer
++    out:func_value      The value calculated by partition function
++
++  RETURN VALUE
++    HA_ERR_NO_PARTITION_FOUND   The fields of the partition function didn't
++                                fit into any partition and thus the values of 
++                                the PF-fields are not allowed.
++    0                           OK
++
++  DESCRIPTION
++    
++    It is actually 8 different variants of this function which are called
++    through a function pointer.
++
++    get_partition_id_list
++    get_partition_id_list_col
++    get_partition_id_range
++    get_partition_id_range_col
++    get_partition_id_hash_nosub
++    get_partition_id_key_nosub
++    get_partition_id_linear_hash_nosub
++    get_partition_id_linear_key_nosub
++*/
++
++static int get_part_id_charset_func_part(partition_info *part_info,
++                                         uint32 *part_id,
++                                         longlong *func_value)
++{
++  int res;
++  DBUG_ENTER("get_part_id_charset_func_part");
++
++  copy_to_part_field_buffers(part_info->part_charset_field_array,
++                             part_info->part_field_buffers,
++                             part_info->restore_part_field_ptrs);
++  res= part_info->get_part_partition_id_charset(part_info,
++                                                part_id, func_value);
++  restore_part_field_pointers(part_info->part_charset_field_array,
++                              part_info->restore_part_field_ptrs);
++  DBUG_RETURN(res);
++}
++
++
++static int get_part_id_charset_func_subpart(partition_info *part_info,
++                                            uint32 *part_id)
++{
++  int res;
++  DBUG_ENTER("get_part_id_charset_func_subpart");
++
++  copy_to_part_field_buffers(part_info->subpart_charset_field_array,
++                             part_info->subpart_field_buffers,
++                             part_info->restore_subpart_field_ptrs);
++  res= part_info->get_subpartition_id_charset(part_info, part_id);
++  restore_part_field_pointers(part_info->subpart_charset_field_array,
++                              part_info->restore_subpart_field_ptrs);
++  DBUG_RETURN(res);
++}
++
++int get_partition_id_list_col(partition_info *part_info,
++                              uint32 *part_id,
++                              longlong *func_value)
++{
++  part_column_list_val *list_col_array= part_info->list_col_array;
++  uint num_columns= part_info->part_field_list.elements;
++  int list_index, cmp;
++  int min_list_index= 0;
++  int max_list_index= part_info->num_list_values - 1;
++  DBUG_ENTER("get_partition_id_list_col");
++
++  while (max_list_index >= min_list_index)
++  {
++    list_index= (max_list_index + min_list_index) >> 1;
++    cmp= cmp_rec_and_tuple(list_col_array + list_index*num_columns,
++                          num_columns);
++    if (cmp > 0)
++      min_list_index= list_index + 1;
++    else if (cmp < 0)
++    {
++      if (!list_index)
++        goto notfound;
++      max_list_index= list_index - 1;
++    }
++    else
++    {
++      *part_id= (uint32)list_col_array[list_index*num_columns].partition_id;
++      DBUG_RETURN(0);
++    }
++  }
++notfound:
++  *part_id= 0;
++  DBUG_RETURN(HA_ERR_NO_PARTITION_FOUND);
++}
++
++
++int get_partition_id_list(partition_info *part_info,
++                          uint32 *part_id,
++                          longlong *func_value)
++{
++  LIST_PART_ENTRY *list_array= part_info->list_array;
++  int list_index;
++  int min_list_index= 0;
++  int max_list_index= part_info->num_list_values - 1;
++  longlong part_func_value;
++  int error= part_val_int(part_info->part_expr, &part_func_value);
++  longlong list_value;
++  bool unsigned_flag= part_info->part_expr->unsigned_flag;
++  DBUG_ENTER("get_partition_id_list");
++
++  if (error)
++    goto notfound;
++
++  if (part_info->part_expr->null_value)
++  {
++    if (part_info->has_null_value)
++    {
++      *part_id= part_info->has_null_part_id;
++      DBUG_RETURN(0);
++    }
++    goto notfound;
++  }
++  *func_value= part_func_value;
++  if (unsigned_flag)
++    part_func_value-= 0x8000000000000000ULL;
++  while (max_list_index >= min_list_index)
++  {
++    list_index= (max_list_index + min_list_index) >> 1;
++    list_value= list_array[list_index].list_value;
++    if (list_value < part_func_value)
++      min_list_index= list_index + 1;
++    else if (list_value > part_func_value)
++    {
++      if (!list_index)
++        goto notfound;
++      max_list_index= list_index - 1;
++    }
++    else
++    {
++      *part_id= (uint32)list_array[list_index].partition_id;
++      DBUG_RETURN(0);
++    }
++  }
++notfound:
++  *part_id= 0;
++  DBUG_RETURN(HA_ERR_NO_PARTITION_FOUND);
++}
++
++
++uint32 get_partition_id_cols_list_for_endpoint(partition_info *part_info,
++                                               bool left_endpoint,
++                                               bool include_endpoint,
++                                               uint32 nparts)
++{
++  part_column_list_val *list_col_array= part_info->list_col_array;
++  uint num_columns= part_info->part_field_list.elements;
++  uint list_index;
++  uint min_list_index= 0;
++  int cmp;
++  /* Notice that max_list_index = last_index + 1 here! */
++  uint max_list_index= part_info->num_list_values;
++  DBUG_ENTER("get_partition_id_cols_list_for_endpoint");
++
++  /* Find the matching partition (including taking endpoint into account). */
++  do
++  {
++    /* Midpoint, adjusted down, so it can never be >= max_list_index. */
++    list_index= (max_list_index + min_list_index) >> 1;
++    cmp= cmp_rec_and_tuple_prune(list_col_array + list_index*num_columns,
++                                 nparts, left_endpoint, include_endpoint);
++    if (cmp > 0)
++    {
++      min_list_index= list_index + 1;
++    }
++    else
++    {
++      max_list_index= list_index;
++      if (cmp == 0)
++        break;
++    }
++  } while (max_list_index > min_list_index);
++  list_index= max_list_index;
++
++  /* Given value must be LESS THAN or EQUAL to the found partition. */
++  DBUG_ASSERT(list_index == part_info->num_list_values ||
++              (0 >= cmp_rec_and_tuple_prune(list_col_array +
++                                              list_index*num_columns,
++                                            nparts, left_endpoint,
++                                            include_endpoint)));
++  /* Given value must be GREATER THAN the previous partition. */
++  DBUG_ASSERT(list_index == 0 ||
++              (0 < cmp_rec_and_tuple_prune(list_col_array +
++                                            (list_index - 1)*num_columns,
++                                           nparts, left_endpoint,
++                                           include_endpoint)));
++
++  /* Include the right endpoint if not already passed end of array. */
++  if (!left_endpoint && include_endpoint && cmp == 0 &&
++      list_index < part_info->num_list_values)
++    list_index++;
++
++  DBUG_RETURN(list_index);
++}
++
++
++/**
++  Find the sub-array part_info->list_array that corresponds to given interval.
++
++  @param part_info         Partitioning info (partitioning type must be LIST)
++  @param left_endpoint     TRUE  - the interval is [a; +inf) or (a; +inf)
++                           FALSE - the interval is (-inf; a] or (-inf; a)
++  @param include_endpoint  TRUE iff the interval includes the endpoint
++
++  This function finds the sub-array of part_info->list_array where values of
++  list_array[idx].list_value are contained within the specifed interval.
++  list_array is ordered by list_value, so
++  1. For [a; +inf) or (a; +inf)-type intervals (left_endpoint==TRUE), the
++     sought sub-array starts at some index idx and continues till array end.
++     The function returns first number idx, such that
++     list_array[idx].list_value is contained within the passed interval.
++
++  2. For (-inf; a] or (-inf; a)-type intervals (left_endpoint==FALSE), the
++     sought sub-array starts at array start and continues till some last
++     index idx.
++     The function returns first number idx, such that
++     list_array[idx].list_value is NOT contained within the passed interval.
++     If all array elements are contained, part_info->num_list_values is
++     returned.
++
++  @note The caller will call this function and then will run along the
++  sub-array of list_array to collect partition ids. If the number of list
++  values is significantly higher then number of partitions, this could be slow
++  and we could invent some other approach. The "run over list array" part is
++  already wrapped in a get_next()-like function.
++
++  @return The index of corresponding sub-array of part_info->list_array.
++*/
++
++uint32 get_list_array_idx_for_endpoint_charset(partition_info *part_info,
++                                               bool left_endpoint,
++                                               bool include_endpoint)
++{
++  uint32 res;
++  copy_to_part_field_buffers(part_info->part_field_array,
++                             part_info->part_field_buffers,
++                             part_info->restore_part_field_ptrs);
++  res= get_list_array_idx_for_endpoint(part_info, left_endpoint,
++                                       include_endpoint);
++  restore_part_field_pointers(part_info->part_field_array,
++                              part_info->restore_part_field_ptrs);
++  return res;
++}
++
++uint32 get_list_array_idx_for_endpoint(partition_info *part_info,
++                                       bool left_endpoint,
++                                       bool include_endpoint)
++{
++  LIST_PART_ENTRY *list_array= part_info->list_array;
++  uint list_index;
++  uint min_list_index= 0, max_list_index= part_info->num_list_values - 1;
++  longlong list_value;
++  /* Get the partitioning function value for the endpoint */
++  longlong part_func_value= 
++    part_info->part_expr->val_int_endpoint(left_endpoint, &include_endpoint);
++  bool unsigned_flag= part_info->part_expr->unsigned_flag;
++  DBUG_ENTER("get_list_array_idx_for_endpoint");
++
++  if (part_info->part_expr->null_value)
++  {
++    /*
++      Special handling for MONOTONIC functions that can return NULL for
++      values that are comparable. I.e.
++      '2000-00-00' can be compared to '2000-01-01' but TO_DAYS('2000-00-00')
++      returns NULL which cannot be compared used <, >, <=, >= etc.
++
++      Otherwise, just return the the first index (lowest value).
++    */
++    enum_monotonicity_info monotonic;
++    monotonic= part_info->part_expr->get_monotonicity_info();
++    if (monotonic != MONOTONIC_INCREASING_NOT_NULL && 
++        monotonic != MONOTONIC_STRICT_INCREASING_NOT_NULL)
++    {
++      /* F(col) can not return NULL, return index with lowest value */
++      DBUG_RETURN(0);
++    }
++  }
++
++  if (unsigned_flag)
++    part_func_value-= 0x8000000000000000ULL;
++  DBUG_ASSERT(part_info->num_list_values);
++  do
++  {
++    list_index= (max_list_index + min_list_index) >> 1;
++    list_value= list_array[list_index].list_value;
++    if (list_value < part_func_value)
++      min_list_index= list_index + 1;
++    else if (list_value > part_func_value)
++    {
++      if (!list_index)
++        goto notfound;
++      max_list_index= list_index - 1;
++    }
++    else 
++    {
++      DBUG_RETURN(list_index + MY_TEST(left_endpoint ^ include_endpoint));
++    }
++  } while (max_list_index >= min_list_index);
++notfound:
++  if (list_value < part_func_value)
++    list_index++;
++  DBUG_RETURN(list_index);
++}
++
++
++int get_partition_id_range_col(partition_info *part_info,
++                               uint32 *part_id,
++                               longlong *func_value)
++{
++  part_column_list_val *range_col_array= part_info->range_col_array;
++  uint num_columns= part_info->part_field_list.elements;
++  uint max_partition= part_info->num_parts - 1;
++  uint min_part_id= 0;
++  uint max_part_id= max_partition;
++  uint loc_part_id;
++  DBUG_ENTER("get_partition_id_range_col");
++
++  while (max_part_id > min_part_id)
++  {
++    loc_part_id= (max_part_id + min_part_id + 1) >> 1;
++    if (cmp_rec_and_tuple(range_col_array + loc_part_id*num_columns,
++                          num_columns) >= 0)
++      min_part_id= loc_part_id + 1;
++    else
++      max_part_id= loc_part_id - 1;
++  }
++  loc_part_id= max_part_id;
++  if (loc_part_id != max_partition)
++    if (cmp_rec_and_tuple(range_col_array + loc_part_id*num_columns,
++                          num_columns) >= 0)
++      loc_part_id++;
++  *part_id= (uint32)loc_part_id;
++  if (loc_part_id == max_partition &&
++      (cmp_rec_and_tuple(range_col_array + loc_part_id*num_columns,
++                         num_columns) >= 0))
++    DBUG_RETURN(HA_ERR_NO_PARTITION_FOUND);
++
++  DBUG_PRINT("exit",("partition: %d", *part_id));
++  DBUG_RETURN(0);
++}
++
++
++int get_partition_id_range(partition_info *part_info,
++                           uint32 *part_id,
++                           longlong *func_value)
++{
++  longlong *range_array= part_info->range_int_array;
++  uint max_partition= part_info->num_parts - 1;
++  uint min_part_id= 0;
++  uint max_part_id= max_partition;
++  uint loc_part_id;
++  longlong part_func_value;
++  int error= part_val_int(part_info->part_expr, &part_func_value);
++  bool unsigned_flag= part_info->part_expr->unsigned_flag;
++  DBUG_ENTER("get_partition_id_range");
++
++  if (error)
++    DBUG_RETURN(HA_ERR_NO_PARTITION_FOUND);
++
++  if (part_info->part_expr->null_value)
++  {
++    *part_id= 0;
++    DBUG_RETURN(0);
++  }
++  *func_value= part_func_value;
++  if (unsigned_flag)
++    part_func_value-= 0x8000000000000000ULL;
++  /* Search for the partition containing part_func_value */
++  while (max_part_id > min_part_id)
++  {
++    loc_part_id= (max_part_id + min_part_id) / 2;
++    if (range_array[loc_part_id] <= part_func_value)
++      min_part_id= loc_part_id + 1;
++    else
++      max_part_id= loc_part_id;
++  }
++  loc_part_id= max_part_id;
++  *part_id= (uint32)loc_part_id;
++  if (loc_part_id == max_partition &&
++      part_func_value >= range_array[loc_part_id] &&
++      !part_info->defined_max_value)
++    DBUG_RETURN(HA_ERR_NO_PARTITION_FOUND);
++
++  DBUG_PRINT("exit",("partition: %d", *part_id));
++  DBUG_RETURN(0);
++}
++
++
++/*
++  Find the sub-array of part_info->range_int_array that covers given interval
++ 
++  SYNOPSIS 
++    get_partition_id_range_for_endpoint()
++      part_info         Partitioning info (partitioning type must be RANGE)
++      left_endpoint     TRUE  - the interval is [a; +inf) or (a; +inf)
++                        FALSE - the interval is (-inf; a] or (-inf; a).
++      include_endpoint  TRUE <=> the endpoint itself is included in the
++                        interval
++
++  DESCRIPTION
++    This function finds the sub-array of part_info->range_int_array where the
++    elements have non-empty intersections with the given interval.
++ 
++    A range_int_array element at index idx represents the interval
++      
++      [range_int_array[idx-1], range_int_array[idx]),
++
++    intervals are disjoint and ordered by their right bound, so
++    
++    1. For [a; +inf) or (a; +inf)-type intervals (left_endpoint==TRUE), the
++       sought sub-array starts at some index idx and continues till array end.
++       The function returns first number idx, such that the interval
++       represented by range_int_array[idx] has non empty intersection with 
++       the passed interval.
++       
++    2. For (-inf; a] or (-inf; a)-type intervals (left_endpoint==FALSE), the
++       sought sub-array starts at array start and continues till some last
++       index idx.
++       The function returns first number idx, such that the interval
++       represented by range_int_array[idx] has EMPTY intersection with the
++       passed interval.
++       If the interval represented by the last array element has non-empty 
++       intersection with the passed interval, part_info->num_parts is
++       returned.
++       
++  RETURN
++    The edge of corresponding part_info->range_int_array sub-array.
++*/
++
++static uint32
++get_partition_id_range_for_endpoint_charset(partition_info *part_info,
++                                            bool left_endpoint,
++                                            bool include_endpoint)
++{
++  uint32 res;
++  copy_to_part_field_buffers(part_info->part_field_array,
++                             part_info->part_field_buffers,
++                             part_info->restore_part_field_ptrs);
++  res= get_partition_id_range_for_endpoint(part_info, left_endpoint,
++                                           include_endpoint);
++  restore_part_field_pointers(part_info->part_field_array,
++                              part_info->restore_part_field_ptrs);
++  return res;
++}
++
++uint32 get_partition_id_range_for_endpoint(partition_info *part_info,
++                                           bool left_endpoint,
++                                           bool include_endpoint)
++{
++  longlong *range_array= part_info->range_int_array;
++  longlong part_end_val;
++  uint max_partition= part_info->num_parts - 1;
++  uint min_part_id= 0, max_part_id= max_partition, loc_part_id;
++  /* Get the partitioning function value for the endpoint */
++  longlong part_func_value= 
++    part_info->part_expr->val_int_endpoint(left_endpoint, &include_endpoint);
++
++  bool unsigned_flag= part_info->part_expr->unsigned_flag;
++  DBUG_ENTER("get_partition_id_range_for_endpoint");
++
++  if (part_info->part_expr->null_value)
++  {
++    /*
++      Special handling for MONOTONIC functions that can return NULL for
++      values that are comparable. I.e.
++      '2000-00-00' can be compared to '2000-01-01' but TO_DAYS('2000-00-00')
++      returns NULL which cannot be compared used <, >, <=, >= etc.
++
++      Otherwise, just return the first partition
++      (may be included if not left endpoint)
++    */
++    enum_monotonicity_info monotonic;
++    monotonic= part_info->part_expr->get_monotonicity_info();
++    if (monotonic != MONOTONIC_INCREASING_NOT_NULL &&
++        monotonic != MONOTONIC_STRICT_INCREASING_NOT_NULL)
++    {
++      /* F(col) can not return NULL, return partition with lowest value */
++      if (!left_endpoint && include_endpoint)
++        DBUG_RETURN(1);
++      DBUG_RETURN(0);               
++
++    }
++  }
++
++  if (unsigned_flag)
++    part_func_value-= 0x8000000000000000ULL;
++  if (left_endpoint && !include_endpoint)
++    part_func_value++;
++
++  /*
++    Search for the partition containing part_func_value
++    (including the right endpoint).
++  */
++  while (max_part_id > min_part_id)
++  {
++    loc_part_id= (max_part_id + min_part_id) / 2;
++    if (range_array[loc_part_id] < part_func_value)
++      min_part_id= loc_part_id + 1;
++    else
++      max_part_id= loc_part_id;
++  }
++  loc_part_id= max_part_id;
++
++  /* Adjust for endpoints */
++  part_end_val= range_array[loc_part_id];
++  if (left_endpoint)
++  {
++    DBUG_ASSERT(part_func_value > part_end_val ?
++                (loc_part_id == max_partition &&
++                 !part_info->defined_max_value) :
++                1);
++    /*
++      In case of PARTITION p VALUES LESS THAN MAXVALUE
++      the maximum value is in the current (last) partition.
++      If value is equal or greater than the endpoint,
++      the range starts from the next partition.
++    */
++    if (part_func_value >= part_end_val &&
++        (loc_part_id < max_partition || !part_info->defined_max_value))
++      loc_part_id++;
++  }
++  else 
++  {
++    /* if 'WHERE <= X' and partition is LESS THAN (X) include next partition */
++    if (include_endpoint && loc_part_id < max_partition &&
++        part_func_value == part_end_val)
++      loc_part_id++;
++
++    /* Right endpoint, set end after correct partition */
++    loc_part_id++;
++  }
++  DBUG_RETURN(loc_part_id);
++}
++
++
++int get_partition_id_hash_nosub(partition_info *part_info,
++                                 uint32 *part_id,
++                                 longlong *func_value)
++{
++  return get_part_id_hash(part_info->num_parts, part_info->part_expr,
++                          part_id, func_value);
++}
++
++
++int get_partition_id_linear_hash_nosub(partition_info *part_info,
++                                        uint32 *part_id,
++                                        longlong *func_value)
++{
++  return get_part_id_linear_hash(part_info, part_info->num_parts,
++                                 part_info->part_expr, part_id, func_value);
++}
++
++
++int get_partition_id_key_nosub(partition_info *part_info,
++                                uint32 *part_id,
++                                longlong *func_value)
++{
++  *part_id= get_part_id_key(part_info->table->file,
++                            part_info->part_field_array,
++                            part_info->num_parts, func_value);
++  return 0;
++}
++
++
++int get_partition_id_linear_key_nosub(partition_info *part_info,
++                                      uint32 *part_id,
++                                      longlong *func_value)
++{
++  *part_id= get_part_id_linear_key(part_info,
++                                   part_info->part_field_array,
++                                   part_info->num_parts, func_value);
++  return 0;
++}
++
++
++int get_partition_id_with_sub(partition_info *part_info,
++                              uint32 *part_id,
++                              longlong *func_value)
++{
++  uint32 loc_part_id, sub_part_id;
++  uint num_subparts;
++  int error;
++  DBUG_ENTER("get_partition_id_with_sub");
++
++  if (unlikely((error= part_info->get_part_partition_id(part_info,
++                                                        &loc_part_id,
++                                                        func_value))))
++  {
++    DBUG_RETURN(error);
++  }
++  num_subparts= part_info->num_subparts;
++  if (unlikely((error= part_info->get_subpartition_id(part_info,
++                                                      &sub_part_id))))
++  {
++    DBUG_RETURN(error);
++  } 
++  *part_id= get_part_id_for_sub(loc_part_id, sub_part_id, num_subparts);
++  DBUG_RETURN(0);
++}
++
++
++/*
++  This function is used to calculate the subpartition id
++
++  SYNOPSIS
++    get_subpartition_id()
++    part_info           A reference to the partition_info struct where all the
++                        desired information is given
++
++  RETURN VALUE
++    part_id             The subpartition identity
++
++  DESCRIPTION
++    A routine used in some SELECT's when only partial knowledge of the
++    partitions is known.
++    
++    It is actually 4 different variants of this function which are called
++    through a function pointer.
++
++    get_partition_id_hash_sub
++    get_partition_id_key_sub
++    get_partition_id_linear_hash_sub
++    get_partition_id_linear_key_sub
++*/
<Skipped 23156 lines>
================================================================

---- gitweb:

http://git.pld-linux.org/gitweb.cgi/packages/mysql.git/commitdiff/d6e5d32452c0af7e2bbf8af0cd1e7e8fe15e523d




More information about the pld-cvs-commit mailing list